From b74c489a2392634d27303459815765f5389a59fd Mon Sep 17 00:00:00 2001 From: schoeller Date: Tue, 24 Nov 2026 22:49:01 +0100 Subject: [PATCH 1/2] Civil: write and read an empty TIN surface's shell (W2-2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A surface the application has not built keeps no triangulation — only its shell: the four bounding corners at the drawing extremes, with no incident triangle and no triangles (the tutorials' Surface-2.dwg "EG", and the snapshot-only surface of Pipe Networks-3B.dwg). The reader refused the block (fewer than 7 vertices, zero triangles) and reported None, so a census of the drawing lost the surface; the writer had no way to add one. The reader now decodes the shell as a corner-only TinSurface (four vertices, no triangles) — empty, not None — and a snapshot of it the same way. The writer emits the app's own form for a surface with no data: add_empty_tin_surface, and add_tin_surface_with accepts definitions that bring no geometry (a snapshot-only surface) by storing the shell. Corners of a shell carry the bare corner flag (0x40) and -1 as their incident triangle, as the app stores them. Closes the D016 gap W2-2: the built Surface-2 now opens in Civil 3D with census 1 == 1 surfaces, audit clean, and the application reads the shell back as name EG, 0 vertices, 0 triangles — identical to the oracle. --- src/classes/civil/create/tin.rs | 110 ++++++++++++++++++++++++++++---- src/classes/civil/mod.rs | 11 ++-- src/classes/civil/tin.rs | 52 ++++++++++++++- 3 files changed, 154 insertions(+), 19 deletions(-) diff --git a/src/classes/civil/create/tin.rs b/src/classes/civil/create/tin.rs index 25a129b1..601326e7 100644 --- a/src/classes/civil/create/tin.rs +++ b/src/classes/civil/create/tin.rs @@ -80,6 +80,23 @@ pub(super) fn triangulate_in(extent: &[Vector3], points: &[Vector3]) -> Triangul } impl Triangulation { + /// The triangulation of a surface with no data: the four bounding + /// corners at the drawing extremes, each with no incident triangle, and + /// no triangles — the record the application writes for a surface it + /// has not built (the "EG" shell of the tutorials' `Surface-2.dwg`). + fn empty() -> Triangulation { + let m = f64::MAX; + Triangulation { + vertices: vec![ + Vector3::new(m, m, m), + Vector3::new(-m, m, m), + Vector3::new(-m, -m, -m), + Vector3::new(m, -m, -m), + ], + triangles: Vec::new(), + } + } + /// The triangle across the edge that starts at each vertex. fn neighbors(&self) -> Vec<[i32; 3]> { let mut by_edge = std::collections::HashMap::new(); @@ -291,18 +308,23 @@ pub(super) fn write_surface(doc: &mut CadDocument, common: EntityCommon, name: & let seed = common.handle.value() ^ tin.vertices.len() as u64; let triangulation = |w: &mut DwgMergedWriter, tin: &Triangulation, hidden: &[bool]| { let neighbors = tin.neighbors(); - let mut incident = vec![0i32; tin.vertices.len()]; + // A vertex of a shell surface has no incident triangle (-1); on a + // built surface every vertex lies on one. + let mut incident = vec![-1i32; tin.vertices.len()]; for (t, tri) in tin.triangles.iter().enumerate() { for v in tri { incident[*v] = t as i32; } } + // A built surface's corners carry the hidden-triangle bits (0x8440); + // the shell stores the bare corner flag (0x40), the app's form. + let corner = if tin.triangles.is_empty() { 0x40 } else { CORNER }; w.write_bit_long(tin.vertices.len() as i32); for c in 0..4 { w.write_bit_long(c); } for (i, v) in tin.vertices.iter().enumerate() { - w.write_raw_long((if i < 4 { CORNER } else { POINT }) as i32); + w.write_raw_long((if i < 4 { corner } else { POINT }) as i32); w.write_raw_long(incident[i]); w.write_raw_double(v.x); w.write_raw_double(v.y); @@ -432,13 +454,27 @@ fn with_source_geometry(doc: &CadDocument, definitions: &[TinDefinition]) -> Res /// Adds a TIN surface triangulated from `points` (three or more, distinct /// in plan) with the drawing's default surface style, on `layer` (layer -/// "0" when `None`). A drawing without a surface style collection gets -/// one (`tree.rs`). +/// "0" when `None`). An empty `points` slice adds the empty surface's +/// shell (see [`add_empty_tin_surface`]). A drawing without a surface +/// style collection gets one (`tree.rs`). pub fn add_tin_surface(doc: &mut CadDocument, name: &str, points: &[Vector3], layer: Option<&str>) -> Result { + if points.is_empty() { + return add_empty_tin_surface(doc, name, layer); + } let points = TinDefinition { operation: TinOperation::AddPoints(points.to_vec()), id: [0; 16], texts: Vec::new(), sources: Vec::new() }; add_tin_surface_with(doc, name, &[points], false, layer) } +/// Adds an empty TIN surface: the shell the application stores for a +/// surface it has not built (the four bounding corners at the drawing +/// extremes, no triangles), with the drawing's default surface style, on +/// `layer` (layer "0" when `None`). Reading it back yields a +/// [`TinSurface`][crate::classes::civil::TinSurface] with four vertices and +/// no triangles. +pub fn add_empty_tin_surface(doc: &mut CadDocument, name: &str, layer: Option<&str>) -> Result { + add_tin_surface_with(doc, name, &[], false, layer) +} + /// Adds a TIN surface built from `definitions` in order (each one's `id` /// is replaced by a new one; texts and sources are written as given), /// rebuilding itself on a source change when `auto_rebuild`. The stored @@ -454,19 +490,40 @@ pub fn add_tin_surface_with(doc: &mut CadDocument, name: &str, definitions: &[Ti } } let resolved = with_source_geometry(doc, definitions)?; + // Whether the definitions bring any geometry in: a surface without any + // stores the empty shell (the four bounding corners, no triangles), as + // the application does for a surface it has not built. + let geometry = |ds: &[TinDefinition]| { + ds.iter().any(|d| match &d.operation { + TinOperation::AddPoints(p) | TinOperation::DrawingObjects { points: p, .. } => !p.is_empty(), + TinOperation::Breaklines(_, l) | TinOperation::Contours(l) | TinOperation::Boundary { lines: l, .. } => l.polylines.iter().flatten().next().is_some(), + TinOperation::AddVertex(_) | TinOperation::VertexElevation(_) => true, + _ => false, + }) + }; let finite = |p: &Vector3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite(); - let all_finite = resolved.iter().all(|d| match &d.operation { - TinOperation::AddPoints(p) | TinOperation::DrawingObjects { points: p, .. } => p.iter().all(finite), - TinOperation::Breaklines(_, l) | TinOperation::Contours(l) | TinOperation::Boundary { lines: l, .. } => l.polylines.iter().flatten().all(finite), - TinOperation::AddVertex(p) | TinOperation::VertexElevation(p) => finite(p), - _ => true, - }); - let (tin, hidden) = all_finite.then(|| super::tin_build::build(&resolved)).flatten().ok_or_else(|| invalid("a surface needs three or more finite points, distinct in plan"))?; + let built = |ds: &[TinDefinition]| -> Result<(Triangulation, Vec), DxfError> { + let all_finite = ds.iter().all(|d| match &d.operation { + TinOperation::AddPoints(p) | TinOperation::DrawingObjects { points: p, .. } => p.iter().all(finite), + TinOperation::Breaklines(_, l) | TinOperation::Contours(l) | TinOperation::Boundary { lines: l, .. } => l.polylines.iter().flatten().all(finite), + TinOperation::AddVertex(p) | TinOperation::VertexElevation(p) => finite(p), + _ => true, + }); + if geometry(ds) { + if !all_finite { + return Err(invalid("a surface needs three or more finite points, distinct in plan")); + } + super::tin_build::build(ds).ok_or_else(|| invalid("a surface needs three or more finite points, distinct in plan")) + } else { + Ok((Triangulation::empty(), Vec::new())) + } + }; + let (tin, hidden) = built(&resolved)?; // A snapshot keeps what the definitions before it build. let snapshots: Vec = definitions.iter().enumerate().filter(|(_, d)| matches!(d.operation, TinOperation::Kind40(_))).map(|(i, _)| i).collect(); let snapshot = match snapshots.as_slice() { [] => None, - [k] => Some(super::tin_build::build(&resolved[..*k]).ok_or_else(|| invalid("a snapshot needs a surface of three or more points before it"))?), + [k] => Some(built(&resolved[..*k]).map_err(|_| invalid("a snapshot needs a surface of three or more points before it"))?), _ => return Err(invalid("a surface holds one snapshot")), }; let layer = layer.unwrap_or("0"); @@ -631,4 +688,33 @@ mod tests { assert_eq!((now.vertices.len(), kept.vertices.len(), now.vertices[4].position.z, kept.vertices[4].position.z), (13, 13, 7.0, 5.0)); assert_eq!(a.tin_definitions().unwrap().0.len(), 3); } + + /// An empty surface stores the shell (four corners at the drawing + /// extremes, no triangles) and decodes back as empty, not `None`; so + /// does the snapshot of a snapshot-only surface (Pipe Networks-3B). + #[test] + fn an_empty_surface_round_trips_as_a_shell() { + let mut doc = drawing(); + let h = crate::classes::civil::add_empty_tin_surface(&mut doc, "EG", None).unwrap(); + let snapshot_only = [TinDefinition { operation: TinOperation::Kind40(0), id: [0; 16], texts: Vec::new(), sources: Vec::new() }]; + let hs = add_tin_surface_with(&mut doc, "SNAP", &snapshot_only, false, None).unwrap(); + let path = std::env::temp_dir().join(format!("civil-tin-empty-{}.dwg", std::process::id())); + DwgWriter::write_to_file(&path, &doc).unwrap(); + let back = DwgReader::from_file(&path).unwrap().read().unwrap(); + let _ = std::fs::remove_file(&path); + for (handle, snapshot) in [(h, false), (hs, true)] { + let Some(crate::entities::EntityType::Extended(x)) = back.get_entity(handle) else { panic!() }; + let crate::entities::ExtendedEntityData::Arch(a) = &x.data else { panic!() }; + let shell = a.tin_surface().unwrap(); + assert_eq!(shell.vertices.len(), 4); + assert!(shell.triangles.is_empty()); + let m = f64::MAX; + assert_eq!(shell.vertices[0].position, Vector3::new(m, m, m)); + assert_eq!(shell.vertices[3].position, Vector3::new(m, -m, -m)); + assert_eq!(a.tin_snapshot().is_some(), snapshot); + if snapshot { + assert_eq!(a.tin_snapshot().unwrap().triangles.len(), 0); + } + } + } } diff --git a/src/classes/civil/mod.rs b/src/classes/civil/mod.rs index c7fc1580..b259e2af 100644 --- a/src/classes/civil/mod.rs +++ b/src/classes/civil/mod.rs @@ -35,7 +35,7 @@ pub use alignment::{ display_station, AlignmentAnchor, AlignmentCriteria, AlignmentElement, AlignmentType, OffsetParameters, OffsetRegion, WideningTransition, AlignmentElementKind, AlignmentPiece, DesignSpeed, GeometryPoint, SpiralShape, StationEquation, CriticalStationData, SuperelevationCurveData, SuperelevationView}; pub use cogo::{CogoPoint, PointGroupClassification, PointGroupOverrides, PropertyValue, UserProperty}; -pub use create::{add_tin_surface_with, add_assembly, add_pkt_subassembly, add_pkt_subassembly_on, PktSource, add_alignment, add_alignment_with_curves, add_offset_alignment, add_offset_alignment_with_widenings, Widening, add_alignment_of_kind, add_design_speeds, add_station_equations, add_superelevation, CriticalStation, CriticalStationKind, SuperelevationCurve, AlignmentKind, VertexCurve, add_corridor, add_corridor_with, add_cogo_point, create_cogo_point, point_creation_layer, NO_ELEVATION, add_intersection, add_point_group, add_point_group_query, add_profile, add_profile_entities, add_profile_with_curves, add_static_profile, add_surface_profile, ProfileEntity, VerticalCurve, add_profile_view, add_profile_view_with_bands, add_profile_view_with_range, BandKind, BandStagger, ProfileViewBand, add_sample_line, add_sample_line_through, add_sample_line_group, add_sections, add_section_view, add_site, add_alignment_on_site, add_feature_line, add_parcel, add_feature_line_vertices, FeatureLineVertex, add_tin_surface, cogo_points, ensure_civil, remove_cogo_point, set_cogo_point, set_cogo_point_name, set_point_group, set_point_group_overrides, set_point_group_query, Comparison, PointAttribute, PointQuery, QueryConstant, QueryExpression, add_lot_line, add_pipe, add_pipe_network, add_pipe_of_family, add_structure, add_structure_of_family, connect_pipe, network_part_families, add_pressure_appurtenance, add_pressure_arc_pipe, add_pressure_cross, add_pressure_fitting, add_pressure_network, add_pressure_part, add_pressure_pipe, add_pressure_pipe_of_size, add_pressure_tee, connect_pressure_parts, pressure_part_descriptions, add_profile_view_style, add_profile_view_with_style, add_offset_profile, add_section_view_group, add_profile_view_style_with, set_feature_line_vertices, set_cogo_point_label_style, add_label_style, add_point_label_style, label_style, LabelStyle, add_intersection_with, add_intersection_with_curb_returns, IntersectionOffsets, CURB_RETURN_MARGIN, add_curb_return, add_curb_return_with, CurbReturnCurve, add_point_choice_property, add_point_property, add_point_property_classification, point_properties, set_cogo_point_property, add_pipe_of_size, network_pipe_sizes, add_structure_of_size, network_structure_size_fields, StructureSizeChoice, add_intersection_with_curb_return_profiles, CurbReturnProfiles}; +pub use create::{add_empty_tin_surface, add_tin_surface_with, add_assembly, add_pkt_subassembly, add_pkt_subassembly_on, PktSource, add_alignment, add_alignment_with_curves, add_offset_alignment, add_offset_alignment_with_widenings, Widening, add_alignment_of_kind, add_design_speeds, add_station_equations, add_superelevation, CriticalStation, CriticalStationKind, SuperelevationCurve, AlignmentKind, VertexCurve, add_corridor, add_corridor_with, add_cogo_point, create_cogo_point, point_creation_layer, NO_ELEVATION, add_intersection, add_point_group, add_point_group_query, add_profile, add_profile_entities, add_profile_with_curves, add_static_profile, add_surface_profile, ProfileEntity, VerticalCurve, add_profile_view, add_profile_view_with_bands, add_profile_view_with_range, BandKind, BandStagger, ProfileViewBand, add_sample_line, add_sample_line_through, add_sample_line_group, add_sections, add_section_view, add_site, add_alignment_on_site, add_feature_line, add_parcel, add_feature_line_vertices, FeatureLineVertex, add_tin_surface, cogo_points, ensure_civil, remove_cogo_point, set_cogo_point, set_cogo_point_name, set_point_group, set_point_group_overrides, set_point_group_query, Comparison, PointAttribute, PointQuery, QueryConstant, QueryExpression, add_lot_line, add_pipe, add_pipe_network, add_pipe_of_family, add_structure, add_structure_of_family, connect_pipe, network_part_families, add_pressure_appurtenance, add_pressure_arc_pipe, add_pressure_cross, add_pressure_fitting, add_pressure_network, add_pressure_part, add_pressure_pipe, add_pressure_pipe_of_size, add_pressure_tee, connect_pressure_parts, pressure_part_descriptions, add_profile_view_style, add_profile_view_with_style, add_offset_profile, add_section_view_group, add_profile_view_style_with, set_feature_line_vertices, set_cogo_point_label_style, add_label_style, add_point_label_style, label_style, LabelStyle, add_intersection_with, add_intersection_with_curb_returns, IntersectionOffsets, CURB_RETURN_MARGIN, add_curb_return, add_curb_return_with, CurbReturnCurve, add_point_choice_property, add_point_property, add_point_property_classification, point_properties, set_cogo_point_property, add_pipe_of_size, network_pipe_sizes, add_structure_of_size, network_structure_size_fields, StructureSizeChoice, add_intersection_with_curb_return_profiles, CurbReturnProfiles}; pub use corridor::{CorridorBaseline, CorridorBoundary, CorridorDefinition, CorridorRegion, CorridorSurfaceDefinition, CurveStations, RegionFrequency, RegionTarget, TargetCurveStations, TargetKind}; pub use grading::{CriteriaValue, GradingCriteria, GradingEntity, GradingGroup, GradingGroupRecord, GradingGroupTree}; pub use intersection::IntersectionLayout; @@ -233,7 +233,8 @@ impl ArchEntityData { } /// The triangulation a TIN surface's snapshot keeps; `None` without a - /// snapshot. + /// snapshot. A snapshot of a surface with no triangulation decodes as a + /// corner-only [`TinSurface`] (four vertices, no triangles). pub fn tin_snapshot(&self) -> Option { if self.civil_kind() != Some(CivilKind::TinSurface) { return None; @@ -244,8 +245,10 @@ impl ArchEntityData { /// Triangulation stored by a Civil 3D TIN surface. /// - /// `None` for other classes or when the body has no readable - /// triangulation. + /// `None` for other classes. A surface the application has not built + /// keeps only its shell (the four bounding corners, no triangles — + /// `Surface-2.dwg` "EG"); it decodes as a [`TinSurface`] with four + /// vertices and no triangles, not as `None`. pub fn tin_surface(&self) -> Option { if self.civil_kind() != Some(CivilKind::TinSurface) { return None; diff --git a/src/classes/civil/tin.rs b/src/classes/civil/tin.rs index a1a79616..ee0002b1 100644 --- a/src/classes/civil/tin.rs +++ b/src/classes/civil/tin.rs @@ -444,11 +444,14 @@ fn triangulation_at(data: &[u8], start: usize, end: usize) -> Option { marker(&mut bits) } -/// A triangulation at `pos` and where it ends. +/// A triangulation at `pos` and where it ends. A surface with no +/// triangulation keeps its shell: the four bounding corners at the drawing +/// extremes (`Surface-2.dwg` "EG", the snapshot-only surface of +/// `Pipe Networks-3B.dwg`), with no incident triangle and no triangles. fn read_at(data: &[u8], pos: usize, end: usize) -> Option<(TinSurface, usize)> { let mut bits = Bits::new(data, pos, end); let count = usize::try_from(bits.bit_long()?).ok()?; - if count < 7 || count.checked_mul(VERTEX_BITS)? > bits.remaining() { + if count < 4 || count.checked_mul(VERTEX_BITS)? > bits.remaining() { return None; } let mut corners = [0u32; 4]; @@ -484,7 +487,12 @@ fn read_at(data: &[u8], pos: usize, end: usize) -> Option<(TinSurface, usize)> { return None; } let triangle_count = usize::try_from(bits.bit_long()?).ok()?; - if triangle_count == 0 || triangle_count.checked_mul(TRIANGLE_BITS)? > bits.remaining() { + if triangle_count.checked_mul(TRIANGLE_BITS)? > bits.remaining() { + return None; + } + // A corner-only shell (the application's record for a surface it has + // not built) has no triangles; anything else needs at least the hull. + if triangle_count == 0 && count != 4 { return None; } let mut triangles = Vec::with_capacity(triangle_count); @@ -638,6 +646,44 @@ mod tests { s.chunks(8).map(|c| c.iter().enumerate().fold(0u8, |a, (i, b)| a | ((b - b'0') << (7 - i)))).collect() } + /// The empty-surface shell of the tutorials' Surface-2.dwg ("EG"): the + /// four bounding corners at the drawing extremes, no triangles. + fn empty_shell() -> String { + let max = "1".repeat(48) + "11101111 01111111"; // RD f64::MAX (0x7FEF_FFFF_FFFF_FFFF) + let corner = |i: &str| match i { + "0" => "10".to_string(), + i => format!("01 {:08b}", i.parse::().unwrap()), + }; + let vertex = format!("01000000 00000000 00000000 00000000 {} {max} {max} {max}", "1".repeat(32)); + format!( + "01 00000100 {} {} {} {} {} {} {} {} 10", + corner("0"), + corner("1"), + corner("2"), + corner("3"), + vertex, + vertex, + vertex, + vertex + ) + } + + #[test] + fn reads_an_empty_surface_shell() { + let b = bits_of(&empty_shell()); + let (surface, end) = read_at(&b, 0, b.len() * 8).unwrap(); + assert_eq!(surface.vertices.len(), 4); + assert!(surface.vertices.iter().all(|v| v.flags == 0x40 && v.triangle == -1)); + assert_eq!(surface.corners, [0, 1, 2, 3]); + assert!(surface.triangles.is_empty()); + assert!(surface.visible_triangles().next().is_none()); + assert_eq!(end, empty_shell().chars().filter(|c| *c == '0' || *c == '1').count()); + // The shell is exactly four corners: any other vertex count with no + // triangles is not a triangulation. + let five = empty_shell().replacen("00000100", "00000101", 1); + assert!(read_at(&bits_of(&five), 0, five.len() * 8).is_none()); + } + #[test] fn reads_a_raise_and_a_kind_40_then_stops_at_an_unknown_kind() { // BL 17, BL 9, BL 16, GUID, BL 0, BD 1.5; BL 40, BL 9, BL 16, GUID, From dcffaeaff2a9e7d39ce919b84529b697cc8cd411 Mon Sep 17 00:00:00 2001 From: schoeller Date: Tue, 24 Nov 2026 23:04:15 +0100 Subject: [PATCH 2/2] Civil: export add_empty_tin_surface from the create module Missed in b74c489a: the civil::civil re-export references the new constructor, but the create-module export was left unstaged, breaking the crate build. --- src/classes/civil/create/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/classes/civil/create/mod.rs b/src/classes/civil/create/mod.rs index 27902814..4298d6cd 100644 --- a/src/classes/civil/create/mod.rs +++ b/src/classes/civil/create/mod.rs @@ -60,4 +60,4 @@ pub use points::{add_cogo_point, cogo_points, create_cogo_point, point_creation_ pub use label_style::{add_label_style, add_point_label_style, label_style, LabelStyle}; pub use support::ensure_civil; pub use user_properties::{add_point_choice_property, add_point_property, add_point_property_classification, point_properties, set_cogo_point_property}; -pub use tin::{add_tin_surface, add_tin_surface_with}; +pub use tin::{add_empty_tin_surface, add_tin_surface, add_tin_surface_with};