Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
3eb74db
Dynamic blocks: author linear and point parameters with stretch and m…
codyvogt Oct 21, 2026
65d2b46
Docs: F3 and the blocks row list the dynamic-block authoring that landed
codyvogt Oct 21, 2026
d30a082
i18n(uk): Parameter and Action command labels
codyvogt Oct 21, 2026
64c0cf2
Dynamic blocks: a linear parameter between points infinitely far apar…
codyvogt Oct 21, 2026
27ce8f7
Dynamic blocks: a grip's location components name their own parameter
codyvogt Oct 25, 2026
c4c5339
Block Editor: the marks cache id uses egui 0.37's Id::unique
codyvogt Oct 25, 2026
4da3598
Dynamic blocks: BSAVEAS gives a dynamic block's copy its own graph
codyvogt Oct 28, 2026
60eaa87
Dynamic blocks: BSAVEAS leaves the edited block as it was and the edi…
codyvogt Oct 29, 2026
fc204c2
BSAVEAS of a dynamic block: the copy starts a new Block Editor history
codyvogt Oct 29, 2026
9131053
Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't …
codyvogt Nov 1, 2026
9c0a904
Merge storytold/cadcraft main into feat/dynblock-author
codyvogt Nov 14, 2026
850eeb1
Dynamic blocks: BSAVEAS refuses a block too big to copy whole
codyvogt Nov 14, 2026
c6b4e4c
i18n: Chinese for the Parameter and Action commands
codyvogt Nov 14, 2026
9cc7092
Merge remote-tracking branch 'upstream/main' into feat/dynblock-author
codyvogt Nov 21, 2026
918af22
File access: BPARAMETER and BACTION touch no file
codyvogt Nov 21, 2026
cfe1d8b
Merge remote-tracking branch 'upstream/main' into feat/dynblock-author
codyvogt Nov 24, 2026
230b76a
Merge remote-tracking branch 'upstream/main' into feat/dynblock-author
codyvogt Nov 29, 2026
fc42c33
Translations to craft-i18n, tests into the crates' it binaries (AGENT…
codyvogt Nov 30, 2026
218faa7
Translations: the Chinese labels of BPARAMETER and BACTION stay, as t…
codyvogt Nov 30, 2026
a192579
Merge main into dynamic block authoring
FredApps Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion crates/doc/src/dynblock.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Dynamic blocks made in another program, read from the data CADCraft keeps for them.
//! Dynamic blocks made in another program, read from the data CADCraft keeps for them, and
//! authored in CADCraft (`write`: the same objects, written).
//!
//! A dynamic block's behaviour lives in objects CADCraft does not write itself and keeps as
//! [`Foreign`](crate::foreign::Foreign) data: the block's BLOCK_RECORD has an extension dictionary
Expand All @@ -20,11 +21,17 @@ use crate::foreign::ForeignObject;
use crate::{Drawing, Handle, RawTag};

mod apply;
mod copy;
mod grips;
mod marks;
mod reference;
mod write;
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
pub use copy::{copy_definition, remap_handles, restore_definition};
pub use grips::{DynGrip, GripPart, GripShape, grips};
pub use marks::{Mark, marks};
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
pub use write::{ActionSpec, MAX_ACTION_ITEMS, ParamPoint, ParameterSpec, add_action, add_parameter, tag_elements};

/// Most objects one evaluation graph is read with.
const MAX_NODES: usize = 10_000;
Expand Down
225 changes: 225 additions & 0 deletions crates/doc/src/dynblock/copy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
//! Saving a dynamic block under another name (BSAVEAS): the copy gets its own evaluation graph,
//! made from the original's objects with new handles, and its own copies of the block's objects
//! (no two blocks share a handle), so references to either change as AutoCAD would change them.

use std::collections::{HashMap, HashSet};

use crate::foreign::{ForeignExtra, ForeignObject};
use crate::{Drawing, EntityKind, EntityStore, Handle, RawTag};

use super::write::{ETAG, dict_entry, guid, record_handle, strip_app};
use super::{MAX_NODES, dynamic_block};

