diff --git a/src/app/block_parameter_properties.rs b/src/app/block_parameter_properties.rs index a4f74eda62..4d288d6ff2 100644 --- a/src/app/block_parameter_properties.rs +++ b/src/app/block_parameter_properties.rs @@ -45,8 +45,13 @@ impl OpenCADStudio { } else { None }; - let definition = - |handle| crate::scene::block_actions::instance::definition(&tab.scene.document, handle); + // A BricsCAD parametric block's references, whether they show the + // block or a copy of it, share the block. + let definition = |handle| { + crate::scene::bricscad_parameters::master_block(&tab.scene.document, handle).or_else( + || crate::scene::block_actions::instance::definition(&tab.scene.document, handle), + ) + }; let first = definition(handles[0])?; handles .iter() @@ -71,6 +76,12 @@ impl OpenCADStudio { let doc = &tab.scene.document; let mut rows = native::properties(doc, None, tab.id, insert); rows.extend(Self::indexed_visibility_property(doc, tab.id, insert)); + rows.extend(Self::bricscad_visibility_properties( + doc, + tab.id, + insert, + editor_session.is_none(), + )); rows }; let key = |value: &PropValue| match value { @@ -175,6 +186,8 @@ impl OpenCADStudio { .document .dynamic_visibility_for_insert(key.insert) .map(|(definition, _)| definition) + } else if matches!(key.component, BlockParameterComponent::Bricscad(_)) { + crate::scene::bricscad_parameters::master_block(&tab.scene.document, key.insert) } else { crate::scene::block_actions::instance::definition(&tab.scene.document, key.insert) }; @@ -229,6 +242,9 @@ impl OpenCADStudio { (BlockParameterComponent::Visibility(_), Input::Choice(state)) => { Self::stage_visibility_property(source, target, state) } + (BlockParameterComponent::Bricscad(_), Input::Choice(state)) => { + Self::stage_bricscad_visibility(source, target, state) + } _ => native::evaluate(source, None, target, input), }?; if let Some(next) = next { @@ -242,6 +258,9 @@ impl OpenCADStudio { (BlockParameterComponent::Visibility(_), Input::Choice(state)) => { Self::stage_visibility_property(&tab.scene.document, key, state) } + (BlockParameterComponent::Bricscad(_), Input::Choice(state)) => { + Self::stage_bricscad_visibility(&tab.scene.document, key, state) + } _ => native::evaluate(&tab.scene.document, baseline, key, input), } }; diff --git a/src/app/bricscad_visibility_tests.rs b/src/app/bricscad_visibility_tests.rs new file mode 100644 index 0000000000..413129b209 --- /dev/null +++ b/src/app/bricscad_visibility_tests.rs @@ -0,0 +1,177 @@ +//! A reference to a BricsCAD parametric block names the block and lists its +//! visibility parameters in Properties, also when it shows an anonymous copy +//! of the block in another state, and a state picked there is shown the way +//! BricsCAD shows it. + +use super::*; +use crate::scene::model::object::{BlockParameterComponent, BlockParameterKey, PropValue}; +use document::Handle; + +/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README), opened +/// the way the application opens a file. +fn opened() -> OpenCADStudio { + let mut app = OpenCADStudio::new_for_test(); + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + app.automation_op(&serde_json::json!({"op": "open", "path": path}).to_string()); + let i = app.active_tab; + assert!( + app.tabs[i] + .scene + .document + .block_records + .get("ocs-bricscad-visibility-block") + .is_some(), + "the fixture did not open" + ); + app +} + +fn select(app: &mut OpenCADStudio, references: &[u64]) { + let i = app.active_tab; + app.tabs[i].scene.selected.clear(); + for (index, &reference) in references.iter().enumerate() { + app.tabs[i] + .scene + .select_entity(Handle::from(reference), index == 0); + } + app.tabs[i].selected_handle = (references.len() == 1).then(|| Handle::from(references[0])); + app.refresh_properties(); +} + +/// The visibility rows as label, shown state and states, with their keys. +fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, Vec, BlockParameterKey)> { + app.tabs[app.active_tab] + .properties + .sections + .iter() + .flat_map(|section| §ion.props) + .filter_map(|property| match &property.value { + PropValue::BlockChoice { + key, + selected, + options, + .. + } if matches!(key.component, BlockParameterComponent::Bricscad(_)) => Some(( + property.label.clone(), + options + .get(*selected) + .cloned() + .unwrap_or_else(|| "*VARIES*".into()), + options.clone(), + *key, + )), + _ => None, + }) + .collect() +} + +fn shown(app: &OpenCADStudio) -> Vec<(String, String)> { + visibility_rows(app) + .into_iter() + .map(|(label, state, ..)| (label, state)) + .collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect() +} + +fn block_name(app: &OpenCADStudio) -> String { + let row = app.tabs[app.active_tab] + .properties + .sections + .iter() + .flat_map(|section| §ion.props) + .find(|property| property.field == "block") + .expect("no block row"); + match &row.value { + PropValue::EditChoice { value, .. } | PropValue::ReadOnly(value) => value.clone(), + other => panic!("block row is {other:?}"), + } +} + +/// Pick `state` in the list of `parameter`, as a click in Properties does. +fn pick(app: &mut OpenCADStudio, parameter: &str, state: &str) { + let (_, _, options, key) = visibility_rows(app) + .into_iter() + .find(|(label, ..)| label == parameter) + .unwrap_or_else(|| panic!("no {parameter} row")); + let index = options.iter().position(|option| option == state).unwrap(); + let _ = app.update(Message::PropBlockChoice { key, index }); +} + +#[test] +fn a_reference_lists_the_states_it_was_set_to_and_names_its_block() { + let mut app = opened(); + for (reference, lamp, label) in [ + (0xEE, "On", "Shown"), + (0x146, "Off", "Shown"), + (0x19E, "Off", "Hidden"), + ] { + select(&mut app, &[reference]); + assert_eq!( + shown(&app), + pairs(&[("LAMP", lamp), ("LABEL", label)]), + "{reference:X}" + ); + let rows = visibility_rows(&app); + assert_eq!(rows[0].2, ["On", "Off"]); + assert_eq!(rows[1].2, ["Shown", "Hidden"]); + assert_eq!( + block_name(&app), + "ocs-bricscad-visibility-block", + "{reference:X} shows its block's name, not its copy's" + ); + } +} + +#[test] +fn a_state_picked_in_properties_is_shown_and_undone_in_one_step() { + let mut app = opened(); + let i = app.active_tab; + let before = app.tabs[i].scene.document.clone(); + select(&mut app, &[0xEE]); + pick(&mut app, "LABEL", "Hidden"); + assert_eq!(shown(&app), pairs(&[("LAMP", "On"), ("LABEL", "Hidden")])); + assert!(app.tabs[i].dirty); + let _ = app.update(Message::Undo); + select(&mut app, &[0xEE]); + assert_eq!(shown(&app), pairs(&[("LAMP", "On"), ("LABEL", "Shown")])); + assert!( + app.tabs[i] + .scene + .document + .block_records + .get("*U4") + .is_none(), + "undo takes the new copy away" + ); + assert_eq!( + app.tabs[i].scene.document.block_records.iter().count(), + before.block_records.iter().count() + ); +} + +#[test] +fn references_selected_together_switch_together() { + let mut app = opened(); + select(&mut app, &[0xEE, 0x146]); + assert_eq!( + shown(&app), + pairs(&[("LAMP", "*VARIES*"), ("LABEL", "Shown")]) + ); + pick(&mut app, "LABEL", "Hidden"); + for (reference, lamp) in [(0xEE, "On"), (0x146, "Off")] { + select(&mut app, &[reference]); + assert_eq!( + shown(&app), + pairs(&[("LAMP", lamp), ("LABEL", "Hidden")]), + "{reference:X}" + ); + } +} diff --git a/src/app/control/block_ops.rs b/src/app/control/block_ops.rs index 06d8f20183..fd535414ee 100644 --- a/src/app/control/block_ops.rs +++ b/src/app/control/block_ops.rs @@ -242,6 +242,16 @@ pub(crate) fn resolve_effective_block( } } + // 5. Fallback: a copy BricsCAD made of one of its parametric blocks, for a + // reference in another state, names that block in its own objects. The + // steps above find nothing for it or the copy itself. + if let Some(original) = evaluated_handle + .filter(|copy| def_handle.is_none_or(|definition| definition == *copy)) + .and_then(|copy| crate::scene::bricscad_parameters::original_block(doc, copy)) + { + def_handle = Some(original); + } + if let Some(def_h) = def_handle { if let Some(def_rec) = doc.block_records.iter().find(|r| r.handle == def_h) { let true_name = doc @@ -258,7 +268,7 @@ pub(crate) fn resolve_effective_block( } } - // 5. Fallback: check AcDbDynamicBlockTrueName XData on Insert or evaluated BlockRecord + // 6. Fallback: check AcDbDynamicBlockTrueName XData on Insert or evaluated BlockRecord let xdata_true_name = insert .common .extended_data diff --git a/src/app/mod.rs b/src/app/mod.rs index 58b53ed716..542bf13e07 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -36,6 +36,8 @@ mod block_test; #[cfg(test)] mod block_test_tests; mod block_visibility; +#[cfg(test)] +mod bricscad_visibility_tests; pub(crate) mod calc; mod command_driver; mod extraction_catalog; diff --git a/src/app/properties.rs b/src/app/properties.rs index 4e0fb56e5f..4a4eeb66c7 100644 --- a/src/app/properties.rs +++ b/src/app/properties.rs @@ -1073,6 +1073,15 @@ impl OpenCADStudio { custom_properties.extend(Self::visibility_property(doc, handle)); } custom_properties.extend(Self::visible_blocks_property(doc, handle)); + // A BricsCAD parametric block's states, switched from a list + // outside the Block Editor and Test Block. + custom_properties.extend(Self::bricscad_visibility_properties( + doc, + self.tabs[i].id, + handle, + self.tabs[i].active_block_edit_session().is_none() + && self.tabs[i].block_test.is_none(), + )); if !custom_properties.is_empty() { sections.push(crate::scene::model::object::PropSection { title: t!("Custom").into_owned(), diff --git a/src/app/visibility.rs b/src/app/visibility.rs index eb1365d9e0..85e6e3fd96 100644 --- a/src/app/visibility.rs +++ b/src/app/visibility.rs @@ -120,6 +120,15 @@ fn visibility_revision(parameter: &BlockVisibilityParameter) -> u64 { hash.finish() } +/// Identifies a BricsCAD visibility parameter by its name and states, so a +/// list built for one block is not applied to a parameter that changed. +fn bricscad_revision(parameter: &crate::scene::bricscad_parameters::VisibilityParameter) -> u64 { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + parameter.name.hash(&mut hash); + parameter.states.hash(&mut hash); + hash.finish() +} + fn visibility_label(parameter: &BlockVisibilityParameter) -> String { if parameter.name.trim().is_empty() { "Visibility1".into() @@ -626,6 +635,96 @@ impl OpenCADStudio { }) } + /// The visibility parameters of a reference to a BricsCAD parametric + /// block, one row each with the state the reference shows. With + /// `editable`, a reference that can be switched (see + /// `bricscad_parameters::can_switch`) gets a list of the states; any + /// other shows the state with the states as tooltip. + pub(super) fn bricscad_visibility_properties( + doc: &document::Document, + document: u64, + handle: Handle, + editable: bool, + ) -> Vec { + use crate::scene::bricscad_parameters as bricscad; + let parameters = bricscad::reference_parameters(doc, handle); + if parameters.is_empty() { + return Vec::new(); + } + let master = bricscad::master_block(doc, handle) + .filter(|_| editable && bricscad::can_switch(doc, handle)); + let master_parameters = master + .map(|master| bricscad::visibility_parameters(doc, master)) + .unwrap_or_default(); + parameters + .into_iter() + .map(|parameter| { + let feature = master_parameters + .iter() + .find(|shown| shown.name == parameter.name && shown.states == parameter.states) + .map(|shown| shown.feature); + let value = match (master, feature) { + (Some(definition), Some(feature)) => PropValue::BlockChoice { + key: BlockParameterKey { + document, + definition, + insert: handle, + batch_generation: None, + editor_session: None, + parameter: feature, + component: BlockParameterComponent::Bricscad(bricscad_revision( + ¶meter, + )), + }, + selected: parameter.current.unwrap_or(usize::MAX), + options: parameter.states.clone(), + description: String::new(), + }, + _ => PropValue::ReadOnlyWithTooltip { + value: parameter + .current + .and_then(|index| parameter.states.get(index).cloned()) + .unwrap_or_default(), + tooltip: parameter.states.join(", "), + }, + }; + Property { + value, + label: parameter.name, + field: "bricscad_visibility", + } + }) + .collect() + } + + /// Show state `state` of the BricsCAD visibility parameter `key` names on + /// a copy of `doc`; `None` when the reference shows it already. + pub(super) fn stage_bricscad_visibility( + doc: &document::Document, + key: BlockParameterKey, + state: usize, + ) -> Result, &'static str> { + use crate::scene::bricscad_parameters as bricscad; + const INVALID: &str = "Select supported targets belonging to this block."; + if bricscad::master_block(doc, key.insert) != Some(key.definition) { + return Err(INVALID); + } + let parameter = bricscad::visibility_parameters(doc, key.definition) + .into_iter() + .find(|parameter| parameter.feature == key.parameter) + .ok_or(INVALID)?; + if key.component != BlockParameterComponent::Bricscad(bricscad_revision(¶meter)) { + return Err(INVALID); + } + let state = parameter.states.get(state).ok_or(INVALID)?; + let mut scene = crate::scene::Scene::new(); + scene.document = doc.clone(); + match scene.set_bricscad_visibility(key.insert, ¶meter.name, state)? { + true => Ok(Some(scene.document)), + false => Ok(None), + } + } + /// Recompute the visibility grip for the active tab's single selection and /// append it (as a Triangle grip) to `selected_grips`. Clears it when the /// selection is not a dynamic-block reference. `wo` is the world offset diff --git a/src/scene/block_parameter_properties.rs b/src/scene/block_parameter_properties.rs index 9acb4d3731..daf89a0955 100644 --- a/src/scene/block_parameter_properties.rs +++ b/src/scene/block_parameter_properties.rs @@ -190,6 +190,7 @@ pub(crate) fn component_id(component: &Component) -> String { Component::Angle => "Angle".to_owned(), Component::Flip => "Flip".to_owned(), Component::Visibility(_) => "Visibility".to_owned(), + Component::Bricscad(_) => "BricscadVisibility".to_owned(), Component::TableRow(_) => "TableRow".to_owned(), Component::LookupOutput { column, .. } => format!("Lookup{column}"), } @@ -376,6 +377,7 @@ pub(crate) fn evaluate( } Component::Flip | Component::Visibility(_) + | Component::Bricscad(_) | Component::TableRow(_) | Component::LookupOutput { .. } => unreachable!(), } diff --git a/src/scene/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs new file mode 100644 index 0000000000..434466ba26 --- /dev/null +++ b/src/scene/bricscad_parameters.rs @@ -0,0 +1,181 @@ +//! Visibility states of BricsCAD parametric blocks, read from the objects +//! BricsCAD keeps them in. +//! +//! BricsCAD stores a parametric block's parameters in objects of its own +//! classes under `BDM_DATABASE` in the block's extension dictionary. They are +//! read as raw records (`ObjectType::Unknown`); this module decodes the few it +//! needs from their DWG bytes (DWG 2010 and later): +//! +//! - `BDMDBFEATUREMANAGER` (`FEATURE_MANAGER`) lists the block's features. +//! - A `BDMDBFEATUREDATA` of type `BdmConfigurationFeature` whose table type +//! is `VisibilityStates` is one visibility parameter: its name and the state +//! the block shows (`LastKeyValue`). +//! - Its `BDMDBCONFIGURATIONTABLE` names the states (`KeyValues`). +//! - The `BdmDbPersIdManager` (`PERSIDMANAGER`) of an anonymous copy names the +//! block it was made from (`original.block`). +//! +//! A reference in a state other than the definition's shows such a copy, whose +//! own features hold the state it shows; the members a state hides sit on the +//! layer `*SUPPRESS` there. +//! +//! [`record`] decodes and encodes the objects; `switch` changes the state a +//! reference shows the way BricsCAD does. + +use document::objects::ObjectType; +use document::{Document, EntityType, Handle}; + +pub(crate) mod record; +mod switch; + +pub(crate) use switch::can_switch; + +use record::{Properties, Record}; + +/// A visibility parameter of a BricsCAD parametric block. +#[derive(Debug, Clone, PartialEq)] +pub struct VisibilityParameter { + pub name: String, + pub states: Vec, + /// The state the block shows, by index into `states`. + pub current: Option, + /// The parameter's feature in the block it was read from. + pub feature: Handle, +} + +/// The visibility parameters of block record `block`, in the order its feature +/// list holds them. Empty for a block BricsCAD did not make parametric, and +/// for one whose objects cannot be read. +pub fn visibility_parameters(document: &Document, block: Handle) -> Vec { + features(document, block) + .into_iter() + .filter_map(|feature| visibility_parameter(document, feature)) + .collect() +} + +/// The visibility parameters of the block reference `insert`, in the states +/// it shows. +pub fn reference_parameters(document: &Document, insert: Handle) -> Vec { + shown_block(document, insert) + .map(|block| visibility_parameters(document, block)) + .unwrap_or_default() +} + +/// The block an anonymous copy of a BricsCAD parametric block was made from. +pub fn original_block(document: &Document, block: Handle) -> Option { + let manager = database_entry(document, block, "PERSIDMANAGER")?; + let original = properties(document, manager)? + .get("original.block")? + .object()?; + (!original.is_null() && original != block).then_some(original) +} + +/// The BricsCAD parametric block a reference shows, or shows a copy of. +pub fn master_block(document: &Document, insert: Handle) -> Option { + let block = shown_block(document, insert)?; + let master = original_block(document, block).unwrap_or(block); + (!visibility_parameters(document, master).is_empty()).then_some(master) +} + +/// The block record a reference shows. +fn shown_block(document: &Document, insert: Handle) -> Option { + let Some(EntityType::Insert(reference)) = document.get_entity(insert) else { + return None; + }; + document + .block_records + .get(&reference.block_name) + .map(|record| record.handle) +} + +/// The features of `block`'s feature manager, in stored order. +fn features(document: &Document, block: Handle) -> Vec { + database_entry(document, block, "FEATURE_MANAGER") + .and_then(|manager| properties(document, manager)) + .and_then(|manager| { + Some( + manager + .get("Features")? + .items()? + .iter() + .filter_map(record::Value::object) + .collect(), + ) + }) + .unwrap_or_default() +} + +fn visibility_parameter(document: &Document, feature: Handle) -> Option { + let handle = feature; + let feature = properties(document, feature)?; + if feature.text("Feature_type")? != "BdmConfigurationFeature" + || feature.text("TableType")? != "VisibilityStates" + { + return None; + } + let table = properties(document, feature.get("ConfigTable")?.object()?)?; + let states: Vec = table + .get("KeyValues")? + .items()? + .iter() + .map(|state| state.text().map(str::to_string)) + .collect::>()?; + let name = table + .text("KeyName") + .or_else(|| feature.text("Name"))? + .to_string(); + let current = feature + .text("LastKeyValue") + .and_then(|shown| states.iter().position(|state| state == shown)); + Some(VisibilityParameter { + name, + states, + current, + feature: handle, + }) +} + +/// Entry `key` of the `BDM_DATABASE` dictionary in `owner`'s extension +/// dictionary. +fn database_entry(document: &Document, owner: Handle, key: &str) -> Option { + let dictionary = |handle: Handle| match document.objects.get(&handle)? { + ObjectType::Dictionary(dictionary) => Some(dictionary), + _ => None, + }; + let extension = dictionary(document.extension_dictionary_handle(owner)?)?; + dictionary(extension.get("BDM_DATABASE")?)?.get(key) +} + +/// The record of the BricsCAD object `handle`, decoded from the DWG record it +/// was read from. `None` for any other object, a record from a DXF file or a +/// DWG before 2010, and a record that does not decode in full. +pub(crate) fn record(document: &Document, handle: Handle) -> Option { + let ObjectType::Unknown { + type_name, + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } = document.objects.get(&handle)? + else { + return None; + }; + record::decode(type_name, data, *raw_dwg_handle_bits, *version) +} + +/// The properties of the BricsCAD object `handle` whose record is a plain +/// property list (see [`record`]). +pub(crate) fn properties(document: &Document, handle: Handle) -> Option { + match record(document, handle)?.body { + record::Body::Properties(properties) => Some(properties), + _ => None, + } +} + +#[cfg(test)] +mod tests; + +#[cfg(test)] +mod record_tests; + +#[cfg(test)] +mod switch_tests; diff --git a/src/scene/bricscad_parameters/record.rs b/src/scene/bricscad_parameters/record.rs new file mode 100644 index 0000000000..00f097a784 --- /dev/null +++ b/src/scene/bricscad_parameters/record.rs @@ -0,0 +1,925 @@ +//! BricsCAD's parameter objects as DWG records (2010 and later), decoded so +//! that encoding them again gives the same bits, and encoded after a change. +//! +//! A record holds the common object header (type, handle, extended data, +//! owner, reactors, extension dictionary) and a body. Most of BricsCAD's +//! classes hold a plain list of named properties; three hold a few values +//! around such a list: +//! +//! - `BDMDBCONSTRAINTMANAGER`: five counts, the objects and child managers it +//! owns, then its settings; +//! - `BDMOBJECT`: a byte and a count, the object it stands for, its +//! properties, a count; +//! - `BDMDBOBJECTDEPENDENCY`: its (empty) properties, a count, the object it +//! depends on. +//! +//! In the data stream a property list is a count and, per property, a type +//! byte and the value. Names and text sit in the string stream and references +//! in the handle stream, both in the order the data stream names them. + +use document::{DxfVersion, Handle}; + +/// A reference through the handle stream and the code it is written with: +/// a reference type (2 to 5) or one of the forms relative to the record's own +/// handle (6, 8, 10, 12). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Ref { + pub(crate) handle: Handle, + pub(crate) code: u8, +} + +impl Ref { + pub(crate) fn new(handle: Handle, code: u8) -> Self { + Self { handle, code } + } +} + +/// A property value. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Value { + Text(String), + Integer(i32), + Real(f64), + Flag(bool), + Byte(u8), + /// Bytes in the data stream; BricsCAD stores some handles this way. + Raw(Vec), + /// A reference: a byte in the data stream, the handle in the handle stream. + Object { + kind: u8, + target: Ref, + }, + List { + element: u8, + items: Vec, + }, + Map { + key: u8, + value: u8, + entries: Vec<(Value, Value)>, + }, +} + +impl Value { + fn kind(&self) -> u8 { + match self { + Value::Text(_) => 2, + Value::Integer(_) => 3, + Value::Real(_) => 4, + Value::Flag(_) => 5, + Value::Byte(_) => 6, + Value::Raw(_) => 7, + Value::Object { .. } => 8, + Value::List { .. } => 9, + Value::Map { .. } => 10, + } + } + + pub(crate) fn text(&self) -> Option<&str> { + match self { + Value::Text(text) => Some(text), + _ => None, + } + } + + pub(crate) fn object(&self) -> Option { + match self { + Value::Object { target, .. } => Some(target.handle), + _ => None, + } + } + + pub(crate) fn items(&self) -> Option<&[Value]> { + match self { + Value::List { items, .. } => Some(items), + _ => None, + } + } + + pub(crate) fn entries(&self) -> Option<&[(Value, Value)]> { + match self { + Value::Map { entries, .. } => Some(entries), + _ => None, + } + } + + /// Every reference in the value, in the order they are written. + fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) { + match self { + Value::Object { target, .. } => visit(target), + Value::List { items, .. } => items.iter_mut().for_each(|item| item.refs_mut(visit)), + Value::Map { entries, .. } => entries.iter_mut().for_each(|(key, value)| { + key.refs_mut(visit); + value.refs_mut(visit); + }), + _ => {} + } + } +} + +/// The named properties of a record, in stored order. +#[derive(Debug, Clone, PartialEq, Default)] +pub(crate) struct Properties(pub(crate) Vec<(String, Value)>); + +impl Properties { + pub(crate) fn get(&self, name: &str) -> Option<&Value> { + self.0 + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value) + } + + pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut Value> { + self.0 + .iter_mut() + .find(|(key, _)| key == name) + .map(|(_, value)| value) + } + + pub(crate) fn text(&self, name: &str) -> Option<&str> { + self.get(name)?.text() + } + + /// Replace the value of an existing property; `false` when there is none. + pub(crate) fn set(&mut self, name: &str, value: Value) -> bool { + match self.get_mut(name) { + Some(slot) => { + *slot = value; + true + } + None => false, + } + } + + fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) { + for (_, value) in &mut self.0 { + value.refs_mut(visit); + } + } +} + +/// What a record holds after the common header. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Body { + Properties(Properties), + /// `BDMDBCONSTRAINTMANAGER`. `counts[1]` objects and `counts[3]` child + /// managers, in that order in `children`. + ConstraintManager { + counts: [i32; 5], + children: Vec, + settings: Properties, + }, + /// `BDMOBJECT`. + Object { + lead: u8, + lead_count: i32, + entity: Ref, + properties: Properties, + tail: i32, + }, + /// `BDMDBOBJECTDEPENDENCY`. + Dependency { + properties: Properties, + tail: i32, + entity: Ref, + }, +} + +impl Body { + pub(crate) fn properties(&self) -> &Properties { + match self { + Body::Properties(properties) + | Body::Object { properties, .. } + | Body::Dependency { properties, .. } => properties, + Body::ConstraintManager { settings, .. } => settings, + } + } + + pub(crate) fn properties_mut(&mut self) -> &mut Properties { + match self { + Body::Properties(properties) + | Body::Object { properties, .. } + | Body::Dependency { properties, .. } => properties, + Body::ConstraintManager { settings, .. } => settings, + } + } + + /// Every reference of the body, in the order they are written. + fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) { + match self { + Body::Properties(properties) => properties.refs_mut(visit), + Body::ConstraintManager { + children, settings, .. + } => { + children.iter_mut().for_each(&mut *visit); + settings.refs_mut(visit); + } + Body::Object { + entity, properties, .. + } => { + visit(entity); + properties.refs_mut(visit); + } + Body::Dependency { + properties, entity, .. + } => { + properties.refs_mut(visit); + visit(entity); + } + } + } +} + +/// One record of a BricsCAD parameter object. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Record { + object_type: u16, + pub(crate) handle: Handle, + handle_code: u8, + extended_data: Vec<(Ref, Vec)>, + pub(crate) owner: Ref, + pub(crate) reactors: Vec, + pub(crate) extension_dictionary: Option, + binary_data: bool, + pub(crate) body: Body, + pub(crate) version: DxfVersion, +} + +impl Record { + /// A new record of the class of `template`, which gives the type number + /// and the version; no extended data, reactors or extension dictionary. + pub(crate) fn like(template: &Record, handle: Handle, owner: Ref, body: Body) -> Self { + Self { + object_type: template.object_type, + handle, + handle_code: template.handle_code, + extended_data: Vec::new(), + owner, + reactors: Vec::new(), + extension_dictionary: None, + binary_data: false, + body, + version: template.version, + } + } + + /// Every reference of the record: owner, reactors, extension dictionary + /// and those of the body. Extended data names applications, which are + /// left alone. + pub(crate) fn refs_mut(&mut self, mut visit: impl FnMut(&mut Ref)) { + visit(&mut self.owner); + self.reactors.iter_mut().for_each(&mut visit); + if let Some(dictionary) = &mut self.extension_dictionary { + visit(dictionary); + } + self.body.refs_mut(&mut visit); + } +} + +/// Decode the record of a `class` object: the merged data, string and handle +/// streams as the DWG reader keeps them, without the size prefixes and the +/// CRC. `None` for a DWG before 2010 and a record that does not decode in +/// full: any data or string bit left over, or more than padding left in the +/// handle stream. +pub(crate) fn decode( + class: &str, + data: &[u8], + handle_bits: i64, + version: DxfVersion, +) -> Option { + if version < DxfVersion::AC1024 { + return None; + } + let total = data.len().checked_mul(8)?; + let handles_at = total.checked_sub(usize::try_from(handle_bits).ok()?)?; + let mut main = Bits::new(data, 0, handles_at); + let object_type = main.object_type()?; + let (handle_code, own) = main.handle(0)?; + let mut extended_data = Vec::new(); + loop { + let size = main.bit_short()?; + if size < 0 { + return None; + } + if size == 0 { + break; + } + let (code, application) = main.handle(0)?; + let bytes = (0..size).map(|_| main.byte()).collect::>>()?; + extended_data.push((Ref::new(Handle::from(application), code), bytes)); + } + let reactor_count = usize::try_from(main.bit_long()?).ok()?; + if reactor_count > total { + return None; + } + let has_extension_dictionary = !main.bit()?; + let binary_data = version >= DxfVersion::AC1027 && main.bit()?; + + let (strings_at, strings_end) = string_stream(data, handles_at)?; + if main.pos > strings_at { + return None; + } + main.end = strings_at; + let mut handles = Bits::new(data, handles_at, total); + let reference = |handles: &mut Bits| { + handles + .handle(own) + .map(|(code, handle)| Ref::new(Handle::from(handle), code)) + }; + let owner = reference(&mut handles)?; + let reactors = (0..reactor_count) + .map(|_| reference(&mut handles)) + .collect::>>()?; + let extension_dictionary = if has_extension_dictionary { + Some(reference(&mut handles)?) + } else { + None + }; + let mut reader = Reader { + main, + strings: Bits::new(data, strings_at, strings_end), + handles, + own, + }; + let body = reader.body(class)?; + let complete = reader.main.pos == reader.main.end + && reader.strings.pos == reader.strings.end + && reader.handles.end - reader.handles.pos < 8; + complete.then_some(Record { + object_type, + handle: Handle::from(own), + handle_code, + extended_data, + owner, + reactors, + extension_dictionary, + binary_data, + body, + version, + }) +} + +/// Encode `record`: the merged streams and the bit count of its handle +/// stream, as the DWG writer takes a raw record. +pub(crate) fn encode(record: &Record) -> (Vec, i64) { + let own = record.handle.value(); + let mut main = Writer::default(); + let strings = Writer::default(); + let mut handles = Writer::default(); + main.object_type(record.object_type); + main.handle(record.handle_code, own, 0); + for (application, bytes) in &record.extended_data { + main.bit_short(bytes.len() as i16); + main.handle(application.code, application.handle.value(), 0); + for byte in bytes { + main.byte(*byte); + } + } + main.bit_short(0); + main.bit_long(record.reactors.len() as i32); + main.bit(record.extension_dictionary.is_none()); + if record.version >= DxfVersion::AC1027 { + main.bit(record.binary_data); + } + handles.reference(record.owner, own); + for reactor in &record.reactors { + handles.reference(*reactor, own); + } + if let Some(dictionary) = record.extension_dictionary { + handles.reference(dictionary, own); + } + let mut encoder = Encoder { + main, + strings, + handles, + own, + }; + encoder.body(&record.body); + let Encoder { + mut main, + strings, + handles, + .. + } = encoder; + let string_bits = strings.len; + if string_bits > 0 { + main.append(&strings); + if string_bits < 0x8000 { + main.raw_short(string_bits as u16); + } else { + main.raw_short((string_bits >> 15) as u16); + main.raw_short((string_bits & 0x7FFF) as u16 | 0x8000); + } + main.bit(true); + } else { + main.bit(false); + } + let main_bits = main.len; + main.append(&handles); + let bytes = main.into_bytes(); + let handle_bits = (bytes.len() * 8 - main_bits) as i64; + (bytes, handle_bits) +} + +/// The bit range of the string stream, which ends where the data stream's +/// last bit says whether there is one. +fn string_stream(data: &[u8], handles_at: usize) -> Option<(usize, usize)> { + let flag = handles_at.checked_sub(1)?; + if !Bits::new(data, flag, handles_at).bit()? { + return Some((flag, flag)); + } + let size_at = flag.checked_sub(16)?; + let mut size = usize::from(Bits::new(data, size_at, flag).raw_short()?); + let mut start = size_at; + if size & 0x8000 != 0 { + let high_at = size_at.checked_sub(16)?; + let high = usize::from(Bits::new(data, high_at, size_at).raw_short()?); + size = (size & 0x7FFF) | (high << 15); + start = high_at; + } + Some((start.checked_sub(size)?, start)) +} + +struct Reader<'a> { + main: Bits<'a>, + strings: Bits<'a>, + handles: Bits<'a>, + own: u64, +} + +impl Reader<'_> { + fn body(&mut self, class: &str) -> Option { + Some(match class { + "BDMDBCONSTRAINTMANAGER" => { + let mut counts = [0; 5]; + for count in &mut counts { + *count = self.main.bit_long()?; + } + // Only the objects and child managers are understood. + if counts[2] != 0 || counts[4] != 0 { + return None; + } + let children = + usize::try_from(counts[1]).ok()? + usize::try_from(counts[3]).ok()?; + if children > self.handles.end { + return None; + } + let children = (0..children) + .map(|_| self.reference()) + .collect::>>()?; + Body::ConstraintManager { + counts, + children, + settings: self.properties()?, + } + } + "BDMOBJECT" => Body::Object { + lead: self.main.byte()?, + lead_count: self.main.bit_long()?, + entity: self.reference()?, + properties: self.properties()?, + tail: self.main.bit_long()?, + }, + "BDMDBOBJECTDEPENDENCY" => Body::Dependency { + properties: self.properties()?, + tail: self.main.bit_long()?, + entity: self.reference()?, + }, + _ => Body::Properties(self.properties()?), + }) + } + + fn reference(&mut self) -> Option { + let (code, handle) = self.handles.handle(self.own)?; + Some(Ref::new(Handle::from(handle), code)) + } + + fn properties(&mut self) -> Option { + let count = self.count()?; + let mut properties = Vec::with_capacity(count.min(64)); + for _ in 0..count { + let name = self.text()?; + let kind = self.main.byte()?; + properties.push((name, self.value(kind, 0)?)); + } + Some(Properties(properties)) + } + + fn value(&mut self, kind: u8, depth: u8) -> Option { + // Lists and maps nest a level or two; a deeper one is not a property + // list. + if depth > 4 { + return None; + } + Some(match kind { + 2 => Value::Text(self.text()?), + 3 => Value::Integer(self.main.bit_long()?), + 4 => Value::Real(self.main.bit_double()?), + 5 => Value::Flag(self.main.bit()?), + 6 => Value::Byte(self.main.byte()?), + 7 => { + let length = self.main.byte()?; + Value::Raw( + (0..length) + .map(|_| self.main.byte()) + .collect::>()?, + ) + } + 8 => Value::Object { + kind: self.main.byte()?, + target: self.reference()?, + }, + 9 => { + let element = self.main.byte()?; + let count = self.count()?; + Value::List { + element, + items: (0..count) + .map(|_| self.value(element, depth + 1)) + .collect::>()?, + } + } + 10 => { + let key = self.main.byte()?; + let value = self.main.byte()?; + let count = self.count()?; + Value::Map { + key, + value, + entries: (0..count) + .map(|_| Some((self.value(key, depth + 1)?, self.value(value, depth + 1)?))) + .collect::>()?, + } + } + _ => return None, + }) + } + + /// An element count. Every element takes at least one bit of one of the + /// streams, so a count beyond the record's bits is not one. + fn count(&mut self) -> Option { + let count = usize::try_from(self.main.bit_long()?).ok()?; + (count <= self.main.data.len() * 8).then_some(count) + } + + /// A string from the string stream: a length, then UTF-16 code units. + fn text(&mut self) -> Option { + let length = usize::try_from(self.strings.bit_short()?).ok()?; + if length * 16 > self.strings.end - self.strings.pos { + return None; + } + let units: Vec = (0..length) + .map(|_| self.strings.raw_short()) + .collect::>()?; + Some(String::from_utf16_lossy(&units)) + } +} + +struct Encoder { + main: Writer, + strings: Writer, + handles: Writer, + own: u64, +} + +impl Encoder { + fn body(&mut self, body: &Body) { + match body { + Body::Properties(properties) => self.properties(properties), + Body::ConstraintManager { + counts, + children, + settings, + } => { + for count in counts { + self.main.bit_long(*count); + } + for child in children { + self.handles.reference(*child, self.own); + } + self.properties(settings); + } + Body::Object { + lead, + lead_count, + entity, + properties, + tail, + } => { + self.main.byte(*lead); + self.main.bit_long(*lead_count); + self.handles.reference(*entity, self.own); + self.properties(properties); + self.main.bit_long(*tail); + } + Body::Dependency { + properties, + tail, + entity, + } => { + self.properties(properties); + self.main.bit_long(*tail); + self.handles.reference(*entity, self.own); + } + } + } + + fn properties(&mut self, properties: &Properties) { + self.main.bit_long(properties.0.len() as i32); + for (name, value) in &properties.0 { + self.text(name); + self.main.byte(value.kind()); + self.value(value); + } + } + + fn value(&mut self, value: &Value) { + match value { + Value::Text(text) => self.text(text), + Value::Integer(integer) => self.main.bit_long(*integer), + Value::Real(real) => self.main.bit_double(*real), + Value::Flag(flag) => self.main.bit(*flag), + Value::Byte(byte) => self.main.byte(*byte), + Value::Raw(bytes) => { + self.main.byte(bytes.len() as u8); + for byte in bytes { + self.main.byte(*byte); + } + } + Value::Object { kind, target } => { + self.main.byte(*kind); + self.handles.reference(*target, self.own); + } + Value::List { element, items } => { + self.main.byte(*element); + self.main.bit_long(items.len() as i32); + for item in items { + self.value(item); + } + } + Value::Map { + key, + value, + entries, + } => { + self.main.byte(*key); + self.main.byte(*value); + self.main.bit_long(entries.len() as i32); + for (key, value) in entries { + self.value(key); + self.value(value); + } + } + } + } + + fn text(&mut self, text: &str) { + let units: Vec = text.encode_utf16().collect(); + self.strings.bit_short(units.len() as i16); + for unit in units { + self.strings.raw_short(unit); + } + } +} + +/// A bit range of a record, read most significant bit first. +pub(super) struct Bits<'a> { + data: &'a [u8], + pos: usize, + end: usize, +} + +impl<'a> Bits<'a> { + fn new(data: &'a [u8], pos: usize, end: usize) -> Self { + Self { + data, + pos, + end: end.min(data.len() * 8), + } + } + + fn bit(&mut self) -> Option { + if self.pos >= self.end { + return None; + } + let bit = self.data[self.pos / 8] >> (7 - self.pos % 8) & 1; + self.pos += 1; + Some(bit == 1) + } + + fn bits(&mut self, count: u32) -> Option { + (0..count).try_fold(0, |value, _| Some(value << 1 | u32::from(self.bit()?))) + } + + fn byte(&mut self) -> Option { + self.bits(8).map(|value| value as u8) + } + + fn raw_short(&mut self) -> Option { + Some(u16::from_le_bytes([self.byte()?, self.byte()?])) + } + + fn raw_long(&mut self) -> Option { + Some(u32::from_le_bytes([ + self.byte()?, + self.byte()?, + self.byte()?, + self.byte()?, + ])) + } + + fn bit_short(&mut self) -> Option { + Some(match self.bits(2)? { + 0 => self.raw_short()? as i16, + 1 => i16::from(self.byte()?), + 2 => 0, + _ => 256, + }) + } + + fn bit_long(&mut self) -> Option { + match self.bits(2)? { + 0 => Some(self.raw_long()? as i32), + 1 => Some(i32::from(self.byte()?)), + 2 => Some(0), + _ => None, + } + } + + fn bit_double(&mut self) -> Option { + match self.bits(2)? { + 0 => { + let mut bytes = [0; 8]; + for byte in &mut bytes { + *byte = self.byte()?; + } + Some(f64::from_le_bytes(bytes)) + } + 1 => Some(1.0), + 2 => Some(0.0), + _ => None, + } + } + + /// The object type of a DWG 2010 or later record. + fn object_type(&mut self) -> Option { + match self.bits(2)? { + 0 => self.byte().map(u16::from), + 1 => self.byte().map(|byte| 0x1F0 + u16::from(byte)), + _ => self.raw_short(), + } + } + + /// A handle reference as its code and the handle; the offset forms count + /// from `reference`. + fn handle(&mut self, reference: u64) -> Option<(u8, u64)> { + let form = self.byte()?; + let mut value = 0u64; + for _ in 0..form & 0x0F { + value = value << 8 | u64::from(self.byte()?); + } + let code = form >> 4; + let handle = match code { + 0x6 => reference.checked_add(1)?, + 0x8 => reference.checked_sub(1)?, + 0xA => reference.checked_add(value)?, + 0xC => reference.checked_sub(value)?, + _ => value, + }; + Some((code, handle)) + } +} + +/// The bits of a record being written, most significant bit first. +#[derive(Default)] +struct Writer { + bytes: Vec, + len: usize, +} + +impl Writer { + fn bit(&mut self, bit: bool) { + if self.len.is_multiple_of(8) { + self.bytes.push(0); + } + if bit { + let last = self.bytes.len() - 1; + self.bytes[last] |= 0x80 >> (self.len % 8); + } + self.len += 1; + } + + fn bits(&mut self, value: u32, count: u32) { + for shift in (0..count).rev() { + self.bit(value >> shift & 1 == 1); + } + } + + fn byte(&mut self, byte: u8) { + self.bits(u32::from(byte), 8); + } + + fn raw_short(&mut self, value: u16) { + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + + fn bit_short(&mut self, value: i16) { + match value { + 0 => self.bits(2, 2), + 256 => self.bits(3, 2), + 1..=255 => { + self.bits(1, 2); + self.byte(value as u8); + } + _ => { + self.bits(0, 2); + self.raw_short(value as u16); + } + } + } + + fn bit_long(&mut self, value: i32) { + match value { + 0 => self.bits(2, 2), + 1..=255 => { + self.bits(1, 2); + self.byte(value as u8); + } + _ => { + self.bits(0, 2); + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + } + } + + fn bit_double(&mut self, value: f64) { + if value.to_bits() == 1.0f64.to_bits() { + self.bits(1, 2); + } else if value.to_bits() == 0.0f64.to_bits() { + self.bits(2, 2); + } else { + self.bits(0, 2); + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + } + + fn object_type(&mut self, value: u16) { + if value <= 0xFF { + self.bits(0, 2); + self.byte(value as u8); + } else if (0x1F0..=0x2EF).contains(&value) { + self.bits(1, 2); + self.byte((value - 0x1F0) as u8); + } else { + self.bits(2, 2); + self.raw_short(value); + } + } + + /// A handle with `code`; an offset form is recomputed from `own`, and + /// falls back to the matching other offset form when the handle moved. + fn handle(&mut self, code: u8, handle: u64, own: u64) { + let (code, value) = match code { + 0x6 | 0x8 | 0xA | 0xC => { + let difference = i128::from(handle) - i128::from(own); + match (code, difference) { + (0x6, 1) => (0x6, 0), + (0x8, -1) => (0x8, 0), + (_, difference) if difference > 0 => (0xA, difference as u64), + (_, difference) if difference < 0 => (0xC, difference.unsigned_abs() as u64), + _ => (0x4, handle), + } + } + code => (code, handle), + }; + let bytes: Vec = value + .to_be_bytes() + .into_iter() + .skip_while(|byte| *byte == 0) + .collect(); + self.byte(code << 4 | bytes.len() as u8); + for byte in bytes { + self.byte(byte); + } + } + + fn reference(&mut self, reference: Ref, own: u64) { + self.handle(reference.code, reference.handle.value(), own); + } + + fn append(&mut self, other: &Writer) { + for index in 0..other.len { + self.bit(other.bytes[index / 8] >> (7 - index % 8) & 1 == 1); + } + } + + fn into_bytes(self) -> Vec { + self.bytes + } +} diff --git a/src/scene/bricscad_parameters/record_tests.rs b/src/scene/bricscad_parameters/record_tests.rs new file mode 100644 index 0000000000..edad3ca260 --- /dev/null +++ b/src/scene/bricscad_parameters/record_tests.rs @@ -0,0 +1,117 @@ +use super::record::{decode, encode, Body, Ref, Value}; +use super::*; + +/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README). +fn fixture() -> Document { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture") +} + +/// Every BricsCAD object of `document` with its class, record bytes, handle +/// stream bits and version. +fn bricscad_records( + document: &Document, +) -> Vec<(Handle, String, Vec, i64, document::DxfVersion)> { + let mut records: Vec<_> = document + .objects + .iter() + .filter_map(|(handle, object)| match object { + ObjectType::Unknown { + type_name, + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } if type_name.to_ascii_uppercase().starts_with("BDM") => Some(( + *handle, + type_name.clone(), + data.clone(), + *raw_dwg_handle_bits, + *version, + )), + _ => None, + }) + .collect(); + records.sort_by_key(|record| record.0); + records +} + +#[test] +fn every_bricscad_record_encodes_to_the_bits_it_was_read_from() { + let document = fixture(); + let records = bricscad_records(&document); + assert_eq!(records.len(), 87, "the fixture's BricsCAD objects"); + for (handle, class, data, handle_bits, version) in records { + let record = decode(&class, &data, handle_bits, version) + .unwrap_or_else(|| panic!("{class} {handle:?} does not decode")); + assert_eq!(record.handle, handle, "{class}"); + assert_eq!( + encode(&record), + (data, handle_bits), + "{class} {handle:?} encodes to other bits" + ); + } +} + +#[test] +fn the_three_classes_around_a_property_list_decode_to_their_parts() { + let document = fixture(); + let manager = record(&document, Handle::from(0x1A5u64)).unwrap(); + let Body::ConstraintManager { + counts, children, .. + } = &manager.body + else { + panic!("{:?}", manager.body); + }; + assert_eq!(*counts, [2, 2, 0, 0, 0]); + assert_eq!( + children + .iter() + .map(|child| child.handle) + .collect::>(), + [Handle::from(0x1A6u64), Handle::from(0x1E1u64)] + ); + let object = record(&document, Handle::from(0x1A6u64)).unwrap(); + let Body::Object { + entity, properties, .. + } = &object.body + else { + panic!("{:?}", object.body); + }; + assert_eq!( + entity.handle, + Handle::from(0x146u64), + "the reference it stands for" + ); + assert_eq!(properties.text("NAME"), Some("Objekt_1")); + let dependency = record(&document, Handle::from(0x1A7u64)).unwrap(); + let Body::Dependency { entity, .. } = &dependency.body else { + panic!("{:?}", dependency.body); + }; + assert_eq!(entity.handle, Handle::from(0x146u64)); +} + +#[test] +fn a_changed_record_reads_back_as_changed() { + let document = fixture(); + let mut feature = record(&document, Handle::from(0x1C7u64)).unwrap(); + assert_eq!(feature.body.properties().text("LastKeyValue"), Some("Off")); + // Longer text, a new handle further away and every reference moved: the + // offset forms are recomputed from the new handle. + feature.body.properties_mut().set( + "LastKeyValue", + Value::Text("A much longer state name".into()), + ); + feature.handle = Handle::from(0x12_3456u64); + feature.refs_mut(|reference: &mut Ref| { + reference.handle = Handle::from(reference.handle.value() + 0x1000); + }); + let (data, handle_bits) = encode(&feature); + let read = decode("BDMDBFEATUREDATA", &data, handle_bits, feature.version).unwrap(); + assert_eq!(read, feature); +} diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs new file mode 100644 index 0000000000..c21cc54eb0 --- /dev/null +++ b/src/scene/bricscad_parameters/switch.rs @@ -0,0 +1,1304 @@ +//! Switching the visibility state a BricsCAD parametric block reference +//! shows, the way BricsCAD does it, so that BricsCAD keeps the block's +//! parameters. +//! +//! A reference shows the block itself or an anonymous copy of it, and +//! BricsCAD reads the states a reference shows from the parameter objects of +//! that copy. When a state is changed in BricsCAD, it starts from the states +//! the reference's entry in model space lists: a `BmAssemblyParameters` +//! feature, linked to the reference through a `BDMOBJECT` and a dependency, +//! that lists every parameter the reference was ever set to with the state it +//! shows. BricsCAD shares a copy between references that show the same +//! states. +//! +//! Switching here: +//! 1. works out the states the reference is to show and the parameters its +//! entry lists; +//! 2. points the reference at the block when those are the block's own states, +//! at a copy of the block that shows them when there is one, or at a new +//! copy: the block's members and all its parameter objects cloned under new +//! handles, with the states set as BricsCAD sets them; +//! 3. moves the reference's attributes on or off `*SUPPRESS` with their +//! definitions in the block it now shows; +//! 4. writes the reference's entry in model space, creating it, and model +//! space's own parameter objects when there are none. + +use std::collections::{BTreeMap, BTreeSet}; + +use document::objects::{ + AssocAction, AssocDependency, AssocEvalValue, AssocEvalVariant, AssociativeData, + AssociativeObject, ObjectType, +}; +use document::{Document, EntityType, Handle}; +use rustc_hash::{FxHashMap, FxHashSet}; + +use super::record::{self, Body, Properties, Record, Ref, Value}; +use super::{ + database_entry, features, original_block, record as read_record, shown_block, + visibility_parameters, +}; +use crate::scene::Scene; + +/// The layer BricsCAD moves the members a state hides to. +const SUPPRESS_LAYER: &str = "*SUPPRESS"; + +const UNSUPPORTED: &str = "This BricsCAD parametric block cannot be switched here."; +const NOT_IN_MODEL_SPACE: &str = "Only a BricsCAD block reference in model space can be switched."; +const NO_SUCH_STATE: &str = "The block has no such visibility state."; + +type Result = std::result::Result; + +/// Whether [`Scene::set_bricscad_visibility`] can switch `insert`: a +/// reference in model space to a BricsCAD parametric block, or to a copy of +/// one, whose parameter objects read. +pub(crate) fn can_switch(document: &Document, insert: Handle) -> bool { + document.get_entity(insert).is_some_and(|entity| { + entity.common().owner_handle == document.header.model_space_block_handle + }) && super::master_block(document, insert).is_some() +} + +impl Scene { + /// Show `state` of the visibility parameter `parameter` on the reference + /// `insert`, as BricsCAD does. `Ok(false)` when the reference shows it + /// already. On an error the document is left as it was only when the + /// caller works on a copy of it; the property and automation paths do. + pub(crate) fn set_bricscad_visibility( + &mut self, + insert: Handle, + parameter: &str, + state: &str, + ) -> Result { + let document = &self.document; + if !can_switch(document, insert) { + return Err(NOT_IN_MODEL_SPACE); + } + let shown = shown_block(document, insert).ok_or(UNSUPPORTED)?; + let master = original_block(document, shown).unwrap_or(shown); + let master_parameters = visibility_parameters(document, master); + let shown_parameters = visibility_parameters(document, shown); + let names: Vec<&str> = master_parameters.iter().map(|p| p.name.as_str()).collect(); + if names.is_empty() + || shown_parameters + .iter() + .map(|p| p.name.as_str()) + .ne(names.iter().copied()) + { + return Err(UNSUPPORTED); + } + let index = names + .iter() + .position(|name| *name == parameter) + .ok_or(NO_SUCH_STATE)?; + if !master_parameters[index].states.iter().any(|s| s == state) { + return Err(NO_SUCH_STATE); + } + let shown_state = |parameters: &[super::VisibilityParameter]| -> Result> { + parameters + .iter() + .map(|p| { + p.current + .and_then(|current| p.states.get(current).cloned()) + .ok_or(UNSUPPORTED) + }) + .collect() + }; + let defaults = shown_state(&master_parameters)?; + let current = shown_state(&shown_parameters)?; + if current[index] == state { + return Ok(false); + } + let mut target = current.clone(); + target[index] = state.to_string(); + + // The entry lists what it listed, what differs from the block, and + // the parameter set now, each in the state it shows. + let entry = find_entry(document, insert); + let mut listed: BTreeSet = entry + .as_ref() + .and_then(|(_, record)| record.body.properties().get("expr.const")) + .and_then(Value::entries) + .map(|entries| { + entries + .iter() + .filter_map(|(key, _)| key.text().map(str::to_string)) + .filter(|key| names.contains(&key.as_str())) + .collect() + }) + .unwrap_or_default(); + for (k, name) in names.iter().enumerate() { + if current[k] != defaults[k] { + listed.insert(name.to_string()); + } + } + listed.insert(parameter.to_string()); + let overrides: Vec<(String, String)> = listed + .iter() + .map(|name| { + let k = names.iter().position(|n| n == name).unwrap_or(index); + (name.clone(), target[k].clone()) + }) + .collect(); + let names: Vec = names.iter().map(|name| name.to_string()).collect(); + + let block = if target == defaults { + master + } else if let Some(copy) = find_copy(&self.document, master, &target) { + copy + } else { + let states: BTreeMap = + names.iter().cloned().zip(target.iter().cloned()).collect(); + self.clone_parametric_copy(master, &states, &listed)? + }; + if block != shown { + let name = self + .document + .block_records + .iter() + .find(|record| record.handle == block) + .map(|record| record.name.clone()) + .ok_or(UNSUPPORTED)?; + self.repoint_representation(insert, shown, block, &name); + follow_attribute_definitions(&mut self.document, insert, block); + } + write_entry(&mut self.document, insert, master, overrides)?; + Ok(true) + } + + /// A new anonymous copy of the BricsCAD parametric block `master` showing + /// `states`, with the parameters in `listed` set on it: the members and + /// every object under the block's extension dictionary cloned under new + /// handles, then the states applied. + pub(super) fn clone_parametric_copy( + &mut self, + master: Handle, + states: &BTreeMap, + listed: &BTreeSet, + ) -> Result { + let document = &self.document; + let master_dictionary = document + .extension_dictionary_handle(master) + .ok_or(UNSUPPORTED)?; + let objects = owned_tree(document, master_dictionary)?; + let records: FxHashMap = objects + .iter() + .filter(|handle| { + matches!( + document.objects.get(handle), + Some(ObjectType::Unknown { .. }) + ) + }) + .map(|handle| Some((*handle, read_record(document, *handle)?))) + .collect::>() + .ok_or(UNSUPPORTED)?; + let tag = block_tag(document, master); + let master_record = document + .block_records + .iter() + .find(|record| record.handle == master) + .ok_or(UNSUPPORTED)?; + let master_name = master_record.name.clone(); + let master_members = crate::scene::block_authoring::members(document, master); + let entities: Vec = master_members + .iter() + .map(|handle| document.get_entity(*handle).cloned()) + .collect::>() + .ok_or(UNSUPPORTED)?; + let layers: Vec = entities + .iter() + .map(|entity| entity.common().layer.clone()) + .collect(); + let base = crate::scene::render_graph::block_base_point(document, &master_name); + let name = next_anonymous_name(document); + + self.define_block_raw_unbumped(&name, base, entities); + let record = self + .document + .block_records + .get_mut(&name) + .ok_or(UNSUPPORTED)?; + record.flags.anonymous = true; + let copy = record.handle; + let copy_members = crate::scene::block_authoring::members(&self.document, copy); + if copy_members.len() != master_members.len() { + return Err(UNSUPPORTED); + } + self.own_copied_xdicts(master_members.clone(), copy_members.clone()); + + let document = &mut self.document; + // A block BricsCAD never copied has no tag yet; BricsCAD gives it one + // when it makes the first copy. + let tag = match tag { + Some(tag) => tag, + None => give_block_tag(document, master), + }; + let copy_dictionary = document.ensure_extension_dictionary(copy); + let mut cloned: FxHashMap = FxHashMap::default(); + for &handle in &objects { + let new = if handle == master_dictionary { + copy_dictionary + } else { + document.allocate_handle() + }; + cloned.insert(handle, new); + } + let members: FxHashMap = master_members + .iter() + .copied() + .zip(copy_members.iter().copied()) + .collect(); + let remap = |handle: Handle| { + if handle == master { + copy + } else { + cloned + .get(&handle) + .or_else(|| members.get(&handle)) + .copied() + .unwrap_or(handle) + } + }; + let mut clones = Vec::with_capacity(objects.len()); + for &handle in &objects { + let new = remap(handle); + let clone = match document.objects.get(&handle).ok_or(UNSUPPORTED)? { + ObjectType::Dictionary(dictionary) => { + let mut dictionary = dictionary.clone(); + dictionary.handle = new; + dictionary.owner = remap(dictionary.owner); + for (_, entry) in &mut dictionary.entries { + *entry = remap(*entry); + } + for reactor in &mut dictionary.reactors { + *reactor = remap(*reactor); + } + dictionary.xdictionary_handle = dictionary.xdictionary_handle.map(remap); + ObjectType::Dictionary(dictionary) + } + ObjectType::Associative(object) => { + let mut object = object.clone(); + remap_associative(&mut object, &remap)?; + ObjectType::Associative(object) + } + // The block's draw order, member by member. + ObjectType::SortEntitiesTable(table) => { + let mut order = document::objects::SortEntitiesTable::for_block(copy); + order.handle = new; + order.owner_handle = remap(table.owner_handle); + for entry in table.entries() { + order.add_entry(remap(entry.entity_handle), remap(entry.sort_handle)); + } + ObjectType::SortEntitiesTable(order) + } + ObjectType::Unknown { type_name, .. } => { + let mut record = records[&handle].clone(); + record.handle = new; + record.refs_mut(|reference| reference.handle = remap(reference.handle)); + unknown(type_name, &record) + } + _ => return Err(UNSUPPORTED), + }; + clones.push((new, clone)); + } + for (handle, object) in clones { + document.objects.insert(handle, object); + } + // The copies' reactors name the clones of the master members' + // parameter objects; anything else they named stays with the master. + for (original, copy_member) in master_members.iter().zip(©_members) { + let reactors: Vec = document + .get_entity(*original) + .map(|entity| { + entity + .common() + .reactors + .iter() + .filter_map(|reactor| cloned.get(reactor).copied()) + .collect() + }) + .unwrap_or_default(); + if let Some(entity) = document.get_entity_mut(*copy_member) { + entity.common_mut().reactors = reactors; + } + } + + // The copy names the block it was made from, member by member. + let manager = database_entry(document, copy, "PERSIDMANAGER").ok_or(UNSUPPORTED)?; + let mut record = read_record(document, manager).ok_or(UNSUPPORTED)?; + let properties = record.body.properties_mut(); + properties + .0 + .retain(|(name, _)| !name.starts_with("original.")); + properties.0.push(( + "original.block".into(), + Value::Object { + kind: 1, + target: Ref::new(master, 5), + }, + )); + properties.0.push(( + "original.map".into(), + Value::Map { + key: 7, + value: 8, + entries: master_members + .iter() + .zip(©_members) + .map(|(original, member)| { + ( + Value::Raw(handle_bytes(*original)), + Value::Object { + kind: 0, + target: Ref::new(*member, 4), + }, + ) + }) + .collect(), + }, + )); + properties.0.push(("original.tag".into(), Value::Text(tag))); + store(document, &record); + + let layers: FxHashMap = copy_members.iter().copied().zip(layers).collect(); + apply_states(document, copy, ©_members, &layers, states, listed)?; + Ok(copy) + } +} + +/// Every object owned, directly or further down, by `root`, root first. +fn owned_tree(document: &Document, root: Handle) -> Result> { + let mut children: FxHashMap> = FxHashMap::default(); + for &handle in document.objects.keys() { + if let Some(owner) = document.object_owner(handle) { + children.entry(owner).or_default().push(handle); + } + } + let mut seen = FxHashSet::default(); + let mut order = Vec::new(); + let mut stack = vec![root]; + while let Some(handle) = stack.pop() { + if handle.is_null() || !seen.insert(handle) { + continue; + } + match document.objects.get(&handle) { + Some( + ObjectType::Dictionary(_) + | ObjectType::Unknown { .. } + | ObjectType::SortEntitiesTable(_), + ) => {} + Some(ObjectType::Associative(AssociativeObject { + data: + AssociativeData::Network(_) + | AssociativeData::Variable(_) + | AssociativeData::ValueDependency(_), + .. + })) => {} + _ => return Err(UNSUPPORTED), + } + order.push(handle); + if let Some(owned) = children.get(&handle) { + let mut owned = owned.clone(); + owned.sort_unstable_by_key(|handle| std::cmp::Reverse(*handle)); + stack.extend(owned); + } + } + Ok(order) +} + +/// Point every handle of an associative network, variable or value dependency +/// through `remap`. +fn remap_associative( + object: &mut AssociativeObject, + remap: &impl Fn(Handle) -> Handle, +) -> Result<()> { + object.handle = remap(object.handle); + object.owner = remap(object.owner); + for reactor in &mut object.reactors { + *reactor = remap(*reactor); + } + object.xdictionary_handle = object.xdictionary_handle.map(remap); + let action = |action: &mut AssocAction| { + action.owning_network = remap(action.owning_network); + action.action_body = remap(action.action_body); + for dependency in &mut action.dependencies { + dependency.dependency = remap(dependency.dependency); + } + for parameter in &mut action.owned_parameters { + *parameter = remap(*parameter); + } + for value in &mut action.values { + value.controlled_object_dependency = remap(value.controlled_object_dependency); + for variable in &mut value.variables { + variable.handle = remap(variable.handle); + if let AssocEvalValue::Handle(handle) = &mut variable.value.value { + *handle = remap(*handle); + } + } + } + }; + let dependency = |dependency: &mut AssocDependency| { + dependency.dependent_on = remap(dependency.dependent_on); + dependency.read_dependency = remap(dependency.read_dependency); + dependency.node = remap(dependency.node); + dependency.dependency_body = remap(dependency.dependency_body); + }; + match &mut object.data { + AssociativeData::Network(network) => { + action(&mut network.action); + for child in &mut network.actions { + child.dependency = remap(child.dependency); + } + for owned in &mut network.owned_actions { + *owned = remap(*owned); + } + } + AssociativeData::Variable(variable) => { + action(&mut variable.action); + for owned in &mut variable.dependencies { + owned.dependency = remap(owned.dependency); + } + if let AssocEvalValue::Handle(handle) = &mut variable.value.value { + *handle = remap(*handle); + } + } + AssociativeData::ValueDependency(value) => { + dependency(&mut value.dependency); + if let AssocEvalValue::Handle(handle) = &mut value.value.value { + *handle = remap(*handle); + } + } + _ => return Err(UNSUPPORTED), + } + Ok(()) +} + +/// Set the copy's parameter objects, associative variables and member layers +/// to `states`, as BricsCAD leaves a copy it made: for each visibility +/// parameter the state, the values of its table's columns and, for a +/// parameter in `listed`, the marks BricsCAD sets on an instance's own +/// parameter; for each suppression its value, status and the layers of the +/// members it moved to `*SUPPRESS`. +fn apply_states( + document: &mut Document, + copy: Handle, + members: &[Handle], + layers: &FxHashMap, + states: &BTreeMap, + listed: &BTreeSet, +) -> Result<()> { + let features = features(document, copy); + let mut columns: FxHashMap = FxHashMap::default(); + let mut suppressions = Vec::new(); + for &feature in &features { + let mut record = read_record(document, feature).ok_or(UNSUPPORTED)?; + let properties = record.body.properties(); + match properties.text("Feature_type") { + Some("BdmConfigurationFeature") + if properties.text("TableType") == Some("VisibilityStates") => {} + Some("BdmSuppressFeature") => { + suppressions.push(feature); + continue; + } + _ => continue, + } + let table = super::properties( + document, + properties + .get("ConfigTable") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?, + ) + .ok_or(UNSUPPORTED)?; + let name = table + .text("KeyName") + .or_else(|| properties.text("Name")) + .ok_or(UNSUPPORTED)? + .to_string(); + let state = states.get(&name).ok_or(UNSUPPORTED)?; + let texts = |key: &str| -> Option> { + table.get(key)?.items()?.iter().map(Value::text).collect() + }; + let keys = texts("KeyValues").ok_or(UNSUPPORTED)?; + let column_names = texts("ColNames").ok_or(UNSUPPORTED)?; + let values: Vec = table + .get("DblValues") + .and_then(Value::items) + .and_then(|items| { + items + .iter() + .map(|item| match item { + Value::Real(value) => Some(*value), + _ => None, + }) + .collect() + }) + .ok_or(UNSUPPORTED)?; + let row = keys + .iter() + .position(|key| key == state) + .ok_or(NO_SUCH_STATE)?; + let own = listed.contains(&name); + let reactors: Vec = properties + .get("Reactors") + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default(); + record + .body + .properties_mut() + .set("LastKeyValue", Value::Text(state.clone())); + store(document, &record); + + for reactor in reactors { + let mut variable_reactor = read_record(document, reactor).ok_or(UNSUPPORTED)?; + let properties = variable_reactor.body.properties_mut(); + let variable = properties + .get("VarId") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?; + if properties.get("IsKeyVar") == Some(&Value::Flag(true)) { + properties.set("String", Value::Text(state.clone())); + properties.set("IsEnabled", Value::Flag(!own)); + if own { + properties.set("Value", Value::Real(row as f64)); + set_variable( + document, + variable, + Some(row.to_string()), + AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(row as i32), + }, + )?; + } + } else { + let column_name = properties.text("VarName").ok_or(UNSUPPORTED)?.to_string(); + let column = column_names + .iter() + .position(|name| *name == column_name) + .ok_or(UNSUPPORTED)?; + let value = *values + .get(row * column_names.len() + column) + .ok_or(UNSUPPORTED)?; + properties.set("Value", Value::Real(value)); + set_variable( + document, + variable, + None, + AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(value), + }, + )?; + columns.insert(column_name, value); + } + store(document, &variable_reactor); + } + } + + let order: FxHashMap = + members.iter().enumerate().map(|(k, h)| (*h, k)).collect(); + let mut suppressed: FxHashSet = FxHashSet::default(); + let layer_handle = + |document: &Document, name: &str| document.layers.get(name).map(|layer| layer.handle); + for feature in suppressions { + let mut record = read_record(document, feature).ok_or(UNSUPPORTED)?; + let reactors: Vec = record + .body + .properties() + .get("Reactors") + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default(); + let mut entities = Vec::new(); + let mut value = None; + for reactor in reactors { + let mut reactor_record = read_record(document, reactor).ok_or(UNSUPPORTED)?; + let properties = reactor_record.body.properties(); + if let Some(dependencies) = properties.get("pers_ids").and_then(Value::items) { + for dependency in dependencies.iter().filter_map(Value::object) { + match read_record(document, dependency).map(|record| record.body) { + Some(Body::Dependency { entity, .. }) => entities.push(entity.handle), + _ => return Err(UNSUPPORTED), + } + } + } else if let Some(variable) = properties.get("var").and_then(Value::object) { + let expression = match document.objects.get(&variable) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => variable.expression.clone(), + _ => return Err(UNSUPPORTED), + }; + let suppress = evaluate(&expression, &columns).ok_or(UNSUPPORTED)?; + reactor_record + .body + .properties_mut() + .set("value", Value::Real(suppress)); + store(document, &reactor_record); + set_variable( + document, + variable, + None, + AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(suppress as i32), + }, + )?; + value = Some(suppress); + } + } + let suppress = value.ok_or(UNSUPPORTED)? != 0.0; + entities.sort_by_key(|entity| order.get(entity).copied().unwrap_or(usize::MAX)); + let properties = record.body.properties_mut(); + properties.set("Status", Value::Integer(if suppress { 32 } else { 0 })); + let Some(Value::Map { entries, .. }) = properties.get_mut("aEntLayerKey") else { + return Err(UNSUPPORTED); + }; + entries.clear(); + if suppress { + for entity in &entities { + let layer = layers.get(entity).ok_or(UNSUPPORTED)?; + let layer = layer_handle(document, layer).ok_or(UNSUPPORTED)?; + entries.push(( + Value::Object { + kind: 0, + target: Ref::new(*entity, 4), + }, + Value::Object { + kind: 1, + target: Ref::new(layer, 5), + }, + )); + } + suppressed.extend(entities); + } + store(document, &record); + } + + if !suppressed.is_empty() { + ensure_suppress_layer(document); + } + for member in members { + let layer = if suppressed.contains(member) { + SUPPRESS_LAYER.to_string() + } else { + layers.get(member).cloned().ok_or(UNSUPPORTED)? + }; + if document + .get_entity(*member) + .is_some_and(|entity| entity.common().layer != layer) + { + if let Some(entity) = document.get_entity_mut(*member) { + entity.common_mut().layer = layer; + } + } + } + Ok(()) +} + +/// The value of a suppression's expression, such as `1 - look_3` or +/// `1 - look_13 * look_14`, over the table columns. +fn evaluate(expression: &str, columns: &FxHashMap) -> Option { + const RESULT: &str = "bricscad_suppression"; + let mut table = crate::scene::named_parameters::ParameterTable::new(); + for (name, value) in columns { + table.set(name, &value.to_string()).ok()?; + } + table.set(RESULT, expression).ok()?; + table.resolve(RESULT).ok().filter(|value| value.is_finite()) +} + +/// Set an associative variable and every read of it: BricsCAD keeps each +/// value dependency at the value of the variable it reads, and takes a +/// variable whose new value its reads already hold for unchanged, leaving +/// what depends on it unevaluated. +fn set_variable( + document: &mut Document, + variable: Handle, + expression: Option, + value: AssocEvalVariant, +) -> Result<()> { + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(object), + reactors, + .. + })) = document.objects.get_mut(&variable) + else { + return Err(UNSUPPORTED); + }; + if let Some(expression) = expression { + object.expression = expression; + } + object.value = value.clone(); + for reactor in reactors.clone() { + if let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(read), + .. + })) = document.objects.get_mut(&reactor) + { + if read.dependency.dependent_on == variable { + read.value = value.clone(); + } + } + } + Ok(()) +} + +/// The layer BricsCAD keeps hidden members on: frozen and off. +fn ensure_suppress_layer(document: &mut Document) { + if document.layers.get(SUPPRESS_LAYER).is_some() { + return; + } + let mut layer = document::tables::Layer::new(SUPPRESS_LAYER); + layer.flags.frozen = true; + layer.flags.off = true; + layer.handle = document.allocate_handle(); + let _ = document.layers.add(layer); +} + +/// A copy of `master`, other than the block itself, that shows `states`. +fn find_copy(document: &Document, master: Handle, states: &[String]) -> Option { + document + .block_records + .iter() + .filter(|record| record.is_anonymous() && record.handle != master) + .filter(|record| original_block(document, record.handle) == Some(master)) + .find(|record| { + let parameters = visibility_parameters(document, record.handle); + parameters.len() == states.len() + && parameters.iter().zip(states).all(|(parameter, state)| { + parameter + .current + .and_then(|current| parameter.states.get(current)) + == Some(state) + }) + }) + .map(|record| record.handle) +} + +/// After the reference `insert` was pointed at `block`, an attribute whose +/// definition there is on `*SUPPRESS` goes there too, and one on `*SUPPRESS` +/// whose definition is not goes back to the definition's layer, as BricsCAD +/// keeps them. +fn follow_attribute_definitions(document: &mut Document, insert: Handle, block: Handle) { + let definitions: FxHashMap = + crate::scene::block_authoring::members(document, block) + .into_iter() + .filter_map(|member| match document.get_entity(member) { + Some(EntityType::AttributeDefinition(definition)) => Some(( + definition.tag.to_uppercase(), + definition.common.layer.clone(), + )), + _ => None, + }) + .collect(); + let needs = match document.get_entity(insert) { + Some(EntityType::Insert(reference)) => reference.attributes.iter().any(|attribute| { + target_layer(&definitions, &attribute.tag, &attribute.common.layer).is_some() + }), + _ => false, + }; + if !needs { + return; + } + if let Some(EntityType::Insert(reference)) = document.get_entity_mut(insert) { + for attribute in &mut reference.attributes { + if let Some(layer) = target_layer(&definitions, &attribute.tag, &attribute.common.layer) + { + attribute.common.layer = layer; + attribute.common.raw_record = None; + } + } + } +} + +fn target_layer(definitions: &FxHashMap, tag: &str, layer: &str) -> Option { + let definition = definitions.get(&tag.to_uppercase())?; + if definition == SUPPRESS_LAYER && layer != SUPPRESS_LAYER { + Some(SUPPRESS_LAYER.to_string()) + } else if definition != SUPPRESS_LAYER && layer == SUPPRESS_LAYER { + Some(definition.clone()) + } else { + None + } +} + +/// The reference's entry in model space: the `BmAssemblyParameters` feature +/// its `BDMOBJECT` leads to, with its record. +pub(super) fn find_entry(document: &Document, insert: Handle) -> Option<(Handle, Record)> { + let reactors = document.get_entity(insert)?.common().reactors.clone(); + reactors.into_iter().find_map(|reactor| { + let Body::Object { properties, .. } = read_record(document, reactor)?.body else { + return None; + }; + properties + .get("PersIdDependencies")? + .items()? + .iter() + .filter_map(Value::object) + .find_map(|dependency| { + read_record(document, dependency)? + .reactors + .iter() + .find_map(|reactor| { + let feature = read_record(document, reactor.handle)?.owner.handle; + let record = read_record(document, feature)?; + (record.body.properties().text("Feature_type") + == Some("BmAssemblyParameters")) + .then_some((feature, record)) + }) + }) + }) +} + +/// Write the reference's entry with `overrides`, creating it when there is +/// none. +fn write_entry( + document: &mut Document, + insert: Handle, + master: Handle, + overrides: Vec<(String, String)>, +) -> Result<()> { + let constants = |entries: Vec<(String, String)>| Value::Map { + key: 2, + value: 2, + entries: entries + .into_iter() + .map(|(name, state)| (Value::Text(name), Value::Text(state))) + .collect(), + }; + if let Some((_, mut record)) = find_entry(document, insert) { + if !record + .body + .properties_mut() + .set("expr.const", constants(overrides)) + { + return Err(UNSUPPORTED); + } + store(document, &record); + return Ok(()); + } + + let template = |class: &str| template_record(document, master, class).ok_or(UNSUPPORTED); + let feature_template = template("BDMDBFEATUREDATA")?; + let reactor_template = template("BDMDBPERSIDREACTOR")?; + let dependency_template = template("BDMDBOBJECTDEPENDENCY")?; + let object_template = template("BDMOBJECT")?; + let (feature_manager, dependency_manager, constraint_manager) = + model_database(document, master)?; + + let names: Vec = features(document, document.header.model_space_block_handle) + .into_iter() + .filter_map(|feature| { + super::properties(document, feature)? + .text("Name") + .map(str::to_string) + }) + .collect(); + let base = format!("*{:X}", insert.value()); + let name = std::iter::once(base.clone()) + .chain((1..).map(|n| format!("{base}_{n}"))) + .find(|name| !names.contains(name)) + .unwrap_or(base); + let mut constraint_record = read_record(document, constraint_manager).ok_or(UNSUPPORTED)?; + let object_number = match &constraint_record.body { + Body::ConstraintManager { + counts, children, .. + } => { + children + .iter() + .take(usize::try_from(counts[1]).unwrap_or(0)) + .filter_map(|child| match read_record(document, child.handle)?.body { + Body::Object { properties, .. } => properties + .text("NAME")? + .strip_prefix("Objekt_")? + .parse::() + .ok(), + _ => None, + }) + .max() + .unwrap_or(0) + + 1 + } + _ => return Err(UNSUPPORTED), + }; + + let [feature, reactor, dependency, object] = [(); 4].map(|_| document.allocate_handle()); + let object_lead = match &object_template.body { + Body::Object { + lead, + lead_count, + tail, + .. + } => (*lead, *lead_count, *tail), + _ => return Err(UNSUPPORTED), + }; + let new_records = [ + Record::like( + &feature_template, + feature, + Ref::new(feature_manager, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ( + "Feature_type".into(), + Value::Text("BmAssemblyParameters".into()), + ), + ("Name".into(), Value::Text(name)), + ( + "Reactors".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 3, + target: Ref::new(reactor, 3), + }], + }, + ), + ("Status".into(), Value::Integer(0)), + ("expr.const".into(), constants(overrides)), + ("expr.orig".into(), constants(Vec::new())), + ( + "modifiedParams".into(), + Value::List { + element: 2, + items: Vec::new(), + }, + ), + ])), + ), + Record::like( + &reactor_template, + reactor, + Ref::new(feature, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ("mask".into(), Value::Integer(1)), + ( + "pers_ids".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 0, + target: Ref::new(dependency, 4), + }], + }, + ), + ("tag".into(), Value::Integer(0)), + ])), + ), + { + let mut record = Record::like( + &dependency_template, + dependency, + Ref::new(dependency_manager, 4), + Body::Dependency { + properties: Properties::default(), + tail: 0, + entity: Ref::new(insert, 5), + }, + ); + record.reactors = vec![Ref::new(reactor, 4)]; + record + }, + Record::like( + &object_template, + object, + Ref::new(constraint_manager, 4), + Body::Object { + lead: object_lead.0, + lead_count: object_lead.1, + entity: Ref::new(insert, 4), + properties: Properties(vec![ + ( + "NAME".into(), + Value::Text(format!("Objekt_{object_number}")), + ), + ( + "PersIdDependencies".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 0, + target: Ref::new(dependency, 4), + }], + }, + ), + ]), + tail: object_lead.2, + }, + ), + ]; + let classes = [ + "BDMDBFEATUREDATA", + "BDMDBPERSIDREACTOR", + "BDMDBOBJECTDEPENDENCY", + "BDMOBJECT", + ]; + for (class, record) in classes.iter().zip(&new_records) { + document + .objects + .insert(record.handle, unknown(class, record)); + } + + append_object(document, feature_manager, "Features", feature)?; + append_object(document, dependency_manager, "deps", dependency)?; + let Body::ConstraintManager { + counts, children, .. + } = &mut constraint_record.body + else { + return Err(UNSUPPORTED); + }; + let at = usize::try_from(counts[1]).map_err(|_| UNSUPPORTED)?; + children.insert(at.min(children.len()), Ref::new(object, 3)); + counts[1] += 1; + store(document, &constraint_record); + if let Some(entity) = document.get_entity_mut(insert) { + entity.common_mut().reactors.push(object); + } + Ok(()) +} + +/// Append a reference to `target` to the list property `list` of `manager`. +fn append_object( + document: &mut Document, + manager: Handle, + list: &str, + target: Handle, +) -> Result<()> { + let mut record = read_record(document, manager).ok_or(UNSUPPORTED)?; + let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut(list) else { + return Err(UNSUPPORTED); + }; + items.push(Value::Object { + kind: 3, + target: Ref::new(target, 3), + }); + store(document, &record); + Ok(()) +} + +/// Model space's feature manager, dependency manager and constraint manager, +/// created after those of `master` when model space has none yet. +fn model_database(document: &mut Document, master: Handle) -> Result<(Handle, Handle, Handle)> { + let model = document.header.model_space_block_handle; + let entries = |document: &Document, owner: Handle| { + Some(( + database_entry(document, owner, "FEATURE_MANAGER")?, + database_entry(document, owner, "PERSIDMANAGER")?, + database_entry(document, owner, "BDM_DATABASE")?, + )) + }; + if let Some(found) = entries(document, model) { + return Ok(found); + } + let model_dictionary = document.ensure_extension_dictionary(model); + let has_database = matches!( + document.objects.get(&model_dictionary), + Some(ObjectType::Dictionary(dictionary)) if dictionary.get("BDM_DATABASE").is_some() + ); + if has_database { + // A database without all three managers is not one this writes into. + return Err(UNSUPPORTED); + } + let master_dictionary = document + .extension_dictionary_handle(master) + .ok_or(UNSUPPORTED)?; + let (master_database, hard_owned) = match document.objects.get(&master_dictionary) { + Some(ObjectType::Dictionary(dictionary)) => ( + dictionary.get("BDM_DATABASE").ok_or(UNSUPPORTED)?, + dictionary + .hard_owner_entries + .iter() + .any(|key| key.eq_ignore_ascii_case("BDM_DATABASE")), + ), + _ => return Err(UNSUPPORTED), + }; + let Some(ObjectType::Dictionary(template)) = document.objects.get(&master_database).cloned() + else { + return Err(UNSUPPORTED); + }; + let (feature_template, dependency_template, constraint_template) = + entries(document, master).ok_or(UNSUPPORTED)?; + let database = document.allocate_handle(); + let mut created = Vec::new(); + let mut handles = FxHashMap::default(); + for (key, template_handle) in [ + ("FEATURE_MANAGER", feature_template), + ("PERSIDMANAGER", dependency_template), + ("BDM_DATABASE", constraint_template), + ] { + let mut record = read_record(document, template_handle).ok_or(UNSUPPORTED)?; + let handle = document.allocate_handle(); + record.handle = handle; + record.owner.handle = database; + for reactor in &mut record.reactors { + reactor.handle = database; + } + match &mut record.body { + Body::Properties(properties) => { + properties + .0 + .retain(|(name, _)| !name.starts_with("original.")); + for list in ["Features", "Contexts", "deps"] { + if let Some(Value::List { items, .. }) = properties.get_mut(list) { + items.clear(); + } + } + } + Body::ConstraintManager { + counts, children, .. + } => { + counts[1] = 0; + counts[3] = 0; + children.clear(); + } + _ => return Err(UNSUPPORTED), + } + let class = match key { + "FEATURE_MANAGER" => "BDMDBFEATUREMANAGER", + "PERSIDMANAGER" => "BdmDbPersIdManager", + _ => "BDMDBCONSTRAINTMANAGER", + }; + created.push((handle, unknown(class, &record))); + handles.insert(key, handle); + } + let mut dictionary = template; + dictionary.handle = database; + dictionary.owner = model_dictionary; + dictionary.reactors = vec![model_dictionary]; + dictionary.xdictionary_handle = None; + for (key, entry) in &mut dictionary.entries { + *entry = *handles.get(key.as_str()).ok_or(UNSUPPORTED)?; + } + document + .objects + .insert(database, ObjectType::Dictionary(dictionary)); + for (handle, object) in created { + document.objects.insert(handle, object); + } + if let Some(ObjectType::Dictionary(dictionary)) = document.objects.get_mut(&model_dictionary) { + dictionary.add_entry("BDM_DATABASE", database); + if hard_owned { + dictionary.hard_owner_entries.push("BDM_DATABASE".into()); + } + } + entries(document, model).ok_or(UNSUPPORTED) +} + +/// A record of `class` to make new ones like: one under `master`'s extension +/// dictionary, or any in the drawing. +fn template_record(document: &Document, master: Handle, class: &str) -> Option { + let tree: FxHashSet = document + .extension_dictionary_handle(master) + .and_then(|root| owned_tree(document, root).ok()) + .map(|tree| tree.into_iter().collect()) + .unwrap_or_default(); + let mut candidates: Vec = document + .objects + .iter() + .filter_map(|(handle, object)| match object { + ObjectType::Unknown { type_name, .. } if type_name == class => Some(*handle), + _ => None, + }) + .collect(); + candidates.sort_by_key(|handle| (!tree.contains(handle), *handle)); + candidates + .into_iter() + .find_map(|handle| read_record(document, handle)) +} + +/// The tag BricsCAD gives a parametric block, kept in its extended data and +/// named by every copy (`original.tag`). +fn block_tag(document: &Document, block: Handle) -> Option { + const NAME: &[u8] = b"ParametricBlockGUID"; + document + .object_xdata(block)? + .records() + .iter() + .filter(|record| record.application_name == "BDM_DB") + .flat_map(|record| &record.values) + .find_map(|value| { + let document::xdata::XDataValue::BinaryData(bytes) = value else { + return None; + }; + let at = bytes + .windows(NAME.len()) + .position(|window| window == NAME)? + + NAME.len(); + // A type byte (2: text), the length and the characters. + if *bytes.get(at)? != 2 { + return None; + } + let length = usize::from(u16::from_le_bytes([ + *bytes.get(at + 1)?, + *bytes.get(at + 2)?, + ])); + let text = bytes.get(at + 3..at + 3 + length)?; + String::from_utf8(text.to_vec()).ok() + }) +} + +/// Give `block` a new tag the way BricsCAD stores it, and return it. +fn give_block_tag(document: &mut Document, block: Handle) -> String { + const NAME: &[u8] = b"ParametricBlockGUID"; + let tag = crate::scene::block_authoring::new_guid().to_lowercase(); + let mut bytes = vec![1, 0, 0, 0]; + bytes.extend((NAME.len() as u16).to_le_bytes()); + bytes.extend(NAME); + bytes.push(2); + bytes.extend((tag.len() as u16).to_le_bytes()); + bytes.extend(tag.as_bytes()); + crate::scene::block_authoring::ensure_app_id(document, "BDM_DB"); + let mut record = document::xdata::ExtendedDataRecord::new("BDM_DB"); + record.add_value(document::xdata::XDataValue::BinaryData(bytes)); + document.set_object_xdata_record(block, record); + tag +} + +/// The handle as BricsCAD stores it in a raw value: its bytes, most +/// significant first, without leading zeros. +fn handle_bytes(handle: Handle) -> Vec { + handle + .value() + .to_be_bytes() + .into_iter() + .skip_while(|byte| *byte == 0) + .collect() +} + +/// The next free name of the form `*U`. +fn next_anonymous_name(document: &Document) -> String { + let next = document + .block_records + .iter() + .filter_map(|record| record.name.strip_prefix("*U")?.parse::().ok()) + .max() + .map_or(1, |n| n + 1); + format!("*U{next}") +} + +/// The raw object for `record`. +fn unknown(class: &str, record: &Record) -> ObjectType { + let (data, handle_bits) = record::encode(record); + ObjectType::Unknown { + type_name: class.to_string(), + handle: record.handle, + owner: record.owner.handle, + raw_dxf_codes: None, + raw_dwg_data: Some(data), + raw_dwg_handle_bits: handle_bits, + raw_dwg_version: Some(record.version), + } +} + +/// Store a changed record over the object it was read from. +fn store(document: &mut Document, record: &Record) { + let class = match document.objects.get(&record.handle) { + Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(), + _ => return, + }; + document + .objects + .insert(record.handle, unknown(&class, record)); +} diff --git a/src/scene/bricscad_parameters/switch_tests.rs b/src/scene/bricscad_parameters/switch_tests.rs new file mode 100644 index 0000000000..660ea5796d --- /dev/null +++ b/src/scene/bricscad_parameters/switch_tests.rs @@ -0,0 +1,507 @@ +//! Switching on the BricsCAD drawing in `tests/fixtures/bricscad` (see its +//! README): EE shows the block in On/Shown, 146 the copy *U2 in Off/Shown and +//! 19E the copy *U3 in Off/Hidden; 146 and 19E have entries in model space. + +use super::record::{Body, Value}; +use super::*; +use crate::scene::Scene; +use std::collections::{BTreeMap, BTreeSet}; + +const MASTER: &str = "ocs-bricscad-visibility-block"; + +fn opened() -> Scene { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + let mut scene = Scene::new(); + scene.document = + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture"); + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); + scene +} + +fn reference(value: u64) -> Handle { + Handle::from(value) +} + +fn block_of(document: &Document, insert: u64) -> String { + match document.get_entity(reference(insert)) { + Some(EntityType::Insert(insert)) => insert.block_name.clone(), + other => panic!("{other:?}"), + } +} + +/// Each parameter and the state the reference shows. +fn shown(document: &Document, insert: u64) -> Vec<(String, String)> { + reference_parameters(document, reference(insert)) + .into_iter() + .map(|parameter| { + let state = parameter.states[parameter.current.unwrap()].clone(); + (parameter.name, state) + }) + .collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect() +} + +/// The parameters the reference's entry in model space lists. +fn entry(document: &Document, insert: u64) -> Option> { + let (_, record) = super::switch::find_entry(document, reference(insert))?; + Some( + record + .body + .properties() + .get("expr.const")? + .entries()? + .iter() + .map(|(key, value)| { + ( + key.text().unwrap().to_string(), + value.text().unwrap().to_string(), + ) + }) + .collect(), + ) +} + +/// The references in the BricsCAD objects of `document` that name an object +/// the drawing does not have, as (holder, target). +fn dangling_references(document: &Document) -> BTreeSet<(Handle, Handle)> { + let mut dangling = BTreeSet::new(); + for (handle, object) in &document.objects { + if !matches!(object, ObjectType::Unknown { type_name, .. } if type_name.to_ascii_uppercase().starts_with("BDM")) + { + continue; + } + let mut record = record(document, *handle).expect("a BricsCAD object decodes"); + record.refs_mut(|reference| { + let target = reference.handle; + let known = target.is_null() + || document.objects.contains_key(&target) + || document.get_entity(target).is_some() + || document.block_records.iter().any(|r| r.handle == target) + || document.layers.iter().any(|layer| layer.handle == target); + if !known { + dangling.insert((*handle, target)); + } + }); + } + dangling +} + +/// No reference in the BricsCAD objects names an object the drawing lacks, +/// apart from those BricsCAD itself left in the fixture: its global constraint +/// manager still lists child managers it purged. +fn assert_no_dangling_references(document: &Document) { + let left_by_bricscad = dangling_references(&opened().document); + let dangling = dangling_references(document); + let new: Vec<_> = dangling.difference(&left_by_bricscad).collect(); + assert!( + new.is_empty(), + "references to objects the drawing lacks: {new:?}" + ); +} + +#[test] +fn a_state_another_copy_shows_shares_that_copy_and_gives_the_reference_an_entry() { + let mut scene = opened(); + assert_eq!(entry(&scene.document, 0xEE), None); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LAMP", "Off") + .unwrap()); + let document = &scene.document; + assert_eq!( + block_of(document, 0xEE), + "*U2", + "BricsCAD shares copies too" + ); + assert_eq!( + shown(document, 0xEE), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_eq!(entry(document, 0xEE), Some(pairs(&[("LAMP", "Off")]))); + assert_eq!( + shown(document, 0x146), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_no_dangling_references(document); +} + +#[test] +fn the_block_s_own_states_show_the_block_and_the_entry_keeps_the_parameter() { + let mut scene = opened(); + assert!(scene + .set_bricscad_visibility(reference(0x146), "LAMP", "On") + .unwrap()); + let document = &scene.document; + assert_eq!(block_of(document, 0x146), MASTER); + assert_eq!( + shown(document, 0x146), + pairs(&[("LAMP", "On"), ("LABEL", "Shown")]) + ); + // BricsCAD keeps a parameter in the entry once set, also in the block's + // own state. + assert_eq!(entry(document, 0x146), Some(pairs(&[("LAMP", "On")]))); +} + +#[test] +fn a_state_no_block_shows_gets_a_new_copy() { + let mut scene = opened(); + let records = scene.document.block_records.iter().count(); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden") + .unwrap()); + let document = &scene.document; + assert_eq!(document.block_records.iter().count(), records + 1); + let copy = block_of(document, 0xEE); + assert_eq!(copy, "*U4"); + let copy = document.block_records.get(©).unwrap().handle; + let master = document.block_records.get(MASTER).unwrap().handle; + assert_eq!(original_block(document, copy), Some(master)); + assert_eq!( + shown(document, 0xEE), + pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]) + ); + assert_eq!(entry(document, 0xEE), Some(pairs(&[("LABEL", "Hidden")]))); + let layers: Vec = crate::scene::block_authoring::members(document, copy) + .into_iter() + .map(|member| document.get_entity(member).unwrap().common().layer.clone()) + .collect(); + assert_eq!( + layers, + ["0", "0", "0", "0", "*SUPPRESS"], + "only the text is hidden" + ); + // The block and the other references are left alone. + assert_eq!( + shown(document, 0x146), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_eq!( + visibility_parameters(document, master) + .iter() + .map(|p| p.current) + .collect::>(), + [Some(0), Some(0)] + ); + assert_no_dangling_references(document); +} + +/// A property value with references written as the kind, code and class of +/// what they name, and members as their place in the block. +fn normalized(document: &Document, members: &[Handle], value: &Value) -> String { + match value { + Value::Object { kind, target } => { + let what = members + .iter() + .position(|member| *member == target.handle) + .map(|index| format!("member {index}")) + .or_else(|| { + document + .objects + .get(&target.handle) + .map(|object| match object { + ObjectType::Unknown { type_name, .. } => type_name.clone(), + ObjectType::Associative(object) => object.dxf_name.clone(), + other => format!("{:?}", std::mem::discriminant(other)), + }) + }) + .or_else(|| { + document + .layers + .iter() + .find(|layer| layer.handle == target.handle) + .map(|layer| format!("layer {}", layer.name)) + }) + .or_else(|| { + document + .block_records + .iter() + .find(|record| record.handle == target.handle) + .map(|record| format!("block {}", record.name)) + }) + .unwrap_or_else(|| format!("{:?}", target.handle)); + format!("ref({kind},{},{what})", target.code) + } + Value::List { element, items } => format!( + "list {element} [{}]", + items + .iter() + .map(|item| normalized(document, members, item)) + .collect::>() + .join(", ") + ), + Value::Map { + key, + value, + entries, + } => format!( + "map {key} {value} [{}]", + entries + .iter() + .map(|(k, v)| format!( + "{} => {}", + normalized(document, members, k), + normalized(document, members, v) + )) + .collect::>() + .join(", ") + ), + Value::Raw(bytes) => { + // A raw handle of a member of the block the copy was made from. + let handle = Handle::from(bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b))); + let master = document.block_records.get(MASTER).unwrap().handle; + let index = crate::scene::block_authoring::members(document, master) + .iter() + .position(|member| *member == handle); + format!("raw member {index:?}") + } + other => format!("{other:?}"), + } +} + +/// Every BricsCAD object under `block`'s extension dictionary, in the order of +/// a walk through its feature and other managers, each as its class and +/// normalized properties. +fn parameter_objects(document: &Document, block: Handle) -> Vec { + let members = crate::scene::block_authoring::members(document, block); + let mut out = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut stack: Vec = ["BDM_DATABASE", "FEATURE_MANAGER", "PERSIDMANAGER"] + .iter() + .filter_map(|key| database_entry(document, block, key)) + .collect(); + stack.reverse(); + while let Some(handle) = stack.pop() { + if !seen.insert(handle) { + continue; + } + let Some(record) = record(document, handle) else { + continue; + }; + let class = match document.objects.get(&handle) { + Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(), + _ => continue, + }; + let mut children = Vec::new(); + let properties = match &record.body { + Body::Properties(properties) => properties.clone(), + Body::ConstraintManager { + counts, + children: owned, + settings, + } => { + children.extend(owned.iter().map(|r| r.handle)); + out.push(format!("{class} counts {counts:?}")); + settings.clone() + } + Body::Object { + entity, properties, .. + } => { + out.push(format!( + "{class} entity {}", + normalized( + document, + &members, + &Value::Object { + kind: 0, + target: *entity + } + ) + )); + properties.clone() + } + Body::Dependency { + entity, properties, .. + } => { + out.push(format!( + "{class} entity {}", + normalized( + document, + &members, + &Value::Object { + kind: 0, + target: *entity + } + ) + )); + properties.clone() + } + }; + for (name, value) in &properties.0 { + out.push(format!( + "{class}.{name} = {}", + normalized(document, &members, value) + )); + let mut value = value.clone(); + let mut collect = |value: &Value| { + if let Value::Object { target, .. } = value { + children.push(target.handle); + } + }; + walk(&mut value, &mut collect); + } + stack.extend(children.into_iter().rev()); + } + out +} + +fn walk(value: &mut Value, visit: &mut impl FnMut(&Value)) { + visit(value); + match value { + Value::List { items, .. } => items.iter_mut().for_each(|item| walk(item, visit)), + Value::Map { entries, .. } => entries.iter_mut().for_each(|(k, v)| { + walk(k, visit); + walk(v, visit); + }), + _ => {} + } +} + +#[test] +fn a_new_copy_holds_what_bricscad_s_own_copy_in_the_same_states_holds() { + let mut scene = opened(); + let master = scene.document.block_records.get(MASTER).unwrap().handle; + let bricscad = scene.document.block_records.get("*U3").unwrap().handle; + let states: BTreeMap = [("LAMP", "Off"), ("LABEL", "Hidden")] + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let listed: BTreeSet = ["LAMP", "LABEL"].iter().map(|s| s.to_string()).collect(); + let copy = scene + .clone_parametric_copy(master, &states, &listed) + .unwrap(); + let ours = parameter_objects(&scene.document, copy); + let theirs = parameter_objects(&scene.document, bricscad); + assert!(ours.len() > 40, "{ours:#?}"); + // The key variables' numbers follow no rule BricsCAD keeps: the same + // state carries 0 in one of its copies and 1 in another. + let differences: Vec<(&String, &String)> = ours + .iter() + .zip(&theirs) + .filter(|(a, b)| a != b) + .filter(|(a, _)| !a.starts_with("BDMDBCONFIGVARREACTOR.Value")) + .collect(); + assert_eq!(ours.len(), theirs.len(), "{ours:#?}\n{theirs:#?}"); + assert!(differences.is_empty(), "{differences:#?}"); + // Member layers too. + let layers = |block: Handle| -> Vec { + crate::scene::block_authoring::members(&scene.document, block) + .into_iter() + .map(|m| scene.document.get_entity(m).unwrap().common().layer.clone()) + .collect() + }; + assert_eq!(layers(copy), layers(bricscad)); +} + +#[test] +fn the_switched_drawing_keeps_its_parameters_through_a_dwg_save() { + let mut scene = opened(); + scene + .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden") + .unwrap(); + scene + .set_bricscad_visibility(reference(0x19E), "LAMP", "On") + .unwrap(); + scene.sync_native_parametric_graph(); + let saved = crate::io::save_to_bytes(&scene.document, "dwg", scene.document.version) + .expect("save as DWG"); + let reopened = crate::io::load_bytes_finalized(std::path::Path::new("saved.dwg"), saved) + .expect("open the saved DWG"); + assert_eq!( + shown(&reopened, 0xEE), + pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]) + ); + assert_eq!( + shown(&reopened, 0x146), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_eq!( + shown(&reopened, 0x19E), + pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]) + ); + assert_eq!( + block_of(&reopened, 0x19E), + block_of(&reopened, 0xEE), + "shared" + ); + assert_eq!( + entry(&reopened, 0x19E), + Some(pairs(&[("LABEL", "Hidden"), ("LAMP", "On")])) + ); + assert_no_dangling_references(&reopened); +} + +#[test] +fn an_unknown_parameter_or_state_is_refused_and_a_shown_state_changes_nothing() { + let mut scene = opened(); + let before = scene.document.clone(); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "NOPE", "On") + .is_err()); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LAMP", "Dim") + .is_err()); + assert_eq!( + scene.set_bricscad_visibility(reference(0xEE), "LAMP", "On"), + Ok(false) + ); + assert!(scene.document == before); +} + +/// BricsCAD keeps each read of a variable at the variable's value, and takes a +/// variable whose reads already hold its new value for unchanged: a stale +/// read would keep it from evaluating what depends on the variable. +#[test] +fn each_read_of_a_variable_holds_the_variable_s_value_after_a_switch() { + use document::objects::{AssociativeData, AssociativeObject}; + let mut scene = opened(); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden") + .unwrap()); + let document = &scene.document; + let copy = document + .block_records + .get(&block_of(document, 0xEE)) + .unwrap() + .handle; + // The copy's network sits in its extension dictionary, behind a + // dictionary of the same name. + let entry = |dictionary: Handle| match document.objects.get(&dictionary) { + Some(ObjectType::Dictionary(dictionary)) => dictionary.get("ACAD_ASSOCNETWORK"), + _ => None, + }; + let mut network = entry(document.extension_dictionary_handle(copy).unwrap()).unwrap(); + while let Some(inner) = entry(network) { + network = inner; + } + let mut reads = 0; + for object in document.objects.values() { + let ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(read), + .. + }) = object + else { + continue; + }; + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + owner, + .. + })) = document.objects.get(&read.dependency.dependent_on) + else { + panic!("a read of something other than a variable"); + }; + assert_eq!(read.value, variable.value, "{}", variable.name); + reads += usize::from(*owner == network); + } + assert!(reads > 0, "the copy's variables are read"); +} diff --git a/src/scene/bricscad_parameters/tests.rs b/src/scene/bricscad_parameters/tests.rs new file mode 100644 index 0000000000..d876386121 --- /dev/null +++ b/src/scene/bricscad_parameters/tests.rs @@ -0,0 +1,141 @@ +use super::*; +use document::DxfVersion; + +/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README). +fn fixture() -> Document { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture") +} + +fn block(document: &Document, name: &str) -> Handle { + document.block_records.get(name).unwrap().handle +} + +/// The block reference with handle `value`. +fn reference(value: u64) -> Handle { + Handle::from(value) +} + +/// Each parameter as its name and the state it shows. +fn shown(parameters: &[VisibilityParameter]) -> Vec<(&str, &str)> { + parameters + .iter() + .map(|parameter| { + ( + parameter.name.as_str(), + parameter + .current + .map_or("?", |index| parameter.states[index].as_str()), + ) + }) + .collect() +} + +#[test] +fn the_definition_names_its_parameters_their_states_and_the_ones_it_shows() { + let document = fixture(); + let parameters = + visibility_parameters(&document, block(&document, "ocs-bricscad-visibility-block")); + assert_eq!( + parameters, + vec![ + VisibilityParameter { + name: "LAMP".into(), + states: vec!["On".into(), "Off".into()], + current: Some(0), + feature: Handle::from(0x16Fu64), + }, + VisibilityParameter { + name: "LABEL".into(), + states: vec!["Shown".into(), "Hidden".into()], + current: Some(0), + feature: Handle::from(0x176u64), + }, + ] + ); +} + +#[test] +fn each_reference_shows_the_states_it_was_set_to() { + let document = fixture(); + assert_eq!( + shown(&reference_parameters(&document, reference(0xEE))), + [("LAMP", "On"), ("LABEL", "Shown")] + ); + assert_eq!( + shown(&reference_parameters(&document, reference(0x146))), + [("LAMP", "Off"), ("LABEL", "Shown")] + ); + assert_eq!( + shown(&reference_parameters(&document, reference(0x19E))), + [("LAMP", "Off"), ("LABEL", "Hidden")] + ); +} + +#[test] +fn a_copy_names_the_block_it_was_made_from() { + let document = fixture(); + let definition = block(&document, "ocs-bricscad-visibility-block"); + for copy in ["*U2", "*U3"] { + assert_eq!( + original_block(&document, block(&document, copy)), + Some(definition), + "{copy}" + ); + } + assert_eq!(original_block(&document, definition), None); +} + +#[test] +fn other_blocks_and_references_have_no_parameters() { + let document = fixture(); + let model = document.header.model_space_block_handle; + assert!(visibility_parameters(&document, model).is_empty()); + assert_eq!(original_block(&document, model), None); + let line = document + .entities() + .find(|entity| matches!(entity, EntityType::Line(_))) + .unwrap() + .common() + .handle; + assert!(reference_parameters(&document, line).is_empty()); +} + +#[test] +fn a_cut_record_decodes_to_nothing_rather_than_a_wrong_answer() { + let document = fixture(); + let mut records = 0; + for object in document.objects.values() { + let ObjectType::Unknown { + type_name, + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } = object + else { + continue; + }; + if type_name != "BDMDBCONFIGURATIONTABLE" { + continue; + } + let whole = record::decode(type_name, data, *raw_dwg_handle_bits, *version) + .expect("the whole record"); + assert!(whole.body.properties().get("KeyValues").is_some()); + records += 1; + for length in 0..data.len() { + // Shorter by whole bytes: the streams no longer line up. + let _ = record::decode(type_name, &data[..length], *raw_dwg_handle_bits, *version); + } + assert_eq!( + record::decode(type_name, data, *raw_dwg_handle_bits, DxfVersion::AC1021), + None + ); + } + assert_eq!(records, 6, "two tables in each of the three blocks"); +} diff --git a/src/scene/dwg_native_constraints.rs b/src/scene/dwg_native_constraints.rs index 02365a1a42..8db93cd4cc 100644 --- a/src/scene/dwg_native_constraints.rs +++ b/src/scene/dwg_native_constraints.rs @@ -4194,38 +4194,7 @@ impl Scene { } pub(crate) fn load_named_parameters_from_document(&mut self) { - self.named_parameters = ParameterTable::new(); - let mut variables: Vec<_> = self - .document - .objects - .values() - .filter_map(|object| match object { - ObjectType::Associative(AssociativeObject { - handle, - data: AssociativeData::Variable(variable), - .. - }) => Some((*handle, variable)), - _ => None, - }) - .collect(); - variables.sort_by_key(|(handle, _)| handle.value()); - let model_network = native_scope_network_handle( - &self.document, - self.document.header.model_space_block_handle, - ); - for (_, variable) in variables { - if model_network.is_none_or(|network| variable.action.owning_network != network) { - continue; - } - let source = if variable.expression.trim().is_empty() { - numeric_value(&variable.value).map(|value| value.to_string()) - } else { - Some(variable.expression.clone()) - }; - if let Some(source) = source { - let _ = self.named_parameters.set(&variable.name, &source); - } - } + self.named_parameters = model_network_parameters(&self.document); } pub(crate) fn load_parametric_constraints_from_document(&mut self) { @@ -4300,6 +4269,8 @@ impl Scene { .map(|&owner| native_scope_network_handle(&self.document, owner).is_some()) .collect() }; + let raw_dependents = networks_raw_objects_depend_on(&self.document); + let mut kept_networks = Vec::new(); let mut scopes = Vec::new(); for (owner, existing) in owners.into_iter().zip(existing_networks) { let runtime = self @@ -4307,6 +4278,18 @@ impl Scene { .iter() .find(|set| set.scope.owner_handle(&self.document) == owner) .cloned(); + if existing { + if let Some(network) = stored_network_to_keep( + &self.document, + owner, + runtime.as_ref(), + &self.named_parameters, + &raw_dependents, + ) { + kept_networks.push(network); + continue; + } + } let set = match runtime { Some(set) => Some(set), None if existing => { @@ -4355,6 +4338,7 @@ impl Scene { ); let root_network_handle = self.document.allocate_handle(); let mut child_networks = Vec::new(); + let rebuilt_scopes = scopes.len(); for (index, (owner, set, variables, groups, foreign)) in scopes.into_iter().enumerate() { let parameters = if set.local_parameters.is_empty() { &self.named_parameters @@ -4376,6 +4360,19 @@ impl Scene { child_networks.push(handle); } } + // The kept networks go under the new root after the rebuilt ones, + // unchanged apart from where they sit in it. + for (offset, network) in kept_networks.into_iter().enumerate() { + if let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Network(kept), + .. + })) = self.document.objects.get_mut(&network) + { + kept.action.owning_network = root_network_handle; + kept.action.action_index = (rebuilt_scopes + offset) as i32 + 1; + child_networks.push(network); + } + } if child_networks.is_empty() { return; } @@ -4431,63 +4428,189 @@ impl Scene { let mut hasher = DefaultHasher::new(); hash_parameter_table(&self.named_parameters, &mut hasher); for set in &self.parametric_constraints { - set.scope.hash(&mut hasher); - for constraint in &set.constraints { - constraint.id.hash(&mut hasher); - (constraint.kind as u16).hash(&mut hasher); - constraint.refs.hash(&mut hasher); - match &constraint.driving_param { - None => 0u8.hash(&mut hasher), - Some(DrivingValue::Literal(value)) => { - 1u8.hash(&mut hasher); - value.to_bits().hash(&mut hasher); - } - Some(DrivingValue::Named(name)) => { - 2u8.hash(&mut hasher); - name.hash(&mut hasher); - } - } - constraint.enabled.hash(&mut hasher); - match constraint.native_origin { - None => 0u8.hash(&mut hasher), - Some(origin) => { - 1u8.hash(&mut hasher); - origin.group.hash(&mut hasher); - origin.node.hash(&mut hasher); - } - } - constraint.rigid_points.len().hash(&mut hasher); - for (reference, point) in &constraint.rigid_points { - reference.hash(&mut hasher); - hash_vector(point, &mut hasher); - } - constraint.distance_direction_type.hash(&mut hasher); - match constraint.distance_direction { - None => 0u8.hash(&mut hasher), - Some(direction) => { - 1u8.hash(&mut hasher); - hash_vector(&direction, &mut hasher); - } - } - match constraint.axis_direction { - None => 0u8.hash(&mut hasher), - Some(direction) => { - 1u8.hash(&mut hasher); - hash_vector(&direction, &mut hasher); - } - } - constraint.angle_sector.hash(&mut hasher); + hash_constraint_set(set, &mut hasher); + } + hasher.finish() + } +} + +/// Hashes one scope's share of the model `constraint_model_fingerprint` +/// covers. Dimension links are hashed in id order, so two sets with the same +/// links hash alike whatever order their maps hold them in. +fn hash_constraint_set(set: &ParametricConstraintSet, hasher: &mut DefaultHasher) { + set.scope.hash(hasher); + for constraint in &set.constraints { + constraint.id.hash(hasher); + (constraint.kind as u16).hash(hasher); + constraint.refs.hash(hasher); + match &constraint.driving_param { + None => 0u8.hash(hasher), + Some(DrivingValue::Literal(value)) => { + 1u8.hash(hasher); + value.to_bits().hash(hasher); } - hash_parameter_table(&set.local_parameters, &mut hasher); - set.dimensions.len().hash(&mut hasher); - for (id, dimension) in &set.dimensions { - id.hash(&mut hasher); - dimension.hash(&mut hasher); + Some(DrivingValue::Named(name)) => { + 2u8.hash(hasher); + name.hash(hasher); } - set.retained_standard_groups.hash(&mut hasher); } - hasher.finish() + constraint.enabled.hash(hasher); + match constraint.native_origin { + None => 0u8.hash(hasher), + Some(origin) => { + 1u8.hash(hasher); + origin.group.hash(hasher); + origin.node.hash(hasher); + } + } + constraint.rigid_points.len().hash(hasher); + for (reference, point) in &constraint.rigid_points { + reference.hash(hasher); + hash_vector(point, hasher); + } + constraint.distance_direction_type.hash(hasher); + match constraint.distance_direction { + None => 0u8.hash(hasher), + Some(direction) => { + 1u8.hash(hasher); + hash_vector(&direction, hasher); + } + } + match constraint.axis_direction { + None => 0u8.hash(hasher), + Some(direction) => { + 1u8.hash(hasher); + hash_vector(&direction, hasher); + } + } + constraint.angle_sector.hash(hasher); + } + hash_parameter_table(&set.local_parameters, hasher); + let mut dimensions: Vec<_> = set.dimensions.iter().collect(); + dimensions.sort_unstable_by_key(|(id, _)| **id); + dimensions.len().hash(hasher); + for (id, dimension) in dimensions { + id.hash(hasher); + dimension.hash(hasher); + } + set.retained_standard_groups.hash(hasher); +} + +fn constraint_set_hash(set: &ParametricConstraintSet) -> u64 { + let mut hasher = DefaultHasher::new(); + hash_constraint_set(set, &mut hasher); + hasher.finish() +} + +/// The networks whose variables an object kept only as its raw record lists +/// as a reactor. Such an object reaches the variables by handle and cannot be +/// re-pointed, so rebuilding the network under new handles would leave it +/// pointing at erased objects. BricsCAD keeps the visibility states and other +/// parameters of its parametric blocks this way: its own objects, which this +/// program reads as raw records, read and drive the block's variables. +fn networks_raw_objects_depend_on(document: &Document) -> FxHashSet { + document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + reactors, + data: AssociativeData::Variable(variable), + .. + }) if reactors.iter().any(|reactor| { + matches!( + document.objects.get(reactor), + Some(ObjectType::Unknown { .. }) + ) + }) => + { + Some(variable.action.owning_network) + } + _ => None, + }) + .collect() +} + +/// The stored network of `owner` when it is written back as it was read: raw +/// objects depend on it (see `networks_raw_objects_depend_on`) and the +/// editor's model of the scope still equals the one the network holds. For +/// model space that includes the drawing's parameter table, which is read +/// from the model-space network. A scope the user changed is rebuilt as +/// before. +fn stored_network_to_keep( + document: &Document, + owner: Handle, + runtime: Option<&ParametricConstraintSet>, + named_parameters: &ParameterTable, + raw_dependents: &FxHashSet, +) -> Option { + if raw_dependents.is_empty() { + return None; + } + let network = native_scope_network_handle(document, owner)?; + if !raw_dependents.contains(&network) { + return None; + } + let mut parameters = if owner == document.header.model_space_block_handle { + let loaded = loaded_named_parameters(document); + if has_pending_surfaces(document) || *named_parameters != loaded { + return None; + } + loaded + } else { + // A block scope reads its parameters into a table of its own. + ParameterTable::new() + }; + let Some(runtime) = runtime else { + return Some(network); + }; + let stored = native_constraint_set(document, owner, &mut parameters)?; + (constraint_set_hash(runtime) == constraint_set_hash(&stored)).then_some(network) +} + +/// The drawing's parameter table as opening the drawing builds it: the +/// variables of the model-space network, then whatever reading each scope's +/// constraints adopts into it. +fn loaded_named_parameters(document: &Document) -> ParameterTable { + let mut parameters = model_network_parameters(document); + for record in document.block_records.iter() { + native_constraint_set(document, record.handle, &mut parameters); + } + parameters +} + +/// The named variables of the model-space network as a parameter table. +fn model_network_parameters(document: &Document) -> ParameterTable { + let mut parameters = ParameterTable::new(); + let Some(model_network) = + native_scope_network_handle(document, document.header.model_space_block_handle) + else { + return parameters; + }; + let mut variables: Vec<_> = document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + handle, + data: AssociativeData::Variable(variable), + .. + }) if variable.action.owning_network == model_network => Some((*handle, variable)), + _ => None, + }) + .collect(); + variables.sort_by_key(|(handle, _)| handle.value()); + for (_, variable) in variables { + let source = if variable.expression.trim().is_empty() { + numeric_value(&variable.value).map(|value| value.to_string()) + } else { + Some(variable.expression.clone()) + }; + if let Some(source) = source { + let _ = parameters.set(&variable.name, &source); + } } + parameters } /// Hashes a parameter table in insertion order: each parameter's name, @@ -4508,6 +4631,9 @@ fn hash_vector(vector: &Vector3, hasher: &mut DefaultHasher) { vector.z.to_bits().hash(hasher); } +#[cfg(test)] +mod raw_dependents_tests; + #[cfg(test)] mod tests { use super::super::parametric_constraints::{ diff --git a/src/scene/dwg_native_constraints/raw_dependents_tests.rs b/src/scene/dwg_native_constraints/raw_dependents_tests.rs new file mode 100644 index 0000000000..6f578ef12d --- /dev/null +++ b/src/scene/dwg_native_constraints/raw_dependents_tests.rs @@ -0,0 +1,303 @@ +//! A network that objects kept only as raw records depend on is written back +//! with its handles while the editor has not changed its scope. +//! +//! BricsCAD keeps the visibility states of its parametric blocks in objects of +//! its own classes. They are read here as raw records and reach the block's +//! associative variables by handle, so a rebuild under new handles leaves them +//! pointing at erased variables and BricsCAD drops the block's parameters. + +use super::*; +use document::entities::Line; + +/// The objects `bind_raw_network` adds. +struct Bound { + network: Handle, + variable: Handle, + raw: Handle, +} + +/// Give `owner` a network with one variable, `look_1` = 1, that lists a raw +/// object as its reactor, the way BricsCAD's variables list the objects that +/// read them. +fn bind_raw_network(document: &mut Document, owner: Handle) -> Bound { + let dictionary = document.ensure_extension_dictionary(owner); + let [network, variable, raw] = [(); 3].map(|_| document.allocate_handle()); + document.objects.insert( + raw, + ObjectType::Unknown { + type_name: "BDMDBCONFIGVARREACTOR".to_string(), + handle: raw, + owner: dictionary, + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0; 8]), + raw_dwg_handle_bits: 0, + raw_dwg_version: None, + }, + ); + document.objects.insert( + network, + ObjectType::Associative(AssociativeObject { + handle: network, + owner: dictionary, + reactors: vec![dictionary], + dxf_name: "ACDBASSOCNETWORK".to_string(), + cpp_class_name: "AcDbAssocNetwork".to_string(), + data: AssociativeData::Network(AssocNetwork { + action: AssocAction { + class_version: 2, + ..Default::default() + }, + network_action_index: 1, + actions: vec![AssocActionDependency { + is_owned: true, + dependency: variable, + }], + ..Default::default() + }), + ..Default::default() + }), + ); + document.objects.insert( + variable, + ObjectType::Associative(AssociativeObject { + handle: variable, + owner: network, + reactors: vec![raw], + dxf_name: "ACDBASSOCVARIABLE".to_string(), + cpp_class_name: "AcDbAssocVariable".to_string(), + data: AssociativeData::Variable(AssocVariable { + action: AssocAction { + class_version: 2, + owning_network: network, + action_index: 1, + ..Default::default() + }, + class_version: 2, + name: "look_1".to_string(), + evaluator: "AcDbCalc:1.0".to_string(), + value: AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(1.0), + }, + ..Default::default() + }), + ..Default::default() + }), + ); + if let Some(ObjectType::Dictionary(dictionary)) = document.objects.get_mut(&dictionary) { + dictionary.add_entry(NETWORK_DICTIONARY_KEY, network); + } + Bound { + network, + variable, + raw, + } +} + +/// A scene with one block definition holding a line. +fn block_scene() -> (Scene, Handle) { + let mut scene = Scene::new(); + scene.define_block_raw( + "states", + Vector3::ZERO, + vec![EntityType::Line(Line::from_points( + Vector3::ZERO, + Vector3::UNIT_X, + ))], + ); + let block = scene.document.block_records.get("states").unwrap().handle; + (scene, block) +} + +/// Read the drawing's parameters and constraints as opening a file does. +fn read_as_opened(scene: &mut Scene) { + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); +} + +fn variable_value(document: &Document, network: Handle, name: &str) -> Option { + document.objects.values().find_map(|object| match object { + ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) if variable.action.owning_network == network && variable.name == name => { + numeric_value(&variable.value) + } + _ => None, + }) +} + +#[test] +fn a_block_network_raw_objects_depend_on_keeps_its_handles() { + let (mut scene, block) = block_scene(); + let bound = bind_raw_network(&mut scene.document, block); + read_as_opened(&mut scene); + let network = scene.document.objects.get(&bound.network).cloned(); + let variable = scene.document.objects.get(&bound.variable).cloned(); + + scene.sync_native_parametric_graph(); + + assert_eq!( + native_scope_network_handle(&scene.document, block), + Some(bound.network), + "the block keeps its network" + ); + assert_eq!(scene.document.objects.get(&bound.network).cloned(), network); + assert_eq!( + scene.document.objects.get(&bound.variable).cloned(), + variable, + "the variable the raw object reads is written back as it was read" + ); + assert!(matches!( + scene.document.objects.get(&bound.raw), + Some(ObjectType::Unknown { .. }) + )); +} + +#[test] +fn a_model_space_network_raw_objects_depend_on_keeps_its_handles() { + // A drawing that is itself a BricsCAD parametric block keeps its + // parameters in the model-space network, which is also where the + // drawing's own parameter table is read from. + let mut scene = Scene::new(); + let model = scene.document.header.model_space_block_handle; + let bound = bind_raw_network(&mut scene.document, model); + read_as_opened(&mut scene); + assert!( + scene.named_parameters.get("look_1").is_some(), + "opening reads the variable into the drawing's parameters" + ); + let variable = scene.document.objects.get(&bound.variable).cloned(); + + scene.sync_native_parametric_graph(); + + assert_eq!( + native_scope_network_handle(&scene.document, model), + Some(bound.network) + ); + assert_eq!( + scene.document.objects.get(&bound.variable).cloned(), + variable + ); +} + +#[test] +fn a_parameter_changed_in_such_a_scope_is_still_written() { + let (mut scene, block) = block_scene(); + let bound = bind_raw_network(&mut scene.document, block); + read_as_opened(&mut scene); + scene + .parametric_constraint_set_mut(ParametricScope::Block(block)) + .local_parameters + .set("look_1", "0") + .unwrap(); + + scene.sync_native_parametric_graph(); + + let network = + native_scope_network_handle(&scene.document, block).expect("the block still has a network"); + assert_ne!(network, bound.network, "a changed scope is rebuilt"); + assert_eq!( + variable_value(&scene.document, network, "look_1"), + Some(0.0) + ); +} + +#[test] +fn a_changed_drawing_parameter_rebuilds_the_model_space_network() { + let mut scene = Scene::new(); + let model = scene.document.header.model_space_block_handle; + let bound = bind_raw_network(&mut scene.document, model); + read_as_opened(&mut scene); + scene.named_parameters.set("look_1", "0").unwrap(); + + scene.sync_native_parametric_graph(); + + let network = native_scope_network_handle(&scene.document, model) + .expect("model space still has a network"); + assert_ne!(network, bound.network, "a changed scope is rebuilt"); + assert_eq!( + variable_value(&scene.document, network, "look_1"), + Some(0.0) + ); +} + +#[test] +fn a_bricscad_parametric_block_keeps_the_variables_its_objects_read_through_a_dwg_save() { + // tests/fixtures/bricscad/README.md describes the drawing. + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + let mut scene = Scene::new(); + scene.document = + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture"); + read_as_opened(&mut scene); + + // Each variable with its name, network and the objects listed as its + // reactors: BricsCAD's objects, and the value dependency of a variable + // another one's expression reads. + let variables = |document: &Document| { + let mut rows: Vec<(Handle, String, Handle, Vec)> = document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + handle, + reactors, + data: AssociativeData::Variable(variable), + .. + }) => Some(( + *handle, + variable.name.clone(), + variable.action.owning_network, + reactors.clone(), + )), + _ => None, + }) + .collect(); + rows.sort_by_key(|row| row.0); + rows + }; + let value_dependencies = |document: &Document| { + document + .objects + .values() + .filter(|object| { + matches!( + object, + ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(_), + .. + }) + ) + }) + .count() + }; + let before = variables(&scene.document); + assert_eq!( + before.len(), + 18, + "six variables in each of the three blocks" + ); + assert_eq!(value_dependencies(&scene.document), 6); + + scene.sync_native_parametric_graph(); + let saved = crate::io::save_to_bytes(&scene.document, "dwg", scene.document.version) + .expect("save as DWG"); + let reopened = crate::io::load_bytes_finalized(std::path::Path::new("saved.dwg"), saved) + .expect("open the saved DWG"); + + assert_eq!(variables(&reopened), before); + assert_eq!(value_dependencies(&reopened), 6); + for (handle, name, _, reactors) in &before { + for reactor in reactors { + assert!( + reopened.objects.contains_key(reactor), + "{name} ({handle:?}) lists {reactor:?}, which the saved drawing lost" + ); + } + } +} diff --git a/src/scene/mod.rs b/src/scene/mod.rs index 41e5a9a332..79430524e6 100644 --- a/src/scene/mod.rs +++ b/src/scene/mod.rs @@ -26,6 +26,7 @@ pub(crate) mod block_point_parameter; pub(crate) mod block_properties_table; pub mod block_service; pub mod block_visibility; +pub(crate) mod bricscad_parameters; pub mod cache; pub mod compare; pub mod convert; diff --git a/src/scene/model/object.rs b/src/scene/model/object.rs index 849142ac86..98da238b9e 100644 --- a/src/scene/model/object.rs +++ b/src/scene/model/object.rs @@ -22,6 +22,9 @@ pub enum BlockParameterComponent { Angle, Flip, Visibility(u64), + // A BricsCAD parametric block's visibility parameter, with a hash of its + // name and states. + Bricscad(u64), TableRow(u64), LookupOutput { column: usize, revision: u64 }, } diff --git a/tests/fixtures/bricscad/README.md b/tests/fixtures/bricscad/README.md new file mode 100644 index 0000000000..35d41144bd --- /dev/null +++ b/tests/fixtures/bricscad/README.md @@ -0,0 +1,32 @@ +A parametric block with visibility states, made in BricsCAD V26 (Linux, German +user interface) and saved there as DWG 2018 (AC1032). + +The block `ocs-bricscad-visibility-block` holds a 10 × 10 frame, a circle with a +cross through it and the text `LABEL`. It has two visibility parameters, set up +with `VISIBILITYSTATES` on the drawing that became the block: + +| Parameter | States | Objects the second state hides | +|---|---|---| +| `LAMP` | `On`, `Off` | the circle and the two cross lines | +| `LABEL` | `Shown`, `Hidden` | the text | + +`visibility-states.dwg` inserts the block three times along the x axis: + +| Handle | At | `LAMP` | `LABEL` | Block | +|---|---|---|---|---| +| `EE` | 0, 0 | `On` | `Shown` | the definition itself | +| `146` | 20, 0 | `Off` | `Shown` | `*U2` | +| `19E` | 40, 0 | `Off` | `Hidden` | `*U3` | + +What the file shows about how BricsCAD stores such a block: + +- A reference in a state other than the definition's shows an anonymous copy + (`*U2`, `*U3`) with every member of the definition in the same order. The + members a state hides sit on the layer `*SUPPRESS`, which is frozen and off. +- The parameters live in objects of BricsCAD's own classes (`BDMDB…`, + `BdmDb…`, `BDMOBJECT`) under `BDM_DATABASE` in the extension dictionary of + the definition, of each copy and of model space. Each block also has an + `ACAD_ASSOCNETWORK` whose variables (`LAMP`, `look_1`, `Unterdrücken_1`, …) + those objects read and drive. The variables list them as reactors and the + objects reach the variables by handle, so the variables must keep their + handles when the drawing is saved. diff --git a/tests/fixtures/bricscad/visibility-states.dwg b/tests/fixtures/bricscad/visibility-states.dwg new file mode 100644 index 0000000000..6a05c3f8f5 Binary files /dev/null and b/tests/fixtures/bricscad/visibility-states.dwg differ