diff --git a/CHANGELOG.md b/CHANGELOG.md index 264baa2..bfa82c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to the `IfcIO` library are documented in this file. ## [Unreleased] ### Fixed +- Import meshes swept disks along open 3D polylines and linear indexed curves, including optional trimming, + mitered joints and hollow sections. - Import reads IFC4 and IFC4.3 `IfcPolygonalFaceSet` geometry, including concave polygons, holes and `PnIndex` point reindexing. Invalid faces are omitted without altering the other faces. - Import reads additional concrete IFC products with a `Body` representation, including curtain walls, piles, diff --git a/docs/public-api.md b/docs/public-api.md index 7fa8b27..ac41e84 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -58,6 +58,13 @@ IFC4 and IFC4.3 `IfcPolygonalFaceSet` import also triangulates indexed polygons honours optional `PnIndex` remapping, and omits malformed faces. It keeps the resulting triangle mesh, not the original indexed polygon groups. +`IfcSweptDiskSolid` import supports open 3D `IfcPolyline` and linear `IfcIndexedPolyCurve` paths, and meshes +the circular section with 16 sides. It honours parameter trims and the optional inner radius, and uses +mitered joints and end caps. `IfcSweptDiskSolidPolygonal` is read without fillets only. Closed paths, +arcs and other curved directrices are not read by this path. Input curves must not self-intersect; +the mesher checks adjacent miters, not intersections between distant parts of the sweep. +A readable `Body-FallBack` takes precedence when the primary body has unreadable items. + Imported meshes use world coordinates. If a swept body cannot be represented by one equivalent parametric solid, the reader keeps its placed mesh instead; IFC export writes that mesh rather than a partial or misplaced solid. Boolean operands also use placed meshes where necessary. Applying arbitrary solid-to-solid diff --git a/src/IfcIO/Core/StepReader.cs b/src/IfcIO/Core/StepReader.cs index b38ec1f..794e062 100644 --- a/src/IfcIO/Core/StepReader.cs +++ b/src/IfcIO/Core/StepReader.cs @@ -105,6 +105,9 @@ public List GetRefList(int index) private static bool Omitted(ReadOnlySpan arg) => arg.Length == 1 && arg[0] is '$' or '*'; + internal bool IsNullParameter(int index) => + TryGetArgument(index, out var arg) && arg.Length == 1 && arg[0] == '$'; + public static List ParseArguments(string args) { var result = new List(); diff --git a/src/IfcIO/Geometry/IfcSweptDiskMesher.cs b/src/IfcIO/Geometry/IfcSweptDiskMesher.cs new file mode 100644 index 0000000..eb98803 --- /dev/null +++ b/src/IfcIO/Geometry/IfcSweptDiskMesher.cs @@ -0,0 +1,111 @@ +namespace IfcIO.Geometry; + +internal static class IfcSweptDiskMesher +{ + internal const int Sides = 16; + private static readonly (double Cos, double Sin)[] Circle = Enumerable.Range(0, Sides) + .Select(i => (Math.Cos(i * Math.Tau / Sides), Math.Sin(i * Math.Tau / Sides))).ToArray(); + + internal static IfcMesh? Build(int id, string name, List path, double radius, double innerRadius) + { + bool hollow = innerRadius > 0; + int stride = hollow ? Sides * 2 : Sides; + var vertices = new List(path.Count * stride + (hollow ? 0 : 2)); + var indices = new List(); + var incoming = Direction(0); + if (incoming == IfcVector3.Zero) return null; + var reference = Math.Abs(incoming.Z) < 0.9 ? IfcVector3.UnitZ : IfcVector3.UnitX; + var x = IfcVector3.Cross(reference, incoming).Normalized(); + var y = IfcVector3.Cross(incoming, x); + var previousAdvance = new double[Sides]; + for (int ring = 0; ring < path.Count; ring++) + { + bool atEnd = ring == path.Count - 1; + var outgoing = atEnd ? incoming : Direction(ring); + if (outgoing == IfcVector3.Zero) return null; + double dot = IfcVector3.Dot(incoming, outgoing); + if (dot <= -1 + 1e-9) return null; + + // Project the incoming section along its axis onto the joint's half-angle plane. + var plane = incoming + outgoing; + double denominator = 1 + dot; + var turn = IfcVector3.Cross(incoming, outgoing); + double length = ring == 0 ? 0 : (path[ring] - path[ring - 1]).Length; + for (int side = 0; side < Sides; side++) + { + var section = x * Circle[side].Cos + y * Circle[side].Sin; + double advance = -IfcVector3.Dot(section, plane) / denominator; + if (ring > 0 && length + radius * (advance - previousAdvance[side]) <= 0) return null; + // The same joint point lies on both cylinders. Express its advance on the next leg. + var projected = section + incoming * advance; + previousAdvance[side] = IfcVector3.Dot(projected, outgoing); + vertices.Add(path[ring] + projected * radius); + } + if (hollow) + { + for (int side = 0; side < Sides; side++) + { + var outer = vertices[ring * stride + side]; + vertices.Add(path[ring] + (outer - path[ring]) * (innerRadius / radius)); + } + } + + // Transport the frame by the shortest rotation so the ring indexing does not twist at bends. + var delta = IfcVector3.Cross(turn, x); + x += delta + IfcVector3.Cross(turn, delta) * (1 / denominator); + x = x.Normalized(); + y = IfcVector3.Cross(outgoing, x).Normalized(); + incoming = outgoing; + } + + if (vertices.Exists(p => !double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z))) return null; + for (int ring = 0; ring < path.Count - 1; ring++) + { + int a = ring * stride, b = a + stride; + for (int side = 0; side < Sides; side++) + { + int next = (side + 1) % Sides; + Quad(a + side, a + next, b + next, b + side); + if (hollow) Quad(a + next + Sides, a + side + Sides, b + side + Sides, b + next + Sides); + } + } + + int last = (path.Count - 1) * stride; + if (hollow) + { + for (int side = 0; side < Sides; side++) + { + int next = (side + 1) % Sides; + Quad(next, side, side + Sides, next + Sides); + Quad(last + side, last + next, last + next + Sides, last + side + Sides); + } + } + else + { + int startCenter = vertices.Count; + vertices.Add(path[0]); + int endCenter = vertices.Count; + vertices.Add(path[^1]); + for (int side = 0; side < Sides; side++) + { + int next = (side + 1) % Sides; + Triangle(startCenter, next, side); + Triangle(endCenter, last + side, last + next); + } + } + return IfcMesh.Create(id, name, vertices, indices); + + IfcVector3 Direction(int edge) => (path[edge + 1] - path[edge]).Normalized(); + void Triangle(int a, int b, int c) + { + indices.Add(a); + indices.Add(b); + indices.Add(c); + } + void Quad(int a, int b, int c, int d) + { + Triangle(a, b, c); + Triangle(a, c, d); + } + } +} diff --git a/src/IfcIO/IfcModel.SweptDisks.cs b/src/IfcIO/IfcModel.SweptDisks.cs new file mode 100644 index 0000000..46255de --- /dev/null +++ b/src/IfcIO/IfcModel.SweptDisks.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using IfcIO.Core; +using IfcIO.Geometry; +using IfcIO.Schema; + +namespace IfcIO; + +public sealed partial class IfcModel +{ + private static IfcMesh? ParseSweptDisk(GeometryReadContext ctx, StepEntity item, string meshName) + { + var step = ctx.Step; + bool polygonal = item.Type.Equals("IFCSWEPTDISKSOLIDPOLYGONAL", StringComparison.OrdinalIgnoreCase); + bool ifc2x3 = ctx.Schema == IfcSchema.Ifc2x3; + if (polygonal && (ifc2x3 || !item.IsNullParameter(5))) return null; // Filleted joints need a curved sweep. + + if (item.GetReal(1) is not double radius || !double.IsFinite(radius) || radius <= 0) return null; + double innerRadius = 0; + if (!item.IsNullParameter(2)) + { + if (item.GetReal(2) is not double inner || !double.IsFinite(inner) || inner <= 0 || inner >= radius) return null; + innerRadius = inner; + } + + if (step.Find(item.GetRef(0)) is not { } curve) return null; + if (ifc2x3 && !curve.Type.Equals("IFCPOLYLINE", StringComparison.OrdinalIgnoreCase)) return null; + var points = ReadLinearDirectrix(ctx, curve, polygonal); + if (points is not { Count: >= 2 }) return null; + + double start = !ifc2x3 && item.IsNullParameter(3) ? 0 : item.GetReal(3) ?? double.NaN; + double end = !ifc2x3 && item.IsNullParameter(4) ? points.Count - 1 : item.GetReal(4) ?? double.NaN; + if (!double.IsFinite(start) || !double.IsFinite(end) || start < 0 || end > points.Count - 1 || end <= start) return null; + + // Each linear edge occupies one unit in the IFC curve's parameter domain. + int first = (int)Math.Floor(start); + int limit = (int)Math.Ceiling(end); + long vertexCount = ((long)limit - first + 1) * IfcSweptDiskMesher.Sides * (innerRadius > 0 ? 2 : 1) + + (innerRadius > 0 ? 0 : 2); + ctx.CheckVertexBudget(vertexCount); + var path = new List(limit - first + 1) { Interpolate(first, start) }; + for (int i = first + 1; i < end; i++) AddPathPoint(points[i]); + AddPathPoint(Interpolate(limit - 1, end)); + if (path[0] == path[^1]) return null; // Closed directrices need a seam-aware frame. + + var mesh = IfcSweptDiskMesher.Build(item.Id, meshName, path, radius, innerRadius); + // The caller charges success. Bound repeated failed attempts that could allocate all the rings. + if (mesh is null) ctx.ChargeVertices((int)vertexCount); + return mesh; + + IfcVector3 Interpolate(int segment, double parameter) + { + double fraction = parameter - segment; + return points[segment] * (1 - fraction) + points[segment + 1] * fraction; + } + + void AddPathPoint(IfcVector3 point) + { + // Trim first: a redundant straight-line vertex still occupies a parameter interval. + if (path.Count >= 2) + { + var incoming = (path[^1] - path[^2]).Normalized(); + var outgoing = (point - path[^1]).Normalized(); + if (IfcVector3.Dot(incoming, outgoing) > 0 + && IfcVector3.Cross(incoming, outgoing).Length <= 1e-12) + { + path[^1] = point; + return; + } + } + path.Add(point); + } + } + + private static List? ReadLinearDirectrix(GeometryReadContext ctx, StepEntity curve, bool polygonal) + { + var points = new List(); + if (curve.Type.Equals("IFCPOLYLINE", StringComparison.OrdinalIgnoreCase)) + { + if (ReadReferenceList(curve, 0) is not { Count: >= 2 } ids) return null; + foreach (int id in ids) + { + if (!TryReadFacetedPoint(ctx.Step.Find(id), out var point)) return null; + points.Add(point); + } + return points; + } + + if (!curve.Type.Equals("IFCINDEXEDPOLYCURVE", StringComparison.OrdinalIgnoreCase) + || ReadTessellatedPoints(ctx, curve.GetRef(0)) is not { Length: >= 2 } coordinates + || (!curve.IsNullParameter(2) && curve.GetBool(2) != false)) return null; + + if (curve.IsNullParameter(1)) + { + foreach (var point in coordinates) + { + if (point is not IfcVector3 coordinate) return null; + points.Add(coordinate); + } + return points; + } + if (polygonal) return null; // The polygonal subtype requires Segments to be omitted. + + int lastIndex = -1; + var segments = ParseStepList(curve.GetRaw(1)); + foreach (string segment in segments) + { + const string lineIndex = "IFCLINEINDEX"; + if (!segment.StartsWith(lineIndex, StringComparison.OrdinalIgnoreCase)) return null; + var wrapper = ParseStepList(segment[lineIndex.Length..].TrimStart()); + if (wrapper.Count != 1) return null; + var indices = ParseStepList(wrapper[0]); + if (indices.Count < 2) return null; + for (int i = 0; i < indices.Count; i++) + { + if (!int.TryParse(indices[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out int index) + || index <= 0 || index > coordinates.Length || coordinates[index - 1] is not IfcVector3 point) + return null; + if (i == 0 && lastIndex != -1) + { + if (index != lastIndex) return null; + } + else + { + points.Add(point); + } + lastIndex = index; + } + } + return points; + } +} diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index 3a441ac..ca9bfc0 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -1772,6 +1772,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions geomToMaterialMap, IfcTransform.Scale(geometryScale).Multiply(ParseWorldCoordinateSystem(step)), radiansPerAngleUnit, + schema, omitUnsupportedPlacements: schema == IfcSchema.Ifc4x3, keepParametric: geometryScale == 1.0); var defaultStorey = model.Storeys[0]; @@ -2790,7 +2791,7 @@ private int WriteRevolvedAreaSolid(StepWriter w, IfcRevolvedAreaSolid solid) /// State shared while reading product geometry: caches for placements and mapped representations. private sealed class GeometryReadContext( StepFile step, Dictionary geomToMaterialMap, IfcTransform root, double radiansPerAngleUnit, - bool omitUnsupportedPlacements, bool keepParametric) + IfcSchema schema, bool omitUnsupportedPlacements, bool keepParametric) { public StepFile Step { get; } = step; public Dictionary GeomToMaterialMap { get; } = geomToMaterialMap; @@ -2798,12 +2799,13 @@ private sealed class GeometryReadContext( /// Unit scale applied after the world coordinate system of the model context. public IfcTransform Root { get; } = root; public double RadiansPerAngleUnit { get; } = radiansPerAngleUnit; + public IfcSchema Schema { get; } = schema; public bool OmitUnsupportedPlacements { get; } = omitUnsupportedPlacements; /// False when geometry is rescaled to metres: parametric solids stay in file units and would disagree with LengthUnit. public bool KeepParametric { get; } = keepParametric; public Dictionary Placements { get; } = []; - public Dictionary MappedRepresentations { get; } = []; + public Dictionary MappedRepresentations { get; } = []; public HashSet MapsInProgress { get; } = []; public HashSet BooleanWarnings { get; } = []; public Dictionary TessellatedPointLists { get; } = []; @@ -2824,8 +2826,13 @@ public void ChargeBooleanNode(int id) public void ChargeVertices(int count) { + CheckVertexBudget(count); _materialisedVertices += count; - if (_materialisedVertices > VertexBudget) + } + + public void CheckVertexBudget(long count) + { + if (count > int.MaxValue || _materialisedVertices + count > VertexBudget) { throw new InvalidDataException( $"IFC geometry expands to more than {VertexBudget} vertices (limit for {Step.EntityCount} entities); check for nested mapped items or Boolean results."); @@ -2870,38 +2877,51 @@ public void ChargeVertices(int count) .Where(r => r.Type.Equals("IFCSHAPEREPRESENTATION", StringComparison.OrdinalIgnoreCase)) .ToList(); - // Legacy products can fall back to another representation; newly discovered products require Body. + // A complete Body-FallBack can replace an incomplete Body, but not vice versa. + // Never substitute e.g. Clearance for Body on newly discovered products. static bool IsBody(StepEntity rep) => string.Equals(rep.GetString(1), "Body", StringComparison.OrdinalIgnoreCase); - var bodies = reps.Where(IsBody); - foreach (var rep in bodyOnly ? bodies : bodies.Concat(reps.Where(r => !IsBody(r)))) - { + static bool IsFallback(StepEntity rep) => string.Equals(rep.GetString(1), "Body-FallBack", StringComparison.OrdinalIgnoreCase); + var fallbacks = reps.Where(IsFallback); + bool hasFallback = reps.Any(IsFallback); + var candidates = reps.Where(IsBody).Concat(fallbacks); + if (!bodyOnly) candidates = candidates.Concat(reps.Where(rep => !IsBody(rep) && !IsFallback(rep))); + (IfcMesh Mesh, IfcMaterial? Material, ParametricBody? Parametric, bool HasBoolean)? selected = null, incompleteBody = null; + foreach (var rep in candidates) + { + if (incompleteBody is not null && !IsBody(rep) && !IsFallback(rep)) break; IfcMaterial? repMaterial = null; - var mesh = ParseRepresentationItems(ctx, rep, meshName, ref repMaterial, out var parametric, out bool hasBoolean); + var mesh = ParseRepresentationItems(ctx, rep, meshName, ref repMaterial, out var parametric, out bool hasBoolean, out bool hasSkippedItems); if (mesh is null) continue; - material = repMaterial; - booleanResult = parametric?.Boolean; - unwritableBooleanBody = hasBoolean && booleanResult is null; - if (parametric is { } body && ctx.KeepParametric && placement.IsTranslationOnly) + if (hasSkippedItems && hasFallback && (IsBody(rep) || IsFallback(rep))) { - solid = body.Solid; - if (solid is not null) solid.Position += placement.Origin; - revolvedSolid = body.Revolved; - if (revolvedSolid is not null) - { - revolvedSolid.Position += placement.Origin; - revolvedSolid.Axis.Location += placement.Origin; - } + incompleteBody ??= (mesh, repMaterial, parametric, hasBoolean); + continue; } + selected = (mesh, repMaterial, parametric, hasBoolean); + break; + } - if (booleanResult is not null && !placement.IsIdentity) - PlaceBooleanOperands(booleanResult, placement); - - var world = placement.ApplyTo(mesh); - return IfcMesh.Create(world.Id, meshName, world.Vertices, world.Indices); + if ((selected ?? incompleteBody) is not { } chosen) return null; + material = chosen.Material; + booleanResult = chosen.Parametric?.Boolean; + unwritableBooleanBody = chosen.HasBoolean && booleanResult is null; + if (chosen.Parametric is { } body && ctx.KeepParametric && placement.IsTranslationOnly) + { + solid = body.Solid; + if (solid is not null) solid.Position += placement.Origin; + revolvedSolid = body.Revolved; + if (revolvedSolid is not null) + { + revolvedSolid.Position += placement.Origin; + revolvedSolid.Axis.Location += placement.Origin; + } } - return null; + if (booleanResult is not null && !placement.IsIdentity) + PlaceBooleanOperands(booleanResult, placement); + var world = placement.ApplyTo(chosen.Mesh); + return IfcMesh.Create(world.Id, meshName, world.Vertices, world.Indices); } /// Merges all readable items of a shape representation into one mesh in the representation's coordinates. @@ -2911,10 +2931,12 @@ public void ChargeVertices(int count) string meshName, ref IfcMaterial? material, out ParametricBody? parametric, - out bool hasBoolean) + out bool hasBoolean, + out bool hasSkippedItems) { parametric = null; hasBoolean = false; + hasSkippedItems = false; if (repEnt is null) return null; var itemIds = repEnt.GetRefList(3); @@ -2922,11 +2944,20 @@ public void ChargeVertices(int count) foreach (int itemId in itemIds) { var itemEnt = ctx.Step.Find(itemId); - if (itemEnt is null) continue; + if (itemEnt is null) + { + hasSkippedItems = true; + continue; + } var itemMaterial = ctx.GeomToMaterialMap.GetValueOrDefault(itemId); - var mesh = ParseRepresentationItem(ctx, itemEnt, meshName, ref itemMaterial, out var itemParametric); - if (mesh is null) continue; + var mesh = ParseRepresentationItem(ctx, itemEnt, meshName, ref itemMaterial, out var itemParametric, out bool skippedNestedItems); + if (mesh is null) + { + hasSkippedItems = true; + continue; + } + hasSkippedItems |= skippedNestedItems; material ??= itemMaterial; // The Boolean reader already charges leaf meshes and triangles emitted by each clip. if (itemParametric?.Boolean is null) ctx.ChargeVertices(mesh.Vertices.Count); @@ -2955,9 +2986,11 @@ public void ChargeVertices(int count) StepEntity itemEnt, string meshName, ref IfcMaterial? material, - out ParametricBody? parametric) + out ParametricBody? parametric, + out bool hasSkippedItems) { parametric = null; + hasSkippedItems = false; var step = ctx.Step; // A/B. Meshes (Brep / TriangulatedFaceSet / surface models) @@ -2989,7 +3022,8 @@ public void ChargeVertices(int count) int? mapId = itemEnt.GetRef(0); if (!mapId.HasValue) return null; - var (mapMesh, mapMaterial) = ParseMappedRepresentation(ctx, mapId.Value, meshName); + var (mapMesh, mapMaterial, skippedMappedItems) = ParseMappedRepresentation(ctx, mapId.Value, meshName); + hasSkippedItems = skippedMappedItems; material ??= mapMaterial; if (mapMesh is null) return null; return ParseCartesianTransformationOperator(step, itemEnt.GetRef(1)).ApplyTo(mapMesh); @@ -3061,14 +3095,15 @@ public void ChargeVertices(int count) } /// Reads an IfcRepresentationMap once, in the coordinates of the mapping (MappingOrigin applied). - private static (IfcMesh? Mesh, IfcMaterial? Material) ParseMappedRepresentation(GeometryReadContext ctx, int mapId, string meshName) + private static (IfcMesh? Mesh, IfcMaterial? Material, bool HasSkippedItems) ParseMappedRepresentation( + GeometryReadContext ctx, int mapId, string meshName) { if (ctx.MappedRepresentations.TryGetValue(mapId, out var cached)) return cached; var mapEnt = ctx.Step.Find(mapId); if (mapEnt is null || !mapEnt.Type.Equals("IFCREPRESENTATIONMAP", StringComparison.OrdinalIgnoreCase)) { - return (null, null); + return (null, null, true); } if (ctx.MapsInProgress.Count >= MaxMappingDepth) @@ -3082,8 +3117,8 @@ private static (IfcMesh? Mesh, IfcMaterial? Material) ParseMappedRepresentation( } IfcMaterial? material = null; - var mesh = ParseRepresentationItems(ctx, ctx.Step.Find(mapEnt.GetRef(1)), meshName, ref material, out _, out _); - var result = (mesh is null ? null : ParseAxis2Placement(ctx.Step, mapEnt.GetRef(0)).ApplyTo(mesh), material); + var mesh = ParseRepresentationItems(ctx, ctx.Step.Find(mapEnt.GetRef(1)), meshName, ref material, out _, out _, out bool skippedItems); + var result = (mesh is null ? null : ParseAxis2Placement(ctx.Step, mapEnt.GetRef(0)).ApplyTo(mesh), material, skippedItems); ctx.MapsInProgress.Remove(mapId); ctx.MappedRepresentations[mapId] = result; @@ -3343,6 +3378,9 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) return ParseTriangulatedFaceSet(ctx, itemEnt, meshName); if (itemEnt.Type.Equals("IFCPOLYGONALFACESET", StringComparison.OrdinalIgnoreCase)) return ParsePolygonalFaceSet(ctx, itemEnt, meshName); + if (itemEnt.Type.Equals("IFCSWEPTDISKSOLID", StringComparison.OrdinalIgnoreCase) + || itemEnt.Type.Equals("IFCSWEPTDISKSOLIDPOLYGONAL", StringComparison.OrdinalIgnoreCase)) + return ParseSweptDisk(ctx, itemEnt, meshName); return null; } diff --git a/tests/IfcIO.Tests/ProductOccurrenceTests.cs b/tests/IfcIO.Tests/ProductOccurrenceTests.cs index 1e6832c..908f5d1 100644 --- a/tests/IfcIO.Tests/ProductOccurrenceTests.cs +++ b/tests/IfcIO.Tests/ProductOccurrenceTests.cs @@ -111,10 +111,11 @@ public void Open_UnreadableBody_DoesNotUseClearanceAsTheProductMesh() { string ifc = BuildIfc("IFC4", """ #20=IFCACTUATOR('1YvctVUKr0kugbFTf53O9L',$,'Actuator',$,$,#6,#14,$,$); - #21=IFCSWEPTDISKSOLID(#22,1.,$,$,$); - #22=IFCPOLYLINE((#4,#23)); + #21=IFCSWEPTDISKSOLIDPOLYGONAL(#22,1.,$,$,$,4.); + #22=IFCPOLYLINE((#4,#23,#25)); #23=IFCCARTESIANPOINT((0.,0.,100.)); #24=IFCSHAPEREPRESENTATION(#7,'Clearance','SweptSolid',(#12)); + #25=IFCCARTESIANPOINT((20.,0.,100.)); """) .Replace("'Body','SweptSolid',(#12)", "'Body','AdvancedSweptSolid',(#21)", StringComparison.Ordinal) .Replace("$,$,(#13)", "$,$,(#13,#24)", StringComparison.Ordinal); diff --git a/tests/IfcIO.Tests/SweptDiskImportTests.cs b/tests/IfcIO.Tests/SweptDiskImportTests.cs new file mode 100644 index 0000000..8cedfe7 --- /dev/null +++ b/tests/IfcIO.Tests/SweptDiskImportTests.cs @@ -0,0 +1,184 @@ +using IfcIO.Geometry; +using Xunit; + +namespace IfcIO.Tests; + +public class SweptDiskImportTests +{ + private static IfcModel Open( + string schema, string directrix, string points, string parameters, string inner = "$", bool useFallback = false, bool mapped = false) + { + string ifc = $$""" + ISO-10303-21; + HEADER; + FILE_SCHEMA(('{{schema}}')); + ENDSEC; + DATA; + #1=IFCPROJECT('0YvctVUKr0kugbFTf53O9L',$,'Swept disks',$,$,$,$,(#7),#2); + #2=IFCUNITASSIGNMENT((#3)); + #3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.); + #4=IFCCARTESIANPOINT((100.,200.,300.)); + #5=IFCAXIS2PLACEMENT3D(#4,$,$); + #6=IFCLOCALPLACEMENT($,#5); + #7=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#16,$); + #8=IFCSWEPTDISKSOLID(#20,2.,{{inner}},{{parameters}}); + #9=IFCSHAPEREPRESENTATION(#7,'Body','{{(mapped ? "MappedRepresentation" : "AdvancedSweptSolid")}}', + ({{(mapped ? "#37" : useFallback ? "#8,#30" : "#8")}})); + #10=IFCPRODUCTDEFINITIONSHAPE($,$,(#9{{(useFallback ? ",#31" : "")}})); + #11=IFCBUILDINGELEMENTPROXY('1YvctVUKr0kugbFTf53O9L',$,'Disk',$,$,#6,#10,$,$); + #15=IFCCARTESIANPOINT((0.,0.,0.)); + #16=IFCAXIS2PLACEMENT3D(#15,$,$); + #20={{directrix}}; + {{points}} + ENDSEC; + END-ISO-10303-21; + """; + return IfcModel.Open(new StringReader(ifc)); + } + + private static IfcMesh? Mesh(IfcModel model) => Assert.Single(model.AllElements).Mesh; + + [Fact] + public void Open_TrimmedIfc2x3Polyline_AppliesBothParametersInTheirSegmentDomain() + { + var model = Open("IFC2X3", "IFCPOLYLINE((#21,#22,#23))", """ + #21=IFCCARTESIANPOINT((0.,0.,0.)); + #22=IFCCARTESIANPOINT((0.,0.,10.)); + #23=IFCCARTESIANPOINT((0.,0.,30.)); + """, "0.5,1.25"); + var mesh = Mesh(model); + Assert.NotNull(mesh); + AssertBox(mesh, new(98, 198, 305), new(102, 202, 315)); + AssertClosed(mesh); + AssertSameBoundsAfterExport(model, mesh); + } + + [Fact] + public void Open_IndexedPolyline_CreatesMiterAndHollowCaps() + { + var model = Open("IFC4", "IFCINDEXEDPOLYCURVE(#21,(IFCLINEINDEX((2,3)),IFCLINEINDEX((3,1))),.F.)", + "#21=IFCCARTESIANPOINTLIST3D(((20.,0.,10.),(0.,0.,0.),(0.,0.,10.)));", "$,$", inner: "1."); + var mesh = Mesh(model); + Assert.NotNull(mesh); + AssertBox(mesh, new(98, 198, 300), new(120, 202, 312)); + AssertClosed(mesh); + + // At the bend the section follows the half-angle plane x + z = 410. + var bend = mesh.Vertices.Where(p => p.X < 110 && p.Z > 302).ToArray(); + Assert.NotEmpty(bend); + Assert.All(bend, point => Assert.Equal(410, point.X + point.Z, 9)); + Assert.DoesNotContain(mesh.Vertices, p => p == new IfcVector3(100, 200, 300)); + AssertSameBoundsAfterExport(model, mesh); + } + + [Theory] + [InlineData("-1.,1.", "$")] + [InlineData("0.,2.", "$")] + [InlineData("0.,1.", "3.")] + [InlineData("*,1.", "$")] + [InlineData("0.,1.", "*")] + public void Open_InvalidParameters_DoesNotInventGeometry(string parameters, string inner) + { + var mesh = Mesh(Open("IFC4", "IFCPOLYLINE((#21,#22))", + "#21=IFCCARTESIANPOINT((0.,0.,0.)); #22=IFCCARTESIANPOINT((0.,0.,10.));", parameters, inner)); + Assert.Null(mesh); + } + + [Fact] + public void Open_Ifc2x3RequiresTrimParameters() + { + Assert.Null(Mesh(Open("IFC2X3", "IFCPOLYLINE((#21,#22))", + "#21=IFCCARTESIANPOINT((0.,0.,0.)); #22=IFCCARTESIANPOINT((0.,0.,10.));", "$,$"))); + } + + [Theory] + [InlineData("IFC2X3", ".F.")] + [InlineData("IFC4", ".U.")] + public void Open_RejectsIndexedCurvesOutsideTheirSchemaOrWithInvalidFlag(string schema, string flag) + { + Assert.Null(Mesh(Open(schema, $"IFCINDEXEDPOLYCURVE(#21,$,{flag})", + "#21=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(0.,0.,10.)));", "0.,1."))); + } + + [Fact] + public void Open_IndexedCurveWithAnArc_DoesNotTreatTheArcAsALine() + { + var mesh = Mesh(Open("IFC4", "IFCINDEXEDPOLYCURVE(#21,(IFCARCINDEX((1,2,3))),.F.)", + "#21=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(0.,10.,10.),(0.,20.,0.)));", "$,$")); + Assert.Null(mesh); + } + + [Fact] + public void Open_RedundantCollinearVertex_DoesNotBreakMiterAfterTrimming() + { + var mesh = Mesh(Open("IFC4", "IFCPOLYLINE((#21,#22,#23,#24))", """ + #21=IFCCARTESIANPOINT((0.,0.,0.)); + #22=IFCCARTESIANPOINT((9.,0.,0.)); + #23=IFCCARTESIANPOINT((10.,0.,0.)); + #24=IFCCARTESIANPOINT((10.,10.,0.)); + """, "0.5,3.")); + Assert.NotNull(mesh); + AssertBox(mesh, new(104.5, 198, 298), new(112, 210, 302)); + AssertClosed(mesh); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Open_PartialSweptDiskBody_PrefersCompleteBodyFallback(bool mapped) + { + var model = Open("IFC4", "IFCPOLYLINE((#21,#22))", """ + #21=IFCCARTESIANPOINT((0.,0.,0.)); + #22=IFCCARTESIANPOINT((0.,0.,10.)); + #30=IFCSWEPTDISKSOLID(#32,2.,$,$,$); + #31=IFCSHAPEREPRESENTATION(#7,'Body-FallBack','Tessellation',(#34)); + #32=IFCINDEXEDPOLYCURVE(#33,(IFCARCINDEX((1,2,3))),.F.); + #33=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(0.,10.,10.),(0.,20.,0.))); + #34=IFCTRIANGULATEDFACESET(#33,$,.F.,((1,2,3)),$); + #35=IFCSHAPEREPRESENTATION(#7,'Body','AdvancedSweptSolid',(#8,#30)); + #36=IFCREPRESENTATIONMAP(#16,#35); + #37=IFCMAPPEDITEM(#36,#38); + #38=IFCCARTESIANTRANSFORMATIONOPERATOR3D($,$,#15,$,$); + """, "$,$", useFallback: true, mapped: mapped); + var mesh = Mesh(model); + Assert.NotNull(mesh); + Assert.Equal(1, mesh.TriangleCount); + } + + private static void AssertSameBoundsAfterExport(IfcModel model, IfcMesh before) + { + var after = Mesh(IfcModel.Open(new StringReader(model.ToStepString()))); + Assert.NotNull(after); + Assert.Equal(before.TriangleCount, after.TriangleCount); + AssertBox(after, before.BoundingBox.Min, before.BoundingBox.Max); + AssertClosed(after); + } + + private static void AssertBox(IfcMesh mesh, IfcVector3 min, IfcVector3 max) + { + Assert.True((mesh.BoundingBox.Min - min).Length < 1e-9, $"Min: {mesh.BoundingBox.Min}, expected {min}"); + Assert.True((mesh.BoundingBox.Max - max).Length < 1e-9, $"Max: {mesh.BoundingBox.Max}, expected {max}"); + } + + private static void AssertClosed(IfcMesh mesh) + { + var edges = new Dictionary<(int, int), (int Count, int Balance)>(); + for (int i = 0; i < mesh.Indices.Count; i += 3) + { + var a = mesh.Indices[i]; + var b = mesh.Indices[i + 1]; + var c = mesh.Indices[i + 2]; + Add(a, b); + Add(b, c); + Add(c, a); + } + Assert.All(edges.Values, edge => Assert.Equal((2, 0), edge)); + + void Add(int a, int b) + { + var key = a < b ? (a, b) : (b, a); + var (count, balance) = edges.GetValueOrDefault(key); + edges[key] = (count + 1, balance + (a < b ? 1 : -1)); + } + } +}