/// Most objects of one block's dynamic data that are copied.
const MAX_COPIED: usize = 8 * MAX_NODES;

/// Group codes whose values are handles: the object's own (5), owners and pointers (330 to 369)
/// and 390 to 399.
fn is_handle_code(code: i32) -> bool {
code == 5 || (330..=369).contains(&code) || (390..=399).contains(&code)
}

/// The owner of an object: its first 330 group outside the `{ACAD_REACTORS` ... `}` groups.
fn owner_of(o: &ForeignObject) -> Option<Handle> {
let mut inside = false;
for t in &o.tags {
match t.code {
102 => inside = t.value.starts_with('{'),
330 if !inside => return Handle::parse_hex(&t.value),
_ => {}
}
}
None
}

/// `root` and the objects it owns, directly or not (at most [`MAX_COPIED`]).
fn owned_subtree(d: &Drawing, root: Handle) -> Vec<Handle> {
let mut children: HashMap<Handle, Vec<Handle>> = HashMap::new();
for o in &d.foreign.objects {
if let Some(owner) = owner_of(o) {
children.entry(owner).or_default().push(o.handle);
}
}
let mut out = vec![root];
let mut seen: HashSet<Handle> = HashSet::from([root]);
let mut at = 0;
while let Some(h) = out.get(at).copied() {
at += 1;
for c in children.get(&h).into_iter().flatten() {
if out.len() < MAX_COPIED && seen.insert(*c) {
out.push(*c);
}
}
}
out
}

/// [`owned_subtree`], refused when it reaches [`MAX_COPIED`]: a copy of only part of it would keep
/// pointing at the original's objects.
fn whole_subtree(d: &Drawing, root: Handle) -> Result<Vec<Handle>, String> {
let out = owned_subtree(d, root);
if out.len() >= MAX_COPIED {
return Err(format!("The dynamic block has {MAX_COPIED} or more objects; it can't be copied."));
}
Ok(out)
}

/// The handle `h` names, as `map` has it.
fn mapped(map: &HashMap<Handle, Handle>, value: &str) -> Option<Handle> {
Handle::parse_hex(value).and_then(|h| map.get(&h)).copied()
}

/// Every handle in `tags` that `map` has, as the new one.
fn retarget(tags: &mut [RawTag], map: &HashMap<Handle, Handle>) {
for t in tags.iter_mut().filter(|t| is_handle_code(t.code)) {
if let Some(n) = mapped(map, &t.value) {
t.value = n.hex();
}
}
}

/// The objects of `store` again with new handles (added to `map`).
fn rehandle(d: &mut Drawing, store: &EntityStore, map: &mut HashMap<Handle, Handle>) -> EntityStore {
for e in store.iter() {
let n = d.new_handle();
map.insert(e.handle, n);
}
remap_handles(store, map)
}

/// The objects of `store` again with the handles `map` gives them: each one's element tag names
/// the object itself, and a hatch's sources are the new copies.
pub fn remap_handles(store: &EntityStore, map: &HashMap<Handle, Handle>) -> EntityStore {
let mut out = EntityStore::new();
for e in store.iter() {
let mut c = (**e).clone();
c.handle = map.get(&e.handle).copied().unwrap_or(e.handle);
for t in c.common.xdata.iter_mut().filter(|t| t.code == 1005) {
if let Some(n) = mapped(map, &t.value) {
t.value = n.hex();
}
}
if let EntityKind::Hatch(h) = &mut c.kind {
for l in &mut h.loops {
l.sources = l.sources.iter().map(|s| map.get(s).copied().unwrap_or(*s)).collect();
}
}
out.push(c);
}
out
}

/// The kept extras of the objects of `store` (reactors within the block; not their extension
/// dictionaries), for their new handles.
fn entity_extras(d: &Drawing, store: &EntityStore, map: &HashMap<Handle, Handle>) -> Vec<(Handle, ForeignExtra)> {
store
.iter()
.filter_map(|e| {
let mut x = d.foreign.entities.get(&e.handle)?.clone();
x.xdict = None;
x.reactors = x.reactors.iter().filter_map(|r| map.get(r).copied()).collect();
Some((map.get(&e.handle).copied()?, x))
})
.collect()
}

