//! Shared in-memory `DocApiBackend` for the runnable examples. //! //! Lets the examples run without the host binary: an in-process mock document //! (HashMap + a kind table) behind the `InProcess` transport. //! Not for production use — the real backend lives in the host (`src/app/doc_api.rs`). use std::collections::HashMap; use ocs_doc_api::backend::{DocApiBackend, KernelBody}; use ocs_doc_api::{ normalize_layer_name, Aabb, ApiError, ApiResult, Curve2Spec, EntityView, GeometryErrorKind, GeometryRevision, LayerInfo, ObjectId, PlacementSpec, }; #[derive(Clone)] pub struct MockBackend { next_id: u64, revision: u64, undo_steps: u32, bodies: HashMap, kinds: HashMap, /// Stored 2D curve specs so `bounds()` works on non-solid entities too. curves: HashMap, /// Stored text content for Text/MText annotations. text_values: HashMap, /// Stored hatch boundary loops. hatch_boundaries: HashMap>>, /// Stored dimension measurements. dimension_measurements: HashMap, /// Stored insert attributes. attributes_store: HashMap>, /// Stored viewport views (target, height). viewport_views: HashMap, /// Stored XDATA records keyed by (entity id, application name). xdata_store: HashMap<(ObjectId, String), ocs_doc_api::XDataRecord>, /// Stored XRECORD payloads keyed by entity id. xrecord_store: HashMap, /// Stored layer table. layers: HashMap, /// Layer name assigned to each entity. entity_layers: HashMap, } impl Default for MockBackend { fn default() -> Self { let mut backend = Self { next_id: 0, revision: 0, undo_steps: 0, bodies: HashMap::new(), kinds: HashMap::new(), curves: HashMap::new(), text_values: HashMap::new(), hatch_boundaries: HashMap::new(), dimension_measurements: HashMap::new(), attributes_store: HashMap::new(), viewport_views: HashMap::new(), xdata_store: HashMap::new(), xrecord_store: HashMap::new(), layers: HashMap::new(), entity_layers: HashMap::new(), }; backend.layers.insert("0".to_string(), LayerInfo::new("0")); backend } } impl MockBackend { fn alloc(&mut self, kind: &str) -> ObjectId { self.next_id += 1; let id = ObjectId::from_u64(self.next_id); self.kinds.insert(id, kind.to_string()); id } fn body(&self, id: ObjectId) -> ApiResult<&KernelBody> { self.bodies.get(&id).ok_or(ApiError::UnknownId(id)) } #[allow(dead_code)] pub fn undo_steps(&self) -> u32 { self.undo_steps } } /// Coarse bounds for a stored 2D curve spec (mirrors the host's entity_bounds). fn curve_bounds(spec: &Curve2Spec) -> Aabb { match spec { Curve2Spec::Line { start, end, .. } => Aabb { min: [ start[0].min(end[0]), start[1].min(end[1]), start[2].min(end[2]), ], max: [ start[0].max(end[0]), start[1].max(end[1]), start[2].max(end[2]), ], }, Curve2Spec::Circle { centre, radius, .. } => Aabb { min: [centre[0] - radius, centre[1] - radius, centre[2]], max: [centre[0] + radius, centre[1] + radius, centre[2]], }, Curve2Spec::Point { position, .. } => Aabb { min: *position, max: *position, }, Curve2Spec::Polyline { points, .. } => { let mut min = [f64::INFINITY; 3]; let mut max = [f64::NEG_INFINITY; 3]; for p in points { for i in 0..3 { min[i] = min[i].min(p[i]); max[i] = max[i].max(p[i]); } } Aabb { min, max } } Curve2Spec::Arc { centre, radius, .. } => Aabb { min: [centre[0] - radius, centre[1] - radius, centre[2]], max: [centre[0] + radius, centre[1] + radius, centre[2]], }, Curve2Spec::Ellipse { centre, major_axis, .. } => { let r = (major_axis[0] * major_axis[0] + major_axis[1] * major_axis[1] + major_axis[2] * major_axis[2]) .sqrt(); Aabb { min: [centre[0] - r, centre[1] - r, centre[2] - r], max: [centre[0] + r, centre[1] + r, centre[2] + r], } } Curve2Spec::Spline { control_points, .. } => { let mut min = [f64::INFINITY; 3]; let mut max = [f64::NEG_INFINITY; 3]; for p in control_points { for i in 0..3 { min[i] = min[i].min(p[i]); max[i] = max[i].max(p[i]); } } Aabb { min, max } } Curve2Spec::Ray { origin, .. } | Curve2Spec::XLine { origin, .. } => Aabb { min: *origin, max: *origin, }, } } impl DocApiBackend for MockBackend { fn resolve_body(&mut self, id: ObjectId) -> ApiResult { Ok(self.body(id)?.clone()) } fn store_solid(&mut self, body: &KernelBody) -> ApiResult { let id = self.alloc("Solid3D"); self.bodies.insert(id, body.clone()); Ok(id) } fn update_solid(&mut self, id: ObjectId, body: &KernelBody) -> ApiResult<()> { if self.bodies.insert(id, body.clone()).is_none() { return Err(ApiError::UnknownId(id)); } Ok(()) } fn create_many(&mut self, specs: &[ocs_doc_api::EntitySpec]) -> ApiResult> { // Validate per-spec layers up front so the op is atomic. for spec in specs { if let Some(name) = spec.layer() { self.lookup_layer(name).map_err(|e| ApiError::validation( "CreateMany", e.to_string(), ))?; } } let mut next = self.clone(); let ids = specs .iter() .map(|spec| match spec { ocs_doc_api::EntitySpec::Solid(spec) => { next.store_solid(&ocs_doc_api::geom::make_solid(spec)?) } ocs_doc_api::EntitySpec::Curve(spec) => { ocs_doc_api::convert::curve_spec_to_entity(spec)?; next.add_curve(spec) } }) .collect::>>()?; next.push_undo("CreateMany"); next.finalize_op(); *self = next; Ok(ids) } fn transform_many(&mut self, ids: &[ObjectId], placement: &PlacementSpec) -> ApiResult<()> { let mut next = self.clone(); for &id in ids { next.transform_entity(id, placement)?; } next.push_undo("TransformMany"); next.finalize_op(); *self = next; Ok(()) } fn add_curve(&mut self, spec: &Curve2Spec) -> ApiResult { let kind = match spec { Curve2Spec::Line { .. } => "Line", Curve2Spec::Circle { .. } => "Circle", Curve2Spec::Polyline { .. } => "LwPolyline", Curve2Spec::Point { .. } => "Point", Curve2Spec::Arc { .. } => "Arc", Curve2Spec::Ellipse { .. } => "Ellipse", Curve2Spec::Spline { .. } => "Spline", Curve2Spec::Ray { .. } => "Ray", Curve2Spec::XLine { .. } => "XLine", }; let layer = spec .layer() .map(|name| { self.lookup_layer(name).map(|info| info.normalized_name()) }) .transpose()?; let id = self.alloc(kind); self.curves.insert(id, spec.clone()); self.entity_layers .insert(id, layer.unwrap_or_else(|| "0".to_string())); Ok(id) } fn lookup_layer(&self, name: &str) -> ApiResult { let norm = normalize_layer_name(name); if norm.is_empty() { return Err(ApiError::validation("LookupLayer", "empty layer name")); } self.layers .get(&norm) .cloned() .ok_or_else(|| ApiError::validation("LookupLayer", format!("layer '{name}' does not exist"))) } fn add_insert(&mut self, spec: &ocs_doc_api::ops::InsertSpec) -> ApiResult { if spec.block_name.is_empty() { return Err(ApiError::validation("CreateInsert", "empty block name")); } Ok(self.alloc("Insert")) } fn add_viewport(&mut self, spec: &ocs_doc_api::ops::ViewportSpec) -> ApiResult { let id = self.alloc("Viewport"); self.viewport_views .insert(id, (spec.view_target, spec.view_height)); Ok(id) } fn add_text(&mut self, spec: &ocs_doc_api::ops::TextSpec) -> ApiResult { let id = self.alloc("Text"); self.text_values.insert(id, spec.value.clone()); Ok(id) } fn add_mtext(&mut self, spec: &ocs_doc_api::ops::MTextSpec) -> ApiResult { let id = self.alloc("MText"); self.text_values.insert(id, spec.value.clone()); Ok(id) } fn set_text_content(&mut self, id: ObjectId, value: &str) -> ApiResult<()> { if let std::collections::hash_map::Entry::Occupied(mut e) = self.text_values.entry(id) { e.insert(value.to_string()); Ok(()) } else { Err(ApiError::UnknownId(id)) } } fn text_content(&self, id: ObjectId) -> ApiResult { self.text_values .get(&id) .cloned() .ok_or(ApiError::UnknownId(id)) } fn add_hatch(&mut self, spec: &ocs_doc_api::ops::HatchSpec) -> ApiResult { let id = self.alloc("Hatch"); self.hatch_boundaries .insert(id, vec![spec.boundary.clone()]); Ok(id) } fn hatch_boundary(&self, id: ObjectId) -> ApiResult>> { self.hatch_boundaries .get(&id) .cloned() .ok_or(ApiError::UnknownId(id)) } fn add_dimension_linear( &mut self, spec: &ocs_doc_api::ops::DimensionSpec, ) -> ApiResult { let id = self.alloc("Dimension"); let d = ((spec.first_point[0] - spec.second_point[0]).powi(2) + (spec.first_point[1] - spec.second_point[1]).powi(2) + (spec.first_point[2] - spec.second_point[2]).powi(2)) .sqrt(); self.dimension_measurements.insert(id, d); Ok(id) } fn add_dimension_radius( &mut self, spec: &ocs_doc_api::ops::DimensionRadialSpec, ) -> ApiResult { let id = self.alloc("Dimension"); let d = ((spec.center[0] - spec.point[0]).powi(2) + (spec.center[1] - spec.point[1]).powi(2) + (spec.center[2] - spec.point[2]).powi(2)) .sqrt(); self.dimension_measurements.insert(id, d); Ok(id) } fn add_dimension_diameter( &mut self, spec: &ocs_doc_api::ops::DimensionRadialSpec, ) -> ApiResult { self.add_dimension_radius(spec) } fn add_dimension_angular( &mut self, _spec: &ocs_doc_api::ops::DimensionAngularSpec, ) -> ApiResult { let id = self.alloc("Dimension"); self.dimension_measurements.insert(id, 90.0); Ok(id) } fn dimension_measurement(&self, id: ObjectId) -> ApiResult { self.dimension_measurements .get(&id) .copied() .ok_or(ApiError::UnknownId(id)) } fn add_attribute_definition( &mut self, spec: &ocs_doc_api::ops::AttributeDefinitionSpec, ) -> ApiResult { if spec.tag.is_empty() { return Err(ApiError::validation( "CreateAttributeDefinition", "empty tag", )); } Ok(self.alloc("AttributeDefinition")) } fn add_dimension_angular2ln( &mut self, _spec: &ocs_doc_api::ops::DimensionAngularSpec, ) -> ApiResult { let id = self.alloc("Dimension"); self.dimension_measurements.insert(id, 90.0); Ok(id) } fn add_table(&mut self, spec: &ocs_doc_api::ops::TableSpec) -> ApiResult { let cols = spec.data.first().map(|r| r.len()).unwrap_or(0); if spec.data.is_empty() || cols == 0 || spec.data.iter().any(|r| r.len() != cols) { return Err(ApiError::validation( "CreateTable", "table needs a non-empty rectangular grid", )); } Ok(self.alloc("Table")) } fn set_attribute(&mut self, id: ObjectId, tag: &str, value: &str) -> ApiResult<()> { if !self.entity_exists(id) { return Err(ApiError::UnknownId(id)); } let attrs = self.attributes_store.entry(id).or_default(); if let Some(a) = attrs.iter_mut().find(|(t, _)| t == tag) { a.1 = value.to_string(); } else { attrs.push((tag.to_string(), value.to_string())); } Ok(()) } fn attributes(&self, id: ObjectId) -> ApiResult> { self.attributes_store .get(&id) .cloned() .ok_or(ApiError::UnknownId(id)) } fn block_entities(&self, _block_name: &str) -> ApiResult> { Ok(Vec::new()) } fn add_raster_image( &mut self, _spec: &ocs_doc_api::ops::RasterImageSpec, ) -> ApiResult { Ok(self.alloc("RasterImage")) } fn loft( &mut self, sections: &[(cadkernel::space::Plane, Vec)], ) -> ApiResult { if sections.len() < 2 { return Err(ApiError::validation("Loft", "loft needs >= 2 profiles")); } let body = cadkernel::brep::make::cuboid([0.0, 0.0, 0.0], [1.0; 3]) .ok_or_else(|| ApiError::geometry(GeometryErrorKind::InvalidInput, "make cuboid"))?; self.store_solid(&body) } fn set_viewport_view( &mut self, id: ObjectId, view_target: [f64; 3], view_height: f64, ) -> ApiResult<()> { if !self.entity_exists(id) { return Err(ApiError::UnknownId(id)); } self.viewport_views.insert(id, (view_target, view_height)); Ok(()) } fn viewport_view(&self, id: ObjectId) -> ApiResult<([f64; 3], f64)> { self.viewport_views .get(&id) .copied() .ok_or(ApiError::UnknownId(id)) } fn set_xdata( &mut self, id: ObjectId, application_name: &str, record: Option<&ocs_doc_api::XDataRecord>, ) -> ApiResult<()> { if !self.entity_exists(id) { return Err(ApiError::UnknownId(id)); } let key = (id, application_name.to_string()); match record { Some(r) => { self.xdata_store.insert(key, r.clone()); } None => { self.xdata_store.remove(&key); } } Ok(()) } fn xdata( &self, id: ObjectId, application_name: &str, ) -> ApiResult> { if !self.entity_exists(id) { return Err(ApiError::UnknownId(id)); } Ok(self .xdata_store .get(&(id, application_name.to_string())) .cloned()) } fn add_xrecord(&mut self, spec: &ocs_doc_api::XRecordSpec) -> ApiResult { let id = self.alloc("XRecord"); self.xrecord_store.insert(id, spec.clone()); Ok(id) } fn set_xrecord(&mut self, id: ObjectId, spec: &ocs_doc_api::XRecordSpec) -> ApiResult<()> { if !self.object_exists(id) { return Err(ApiError::validation( "SetXRecord", format!("unknown ObjectId {id:?}"), )); } self.xrecord_store.insert(id, spec.clone()); Ok(()) } fn xrecord(&self, id: ObjectId) -> ApiResult> { if !self.object_exists(id) { return Err(ApiError::validation( "GetXRecord", format!("unknown ObjectId {id:?}"), )); } Ok(self.xrecord_store.get(&id).cloned()) } fn create_layer(&mut self, info: &LayerInfo) -> ApiResult<()> { let name = normalize_layer_name(&info.name); if name.is_empty() { return Err(ApiError::validation("CreateLayer", "empty layer name")); } if self.layers.contains_key(&name) { return Err(ApiError::validation( "CreateLayer", format!("layer '{name}' already exists"), )); } let mut stored = info.clone(); stored.name = name.clone(); self.layers.insert(name, stored); Ok(()) } fn update_layer(&mut self, name: &str, info: &LayerInfo) -> ApiResult<()> { let name_upper = normalize_layer_name(name); if !self.layers.contains_key(&name_upper) { return Err(ApiError::validation( "UpdateLayer", format!("layer '{name}' does not exist"), )); } let mut stored = info.clone(); stored.name = name_upper.clone(); self.layers.insert(name_upper, stored); Ok(()) } fn delete_layer(&mut self, name: &str) -> ApiResult<()> { let name_upper = normalize_layer_name(name); if name_upper == "0" { return Err(ApiError::validation("DeleteLayer", "cannot delete layer 0")); } if self.entity_layers.values().any(|l| normalize_layer_name(l) == name_upper) { return Err(ApiError::validation( "DeleteLayer", format!("layer '{name_upper}' still in use"), )); } if self.layers.remove(&name_upper).is_none() { return Err(ApiError::validation( "DeleteLayer", format!("layer '{name}' does not exist"), )); } Ok(()) } fn set_entity_layer(&mut self, id: ObjectId, layer: &str) -> ApiResult<()> { if !self.entity_exists(id) { return Err(ApiError::UnknownId(id)); } let layer_upper = normalize_layer_name(layer); let target = self .layers .get(&layer_upper) .ok_or_else(|| { ApiError::validation( "SetEntityLayer", format!("layer '{layer_upper}' does not exist"), ) })?; if target.flags.locked { return Err(ApiError::Unsupported(format!( "entity {id:?} cannot be moved to locked layer '{layer_upper}'" ))); } self.entity_layers.insert(id, layer_upper); Ok(()) } fn layers(&self) -> ApiResult> { let mut v: Vec<_> = self.layers.values().cloned().collect(); v.sort_by(|a, b| a.name.cmp(&b.name)); Ok(v) } fn entity_layer(&self, id: ObjectId) -> ApiResult { self.entity_layers .get(&id) .cloned() .ok_or(ApiError::UnknownId(id)) } fn add_vertex(&mut self, id: ObjectId, _at: usize, _point: [f64; 3]) -> ApiResult<()> { if self.entity_exists(id) { Ok(()) } else { Err(ApiError::UnknownId(id)) } } fn remove_entity(&mut self, id: ObjectId) -> ApiResult { self.bodies.remove(&id); self.xdata_store.retain(|(k, _), _| *k != id); self.xrecord_store.remove(&id); self.entity_layers.remove(&id); Ok(self.kinds.remove(&id).is_some()) } fn enumerate_entities( &self, kind: Option<&str>, layer: Option<&str>, include_bounds: bool, ) -> ApiResult> { let mut out = Vec::new(); for (id, kind_name) in &self.kinds { if let Some(k) = kind { if !k.eq_ignore_ascii_case(kind_name) { continue; } } let entity_layer = self .entity_layers .get(id) .cloned() .unwrap_or_else(|| "0".to_string()); if let Some(l) = layer { if !l.eq_ignore_ascii_case(&entity_layer) { continue; } } let bounds = if include_bounds { self.curves.get(id).map(curve_bounds) } else { None }; out.push(EntityView { id: *id, kind: kind_name.clone(), layer: entity_layer, bounds, }); } Ok(out) } fn point_position(&self, id: ObjectId) -> ApiResult<[f64; 3]> { let spec = self.curves.get(&id).ok_or(ApiError::UnknownId(id))?; match spec { Curve2Spec::Point { position, .. } => Ok(*position), _ => Err(ApiError::Unsupported( "GetPointPosition is only for Point entities".into(), )), } } fn line_geometry(&self, id: ObjectId) -> ApiResult<([f64; 3], [f64; 3])> { let spec = self.curves.get(&id).ok_or(ApiError::UnknownId(id))?; match spec { Curve2Spec::Line { start, end, .. } => Ok((*start, *end)), _ => Err(ApiError::Unsupported( "GetLineGeometry is only for Line entities".into(), )), } } fn get_entity(&mut self, id: ObjectId) -> ApiResult { let kind = self.kinds.get(&id).ok_or(ApiError::UnknownId(id))?.clone(); let layer = self .entity_layers .get(&id) .cloned() .unwrap_or_else(|| "0".to_string()); let bounds = self.bodies.get(&id).and_then(|b| { cadkernel::brep::body_bounds(b).map(|bb| Aabb { min: bb.min, max: bb.max, }) }); Ok(EntityView { id, kind, layer, bounds, }) } fn transform_entity(&mut self, id: ObjectId, placement: &PlacementSpec) -> ApiResult<()> { if !self.entity_exists(id) { return Err(ApiError::UnknownId(id)); } if let Some(body) = self.bodies.get(&id).cloned() { let place = cadkernel::brep::Placement { x_axis: placement.x_axis, y_axis: placement.y_axis, z_axis: placement.z_axis, origin: placement.origin, }; let moved = cadkernel::brep::transform(&body, &place).ok_or_else(|| { ApiError::geometry(GeometryErrorKind::InvalidInput, "transform failed") })?; self.bodies.insert(id, moved); } Ok(()) } fn profile_curves(&self, _id: ObjectId) -> ApiResult> { Err(ApiError::Unsupported("profiles not mocked".into())) } fn bounds(&mut self, id: ObjectId) -> ApiResult { // Solids via the kernel body; 2D curves from their stored spec. if let Some(body) = self.bodies.get(&id) { let bb = cadkernel::brep::body_bounds(body) .ok_or_else(|| ApiError::geometry(GeometryErrorKind::Empty, "no bounds"))?; return Ok(Aabb { min: bb.min, max: bb.max, }); } if let Some(spec) = self.curves.get(&id) { return Ok(curve_bounds(spec)); } Err(ApiError::UnknownId(id)) } fn centroid(&mut self, id: ObjectId) -> ApiResult<[f64; 3]> { let body = self.body(id)?; Ok(mesh_vc(&cadkernel::brep::mesh_body(body, 0.5, 1e-3)).1) } fn volume(&mut self, id: ObjectId) -> ApiResult { let body = self.body(id)?; Ok(mesh_vc(&cadkernel::brep::mesh_body(body, 0.5, 1e-3)).0) } fn entity_exists(&self, id: ObjectId) -> bool { self.kinds.contains_key(&id) } fn object_exists(&self, id: ObjectId) -> bool { self.xrecord_store.contains_key(&id) } fn revision(&self) -> GeometryRevision { GeometryRevision(self.revision) } fn push_undo(&mut self, _label: &str) {} fn finalize_op(&mut self) { self.undo_steps += 1; self.revision += 1; } } /// Signed volume + centroid of a closed mesh — delegates to the crate's single /// source of truth (divergence theorem) so the example mock can't drift. fn mesh_vc(mesh: &cadkernel::brep::Mesh) -> (f64, [f64; 3]) { ocs_doc_api::geom::mesh_volume_centroid(mesh) }