From 0e16d77dcd741077f6b98f98e435a83f53ed52d0 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:36:43 +0100 Subject: [PATCH 1/4] Saving keeps the associative network a BricsCAD parametric block depends on BricsCAD keeps the visibility states of its parametric blocks in objects of its own classes, which are read here as raw records. They reach the block's ACAD_ASSOCNETWORK variables by handle, and the variables list them as reactors. The graph sync that runs on save rebuilt every scope's network under new handles and dropped its value dependencies, so BricsCAD found its objects pointing at erased variables and dropped every parameter of the drawing. A network whose variables list a raw record as reactor is now written back as it was read, as long as the editor's model of that scope still equals the one the network holds; a scope the user changed is rebuilt as before. Kept networks go back under the rebuilt root network. --- src/scene/dwg_native_constraints.rs | 296 ++++++++++++----- .../raw_dependents_tests.rs | 303 ++++++++++++++++++ tests/fixtures/bricscad/README.md | 32 ++ tests/fixtures/bricscad/visibility-states.dwg | Bin 0 -> 22349 bytes 4 files changed, 546 insertions(+), 85 deletions(-) create mode 100644 src/scene/dwg_native_constraints/raw_dependents_tests.rs create mode 100644 tests/fixtures/bricscad/README.md create mode 100644 tests/fixtures/bricscad/visibility-states.dwg 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/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 0000000000000000000000000000000000000000..6a05c3f8f5af6158bd406f3f8cdc90149246857d GIT binary patch literal 22349 zcmc$`4M0@Y)-b&G`J2Q1z+o6*h95bc84yr#eed_(`@GM0 zV4t6T_SrvcueJ7CYp*r7yrI^NbO;>7Xg>jnA2y)>>6ep;S%E{r)P6{}p+R4{L{$M!jwq0|_wq#Y?|H?$@{f+O-e+_XhT9P%-vz z+TA_|`WYGj{JfQ;COjXPP^~(fos{(W^iyLVcL;+Xr2#1NDYosx2DxDrKqhAWcORQw z6UXY*QEIGLSLk$1#zyg$Fnr*0W`1-cUV>_zGim`eVSz+o_Z}mbx>D${mDFGO@;zH9 z0RNWt=v%LU67SjUUH@_+r;Hv*6asDlEXl#Ya{I4*^Iw|!H$TUk{+-VM`=4X~|7FnK z1;fAjIS&6{o4Eh@?BD#{_%ET&f3*JJ@VOJZKO@s7s5JA{^=}~=Kwt-^O6yq^ba@H`j$C&DD`>4N?{2VQIYdl1OC z;kQ-z6eu;nzs@8q>%ja#zvlLjFz|j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cf)5e@4sA3AdA$oK7rN8ft(`h6#reWx#6*?i{WhTk9C`u+YWaqN_(Y0hby#rz|& z70b1gd|k%|)Mpn~*5wbs*P1`Clz!y>{k^Xqf9BAUi0VPr)sxA($xDYWA67qRMfOAA zT=t%N?$dp7_a+wY2!Hgab01mI>mTn{;V&xn zKS13S%+}T8t^tETGZ&!fD*gy7#w5UgZ^&$e0u7PnM(s9});8ZUZ$!c3ss)Y(HARbS zy@`rWq)fmR@nzvof*Op2l+k4{j)FGVfCplMel#+GfzA{IVSL^XNAD(B+bx@9ZYcv&&X2o#57y6==` zTYU{(X1o-ws%IOfxMG<}^C}n2ud8ilMcxRrL&L2{HRVII%W5|6pV7>f4Zj#ymR!n} z4p5K4f(0uUESOR=cm4twE2_0nzWCs2P1*mo%@NFcdl+N3#(*3alA2qPlUM?r;bM&8 zk6qXpz|_lN8DrJcd&hi^VvaPkM`B(|PO5@H4r_!&?9G%OiCAW7)eC}pHOw Date: Mon, 23 Nov 2026 10:52:21 +0100 Subject: [PATCH 2/4] Properties show the visibility states of a BricsCAD parametric block reference BricsCAD keeps the visibility parameters of its parametric blocks in objects of its own classes, which are read as raw records. A new scene module decodes the few it needs from their DWG bytes (2010 and later): each object is a list of named properties, with names and text in the string stream and object references in the handle stream. From them it reads a block's visibility parameters, their states and the state the block shows, and the block an anonymous copy was made from. A reference to such a block now shows one read-only row per parameter in the Custom section, with the state it shows and the states as tooltip, and its Name row names the block rather than the *U copy a reference in another state shows. --- src/app/bricscad_visibility_tests.rs | 97 ++++++ src/app/control/block_ops.rs | 12 +- src/app/mod.rs | 2 + src/app/properties.rs | 1 + src/app/visibility.rs | 25 ++ src/scene/bricscad_parameters.rs | 448 +++++++++++++++++++++++++ src/scene/bricscad_parameters/tests.rs | 134 ++++++++ src/scene/mod.rs | 1 + 8 files changed, 719 insertions(+), 1 deletion(-) create mode 100644 src/app/bricscad_visibility_tests.rs create mode 100644 src/scene/bricscad_parameters.rs create mode 100644 src/scene/bricscad_parameters/tests.rs diff --git a/src/app/bricscad_visibility_tests.rs b/src/app/bricscad_visibility_tests.rs new file mode 100644 index 0000000000..cabb023715 --- /dev/null +++ b/src/app/bricscad_visibility_tests.rs @@ -0,0 +1,97 @@ +//! A reference to a BricsCAD parametric block names the block and shows its +//! visibility parameters in Properties, also when it shows an anonymous copy +//! of the block in another state. + +use super::*; +use crate::scene::model::object::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, value and tooltip. +fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, String)> { + app.tabs[app.active_tab] + .properties + .sections + .iter() + .flat_map(|section| §ion.props) + .filter(|property| property.field == "bricscad_visibility") + .map(|property| match &property.value { + PropValue::ReadOnlyWithTooltip { value, tooltip } => { + (property.label.clone(), value.clone(), tooltip.clone()) + } + other => panic!("{} is {other:?}", property.label), + }) + .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:?}"), + } +} + +fn rows(lamp: &str, label: &str) -> Vec<(String, String, String)> { + vec![ + ("LAMP".into(), lamp.into(), "On, Off".into()), + ("LABEL".into(), label.into(), "Shown, Hidden".into()), + ] +} + +#[test] +fn a_reference_shows_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!(visibility_rows(&app), rows(lamp, label), "{reference:X}"); + assert_eq!( + block_name(&app), + "ocs-bricscad-visibility-block", + "{reference:X} shows its block's name, not its copy's" + ); + } +} 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..08dc63885b 100644 --- a/src/app/properties.rs +++ b/src/app/properties.rs @@ -1073,6 +1073,7 @@ impl OpenCADStudio { custom_properties.extend(Self::visibility_property(doc, handle)); } custom_properties.extend(Self::visible_blocks_property(doc, handle)); + custom_properties.extend(Self::bricscad_visibility_properties(doc, handle)); 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..1f503d594f 100644 --- a/src/app/visibility.rs +++ b/src/app/visibility.rs @@ -626,6 +626,31 @@ impl OpenCADStudio { }) } + /// The visibility parameters of a reference to a BricsCAD parametric + /// block, one read-only row each with the state the reference shows and + /// the parameter's states as tooltip. They are read from BricsCAD's own + /// objects, which are kept as they were read, so they are not changed + /// here. + pub(super) fn bricscad_visibility_properties( + doc: &document::Document, + handle: Handle, + ) -> Vec { + crate::scene::bricscad_parameters::reference_parameters(doc, handle) + .into_iter() + .map(|parameter| Property { + value: PropValue::ReadOnlyWithTooltip { + value: parameter + .current + .and_then(|index| parameter.states.get(index).cloned()) + .unwrap_or_default(), + tooltip: parameter.states.join(", "), + }, + label: parameter.name, + field: "bricscad_visibility", + }) + .collect() + } + /// 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/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs new file mode 100644 index 0000000000..f7fddeb470 --- /dev/null +++ b/src/scene/bricscad_parameters.rs @@ -0,0 +1,448 @@ +//! 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. +//! +//! Each of these objects is a list of named properties. The data stream holds +//! the count and, per property, a type byte and the value. Names and text +//! values are in the string stream and object references in the handle +//! stream, in the order the properties name them. + +use document::objects::ObjectType; +use document::{Document, DxfVersion, EntityType, Handle}; + +/// 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 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 { + let Some(manager) = database_entry(document, block, "FEATURE_MANAGER") else { + return Vec::new(); + }; + let Some(Value::List(features)) = + properties(document, manager).and_then(|p| p.take("Features")) + else { + return Vec::new(); + }; + features + .iter() + .filter_map(|feature| match feature { + Value::Object(handle) => visibility_parameter(document, *handle), + _ => None, + }) + .collect() +} + +/// The visibility parameters of the block reference `insert`, in the states +/// it shows. +pub fn reference_parameters(document: &Document, insert: Handle) -> Vec { + let Some(EntityType::Insert(reference)) = document.get_entity(insert) else { + return Vec::new(); + }; + document + .block_records + .get(&reference.block_name) + .map(|record| visibility_parameters(document, record.handle)) + .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")?; + match properties(document, manager)?.take("original.block")? { + Value::Object(original) if !original.is_null() && original != block => Some(original), + _ => None, + } +} + +fn visibility_parameter(document: &Document, feature: Handle) -> Option { + let feature = properties(document, feature)?; + if feature.text("Feature_type")? != "BdmConfigurationFeature" + || feature.text("TableType")? != "VisibilityStates" + { + return None; + } + let Value::Object(table) = feature.get("ConfigTable")? else { + return None; + }; + let table = properties(document, *table)?; + let Value::List(keys) = table.get("KeyValues")? else { + return None; + }; + let states: Vec = keys + .iter() + .map(|key| match key { + Value::Text(state) => Some(state.clone()), + _ => None, + }) + .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, + }) +} + +/// Entry `key` of the `BDM_DATABASE` dictionary in `block`'s extension +/// dictionary. +fn database_entry(document: &Document, block: 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(block)?)?; + dictionary(extension.get("BDM_DATABASE")?)?.get(key) +} + +/// A property value of a BricsCAD object. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Value { + Text(String), + Integer(i32), + Real(f64), + Flag(bool), + Byte(u8), + /// A handle written as its bytes in the data stream. + Raw(Vec), + /// A reference through the handle stream. + Object(Handle), + List(Vec), + Map(Vec<(Value, Value)>), +} + +/// The named properties of one BricsCAD object, 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) + } + + fn take(mut self, name: &str) -> Option { + let index = self.0.iter().position(|(key, _)| key == name)?; + Some(self.0.swap_remove(index).1) + } + + fn text(&self, name: &str) -> Option<&str> { + match self.get(name)? { + Value::Text(text) => Some(text), + _ => None, + } + } +} + +/// The properties 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 properties(document: &Document, handle: Handle) -> Option { + let ObjectType::Unknown { + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } = document.objects.get(&handle)? + else { + return None; + }; + decode(data, *raw_dwg_handle_bits, *version) +} + +/// Decode one object record: the merged data, string and handle streams as +/// the DWG reader keeps them, without the size prefixes and the CRC. +pub(crate) fn decode(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); + main.object_type()?; + let own = main.handle(0)?; + // Extended data: blocks of a size, an application handle and the bytes, + // until a size of 0. + loop { + let size = main.bit_short()?; + if size <= 0 { + break; + } + main.handle(0)?; + for _ in 0..size { + main.byte()?; + } + } + let reactors = main.bit_long()?; + let has_extension_dictionary = !main.bit()?; + if 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); + handles.handle(own)?; // owner + for _ in 0..reactors { + handles.handle(own)?; + } + if has_extension_dictionary { + handles.handle(own)?; + } + let mut reader = Reader { + main, + strings: Bits::new(data, strings_at, strings_end), + handles, + own, + }; + let properties = reader.properties()?; + // A record that leaves data unread was not one of these property lists. + (reader.main.pos == reader.main.end).then_some(properties) +} + +/// 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 properties(&mut self) -> Option { + let count = self.main.bit_long()?; + let mut properties = Vec::new(); + 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 at most 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 => { + self.main.byte()?; // the kind of reference + Value::Object(Handle::from(self.handles.handle(self.own)?)) + } + 9 => { + let element = self.main.byte()?; + let count = self.count()?; + Value::List( + (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( + (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)) + } +} + +/// A bit range of a record, read most significant bit first. +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; the offset codes count from `reference`. + fn handle(&mut self, reference: u64) -> Option { + let form = self.byte()?; + let mut value = 0u64; + for _ in 0..form & 0x0F { + value = value << 8 | u64::from(self.byte()?); + } + Some(match form >> 4 { + 0x6 => reference.checked_add(1)?, + 0x8 => reference.checked_sub(1)?, + 0xA => reference.checked_add(value)?, + 0xC => reference.checked_sub(value)?, + _ => value, + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/scene/bricscad_parameters/tests.rs b/src/scene/bricscad_parameters/tests.rs new file mode 100644 index 0000000000..393ec3cc1b --- /dev/null +++ b/src/scene/bricscad_parameters/tests.rs @@ -0,0 +1,134 @@ +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") +} + +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), + }, + VisibilityParameter { + name: "LABEL".into(), + states: vec!["Shown".into(), "Hidden".into()], + current: Some(0), + }, + ] + ); +} + +#[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 = decode(data, *raw_dwg_handle_bits, *version).expect("the whole record"); + assert!(whole.get("KeyValues").is_some()); + records += 1; + for length in 0..data.len() { + // Shorter by whole bytes: the streams no longer line up. + let _ = decode(&data[..length], *raw_dwg_handle_bits, *version); + } + assert_eq!(decode(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/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; From 675d7bd29529574d805a71a44a6a7771693d89fc Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:53:35 +0100 Subject: [PATCH 3/4] Properties switch the visibility states of a BricsCAD parametric block reference A reference to a BricsCAD parametric block now lists each visibility parameter's states in Properties, and a state picked there is shown the way BricsCAD shows it, so BricsCAD reads the reference in that state, keeps its parameters and goes on from there: - the reference shows the block when the states are the block's own, a copy of the block that shows them when there is one (BricsCAD shares copies too), or a new anonymous copy: the block's members and every object under its extension dictionary (BricsCAD's parameter objects, the associative network, the draw order) cloned under new handles, with the states set as BricsCAD sets them in its own copies; - its attributes move on or off *SUPPRESS with their definitions; - its entry in model space (a BmAssemblyParameters feature reached through a BDMOBJECT) lists every parameter set on it, as BricsCAD keeps it, and is created, with model space's own parameter objects when there are none. A block BricsCAD never copied gets the tag BricsCAD gives it on its first copy. Picking works for several references at once and is one undo step. Writing BricsCAD's objects needs their records encoded again: the decoder moves into scene::bricscad_parameters::record, keeps everything needed to write a record back bit for bit, and encodes. Besides the plain property lists it reads the constraint manager, BDMOBJECT and the object dependency. --- src/app/block_parameter_properties.rs | 23 +- src/app/bricscad_visibility_tests.rs | 116 +- src/app/properties.rs | 10 +- src/app/visibility.rs | 104 +- src/scene/block_parameter_properties.rs | 2 + src/scene/bricscad_parameters.rs | 431 ++---- src/scene/bricscad_parameters/record.rs | 925 ++++++++++++ src/scene/bricscad_parameters/record_tests.rs | 117 ++ src/scene/bricscad_parameters/switch.rs | 1288 +++++++++++++++++ src/scene/bricscad_parameters/switch_tests.rs | 458 ++++++ src/scene/bricscad_parameters/tests.rs | 15 +- src/scene/model/object.rs | 3 + 12 files changed, 3103 insertions(+), 389 deletions(-) create mode 100644 src/scene/bricscad_parameters/record.rs create mode 100644 src/scene/bricscad_parameters/record_tests.rs create mode 100644 src/scene/bricscad_parameters/switch.rs create mode 100644 src/scene/bricscad_parameters/switch_tests.rs 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 index cabb023715..413129b209 100644 --- a/src/app/bricscad_visibility_tests.rs +++ b/src/app/bricscad_visibility_tests.rs @@ -1,9 +1,10 @@ -//! A reference to a BricsCAD parametric block names the block and shows its +//! 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. +//! 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::PropValue; +use crate::scene::model::object::{BlockParameterComponent, BlockParameterKey, PropValue}; use document::Handle; /// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README), opened @@ -40,23 +41,46 @@ fn select(app: &mut OpenCADStudio, references: &[u64]) { app.refresh_properties(); } -/// The visibility rows as label, value and tooltip. -fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, String)> { +/// 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(|property| property.field == "bricscad_visibility") - .map(|property| match &property.value { - PropValue::ReadOnlyWithTooltip { value, tooltip } => { - (property.label.clone(), value.clone(), tooltip.clone()) - } - other => panic!("{} is {other:?}", property.label), + .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 @@ -71,15 +95,18 @@ fn block_name(app: &OpenCADStudio) -> String { } } -fn rows(lamp: &str, label: &str) -> Vec<(String, String, String)> { - vec![ - ("LAMP".into(), lamp.into(), "On, Off".into()), - ("LABEL".into(), label.into(), "Shown, Hidden".into()), - ] +/// 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_shows_the_states_it_was_set_to_and_names_its_block() { +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"), @@ -87,7 +114,14 @@ fn a_reference_shows_the_states_it_was_set_to_and_names_its_block() { (0x19E, "Off", "Hidden"), ] { select(&mut app, &[reference]); - assert_eq!(visibility_rows(&app), rows(lamp, label), "{reference:X}"); + 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", @@ -95,3 +129,49 @@ fn a_reference_shows_the_states_it_was_set_to_and_names_its_block() { ); } } + +#[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/properties.rs b/src/app/properties.rs index 08dc63885b..4a4eeb66c7 100644 --- a/src/app/properties.rs +++ b/src/app/properties.rs @@ -1073,7 +1073,15 @@ impl OpenCADStudio { custom_properties.extend(Self::visibility_property(doc, handle)); } custom_properties.extend(Self::visible_blocks_property(doc, handle)); - custom_properties.extend(Self::bricscad_visibility_properties(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 1f503d594f..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() @@ -627,30 +636,95 @@ impl OpenCADStudio { } /// The visibility parameters of a reference to a BricsCAD parametric - /// block, one read-only row each with the state the reference shows and - /// the parameter's states as tooltip. They are read from BricsCAD's own - /// objects, which are kept as they were read, so they are not changed - /// here. + /// 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 { - crate::scene::bricscad_parameters::reference_parameters(doc, handle) + 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| Property { - value: PropValue::ReadOnlyWithTooltip { - value: parameter - .current - .and_then(|index| parameter.states.get(index).cloned()) - .unwrap_or_default(), - tooltip: parameter.states.join(", "), - }, - label: parameter.name, - field: "bricscad_visibility", + .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 index f7fddeb470..434466ba26 100644 --- a/src/scene/bricscad_parameters.rs +++ b/src/scene/bricscad_parameters.rs @@ -18,13 +18,18 @@ //! own features hold the state it shows; the members a state hides sit on the //! layer `*SUPPRESS` there. //! -//! Each of these objects is a list of named properties. The data stream holds -//! the count and, per property, a type byte and the value. Names and text -//! values are in the string stream and object references in the handle -//! stream, in the order the properties name them. +//! [`record`] decodes and encodes the objects; `switch` changes the state a +//! reference shows the way BricsCAD does. use document::objects::ObjectType; -use document::{Document, DxfVersion, EntityType, Handle}; +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)] @@ -33,71 +38,86 @@ pub struct VisibilityParameter { 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 { - let Some(manager) = database_entry(document, block, "FEATURE_MANAGER") else { - return Vec::new(); - }; - let Some(Value::List(features)) = - properties(document, manager).and_then(|p| p.take("Features")) - else { - return Vec::new(); - }; - features - .iter() - .filter_map(|feature| match feature { - Value::Object(handle) => visibility_parameter(document, *handle), - _ => None, - }) + 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 Vec::new(); + return None; }; document .block_records .get(&reference.block_name) - .map(|record| visibility_parameters(document, record.handle)) - .unwrap_or_default() + .map(|record| record.handle) } -/// 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")?; - match properties(document, manager)?.take("original.block")? { - Value::Object(original) if !original.is_null() && original != block => Some(original), - _ => None, - } +/// 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 Value::Object(table) = feature.get("ConfigTable")? else { - return None; - }; - let table = properties(document, *table)?; - let Value::List(keys) = table.get("KeyValues")? else { - return None; - }; - let states: Vec = keys + let table = properties(document, feature.get("ConfigTable")?.object()?)?; + let states: Vec = table + .get("KeyValues")? + .items()? .iter() - .map(|key| match key { - Value::Text(state) => Some(state.clone()), - _ => None, - }) + .map(|state| state.text().map(str::to_string)) .collect::>()?; let name = table .text("KeyName") @@ -110,66 +130,27 @@ fn visibility_parameter(document: &Document, feature: Handle) -> Option Option { +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(block)?)?; + let extension = dictionary(document.extension_dictionary_handle(owner)?)?; dictionary(extension.get("BDM_DATABASE")?)?.get(key) } -/// A property value of a BricsCAD object. -#[derive(Debug, Clone, PartialEq)] -pub(crate) enum Value { - Text(String), - Integer(i32), - Real(f64), - Flag(bool), - Byte(u8), - /// A handle written as its bytes in the data stream. - Raw(Vec), - /// A reference through the handle stream. - Object(Handle), - List(Vec), - Map(Vec<(Value, Value)>), -} - -/// The named properties of one BricsCAD object, 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) - } - - fn take(mut self, name: &str) -> Option { - let index = self.0.iter().position(|(key, _)| key == name)?; - Some(self.0.swap_remove(index).1) - } - - fn text(&self, name: &str) -> Option<&str> { - match self.get(name)? { - Value::Text(text) => Some(text), - _ => None, - } - } -} - -/// The properties 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 properties(document: &Document, handle: Handle) -> Option { +/// 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), @@ -178,271 +159,23 @@ pub(crate) fn properties(document: &Document, handle: Handle) -> Option 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); - main.object_type()?; - let own = main.handle(0)?; - // Extended data: blocks of a size, an application handle and the bytes, - // until a size of 0. - loop { - let size = main.bit_short()?; - if size <= 0 { - break; - } - main.handle(0)?; - for _ in 0..size { - main.byte()?; - } - } - let reactors = main.bit_long()?; - let has_extension_dictionary = !main.bit()?; - if 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); - handles.handle(own)?; // owner - for _ in 0..reactors { - handles.handle(own)?; - } - if has_extension_dictionary { - handles.handle(own)?; - } - let mut reader = Reader { - main, - strings: Bits::new(data, strings_at, strings_end), - handles, - own, - }; - let properties = reader.properties()?; - // A record that leaves data unread was not one of these property lists. - (reader.main.pos == reader.main.end).then_some(properties) + record::decode(type_name, data, *raw_dwg_handle_bits, *version) } -/// 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 properties(&mut self) -> Option { - let count = self.main.bit_long()?; - let mut properties = Vec::new(); - 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 at most 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 => { - self.main.byte()?; // the kind of reference - Value::Object(Handle::from(self.handles.handle(self.own)?)) - } - 9 => { - let element = self.main.byte()?; - let count = self.count()?; - Value::List( - (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( - (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)) +/// 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, } } -/// A bit range of a record, read most significant bit first. -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(), - } - } +#[cfg(test)] +mod tests; - /// A handle reference; the offset codes count from `reference`. - fn handle(&mut self, reference: u64) -> Option { - let form = self.byte()?; - let mut value = 0u64; - for _ in 0..form & 0x0F { - value = value << 8 | u64::from(self.byte()?); - } - Some(match form >> 4 { - 0x6 => reference.checked_add(1)?, - 0x8 => reference.checked_sub(1)?, - 0xA => reference.checked_add(value)?, - 0xC => reference.checked_sub(value)?, - _ => value, - }) - } -} +#[cfg(test)] +mod record_tests; #[cfg(test)] -mod tests; +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..0c29d8937b --- /dev/null +++ b/src/scene/bricscad_parameters/switch.rs @@ -0,0 +1,1288 @@ +//! 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()) +} + +fn set_variable( + document: &mut Document, + variable: Handle, + expression: Option, + value: AssocEvalVariant, +) -> Result<()> { + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) = document.objects.get_mut(&variable) + else { + return Err(UNSUPPORTED); + }; + if let Some(expression) = expression { + variable.expression = expression; + } + variable.value = value; + 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..8e8a46bdf8 --- /dev/null +++ b/src/scene/bricscad_parameters/switch_tests.rs @@ -0,0 +1,458 @@ +//! 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); +} diff --git a/src/scene/bricscad_parameters/tests.rs b/src/scene/bricscad_parameters/tests.rs index 393ec3cc1b..d876386121 100644 --- a/src/scene/bricscad_parameters/tests.rs +++ b/src/scene/bricscad_parameters/tests.rs @@ -1,4 +1,5 @@ use super::*; +use document::DxfVersion; /// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README). fn fixture() -> Document { @@ -47,11 +48,13 @@ fn the_definition_names_its_parameters_their_states_and_the_ones_it_shows() { 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), }, ] ); @@ -121,14 +124,18 @@ fn a_cut_record_decodes_to_nothing_rather_than_a_wrong_answer() { if type_name != "BDMDBCONFIGURATIONTABLE" { continue; } - let whole = decode(data, *raw_dwg_handle_bits, *version).expect("the whole record"); - assert!(whole.get("KeyValues").is_some()); + 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 _ = decode(&data[..length], *raw_dwg_handle_bits, *version); + let _ = record::decode(type_name, &data[..length], *raw_dwg_handle_bits, *version); } - assert_eq!(decode(data, *raw_dwg_handle_bits, DxfVersion::AC1021), None); + 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/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 }, } From f8fd5cc8888dfc0b836f48de2f98c9e31f2dc389 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:03:48 +0100 Subject: [PATCH 4/4] A switched BricsCAD block keeps each read of a variable at its value BricsCAD keeps every value dependency (ACDBASSOCVALUEDEPENDENCY) at the value of the variable it reads: all 14,882 of them in 408 drawings made in BricsCAD do. It takes a variable whose new value its reads already hold for unchanged and does not evaluate what depends on it; in model space a stale read keeps it from hiding a member on the next change of state. A copy made for a reference kept the reads of the block it was cloned from. Setting a variable now sets its reads too. --- src/scene/bricscad_parameters/switch.rs | 22 +++++++-- src/scene/bricscad_parameters/switch_tests.rs | 49 +++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs index 0c29d8937b..c21cc54eb0 100644 --- a/src/scene/bricscad_parameters/switch.rs +++ b/src/scene/bricscad_parameters/switch.rs @@ -708,6 +708,10 @@ fn evaluate(expression: &str, columns: &FxHashMap) -> Option { 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, @@ -715,16 +719,28 @@ fn set_variable( value: AssocEvalVariant, ) -> Result<()> { let Some(ObjectType::Associative(AssociativeObject { - data: AssociativeData::Variable(variable), + data: AssociativeData::Variable(object), + reactors, .. })) = document.objects.get_mut(&variable) else { return Err(UNSUPPORTED); }; if let Some(expression) = expression { - variable.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(); + } + } } - variable.value = value; Ok(()) } diff --git a/src/scene/bricscad_parameters/switch_tests.rs b/src/scene/bricscad_parameters/switch_tests.rs index 8e8a46bdf8..660ea5796d 100644 --- a/src/scene/bricscad_parameters/switch_tests.rs +++ b/src/scene/bricscad_parameters/switch_tests.rs @@ -456,3 +456,52 @@ fn an_unknown_parameter_or_state_is_refused_and_a_shown_state_changes_nothing() ); 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"); +}