mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-23 14:25:22 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6855f76f5a | ||
|
|
fc82a0d148 | ||
|
|
4680fd28a6 | ||
|
|
b69dc2a380 | ||
|
|
787929ee50 | ||
|
|
7b81b92906 | ||
|
|
34b4899eee | ||
|
|
6ed01dea96 | ||
|
|
ce4b33ade2 | ||
|
|
50a1f833ad | ||
|
|
e36d1fde4b | ||
|
|
44a4e05506 | ||
|
|
0829bfa0eb |
@@ -123,6 +123,11 @@ sync_github_name = true
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.whaslbeck]
|
||||
real_name = "Walter Haslbeck"
|
||||
display_name = "Walter Haslbeck"
|
||||
sync_github_name = false
|
||||
|
||||
[people.V1dalTheAbidal]
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ mod curves;
|
||||
mod dim;
|
||||
mod fill;
|
||||
mod layout;
|
||||
mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
|
||||
@@ -52,12 +53,18 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface
|
||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||
pub use fill::{Gradient, Hatch, HatchLoop};
|
||||
pub use layout::{Image, Table, TableCell, Viewport};
|
||||
pub use proxy::{ProxyTables, proxy_entities};
|
||||
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
||||
pub use wipeout::Wipeout;
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Unknown {
|
||||
pub dxf_type: String,
|
||||
pub tags: Vec<RawTag>,
|
||||
/// What an ACAD_PROXY_ENTITY draws: its proxy graphics as read-only entities, made when the
|
||||
/// drawing is read (the graphics refer to table rows by their place in the file). Drawn and
|
||||
/// measured like block contents; saving writes `tags` unchanged.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub graphics: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl Unknown {
|
||||
@@ -264,7 +271,8 @@ impl EntityKind {
|
||||
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
|
||||
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
|
||||
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
|
||||
EntityKind::Unknown(_) => Vec::new(),
|
||||
// What its proxy graphics draw, so a proxy can be picked and snapped to.
|
||||
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,717 @@
|
||||
//! The proxy graphics an ACAD_PROXY_ENTITY carries (DXF groups 92/160 and 310): the picture
|
||||
//! the owning application left for programs that don't have it, drawn as AutoCAD draws it with
|
||||
//! PROXYSHOW 1. The layout follows the Open Design Alliance's public DWG specification
|
||||
//! ("Proxy Entity Graphics"): a header (total size, chunk count), then chunks of (size, type,
|
||||
//! data), sizes in bytes including the 8-byte chunk header, all little-endian.
|
||||
//!
|
||||
//! The picture becomes ordinary, read-only entities: drawn and measured like the contents of a
|
||||
//! block, with layer 0, ByBlock colour, linetype and lineweight standing for the proxy's own
|
||||
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
|
||||
//! polylines, materials) are skipped.
|
||||
|
||||
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
|
||||
|
||||
/// Bytes of proxy graphics read at most from one entity.
|
||||
const MAX_BYTES: usize = 16 << 20;
|
||||
/// Entities made at most from one entity's proxy graphics.
|
||||
const MAX_ENTITIES: usize = 100_000;
|
||||
/// Vertices read at most from one polyline or polygon chunk.
|
||||
const MAX_VERTICES: usize = 1_000_000;
|
||||
/// Matrices pushed at most.
|
||||
const MAX_MATRICES: usize = 64;
|
||||
|
||||
/// The table names proxy graphics refer to by index, in the order of the file's tables.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ProxyTables {
|
||||
/// LAYER records in file order.
|
||||
pub layers: Vec<String>,
|
||||
/// LTYPE records in file order, without ByBlock and ByLayer (indices count only the others).
|
||||
pub linetypes: Vec<String>,
|
||||
/// Text styles (name, font file) in file order: a text chunk names its font, and the first
|
||||
/// style with that font draws it.
|
||||
pub styles: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Unknown {
|
||||
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
|
||||
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
|
||||
/// without graphics and for one whose data isn't hex.
|
||||
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
|
||||
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
|
||||
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
|
||||
let mut out = Vec::with_capacity(size);
|
||||
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
|
||||
// Damaged data draws nothing rather than a picture cut at a guess.
|
||||
if !push_hex(&mut out, &t.value) {
|
||||
return Vec::new();
|
||||
}
|
||||
if out.len() >= size {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.truncate(size);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
|
||||
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
|
||||
let digits: Vec<u8> = s.trim().bytes().collect();
|
||||
for pair in digits.chunks(2) {
|
||||
let (Some(&hi), Some(&lo)) = (pair.first(), pair.get(1)) else { return false };
|
||||
let (Some(hi), Some(lo)) = ((hi as char).to_digit(16), (lo as char).to_digit(16)) else { return false };
|
||||
out.push((hi * 16 + lo) as u8);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
|
||||
/// selects the proxy.
|
||||
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
|
||||
let mut r = Decoder {
|
||||
tables,
|
||||
handle,
|
||||
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
|
||||
fill: false,
|
||||
matrices: Vec::new(),
|
||||
out: Vec::new(),
|
||||
};
|
||||
let mut at = 8;
|
||||
while let (Some(size), Some(kind)) = (u32_at(bytes, at), u32_at(bytes, at + 4)) {
|
||||
let size = size as usize;
|
||||
if size < 8 || r.out.len() >= MAX_ENTITIES {
|
||||
break;
|
||||
}
|
||||
let Some(data) = bytes.get(at + 8..at.saturating_add(size)) else { break };
|
||||
r.chunk(kind, data);
|
||||
at += size;
|
||||
}
|
||||
r.out
|
||||
}
|
||||
|
||||
struct Decoder<'a> {
|
||||
tables: &'a ProxyTables,
|
||||
handle: Handle,
|
||||
/// Layer, colour, linetype and lineweight for the entities that follow.
|
||||
pen: Common,
|
||||
fill: bool,
|
||||
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
|
||||
matrices: Vec<[f64; 12]>,
|
||||
out: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl Decoder<'_> {
|
||||
/// Decode one chunk of type `kind`: draw it, or change the pen for what follows.
|
||||
fn chunk(&mut self, kind: u32, data: &[u8]) {
|
||||
let mut b = Bytes { data, at: 0 };
|
||||
match kind {
|
||||
// CIRCLE: centre, radius, normal.
|
||||
2 => {
|
||||
if let (Some(c), Some(r)) = (b.point(), b.f64()) {
|
||||
self.circle(c, r);
|
||||
}
|
||||
}
|
||||
// CIRCLE_3P: three points on it.
|
||||
3 => {
|
||||
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
|
||||
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
|
||||
{
|
||||
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
|
||||
}
|
||||
}
|
||||
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
|
||||
4 => {
|
||||
if let (Some(c), Some(r), Some(n), Some(v), Some(sweep)) = (b.point(), b.f64(), b.point(), b.point(), b.f64()) {
|
||||
self.arc(c, r, n, v, sweep);
|
||||
}
|
||||
}
|
||||
// CIRCULAR_ARC_3P: start, a point on the arc, end.
|
||||
5 => {
|
||||
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
|
||||
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
|
||||
}
|
||||
}
|
||||
// POLYLINE and POLYGON: a count, then the points.
|
||||
6 | 7 => {
|
||||
let Some(n) = b.u32() else { return };
|
||||
let n = (n as usize).min(MAX_VERTICES);
|
||||
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
|
||||
self.polyline(pts, kind == 7);
|
||||
}
|
||||
// TEXT: position, normal, direction, height, width factor, oblique, string.
|
||||
10 => {
|
||||
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
|
||||
let s = b.string();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
|
||||
}
|
||||
}
|
||||
// TEXT2: position, normal, direction, string, length (the characters drawn), raw
|
||||
// flag, height, width factor, oblique, tracking, five style flags, font, big font.
|
||||
11 => {
|
||||
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
|
||||
let s = b.string();
|
||||
let s = first_chars(s, b.u32());
|
||||
b.skip(4);
|
||||
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
|
||||
b.skip(8 + 20);
|
||||
let font = b.string();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
|
||||
}
|
||||
}
|
||||
}
|
||||
// UNICODE_TEXT: as TEXT with a UTF-16 string.
|
||||
36 => {
|
||||
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
|
||||
let s = b.unicode();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
|
||||
}
|
||||
}
|
||||
// UNICODE_TEXT2: as TEXT2 with UTF-16 strings, and bold, italic, charset, pitch and
|
||||
// the typeface before the font file.
|
||||
38 => {
|
||||
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
|
||||
let s = b.unicode();
|
||||
let s = first_chars(s, b.u32());
|
||||
b.skip(4);
|
||||
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
|
||||
b.skip(8 + 20 + 16);
|
||||
let _typeface = b.unicode();
|
||||
let font = b.unicode();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
|
||||
}
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_COLOR: ACI, 0 ByBlock, 256 ByLayer.
|
||||
14 => {
|
||||
if let Some(c) = b.u32() {
|
||||
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
|
||||
16 => {
|
||||
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
|
||||
self.pen.layer = name.clone();
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
|
||||
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
|
||||
18 => {
|
||||
if let Some(i) = b.u32() {
|
||||
self.pen.linetype = match i {
|
||||
32766 => "ByBlock".into(),
|
||||
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
|
||||
};
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_FILL: the next polygon is filled.
|
||||
20 => self.fill = b.u32().is_some_and(|f| f != 0),
|
||||
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
|
||||
22 => {
|
||||
if let Some(v) = b.u32() {
|
||||
self.pen.color = match v >> 24 {
|
||||
0xC0 => Color::ByLayer,
|
||||
0xC1 => Color::ByBlock,
|
||||
0xC2 => Color::True(Rgb::from_u32(v & 0x00FF_FFFF)),
|
||||
0xC3 => Color::from_aci((v & 0xFF) as i16),
|
||||
_ => self.pen.color,
|
||||
};
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LINEWEIGHT: hundredths of a millimetre, or -1 ByLayer, -2 ByBlock,
|
||||
// -3 the default.
|
||||
23 => {
|
||||
if let Some(v) = b.u32() {
|
||||
self.pen.lineweight = Lineweight::from_dxf(i16::try_from(v as i32).unwrap_or(-1));
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LTSCALE.
|
||||
24 => {
|
||||
if let Some(s) = b.f64().filter(|s| s.is_finite() && *s > 0.0) {
|
||||
self.pen.ltscale = s;
|
||||
}
|
||||
}
|
||||
// PUSH_MATRIX, PUSH_MATRIX2: a 4x4 model transform for what follows; POP_MATRIX.
|
||||
29 | 30 => {
|
||||
let m: Vec<f64> = (0..16).map_while(|_| b.f64()).collect();
|
||||
if let Some(m) = m.get(..12).and_then(|m| <[f64; 12]>::try_from(m).ok())
|
||||
&& m.iter().all(|x| x.is_finite())
|
||||
&& self.matrices.len() < MAX_MATRICES
|
||||
{
|
||||
self.matrices.push(m);
|
||||
}
|
||||
}
|
||||
31 => {
|
||||
self.matrices.pop();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an entity drawn with the current pen (up to [`MAX_ENTITIES`]).
|
||||
fn push(&mut self, kind: EntityKind) {
|
||||
if self.out.len() < MAX_ENTITIES {
|
||||
self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind });
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` through the pushed matrices, innermost first, in the XY plane.
|
||||
fn xy(&self, p: Vec3) -> Vec2 {
|
||||
let mut p = p;
|
||||
for m in self.matrices.iter().rev() {
|
||||
p = Vec3::new(
|
||||
m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3],
|
||||
m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7],
|
||||
m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11],
|
||||
);
|
||||
}
|
||||
p.xy()
|
||||
}
|
||||
|
||||
/// How much the pushed matrices scale lengths (1 without any).
|
||||
fn scale(&self) -> f64 {
|
||||
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
|
||||
}
|
||||
|
||||
/// A full circle around `c`, through the pushed matrices.
|
||||
fn circle(&mut self, c: Vec3, r: f64) {
|
||||
let r = r * self.scale();
|
||||
let c = self.xy(c);
|
||||
if r.is_finite() && r > 0.0 && c.is_finite() {
|
||||
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
|
||||
}
|
||||
}
|
||||
|
||||
/// An arc around `c` from the direction `start`, turned by `sweep` around `normal`.
|
||||
fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) {
|
||||
if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
// The start point and the end point (the start vector turned by the sweep around the
|
||||
// normal: clockwise in plan for a normal pointing down), through the matrices.
|
||||
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
|
||||
let a0 = start.y.atan2(start.x);
|
||||
let a1 = a0 + dir * sweep;
|
||||
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
|
||||
let mid = on((a0 + a1) / 2.0);
|
||||
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
|
||||
return self.circle(c, r);
|
||||
}
|
||||
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
|
||||
}
|
||||
|
||||
/// The arc from `p1` through `p2` to `p3`.
|
||||
fn arc_3p(&mut self, p1: Vec2, p2: Vec2, p3: Vec2) {
|
||||
let Some((c, r)) = circle_through(p1, p2, p3) else {
|
||||
return self.polyline(vec![p1, p3], false);
|
||||
};
|
||||
let ang = |p: Vec2| (p.y - c.y).atan2(p.x - c.x);
|
||||
let (a1, a2, a3) = (ang(p1), ang(p2), ang(p3));
|
||||
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
|
||||
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
|
||||
let (start, end) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, a3) } else { (a3, a1) };
|
||||
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
|
||||
}
|
||||
|
||||
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
|
||||
/// which applies to this one polygon only.
|
||||
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
|
||||
let fill = std::mem::take(&mut self.fill);
|
||||
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
|
||||
return;
|
||||
}
|
||||
if polygon && fill && pts.len() >= 3 {
|
||||
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
|
||||
return self.push(EntityKind::Hatch(Hatch {
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
style: 0,
|
||||
elevation: 0.0,
|
||||
gradient: None,
|
||||
origin: Vec2::ZERO,
|
||||
background: None,
|
||||
pattern_lines: Vec::new(),
|
||||
}));
|
||||
}
|
||||
match pts.as_slice() {
|
||||
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
|
||||
_ => {
|
||||
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
|
||||
self.push(EntityKind::LwPolyline(LwPolyline { vertices, closed: polygon, const_width: 0.0, elevation: 0.0, plinegen: false }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-line text, its style the first one whose font file the chunk names.
|
||||
fn text(&mut self, t: TextChunk) {
|
||||
let TextChunk { p, dir, height, width, oblique, value, font } = t;
|
||||
let font = font.as_str();
|
||||
let height = height * self.scale();
|
||||
if !(height.is_finite() && height > 0.0) || value.is_empty() {
|
||||
return;
|
||||
}
|
||||
let at = self.xy(p);
|
||||
if !at.is_finite() {
|
||||
return;
|
||||
}
|
||||
let towards = self.xy(p + dir) - at;
|
||||
let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 };
|
||||
let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase();
|
||||
let style = self
|
||||
.tables
|
||||
.styles
|
||||
.iter()
|
||||
.find(|(_, f)| !font.is_empty() && stem(f) == stem(font))
|
||||
.map(|(n, _)| n.clone())
|
||||
.unwrap_or_else(|| "Standard".into());
|
||||
self.push(EntityKind::Text(Text {
|
||||
insert: at.to3(0.0),
|
||||
align_pt: None,
|
||||
height,
|
||||
value,
|
||||
rotation,
|
||||
width_factor: if width.is_finite() && width > 0.0 { width } else { 1.0 },
|
||||
oblique: if oblique.is_finite() { oblique } else { 0.0 },
|
||||
style,
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `length` characters of `s`: a text chunk may carry more text than it draws (the
|
||||
/// rest of a note, drawn by the chunks after it). No length, or one past the end, keeps it all.
|
||||
fn first_chars(s: String, length: Option<u32>) -> String {
|
||||
match length.map(|n| n as usize) {
|
||||
Some(n) if n > 0 && n < s.chars().count() => s.chars().take(n).collect(),
|
||||
_ => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// A text chunk: position, direction, height, width factor, oblique, string and font file.
|
||||
struct TextChunk {
|
||||
p: Vec3,
|
||||
dir: Vec3,
|
||||
height: f64,
|
||||
width: f64,
|
||||
oblique: f64,
|
||||
value: String,
|
||||
font: String,
|
||||
}
|
||||
|
||||
/// The circle through three points (centre, radius), if they aren't on one line.
|
||||
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
|
||||
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
|
||||
if !d.is_finite() || d.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
|
||||
let center =
|
||||
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
|
||||
let r = (a - center).len();
|
||||
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
|
||||
}
|
||||
|
||||
/// The little-endian u32 at `at`, if `bytes` holds one there.
|
||||
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
|
||||
bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// A reader over one chunk's data. Strings are padded to four bytes.
|
||||
struct Bytes<'a> {
|
||||
data: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Bytes<'_> {
|
||||
/// The next `n` bytes, if there are that many.
|
||||
fn take(&mut self, n: usize) -> Option<&[u8]> {
|
||||
let s = self.data.get(self.at..self.at.checked_add(n)?)?;
|
||||
self.at += n;
|
||||
Some(s)
|
||||
}
|
||||
/// Pass over `n` bytes (reads after the end then find nothing).
|
||||
fn skip(&mut self, n: usize) {
|
||||
self.at = self.at.saturating_add(n);
|
||||
}
|
||||
/// A little-endian u32.
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
|
||||
}
|
||||
/// A little-endian double.
|
||||
fn f64(&mut self) -> Option<f64> {
|
||||
self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes)
|
||||
}
|
||||
/// Three doubles, if all are finite.
|
||||
fn point(&mut self) -> Option<Vec3> {
|
||||
let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?);
|
||||
(p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p)
|
||||
}
|
||||
/// Move on to the next multiple of four bytes, where padded strings end.
|
||||
fn align(&mut self) {
|
||||
self.at = self.at.saturating_add((4 - self.at % 4) % 4);
|
||||
}
|
||||
/// A zero-terminated string in the drawing's code page; bytes above 0x7F as Latin-1.
|
||||
fn string(&mut self) -> String {
|
||||
let rest = self.data.get(self.at..).unwrap_or_default();
|
||||
let end = rest.iter().position(|&c| c == 0).unwrap_or(rest.len());
|
||||
let s: String = rest.iter().take(end).map(|&c| c as char).collect();
|
||||
self.at += end + 1;
|
||||
self.align();
|
||||
s
|
||||
}
|
||||
/// A UTF-16 string ended by a zero code unit.
|
||||
fn unicode(&mut self) -> String {
|
||||
let rest = self.data.get(self.at..).unwrap_or_default();
|
||||
let (pairs, _) = rest.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&p| u16::from_le_bytes(p)).take_while(|&u| u != 0).collect();
|
||||
self.at += units.len() * 2 + 2;
|
||||
self.align();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::RawTag;
|
||||
|
||||
/// A chunk of type `kind`, its data padded to four bytes.
|
||||
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
|
||||
let mut d = data.to_vec();
|
||||
d.resize(d.len().div_ceil(4) * 4, 0);
|
||||
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend(kind.to_le_bytes());
|
||||
out.extend(d);
|
||||
out
|
||||
}
|
||||
/// Proxy graphics: the header (total size, chunk count), then the chunks.
|
||||
fn graphics(chunks: &[Vec<u8>]) -> Vec<u8> {
|
||||
let body: Vec<u8> = chunks.concat();
|
||||
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend((chunks.len() as u32).to_le_bytes());
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
/// A point in the XY plane as three doubles.
|
||||
fn pt(x: f64, y: f64) -> Vec<u8> {
|
||||
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
/// Two layers, two linetypes and two text styles.
|
||||
fn tables() -> ProxyTables {
|
||||
ProxyTables {
|
||||
layers: vec!["0".into(), "BALLOONS".into()],
|
||||
linetypes: vec!["Continuous".into(), "DASHED".into()],
|
||||
styles: vec![("Standard".into(), "txt".into()), ("ISO".into(), "isocp.shx".into())],
|
||||
}
|
||||
}
|
||||
|
||||
/// A balloon as AutoCAD Mechanical stores one: layer, colour, a circle, the leader and the
|
||||
/// number as TEXT2.
|
||||
#[test]
|
||||
fn a_balloon_becomes_circle_line_and_text() {
|
||||
let mut text2 = pt(173.0, 112.0);
|
||||
text2.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
|
||||
text2.extend(pt(1.0, 0.0));
|
||||
text2.extend(b"12\0\0");
|
||||
text2.extend(2i32.to_le_bytes());
|
||||
text2.extend(0i32.to_le_bytes());
|
||||
for v in [6.0f64, 1.0, 0.0, 0.0] {
|
||||
text2.extend(v.to_le_bytes());
|
||||
}
|
||||
text2.extend([0u8; 20]);
|
||||
text2.extend(b"ISOCP.SHX\0\0\0\0\0");
|
||||
let mut circle = pt(175.0, 115.0);
|
||||
circle.extend(6.0f64.to_le_bytes());
|
||||
circle.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
|
||||
let mut leader = 2u32.to_le_bytes().to_vec();
|
||||
leader.extend(pt(170.0, 111.0));
|
||||
leader.extend(pt(150.0, 90.0));
|
||||
let g = graphics(&[chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text2)]);
|
||||
let es = proxy_entities(&g, &tables(), Handle(0x35));
|
||||
assert_eq!(es.len(), 3);
|
||||
assert!(es.iter().all(|e| e.handle == Handle(0x35) && e.common.layer == "BALLOONS" && e.common.color == Color::Index(1)));
|
||||
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(175.0, 115.0, 0.0) && c.radius == 6.0));
|
||||
assert!(matches!(&es[1].kind, EntityKind::Line(l) if l.b == Vec3::new(150.0, 90.0, 0.0)));
|
||||
assert!(matches!(&es[2].kind, EntityKind::Text(t) if t.value == "12" && t.height == 6.0 && t.style == "ISO" && t.rotation == 0.0));
|
||||
}
|
||||
|
||||
/// A TEXT2 chunk draws only as many characters as its length says.
|
||||
#[test]
|
||||
fn text2_draws_its_length() {
|
||||
let text2 = |value: &[u8], length: i32| {
|
||||
let mut t = pt(0.0, 0.0);
|
||||
t.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
t.extend(pt(1.0, 0.0));
|
||||
t.extend(value);
|
||||
t.extend(vec![0u8; 4 - value.len() % 4]);
|
||||
t.extend(length.to_le_bytes());
|
||||
t.extend(1i32.to_le_bytes());
|
||||
for v in [2.5f64, 1.0, 0.0, 0.0] {
|
||||
t.extend(v.to_le_bytes());
|
||||
}
|
||||
t.extend([0u8; 20]);
|
||||
t.extend(b"txt\0");
|
||||
let es = proxy_entities(&graphics(&[chunk(11, &t)]), &tables(), Handle(1));
|
||||
match es.first().map(|e| &e.kind) {
|
||||
Some(EntityKind::Text(t)) => t.value.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
};
|
||||
assert_eq!(text2(b"two lines\\Pof text", 9), "two lines");
|
||||
assert_eq!(text2(b"whole", 0), "whole");
|
||||
assert_eq!(text2(b"whole", 99), "whole");
|
||||
}
|
||||
|
||||
/// Without layer and colour chunks the picture takes the proxy's own (layer 0, ByBlock).
|
||||
#[test]
|
||||
fn unset_traits_are_the_proxys() {
|
||||
let mut leader = 3u32.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0)] {
|
||||
leader.extend(pt(x, y));
|
||||
}
|
||||
let es = proxy_entities(
|
||||
&graphics(&[chunk(6, &leader), chunk(16, &u32::MAX.to_le_bytes()), chunk(18, &32766u32.to_le_bytes())]),
|
||||
&tables(),
|
||||
Handle(1),
|
||||
);
|
||||
let e = es.first().expect("polyline");
|
||||
assert_eq!(
|
||||
(e.common.layer.as_str(), e.common.color, e.common.linetype.as_str(), e.common.lineweight),
|
||||
("0", Color::ByBlock, "ByBlock", Lineweight::ByBlock)
|
||||
);
|
||||
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
|
||||
let mut tri = 3u32.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
|
||||
tri.extend(pt(x, y));
|
||||
}
|
||||
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
|
||||
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
|
||||
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
|
||||
}
|
||||
|
||||
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
|
||||
/// which runs clockwise in plan (from 0° to -90°).
|
||||
#[test]
|
||||
fn arcs_follow_their_normal() {
|
||||
let arc = |nz: f64| {
|
||||
let mut a = pt(0.0, 0.0);
|
||||
a.extend(2.0f64.to_le_bytes());
|
||||
a.extend([0.0f64, 0.0, nz].iter().flat_map(|v| v.to_le_bytes()));
|
||||
a.extend(pt(1.0, 0.0));
|
||||
a.extend(std::f64::consts::FRAC_PI_2.to_le_bytes());
|
||||
a.extend(0u32.to_le_bytes());
|
||||
match proxy_entities(&graphics(&[chunk(4, &a)]), &tables(), Handle(1)).first().map(|e| e.kind.clone()) {
|
||||
Some(EntityKind::Arc(a)) => (a.start, a.end, a.radius),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
};
|
||||
let (s, e, r) = arc(1.0);
|
||||
assert!(s.abs() < 1e-9 && (e - std::f64::consts::FRAC_PI_2).abs() < 1e-9 && (r - 2.0).abs() < 1e-9);
|
||||
let (s, e, _) = arc(-1.0);
|
||||
assert!((s + std::f64::consts::FRAC_PI_2).abs() < 1e-9 && e.abs() < 1e-9, "{s} {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_matrix_moves_what_follows_until_popped() {
|
||||
let mut m = [0.0f64; 16];
|
||||
(m[0], m[5], m[10], m[15], m[3], m[7]) = (2.0, 2.0, 1.0, 1.0, 100.0, 50.0);
|
||||
let mut circle = pt(1.0, 1.0);
|
||||
circle.extend(1.0f64.to_le_bytes());
|
||||
circle.extend(pt(0.0, 0.0));
|
||||
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(31, &[]), chunk(2, &circle)]), &tables(), Handle(1));
|
||||
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(102.0, 52.0, 0.0) && c.radius == 2.0));
|
||||
assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0));
|
||||
}
|
||||
|
||||
/// A finite matrix can still move a point past the largest float: a circle or a text that
|
||||
/// would land there is left out, as a polyline is, so no infinity reaches the extents.
|
||||
#[test]
|
||||
fn what_a_matrix_moves_out_of_range_is_left_out() {
|
||||
let mut m = [0.0f64; 16];
|
||||
(m[0], m[5], m[10], m[15], m[3]) = (1.0, 1.0, 1.0, 1.0, 1.7e308);
|
||||
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let mut circle = pt(1e308, 0.0);
|
||||
circle.extend(1.0f64.to_le_bytes());
|
||||
circle.extend(pt(0.0, 0.0));
|
||||
let mut text = pt(1e308, 0.0);
|
||||
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
text.extend(pt(1.0, 0.0));
|
||||
text.extend(b"far\0");
|
||||
text.extend(0i32.to_le_bytes());
|
||||
text.extend(1i32.to_le_bytes());
|
||||
for v in [2.5f64, 1.0, 0.0, 0.0] {
|
||||
text.extend(v.to_le_bytes());
|
||||
}
|
||||
text.extend([0u8; 20]);
|
||||
text.extend(b"txt\0");
|
||||
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(11, &text)]), &tables(), Handle(1));
|
||||
assert!(es.is_empty(), "{es:?}");
|
||||
// The same text without the matrix is drawn: the chunk itself is sound.
|
||||
assert_eq!(proxy_entities(&graphics(&[chunk(11, &text)]), &tables(), Handle(1)).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_come_from_the_310_groups_after_the_size() {
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let u = Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: vec![tag(90, "498"), tag(92, "5"), tag(310, "0102"), tag(310, "030405FF"), tag(93, "0")],
|
||||
graphics: Vec::new(),
|
||||
};
|
||||
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
|
||||
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
|
||||
assert!(other.proxy_graphics_bytes().is_empty());
|
||||
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
|
||||
assert!(bad.proxy_graphics_bytes().is_empty());
|
||||
}
|
||||
|
||||
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
|
||||
/// never panic.
|
||||
#[test]
|
||||
fn hostile_graphics_do_not_panic() {
|
||||
let mut huge = u32::MAX.to_le_bytes().to_vec();
|
||||
huge.extend(pt(1.0, 1.0));
|
||||
let mut nan = pt(f64::NAN, 0.0);
|
||||
nan.extend(1.0f64.to_le_bytes());
|
||||
let cases: Vec<Vec<u8>> = vec![
|
||||
Vec::new(),
|
||||
vec![0; 7],
|
||||
graphics(&[chunk(6, &huge)]),
|
||||
graphics(&[chunk(2, &nan)]),
|
||||
graphics(&[chunk(11, &[0xFF; 30])]),
|
||||
graphics(&[chunk(38, &[0x41; 77])]),
|
||||
graphics(&[chunk(29, &[1; 40])]),
|
||||
graphics(&[chunk(31, &[]), chunk(31, &[])]),
|
||||
[graphics(&[chunk(2, &pt(0.0, 0.0))]), vec![0xFF; 9]].concat(),
|
||||
{
|
||||
let mut g = graphics(&[]);
|
||||
g.extend(4u32.to_le_bytes());
|
||||
g.extend(2u32.to_le_bytes());
|
||||
g
|
||||
},
|
||||
{
|
||||
let mut g = graphics(&[]);
|
||||
g.extend(1_000u32.to_le_bytes());
|
||||
g.extend(2u32.to_le_bytes());
|
||||
g
|
||||
},
|
||||
];
|
||||
for g in cases {
|
||||
let _ = proxy_entities(&g, &tables(), Handle(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -371,6 +371,28 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo
|
||||
bounds_in(d, e, depth, blocks, off_counts)
|
||||
}
|
||||
|
||||
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
|
||||
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
|
||||
/// OLE2FRAME as its frame.
|
||||
fn unknown_bounds<'a>(
|
||||
d: &'a Drawing,
|
||||
u: &crate::Unknown,
|
||||
depth: usize,
|
||||
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
|
||||
off_counts: bool,
|
||||
) -> Bounds2 {
|
||||
if u.graphics.is_empty() {
|
||||
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
|
||||
}
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Bounds2::EMPTY;
|
||||
}
|
||||
u.graphics
|
||||
.iter()
|
||||
.filter(|g| in_block_visible(d, g, off_counts))
|
||||
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
|
||||
}
|
||||
|
||||
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
|
||||
/// by block name and depth: every further reference to a block at that depth reuses them instead of
|
||||
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
|
||||
@@ -516,8 +538,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
|
||||
Bounds2::from_points([o, o + u, o + v, o + u + v])
|
||||
}
|
||||
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
|
||||
// An OLE object's content is not drawn, but its frame is, so the frame counts (#2422).
|
||||
EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points),
|
||||
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
|
||||
// frame is, so the frame counts (#2422).
|
||||
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
|
||||
kind => {
|
||||
let mut b = Bounds2::EMPTY;
|
||||
for p in kind.prims() {
|
||||
@@ -718,12 +741,15 @@ mod tests {
|
||||
#[test]
|
||||
fn ole_frame_counts_in_extents() {
|
||||
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]));
|
||||
assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0)));
|
||||
assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame");
|
||||
assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty());
|
||||
assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty());
|
||||
assert!(
|
||||
bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")], graphics: Vec::new() }))
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
|
||||
|
||||
@@ -57,6 +57,10 @@ impl EntityStore {
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
|
||||
self.chunks.iter().flat_map(|c| c.items.iter())
|
||||
}
|
||||
/// Iterate from the top of the draw order down.
|
||||
pub fn iter_rev(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
|
||||
self.chunks.iter().rev().flat_map(|c| c.items.iter().rev())
|
||||
}
|
||||
pub fn handles(&self) -> Vec<Handle> {
|
||||
self.iter().map(|e| e.handle).collect()
|
||||
}
|
||||
@@ -346,6 +350,7 @@ mod tests {
|
||||
}
|
||||
assert!(s.move_next_to(Handle(1), Handle(3), true));
|
||||
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
|
||||
assert_eq!(s.iter_rev().map(|e| e.handle.0).collect::<Vec<_>>(), [5, 4, 1, 3, 2], "top down");
|
||||
assert!(s.move_next_to(Handle(5), Handle(2), false));
|
||||
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
|
||||
assert!(!s.move_next_to(Handle(5), Handle(5), true));
|
||||
|
||||
@@ -593,7 +593,9 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if let Some(f) = points_param(p, "fence") {
|
||||
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
|
||||
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
targets(s, p)?
|
||||
// Handles named outright, less the proxies: no selection takes one in.
|
||||
let d = s.doc()?;
|
||||
targets(s, p)?.into_iter().filter(|h| !d.entity(*h).is_some_and(|e| crate::select::kept_as_read(&e.kind))).collect()
|
||||
} else {
|
||||
// Nothing to select with: the selection stays, also what the active viewport does not draw.
|
||||
s.stored_selection()
|
||||
|
||||
@@ -219,14 +219,18 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidate objects: the whole edit space, or the current selection.
|
||||
/// The candidate objects: the whole edit space (without proxies, which no selection takes in), or
|
||||
/// the current selection.
|
||||
fn candidates(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
let apply = str_param(p, "applyTo").unwrap_or("drawing").to_ascii_lowercase();
|
||||
if apply.starts_with("sel") || apply == "current" {
|
||||
return Ok(s.selection());
|
||||
}
|
||||
let space = s.space();
|
||||
Ok(s.doc()?.space(&space).map(|st| st.iter().take(MAX_SCAN).map(|e| e.handle).collect()).unwrap_or_default())
|
||||
Ok(s.doc()?
|
||||
.space(&space)
|
||||
.map(|st| st.iter().take(MAX_SCAN).filter(|e| !crate::select::kept_as_read(&e.kind)).map(|e| e.handle).collect())
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -161,19 +161,25 @@ pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
|
||||
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
|
||||
/// layers frozen in the layout viewport the selection is made through: what the Last option
|
||||
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
|
||||
/// A proxy is passed over: no selection takes one in ([`kept_as_read`]).
|
||||
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
|
||||
if frozen.is_empty() {
|
||||
return store.last().map(|e| e.handle);
|
||||
}
|
||||
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
|
||||
store.iter_rev().find(|e| !kept_as_read(&e.kind) && !on_frozen_layer(frozen, e)).map(|e| e.handle)
|
||||
}
|
||||
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]), it is not
|
||||
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
|
||||
/// model space, so `frozen` goes with a selection in model space only.
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else), and commands can
|
||||
/// edit it. A viewport shows model space, so `frozen` goes with a selection in model space only.
|
||||
/// A proxy (or another record CADCraft keeps as it was read) is drawn and snapped to, but never
|
||||
/// selected: commands can't edit it, and saving writes its record as it was read.
|
||||
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e)
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e) && !kept_as_read(&e.kind)
|
||||
}
|
||||
|
||||
/// Whether `k` is a record CADCraft keeps as it was read and commands can't edit: every
|
||||
/// [`EntityKind::Unknown`] but an OLE2FRAME, which moves and scales with its frame.
|
||||
pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
|
||||
matches!(k, EntityKind::Unknown(u) if !u.is_ole_frame())
|
||||
}
|
||||
|
||||
/// Entities to test, in the order to test them, each with its bounds when already known.
|
||||
@@ -599,7 +605,8 @@ mod tests {
|
||||
#[test]
|
||||
fn clicking_an_ole_frame_edge_selects_it() {
|
||||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||||
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let frame =
|
||||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap();
|
||||
|
||||
@@ -1561,6 +1561,50 @@ fn setvar_rejects_non_finite_text_for_real_variables() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_is_drawn_but_no_selection_takes_it_in() {
|
||||
// A proxy's graphics are drawn and measured, but saving writes its record unchanged: an edit
|
||||
// could not hold. So a window round a line and a proxy, ALL, SELECTALL and a pick on the
|
||||
// proxy's graphics leave the proxy out, and MOVE moves the line alone.
|
||||
use cadcraft_doc::{Common, Entity, Handle, Line, Space, Unknown, entity_bounds};
|
||||
use cadcraft_geom::Vec3;
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let line = s.doc().unwrap().model.last().unwrap().handle;
|
||||
let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }));
|
||||
let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] };
|
||||
let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap();
|
||||
let bounds = |s: &Session| entity_bounds(s.doc().unwrap(), s.doc().unwrap().entity(proxy).unwrap(), 0);
|
||||
let before = bounds(&s);
|
||||
assert!(!before.is_empty(), "the proxy measures as its graphics");
|
||||
|
||||
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
|
||||
assert_eq!(s.selection(), Vec::<Handle>::new(), "a pick on the proxy's graphics");
|
||||
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
|
||||
s.idle_click(Vec2::new(11.0, 6.0), false).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "a window round both");
|
||||
s.execute("selectall", &json!({})).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "SELECTALL");
|
||||
|
||||
s.execute("move", &json!({"delta": [0, 20]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved");
|
||||
assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it");
|
||||
|
||||
// Handles named outright leave the proxy out too.
|
||||
s.execute("select", &json!({"handles": [proxy.hex(), line.hex()]})).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "SELECT by handles");
|
||||
|
||||
// Last passes over the proxy drawn last: it takes the line.
|
||||
s.set_selection(Vec::new());
|
||||
s.start("erase").unwrap();
|
||||
s.input(Input::Text("L".into())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.entity(line).is_none(), "Last took the line");
|
||||
assert!(d.entity(proxy).is_some(), "the proxy is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_tools_keeps_compatible_command_ids() {
|
||||
assert_eq!(crate::cmd::resolve_alias("-blockreplace"), "blockreplace");
|
||||
|
||||
@@ -9,8 +9,11 @@ use serde_json::json;
|
||||
fn session() -> (Session, String) {
|
||||
let tag = |code: i32, v: &str| RawTag { code, value: v.into() };
|
||||
let mut d = Drawing::new_imperial();
|
||||
let kind =
|
||||
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
|
||||
let kind = EntityKind::Unknown(Unknown {
|
||||
dxf_type: "OLE2FRAME".into(),
|
||||
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
let h = d.add(&Space::Model, Common::default(), kind).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ole.dxf", None);
|
||||
@@ -75,7 +78,8 @@ fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, Strin
|
||||
tags.push(tag(310, &hex[at..]));
|
||||
}
|
||||
let mut d = Drawing::new_imperial();
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags })).unwrap();
|
||||
let h =
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() })).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ole.dxf", None);
|
||||
(s, h.hex())
|
||||
@@ -160,8 +164,11 @@ fn a_locked_ole_frame_does_not_block_an_in_place_rotation() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.ensure_layer("L");
|
||||
let common = Common { layer: "L".into(), ..Common::default() };
|
||||
let kind =
|
||||
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
|
||||
let kind = EntityKind::Unknown(Unknown {
|
||||
dxf_type: "OLE2FRAME".into(),
|
||||
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
let ole = d.add(&Space::Model, common, kind).unwrap();
|
||||
if let Some(l) = d.layer_mut("L") {
|
||||
l.locked = true;
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Un
|
||||
use serde_json::json;
|
||||
|
||||
fn unknown(kind: &str) -> EntityKind {
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] })
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -129,6 +129,7 @@ fn proxy_entities_are_reported_only_before_2013() {
|
||||
RawTag { code: 90, value: "498".into() },
|
||||
RawTag { code: 91, value: class.to_string() },
|
||||
],
|
||||
graphics: Vec::new(),
|
||||
})
|
||||
};
|
||||
let mut d = Drawing::new_imperial();
|
||||
@@ -190,6 +191,7 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() {
|
||||
RawTag { code: 1, value: "400 1 1 0".into() },
|
||||
RawTag { code: 3, value: "End-of-ACIS-data".into() },
|
||||
],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
d.add(&Space::Model, Common::default(), sat).unwrap();
|
||||
let mut s = Session::empty();
|
||||
@@ -219,7 +221,7 @@ fn a_dxf_2013_loss_is_known_before_saving() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
let sat = |d: &mut Drawing| {
|
||||
let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }];
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap();
|
||||
};
|
||||
let mut modern = Drawing::new_imperial();
|
||||
modern.header.set_str("ACADVER", "AC1032");
|
||||
@@ -255,6 +257,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
RawTag { code: 1, value: "400 1 1 0".into() },
|
||||
RawTag { code: 3, value: "End-of-ACIS-data".into() },
|
||||
],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
d.add(&Space::Model, Common::default(), sat).unwrap();
|
||||
d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door")));
|
||||
@@ -276,7 +279,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
|
||||
use cadcraft_engine::cmd::file::{Version, not_saved_as};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
|
||||
@@ -352,6 +355,7 @@ fn proxy_entity(strings: &str) -> EntityKind {
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
|
||||
graphics: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,9 @@ struct Rx {
|
||||
block_arrays: HashMap<String, cadcraft_doc::ArrayParams>,
|
||||
/// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers).
|
||||
layers: HashMap<String, String>,
|
||||
/// Layer, linetype and text style names in the order of the file's tables, which proxy
|
||||
/// graphics refer to by index (the drawing's own tables are ordered differently).
|
||||
proxy_tables: cadcraft_doc::ProxyTables,
|
||||
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
|
||||
ucss: HashMap<String, String>,
|
||||
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
|
||||
@@ -75,6 +78,26 @@ struct Rx {
|
||||
image_defs: HashMap<Handle, String>,
|
||||
}
|
||||
|
||||
/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned`
|
||||
/// names: records the file doesn't have keep their order after the file's own. A file without
|
||||
/// that table changes nothing.
|
||||
fn keep_file_order<T>(items: &mut [T], name: impl Fn(&T) -> &str, order: &[String], pinned: &[&str]) {
|
||||
if order.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut place: HashMap<String, usize> = HashMap::new();
|
||||
for (i, n) in order.iter().enumerate() {
|
||||
place.entry(n.to_ascii_lowercase()).or_insert(i);
|
||||
}
|
||||
items.sort_by_key(|it| {
|
||||
let n = name(it);
|
||||
match pinned.iter().position(|p| p.eq_ignore_ascii_case(n)) {
|
||||
Some(i) => (0, i),
|
||||
None => place.get(&n.to_ascii_lowercase()).map_or((2, 0), |&i| (1, i)),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Read a DXF file into a drawing.
|
||||
pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
||||
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS)
|
||||
@@ -179,6 +202,13 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Proxy graphics name layers and linetypes by their place in the file's tables, and saving
|
||||
// writes them unchanged: the tables keep the file's order, with what CADCraft adds after it.
|
||||
keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]);
|
||||
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
|
||||
// A proxy text takes the first style on its font, so the styles keep the file's order too.
|
||||
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
|
||||
keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]);
|
||||
// A file CADCraft wrote names its own next handle (#495): its table records and objects
|
||||
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
|
||||
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
|
||||
|
||||
@@ -329,6 +329,7 @@ pub(super) fn entity_with_table_budget(
|
||||
other => EntityKind::Unknown(Unknown {
|
||||
dxf_type: other.to_string(),
|
||||
tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(),
|
||||
graphics: Vec::new(),
|
||||
}),
|
||||
};
|
||||
Some((c, k))
|
||||
@@ -488,6 +489,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
|
||||
/// needs the file's handle maps.
|
||||
pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) {
|
||||
match (kind, k) {
|
||||
// Its proxy graphics, with the table indices resolved while the file's order is known.
|
||||
("ACAD_PROXY_ENTITY", EntityKind::Unknown(u)) => {
|
||||
u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h);
|
||||
}
|
||||
("DIMENSION", EntityKind::Dimension(dm)) => {
|
||||
dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes);
|
||||
dm.assoc = crate::dxf_ext::read_assoc(tags);
|
||||
|
||||
@@ -299,6 +299,7 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue };
|
||||
match kind.as_str() {
|
||||
"STYLE" => {
|
||||
rx.proxy_tables.styles.push((name.clone(), table.s(3).unwrap_or_default()));
|
||||
rx.styles.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"BLOCK_RECORD" => {
|
||||
@@ -310,9 +311,13 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
rx.brs.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"LTYPE" => {
|
||||
if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") {
|
||||
rx.proxy_tables.linetypes.push(name.clone());
|
||||
}
|
||||
rx.ltypes.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"LAYER" => {
|
||||
rx.proxy_tables.layers.push(name.clone());
|
||||
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"UCS" => {
|
||||
|
||||
@@ -39,7 +39,11 @@ fn drawing() -> Drawing {
|
||||
d.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }),
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACME_WIDGET".into(),
|
||||
tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")],
|
||||
graphics: Vec::new(),
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap();
|
||||
@@ -521,7 +525,7 @@ fn corpus_round_trip_report() {
|
||||
fn types_the_dwg_writer_cannot_write_are_reported_lost() {
|
||||
use corpus::{CorpusReport, FileReport, Format, round_trip};
|
||||
crate::dwg_worker::allow_in_process();
|
||||
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags });
|
||||
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags, graphics: Vec::new() });
|
||||
let mut d = Drawing::new_metric();
|
||||
let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")];
|
||||
d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap();
|
||||
|
||||
@@ -370,7 +370,7 @@ fn top_line_kept_objects_and_unknown(handle: Handle) -> Drawing {
|
||||
RawTag { code: 100, value: "SyntheticWidget".into() },
|
||||
RawTag { code: 1, value: "widget".into() },
|
||||
];
|
||||
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags });
|
||||
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() });
|
||||
d.model.push(Entity { handle, common: Common::default(), kind });
|
||||
d
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() {
|
||||
use cadcraft_doc::foreign::{Foreign, sat_text_acis};
|
||||
use cadcraft_doc::{Handle, RawTag, Unknown};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags };
|
||||
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() };
|
||||
let none = std::collections::BTreeSet::new();
|
||||
let h = Handle(0x2B);
|
||||
// A stray 1 or 3 outside AcDbModelerGeometry is not SAT text.
|
||||
|
||||
@@ -69,6 +69,7 @@ mod plot_model_png_scale;
|
||||
mod plot_styles;
|
||||
mod polyface_roundtrip;
|
||||
mod portable_fonts;
|
||||
mod proxy_graphics;
|
||||
mod region_roundtrip;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod render_settings_version;
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! ACAD_PROXY_ENTITY draws its proxy graphics (#2646): read from DXF with the table indices of the
|
||||
//! file, measured in the extents, and written back unchanged.
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::{EntityKind, Space};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
/// A proxy graphics chunk of type `kind`, its data padded to four bytes.
|
||||
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
|
||||
let mut d = data.to_vec();
|
||||
d.resize(d.len().div_ceil(4) * 4, 0);
|
||||
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend(kind.to_le_bytes());
|
||||
out.extend(d);
|
||||
out
|
||||
}
|
||||
|
||||
/// A point in the XY plane as three doubles.
|
||||
fn pt(x: f64, y: f64) -> Vec<u8> {
|
||||
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A balloon: layer 1 of the file's LAYER table, colour 1, a circle, a leader and the number.
|
||||
fn balloon() -> Vec<u8> {
|
||||
let mut circle = pt(175.0, 115.0);
|
||||
circle.extend(6.0f64.to_le_bytes());
|
||||
circle.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let mut leader = 2u32.to_le_bytes().to_vec();
|
||||
leader.extend(pt(170.8, 110.8));
|
||||
leader.extend(pt(150.0, 90.0));
|
||||
let mut text = pt(172.9, 112.0);
|
||||
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
text.extend(pt(1.0, 0.0));
|
||||
text.extend(b"1\0\0\0");
|
||||
text.extend(1i32.to_le_bytes());
|
||||
text.extend(0i32.to_le_bytes());
|
||||
for v in [6.0f64, 1.0, 0.0, 0.0] {
|
||||
text.extend(v.to_le_bytes());
|
||||
}
|
||||
text.extend([0u8; 20]);
|
||||
text.extend(b"isocp.shx\0\0\0\0\0\0\0");
|
||||
let chunks = [chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text)];
|
||||
let body = chunks.concat();
|
||||
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend((chunks.len() as u32).to_le_bytes());
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
|
||||
/// A DXF whose LAYER table holds 0 and BALLOONS only (CADCraft keeps Defpoints at index 1 of
|
||||
/// its own table), a text style on isocp.shx, a line and one proxy balloon.
|
||||
fn file() -> String {
|
||||
let graphics = balloon();
|
||||
let hex: Vec<String> = graphics.chunks(127).map(|c| c.iter().map(|b| format!("{b:02X}")).collect()).collect();
|
||||
let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "CLASSES".into())];
|
||||
for (c, v) in [(0, "CLASS"), (1, "SYNBALLOON"), (2, "SynBalloon"), (3, "SyntheticProxyApp"), (90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC")] {
|
||||
tags.push((c, v.into()));
|
||||
}
|
||||
for (c, v) in [
|
||||
(0, "SECTION"),
|
||||
(2, "TABLES"),
|
||||
(0, "TABLE"),
|
||||
(2, "LAYER"),
|
||||
(0, "LAYER"),
|
||||
(5, "10"),
|
||||
(2, "0"),
|
||||
(62, "7"),
|
||||
(0, "LAYER"),
|
||||
(5, "11"),
|
||||
(2, "BALLOONS"),
|
||||
(62, "3"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "TABLE"),
|
||||
(2, "STYLE"),
|
||||
(0, "STYLE"),
|
||||
(5, "12"),
|
||||
(2, "ISO"),
|
||||
(3, "isocp.shx"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "ENDSEC"),
|
||||
(0, "SECTION"),
|
||||
(2, "ENTITIES"),
|
||||
(0, "LINE"),
|
||||
(5, "20"),
|
||||
(8, "0"),
|
||||
(10, "50"),
|
||||
(20, "40"),
|
||||
(11, "150"),
|
||||
(21, "90"),
|
||||
(0, "ACAD_PROXY_ENTITY"),
|
||||
(5, "21"),
|
||||
(100, "AcDbEntity"),
|
||||
(8, "0"),
|
||||
(100, "AcDbProxyEntity"),
|
||||
(90, "498"),
|
||||
(91, "500"),
|
||||
(95, "0"),
|
||||
(70, "0"),
|
||||
] {
|
||||
tags.push((c, v.into()));
|
||||
}
|
||||
tags.push((92, graphics.len().to_string()));
|
||||
tags.extend(hex.into_iter().map(|h| (310, h)));
|
||||
for (c, v) in [(93, "0"), (94, "0"), (0, "ENDSEC"), (0, "EOF")] {
|
||||
tags.push((c, v.into()));
|
||||
}
|
||||
tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_draws_its_graphics_with_the_files_table_indices() {
|
||||
let d = read_dxf(file().as_bytes()).expect("read");
|
||||
let proxy = d.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy");
|
||||
let EntityKind::Unknown(u) = &proxy.kind else { unreachable!() };
|
||||
let kinds: Vec<(&str, &str, Color)> = u.graphics.iter().map(|g| (g.kind.dxf_name(), g.common.layer.as_str(), g.common.color)).collect();
|
||||
// Layer index 1 is BALLOONS, the file's second layer, not CADCraft's Defpoints.
|
||||
assert_eq!(kinds, [("CIRCLE", "BALLOONS", Color::Index(1)), ("LINE", "BALLOONS", Color::Index(1)), ("TEXT", "BALLOONS", Color::Index(1))]);
|
||||
assert!(matches!(&u.graphics[2].kind, EntityKind::Text(t) if t.value == "1" && t.style == "ISO"));
|
||||
// The extents reach the balloon (the line alone ends at 150, 90).
|
||||
let b = d.extents(&Space::Model);
|
||||
assert!(b.max.x >= 181.0 && b.max.y >= 121.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_is_written_back_unchanged_and_draws_again() {
|
||||
let d = read_dxf(file().as_bytes()).expect("read");
|
||||
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
|
||||
let graphics = |d: &cadcraft_doc::Drawing| {
|
||||
d.model.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::Unknown(u) => Some((u.proxy_graphics_bytes(), u.graphics.len())),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
assert_eq!(graphics(&again), graphics(&d));
|
||||
assert_eq!(graphics(&d).map(|g| g.1), Some(3));
|
||||
// The saved LAYER table keeps the file's order, so index 1 is still BALLOONS (CADCraft's
|
||||
// Defpoints comes after it) and the reopened graphics stay on that layer.
|
||||
let layers = |d: &cadcraft_doc::Drawing| -> Vec<String> {
|
||||
d.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
EntityKind::Unknown(u) => Some(u.graphics.iter().map(|g| g.common.layer.clone()).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
assert_eq!(layers(&again), ["BALLOONS"; 3]);
|
||||
let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["0", "BALLOONS", "Defpoints"]);
|
||||
}
|
||||
|
||||
/// A proxy text takes the first style on its font. With ISO and then Standard both on
|
||||
/// isocp.shx, it is ISO, and stays ISO after a save: CADCraft's own Standard, which the file's
|
||||
/// replaces, would otherwise come first in the saved STYLE table.
|
||||
#[test]
|
||||
fn a_proxy_text_keeps_its_style_after_a_save() {
|
||||
let iso = "0\nSTYLE\n5\n12\n2\nISO\n3\nisocp.shx\n";
|
||||
let src = file().replacen(iso, &format!("{iso}0\nSTYLE\n5\n13\n2\nStandard\n3\nisocp.shx\n"), 1);
|
||||
let style = |d: &cadcraft_doc::Drawing| {
|
||||
d.model.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::Unknown(u) => u.graphics.iter().find_map(|g| match &g.kind {
|
||||
EntityKind::Text(t) => Some(t.style.clone()),
|
||||
_ => None,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let d = read_dxf(src.as_bytes()).expect("read");
|
||||
assert_eq!(style(&d).as_deref(), Some("ISO"));
|
||||
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
|
||||
assert_eq!(style(&again).as_deref(), Some("ISO"), "after a save");
|
||||
}
|
||||
@@ -27,7 +27,7 @@ fn drawing() -> Drawing {
|
||||
RawTag { code: 30, value: "3.75".into() },
|
||||
RawTag { code: 330, value: target.hex() },
|
||||
];
|
||||
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags })));
|
||||
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() })));
|
||||
d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) })));
|
||||
d
|
||||
}
|
||||
|
||||
@@ -40,6 +40,23 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A proxy entity draws its proxy graphics as AutoCAD does with PROXYSHOW 1, like block contents:
|
||||
/// layer 0 and ByBlock in the picture stand for the proxy's own layer and properties. Other
|
||||
/// unknown records draw nothing. `own` is the proxy's transparency without its locked-layer fade,
|
||||
/// as for a block reference.
|
||||
pub(crate) fn proxy(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, own: u8) {
|
||||
if u.graphics.is_empty() || ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH {
|
||||
return;
|
||||
}
|
||||
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::IDENTITY) };
|
||||
for g in &u.graphics {
|
||||
if !b.expand() {
|
||||
break;
|
||||
}
|
||||
entity(b, &sub, g);
|
||||
}
|
||||
}
|
||||
|
||||
/// `own` is the reference's resolved transparency without its locked-layer fade: what ByBlock
|
||||
/// children inherit (a child fades only for its own layer).
|
||||
pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink, own: u8) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::blocks::{insert, sub_ctx};
|
||||
use super::blocks::{insert, proxy, sub_ctx};
|
||||
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
|
||||
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
|
||||
use super::props::{resolve, transparency};
|
||||
@@ -240,12 +240,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
b.polyline(ctx, rgb, lw, l);
|
||||
}
|
||||
}
|
||||
// An OLE object's content is not drawn; its frame, from its two corner points, is.
|
||||
EntityKind::Unknown(u) if u.is_ole_frame() => {
|
||||
if let Some(q) = cadcraft_doc::ole_frame(&u.tags) {
|
||||
b.polyline(ctx, rgb, lw, &q);
|
||||
}
|
||||
}
|
||||
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => draw_unknown(b, ctx, e, u, rgb, lw, own),
|
||||
kind => {
|
||||
for prim in kind.prims() {
|
||||
match prim {
|
||||
@@ -302,6 +297,17 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade
|
||||
}
|
||||
}
|
||||
|
||||
/// A record kept as read that draws something: a proxy its proxy graphics, and an OLE object its
|
||||
/// frame, from its two corner points (its content is not drawn). `own`: the proxy's transparency
|
||||
/// without its locked-layer fade, for its graphics.
|
||||
fn draw_unknown(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, rgb: Ink, lw: f32, own: u8) {
|
||||
if !u.graphics.is_empty() {
|
||||
proxy(b, ctx, e, u, own);
|
||||
} else if let Some(q) = cadcraft_doc::ole_frame(&u.tags) {
|
||||
b.polyline(ctx, rgb, lw, &q);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_image(b: &mut Builder, ctx: &Ctx, i: &cadcraft_doc::Image, rgb: Ink, lw: f32) {
|
||||
let o = i.insert.xy();
|
||||
let u = i.u.xy() * i.size.x;
|
||||
|
||||
@@ -1299,7 +1299,8 @@ fn raster_hatch_pattern_matches_one_by_one() {
|
||||
#[test]
|
||||
fn ole_frame_draws_its_outline() {
|
||||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||||
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let frame =
|
||||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "1"), tag(20, "2")])).unwrap();
|
||||
@@ -1333,6 +1334,51 @@ fn without_linetypes_every_line_is_drawn_whole() {
|
||||
assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len());
|
||||
}
|
||||
|
||||
/// A proxy draws its proxy graphics like block contents: layer 0 and ByBlock in the picture are
|
||||
/// the proxy's own, and the proxy's layer hides all of it.
|
||||
#[test]
|
||||
fn proxy_graphics_draw_like_block_contents() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Notes".into(), color: Color::Index(3), ..Default::default() });
|
||||
let byblock = Common { color: Color::ByBlock, ..Default::default() };
|
||||
let graphics = vec![
|
||||
block_entity(7, byblock, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })),
|
||||
block_entity(
|
||||
7,
|
||||
Common { color: Color::Index(1), ..Default::default() },
|
||||
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(15.0, 0.0, 0.0), radius: 5.0 }),
|
||||
),
|
||||
];
|
||||
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||||
d.add(&Space::Model, Common { layer: "Notes".into(), ..Default::default() }, proxy).unwrap();
|
||||
let l = build(&d, &Space::Model, &Options::default());
|
||||
assert_eq!(l.prims.iter().map(|p| p.color).collect::<Vec<_>>(), [Rgb(0, 255, 0), Rgb(255, 0, 0)]);
|
||||
let b = d.extents(&Space::Model);
|
||||
assert!((b.min.x, b.max.x, b.max.y) == (0.0, 20.0, 5.0), "{b:?}");
|
||||
d.layer_mut("Notes").unwrap().frozen = true;
|
||||
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty());
|
||||
}
|
||||
|
||||
/// On a locked layer, a proxy's graphics fade like a block's contents: layer 0 in the picture takes
|
||||
/// the proxy's fade, a ByBlock part on an unlocked layer only the proxy's own transparency.
|
||||
#[test]
|
||||
fn proxy_graphics_on_a_locked_layer_fade_like_block_contents() {
|
||||
use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent};
|
||||
for (own, want) in [(ByLayer, 0), (Percent(20), 20)] {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() });
|
||||
let line = |x: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(x, 0.0, 0.0), b: Vec3::new(x + 1.0, 0.0, 0.0) });
|
||||
let graphics = vec![
|
||||
block_entity(7, Common::default(), line(0.0)),
|
||||
block_entity(7, Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() }, line(2.0)),
|
||||
];
|
||||
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||||
d.add(&Space::Model, Common { layer: "Locked".into(), transparency: own, ..Default::default() }, proxy).unwrap();
|
||||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![50.max(want), want], "{own:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A broken table whose parts, with their repeated labels, together hold more cells than a table may
|
||||
/// lay out is drawn as its outline, though the table's own cells are within the limit.
|
||||
#[test]
|
||||
|
||||
@@ -15,7 +15,7 @@ use cadcraft_ui_egui::{CadApp, Services, menus};
|
||||
const ORIGINAL: &[u8] = b"original";
|
||||
|
||||
fn unknown(kind: &str) -> EntityKind {
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] })
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() })
|
||||
}
|
||||
|
||||
/// A drawing with objects of `types`, which DWG can't keep, opened from a DWG file on disk.
|
||||
|
||||
Reference in New Issue
Block a user