Files
cadcraft/crates/render/src/raster.rs
T
26179f7428 Draw object transparency on screen, in exports and in plots (#764)
* Draw object transparency on screen, in exports and in plots

Transparency was read and saved (entity group 440, layer xdata, ByLayer and
ByBlock) but never drawn. Display lists now carry each object's effective
transparency (its own, its layer's, or the block reference's), and:

- the canvas (GPU and CPU paths), ui.render and PNG/SVG exports blend it;
  TRANSPARENCYDISPLAY turns it off on screen and is now on by default, as in
  AutoCAD (initial value 1);
- plots draw it only when "Plot transparency" is on: a page setup option
  (PAGESETUP `plotTransparency`, a checkbox in the Page Setup Manager and the
  Plot dialog), overridable per plot, with PLOTTRANSPARENCYOVERRIDE (0 never,
  1 the setting, 2 always). PDF gets /ExtGState alpha, PNG plots blend, SVG
  uses opacity. Plots without it are byte-identical to before.

The public DXF Reference has no plot layout flag for plot transparency, so
the option is kept in the session and in JSON, not in DXF/DWG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Transparency fixes: attributes, PDF overlaps, drag previews

- Attributes draw with their own transparency (their definition's, layer 0
  meaning the reference's layer, ByBlock the reference's) instead of the
  block reference's.
- PDF plots stroke overlapping transparent objects one by one, so they build
  up where they cross as in PNG plots; opaque output is unchanged.
- Drag and rubber-band previews follow TRANSPARENCYDISPLAY.
- Effective transparency is worked out only when it is drawn, reusing the
  layer the property lookup already found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Transparency: one PDF stroke per transparent primitive; opaque rebuilt previews

- PDF plots never batch two transparent primitives into one path. Block and
  viewport contents share their reference's handle, so the per-object flush
  missed them; each primitive now blends on its own, as in PNG plots and on
  screen. Opaque output is unchanged.
- Previews the session rebuilds with the current properties (rubber bands,
  copies of objects) are drawn opaque again: they carry CLAYER's
  transparency, not the objects'. The GPU drag of the objects themselves
  keeps following TRANSPARENCYDISPLAY.
- Tests for attributes on a transparent reference layer, attributes without a
  definition, and the drag cache across the TRANSPARENCYDISPLAY toggle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Selection like AutoCAD: colour highlight and the Options Selection tab

Selecting or hovering an object outlined each filled primitive (TrueType
glyphs, dimension and leader arrowheads, solid hatches, wide polylines)
by the rectangle around its triangles, and dashed everything else. A
selected dimension's text became a row of dashed boxes, one per glyph,
and its closed arrowheads small rectangles.

Selected objects are now redrawn in the selection colour: lines solid,
fills filled half see-through (so the lines and text on a highlighted
hatch stay visible), and the whole object reads as selected, text and
arrowheads included. A wipeout is always outlined, since filling it would
hide the drawing under it.

The Options dialog's Selection tab is laid out as AutoCAD's, with the
settings CADCraft can act on, each one AutoCAD's variable, kept in the
user profile:

- Selection modes: noun/verb selection (PICKFIRST), Shift to add
  (PICKADD), Object grouping (PICKSTYLE bit 1, now saved in the profile).
- Selection effect color (selectionColor, an interface preference; null
  is the theme's).
- Grips: Show grips (GRIPS) and the object selection limit for display of
  grips (GRIPOBJLIMIT, 100; 0 no limit): grips are neither drawn nor
  picked beyond it.
- Selection preview (SELECTIONPREVIEW): the object under the cursor is
  highlighted when a command is active (2) and when none is (1).
- Visual Effect Settings: the selection area effect (SELECTIONAREA,
  WINDOWAREACOLOR 150, CROSSINGAREACOLOR 100, SELECTIONAREAOPACITY 25)
  and the Selection Preview Filter (PREVIEWFILTER 3: 1 objects on locked
  layers, 2 xrefs, 4 tables, 8 multiline text, 16 hatches, 32 groups).

As in AutoCAD these are typed, not on the dialog: HIGHLIGHT (0 shows only
the grips of selected objects; not saved, so every session starts
highlighted), SELECTIONEFFECT (1 the selection colour, 0 dashed lines with
fills outlined along their real boundary) and PREVIEWEFFECT (the preview
dashed 0, thicker 1 or both 2).

Left for later, as CADCraft lacks what they control: lasso, grip tips and
menus, group grips, grips within blocks, associative hatch selection,
command and property preview, PICKDRAG, PICKAUTO and PROPOBJLIMIT.

DisplayList::fill_outlines returns the boundary of the region a filled
primitive covers as closed polylines (edges only one triangle has; the
slab filler's horizontal cuts, which need not line up between trapezoids,
are split at every x on their line and kept where an odd number cover
them), falling back to the bounding box over 600,000 vertices. The GPU
and CPU highlight paths and the drawing comparison overlay share the same
looks.

The new labels have Ukrainian rows (the required catalog); other
languages fall back to English.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: EP995LAB <293597958+EP995LAB@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com>
Co-authored-by: Brandon Thomas <echelon@gmail.com>
2026-10-13 06:12:48 -04:00

162 lines
6.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! CPU rasteriser: draws a display list with tiny-skia (PNG export, plot preview, tests).
use cadcraft_color::Rgb;
use cadcraft_geom::{Bounds2, Vec2};
use tiny_skia::{FillRule, LineCap, LineJoin, Paint, PathBuilder, Pixmap, Stroke, Transform};
use crate::{DisplayList, Kind};
/// A 2D view: world point at the image centre and pixels per drawing unit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
pub center: Vec2,
pub scale: f64,
pub width: u32,
pub height: u32,
}
impl View {
pub fn to_screen(&self, p: Vec2) -> (f32, f32) {
let x = (p.x - self.center.x) * self.scale + f64::from(self.width) / 2.0;
let y = f64::from(self.height) / 2.0 - (p.y - self.center.y) * self.scale;
(x as f32, y as f32)
}
/// Fit `b` with a margin fraction.
pub fn fit(b: &Bounds2, width: u32, height: u32, margin: f64) -> View {
if b.is_empty() {
return View { center: Vec2::ZERO, scale: 1.0, width, height };
}
let w = b.width().max(1e-9);
let h = b.height().max(1e-9);
let s = (f64::from(width) / w).min(f64::from(height) / h) * (1.0 - margin);
View { center: b.center(), scale: if s.is_finite() && s > 0.0 { s } else { 1.0 }, width, height }
}
/// The view of `window` (drawing units), filling the image: `width` × `height` pixels when both
/// are given; otherwise the side given (default 1600 wide) with the other matching the window's
/// shape, each side 16..=8192.
pub fn of_window(window: &Bounds2, width: Option<u32>, height: Option<u32>) -> View {
let aspect = if window.width() > 1e-12 && window.height() > 1e-12 { window.width() / window.height() } else { 1.0 };
let side = |v: f64| v.round().clamp(16.0, 8192.0) as u32;
let (w, h) = match (width, height) {
(Some(w), Some(h)) => (side(f64::from(w)), side(f64::from(h))),
(None, Some(h)) => (side(f64::from(h) * aspect), side(f64::from(h))),
(w, None) => {
let w = f64::from(w.unwrap_or(1600));
(side(w), side(w / aspect))
}
};
View::fit(window, w, h, 0.0)
}
pub fn world_bounds(&self) -> Bounds2 {
let hw = f64::from(self.width) / 2.0 / self.scale;
let hh = f64::from(self.height) / 2.0 / self.scale;
Bounds2::new(self.center - Vec2::new(hw, hh), self.center + Vec2::new(hw, hh))
}
}
#[derive(Clone, Copy, Debug)]
pub struct RasterOptions {
pub background: Rgb,
/// Line width in pixels for zero-lineweight lines.
pub hairline: f32,
/// Pixels per mm for lineweights (0 = ignore lineweights).
pub px_per_mm: f32,
pub antialias: bool,
}
impl Default for RasterOptions {
fn default() -> Self {
RasterOptions { background: Rgb(33, 40, 48), hairline: 1.0, px_per_mm: 0.0, antialias: true }
}
}
/// Render to a pixmap. Returns `None` for zero or absurd sizes.
pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixmap> {
if view.width == 0 || view.height == 0 || view.width > 16384 || view.height > 16384 {
return None;
}
let mut pm = Pixmap::new(view.width, view.height)?;
pm.fill(tiny_skia::Color::from_rgba8(o.background.0, o.background.1, o.background.2, 255));
let vis = view.world_bounds();
for p in &list.prims {
let c = p.display_rgb(o.background);
let mut paint = Paint::default();
// A transparent object blends with what is drawn under it.
paint.set_color_rgba8(c.0, c.1, c.2, p.alpha());
paint.anti_alias = o.antialias;
let pts = list.points(p);
match p.kind {
Kind::Polyline => {
let bb = Bounds2::from_points(pts.iter().copied());
if !bb.intersects(&vis) {
continue;
}
let mut pb = PathBuilder::new();
for (i, q) in pts.iter().enumerate() {
let (x, y) = view.to_screen(*q);
if i == 0 {
pb.move_to(x, y);
} else {
pb.line_to(x, y);
}
}
if let Some(path) = pb.finish() {
let w = if o.px_per_mm > 0.0 && p.lw > 0.0 { (p.lw * o.px_per_mm).max(o.hairline) } else { o.hairline };
let stroke = Stroke { width: w, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Default::default() };
pm.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
}
}
Kind::Tris | Kind::Mask => {
if p.kind == Kind::Mask {
paint.set_color_rgba8(o.background.0, o.background.1, o.background.2, 255);
}
let mut pb = PathBuilder::new();
for t in pts.chunks(3) {
if let [a, b, c] = t {
let (ax, ay) = view.to_screen(*a);
let (bx, by) = view.to_screen(*b);
let (cx, cy) = view.to_screen(*c);
pb.move_to(ax, ay);
pb.line_to(bx, by);
pb.line_to(cx, cy);
pb.close();
}
}
if let Some(path) = pb.finish() {
pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
}
}
Kind::Point => {
if let Some(q) = pts.first() {
let (x, y) = view.to_screen(*q);
// Filled as a path: tiny-skia's anti-aliased `fill_rect` trips a debug
// assertion on rects under two pixels wide whose sides both fall mid-pixel.
if let Some(r) = tiny_skia::Rect::from_xywh(x - 0.5, y - 0.5, 1.5, 1.5) {
pm.fill_path(&PathBuilder::from_rect(r), &paint, FillRule::Winding, Transform::identity(), None);
}
}
}
Kind::Infinite { ray } => {
let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) else { continue };
let far = (vis.width() + vis.height()) * 2.0 + base.dist(vis.center());
let a = if ray { *base } else { *base - *dir * far };
let b = *base + *dir * far;
let mut pb = PathBuilder::new();
let (ax, ay) = view.to_screen(a);
let (bx, by) = view.to_screen(b);
pb.move_to(ax, ay);
pb.line_to(bx, by);
if let Some(path) = pb.finish() {
pm.stroke_path(&path, &paint, &Stroke { width: o.hairline, ..Default::default() }, Transform::identity(), None);
}
}
}
}
Some(pm)
}
/// Render and encode as PNG.
pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Vec<u8>> {
render(list, view, o)?.encode_png().ok()
}