/// The applications whose record xdata make a block dynamic.
const DYNAMIC_APPS: [&str; 3] = ["AcDbDynamicBlockTrueName", "AcDbDynamicBlockGUID", ETAG];

/// Block `name`'s (upper case) dynamic data removed: the objects its extension dictionary owns
/// and its record's dynamic data. What a redefined block's old graph would point at is gone.
fn remove_definition(d: &mut Drawing, name: &str) {
let key = ("BLOCK_RECORD".to_string(), name.to_string());
let Some(xdict) = d.foreign.records.get(&key).and_then(|x| x.xdict) else { return };
let owned: HashSet<Handle> = owned_subtree(d, xdict).into_iter().collect();
let f = std::sync::Arc::make_mut(&mut d.foreign);
f.objects.retain(|o| !owned.contains(&o.handle));
let empty = f.records.get_mut(&key).is_some_and(|x| {
x.xdict = None;
DYNAMIC_APPS.iter().for_each(|app| strip_app(&mut x.xdata, app));
x.is_empty()
});
if empty {
f.records.remove(&key);
}
}

/// Block `name`'s dynamic data in `d` as `host` has it (BSAVEAS leaves the edited block as it
/// was: the editor's changes to its graph belong to the copy only).
pub fn restore_definition(d: &mut Drawing, host: &Drawing, name: &str) {
let name = name.trim().to_ascii_uppercase();
remove_definition(d, &name);
let key = ("BLOCK_RECORD".to_string(), name);
let Some(record) = host.foreign.records.get(&key) else { return };
let owned: HashSet<Handle> = record.xdict.map(|x| owned_subtree(host, x)).unwrap_or_default().into_iter().collect();
let objects: Vec<ForeignObject> = host.foreign.objects.iter().filter(|o| owned.contains(&o.handle)).cloned().collect();
let f = std::sync::Arc::make_mut(&mut d.foreign);
f.objects.extend(objects);
f.records.insert(key, record.clone());
}

/// Block record xdata `xdata` with the dynamic block's true name and GUID replaced.
fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) {
let mut app = String::new();
for t in xdata {
match t.code {
1001 => app = t.value.to_ascii_uppercase(),
1000 if app == "ACDBDYNAMICBLOCKTRUENAME" => t.value = name.to_string(),
1000 if app == "ACDBDYNAMICBLOCKGUID" => t.value = guid.to_string(),
_ => {}
}
}
}

/// Make block `to` a copy of dynamic block `from` (BSAVEAS): `store`, the objects it is saved
/// with, get new handles; the copy has its own evaluation graph and objects, made from the
/// original's with new handles, and its own true name and GUID. What `to` had of dynamic data goes
/// first (a block replaced by one that isn't dynamic keeps none). Returns the handles the objects
/// of `store` got, by their old ones; nothing changes when `from` has no dynamic data or is `to`.
/// Refused, changing nothing, when `from` has too many objects to copy whole.
pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> Result<HashMap<Handle, Handle>, String> {
let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string());
if from_name == to_name {
return Ok(HashMap::new());
}
let source = d.foreign.records.get(&key(&from_name)).cloned();
let owned = match source.as_ref().and_then(|s| s.xdict) {
Some(xdict) if dynamic_block(d, from).is_some() => Some(whole_subtree(d, xdict)?),
_ => None,
};
remove_definition(d, &to_name);
let (Some(source), Some(owned)) = (source, owned) else { return Ok(HashMap::new()) };
let Some(xdict) = source.xdict else { return Ok(HashMap::new()) };
let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK");
let owned_set: HashSet<Handle> = owned.iter().copied().collect();
let mut map: HashMap<Handle, Handle> = owned.iter().map(|h| (*h, d.new_handle())).collect();
let old_record = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == from_name).map(|(h, _)| *h);
let new_record = record_handle(d, &to_name);
map.extend(old_record.map(|h| (h, new_record)));
let entities = rehandle(d, store, &mut map);
let extras = entity_extras(d, store, &map);
let copies: Vec<ForeignObject> = d
.foreign
.objects
.iter()
.filter(|o| owned_set.contains(&o.handle))
.map(|o| {
let mut c = o.clone();
retarget(&mut c.tags, &map);
c.handle = map.get(&o.handle).copied().unwrap_or(o.handle);
c
})
.collect();
let mut record = source;
record.xdict = map.get(&xdict).copied();
let new_graph = graph.and_then(|g| map.get(&g).copied()).unwrap_or(new_record);
rename_in_xdata(&mut record.xdata, to.trim(), &guid(to.trim(), new_graph));
let f = std::sync::Arc::make_mut(&mut d.foreign);
f.objects.extend(copies);
f.records.insert(key(&to_name), record);
f.entities.extend(extras);
let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect();
*store = entities;
Ok(made)
}
58 changes: 58 additions & 0 deletions crates/doc/src/dynblock/marks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//! What the Block Editor shows of a dynamic block's parameters and actions: each one's
//! geometry and label, in block coordinates, for the editor to draw.

