Skip to main content

openbim_ifc_binding_core/authoring/
copying.rs

1//! Copying a product with what it solely owns, and appending entities from
2//! another model (#479, feature `author`).
3//!
4//! [`IfcModel::copy_product`] runs the facade's `AuthorOp::CopyProduct` as
5//! a batch of one; [`IfcModel::append`] runs `ifc::apply_append`. With
6//! `dry_run` each only plans: the report is the same and the model is
7//! unchanged. Every host returns the [`CopyReport`] as its record.
8//!
9//! Refusals: `missing-entity` for no such product or source root;
10//! `wrong-entity-type` for a product that is neither an `IfcProduct` nor
11//! an `IfcTypeObject`; `unsupported` for an offset onto a placement that is
12//! not a local placement with a Cartesian location, a moved copy whose
13//! openings, fillings or ports are not placed relative to it, and models
14//! whose length or plane angle units differ (convert one with
15//! `convert_length_unit` first, #469);
16//! `unsupported-schema` for an entity the target release cannot hold (a
17//! type or attribute it lacks, a constant it does not know); `invalid-value`
18//! for a `GlobalId` the target holds already, kept, and for an unknown
19//! `GlobalId` mode; `feature-disabled` without the `author` feature.
20
21use crate::record::{Field, Record, ToRecord};
22use crate::{BindingError, IfcModel};
23
24/// What [`IfcModel::copy_product`] copies and joins (the facade's
25/// `CopyProductOptions`).
26#[derive(Debug, Clone, Copy, PartialEq)]
27#[non_exhaustive]
28pub struct CopyProductOptions {
29    /// Move the copy by this vector, in its parent placement's frame.
30    pub offset: Option<[f64; 3]>,
31    /// Place the copy by this `IfcObjectPlacement` instead.
32    pub placement: Option<u64>,
33    /// Copy the openings voiding the product.
34    pub openings: bool,
35    /// Copy the doors and windows filling a copied opening.
36    pub fillings: bool,
37    /// Contain the copy in the original's spatial structure element.
38    pub container: bool,
39    /// Make the copy a part of the original's whole.
40    pub aggregate: bool,
41    /// Report what would be copied without changing the model.
42    pub dry_run: bool,
43}
44
45impl Default for CopyProductOptions {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl CopyProductOptions {
52    /// In place, with openings and fillings, in the original's container
53    /// and whole, applied: the default.
54    #[must_use]
55    pub const fn new() -> Self {
56        Self {
57            offset: None,
58            placement: None,
59            openings: true,
60            fillings: true,
61            container: true,
62            aggregate: true,
63            dry_run: false,
64        }
65    }
66}
67
68/// How [`IfcModel::append`] copies from another model (the facade's
69/// `AppendOptions`).
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct AppendOptions {
73    /// `keep` (the default), `regenerate`, `regenerate-colliding` or
74    /// `merge`.
75    pub global_ids: String,
76    /// Reuse the target's equal units.
77    pub reuse_units: bool,
78    /// Reuse the target's equal representation contexts.
79    pub reuse_contexts: bool,
80    /// Reuse the target's equal owner history and actors.
81    pub reuse_owner_history: bool,
82    /// Reuse the target's equal material definitions.
83    pub reuse_materials: bool,
84    /// Reuse the target's equal presentation styles.
85    pub reuse_styles: bool,
86    /// Report what would be copied without changing the model.
87    pub dry_run: bool,
88}
89
90impl Default for AppendOptions {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96impl AppendOptions {
97    /// Keep `GlobalId`s, reuse every equal resource, applied: the default.
98    #[must_use]
99    pub fn new() -> Self {
100        Self {
101            global_ids: "keep".to_owned(),
102            reuse_units: true,
103            reuse_contexts: true,
104            reuse_owner_history: true,
105            reuse_materials: true,
106            reuse_styles: true,
107            dry_run: false,
108        }
109    }
110}
111
112/// One original and its copy (or the target entity reused for it).
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct CopiedEntity {
115    /// The original's id: in this model for a copy, in the source for an
116    /// append.
117    pub original: u64,
118    /// The copy's id.
119    pub copy: u64,
120    /// Its type, upper case.
121    pub type_name: String,
122}
123
124/// What a copy or an append did, or, for a dry run, would do.
125#[derive(Debug, Clone, Default, PartialEq, Eq)]
126pub struct CopyReport {
127    /// The product's copy; `None` for an append.
128    pub copy: Option<u64>,
129    /// Every entity copied, in the order the copies were made.
130    pub copied: Vec<CopiedEntity>,
131    /// Append: source entities the target holds an equal one of, with it.
132    pub reused: Vec<CopiedEntity>,
133    /// Existing relationships and layers the copies joined.
134    pub joined: Vec<u64>,
135    /// Relationships of an original the copies do not get.
136    pub skipped: Vec<u64>,
137    /// Append: copies whose `GlobalId` was regenerated.
138    pub regenerated: Vec<u64>,
139    /// Whether the model was changed: `false` for a dry run.
140    pub applied: bool,
141}
142
143impl ToRecord for CopiedEntity {
144    fn to_record(&self) -> Record {
145        Record::new(
146            "CopiedEntity",
147            vec![
148                ("original", Field::Id(self.original)),
149                ("copy", Field::Id(self.copy)),
150                ("type_name", Field::Text(self.type_name.clone())),
151            ],
152        )
153    }
154}
155
156impl ToRecord for CopyReport {
157    fn to_record(&self) -> Record {
158        Record::new(
159            "CopyReport",
160            vec![
161                ("copy", Field::id(self.copy)),
162                ("copied", Field::records(&self.copied)),
163                ("reused", Field::records(&self.reused)),
164                ("joined", Field::ids(self.joined.iter().copied())),
165                ("skipped", Field::ids(self.skipped.iter().copied())),
166                ("regenerated", Field::ids(self.regenerated.iter().copied())),
167                ("applied", Field::Bool(self.applied)),
168            ],
169        )
170    }
171}
172
173impl IfcModel {
174    /// Copy product (or type object) `id` with everything it solely owns,
175    /// as one checked transaction: its placement (moved or replaced by
176    /// option), representation, own property sets, material usage, ports
177    /// and, by option, openings and fillings; joining its type, shared
178    /// property sets, classification and, by option, container and whole.
179    /// With `options.dry_run`, only report. See the module docs for the
180    /// refusals.
181    pub fn copy_product(
182        &mut self,
183        id: u64,
184        options: CopyProductOptions,
185    ) -> Result<CopyReport, BindingError> {
186        #[cfg(feature = "author")]
187        {
188            let seed = crate::relations::fresh_seed()?;
189            self.tracked(|this| this.copy_product_seeded(id, options, seed))
190        }
191        #[cfg(not(feature = "author"))]
192        {
193            let _ = (id, options);
194            Err(BindingError::FeatureDisabled("author"))
195        }
196    }
197
198    /// [`Self::copy_product`] with the seed the copy's new `GlobalId`s
199    /// derive from: a host with entropy of its own (the browser) passes it.
200    /// The seed names the batch; reusing it on a model that holds its
201    /// `GlobalId`s is refused (`invalid-value`).
202    pub fn copy_product_seeded(
203        &mut self,
204        id: u64,
205        options: CopyProductOptions,
206        seed: u128,
207    ) -> Result<CopyReport, BindingError> {
208        #[cfg(feature = "author")]
209        {
210            let placement = match (options.offset, options.placement) {
211                (Some(_), Some(_)) => {
212                    return Err(BindingError::InvalidValue(
213                        "copy_product takes `offset` or `placement`, not both".into(),
214                    ))
215                }
216                (Some(offset), None) => ifc::CopyPlacement::Offset(offset),
217                (None, Some(placement)) => ifc::CopyPlacement::At(ifc::EntityId(placement)),
218                (None, None) => ifc::CopyPlacement::Same,
219            };
220            let op = ifc::AuthorOp::CopyProduct {
221                product: ifc::EntityId(id),
222                options: ifc::CopyProductOptions::new()
223                    .placement(placement)
224                    .openings(options.openings)
225                    .fillings(options.fillings)
226                    .container(options.container)
227                    .aggregate(options.aggregate),
228            };
229            let schema = self.declared_schema()?;
230            let ops = [op];
231            let (ids, copies) = if options.dry_run {
232                let staged = ifc::stage_authoring(&self.inner, schema, &ops, seed)
233                    .map_err(super::convert::error)?;
234                (staged.ids, staged.copies)
235            } else {
236                let outcome = self
237                    .tracked(|this| ifc::apply_authoring(&mut this.inner, schema, &ops, seed))
238                    .map_err(super::convert::error)?;
239                (outcome.ids, outcome.copies)
240            };
241            let report = copies
242                .into_iter()
243                .next()
244                .flatten()
245                .ok_or_else(|| BindingError::InvalidModel("the copy made no report".into()))?;
246            let mut report = convert(report, !options.dry_run);
247            report.copy = ids.first().copied().flatten().map(|id| id.0);
248            Ok(report)
249        }
250        #[cfg(not(feature = "author"))]
251        {
252            let _ = (id, options, seed);
253            Err(BindingError::FeatureDisabled("author"))
254        }
255    }
256
257    /// Copy `roots` of `source` into this model with what belongs to them,
258    /// as one checked transaction: what they reference, their property
259    /// sets, type, material and classification, openings, fillings and
260    /// ports; units, contexts, owner history, materials and styles equal
261    /// to this model's are reused. Relationships to objects not copied are
262    /// skipped and reported. With `options.dry_run`, only report. See the
263    /// module docs for the refusals.
264    pub fn append(
265        &mut self,
266        source: &IfcModel,
267        roots: &[u64],
268        options: &AppendOptions,
269    ) -> Result<CopyReport, BindingError> {
270        #[cfg(feature = "author")]
271        {
272            let seed = crate::relations::fresh_seed()?;
273            self.tracked(|this| this.append_seeded(source, roots, options, seed))
274        }
275        #[cfg(not(feature = "author"))]
276        {
277            let _ = (source, roots, options);
278            Err(BindingError::FeatureDisabled("author"))
279        }
280    }
281
282    /// [`Self::append`] with the seed new `GlobalId`s derive from: a host
283    /// with entropy of its own (the browser) passes it. The seed names the
284    /// batch; reusing it on a model that holds its `GlobalId`s is refused
285    /// (`invalid-value`).
286    pub fn append_seeded(
287        &mut self,
288        source: &IfcModel,
289        roots: &[u64],
290        options: &AppendOptions,
291        seed: u128,
292    ) -> Result<CopyReport, BindingError> {
293        #[cfg(feature = "author")]
294        {
295            let global_ids = ifc::GlobalIdMode::parse(&options.global_ids).ok_or_else(|| {
296                BindingError::InvalidValue(format!(
297                    "GlobalId mode `{}` is not keep, regenerate, regenerate-colliding or merge",
298                    options.global_ids
299                ))
300            })?;
301            let mut reuse = ifc::ReuseOptions::none();
302            reuse.units = options.reuse_units;
303            reuse.contexts = options.reuse_contexts;
304            reuse.owner_history = options.reuse_owner_history;
305            reuse.materials = options.reuse_materials;
306            reuse.styles = options.reuse_styles;
307            let facade = ifc::AppendOptions::new()
308                .global_ids(global_ids)
309                .reuse(reuse);
310            let (target_schema, source_schema) =
311                (self.declared_schema()?, source.declared_schema()?);
312            let roots: Vec<ifc::EntityId> = roots.iter().copied().map(ifc::EntityId).collect();
313            let report = if options.dry_run {
314                ifc::stage_append(
315                    &self.inner,
316                    target_schema,
317                    &source.inner,
318                    source_schema,
319                    &roots,
320                    &facade,
321                    seed,
322                )
323                .map_err(super::convert::error)?
324                .report
325            } else {
326                self.tracked(|this| {
327                    ifc::apply_append(
328                        &mut this.inner,
329                        target_schema,
330                        &source.inner,
331                        source_schema,
332                        &roots,
333                        &facade,
334                        seed,
335                    )
336                })
337                .map_err(super::convert::error)?
338                .report
339            };
340            Ok(convert(report, !options.dry_run))
341        }
342        #[cfg(not(feature = "author"))]
343        {
344            let _ = (source, roots, options, seed);
345            Err(BindingError::FeatureDisabled("author"))
346        }
347    }
348}
349
350#[cfg(feature = "author")]
351fn convert(report: ifc::CopyReport, applied: bool) -> CopyReport {
352    let entities = |list: Vec<ifc::CopiedEntity>| {
353        list.into_iter()
354            .map(|entity| CopiedEntity {
355                original: entity.original.0,
356                copy: entity.copy.0,
357                type_name: entity.type_name,
358            })
359            .collect()
360    };
361    let ids = |list: Vec<ifc::EntityId>| list.into_iter().map(|id| id.0).collect();
362    CopyReport {
363        copy: None,
364        copied: entities(report.copied),
365        reused: entities(report.reused),
366        joined: ids(report.joined),
367        skipped: ids(report.skipped),
368        regenerated: ids(report.regenerated),
369        applied,
370    }
371}