diff --git a/CHANGELOG.md b/CHANGELOG.md index b141589..df23bf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,11 @@ API between minor releases. of table rows can be read in a given encoding. `TdbReadOptions.TextEncoding` now applies to them too. - Tests of the adapter in `TdbIO.Scene.Tests`, and test runs on Linux and macOS in CI. - `docs/versions.md`: differences between Tekla Structures versions. +- Geometry diagnostics of the scene adapter: `TdbSceneResult.GeometryDiagnostics` (`TdbGeometryDiagnostic`) reports + the parts whose proxy box has the default dimensions of 150 mm × 150 mm, because none were read from the profile + name, and the parts without a usable geometry; `TdbSceneResult.PartCount` counts the parts. The IFC, scene JSON and + HTML exports of `tdbio` warn on standard error how many parts are rectangular proxy boxes, and the last two also list + the findings. The warnings are not part of the exported data. ### Changed diff --git a/README.md b/README.md index 5653b99..b289b68 100644 --- a/README.md +++ b/README.md @@ -118,8 +118,10 @@ tdbio export model.db1 viewer.html ``` Every command takes `--json` to write one JSON object instead of text. Warnings go to standard error and do not change -the exit code. The outputs above come from small synthetic files; the values are made up. Run `tdbio --help` for the -usage, and see [the command line](docs/cli.md) for every key, column and JSON property. +the exit code. The IFC, scene and HTML exports warn on standard error how many parts are drawn as proxy boxes; the +scene and HTML exports also name the parts whose box has the default dimensions and the parts with no usable geometry. +The outputs above come from small synthetic files; the values are made up. Run `tdbio --help` for the usage, and see +[the command line](docs/cli.md) for every key, column and JSON property. | Code | Meaning | | --- | --- | diff --git a/docs/cli.md b/docs/cli.md index 1553133..8931888 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -22,6 +22,7 @@ Usage: tdbio info [--json] [--encoding ascii|utf-8|cp1251|cp1252] | `tdbio info ` | every supported kind | `key: value` lines: the kind, its main values and the number of warnings. | | `tdbio tables ` | model databases (`.db1`), DBV@ files | A tab-separated header line, then one line per table section. | | `tdbio text ` | model databases (`.db1`) | A tab-separated header line, then one line per text chain, then one line per orphan row. | +| `tdbio export [output]` | model databases (`.db1`) | The object model as JSON (default), or with an option: `--ifc` (IFC), `--scene-json` (an IOScene scene), or no format option and an `.html` output (a standalone viewer). | | `tdbio --help`, `tdbio -h` | | The usage text, on standard output. | | `tdbio --version` | | `tdbio `, for example `tdbio 0.1.0`. | @@ -37,6 +38,21 @@ from its extension (reports, which have no signature, are recognised by the `.xs An option given twice is a usage error. +## Geometry warnings of an export + +The IFC, scene JSON and HTML viewer exports draw every part as a rectangular proxy box between its start and end point, +with the width and height estimated from the numbers in the profile name (150 mm × 150 mm when none are read). The +estimate does not check the profile. The meshes are not decoded Tekla solids and are not made for clash detection or +exact measurement. The warnings go to standard error, so the output on standard output or in the file holds none of +them, and they do not change the exit code. The JSON export of the object model has no geometry and no such warning. + +All three exports print one line with the number of proxy boxes. The scene JSON export (`--scene-json`) and the HTML +viewer export build the scene of the `TdbIO.Scene` adapter and then also print, each after a summary line, one line per +part whose box has the default dimensions and one line per part with no usable geometry (no start or end point, or a +degenerate axis). A part is named by its GUID, or `part:{id}` when it has none. Up to 20 parts per kind are listed; the +summary line counts them all, and the full list is in `TdbSceneResult.GeometryDiagnostics`. The IFC export prints only +the line with the number of boxes. + ## Exit codes | Code | Name | Meaning | @@ -49,8 +65,8 @@ The whole output is built before anything is written, so a failing command write message about malformed data ends with the offset of the problem, for example `tdbio: not a recognised Tekla file at offset 0x0`. -Warnings are written after the output, one line each: `tdbio: warning: `. They name an offset or a line, never -text from the file. +Warnings are written after the output, one line each: `tdbio: warning: `. They name an offset, a line, or, for +the [geometry warnings](#geometry-warnings-of-an-export), a part by its GUID or number, never text from the file. ## info diff --git a/docs/public-api.md b/docs/public-api.md index f24e100..552da97 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -141,6 +141,17 @@ High-level connected object model produced by `Db1Document.ReadModel()`: | `ModelCoordsys` | Local coordinate system origin and scale: `Id`, `X`, `Y`, `Z`, `Length`. | | `ModelBoltHole` | Bolt hole penetration: `No`, `PartId`, `Part`, `PointZ`, `Length`, `LongHoleDir`, `LongHoleType`, `ShorteningLength`. | +## Scene adapter + +`TdbIO.Scene` (a separate package) turns a `TeklaModel` into an IOScene scene document in metres: + +| Type | Use | +| --- | --- | +| `TdbSceneReader` | `Read(path, options)` and `Read(model, options)` convert a model database or an in-memory model into a scene. | +| `TdbSceneOptions` | `ModelKey`, `IncludeBolts`, `IncludeWelds`, `GenerateGeometry` (all true by default). | +| `TdbSceneResult` | `Document` (the scene), `Diagnostics` (the structural validation of the scene), `GeometryDiagnostics`, `MetresPerUnit`, `ElementCount`, `PartCount`, `ElementsWithGeometry`, `GeometryCount`. | +| `TdbGeometryDiagnostic` | One finding about the geometry of a part: `Kind` (`FallbackDimensions`, `NoGeometry`), `ElementId`, `SourceId`, `Profile`, `Message` (names the part by `SourceId`, no text from the file). Every mesh is a rectangular proxy box around the part axis, not the decoded Tekla solid, and `ElementsWithGeometry` counts them; the scene is for viewing, not for clash detection or exact measurement. A part without `FallbackDimensions` has a size estimated from the numbers in its profile name, which does not check the profile. | + ## Files next to the model | Type | Use | diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index ff9a4da..76bce10 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; @@ -96,15 +97,17 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr) // Everything is read before anything is written, so an error never leaves half an output. var output = new StringWriter(); string? error = null; + var exportWarnings = new List(); switch (command.Name) { case "info": error = Info(output, doc, command.Json); break; case "tables": Tables(output, doc, command.Json); break; - case "export": Export(output, doc, command); break; + case "export": exportWarnings.AddRange(Export(output, doc, command)); break; default: Text(output, doc, command.Json); break; } stdout.Write(output.ToString()); foreach (string warning in doc.Warnings) stderr.WriteLine($"tdbio: warning: {warning}"); + foreach (string warning in exportWarnings) stderr.WriteLine($"tdbio: warning: {warning}"); if (error != null) { stderr.WriteLine($"tdbio: {error}"); @@ -376,14 +379,18 @@ private static void Text(TextWriter w, TdbDocument doc, bool json) } } - private static void Export(TextWriter w, TdbDocument doc, Command cmd) + private static IReadOnlyList Export(TextWriter w, TdbDocument doc, Command cmd) { + var geometryWarnings = new List(); if (doc is not Db1Document db1) throw new WrongKindException($"'export' needs a model database (.db1), not {doc.Kind}."); var model = db1.ReadModel(); model.ValidateFiniteNumbers(); if (cmd.Ifc) { + // The parts the IFC output gives a body: those with both points. + int boxes = model.Parts.Count(part => part.StartPoint.HasValue && part.EndPoint.HasValue); + if (boxes > 0) geometryWarnings.Add(ProxyBoxWarning(boxes, model.Parts.Count)); if (cmd.OutputPath != null) { WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp => model.WriteIfc(tmp)); @@ -408,6 +415,7 @@ private static void Export(TextWriter w, TdbDocument doc, Command cmd) { throw new InvalidDataException(errors[0].Message); } + geometryWarnings.AddRange(SceneGeometryWarnings(sceneResult)); WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp => HtmlViewerExporter.Save(sceneResult.Document, tmp)); } else if (cmd.SceneJson) @@ -421,6 +429,7 @@ private static void Export(TextWriter w, TdbDocument doc, Command cmd) { throw new InvalidDataException(errors[0].Message); } + geometryWarnings.AddRange(SceneGeometryWarnings(sceneResult)); if (cmd.OutputPath != null) { WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp => @@ -464,8 +473,55 @@ private static void Export(TextWriter w, TdbDocument doc, Command cmd) w.WriteLine(model.ToJson(cmd.Indent)); } } + return geometryWarnings; } + // The warning lines for the geometry of a scene conversion: one line for the proxy boxes, then for the parts with + // fallback dimensions and for those without a usable geometry a summary line and one detail line per part, up to + // DetailLimit parts per kind. Without the 'tdbio: warning: ' prefix; the caller adds it when the lines are written to + // standard error. + private const int DetailLimit = 20; + + private static string ProxyBoxWarning(int boxes, int parts) => string.Create(CultureInfo.InvariantCulture, + $"{boxes} of {parts} {Noun(parts, "part", "parts")} {Noun(boxes, "uses", "use")} rectangular proxy boxes instead of decoded Tekla solids; the meshes are for viewing, not for measurements."); + + internal static IReadOnlyList SceneGeometryWarnings(TdbSceneResult result) + { + var lines = new List(); + var fallback = new List(); + var none = new List(); + foreach (var d in result.GeometryDiagnostics) + { + switch (d.Kind) + { + case TdbGeometryDiagnosticKind.FallbackDimensions: fallback.Add(d); break; + case TdbGeometryDiagnosticKind.NoGeometry: none.Add(d); break; + } + } + // Only parts have meshes, and each mesh is a proxy box. + if (result.ElementsWithGeometry > 0) lines.Add(ProxyBoxWarning(result.ElementsWithGeometry, result.PartCount)); + AddDetails(lines, fallback, Noun(fallback.Count, "part uses", "parts use") + " the default dimensions of 150x150 mm because none were read from the profile name:"); + AddDetails(lines, none, Noun(none.Count, "part has", "parts have") + " no usable geometry:"); + return lines; + } + + // The summary of one kind of geometry findings and its per-part detail lines, capped at DetailLimit. + private static void AddDetails(List lines, List found, string summary) + { + if (found.Count == 0) + { + return; + } + lines.Add(string.Create(CultureInfo.InvariantCulture, $"{found.Count} {summary}")); + lines.AddRange(found.Take(DetailLimit).Select(d => " " + d.Message)); + if (found.Count > DetailLimit) + { + lines.Add(string.Create(CultureInfo.InvariantCulture, $" and {found.Count - DetailLimit} more parts; the full list is in TdbSceneResult.GeometryDiagnostics.")); + } + } + + private static string Noun(int count, string singular, string plural) => count == 1 ? singular : plural; + private static void WriteFileAtomically(string inputPath, string outputPath, Action writeAction) { if (AreSameFile(inputPath, outputPath)) diff --git a/src/TdbIO.Scene/TdbGeometryDiagnostic.cs b/src/TdbIO.Scene/TdbGeometryDiagnostic.cs new file mode 100644 index 0000000..f2e94cf --- /dev/null +++ b/src/TdbIO.Scene/TdbGeometryDiagnostic.cs @@ -0,0 +1,28 @@ +namespace TdbIO.Scene; + +/// What the conversion did with the geometry of one part. +public enum TdbGeometryDiagnosticKind +{ + /// No dimensions were read from the profile name and the proxy box of the part uses the default ones. A part + /// without this finding has dimensions estimated from the name, which are not a check of the profile. + FallbackDimensions, + + /// The part has no usable geometry (no endpoints or a degenerate axis) and got no mesh. + NoGeometry, +} + +/// One finding about the scene geometry of a part. Every mesh is a rectangular proxy box around the part axis, +/// not the decoded Tekla solid ( counts them, so they have no findings +/// of their own); some boxes have default dimensions and some parts get no mesh. The scene of is for viewing; it is not made for clash detection or exact measurement. +/// The kind of the finding. +/// The id of the scene element of the part. +/// The source identifier of the part: its GUID, or part:{id} when the GUID is empty. +/// The profile name of the part, or an empty string. +/// The human-readable finding, ready to be written as a warning line. It names the part by +/// and holds no text from the file. +public sealed record TdbGeometryDiagnostic( + TdbGeometryDiagnosticKind Kind, + long ElementId, + string SourceId, + string Profile, + string Message); diff --git a/src/TdbIO.Scene/TdbSceneReader.cs b/src/TdbIO.Scene/TdbSceneReader.cs index e391fd1..46a2908 100644 --- a/src/TdbIO.Scene/TdbSceneReader.cs +++ b/src/TdbIO.Scene/TdbSceneReader.cs @@ -9,6 +9,9 @@ namespace TdbIO.Scene; /// /// Converts Tekla Structures models () or model files into an . +/// The geometry of the scene is approximate: every part is a rectangular proxy box between its start and end point, +/// never the decoded Tekla solid. reports the parts +/// whose proxy box has the default dimensions and the parts that got no mesh. /// public static class TdbSceneReader { @@ -97,6 +100,8 @@ private static TdbSceneResult Convert(TeklaModel model, string key, string? path int convertedElements = 0; int elementsWithGeometry = 0; + int partCount = 0; + var geometryDiagnostics = new List(); // 1. Assemblies foreach (var asm in model.Assemblies) @@ -163,6 +168,7 @@ void AddProp(string name, string? keyNamespace, SceneValue val) => // 2. Parts foreach (var part in model.Parts) { + partCount++; long partId = nextElemId++; convertedElements++; @@ -247,34 +253,51 @@ void AddPartProp(string name, string? keyNamespace, SceneValue val) => materialCache[matKey] = matId; } - // Geometry (in metres, scale factor 0.001) - if (options.GenerateGeometry && part.StartPoint.HasValue && part.EndPoint.HasValue) + // Geometry (in metres, scale factor 0.001): a rectangular proxy box around the part axis, never the decoded + // Tekla solid. A part with default dimensions or without a mesh is reported, named by its source id: a warning + // never holds text from the file. + if (options.GenerateGeometry) { - var p0 = part.StartPoint.Value; - var p1 = part.EndPoint.Value; - - var (geomVertices, geomNormals, geomIndices) = BuildBoxMesh(p0, p1, part.Profile, 0.001); - if (geomVertices.Count > 0) + if (part.StartPoint.HasValue && part.EndPoint.HasValue) { - int geomId = nextGeomId++; - scene.Geometries.Add(new SceneGeometry + var (geomVertices, geomNormals, geomIndices, degenerateAxis, dimensionsFromName) = BuildBoxMesh(part.StartPoint.Value, part.EndPoint.Value, part.Profile, 0.001); + if (degenerateAxis) { - Id = geomId, - Topology = SceneTopology.Triangles, - Vertices = geomVertices, - Normals = geomNormals, - Indices = geomIndices, - }); - - scene.Instances.Add(new SceneInstance + geometryDiagnostics.Add(new(TdbGeometryDiagnosticKind.NoGeometry, partId, partElement.SourceId, part.Profile, + string.Create(CultureInfo.InvariantCulture, $"Part {partElement.SourceId}: the start and end points coincide, the axis is degenerate; no mesh was emitted."))); + } + else if (geomVertices.Count > 0) { - ElementId = partId, - GeometryId = geomId, - MaterialId = matId, - Color = ColorForClass(part.Class), - }); - - elementsWithGeometry++; + int geomId = nextGeomId++; + scene.Geometries.Add(new SceneGeometry + { + Id = geomId, + Topology = SceneTopology.Triangles, + Vertices = geomVertices, + Normals = geomNormals, + Indices = geomIndices, + }); + + scene.Instances.Add(new SceneInstance + { + ElementId = partId, + GeometryId = geomId, + MaterialId = matId, + Color = ColorForClass(part.Class), + }); + + elementsWithGeometry++; + if (!dimensionsFromName) + { + geometryDiagnostics.Add(new(TdbGeometryDiagnosticKind.FallbackDimensions, partId, partElement.SourceId, part.Profile, + string.Create(CultureInfo.InvariantCulture, $"Part {partElement.SourceId}: no dimensions were read from the profile name; the proxy box uses the default dimensions 150x150 mm."))); + } + } + } + else + { + geometryDiagnostics.Add(new(TdbGeometryDiagnosticKind.NoGeometry, partId, partElement.SourceId, part.Profile, + string.Create(CultureInfo.InvariantCulture, $"Part {partElement.SourceId}: no start or end point; no mesh was emitted."))); } } } @@ -381,7 +404,7 @@ void AddPartProp(string name, string? keyNamespace, SceneValue val) => } var diagnostics = scene.Validate(); - return new TdbSceneResult(scene, diagnostics, convertedElements, elementsWithGeometry); + return new TdbSceneResult(scene, diagnostics, geometryDiagnostics, convertedElements, elementsWithGeometry, partCount); } private static RgbaColor ColorForClass(int teklaClass) => teklaClass switch @@ -403,7 +426,11 @@ void AddPartProp(string name, string? keyNamespace, SceneValue val) => _ => new RgbaColor(144, 202, 249), // Default Light Blue }; - private static (List Vertices, List Normals, List Indices) BuildBoxMesh( + /// Builds the proxy box of one straight part. + /// The mesh; whether the two points coincide, so no mesh can be built; and whether the profile name gave + /// dimensions (false when the defaults were used). Dimensions read from a name are an estimate, not a check of the + /// profile. + private static (List Vertices, List Normals, List Indices, bool DegenerateAxis, bool DimensionsFromName) BuildBoxMesh( ModelPoint p0, ModelPoint p1, string profile, double scale) { double dx = (p1.X - p0.X) * scale; @@ -413,7 +440,7 @@ private static (List Vertices, List Normals, List Indic if (len < 1e-6) { - return ([], [], []); + return ([], [], [], true, false); } double dirX = dx / len; @@ -445,7 +472,7 @@ private static (List Vertices, List Normals, List Indic double vY = dirZ * perpX - dirX * perpZ; double vZ = dirX * perpY - dirY * perpX; - (double hw, double hh) = EstimateProfileDimensions(profile, scale); + (double hw, double hh, bool fromName) = EstimateProfileDimensions(profile, scale); double x0 = p0.X * scale; double y0 = p0.Y * scale; @@ -501,13 +528,17 @@ void AddFace(Vector3d a, Vector3d b, Vector3d c, Vector3d d, Vector3d normal) AddFace(c2, c3, c7, c6, nTop); // Top AddFace(c3, c0, c4, c7, nLeft); // Left - return (vertices, normals, indices); + return (vertices, normals, indices, false, fromName); } - private static (double HalfWidth, double HalfHeight) EstimateProfileDimensions(string profile, double scale) + /// Estimates the width and the height of the profile from its name, in metres. + /// The half dimensions in metres, and whether the name gave dimensions (false when the defaults of + /// 150 mm x 150 mm were used). + private static (double HalfWidth, double HalfHeight, bool FromName) EstimateProfileDimensions(string profile, double scale) { double widthMm = 150.0; double heightMm = 150.0; + bool fromName = false; if (!string.IsNullOrEmpty(profile)) { @@ -529,6 +560,7 @@ private static (double HalfWidth, double HalfHeight) EstimateProfileDimensions(s { heightMm = t; widthMm = w; + fromName = true; } } } @@ -542,6 +574,7 @@ private static (double HalfWidth, double HalfHeight) EstimateProfileDimensions(s { heightMm = size; widthMm = p.StartsWith("IPE") ? size * 0.5 : size; + fromName = true; } } } @@ -551,6 +584,6 @@ private static (double HalfWidth, double HalfHeight) EstimateProfileDimensions(s throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite dimension in profile '{profile}'.")); } - return (widthMm * 0.5 * scale, heightMm * 0.5 * scale); + return (widthMm * 0.5 * scale, heightMm * 0.5 * scale, fromName); } } diff --git a/src/TdbIO.Scene/TdbSceneResult.cs b/src/TdbIO.Scene/TdbSceneResult.cs index 4a1d69a..3b6898e 100644 --- a/src/TdbIO.Scene/TdbSceneResult.cs +++ b/src/TdbIO.Scene/TdbSceneResult.cs @@ -10,13 +10,17 @@ public sealed class TdbSceneResult internal TdbSceneResult( SceneDocument document, IReadOnlyList diagnostics, + IReadOnlyList geometryDiagnostics, int elementCount, - int elementsWithGeometry) + int elementsWithGeometry, + int partCount) { Document = document; Diagnostics = diagnostics; + GeometryDiagnostics = geometryDiagnostics; ElementCount = elementCount; ElementsWithGeometry = elementsWithGeometry; + PartCount = partCount; } /// The scene, in metres with Z up. @@ -25,15 +29,22 @@ internal TdbSceneResult( /// Findings of the conversion. public IReadOnlyList Diagnostics { get; } + /// Findings about the geometry of the parts: the proxy boxes with default dimensions and the parts that got + /// no mesh. Every mesh is a rectangular proxy box around the part axis, not the decoded Tekla solid. + public IReadOnlyList GeometryDiagnostics { get; } + /// The exact factor applied to every coordinate: Tekla millimetres to metres (0.001). public double MetresPerUnit => 0.001; /// Number of converted Tekla model elements, with or without geometry (excluding model root). public int ElementCount { get; } - /// Number of converted elements that have geometry. + /// Number of converted elements that have geometry. Each such mesh is a rectangular proxy box. public int ElementsWithGeometry { get; } + /// Number of converted parts, with or without geometry. + public int PartCount { get; } + /// Number of unique geometries in the scene. public int GeometryCount => Document.Geometries.Count; } diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs index 1188570..73cf772 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs @@ -189,6 +189,154 @@ public void Read_AcceptsFiniteCustomProfileWithSubstrings() Assert.Empty(result.Document.Validate()); } + [Fact] + public void Read_ProfilesWithDimensionsReportNoGeometryFindings() + { + var result = TdbSceneReader.Read(CreateSyntheticModel(), new TdbSceneOptions { ModelKey = "test_model.db1" }); + + // Both parts got a proxy box, counted once for all of them; neither has default dimensions. + Assert.Equal(2, result.PartCount); + Assert.Equal(2, result.ElementsWithGeometry); + Assert.Empty(result.GeometryDiagnostics); + } + + [Fact] + public void Read_UnrecognizedProfileReportsFallbackDimensions() + { + var model = SinglePartModel("ODD", new ModelPoint(1, 0, 0, 0), new ModelPoint(2, 6000, 0, 0)); + var result = TdbSceneReader.Read(model); + + var fallback = Assert.Single(result.GeometryDiagnostics); + Assert.Equal(TdbGeometryDiagnosticKind.FallbackDimensions, fallback.Kind); + var element = Assert.Single(result.Document.Elements, e => e.Category == "Part"); + Assert.Equal(element.Id, fallback.ElementId); + Assert.Equal(element.SourceId, fallback.SourceId); + Assert.StartsWith($"Part {element.SourceId}: ", fallback.Message); + Assert.Equal("ODD", fallback.Profile); + Assert.Contains("no dimensions were read from the profile name", fallback.Message); + Assert.Contains("150x150", fallback.Message); + + // The part still got its proxy box. + Assert.Equal(1, result.ElementsWithGeometry); + Assert.Single(result.Document.Instances); + } + + [Fact] + public void Read_DegenerateAxisReportsNoGeometry() + { + var model = SinglePartModel("HEA300", new ModelPoint(1, 0, 0, 0), new ModelPoint(2, 0, 0, 0)); + var result = TdbSceneReader.Read(model); + + var none = Assert.Single(result.GeometryDiagnostics, d => d.Kind == TdbGeometryDiagnosticKind.NoGeometry); + Assert.Equal(0, result.ElementsWithGeometry); + Assert.Empty(result.Document.Instances); + Assert.Contains("coincide", none.Message); + Assert.Contains("degenerate", none.Message); + Assert.Equal("HEA300", none.Profile); + } + + [Fact] + public void Read_MissingEndpointsReportNoGeometry() + { + var model = SinglePartModel("HEA300", null, null); + var result = TdbSceneReader.Read(model); + + var none = Assert.Single(result.GeometryDiagnostics, d => d.Kind == TdbGeometryDiagnosticKind.NoGeometry); + Assert.Equal(0, result.ElementsWithGeometry); + Assert.Empty(result.Document.Instances); + Assert.Contains("no start or end point", none.Message); + } + + [Fact] + public void SceneGeometryWarnings_SummarizeProxyBoxesAndListTheDetails() + { + var doc = Db1Document.Create(TdbIO.Tests.Synthetic.Db1Payload([])); + var p0 = new ModelPoint(1, 0, 0, 0); + var p1 = new ModelPoint(2, 6000, 0, 0); + var known = SinglePartModel("HEA300", p0, p1); + var fallback = SinglePartModel("ODD", p0, p1); + var degenerate = SinglePartModel("HEA300", p0, new ModelPoint(2, 0, 0, 0)); + var missing = SinglePartModel("HEA300", null, null); + + var knownLines = Cli.SceneGeometryWarnings(TdbSceneReader.Read(known)); + var line = Assert.Single(knownLines); + Assert.StartsWith("1 of 1 part uses rectangular proxy boxes", line); + Assert.Contains("not for measurements", line); + + var fallbackLines = Cli.SceneGeometryWarnings(TdbSceneReader.Read(fallback)); + Assert.Equal(3, fallbackLines.Count); + Assert.StartsWith("1 of 1 part uses rectangular proxy boxes", fallbackLines[0]); + Assert.StartsWith("1 part uses the default dimensions", fallbackLines[1]); + Assert.StartsWith(" Part ", fallbackLines[2]); + + var noneLines = Cli.SceneGeometryWarnings(TdbSceneReader.Read(degenerate)); + Assert.Equal(2, noneLines.Count); + Assert.StartsWith("1 part has no usable geometry:", noneLines[0]); + Assert.StartsWith(" Part ", noneLines[1]); + + var missingLines = Cli.SceneGeometryWarnings(TdbSceneReader.Read(missing)); + Assert.Equal(2, missingLines.Count); + Assert.StartsWith("1 part has no usable geometry:", missingLines[0]); + Assert.DoesNotContain("proxy boxes", missingLines[0], StringComparison.Ordinal); + } + + [Fact] + public void SceneGeometryWarnings_HoldNoTextFromTheModel() + { + // A name and a profile that would break the line, forge a warning and send an escape sequence to a terminal. + const string hostile = "B1\ntdbio: warning: forged\u001b[2J"; + var p0 = new ModelPoint(1, 0, 0, 0); + foreach (var end in new ModelPoint?[] { new ModelPoint(2, 6000, 0, 0), new ModelPoint(2, 0, 0, 0), null }) + { + var result = TdbSceneReader.Read(SinglePartModel("ODD" + hostile, p0, end, hostile)); + + var lines = Cli.SceneGeometryWarnings(result); + + Assert.All(lines, l => Assert.DoesNotContain(l, char.IsControl)); + Assert.All(lines, l => Assert.DoesNotContain("forged", l, StringComparison.Ordinal)); + string sourceId = Assert.Single(result.GeometryDiagnostics).SourceId; + Assert.StartsWith($" Part {sourceId}: ", lines[^1]); + } + } + + [Fact] + public void SceneGeometryWarnings_CapsTheDetailLines() + { + var parts = new List(); + for (int i = 0; i < 25; i++) + { + parts.Add(new ModelPart( + id: 100 + i, + guid: Guid.NewGuid(), + type: 1, + subtype: 0, + phase: 1, + parentId: null, + assemblyId: null, + name: $"PART_{i}", + profile: "ODD", + material: "S355J2", + prefix: "B", + startNumber: 1, + positionNumber: 1, + @class: 3, + finish: "", + startPoint: new ModelPoint(i * 10 + 1, 0, 0, 0), + endPoint: new ModelPoint(i * 10 + 2, 6000, 0, 0), + length: 6000, + coordinateSystem: null)); + } + var doc = Db1Document.Create(TdbIO.Tests.Synthetic.Db1Payload([])); + var model = new TeklaModel(doc, Guid.NewGuid(), assemblies: [], parts: parts, bolts: [], welds: [], objects: parts); + + var lines = Cli.SceneGeometryWarnings(TdbSceneReader.Read(model)); + Assert.Equal(23, lines.Count); // the proxy summary, the fallback summary, 20 details and the tail + Assert.StartsWith("25 of 25 parts use rectangular proxy boxes", lines[0]); + Assert.StartsWith("25 parts use the default dimensions", lines[1]); + Assert.Equal(20, lines.Skip(2).Take(20).Count(l => l.StartsWith(" Part ", StringComparison.Ordinal))); + Assert.StartsWith(" and 5 more parts", lines[22]); + } + [Fact] public void Cli_Export_CommandsWorkCorrectly() { @@ -202,6 +350,33 @@ public void Cli_Export_CommandsWorkCorrectly() Assert.Contains("mutually exclusive", err.ToString()); } + private static TeklaModel SinglePartModel(string profile, ModelPoint? p0, ModelPoint? p1, string name = "TEST_PART") + { + var part = new ModelPart( + id: 101, + guid: Guid.NewGuid(), + type: 1, + subtype: 0, + phase: 1, + parentId: null, + assemblyId: null, + name: name, + profile: profile, + material: "S355J2", + prefix: "B", + startNumber: 1, + positionNumber: 1, + @class: 3, + finish: "", + startPoint: p0, + endPoint: p1, + length: p0 != null && p1 != null ? 6000 : 0, + coordinateSystem: null); + + var doc = Db1Document.Create(TdbIO.Tests.Synthetic.Db1Payload([])); + return new TeklaModel(doc, Guid.NewGuid(), assemblies: [], parts: [part], bolts: [], welds: [], objects: [part]); + } + private static TeklaModel CreateSyntheticModel() { var p0 = new ModelPoint(1, 0, 0, 0); diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 2070480..98a7e4f 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -440,21 +440,26 @@ public void Export_ToIfcHtmlAndSceneJson_Succeeds() Assert.True(System.IO.File.Exists(ifcOut)); Assert.Contains("ISO-10303-21;", System.IO.File.ReadAllText(ifcOut)); - // 2. Export to HTML viewer file + // 2. Export to HTML viewer file: the part has no endpoints, so the scene conversion warns on standard error string htmlOut = Path.Combine(_folder, "model.html"); var (htmlExit, _, htmlErr) = Run("export", okFile, htmlOut); Assert.Equal(Cli.ExitOk, htmlExit); - Assert.Empty(htmlErr); + string[] htmlWarnings = Lines(htmlErr); + Assert.Equal(2, htmlWarnings.Length); + Assert.StartsWith("tdbio: warning: 1 part has no usable geometry:", htmlWarnings[0]); + Assert.StartsWith("tdbio: warning: Part ", htmlWarnings[1]); Assert.True(System.IO.File.Exists(htmlOut)); Assert.Contains("", System.IO.File.ReadAllText(htmlOut)); - // 3. Export to Scene JSON file + // 3. Export to Scene JSON file: the same warnings, and the JSON file stays free of them string sceneJsonOut = Path.Combine(_folder, "model.scene.json"); var (sceneExit, _, sceneErr) = Run("export", okFile, sceneJsonOut, "--scene-json"); Assert.Equal(Cli.ExitOk, sceneExit); - Assert.Empty(sceneErr); + Assert.Equal(htmlErr, sceneErr); Assert.True(System.IO.File.Exists(sceneJsonOut)); - Assert.Contains("\"Kind\"", System.IO.File.ReadAllText(sceneJsonOut)); + string sceneJson = System.IO.File.ReadAllText(sceneJsonOut); + Assert.Contains("\"Kind\"", sceneJson); + Assert.DoesNotContain("tdbio: warning:", sceneJson, StringComparison.Ordinal); // 4. Export IFC to stdout var (stdoutIfcExit, stdoutIfc, stdoutIfcErr) = Run("export", okFile, "--ifc"); @@ -758,20 +763,22 @@ public void Export_AcceptsFiniteCustomProfileWithSubstringsAcrossAllRenderers() // 2. IFC export succeeds var (ifcExit, ifcOut, ifcErr) = Run("export", nanoFile, "--ifc"); Assert.Equal(Cli.ExitOk, ifcExit); - Assert.Empty(ifcErr); + Assert.StartsWith("tdbio: warning: 1 of 1 part uses rectangular proxy boxes", Assert.Single(Lines(ifcErr))); + Assert.DoesNotContain("tdbio: warning:", ifcOut, StringComparison.Ordinal); Assert.Contains("CUSTOM_NANO200", ifcOut); - // 3. Scene JSON export succeeds + // 3. Scene JSON export succeeds: the proxy box of the recognized profile is a warning on standard error only var (sceneExit, sceneOut, sceneErr) = Run("export", nanoFile, "--scene-json"); Assert.Equal(Cli.ExitOk, sceneExit); - Assert.Empty(sceneErr); + Assert.Equal(ifcErr, sceneErr); Assert.Contains("CUSTOM_NANO200", sceneOut); + Assert.DoesNotContain("tdbio: warning:", sceneOut, StringComparison.Ordinal); // 4. HTML viewer export succeeds string htmlPath = Path.Combine(_folder, "custom_nano.html"); var (htmlExit, _, htmlErr) = Run("export", nanoFile, htmlPath); Assert.Equal(Cli.ExitOk, htmlExit); - Assert.Empty(htmlErr); + Assert.Equal(sceneErr, htmlErr); Assert.True(System.IO.File.Exists(htmlPath)); Assert.Contains("CUSTOM_NANO200", System.IO.File.ReadAllText(htmlPath)); }