diff --git a/README.md b/README.md index f78661f1..55bb95dd 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ RvtIO is a .NET library and command line tool that reads Autodesk Revit projects - Queries elements through `FilteredElementCollector`. - Exports IFC2X3 coordination view (default) and IFC4 (ISO 16739-1:2018 / ADD2 TC1; `ReferenceView_V1.2` and `DesignTransferView_V1.0`), with shared JSON/API configuration presets and optional Revit parameters as property sets. - Exports binary glTF 2.0 (`.glb`) directly via `GlbExporter` / `--glb` in Y-up metres with shared family symbol meshes, PBR colors/transparency, and element/material metadata in `extras`. +- Exports element CSV with identifiers shared with GLB and quantities in SI units. - Writes compact JSON or a full JSON dump with every parameter and geometry. - Returns the triangle meshes of the model elements, with one shared mesh per family symbol for repeated instances (`ElementMeshes`). - Lists the sheets of a file and the viewports placed on them (`SheetCatalog`), with the sheet number, name, issue date, by-lines, the viewports of each sheet and the elements each sheet owns. Page size, view placement and 2D content are not decoded yet; the catalog reports each limit. @@ -87,10 +88,10 @@ rvtio project.rvt project.glb Export multiple formats in a single read: ```sh -rvtio project.rvt --ifc project.ifc --glb project.glb --compact-json project.compact.json --scene project.scene.json +rvtio project.rvt --ifc project.ifc --glb project.glb --csv elements.csv --compact-json project.compact.json --scene project.scene.json ``` -A `.ifc` output path selects IFC and a `.glb` output path selects binary glTF 2.0 (GLB). Any other output path selects JSON, which is compact by default. When `--ifc`, `--glb`, `--compact-json`, `--full-json`, or `--scene` are specified, the model is read once and each requested format is exported sequentially. Positional output arguments remain fully backward compatible. Single-output and multi-output exports produce byte-identical files. On Revit 2023+ (own-schema) models, JSON formats retain their wide-schema representation by default (use `--r22-layout` to export JSON in Revit 2022 layout too), while IFC, GLB, and Scene exports use the Revit 2022 geometry layout, sharing decoded geometry and quantities without reading the model again. If no output path is given, the tool writes `output.json`. Diagnostics go to standard error. See [GLB export](docs/glb-export.md). +A `.ifc` output path selects IFC and a `.glb` output path selects binary glTF 2.0 (GLB). Any other positional output path selects JSON, which is compact by default. With explicit output options, the model is read once and each requested format is exported sequentially. Single-output and multi-output exports produce byte-identical files. On Revit 2023+ (own-schema) models, JSON formats retain their wide-schema representation by default (use `--r22-layout` to export JSON in Revit 2022 layout too), while IFC, GLB, CSV, and Scene exports use the Revit 2022 layout. If no output path is given, the tool writes `output.json`. Diagnostics go to standard error. See [GLB export and element CSV](docs/glb-export.md). List the sheets and the viewports placed on them: diff --git a/docs/glb-export.md b/docs/glb-export.md index b717367b..b1071113 100644 --- a/docs/glb-export.md +++ b/docs/glb-export.md @@ -44,4 +44,19 @@ rvtio project.rvt --glb project.glb --ifc project.ifc --compact-json project.jso With `--report`, a GLB-only run includes element, node and mesh counts in `export`. When IFC or JSON provides the main `export` summary, the GLB counts appear in `glbExport`. -When `--glb` is combined with `--ifc`, `--scene`, `--compact-json`, or `--full-json`, the `.rvt` file is read once (and `ElementMeshes` is extracted once when paired with `--scene`). +When `--glb` is combined with `--csv`, `--ifc`, `--scene`, `--compact-json`, or `--full-json`, the `.rvt` file is read once (and `ElementMeshes` is extracted once when paired with `--scene`). + +## Element CSV + +```sh +rvtio project.rvt --csv elements.csv +rvtio project.rvt --glb project.glb --csv elements.csv +``` + +The CSV has one record per decoded element, sorted by `elementId`, including types and elements without geometry. +It excludes orphan geometry blocks and discovered records outside an exact element table. Join the CSV to glTF node +`extras.elementId` from the same model. The CSV and GLB also share `uniqueId` and `ifcGuid` when available. + +The measurement columns `length_m`, `area_m2`, and `volume_m3` contain stored Revit quantities converted to metres, +square metres, and cubic metres. Missing or approximate measurements are blank, and stored zeroes are written as zero. +The CSV uses UTF-8 with a BOM and invariant decimal formatting. The library API is `RvtIO.Csv.ElementCsvExporter.Export`. diff --git a/src/RvtIO.Cli/ExportCommand.cs b/src/RvtIO.Cli/ExportCommand.cs index d5fa3801..4f584535 100644 --- a/src/RvtIO.Cli/ExportCommand.cs +++ b/src/RvtIO.Cli/ExportCommand.cs @@ -3,6 +3,7 @@ using RvtIO.Internal; using RvtIO; using RvtIO.Compact; +using RvtIO.Csv; using RvtIO.BuiltIns; using RvtIO.Ifc; using RvtIO.Gltf; @@ -11,7 +12,7 @@ internal static partial class Program { /// The values of the command line that decide the export. - private sealed record ExportArguments(string[] Args, string RvtPath, string? IfcPath, string? GlbPath, string? CompactJsonPath, string? FullJsonPath, string? ScenePath, + private sealed record ExportArguments(string[] Args, string RvtPath, string? IfcPath, string? GlbPath, string? CsvPath, string? CompactJsonPath, string? FullJsonPath, string? ScenePath, string? ExternalDumpPath, string? ExternalDumpClassPrefix, IfcProfile Profile, string JsonClassPrefix, IfcExportConfiguration MergedIfcConfiguration, string? SaveIfcConfigPath); @@ -32,15 +33,16 @@ private static ExportInput ReadExportInput(string path, RvtReaderOptions options return new(model, json, names, reader.WideState is { } wide ? new JsonReadFacts(wide, compact, debugNative) : names, quantities, state.ElemTable.Keys); } - // The export: reads the file and writes the requested formats (IFC, GLB, scene JSON, compact JSON, full JSON). + // The export: reads the file and writes the requested formats (IFC, GLB, element CSV, scene JSON, compact JSON, full JSON). private static int Export(ExportArguments arguments) { - var (args, rvtPath, ifcPath, glbPath, compactJsonPath, fullJsonPath, scenePath, externalDumpPath, externalDumpClassPrefix, profile, jsonClassPrefix, mergedIfcConfig, saveIfcConfigPath) = arguments; + var (args, rvtPath, ifcPath, glbPath, csvPath, compactJsonPath, fullJsonPath, scenePath, externalDumpPath, externalDumpClassPrefix, profile, jsonClassPrefix, mergedIfcConfig, saveIfcConfigPath) = arguments; WarnIfRevitLocalization(args); var exportOutputs = new List<(string Option, string Path)>(); if (ifcPath != null) exportOutputs.Add(("--ifc", ifcPath)); if (glbPath != null) exportOutputs.Add(("--glb", glbPath)); + if (csvPath != null) exportOutputs.Add(("--csv", csvPath)); if (compactJsonPath != null) exportOutputs.Add(("--compact-json", compactJsonPath)); if (fullJsonPath != null) exportOutputs.Add(("--full-json", fullJsonPath)); if (scenePath != null) exportOutputs.Add(("--scene", scenePath)); @@ -71,7 +73,7 @@ private static int Export(ExportArguments arguments) } } - bool needIfcLayout = ifcPath != null || scenePath != null || glbPath != null; + bool needIfcLayout = ifcPath != null || scenePath != null || glbPath != null || csvPath != null; bool multiJson = compactJsonPath != null && fullJsonPath != null; bool needR22 = needIfcLayout || multiJson; bool hasJsonOutput = compactJsonPath != null || fullJsonPath != null; @@ -84,7 +86,7 @@ private static int Export(ExportArguments arguments) ExternalDumpClassPrefix = externalDumpClassPrefix, SystemFamilyNameLocale = profile == RvtIO.Ifc.IfcProfile.Current ? "ENU" : null, SeparateFacesWithDistinctOpenings = profile == RvtIO.Ifc.IfcProfile.Current, - // IFC, Scene, and multi-JSON exports decode geometry with the Revit 2022 readers; --no-r22-layout keeps the 64-bit schema path alone + // CSV uses the same element layout as GLB; --no-r22-layout keeps the 64-bit schema path alone. R22Layout = (needR22 && !noR22) || explicitR22, PreserveWideLayout = (needIfcLayout || multiJson) && hasJsonOutput && !explicitR22 && !noR22, ResolveCurrentCopies = RvtIO.Cli.CurrentCopiesOption.Resolve(args), @@ -165,10 +167,12 @@ private static int Export(ExportArguments arguments) var jsonState = input.JsonFacts; var ifcModel = input.Geometry; GlbExportResult? glbResult = null; + var sceneDocument = scenePath != null || glbPath != null || csvPath != null + ? RvtDocument.ForSceneExport(ifcModel) : null; if (scenePath != null || glbPath != null) { - var doc = RvtDocument.ForSceneExport(ifcModel); + var doc = sceneDocument!; var sharedMeshes = RvtIO.Meshes.ElementMeshes.Extract(doc); if (scenePath != null) { @@ -206,6 +210,14 @@ private static int Export(ExportArguments arguments) } } + if (csvPath != null) + { + var swCsv = System.Diagnostics.Stopwatch.StartNew(); + int count = ElementCsvExporter.Export(sceneDocument!, csvPath); + Console.Error.WriteLine($"Timing: csv {swCsv.Elapsed.TotalSeconds:F1}s"); + Console.Error.WriteLine($"CSV written to {csvPath} ({count} elements)"); + } + if (ifcPath != null) { // Without the option the current profile exports the rooms of the last project phase that exists as a phase element (the diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 7245cf27..df1766a7 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -10,14 +10,15 @@ internal static partial class Program Usage: rvtio [output.ifc|output.json|output.glb] [options] rvtio --help | --version - Reads a Revit file and writes IFC, GLB, JSON, or an IOScene scene. A .ifc output path writes IFC and a .glb + Reads a Revit file and writes IFC, GLB, element CSV, JSON, or an IOScene scene. A .ifc output path writes IFC and a .glb output path writes binary glTF 2.0 (GLB); any other path writes JSON (default output.json). Pass multiple output - options (--ifc, --glb, --scene, --compact-json, --full-json) to write several formats from a single file read. + options (--ifc, --glb, --csv, --scene, --compact-json, --full-json) to write several formats from a single file read. Diagnostics go to standard error. Export options: --ifc write IFC output to the specified path --glb write binary glTF 2.0 (.glb) output to the specified path + --csv write one record per element with GLB identifiers and SI quantities --scene write IOScene scene JSON to the specified path --compact-json [file.json] write compact JSON (optionally to the specified path) --full-json write the full JSON dump to the specified path @@ -130,7 +131,7 @@ apply an ordered batch of supported parameter assignments and clears atomically // Options that take one value, and options that take two; every other option starting with "--" is a switch. private static readonly HashSet OneValueOptions = [ - "--ifc", "--glb", "--scene", "--full-json", "--json", + "--ifc", "--glb", "--csv", "--scene", "--full-json", "--json", "--ifc-profile", "--ifc-phase", "--ifc-room-phase", RvtIO.Cli.IfcConfigurationOptions.SchemaOption, RvtIO.Cli.IfcConfigurationOptions.ModelViewOption, @@ -213,6 +214,7 @@ internal static int Main(string[] args) string? ifcPath = null; string? glbPath = null; + string? csvPath = null; string? scenePath = null; string? fullJsonPath = null; string? explicitJsonPath = null; @@ -222,7 +224,7 @@ internal static int Main(string[] args) for (int i = 1; i < args.Length; i++) { string arg = args[i]; - if (arg is "--ifc" or "--glb" or "--scene" or "--full-json" or "--json") + if (arg is "--ifc" or "--glb" or "--csv" or "--scene" or "--full-json" or "--json") { if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal) || string.IsNullOrWhiteSpace(args[i + 1])) { @@ -232,6 +234,7 @@ internal static int Main(string[] args) string path = args[++i]; if (arg == "--ifc") ifcPath = path; else if (arg == "--glb") glbPath = path; + else if (arg == "--csv") csvPath = path; else if (arg == "--scene") scenePath = path; else if (arg == "--full-json") fullJsonPath = path; else if (arg == "--json") explicitJsonPath = path; @@ -293,7 +296,7 @@ static bool IsNonJsonPositionalExtension(string path) => : "output.json"; } - bool anyExplicitOutput = ifcPath != null || glbPath != null || scenePath != null || compactJsonPath != null || fullJsonPath != null; + bool anyExplicitOutput = ifcPath != null || glbPath != null || csvPath != null || scenePath != null || compactJsonPath != null || fullJsonPath != null; if (!anyExplicitOutput) { if (jsonFull) fullJsonPath = "output.json"; @@ -407,7 +410,7 @@ static bool IsNonJsonPositionalExtension(string path) => && !RvtIO.Cli.IfcConfigurationOptions.CanSaveConfiguration( saveConfigPath, hasIfcOutput || !rvtPath.StartsWith("--", StringComparison.Ordinal) ? rvtPath : null, cliIfcOptions.ConfigPath, hasIfcOutput ? [ - ifcPath, glbPath, compactJsonPath, fullJsonPath, scenePath, ValueOf(args, "--report"), ValueOf(args, "--dev-external-dump"), + ifcPath, glbPath, csvPath, compactJsonPath, fullJsonPath, scenePath, ValueOf(args, "--report"), ValueOf(args, "--dev-external-dump"), ..RvtIO.Cli.ReportPathOption.DumpOptions.Select(option => ValueOf(args, option)), ] : [])) return 1; @@ -504,7 +507,7 @@ static bool IsNonJsonPositionalExtension(string path) => if (inspectBatchIdsFile != null && inspectBatchOutPath != null) return InspectBatch(rvtPath, inspectBatchIdsFile, inspectBatchOutPath); if (listCategoryOutPath != null) return ListCategory(rvtPath, listCategoryId, listCategoryOutPath); - return Export(new ExportArguments(args, rvtPath, ifcPath, glbPath, compactJsonPath, fullJsonPath, scenePath, + return Export(new ExportArguments(args, rvtPath, ifcPath, glbPath, csvPath, compactJsonPath, fullJsonPath, scenePath, externalDumpPath, externalDumpClassPrefix, resolvedIfcConfiguration.Profile, jsonClassPrefix, mergedIfcConfiguration, cliIfcOptions.SaveConfigPath)); } diff --git a/src/RvtIO.Cli/ReportPathOption.cs b/src/RvtIO.Cli/ReportPathOption.cs index c52d89e6..15ec4e52 100644 --- a/src/RvtIO.Cli/ReportPathOption.cs +++ b/src/RvtIO.Cli/ReportPathOption.cs @@ -7,7 +7,7 @@ internal static class ReportPathOption /// The dump options of the export whose value is an output path. public static readonly string[] DumpOptions = ["--dev-candidates", "--dev-trace", "--dev-facts", "--dev-solids", "--dev-user-params", "--dev-collisions", - "--ifc", "--glb", "--scene", "--full-json", "--json"]; + "--ifc", "--glb", "--csv", "--scene", "--full-json", "--json"]; /// Every file the command line names as an output: the input never, the export and every named dump. public static IEnumerable OutputPaths(string[] args, string rvtPath, string? outputPath, string? externalDumpPath) diff --git a/src/RvtIO/Csv/ElementCsvExporter.cs b/src/RvtIO/Csv/ElementCsvExporter.cs new file mode 100644 index 00000000..90d1f328 --- /dev/null +++ b/src/RvtIO/Csv/ElementCsvExporter.cs @@ -0,0 +1,103 @@ +using System.Globalization; +using System.Text; +using RvtIO.BuiltIns; +using RvtIO.Ifc; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Csv; + +/// Exports one CSV record per decoded Revit element, with GLB-compatible identifiers. +public static class ElementCsvExporter +{ + private const double MetresPerFoot = 0.3048; + private const double SquareMetresPerSquareFoot = MetresPerFoot * MetresPerFoot; + private const double CubicMetresPerCubicFoot = SquareMetresPerSquareFoot * MetresPerFoot; + + /// Writes a UTF-8 CSV file, replacing an existing destination atomically, and returns the number of data rows. + public static int Export(RvtDocument document, string outputPath) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); + if (document.SourcePath is { } source && FileIdentity.SameFile(source, outputPath)) + throw new ArgumentException("The CSV destination must not name the source model.", nameof(outputPath)); + + string destination = Path.GetFullPath(outputPath); + if (Path.GetDirectoryName(destination) is { Length: > 0 } directory) + Directory.CreateDirectory(directory); + + string temporary = destination + "." + Guid.NewGuid().ToString("N") + ".tmp"; + var stream = File.Open(temporary, FileMode.CreateNew, FileAccess.Write); + try + { + int count; + using (stream) + using (var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)) { NewLine = "\r\n" }) + count = WriteRows(document, writer); + File.Move(temporary, destination, overwrite: true); + return count; + } + finally + { + File.Delete(temporary); + } + } + + private static int WriteRows(RvtDocument document, TextWriter writer) + { + writer.WriteLine("elementId,uniqueId,ifcGuid,categoryId,category,name,typeId,typeName,length_m,area_m2,volume_m3"); + int count = 0; + foreach (var element in document.Elements.DistinctBy(e => e.Id).OrderBy(e => e.Id)) + { + if (element.IsBlockOnly || (document.RawData.ElemTableIsExact && element.IsDiscovered)) + continue; + + string? category = element.CategoryId is int id && ((BuiltInCategory)id).TryGetCategoryName(out string? name) + ? name : element.Category; + int? categoryId = element.CategoryId is 0 or int.MinValue ? null : element.CategoryId; + int? typeId = element.TypeId > 0 ? element.TypeId : null; + bool room = element.CategoryId is (int)BuiltInCategory.OST_Rooms or (int)BuiltInCategory.OST_MEPSpaces; + double? length = Quantity(element, BuiltInParameter.CURVE_ELEM_LENGTH); + double? area = Quantity(element, room ? BuiltInParameter.ROOM_AREA : BuiltInParameter.HOST_AREA_COMPUTED); + double? volume = Quantity(element, room ? BuiltInParameter.ROOM_VOLUME : BuiltInParameter.HOST_VOLUME_COMPUTED); + + writer.WriteLine(string.Join(",", + element.Id.ToString(CultureInfo.InvariantCulture), + Escape(element.UniqueId), + IfcGuid.FromElement(element), + categoryId?.ToString(CultureInfo.InvariantCulture), + Escape(category), + Escape(element.Name), + typeId?.ToString(CultureInfo.InvariantCulture), + Escape(document.GetTypeElement(element)?.Name), + FormatQuantity(length, MetresPerFoot), + FormatQuantity(area, SquareMetresPerSquareFoot), + FormatQuantity(volume, CubicMetresPerCubicFoot))); + count++; + } + return count; + } + + private static double? Quantity(Element element, BuiltInParameter id) + { + foreach (var parameter in element.Parameters) + { + if (parameter.Id == (int)id && parameter is { StorageType: StorageType.Double, HasRevitValue: true, Value: double value }) + return value; + } + return null; + } + + private static string? FormatQuantity(double? value, double factor) => + (value * factor)?.ToString("R", CultureInfo.InvariantCulture); + + private static string? Escape(string? value) + { + if (string.IsNullOrEmpty(value)) return value; + var trimmed = value.AsSpan().TrimStart(); + // Quotation alone does not prevent a spreadsheet from evaluating a formula. + if (value[0] is '\t' or '\r' or '\n' || (!trimmed.IsEmpty && trimmed[0] is '=' or '+' or '-' or '@')) + value = "'" + value; + return value.AsSpan().IndexOfAny(",\"\r\n") < 0 ? value : "\"" + value.Replace("\"", "\"\"") + "\""; + } +} diff --git a/src/RvtIO/Gltf/GlbExporter.cs b/src/RvtIO/Gltf/GlbExporter.cs index 0c7e8d7d..5335db05 100644 --- a/src/RvtIO/Gltf/GlbExporter.cs +++ b/src/RvtIO/Gltf/GlbExporter.cs @@ -6,7 +6,6 @@ using RvtIO.Internal; using RvtIO.Meshes; using RvtIO.Model; -using RvtIO.Parsing; namespace RvtIO.Gltf; @@ -248,7 +247,7 @@ private void ProcessElement(ElementMesh elemMesh) int? typeId = element?.TypeId is > 0 and int tid ? tid : null; string? typeName = element != null ? NullIfEmpty(_document.GetTypeElement(element)?.Name) : null; string? uniqueId = NullIfEmpty(element?.UniqueId); - string? ifcGuid = element != null ? IfcGuidOf(element) : null; + string? ifcGuid = element != null ? IfcGuid.FromElement(element) : null; string coverage = elemMesh.Coverage.ToString(); // Resolve placements (shared family symbol meshes). @@ -784,25 +783,6 @@ private static MeshVector LowestCorner(IReadOnlyList meshes) private static string? CategoryName(Element? element) => element?.CategoryId is int id && ((BuiltInCategory)id).TryGetCategoryName(out string? name) ? name : element?.Category; - private static string? IfcGuidOf(Element element) - { - foreach (var parameter in element.Parameters) - { - if (parameter.Id == (int)BuiltInParameter.IFC_GUID - && parameter.Value is string stored - && IfcGuid.Parse(stored) != null) - return stored; - } - - if (element.UniqueId is { Length: 45 } uniqueId && uniqueId[36] == '-' - && Guid.TryParseExact(uniqueId.AsSpan(0, 36), "D", out var episode) - && uint.TryParse(uniqueId.AsSpan(37), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint originalId)) - { - return IfcGuid.ToIfcGuid(ElementExportIds.ExportId(episode, originalId)); - } - return null; - } - private static bool IsFinite(MeshVector v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z); diff --git a/src/RvtIO/Ifc/IfcGuid.cs b/src/RvtIO/Ifc/IfcGuid.cs index 9fb312db..80c6f962 100644 --- a/src/RvtIO/Ifc/IfcGuid.cs +++ b/src/RvtIO/Ifc/IfcGuid.cs @@ -1,5 +1,9 @@ +using System.Globalization; using System.Security.Cryptography; using System.Text; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; namespace RvtIO.Ifc; @@ -12,6 +16,25 @@ internal static class IfcGuid { private const string Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; + internal static string? FromElement(Element element) + { + foreach (var parameter in element.Parameters) + { + if (parameter.Id == (int)BuiltInParameter.IFC_GUID + && parameter.Value is string stored + && Parse(stored) != null) + return stored; + } + + if (element.UniqueId is { Length: 45 } uniqueId && uniqueId[36] == '-' + && Guid.TryParseExact(uniqueId.AsSpan(0, 36), "D", out var episode) + && uint.TryParse(uniqueId.AsSpan(37), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint originalId)) + { + return ToIfcGuid(ElementExportIds.ExportId(episode, originalId)); + } + return null; + } + /// Convert a .NET Guid to IFC GlobalId (22 chars). public static string ToIfcGuid(Guid guid) { diff --git a/src/RvtIO/RvtIO.csproj b/src/RvtIO/RvtIO.csproj index fc3e0554..2e19a44a 100644 --- a/src/RvtIO/RvtIO.csproj +++ b/src/RvtIO/RvtIO.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/RvtIO.Tests/ElementCsvExporterTests.cs b/tests/RvtIO.Tests/ElementCsvExporterTests.cs new file mode 100644 index 00000000..36639c05 --- /dev/null +++ b/tests/RvtIO.Tests/ElementCsvExporterTests.cs @@ -0,0 +1,140 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text.Json; +using Microsoft.VisualBasic.FileIO; +using RvtIO.BuiltIns; +using RvtIO.Csv; +using RvtIO.Gltf; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests; + +public class ElementCsvExporterTests +{ + [Fact] + public void Export_WritesOneRecordPerElementWithGlbIdentitiesAndInvariantQuantities() + { + const string storedGuid = "3KMnWMoynDnh2x07HdzyEW"; + const string name = "Стена, \"A\"\r\nсекция"; + const string formulaLike = " =1+2"; + var document = RvtDocument.FromInfo(new RevitFileInfo + { + ElemTableIsExact = true, + Elements = + [ + new Element { Id = 5, IsBlockOnly = true }, + new Element { Id = 6, IsDiscovered = true }, + new Element { Id = 4, Name = formulaLike }, + new Element + { + Id = 1, + UniqueId = "d45b1816-cbcc-4dc6-b0bb-007467f3c600-00000001", + CategoryId = (int)BuiltInCategory.OST_Walls, + TypeId = 4, + Parameters = + [ + new Parameter + { + Id = (int)BuiltInParameter.ELEM_TYPE_PARAM, + Definition = new Definition { Name = "ELEM_TYPE_PARAM", Id = (int)BuiltInParameter.ELEM_TYPE_PARAM }, + StorageType = StorageType.ElementId, + Value = 4, + }, + new Parameter { Id = (int)BuiltInParameter.IFC_GUID, StorageType = StorageType.String, Value = storedGuid }, + Quantity(BuiltInParameter.CURVE_ELEM_LENGTH, 2), + Quantity(BuiltInParameter.HOST_AREA_COMPUTED, 3), + Quantity(BuiltInParameter.HOST_VOLUME_COMPUTED, 4), + ], + }, + new Element + { + Id = 2, + UniqueId = "d45b1816-cbcc-4dc6-b0bb-007467f3c600-00000003", + CategoryId = (int)BuiltInCategory.OST_Rooms, + Parameters = + [ + new Parameter { Id = (int)BuiltInParameter.IFC_GUID, StorageType = StorageType.String, Value = "invalid" }, + Quantity(BuiltInParameter.CURVE_ELEM_LENGTH, 0), + Quantity(BuiltInParameter.ROOM_AREA, 5), + Quantity(BuiltInParameter.ROOM_VOLUME, 15), + ], + }, + new Element + { + Id = 3, + Name = name, + Parameters = + [ + Quantity(BuiltInParameter.CURVE_ELEM_LENGTH, 9, approximate: true), + Quantity(BuiltInParameter.HOST_AREA_COMPUTED, 1e30), + Quantity(BuiltInParameter.HOST_VOLUME_COMPUTED, double.NaN), + ], + }, + new Element { Id = 1, Name = "duplicate" }, + ], + }); + var meshSet = new MeshSet + { + Elements = [new ElementMesh { ElementId = 1 }, new ElementMesh { ElementId = 2 }, new ElementMesh { ElementId = 3 }], + }; + byte[] glb = GlbExporter.ExportToBytes(document, out _, meshes: meshSet); + int jsonLength = BinaryPrimitives.ReadInt32LittleEndian(glb.AsSpan(12, 4)); + using var glbJson = JsonDocument.Parse(glb.AsMemory(20, jsonLength)); + + string csv = TestFiles.Scratch("elements.csv"); + CultureInfo originalCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); + Assert.Equal(4, ElementCsvExporter.Export(document, csv)); + Assert.True(File.ReadAllBytes(csv).AsSpan().StartsWith(new byte[] { 0xEF, 0xBB, 0xBF })); + using var parser = new TextFieldParser(csv) { TrimWhiteSpace = false }; + parser.SetDelimiters(","); + Assert.Equal(new[] { "elementId", "uniqueId", "ifcGuid", "categoryId", "category", "name", "typeId", "typeName", "length_m", "area_m2", "volume_m3" }, + parser.ReadFields()); + var rows = new List(); + while (!parser.EndOfData) + rows.Add(parser.ReadFields()!); + Assert.Equal(new[] { "1", "2", "3", "4" }, rows.Select(row => row[0])); + Assert.Equal(name, rows[2][5]); + Assert.Equal("4", rows[0][6]); + Assert.Equal("'" + formulaLike, rows[0][7]); + Assert.Equal("'" + formulaLike, rows[3][5]); + Assert.Equal(storedGuid, rows[0][2]); + Assert.NotEmpty(rows[1][2]); + Assert.Equal(new[] { "", "" }, rows[2][1..3]); + Assert.Equal("0.6096", rows[0][8]); + Assert.Equal(0.27870912, double.Parse(rows[0][9], CultureInfo.InvariantCulture), 10); + Assert.Equal(0.113267386368, double.Parse(rows[0][10], CultureInfo.InvariantCulture), 12); + Assert.Equal("0", rows[1][8]); + Assert.Equal(0.4645152, double.Parse(rows[1][9], CultureInfo.InvariantCulture), 10); + Assert.Equal(0.42475269888, double.Parse(rows[1][10], CultureInfo.InvariantCulture), 12); + Assert.Equal(new[] { "", "", "" }, rows[2][8..]); + + var nodes = glbJson.RootElement.GetProperty("nodes").EnumerateArray().ToArray(); + Assert.Equal(3, nodes.Length); + foreach (var node in nodes) + { + var extras = node.GetProperty("extras"); + var row = rows[extras.GetProperty("elementId").GetInt32() - 1]; + Assert.Equal(extras.TryGetProperty("uniqueId", out var id) ? id.GetString() : "", row[1]); + Assert.Equal(extras.TryGetProperty("ifcGuid", out var guid) ? guid.GetString() : "", row[2]); + } + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + File.Delete(csv); + } + } + + private static Parameter Quantity(BuiltInParameter id, double value, bool approximate = false) => new() + { + Id = (int)id, + StorageType = StorageType.Double, + Value = value, + IsApproximate = approximate, + }; +} diff --git a/tests/RvtIO.Tests/MultiOutputExportTests.cs b/tests/RvtIO.Tests/MultiOutputExportTests.cs index bb82e0a1..bd7998d0 100644 --- a/tests/RvtIO.Tests/MultiOutputExportTests.cs +++ b/tests/RvtIO.Tests/MultiOutputExportTests.cs @@ -132,6 +132,42 @@ public void MultiOutput_ByteIdentical_ToSingleOutputRuns() } } + [Fact] + public void ElementCsv_StandaloneAndCombinedExportsMatchAndCollisionsAreRefused() + { + string rvt = TestFiles.Scratch("csv-model.rvt"); + string standalone = TestFiles.Scratch("standalone.csv"); + string combined = TestFiles.Scratch("combined.csv"); + string glb = TestFiles.Scratch("csv-model.glb"); + string report = TestFiles.Scratch("csv-report.json"); + CliExitCodeTests.WriteSyntheticRvt(rvt); + try + { + var (singleExit, singleError, _) = Run(rvt, "--csv", standalone, "--report", report); + Assert.True(singleExit == 0, singleError); + byte[] csv = File.ReadAllBytes(standalone); + Assert.StartsWith("elementId,uniqueId,ifcGuid,", File.ReadAllText(standalone)); + using var reportDocument = JsonDocument.Parse(File.ReadAllText(report)); + + var (combinedExit, combinedError, _) = Run(rvt, "--csv", combined, "--glb", glb); + Assert.True(combinedExit == 0, combinedError); + Assert.Equal(csv, File.ReadAllBytes(combined)); + Assert.True(File.Exists(glb)); + + byte[] model = File.ReadAllBytes(rvt); + Assert.Equal(1, Run(rvt, "--csv", rvt).ExitCode); + Assert.Equal(model, File.ReadAllBytes(rvt)); + Assert.Equal(1, Run(rvt, "--csv", standalone, "--glb", standalone).ExitCode); + Assert.Equal(1, Run(rvt, "--csv", standalone, "--report", standalone).ExitCode); + Assert.Equal(csv, File.ReadAllBytes(standalone)); + } + finally + { + foreach (string path in new[] { rvt, standalone, combined, glb, report }) + File.Delete(path); + } + } + [Fact] public void MultiOutput_InputCollision_ExitsWithCode1() { @@ -180,6 +216,7 @@ public void MultiOutput_MutualDestinationCollision_ExitsWithCode1() [Theory] [InlineData("--ifc")] + [InlineData("--csv")] [InlineData("--scene")] [InlineData("--full-json")] [InlineData("--json")]