Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/classes/civil/create/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
110 changes: 98 additions & 12 deletions src/classes/civil/create/tin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<Handle, DxfError> {
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<Handle, DxfError> {
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
Expand All @@ -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<bool>), 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<usize> = 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");
Expand Down Expand Up @@ -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);
}
}
}
}
11 changes: 7 additions & 4 deletions src/classes/civil/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<TinSurface> {
if self.civil_kind() != Some(CivilKind::TinSurface) {
return None;
Expand All @@ -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<TinSurface> {
if self.civil_kind() != Some(CivilKind::TinSurface) {
return None;
Expand Down
52 changes: 49 additions & 3 deletions src/classes/civil/tin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,11 +444,14 @@ fn triangulation_at(data: &[u8], start: usize, end: usize) -> Option<usize> {
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];
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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::<u8>().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,
Expand Down
Loading