use cadcraft_geom::Vec3;
use serde::Serialize;

use super::{Cursor, ParameterKind, dynamic_block, section, sections};
use crate::Drawing;

/// One parameter or action as the Block Editor draws it.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Mark {
/// A linear parameter: a dimension from `base` to `end`, its line `offset` to the left of
/// base → end, its label in the middle; arrows at the ends that have grips.
Linear { node: i32, base: Vec3, end: Vec3, offset: f64, label: String, base_grip: bool, end_grip: bool },
/// A point parameter: a marker at `at` and its label at `label_at`.
Point { node: i32, at: Vec3, label_at: Vec3, label: String, grip: bool },
/// Another parameter: its name at `at`.
Parameter { node: i32, at: Vec3, label: String },
/// An action: a badge with its name at `at`.
Action { node: i32, at: Vec3, name: String },
}

/// Block `name`'s parameters and actions as the Block Editor draws them (empty when it has none).
pub fn marks(d: &Drawing, name: &str) -> Vec<Mark> {
let Some(m) = dynamic_block(d, name) else { return Vec::new() };
let mut out = Vec::new();
for p in &m.parameters {
let tags = d.foreign.objects.iter().find(|o| o.handle == p.handle).map(|o| o.tags.as_slice()).unwrap_or_default();
let secs = sections(tags);
let label = p.kind.label().unwrap_or(&p.element).to_string();
let grip = |i: usize| p.grips.get(i).is_some_and(|g| *g != 0);
out.push(match &p.kind {
ParameterKind::Linear { base, end, .. } => {
// The label's offset (140) after its name and description (305, 306).
let mut c = Cursor::new(section(&secs, "AcDbBlockLinearParameter"));
c.next(306);
Mark::Linear { node: p.node, base: *base, end: *end, offset: c.real(140), label, base_grip: grip(0), end_grip: grip(1) }
}
ParameterKind::Point { at, .. } => {
let label_at = Cursor::new(section(&secs, "AcDbBlockPointParameter")).point(1011);
Mark::Point { node: p.node, at: *at, label_at, label, grip: grip(0) }
}
ParameterKind::Polar { base, .. }
| ParameterKind::Xy { base, .. }
| ParameterKind::Rotation { base, .. }
| ParameterKind::Alignment { base, .. }
| ParameterKind::Flip { base, .. } => Mark::Parameter { node: p.node, at: *base, label },
ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } | ParameterKind::BasePoint { at } => {
Mark::Parameter { node: p.node, at: *at, label }
}
ParameterKind::Other { .. } => continue,
});
}
out.extend(m.actions.iter().map(|a| Mark::Action { node: a.node, at: a.at, name: a.name.clone() }));
out
}
Loading
Loading