From 5165ce911f65488cf1c4ec20dd2d0b9140c8a860 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:19:22 +0300 Subject: [PATCH 1/3] Add experimental native RVT downgrade output --- CHANGELOG.md | 2 + README.md | 30 +- docs/export-report.md | 2 +- docs/public-api.md | 2 +- src/RvtIO.Cli/DowngradeCommand.cs | 129 +- src/RvtIO.Cli/Program.cs | 7 +- src/RvtIO/Parsing/DocumentIncrementTable.cs | 9 +- src/RvtIO/Parsing/ElemTableLayout.cs | 16 +- src/RvtIO/Parsing/LegacyEnergySchedules.cs | 58 + src/RvtIO/Parsing/R22Transcoder.cs | 946 ++++++++++- src/RvtIO/Parsing/WideBlockWalker.cs | 32 +- src/RvtIO/Parsing/WideSolidQuantities.cs | 2 +- src/RvtIO/RvtFileReader.R22Layout.cs | 2 +- src/RvtIO/Writing/ArchiveContents.cs | 34 + src/RvtIO/Writing/BasicFileInfoPatcher.cs | 94 ++ src/RvtIO/Writing/DocumentIncrementFixup.cs | 105 ++ src/RvtIO/Writing/DowngradeAnalytics.cs | 220 +++ .../DowngradeContentDocumentsRewriter.cs | 103 ++ .../Writing/DowngradeElemTableRewriter.cs | 69 + src/RvtIO/Writing/DowngradeGlobalRewriter.cs | 65 + src/RvtIO/Writing/DowngradeHistoryRewriter.cs | 32 + .../Writing/DowngradePartitionRewriter.cs | 607 +++++++ src/RvtIO/Writing/DowngradePlanner.cs | 15 +- src/RvtIO/Writing/DowngradeWriter.cs | 566 +++++++ src/RvtIO/Writing/ElementCensus.cs | 5 +- src/RvtIO/Writing/EnergyAnalysisArchive.cs | 182 +++ src/RvtIO/Writing/EnergyAnalysisTracking.cs | 106 ++ src/RvtIO/Writing/LegacyAnalyticalMembers.cs | 1436 +++++++++++++++++ src/RvtIO/Writing/LegacyElectricalStyle.cs | 133 ++ src/RvtIO/Writing/LegacyProjectDefaults.cs | 226 +++ src/RvtIO/Writing/LegacySchemaCatalogs.cs | 72 + src/RvtIO/Writing/LegacyUnitFormats.cs | 109 ++ src/RvtIO/Writing/LegacyWireReferences.cs | 117 ++ src/RvtIO/Writing/TagCellRewriter.cs | 399 +++++ tests/RvtIO.Tests/ArchiveContentsTests.cs | 54 + .../DocumentIncrementFixupTests.cs | 33 + tests/RvtIO.Tests/DowngradeAnalyticsTests.cs | 422 +++++ tests/RvtIO.Tests/DowngradeCommandTests.cs | 10 +- .../DowngradeElemTableRewriterTests.cs | 175 ++ .../DowngradeHistoryRewriterTests.cs | 64 + tests/RvtIO.Tests/DowngradeSampleTests.cs | 3 +- tests/RvtIO.Tests/DowngradeWriterTests.cs | 643 ++++++++ .../RvtIO.Tests/EnergyAnalysisArchiveTests.cs | 77 + .../EnergyAnalysisTrackingTests.cs | 34 + .../RvtIO.Tests/LegacySchemaCatalogsTests.cs | 44 + tests/RvtIO.Tests/LegacyUnitFormatsTests.cs | 68 + .../R22TranscoderQueueDrainTests.cs | 664 ++++++++ tests/RvtIO.Tests/R22TranscoderTests.cs | 90 +- tests/RvtIO.Tests/RecordRoutingTests.cs | 24 +- tests/RvtIO.Tests/RvtWriterTests.cs | 92 ++ tests/RvtIO.Tests/TagCellRewriterTests.cs | 59 + .../TranscoderPointerMismatchTests.cs | 50 + tools/verify-downgrade-chain.ps1 | 90 ++ 53 files changed, 8513 insertions(+), 115 deletions(-) create mode 100644 src/RvtIO/Parsing/LegacyEnergySchedules.cs create mode 100644 src/RvtIO/Writing/ArchiveContents.cs create mode 100644 src/RvtIO/Writing/BasicFileInfoPatcher.cs create mode 100644 src/RvtIO/Writing/DocumentIncrementFixup.cs create mode 100644 src/RvtIO/Writing/DowngradeAnalytics.cs create mode 100644 src/RvtIO/Writing/DowngradeContentDocumentsRewriter.cs create mode 100644 src/RvtIO/Writing/DowngradeElemTableRewriter.cs create mode 100644 src/RvtIO/Writing/DowngradeGlobalRewriter.cs create mode 100644 src/RvtIO/Writing/DowngradeHistoryRewriter.cs create mode 100644 src/RvtIO/Writing/DowngradePartitionRewriter.cs create mode 100644 src/RvtIO/Writing/DowngradeWriter.cs create mode 100644 src/RvtIO/Writing/EnergyAnalysisArchive.cs create mode 100644 src/RvtIO/Writing/EnergyAnalysisTracking.cs create mode 100644 src/RvtIO/Writing/LegacyAnalyticalMembers.cs create mode 100644 src/RvtIO/Writing/LegacyElectricalStyle.cs create mode 100644 src/RvtIO/Writing/LegacyProjectDefaults.cs create mode 100644 src/RvtIO/Writing/LegacySchemaCatalogs.cs create mode 100644 src/RvtIO/Writing/LegacyUnitFormats.cs create mode 100644 src/RvtIO/Writing/LegacyWireReferences.cs create mode 100644 src/RvtIO/Writing/TagCellRewriter.cs create mode 100644 tests/RvtIO.Tests/ArchiveContentsTests.cs create mode 100644 tests/RvtIO.Tests/DocumentIncrementFixupTests.cs create mode 100644 tests/RvtIO.Tests/DowngradeAnalyticsTests.cs create mode 100644 tests/RvtIO.Tests/DowngradeElemTableRewriterTests.cs create mode 100644 tests/RvtIO.Tests/DowngradeHistoryRewriterTests.cs create mode 100644 tests/RvtIO.Tests/DowngradeWriterTests.cs create mode 100644 tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs create mode 100644 tests/RvtIO.Tests/EnergyAnalysisTrackingTests.cs create mode 100644 tests/RvtIO.Tests/LegacySchemaCatalogsTests.cs create mode 100644 tests/RvtIO.Tests/LegacyUnitFormatsTests.cs create mode 100644 tests/RvtIO.Tests/R22TranscoderQueueDrainTests.cs create mode 100644 tests/RvtIO.Tests/TagCellRewriterTests.cs create mode 100644 tests/RvtIO.Tests/TranscoderPointerMismatchTests.cs create mode 100644 tools/verify-downgrade-chain.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index bd8c44f2..20a84cc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ API between minor releases. ### Added +- Add experimental native RVT downgrade output using a target-release profile. The CLI writes a separate file and can report known omissions. + - Report progress while reading a Revit file: `RvtReadProgress` (phase, completed and total units), `RvtReaderOptions.Progress` and `RvtSceneOptions.ReadProgress` (for `RvtSceneReader.Read(path)`). The reader calls `IProgress.Report` synchronously on the reading thread, in phase order; see diff --git a/README.md b/README.md index b6b011aa..f69282e8 100644 --- a/README.md +++ b/README.md @@ -189,26 +189,32 @@ A file saved in several increments can hold an element in more than one partitio | 2 | The input cannot be read: it is missing, empty, not a compound file, or cut or damaged. One line on standard error, no stack trace. | | 3 | A stream exceeded a limit of the reader and the read was cut. Nothing is exported unless `--allow-partial` is given. | | 4 | The file is readable but a decoder failed on its content. | -| 5 | `downgrade --check` refused the request, for example because the source is newer than release 2026, the profile is not older than the source, the saving release of a file does not match its class table, or a class name occurs twice in a table. One line on standard error. | +| 5 | `downgrade` refused the requested conversion, for example because the profile is not older than the source or the file does not match its class table. | | 6 | `--strict` was given and the read was partial without hitting a limit (a member failed to decode, was rebuilt by structural recovery, or decoded without a matching checksum, or the element table decoded no row). Nothing is exported; the report lists the streams and the reason. | `--report project.report.json` writes a machine-readable report: the fraction of each partition stream and of the element table that decoded, the streams cut by a limit, the elements the export left out with their class and reason, and the exported fraction. `--strict` makes partial reads that did not hit a limit fail with exit code 6 instead of exporting with exit code 0. `--raise-limits` raises the limits for a very large model. A complete export without these options behaves as before. The report format and the limits are described in [the export report](docs/export-report.md). -### Plan a downgrade to an older release (experimental) +### Downgrade a project to an older release (experimental) ```powershell -rvtio downgrade project2026.rvt --target-profile project2025.rvt --check --report downgrade.json +rvtio downgrade project2027.rvt --target-profile profile2026.rvt --check --report plan.json +rvtio downgrade project2027.rvt --target-profile profile2026.rvt --output project2026.rvt --allow-loss --report downgrade.json ``` -`downgrade --check` compares the class table of a project (the stream `Formats/Latest`) with the class table of a project or family saved by an older release, the profile, and reports what editing the first table to fit the second would change. It writes nothing but the report. Nothing is embedded in RvtIO: the profile is read from the file you give. The report lists: - -- the classes only the source defines, with the number of elements the file holds in each (counted from the partition streams); in an earlier trial with one 2026 sample project edited by hand and opened in Revit 2025, the 64 elements of such classes were not in the file that Revit 2025 then saved; -- the classes only the profile defines; -- the classes whose version is higher in the source (the version is lowered to the profile's); -- per class, the stored fields that exist in one table only, matched by name (the command only lists them; what an older release does with them was compared in that one trial only, where one element out of 13872 kept in both files differed in the values of a property); -- the classes whose list of upgrade identifiers changes, with the number added and removed. `--guid-rule exact` (the default) makes the list the profile's list of the same class; `--guid-rule minimal` only removes the identifiers the profile does not list. A list is empty after the edit only when the rule yields no identifier for that class. - -Limits: the plan is computed from the bytes of the two files. This version cannot write a converted file, and no application opened a converted file as part of this change. The tested source release is 2026; a source of a newer release, a source whose saving release differs from the release of its class table, and a profile that is not older than the source are refused with exit code 5 and one line on standard error. A file that cannot be read, or whose partition stream is damaged, exits with code 2; a wrong command line, including an empty or unusable path, exits with code 1. Without `--check` the command refuses to run. +Use a profile saved by the target release. `--check` compares class versions, +stored fields, and upgrade identifiers and writes only the optional report. +`--guid-rule exact` is the default. `--guid-rule minimal` keeps identifiers that +both tables declare. `--output` writes a separate RVT and leaves the original +and profile intact. For a chain across multiple releases, use the output of +each step as the input for the next one. + +Older Revit releases cannot represent every newer record. A conversion with +known omitted record owners requires `--allow-loss` and a JSON `--report`. +The report lists affected record owners and known project and analytical omissions. +Review the report and open the output in the target Revit release before relying +on it. `--restore-legacy-analytics` applies only when writing Revit 2022 from a +Revit 2023 or later project. It requires an earlier Revit 2022 revision of the +same project as the profile and restores supported analytical records. ### Measure how much of a file is decoded diff --git a/docs/export-report.md b/docs/export-report.md index 67bdaa71..081a61cb 100644 --- a/docs/export-report.md +++ b/docs/export-report.md @@ -21,7 +21,7 @@ Without the new options the output (IFC, JSON, standard error text) and the exit | 2 | input error | The input cannot be read: the file does not exist or cannot be opened, is empty, is not a compound file, or is cut or damaged so that a stream ends before its declared length. One line on standard error, no stack trace, nothing exported. | | 3 | limit exceeded | A stream exceeded a reader limit. For a recoverable limit, `--allow-partial` permits export. Hard limits (`array-length`, `element-id-range`) stop export with exit code 3 regardless of options. | | 4 | decode error | The compound file is readable but a decoder failed on its content (damaged or unsupported data). One line on standard error; the report holds the exception with its stack trace. | -| 5 | refused | `downgrade --check` refused the request (for example a source newer than release 2026, a profile not older than the source, a saving release that does not match the class table, or an ambiguous class name). One line on standard error. | +| 5 | refused | `downgrade` refused the request (for example a profile not older than the source, a saving release that does not match the class table, or known omissions without `--allow-loss`). One line on standard error. | | 6 | partial read | `--strict` was given and the read finished partial without exceeding a limit (members of a stream failed to decode, were rebuilt by structural recovery, or decoded without a matching checksum, or the element table decoded no row). One line on standard error naming the streams and the reason, nothing exported; the report holds the stream counts and `issues[]`. | A standalone family without decoded triangle geometry cannot be exported to GLB. The CLI returns 4 and the report records `error.kind: "glb-family-geometry-unavailable"`. diff --git a/docs/public-api.md b/docs/public-api.md index 68fda70f..857f95d2 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -15,7 +15,7 @@ projects through `InternalsVisibleTo`. | `RvtReadDiagnostics`, `StreamRecord`, `ReaderLimitHit` | What a read collects when `RvtReaderOptions.Diagnostics` is set: the partition and metadata streams read (stored and inflated byte sizes and member decode counts) and the streams cut by a limit. | | `RvtReadProgress` | File-reading updates delivered through `RvtReaderOptions.Progress`. | | `ExportReport`, `SkipLog`, `GeometryQualityClass`, `ElementGeometryQuality` | The machine-readable report of a run (`ToJson`), the per-element geometry quality classification and totals, and the elements an export left out; see [the export report](export-report.md). | -| `RvtExitCodes`, `RvtInputException`, `RvtLimitException`, `RvtContainerCheck` | The exit codes 0 to 4 and 6 of the command line tool (code 5 is returned by `downgrade --check` and `save-as` when refused), the exceptions `RvtFileReader.Read` and `ReadStream` throw for input they cannot read (`ReadStream` also throws `ArgumentNullException` and `ArgumentException` for a missing, unreadable or non-seekable stream), and the check that raises them. | +| `RvtExitCodes`, `RvtInputException`, `RvtLimitException`, `RvtContainerCheck` | The exit codes 0 to 4 and 6 of the command line tool (code 5 is returned by `downgrade` and `save-as` when refused), the exceptions `RvtFileReader.Read` and `ReadStream` throw for input they cannot read (`ReadStream` also throws `ArgumentNullException` and `ArgumentException` for a missing, unreadable or non-seekable stream), and the check that raises them. | | `FilteredElementCollector` | Query over the elements of a document (`OfCategory`, `WhereElementIsNotElementType`, `Where`, ...). | | `RvtRevisionDiffer`, `RvtDiffOptions`, `RvtRevisionDiffResult` | `RvtIO.Diff`: compares two RVT files or opened `RvtDocument` revisions by persistent `UniqueId`, reporting additions, removals, parameter/type/placement/geometry/relationship/link changes, affected-instance impacts, ambiguous matches, and partial-decode gaps as deterministic JSON. See [revision comparison](diff.md). | | `BuildingStoreyCatalog`, `BuildingStorey` | `RvtDocument.GetBuildingStoreyCatalog()` lists native project building storeys in order of elevation and Revit ID. Each storey carries its ID, name and resolved elevation in internal feet. `GetStoreyId(elementId)` uses the current IFC storey rules and returns null for an unknown element or one assigned to the building itself. Obtain a new catalog after editing levels. | diff --git a/src/RvtIO.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs index f96c1793..bcdbb65d 100644 --- a/src/RvtIO.Cli/DowngradeCommand.cs +++ b/src/RvtIO.Cli/DowngradeCommand.cs @@ -8,14 +8,16 @@ namespace RvtIO.Cli; /// -/// rvtio downgrade <source> --target-profile <file> --check [--guid-rule exact|minimal] [--report report.json]: plans the edit of the -/// class table of a newer project so that an older release may load it, and reports it. It writes nothing but the report. Exit codes: -/// 0 planned, 1 usage error (also an unusable path), 2 a file cannot be read or a partition stream is damaged, 5 refused (the releases are out of scope or the edit does not apply). +/// rvtio downgrade <source> --target-profile <file> (--check | --output <file>) [--guid-rule exact|minimal] [--report report.json]: plans the edit of the +/// class table of a newer project so that an older release may load it (--check), and writes a downgraded copy +/// (--output) with the class table lowered and BasicFileInfo pointed at the target release. Exit codes: +/// 0 done, 1 usage error (also an unusable path), 2 a file cannot be read or a partition stream is damaged, 5 refused (the releases are out of scope or the edit does not apply). /// internal static class DowngradeCommand { internal const int Refused = 5; internal const string ReportSchema = "rvtio-downgrade-check/1"; + internal const string WriteReportSchema = "rvtio-downgrade/1"; private static readonly JsonSerializerOptions JsonOptions = new() { @@ -27,21 +29,24 @@ internal static class DowngradeCommand internal static int Run(string[] args, TextWriter output, TextWriter error) { - string? source = null, profile = null, reportPath = null; + string? source = null, profile = null, reportPath = null, outputPath = null; var rule = GuidRule.Exact; - bool check = false; + bool check = false, restoreLegacyAnalytics = false, allowLoss = false; for (int i = 0; i < args.Length; i++) { string arg = args[i]; switch (arg) { case "--check": check = true; break; - case "--target-profile" or "--report" or "--guid-rule": + case "--allow-loss": allowLoss = true; break; + case "--restore-legacy-analytics": restoreLegacyAnalytics = true; break; + case "--target-profile" or "--report" or "--guid-rule" or "--output": if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) return Usage(error, $"{arg} requires one value."); string value = args[++i]; if (arg == "--target-profile") { if (profile != null) return Usage(error, "--target-profile is given twice."); profile = value; } else if (arg == "--report") { if (reportPath != null) return Usage(error, "--report is given twice."); reportPath = value; } + else if (arg == "--output") { if (outputPath != null) return Usage(error, "--output is given twice."); outputPath = value; } else if (value == "exact") rule = GuidRule.Exact; else if (value == "minimal") rule = GuidRule.Minimal; else return Usage(error, "--guid-rule requires one value: exact or minimal."); @@ -55,8 +60,11 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) } if (source == null) return Usage(error, "downgrade requires the source file."); if (profile == null) return Usage(error, "downgrade requires --target-profile , a project or family saved by the target release."); - if (!check) return Usage(error, "downgrade only plans in this version: add --check. No converted file can be written."); - if (PathProblem(source, profile, reportPath) is { } problem) return Usage(error, problem + " Nothing was read or written."); + if (!check && outputPath == null) return Usage(error, "downgrade requires --check to plan or --output to write a downgraded copy."); + if (allowLoss && (outputPath == null || reportPath == null)) + return Usage(error, "--allow-loss requires --output and --report."); + if (restoreLegacyAnalytics && outputPath == null) return Usage(error, "--restore-legacy-analytics requires --output."); + if (PathProblem(source, profile, reportPath, outputPath) is { } problem) return Usage(error, problem + " Nothing was read or written."); string sourceName = Path.GetFileName(source), profileName = Path.GetFileName(profile); DowngradePlanner.Result result; @@ -85,23 +93,79 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) output.WriteLine($"Classes only in the profile: {plan.ClassesOnlyInTarget.Count.ToString(inv)}; classes with different fields: {plan.FieldDifferences.Count.ToString(inv)}"); int emptied = plan.GuidLists.Count(g => g.Result == 0); if (emptied > 0) output.WriteLine($"Upgrade-identifier lists that become empty: {emptied.ToString(inv)} (the rule yields no identifier for them)"); + if (!restoreLegacyAnalytics && result.OmittedContextualMembers is > 0) + error.WriteLine($"warning: Revit 2022 cannot open independent analytical members. Downgrade omits {result.OmittedContextualMembers.Value.ToString(inv)} AnalyticalMember elements."); if (result.CountFailure != null) error.WriteLine($"warning: the elements were not counted: {result.CountFailure}."); + + if (outputPath != null) + { + DowngradeWriter.DowngradeWriteResult written; + try + { + written = DowngradeWriter.Write(source, profile, outputPath, rule, includeOmittedAnalytics: reportPath is not null, + restoreLegacyAnalytics: restoreLegacyAnalytics, allowLoss: allowLoss); + if (written.RestoredAnalyticalMembers is { } restored) + output.WriteLine($"Restored analytical members: {restored.Count.ToString(inv)}. Panels: {(written.RestoredAnalyticalPanels?.Count ?? 0).ToString(inv)}. Point supports: {(written.RestoredPointSupports?.Count ?? 0).ToString(inv)}. Line supports: {(written.RestoredLineSupports?.Count ?? 0).ToString(inv)}."); + if (written.RestoredAnalyticalOpenings is { Count: > 0 } openings) + output.WriteLine($"Restored analytical openings: {openings.Count.ToString(inv)}."); + int boundaries = written.OmittedProjectElements?.GetValueOrDefault("BoundaryConditions") ?? 0; + if (boundaries > 0) + error.WriteLine($"warning: Downgrade omits {boundaries.ToString(inv)} boundary conditions. See omittedProjectElements in the write report."); + output.WriteLine($"Downgraded: {Path.GetFileName(written.OutputPath)} (release {written.SourceRelease} to {written.TargetRelease}, {written.EditedClasses.ToString(inv)} classes edited, {written.ReplacedStreams.ToString(inv)} streams replaced)"); + } + catch (DowngradeRefusedException exception) + { + return End(error, reportPath, Refused, exception.Kind, exception.Message, sourceName, profileName, rule, outputPath); + } + catch (RvtInputException exception) + { + return End(error, reportPath, RvtExitCodes.InputError, exception.Kind, exception.Message, sourceName, profileName, rule, outputPath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException) + { + error.WriteLine($"error: the downgraded file cannot be written: {exception.Message} Nothing was written (exit code {RvtExitCodes.InputError.ToString(inv)})."); + var failed = new + { + schema = WriteReportSchema, + status = "unreadable", + kind = "write-failed", + message = exception.Message, + guidRule = RuleName(rule), + source = new { file = sourceName }, + profile = new { file = profileName }, + output = new { file = Path.GetFileName(outputPath) }, + }; + return WriteReport(error, reportPath, failed, RvtExitCodes.InputError); + } + if (!check) + return WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, written), RvtExitCodes.Success); + output.WriteLine("Check and write done" + (reportPath == null ? "." : $" except the report {reportPath}.")); + return WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, written), RvtExitCodes.Success); + } + output.WriteLine("Check only: no file was written" + (reportPath == null ? "." : $" except the report {reportPath}.")); return WriteReport(error, reportPath, Report(result, sourceName, profileName), RvtExitCodes.Success); } // Normalising a path can throw; every such failure, an empty path and a directory as report are usage errors found before any file is read. - private static string? PathProblem(string source, string profile, string? report) + private static string? PathProblem(string source, string profile, string? report, string? output) { - foreach (var (option, path) in new[] { ("downgrade source", source), ("--target-profile", profile), ("--report", report) }) + foreach (var (option, path) in new[] { ("downgrade source", source), ("--target-profile", profile), ("--report", report), ("--output", output) }) if (path != null && string.IsNullOrWhiteSpace(path)) return $"The path of {option} is empty."; try { Path.GetFullPath(source); Path.GetFullPath(profile); + if (output != null) + { + Path.GetFullPath(output); + if (Directory.Exists(output)) return "--output names a directory, not a file."; + if (FileIdentity.SameFile(output, source) || FileIdentity.SameFile(output, profile)) return "--output must not name the source file or the profile file."; + } if (report == null) return null; if (Directory.Exists(report)) return "--report names a directory, not a file."; if (FileIdentity.SameFile(report, source) || FileIdentity.SameFile(report, profile)) return "--report must not name the source file or the profile file."; + if (output != null && FileIdentity.SameFile(report, output)) return "--report must not name the output file."; return null; } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException or IOException or UnauthorizedAccessException) @@ -114,26 +178,64 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) private static int Usage(TextWriter error, string message) { - error.WriteLine($"{message} Usage: rvtio downgrade --target-profile --check [--guid-rule exact|minimal] [--report ]"); + error.WriteLine($"{message} Usage: rvtio downgrade --target-profile (--check | --output ) [--guid-rule exact|minimal] [--allow-loss] [--restore-legacy-analytics] [--report ]"); return RvtExitCodes.Usage; } - private static int End(TextWriter error, string? reportPath, int exitCode, string kind, string message, string sourceName, string profileName, GuidRule rule) + private static int End(TextWriter error, string? reportPath, int exitCode, string kind, string message, string sourceName, string profileName, GuidRule rule, string? outputPath = null) { error.WriteLine($"error: {message} Nothing was written (exit code {exitCode.ToString(CultureInfo.InvariantCulture)})."); var report = new { - schema = ReportSchema, + schema = outputPath == null ? ReportSchema : WriteReportSchema, status = exitCode == Refused ? "refused" : "unreadable", kind, message, guidRule = RuleName(rule), source = new { file = sourceName }, profile = new { file = profileName }, + output = outputPath == null ? null : new { file = Path.GetFileName(outputPath) }, }; return WriteReport(error, reportPath, report, exitCode); } + private static object WriteReportBody(DowngradePlanner.Result result, string sourceName, string profileName, DowngradeWriter.DowngradeWriteResult written) + { + var plan = result.Plan; + return new + { + schema = WriteReportSchema, + status = "ok", + guidRule = RuleName(plan.Rule), + source = new { file = sourceName, release = result.SourceRelease, classes = plan.SourceClasses }, + profile = new { file = profileName, release = result.TargetRelease, classes = plan.TargetClasses }, + output = new { file = Path.GetFileName(written.OutputPath), release = result.TargetRelease, editedClasses = plan.Edits.Count }, + omittedProjectElements = written.OmittedProjectElements, + omittedRecordOwners = written.OmittedRecordOwners.Select(id => id.ToString(CultureInfo.InvariantCulture)), + archivedEnergyAnalysisRecords = written.ArchivedEnergyAnalysisRecords, + omittedAnalyticalData = written.OmittedAnalyticalData, + restoredAnalyticalMembers = written.RestoredAnalyticalMembers, + restoredPointSupports = written.RestoredPointSupports, + restoredAnalyticalPanels = written.RestoredAnalyticalPanels, + restoredAnalyticalOpenings = written.RestoredAnalyticalOpenings, + restoredLineSupports = written.RestoredLineSupports, + restoredAttachedNodes = written.RestoredAttachedNodes, + restoredLineLoads = written.RestoredLineLoads, + commonClasses = plan.CommonClasses, + classesOnlyInSource = plan.ClassesOnlyInSource.Select(c => new { name = c.Name, elements = c.Elements }), + elementsInClassesOnlyInSource = plan.ElementsInSourceOnlyClasses, + omittedContextualAnalyticalMembers = result.OmittedContextualMembers is int omitted + ? omitted - (written.RestoredAnalyticalMembers?.Count ?? 0) : (int?)null, + elementCountFailure = result.CountFailure, + classesOnlyInProfile = plan.ClassesOnlyInTarget, + classesWithHigherVersion = plan.HigherVersions.Select(v => new { name = v.Name, source = v.Source, profile = v.Target }), + classesWithLowerVersion = plan.LowerVersions, + fieldDifferences = plan.FieldDifferences.Select(f => new { name = f.Name, onlyInSource = f.OnlyInSource, onlyInProfile = f.OnlyInTarget }), + upgradeIdentifierLists = plan.GuidLists.Select(g => new { name = g.Name, source = g.Source, profile = g.Target, result = g.Result, added = g.Added, removed = g.Removed }), + edits = new { classVersions = plan.HigherVersions.Count, upgradeIdentifierLists = plan.GuidLists.Count, classTableBytesBefore = result.SourceStreamBytes, classTableBytesAfter = result.EditedStreamBytes }, + }; + } + private static object Report(DowngradePlanner.Result result, string sourceName, string profileName) { var plan = result.Plan; @@ -147,6 +249,7 @@ private static object Report(DowngradePlanner.Result result, string sourceName, commonClasses = plan.CommonClasses, classesOnlyInSource = plan.ClassesOnlyInSource.Select(c => new { name = c.Name, elements = c.Elements }), elementsInClassesOnlyInSource = plan.ElementsInSourceOnlyClasses, + omittedContextualAnalyticalMembers = result.OmittedContextualMembers, elementCountFailure = result.CountFailure, classesOnlyInProfile = plan.ClassesOnlyInTarget, classesWithHigherVersion = plan.HigherVersions.Select(v => new { name = v.Name, source = v.Source, profile = v.Target }), diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 7a2c0605..00ff6063 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -96,10 +96,11 @@ Developer options (measurement and comparison dumps, not a stable interface): --dev-collisions compact JSON: write user parameters that share a group and label --dev-solids compact JSON: write the solid quantities; with --dev-solids-only stop after it --dev-native compact JSON: print the native record of elements - downgrade --target-profile --check [--guid-rule exact|minimal] [--report ] + downgrade --target-profile (--check | --output ) [--guid-rule exact|minimal] [--allow-loss] [--restore-legacy-analytics] [--report ] (first argument) plan the class table edit that would let an older release load a newer - project and report it; the profile is a project or family saved by that older release; - writes nothing but the report; exit code 5 when the releases are out of scope + project (--check) and write a downgraded copy with BasicFileInfo pointed + at the target release (--output, same-width edit or cross-width transcode); the profile is a project or + family saved by that older release; exit code 5 when the releases are out of scope save-as [] [--check] [--report ] (first argument) inspect the write-capability matrix (--check) or write a verified lossless copy of a local 2020-2027 project or family; exit code 5 when refused by the matrix diff --git a/src/RvtIO/Parsing/DocumentIncrementTable.cs b/src/RvtIO/Parsing/DocumentIncrementTable.cs index 75ef40e7..9d09aedc 100644 --- a/src/RvtIO/Parsing/DocumentIncrementTable.cs +++ b/src/RvtIO/Parsing/DocumentIncrementTable.cs @@ -88,9 +88,10 @@ private object Field(FormatsSchema.Field field, int depth) } /// The table of a decoded Global/DocumentIncrementTable stream, or null unless the stream is exactly this - /// schema's DocumentIncrementTable (class id first, every field consumed, only zero padding after) and its global and - /// local rows have the same count. names the violated expectation. - internal static Table? TryParse(byte[] data, FormatsSchema schema, out string? failure) + /// schema's DocumentIncrementTable (class id first, every field consumed, only zero padding after). Routing requires + /// paired global and local rows. A workshared local file may retain more central history than local increments. + /// names the violated expectation. + internal static Table? TryParse(byte[] data, FormatsSchema schema, out string? failure, bool allowUnpairedHistory = false) { failure = null; if (schema.Get("DocumentIncrementTable") is not { } def) { failure = "no DocumentIncrementTable class"; return null; } @@ -102,7 +103,7 @@ private object Field(FormatsSchema.Field field, int depth) if (data.Skip(reader.Position).Any(b => b != 0)) { failure = "trailing bytes"; return null; } var increments = Rows(root["m_increments"]); var local = Rows(root["m_localIncrements"]); - if (increments.Count != local.Count) { failure = "global/local row count"; return null; } + if (!allowUnpairedHistory && increments.Count != local.Count) { failure = "global/local row count"; return null; } var permutation = ((List)root["m_permutation"]).Cast>() .Select(p => ((long)((Dictionary)p["first"])["m_id"], (long)p["second"])) .ToList(); diff --git a/src/RvtIO/Parsing/ElemTableLayout.cs b/src/RvtIO/Parsing/ElemTableLayout.cs index 741a9896..340ad9a6 100644 --- a/src/RvtIO/Parsing/ElemTableLayout.cs +++ b/src/RvtIO/Parsing/ElemTableLayout.cs @@ -1,3 +1,5 @@ +using System.Buffers.Binary; + namespace RvtIO.Parsing; /// @@ -23,6 +25,15 @@ internal static class ElemTableLayout internal static int? IdWidth(FormatsSchema schema) => schema.Get("Identifier") is { Fields: [{ } field] } && LeafWidth(field.Type) is int width && Agrees(SchemaRelease.IdWidth(schema.Release), width) ? width : null; + internal static bool TrySetLegacyOwner(Span row, FormatsSchema schema, long owner) + { + if (IdWidth(schema) != sizeof(int) || RowLength(schema) != row.Length || + schema.Get("ElemRec") is not { } record || Offset(schema, record, ["m_OwningElementId"]) is not int offset) + return false; + BinaryPrimitives.WriteInt32LittleEndian(row[offset..], checked((int)owner)); + return true; + } + /// True when the declared element id width contradicts the recognized release. Such a schema must not fall back /// to a layout with a different width. internal static bool DisagreesWithRelease(FormatsSchema schema) @@ -87,8 +98,9 @@ private static long Read(byte[] data, int at, int width) } /// Byte offset inside a row of the leaf reached by the field names in , followed down through - /// single-field wrapper classes (ElementId -> Identifier) until a leaf; null when a name is missing. - private static int? Offset(FormatsSchema schema, FormatsSchema.ClassDef def, string[] path) + /// single-field wrapper classes (ElementId -> Identifier) until a leaf; null when a name is missing. Internal for the + /// downgrade ElemTable transcoder, which reuses the same offsets to copy leaves between layouts. + internal static int? Offset(FormatsSchema schema, FormatsSchema.ClassDef def, string[] path) { int offset = 0; for (int step = 0; step < path.Length; step++) diff --git a/src/RvtIO/Parsing/LegacyEnergySchedules.cs b/src/RvtIO/Parsing/LegacyEnergySchedules.cs new file mode 100644 index 00000000..54684b51 --- /dev/null +++ b/src/RvtIO/Parsing/LegacyEnergySchedules.cs @@ -0,0 +1,58 @@ +using System.Buffers.Binary; + +namespace RvtIO.Parsing; + +internal static class LegacyEnergySchedules +{ + private const string DayPair = "std::pair< int, EnergyAnalysisDaySchedule >"; + + internal static Dictionary Read(WideBlockWalker walker, byte[] data, int offset, int size, int tag) + { + var walk = walker.Run(data, offset, size, tag); + if (!walk.Exact) return []; + var days = new Dictionary(); + var fields = walk.Captures; + for (int i = 1; i < fields.Count; i++) + { + if (fields[i] is { DeclaringClass: DayPair, Field: "second", TargetQueueIndex: int targetSlot } && + fields[i - 1] is { DeclaringClass: DayPair, Field: "first" } key && + !days.TryAdd(key.Integer, targetSlot)) return []; + } + var slots = fields.Where(f => f.QueueIndex >= 0).ToLookup(f => f.QueueIndex); + var result = new Dictionary(); + foreach (var field in fields) + { + if (field is not { DeclaringClass: "EnergyAnalysisSchedule", Field: "m_oYearScheduleInfos", + TargetQueueIndex: int yearSlot } || slots[field.QueueIndex].Any(other => + other.Key == "all:EnergyAnalysisSchedule.m_oYearScheduleInfos#" && other.Integer != 1)) + continue; + var year = slots[yearSlot].ToArray(); + long[] dates = year.Where(f => f.DeclaringClass == "ATime").Select(f => f.Integer).ToArray(); + if (dates.Length != 4) continue; + long end = ((long)(uint)dates[0] << 32) | (uint)dates[1]; + long start = ((long)(uint)dates[2] << 32) | (uint)dates[3]; + if (!IsCalendarYear(start, end)) continue; + + long day = year.FirstOrDefault(f => f.Field == "m_dayScheduleIndex").Integer; + var hours = day >= 0 && days.TryGetValue(day, out int daySlot) ? slots[daySlot] : year.AsEnumerable(); + var values = hours.Where(f => f.Field == "m_dayScheduleValues" && + f.Kind == WideBlockWalker.CaptureKind.Real).Select(f => f.Real).ToArray(); + if (values.Length != 24 || !values.All(double.IsFinite)) continue; + + byte[] bytes = new byte[sizeof(int) + values.Length * sizeof(double)]; + BinaryPrimitives.WriteInt32LittleEndian(bytes, values.Length); + for (int i = 0; i < values.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(bytes.AsSpan(sizeof(int) + i * sizeof(double)), values[i]); + result[field.QueueIndex] = bytes; + } + return result; + } + + internal static bool IsCalendarYear(long start, long end) + { + if (start < -62_135_596_800 || end > 253_402_300_799 || start > end) return false; + var first = DateTimeOffset.FromUnixTimeSeconds(start); + var last = DateTimeOffset.FromUnixTimeSeconds(end); + return first.Year == last.Year && first is { Month: 1, Day: 1 } && last is { Month: 12, Day: 31 }; + } +} diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index 1ed6ef55..78c97314 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using RvtIO.BuiltIns; namespace RvtIO.Parsing; @@ -12,46 +13,173 @@ namespace RvtIO.Parsing; /// record = [id:W][size:4][payload][size:4] block = [id:W][adler32(payload):4][size:4][payload][size:4] /// The payload walk is the field grammar of (breadth-first queue of owned objects); the edits it /// finds (tag renumbering, id narrowing, cut and inserted fields, left-out objects with the count of their array) are applied -/// to the payload bytes. A block that cannot be rewritten (unknown class at the root, an extensible-storage blob, a field of a -/// class the 2022 table lacks) keeps its bytes with the root class tag 0xFFFE, which no reader recognises. +/// to the payload bytes, and the queued objects are written in the order of the target pointer fields (Revit 2024 and later +/// store many classes in another order). A field renamed between the releases is matched by an explicit map; an +/// ESEntity blob is read by the schema it names and left empty, since the target release keeps the schemas in another +/// field. and keep the block bytes with the root class tag 0xFFFE when a block +/// cannot be rewritten; the downgrade writer leaves such an element out instead. /// internal sealed class R22Transcoder { internal const ushort UnknownTag = 0xFFFE; + internal const string ContextualAnalyticalMember = "AnalyticalMember"; private sealed class Fail(string message) : Exception(message); - private readonly record struct Edit(int Start, int End, byte[] Replacement); + private readonly record struct Edit(int Start, int End, byte[] Replacement, int? Slot = null); private readonly Dictionary _source; private readonly Dictionary _target; + private readonly SchemaDocument _sourceDocument; + private readonly SchemaDocument _targetDocument; private readonly Dictionary _targetByName; + /// Diagnostics: element-id invalidations and array-item drops across payloads. + internal int DiagDropItem, DiagMinusOne; + private readonly Dictionary _tagMap = new(); + private readonly HashSet _nonElementRecordClasses = []; + private readonly HashSet _legacyHostedLoads = []; private readonly int _sourceWidth; private readonly int _sourceIdentifier; private readonly ElementIdMap? _ids; + private readonly int _targetIdentifierWidth; + private readonly bool _tagMapping; + private readonly bool _clearAnalyticalMemberGeometry; + private readonly bool _clearAnalyticalPanelGeometry; + private readonly int? _uniqueElementSlots; + private readonly int? _legacyPropagationRule; + private readonly int _inlineContourSiteSurface; + private readonly bool _rekeyRebarSystems; + private HashSet _droppedElements = []; + private readonly SchemaField[]?[]? _entityFields; + private readonly Dictionary? _entityIndexOf; + private readonly Dictionary? _entityTargetSchemas; private readonly Dictionary _plans = new(); + private WideBlockWalker? _validationWalker; + private readonly WideBlockWalker? _energyScheduleWalker; /// Source fields in serialization order, the target class of the same name and the target field positions by (declaring class, field). private sealed record Plan((SchemaClass Declaring, SchemaField Field)[] Source, (SchemaClass Declaring, SchemaField Field)[] Target, int[] TargetIndex, bool[] TargetPresent, bool Reordered, bool[] Narrow); - internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceIdWidth, ElementIdMap? ids = null) + internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceIdWidth, + IReadOnlyDictionary? entitySchemas = null, bool tagMapping = false, int? downgradeRelease = null, ElementIdMap? ids = null) { + _tagMapping = tagMapping; + _uniqueElementSlots = downgradeRelease switch { 2020 => 78, 2021 => 81, 2022 => 83, 2023 => 85, _ => null }; + if (downgradeRelease == 2023) + _legacyPropagationRule = source.Classes.FirstOrDefault(c => c.Name == "OneDependencyPropagationFilterData" + && c.Fields.LastOrDefault(f => f.Stored) is { Name: "m_atomType", Type: 3, Mods: 0 })?.Id; _source = source.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); _target = target.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); + _sourceDocument = source; + _targetDocument = target; _targetByName = new(StringComparer.Ordinal); foreach (var c in target.Classes.OrderBy(c => c.Id)) _targetByName.TryAdd(c.Name, c.Id); + _clearAnalyticalMemberGeometry = downgradeRelease is not null && IsMissingTargetClass("AnalyticalMemberGStep"); + _clearAnalyticalPanelGeometry = downgradeRelease is not null && IsMissingTargetClass("AnalyticalPanelGStep"); + _rekeyRebarSystems = downgradeRelease is <= 2021 + && HasStoredUncutCurves(source) && !HasStoredUncutCurves(target); + if (source.Classes.Any(c => c.Name == "EnergyAnalysisSchedule" && c.Fields.Any(f => f.Name == "m_oYearScheduleInfos")) && + target.Classes.Any(c => c.Name == "EnergyAnalysisSchedule" && + c.Fields.Any(f => f is { Name: "m_dayScheduleValues", Type: 7, Mods: 0x50 }))) + { + _energyScheduleWalker = new WideBlockWalker(source, (c, f) => + c.Name.Contains("Schedule", StringComparison.Ordinal) || c.Name == "ATime" + ? WideBlockWalker.AllItemsKeyPrefix + c.Name + "." + f.Name : null, []); + if (entitySchemas is not null) _energyScheduleWalker.UseEntitySchemas(entitySchemas, passUnknown: true); + } + if (source.Classes.Any(c => c.Name == "ContourWrapper" && c.Fields.Any(f => f is { Name: "m_pData", Type: 14, Mods: 1 })) + && target.Classes.Any(c => c.Name == "ContourWrapper" && c.Fields.Any(f => f is { Name: "m_arr", Type: 14, Mods: 0x50 }))) + _inlineContourSiteSurface = source.Classes.FirstOrDefault(c => c.Name == "SiteSurface")?.Id ?? 0; foreach (var c in source.Classes) - if (_targetByName.TryGetValue(c.Name, out int id)) _tagMap[c.Id] = id; + { + // The 2022 table declares this preview class, but released Revit 2022 rejects its instances. + if (downgradeRelease == 2022 && c.Name == ContextualAnalyticalMember) continue; + if (_targetByName.TryGetValue(c.Name, out int id) + || (RenamedClasses.TryGetValue(c.Name, out string? renamedClass) && _targetByName.TryGetValue(renamedClass, out id)) + || (_tagMapping && TagRenamedClasses.TryGetValue(c.Name, out string? renamed) && _targetByName.TryGetValue(renamed, out id)) + || (ProjectedClasses.TryGetValue(c.Name, out var projection) && _targetByName.TryGetValue(projection.TargetClass, out id))) + _tagMap[c.Id] = id; + } + if (downgradeRelease is <= 2022 && source.Classes.FirstOrDefault(c => c.Name == "LoadBCBase") is { } loadBase) + foreach (var c in source.Classes) + // Revit 2021 can retain an area load's values with an empty host pick. + if (IsKindOf(_source, c.Id, loadBase.Id) && !(downgradeRelease == 2021 && c.Name == "AreaLoad")) + _legacyHostedLoads.Add(c.Id); + if (_targetByName.TryGetValue("Element", out int targetElement)) + foreach (var (sourceClass, targetClass) in _tagMap) + if (!IsKindOf(_target, targetClass, targetElement)) + _nonElementRecordClasses.Add(sourceClass); _sourceWidth = sourceIdWidth; _ids = ids; _sourceIdentifier = source.Classes.FirstOrDefault(c => c.Name == "ElementId")?.Id ?? -1; + // the width of an ElementId value in the target file: 8 bytes when the identifier class stores m_id64, else 4 + _targetIdentifierWidth = target.Classes.FirstOrDefault(c => c.Name == "Identifier") is { } targetIdentifier + && targetIdentifier.Fields.Any(f => f.Stored && f.Name == "m_id64" && f.Type == 11) ? 8 : 4; + if (entitySchemas is { Count: > 0 }) + { + _entityFields = [.. entitySchemas.Values]; + _entityIndexOf = entitySchemas.Keys.Select((guid, index) => (guid, index)).ToDictionary(pair => pair.guid, pair => pair.index); + // the same schemas with the class references of the target table: the check walk reads the + // written entity values with them, exactly as the older Revit will + _entityTargetSchemas = entitySchemas.ToDictionary( + pair => pair.Key, + pair => pair.Value is null ? (SchemaField[]?)null : [.. pair.Value.Select(MapToTarget)]); + } } - /// Class number of the 2022 table for a class of the file, 0 when it has none. + /// The class references of a field through the source-to-target map (template arguments too). + private SchemaField MapToTarget(SchemaField field) => field with + { + Ref = field.Ref is int reference ? _tagMap.GetValueOrDefault(reference) is int target && target != 0 ? target : null : null, + Ref2 = field.Ref2 is int reference2 ? _tagMap.GetValueOrDefault(reference2) is int target2 && target2 != 0 ? target2 : null : null, + Args = field.Args is null ? null : [.. field.Args.Select(MapToTarget)], + }; + + /// A saved element requires a target class that still derives from Element. + internal bool CanWriteRecord(int sourceClass, bool isElement) => + _tagMap.ContainsKey(sourceClass) && (!isElement || !_nonElementRecordClasses.Contains(sourceClass)); + internal int TargetId(int sourceClass) => _tagMap.GetValueOrDefault(sourceClass); + /// True when the file's own class table declares the class. + internal bool HasSourceClass(int sourceClass) => _source.ContainsKey(sourceClass); + + /// Pointer class tags that do not derive from the field's declared class in the target table (diagnostics). + internal Dictionary PointerMismatches { get; } = new(StringComparer.Ordinal); + + private string NameOfSource(int classId) => _source.GetValueOrDefault(classId)?.Name ?? classId.ToString(); + + private string NameOfTarget(int classId) => _target.GetValueOrDefault(classId)?.Name ?? classId.ToString(); + + private static bool IsKindOf(Dictionary classes, int classId, int baseClassId) + { + for (int guard = 0; classId != 0 && guard < 64; guard++) + { + if (classId == baseClassId) return true; + if (!classes.TryGetValue(classId, out var c)) return false; + classId = c.Base; + } + return false; + } + + + /// + /// The element ids the written file holds () and the highest one, plus + /// the ids explicitly left out (): only a reference to a dropped id is + /// dangling and is written as invalid (-1) or leaves its array, so the older Revit does not + /// follow it into an element that is gone. Ids that were never held (built-in elements without + /// owner records) and ids above the highest present one are left alone. + /// + internal void SetElementUniverse(IReadOnlySet present, uint maxElementId, IReadOnlySet? dropped = null) + { + _droppedElements = dropped is null || present.Count == 0 + ? [] : [.. dropped.Where(id => id <= maxElementId).Select(id => (ulong)id)]; + } + + internal void SetDroppedElementIds(IReadOnlySet dropped) => _droppedElements = [.. dropped]; + /// Where wrote a block of its input: in the concatenation of the chunks it /// returned, for bytes; the block was bytes in the input. @@ -400,20 +528,81 @@ private sealed class Context(byte[] data, int pos, int end) public readonly int End = end; public readonly List<(int Tag, bool Dropped)> Queue = []; public readonly List Edits = []; + /// The source offset at which each queued object starts, in queue (storage) order. + public readonly List ObjectStarts = []; + /// Per object slot (root = -1, queued object i = i) the queue ranges its pointer fields created, by target field index. + public readonly Dictionary> Groups = []; + /// The object whose fields are being read: -1 at the root. + public int Slot = -1; + /// The target index of the top-level field being read, inherited by inline structures. + public int FieldKey = int.MaxValue; + public int GroupSeq; + /// The payload reorders pointer fields or class fields, so its structure is checked against the target schema. + public bool NeedsValidation; public bool Cutting; - public int Dropped; + public bool LegacyHostedLoad; + public IReadOnlyDictionary? DailySchedules; public bool InArray; + /// Inside a counted array, also through inline structures (its items must keep their stored order). + public bool DeepInArray; /// The 64-bit scalars being read take the place of 32-bit 2022 fields. public bool Narrow; + /// The field being read ("Declaring.field"), for failure messages. + public string? Field; + /// The last ForgeTypeId text read (a parameter group type id). + public string? LastForgeText; + /// The built-in parameter group element id the current ParamDef names (its source has a type id instead). + public int? GroupElementId; + public byte[]? RebarSystemVolume; + /// The m_bByRange value of the color fill entry being read (its target has a lowest-entry flag the source lacks). + public byte LastByRange; + /// The index of the item being read in its counted array. + public int ArrayItemIndex; + /// A counted-array item holds a reference to a dropped element and goes out with it. + public bool DropItem; + /// Diagnostics: element-id reads by outcome. + public int Dropped; + public int DiagMinusOne, DiagDropItem; + /// Inside a counted array whose items can be left out (fixed-size arrays keep every item). + public bool Droppable; + /// Inside a fixed-size array (its items keep their places; a dangling id becomes invalid). + public bool InFixedArray; } /// The payload (class tag first) in the 2022 layout, or null when it cannot be rewritten. internal byte[]? Payload(byte[] data, int offset, int size) => Payload(data, offset, size, out _); + /// The payload in the 2022 layout with every byte after the object copied unchanged (a stream that holds one + /// class object followed by opaque data), or null when the object cannot be rewritten. + internal byte[]? PayloadWithTail(byte[] data, int offset, int size, out string? failure) + { + byte[]? prefix = PayloadObject(data, offset, size, out int objectEnd, out failure, validateTarget: true); + if (prefix is null) return null; + if (objectEnd == offset + size) return prefix; + var result = new byte[prefix.Length + (offset + size - objectEnd)]; + prefix.CopyTo(result, 0); + Buffer.BlockCopy(data, objectEnd, result, prefix.Length, offset + size - objectEnd); + return result; + } + /// Why the payload cannot be rewritten (the root class and the first rule that failed), null when it can. internal byte[]? Payload(byte[] data, int offset, int size, out string? failure) + { + byte[]? rewritten = PayloadObject(data, offset, size, out int objectEnd, out failure); + if (rewritten is null) return null; + if (objectEnd != offset + size) + { + failure = (_source.TryGetValue(BitConverter.ToUInt16(data, offset), out var root) ? root.Name : "class") + + ": bytes after the end of the object"; + return null; + } + return rewritten; + } + + private byte[]? PayloadObject(byte[] data, int offset, int size, out int objectEnd, out string? failure, bool validateTarget = false) { failure = null; + objectEnd = offset; if (size < 2 || offset + (long)size > data.Length) { failure = "short payload"; return null; } int rootClass = BitConverter.ToUInt16(data, offset); if (!_tagMap.ContainsKey(rootClass)) @@ -421,43 +610,198 @@ private sealed class Context(byte[] data, int pos, int end) failure = (_source.TryGetValue(rootClass, out var unknown) ? unknown.Name : "tag " + rootClass) + ": root class without a 2022 counterpart"; return null; } - var c = new Context(data, offset + 2, offset + size); + var c = new Context(data, offset + 2, offset + size) + { + LegacyHostedLoad = _legacyHostedLoads.Contains(rootClass), + }; + if (_energyScheduleWalker is not null && _source[rootClass].Name == "EnergyAnalysisDetailModel") + c.DailySchedules = LegacyEnergySchedules.Read(_energyScheduleWalker, data, offset, size, rootClass); try { c.Edits.Add(new(offset, offset + 2, Tag(_tagMap[rootClass]))); ReadObject(c, rootClass); for (int i = 0; i < c.Queue.Count; i++) { + c.ObjectStarts.Add(c.Pos); + c.Slot = i; var (tag, dropped) = c.Queue[i]; - if (dropped || !_tagMap.ContainsKey(tag)) + if (dropped || (tag >= 0 && !_tagMap.ContainsKey(tag))) { - // an object of a class the 2022 table does not know: read it with the source grammar and cut it out + // an object of a class the 2022 table does not know: read it with the source grammar and cut it out. + // Only edits strictly inside the cut region are discarded: a zero-width insertion exactly at its + // start belongs to the previous object (for example a default field value appended to it) and stays. int start = c.Pos, mark = c.Queue.Count; c.Cutting = true; ReadObject(c, tag); c.Cutting = false; - c.Edits.RemoveAll(e => e.Start >= start); + c.Edits.RemoveAll(e => e.Start > start || (e.Start == start && e.End > start)); c.Edits.Add(new(start, c.Pos, [])); for (int j = mark; j < c.Queue.Count; j++) c.Queue[j] = (c.Queue[j].Tag, true); + c.Slot = -1; continue; } ReadObject(c, tag); + c.Slot = -1; } - if (c.Pos != c.End) { failure = _source[rootClass].Name + ": bytes after the end of the object"; return null; } + objectEnd = c.Pos; } catch (Fail fail) { - failure = _source[rootClass].Name + ": " + fail.Message; + failure = _source[rootClass].Name + ": " + fail.Message + (c.Field is null ? "" : " at " + c.Field); return null; } - try { return Apply(data, offset, offset + size, c.Edits); } + try + { + byte[] assembled = Assemble(c, offset, c.Pos); + if (_inlineContourSiteSurface != 0 && IsKindOf(_source, rootClass, _inlineContourSiteSurface)) + { + assembled = InlineSurfaceContours(data, offset, rootClass, c.Pos, assembled); + c.NeedsValidation = true; + } + DiagDropItem += c.DiagDropItem; + DiagMinusOne += c.DiagMinusOne; + bool rekey = _rekeyRebarSystems && _source[rootClass].Name == "RebarSystem"; + if (validateTarget || c.NeedsValidation || rekey) + { + if (_validationWalker is null) + { + _validationWalker = new WideBlockWalker(_targetDocument, (_, _) => null, []); + if (_entityTargetSchemas is not null) _validationWalker.UseEntitySchemas(_entityTargetSchemas, passUnknown: true); + } + var walk = _validationWalker.Run(assembled, 0, assembled.Length, BitConverter.ToUInt16(assembled, 0), + captureArchiveKeys: rekey); + if (!walk.Exact || walk.Error != null) + { + failure = _source[rootClass].Name + ": the rewritten object does not read to its end" + + (walk.Error is null ? "" : " (" + walk.Error + ")") + + (walk.StopField is null ? "" : " at " + walk.StopField); + return null; + } + if (walk.ArchiveKeys is { } keys) RekeyArchive(assembled, keys); + } + return assembled; + } catch (Fail fail) { - failure = _source[rootClass].Name + ": " + fail.Message; + failure = _source[rootClass].Name + ": " + fail.Message + (c.Field is null ? "" : " at " + c.Field); return null; } } + private static bool HasStoredUncutCurves(SchemaDocument schema) => + schema.Classes.Any(c => c.Name == "RebarSystemLayer" && c.Fields.Any(f => f.Stored && f.Name == "m_uncutCurves")); + + private byte[] InlineSurfaceContours(byte[] source, int start, int sourceClass, int end, byte[] target) + { + var sourceWalker = new WideBlockWalker(_sourceDocument, (c, f) => (c.Name, f.Name) switch + { + ("ContourWrapper", "m_pData") => "pointer", + ("SurfaceContourData", "m_arr") => "polylines", + _ => null, + }, []); + if (_entityFields is not null && _entityIndexOf is not null) + sourceWalker.UseEntitySchemas(_entityIndexOf.ToDictionary(p => p.Key, p => _entityFields[p.Value]), passUnknown: true); + var sourceWalk = sourceWalker.Run(source, start, end - start, sourceClass); + if (!sourceWalk.Exact) throw new Fail("cannot read source surface contours"); + var pointers = sourceWalk.Captures.Where(c => c.Key == "pointer").ToArray(); + if (pointers.All(c => c.Integer == 0)) return target; + + var targetWalker = new WideBlockWalker(_targetDocument, + (c, f) => c.Name == "ContourWrapper" && f.Name == "m_arr" ? "polylines" : null, []); + if (_entityTargetSchemas is not null) targetWalker.UseEntitySchemas(_entityTargetSchemas, passUnknown: true); + var targetWalk = targetWalker.Run(target, 0, target.Length, BitConverter.ToUInt16(target)); + var arrays = targetWalk.Captures.Where(c => c.Key == "polylines#").ToArray(); + if (!targetWalk.Exact || pointers.Length != arrays.Length || arrays.Any(c => c.Integer != 0)) + throw new Fail("cannot match target surface contours"); + var spans = sourceWalk.Captures.Where(c => c.Key == "polylines#").ToDictionary(c => c.QueueIndex); + var edits = new List(); + for (int i = 0; i < pointers.Length; i++) + { + if (pointers[i].Integer == 0) continue; + if (pointers[i].TargetQueueIndex is not int slot || sourceWalker.Class(sourceWalk.Queue[slot])?.Name != "SurfaceContourData" + || !spans.TryGetValue(slot, out var field) || field.Offset != sourceWalk.QueueStart[slot]) + throw new Fail("unknown surface contour payload"); + int next = slot + 1 < sourceWalk.QueueStart.Count ? sourceWalk.QueueStart[slot + 1] : end; + // Both layouts store counted polylines of three doubles per point. + edits.Add(new(arrays[i].Offset, arrays[i].Offset + sizeof(int), source.AsSpan(field.Offset, next - field.Offset).ToArray())); + } + return Apply(target, 0, target.Length, edits); + } + + private static void RekeyArchive(byte[] payload, List keys) + { + // The older reader registers positive keys in order. Removing the uncut curves leaves gaps. + var mapping = new Dictionary(); + foreach (var key in keys) + if (key.Owned && !mapping.TryAdd(key.Key, (uint)mapping.Count + 3)) + throw new Fail("duplicate archive key " + key.Key); + foreach (var key in keys) + { + if (!mapping.TryGetValue(key.Key, out uint replacement)) + throw new Fail("unresolved archive key " + key.Key); + BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(key.Offset), replacement); + } + } + + /// + /// The rewritten payload: the root fields, then the queued objects in the order of the target + /// pointer fields (breadth-first over the recorded field groups), with the objects of dropped + /// classes left out. Each object's bytes are its own source range with its own edits. + /// + private static byte[] Assemble(Context c, int offset, int objectEnd) + { + int n = c.ObjectStarts.Count; + int rootEnd = n > 0 ? c.ObjectStarts[0] : objectEnd; + var bySlot = new List[n + 1]; + for (int i = 0; i <= n; i++) bySlot[i] = []; + foreach (var edit in c.Edits) + { + int slot = edit.Slot is int objectSlot ? objectSlot + 1 : 0; + if (edit.Slot is null && n > 0) + { + // an insertion exactly at an object start belongs to the object before it (its + // trailing default fields), so it is looked up with a strict comparison + bool insertion = edit.Start == edit.End; + int lo = 0, hi = n - 1, found = -1; + while (lo <= hi) + { + int mid = (lo + hi) / 2; + bool atOrBefore = insertion ? c.ObjectStarts[mid] < edit.Start : c.ObjectStarts[mid] <= edit.Start; + if (atOrBefore) { found = mid; lo = mid + 1; } + else hi = mid - 1; + } + slot = found + 1; + } + bySlot[slot].Add(edit); + } + + var order = new List(); + var emitted = new bool[n]; + void Children(int slot) + { + if (!c.Groups.TryGetValue(slot, out var groups)) return; + foreach (var group in groups.OrderBy(g => g.Key).ThenBy(g => g.Seq)) + for (int i = group.Start; i < group.End; i++) + if (!c.Queue[i].Dropped && !emitted[i]) + { + emitted[i] = true; + order.Add(i); + } + } + Children(-1); + for (int i = 0; i < order.Count; i++) Children(order[i]); + + using var output = new MemoryStream(); + output.Write(Apply(c.D, offset, rootEnd, bySlot[0])); + foreach (int q in order) + { + int start = c.ObjectStarts[q]; + int end = q + 1 < n ? c.ObjectStarts[q + 1] : objectEnd; + output.Write(Apply(c.D, start, end, bySlot[q + 1])); + } + return output.ToArray(); + } + /// The bytes [start, end) with the edits applied (insertions sort before the replacement that starts at the same place). private static byte[] Apply(byte[] data, int start, int end, List edits) { @@ -503,13 +847,16 @@ private static byte[] Tag(int id) private Plan PlanOf(int sourceClass) { if (_plans.TryGetValue(sourceClass, out var plan)) return plan; - if (!_tagMap.TryGetValue(sourceClass, out int targetClass)) throw new Fail("class without a 2022 counterpart"); + if (!_tagMap.TryGetValue(sourceClass, out int targetClass)) + throw new Fail("class " + (_source.GetValueOrDefault(sourceClass)?.Name ?? sourceClass.ToString()) + " without a 2022 counterpart"); var source = Chain(_source, sourceClass); var target = Chain(_target, targetClass); var index = new Dictionary<(string, string), int>(); for (int i = 0; i < target.Length; i++) index[(target[i].Declaring.Name, target[i].Field.Name)] = i; - var sourceKeys = source.Select(s => (s.Declaring.Name, s.Field.Name)).ToHashSet(); - var targetIndex = source.Select(s => index.GetValueOrDefault((s.Declaring.Name, s.Field.Name), -1)).ToArray(); + string TargetName(string declaring, string field) => + !index.ContainsKey((declaring, field)) && TryRenamed(declaring, field, out var rename) ? rename.Name : field; + var sourceKeys = source.Select(s => (s.Declaring.Name, TargetName(s.Declaring.Name, s.Field.Name))).ToHashSet(); + var targetIndex = source.Select(s => index.GetValueOrDefault((s.Declaring.Name, TargetName(s.Declaring.Name, s.Field.Name)), -1)).ToArray(); // Revit 2024 widened some 32-bit fields to 64 bits under a new name ("m_id" became "m_id64", "m_otherInt" "m_otherInt64"): // a 64-bit source field takes the place of the 32-bit 2022 field of the name without the "64", when the file has no field of that name var narrow = new bool[source.Length]; @@ -524,9 +871,46 @@ private Plan PlanOf(int sourceClass) targetIndex[i] = k; narrow[i] = true; } + // A renamed source field takes the place of its target name when the source has no field of that name. + for (int i = 0; i < source.Length; i++) + { + var (declaring, field) = source[i]; + if (targetIndex[i] < 0 || target[targetIndex[i]].Field.Name == field.Name + || !TryRenamed(declaring.Name, field.Name, out var rename) || !rename.Narrow) continue; + var t = target[targetIndex[i]]; + if (field.Type != 11 || t.Field.Type is not (4 or 5) || t.Field.Mods != field.Mods) + throw new Fail($"renamed field {declaring.Name}.{field.Name} does not fit {t.Declaring.Name}.{t.Field.Name}"); + for (int other = 0; other < i; other++) + if (targetIndex[other] == targetIndex[i]) throw new Fail($"renamed field {declaring.Name}.{field.Name} is claimed twice"); + narrow[i] = true; + } + // A field the target declares in another class of the chain (a base class renamed between + // the releases): match it by its own name when the type and modifiers agree and it is the + // only free target field of that name. + { + var claimed = new HashSet(targetIndex.Where(k => k >= 0)); + var unmatched = Enumerable.Range(0, source.Length).Where(i => targetIndex[i] < 0).ToList(); + foreach (int i in unmatched) + { + var field = source[i].Field; + string targetName = TargetName(source[i].Declaring.Name, field.Name); + if (unmatched.Count(j => TargetName(source[j].Declaring.Name, source[j].Field.Name) == targetName) != 1) continue; + int candidate = -1; + for (int t = 0; t < target.Length; t++) + { + if (claimed.Contains(t) || target[t].Field.Name != targetName) continue; + if (target[t].Field.Type != field.Type || target[t].Field.Mods != field.Mods) continue; + if (candidate >= 0) { candidate = -2; break; } + candidate = t; + } + if (candidate < 0) continue; + targetIndex[i] = candidate; + claimed.Add(candidate); + } + } var present = target.Select(t => sourceKeys.Contains((t.Declaring.Name, t.Field.Name))).ToArray(); for (int i = 0; i < source.Length; i++) - if (narrow[i]) present[targetIndex[i]] = true; + if (targetIndex[i] >= 0) present[targetIndex[i]] = true; // the fields both classes have are stored in another order (Revit 2024 and later store many classes in a changed order) var kept = targetIndex.Where(k => k >= 0).ToArray(); bool reordered = kept.Zip(kept.Skip(1), (a, b) => b < a).Any(x => x); @@ -548,9 +932,17 @@ private static (SchemaClass Declaring, SchemaField Field)[] Chain(Dictionary= _entityFields.Length || _entityFields[layout] is not { } entityFields) + throw new Fail("entity schema fields are not known"); + foreach (var field in entityFields) ReadField(c, "ESBlob", field, 0); + return; + } if (c.Cutting) { - foreach (var (_, field) in Chain(_source, sourceClass)) ReadField(c, field, 0); + foreach (var (declaring, field) in Chain(_source, sourceClass)) ReadField(c, declaring.Name, field, 0); return; } ReadFields(c, sourceClass, 0); @@ -560,47 +952,144 @@ private void ReadObject(Context c, int sourceClass) /// in another order) rewritten in the order of the 2022 class. private void ReadFields(Context c, int sourceClass, int depth) { + string sourceName = _source[sourceClass].Name; + if (!_targetByName.ContainsKey(sourceName) && ProjectedClasses.TryGetValue(sourceName, out var projected)) + { + ReadProjectedClass(c, sourceClass, projected.SubField, depth); + return; + } var plan = PlanOf(sourceClass); + bool projectBrowserMap = sourceName == "BrowserOrganizationTracking" + && plan.Source.Any(f => f.Field.Name == "m_currentBrOrgTypeToBrOrgMap") + && !plan.Target.Any(f => f.Field.Name == "m_currentBrOrgTypeToBrOrgMap"); + bool projectEsUnit = sourceName == "ESField" + && plan.Target.Any(f => f.Field.Name == "m_unitType") + && !plan.Source.Any(f => f.Field.Name == "m_unitType"); + bool composeFields = plan.Reordered || projectBrowserMap || projectEsUnit; + // The legacy analytical classes regenerate from their own curve or surface. Their geometry steps + // and geometry table must be cleared together when the target does not have the new step class. + bool clearAnalyticalGeometry = depth == 0 && (sourceName switch + { + "AnalyticalMember" => _clearAnalyticalMemberGeometry, + "AnalyticalPanel" => _clearAnalyticalPanelGeometry, + _ => false, + }); + if (composeFields) c.NeedsValidation = true; int regionStart = c.Pos, regionEdits = c.Edits.Count; var spans = new (int Start, int End, int EditFrom, int EditTo)[plan.Source.Length]; + (byte First, byte Last)? includedBarEnds = null; + Dictionary? browserOrganizations = null; + string? esSpec = null; + byte[] MissingField(int index) + { + var target = plan.Target[index]; + if (projectEsUnit && target.Field.Name == "m_unitType") + return BitConverter.GetBytes((int)LegacyEsUnit(esSpec)); + if (browserOrganizations is not null && target.Declaring.Name == "BrowserOrganizationTracking" + && target.Field is { Type: 14, Mods: 0, Ref: int reference } + && _target.GetValueOrDefault(reference)?.Name == "ElementId") + { + int kind = target.Field.Name switch + { + "m_currentBrOrgViews" => 0, + "m_currentBrOrgSheets" => 1, + "m_currentBrOrgSchedules" => 3, + _ => -1, + }; + if (kind >= 0) + { + long id = browserOrganizations.GetValueOrDefault(kind, -1); + if (id > 0 && _droppedElements.Contains((ulong)id)) id = -1; + if (_targetIdentifierWidth == 4 && (id < int.MinValue || id > uint.MaxValue)) + throw new Fail("id beyond 32 bits: " + id); + return TargetElementId(id); + } + } + if (includedBarEnds is { } ends && target.Declaring.Name == "RebarInstBase" + && target.Field is { Type: 1, Mods: 0 }) + { + if (target.Field.Name == "m_includeFirstBar") return [ends.First]; + if (target.Field.Name == "m_includeLastBar") return [ends.Last]; + } + return DefaultFor(c, target); + } + int last = -1, lastQueuing = -1; for (int i = 0; i < plan.Source.Length; i++) { int k = plan.TargetIndex[i]; int start = c.Pos, editFrom = c.Edits.Count, queued = c.Queue.Count; + var (declaring, field) = plan.Source[i]; if (k < 0) { // a field the 2022 class does not have: read with the source grammar and cut out + bool readEsSpec = projectEsUnit && field.Name == "m_specTypeId"; + if (readEsSpec) c.LastForgeText = null; c.Cutting = true; - ReadField(c, plan.Source[i].Field, depth); + ReadField(c, declaring.Name, field, depth); c.Cutting = false; + if (readEsSpec) esSpec = c.LastForgeText; + if (projectBrowserMap && field.Name == "m_currentBrOrgTypeToBrOrgMap") + browserOrganizations = ReadBrowserOrganizations(c.D.AsSpan(start, c.Pos - start), field); + if (declaring.Name == "RebarInstBase" && field is { Name: "m_includedBars", Type: 1, Mods: 0x50 } + && c.Pos > start + 4) + includedBarEnds = (c.D[start + 4], c.D[c.Pos - 1]); + if (depth == 0 && c.Slot == -1 && declaring.Name == "RebarSystemBase" + && field is { Name: "m_totalVolume", Type: 7, Mods: 0 }) + c.RebarSystemVolume = c.D.AsSpan(start, 8).ToArray(); + if (plan.Source[i].Declaring.Name == "ParamDef" && plan.Source[i].Field.Name == "m_groupTypeId" && c.LastForgeText is { } cutGroup) + c.GroupElementId = ParameterGroupElementIds.GetValueOrDefault(cutGroup, -1); c.Edits.RemoveRange(editFrom, c.Edits.Count - editFrom); c.Edits.Add(new(start, c.Pos, [])); spans[i] = (-1, -1, 0, 0); continue; } - if (!plan.Reordered) + if (!composeFields) { for (int j = last + 1; j < k; j++) - if (!plan.TargetPresent[j]) c.Edits.Add(new(start, start, Default(plan.Target[j]))); + if (!plan.TargetPresent[j]) c.Edits.Add(new(start, start, MissingField(j), c.Slot)); last = Math.Max(last, k); editFrom = c.Edits.Count; } c.Narrow = plan.Narrow[i]; - ReadField(c, plan.Source[i].Field, depth); + if (depth == 0) c.FieldKey = k; + if (clearAnalyticalGeometry && declaring.Name == "Element" && field.Type == 14 && field.Mods == 1 + && field.Name is "m_geomSteps" or "m_pGeomTable") + { + c.Cutting = true; + ReadField(c, declaring.Name, field, depth); + c.Cutting = false; + c.Edits.Add(new(start, c.Pos, new byte[4])); + c.NeedsValidation = true; + } + else if (plan.Target[k].Field.Name != plan.Source[i].Field.Name + && TryRenamed(plan.Source[i].Declaring.Name, plan.Source[i].Field.Name, out var projection) + && projection.SubField is { } subField && k >= 0) + ReadProjectedField(c, plan.Source[i].Field, subField, depth); + else + ReadField(c, plan.Source[i].Declaring.Name, plan.Source[i].Field, depth); c.Narrow = false; + if (depth == 0 && plan.Source[i].Declaring.Name == "ParamDef" && plan.Source[i].Field.Name == "m_groupTypeId" && c.LastForgeText is { } group) + c.GroupElementId = ParameterGroupElementIds.GetValueOrDefault(group, -1); spans[i] = (start, c.Pos, editFrom, c.Edits.Count); if (c.Queue.Count != queued) { - // the objects of the pointers follow in the order of the fields: they cannot change places - if (k < lastQueuing) throw new Fail("pointer fields change their order"); + // the objects of the pointers follow in the order of the fields; at the top level + // the queue is put into the order of the target fields when the payload is assembled + if (depth > 0 && k < lastQueuing) throw new Fail("pointer fields change their order"); + if (depth == 0 && k < lastQueuing) c.NeedsValidation = true; + if (k >= 0) + { + if (!c.Groups.TryGetValue(c.Slot, out var groups)) c.Groups[c.Slot] = groups = []; + groups.Add((c.FieldKey, queued, c.Queue.Count, c.GroupSeq++)); + } lastQueuing = k; } } - if (!plan.Reordered) + if (!composeFields) { for (int j = last + 1; j < plan.Target.Length; j++) - if (!plan.TargetPresent[j]) c.Edits.Add(new(c.Pos, c.Pos, Default(plan.Target[j]))); + if (!plan.TargetPresent[j]) c.Edits.Add(new(c.Pos, c.Pos, MissingField(j), c.Slot)); return; } var bySource = new int[plan.Target.Length]; @@ -610,15 +1099,104 @@ private void ReadFields(Context c, int sourceClass, int depth) var composed = new MemoryStream(); for (int j = 0; j < plan.Target.Length; j++) { - if (bySource[j] < 0) { composed.Write(Default(plan.Target[j])); continue; } + if (bySource[j] < 0) { composed.Write(MissingField(j)); continue; } var (start, end, from, to) = spans[bySource[j]]; composed.Write(Apply(c.D, start, end, c.Edits.GetRange(from, to - from))); } c.Edits.RemoveRange(regionEdits, c.Edits.Count - regionEdits); - c.Edits.Add(new(regionStart, c.Pos, composed.ToArray())); + c.Edits.Add(new(regionStart, c.Pos, composed.ToArray(), c.Slot)); + } + + private static UnitType LegacyEsUnit(string? spec) + { + // ForgeTypeId identity excludes the version suffix. + int version = spec?.IndexOf('-') ?? -1; + string? name = version < 0 ? spec : spec![..version]; + return name switch + { + "" => UnitType.UT_Undefined, + "autodesk.spec:custom" => UnitType.UT_Custom, + "autodesk.spec.aec:angle" => UnitType.UT_Angle, + "autodesk.spec.aec:length" => UnitType.UT_Length, + "autodesk.spec.aec.structural:force" => UnitType.UT_Force, + "autodesk.spec.aec.structural:linearForce" => UnitType.UT_LinearForce, + "autodesk.spec.aec.structural:linearMoment" => UnitType.UT_LinearMoment, + "autodesk.spec.aec.structural:moment" => UnitType.UT_Moment, + "autodesk.spec.aec.structural:stress" => UnitType.UT_Stress, + // shortcut: only verified legacy equivalents are mapped. Extend when another spec has a verified equivalent. + _ => throw new Fail($"ESField spec '{spec ?? ""}' has no known legacy unit"), + }; + } + + private Dictionary ReadBrowserOrganizations(ReadOnlySpan data, SchemaField field) + { + if (field is not { Type: 14, Mods: 0x50, Ref: int pairId } || !_source.TryGetValue(pairId, out var pair) + || pair.Base != 0 || pair.Fields.Where(f => f.Stored).ToArray() is not + [{ Name: "first", Type: 4, Mods: 0 }, { Name: "second", Type: 14, Mods: 0, Ref: int idRef }] + || idRef != _sourceIdentifier || data.Length < sizeof(uint)) + throw new Fail("browser organization map layout"); + uint count = BinaryPrimitives.ReadUInt32LittleEndian(data); + if (count == uint.MaxValue) count = 0; + int itemWidth = sizeof(int) + _sourceWidth; + if (data.Length != sizeof(uint) + (long)count * itemWidth) + throw new Fail("browser organization map length"); + var organizations = new Dictionary(); + for (int at = sizeof(uint); at < data.Length; at += itemWidth) + { + int kind = BinaryPrimitives.ReadInt32LittleEndian(data[at..]); + var value = data[(at + sizeof(int))..]; + long id = _sourceWidth == 8 ? BinaryPrimitives.ReadInt64LittleEndian(value) : BinaryPrimitives.ReadInt32LittleEndian(value); + if (!organizations.TryAdd(kind, id)) throw new Fail("duplicate browser organization kind"); + } + return organizations; } + /// Reads one field of an inline structure as the target field: the other fields of the + /// source structure are read only to keep the grammar and cut (the 2027 reference id key holds + /// the 2023 tagged element as its first field, the rest has no counterpart). + /// Reads a source class through one of its sub-objects as the target class (the 2027 + /// schema usage entry is the 2023 stored schema plus the data around it). + private void ReadProjectedClass(Context c, int sourceClass, string subField, int depth) + { + foreach (var (declaring, field) in Chain(_source, sourceClass)) + { + if (field.Name == subField) + { + ReadField(c, declaring.Name, field, depth); + continue; + } + int start = c.Pos; + c.Cutting = true; + ReadField(c, declaring.Name, field, depth); + c.Cutting = false; + c.Edits.RemoveAll(e => e.Start >= start); + c.Edits.Add(new(start, c.Pos, [])); + } + } + + private void ReadProjectedField(Context c, SchemaField field, string subField, int depth) + { + if (field.Ref is not int inlineClass) throw new Fail("projected field without a class"); + foreach (var (declaring, nested) in Chain(_source, inlineClass)) + { + if (nested.Name == subField) + { + ReadField(c, declaring.Name, nested, depth); + continue; + } + int start = c.Pos; + c.Cutting = true; + ReadField(c, declaring.Name, nested, depth); + c.Cutting = false; + c.Edits.RemoveAll(e => e.Start >= start); + c.Edits.Add(new(start, c.Pos, [])); + } + } + + private bool IsMissingTargetClass(string name) => + !_targetByName.ContainsKey(name) && _source.Values.Any(c => c.Name == name); + private static int Take(Context c, int n) { if (n < 0 || c.Pos + (long)n > c.End) throw new Fail("end of payload"); @@ -629,13 +1207,17 @@ private static int Take(Context c, int n) private static uint U32(Context c) => BitConverter.ToUInt32(c.D, Take(c, 4)); - private void ReadField(Context c, SchemaField f, int depth) + private void ReadField(Context c, string? declaring, SchemaField f, int depth) { + c.Field = (declaring ?? "?") + "." + f.Name; int hi = f.Mods >> 4; - if (hi == 6) { ReadScalar(c, f, depth); return; } + if (hi == 6) { ReadScalar(c, declaring, f, depth); return; } if (hi == 1) { - for (int i = 0; i < (f.Fixed ?? 0); i++) ReadScalar(c, f, depth); + bool outerFixed = c.InFixedArray; + c.InFixedArray = true; + for (int i = 0; i < (f.Fixed ?? 0); i++) ReadScalar(c, declaring, f, depth); + c.InFixedArray = outerFixed; return; } if (hi == 5) @@ -645,22 +1227,73 @@ private void ReadField(Context c, SchemaField f, int depth) if (n == 0xFFFFFFFF) n = 0; if (n > 5_000_000) throw new Fail("count"); if (f.Type is 1 or 2 && (f.Mods & 15) == 0) { Take(c, (int)n); return; } + uint kept = n; + if (_uniqueElementSlots is int slots && !c.Cutting && IsUniqueElementSlot(declaring, f) + && f.Type == 14 && f.Mods == 0x50 && f.Ref == _sourceIdentifier) + kept = Math.Min(n, (uint)slots); int before = c.Dropped; - bool outer = c.InArray; + bool pruneQueuedItems = (declaring, f.Name) is ("NOBLE_SecondaryDataStorage", "m_data") + or ("NobleDocWarnings", "m_nobleWarningsMap"); + bool prunePropagationItems = !c.Cutting && _legacyPropagationRule is int ruleClass + && declaring == "PropagationFilterData" && f is { Name: "m_data", Type: 14, Mods: 0x50 } && f.Ref == ruleClass; + bool outer = c.InArray, outerDeep = c.DeepInArray, outerDrop = c.DropItem; + bool outerDroppable = c.Droppable, outerFixed = c.InFixedArray; + int outerIndex = c.ArrayItemIndex; c.InArray = true; - for (uint i = 0; i < n; i++) ReadScalar(c, f, depth); + c.DeepInArray = true; + c.Droppable = true; + c.InFixedArray = false; + int itemsDropped = 0; + for (uint i = 0; i < kept; i++) + { + c.ArrayItemIndex = (int)i; + int itemStart = c.Pos, itemQueue = c.Queue.Count, droppedBeforeItem = c.Dropped; + c.DropItem = false; + ReadScalar(c, declaring, f, depth); + // Revit 2023 cannot register the later AtomAddLayerShadowCleanPair rule (1568). + if (prunePropagationItems && BitConverter.ToUInt16(c.D, c.Pos - sizeof(ushort)) == 1568) + c.DropItem = true; + if (c.DropItem && (pruneQueuedItems || c.Queue.Count == itemQueue)) + { + // Remove the entire invalid item, including any object it queued. + c.Edits.RemoveAll(e => e.Start > itemStart || (e.Start == itemStart && e.End > itemStart)); + c.Edits.Add(new(itemStart, c.Pos, [])); + for (int j = itemQueue; j < c.Queue.Count; j++) + c.Queue[j] = (c.Queue[j].Tag, true); + c.NeedsValidation |= c.Queue.Count != itemQueue; + c.Dropped = droppedBeforeItem; + itemsDropped++; + } + } + c.DropItem = outerDrop; c.InArray = outer; - if (c.Dropped > before) c.Edits.Add(new(countAt, countAt + 4, BitConverter.GetBytes(n - (uint)(c.Dropped - before)))); + c.DeepInArray = outerDeep; + c.Droppable = outerDroppable; + c.InFixedArray = outerFixed; + c.ArrayItemIndex = outerIndex; + if (kept != n) + { + int trailing = Take(c, checked((int)(n - kept) * _sourceWidth)); + c.Edits.Add(new(trailing, c.Pos, [])); + } + if (c.Dropped > before || itemsDropped > 0 || kept != n) + c.Edits.Add(new(countAt, countAt + 4, BitConverter.GetBytes(kept - (uint)(c.Dropped - before) - (uint)itemsDropped))); return; } - ReadScalar(c, f, depth); + ReadScalar(c, declaring, f, depth); } - private void ReadScalar(Context c, SchemaField f, int depth) + private void ReadScalar(Context c, string? declaring, SchemaField f, int depth) { switch (f.Type) { - case 1: case 2: Take(c, 1); return; + case 1: case 2: + { + int p = Take(c, 1); + if (!c.Cutting && declaring == "ColorFillData" && f.Name == "m_bByRange") + c.LastByRange = c.D[p]; + return; + } case 3: Take(c, 2); return; case 4: case 5: case 6: Take(c, 4); return; case 7: Take(c, 8); return; @@ -670,8 +1303,8 @@ private void ReadScalar(Context c, SchemaField f, int depth) if (c.Narrow && !c.Cutting) { long value = BitConverter.ToInt64(c.D, p); - if (value < int.MinValue || value > int.MaxValue) throw new Fail("value beyond 32 bits"); - c.Edits.Add(new(p, p + 8, BitConverter.GetBytes((int)value))); + if (value < int.MinValue || value > uint.MaxValue) throw new Fail("value beyond 32 bits"); + c.Edits.Add(new(p, p + 8, BitConverter.GetBytes(unchecked((int)value)))); } return; } @@ -689,8 +1322,10 @@ private void ReadScalar(Context c, SchemaField f, int depth) case 8: { uint len = U32(c); - if (len > 100_000) throw new Fail("text length"); - Take(c, 2 * (int)len); + if (2L * len > c.End - c.Pos) throw new Fail("text length"); + int p = Take(c, 2 * (int)len); + if (declaring == "ForgeTypeId" && f.Name == "m_typeId") + c.LastForgeText = System.Text.Encoding.Unicode.GetString(c.D, p, 2 * (int)len); return; } case 9: Take(c, 16); return; @@ -698,23 +1333,40 @@ private void ReadScalar(Context c, SchemaField f, int depth) { if (f.Args is not { Count: 1 } args || args[0].Fixed is not int count) throw new Fail("template field"); var item = args[0] with { Mods = (byte)(args[0].Mods & 15) }; - for (int i = 0; i < count; i++) ReadScalar(c, item, depth); + for (int i = 0; i < count; i++) ReadScalar(c, declaring, item, depth); return; } - case 14: ReadReference(c, f, depth); return; + case 14: ReadReference(c, declaring, f, depth); return; default: throw new Fail("type " + f.Type); } } - private void ReadReference(Context c, SchemaField f, int depth) + private void ReadReference(Context c, string? declaring, SchemaField f, int depth) { int lo = f.Mods & 15; if (lo == 3) { Take(c, 4); return; } if (lo is 1 or 2 or 4) { + if (declaring == "ESEntity" && f.Name == "m_blob") + { + ReadEntityBlob(c); + return; + } int handleAt = Take(c, 4); if (BitConverter.ToUInt32(c.D, handleAt) == 0) return; + int tagAt = c.Pos; Pointer(c, handleAt); + if (!c.Cutting) + { + int objectTag = BitConverter.ToUInt16(c.D, tagAt); + if (_tagMap.TryGetValue(objectTag, out int mapped) && mapped != 0 + && f.Ref is int declared && _tagMap.TryGetValue(declared, out int declaredTarget) && declaredTarget != 0 + && !IsKindOf(_target, mapped, declaredTarget)) + { + string key = (declaring ?? "?") + "." + f.Name + ": " + NameOfSource(objectTag) + " for " + NameOfTarget(declaredTarget); + PointerMismatches[key] = PointerMismatches.GetValueOrDefault(key) + 1; + } + } return; } if (f.Ref is int reference) @@ -722,16 +1374,40 @@ private void ReadReference(Context c, SchemaField f, int depth) if (reference == _sourceIdentifier) { int p = Take(c, _sourceWidth); - if (_sourceWidth == 8 && !c.Cutting) + bool narrow = _sourceWidth == 8 && _targetIdentifierWidth == 4; + if (!c.Cutting && (narrow || _droppedElements.Count > 0)) { - long id = BitConverter.ToInt64(c.D, p); - if (_ids == null && (id < int.MinValue || id > int.MaxValue)) throw new Fail("id beyond 32 bits"); - c.Edits.Add(new(p, p + 8, BitConverter.GetBytes(_ids?.Key(id) ?? (int)id))); + long id = _sourceWidth == 8 ? BitConverter.ToInt64(c.D, p) : BitConverter.ToUInt32(c.D, p); + if (narrow && _ids != null) + { + c.Edits.Add(new(p, p + _sourceWidth, BitConverter.GetBytes(_ids.Key(id)))); + return; + } + bool dangling = id > 0 && _droppedElements.Contains((ulong)id); + // The index, rather than the value, identifies a unique document setting. + bool slot = IsUniqueElementSlot(declaring, f); + if (dangling && c.LegacyHostedLoad && declaring == "ElemPick" && f.Name == "m_elemId") + throw new Fail("the analytical load or boundary condition has no host in the target"); + if (dangling && c.Droppable && c.DeepInArray && !c.InFixedArray && !slot) + { + c.DropItem = true; + c.DiagDropItem++; + c.Edits.Add(new(p, p + _sourceWidth, TargetElementId(-1))); + return; + } + if (dangling && (!c.DeepInArray || c.InFixedArray || slot)) + { + id = -1; + c.DiagMinusOne++; + } + if (narrow && (id < int.MinValue || id > uint.MaxValue)) throw new Fail("id beyond 32 bits: " + id); + if (narrow || (dangling && id == -1)) + c.Edits.Add(new(p, p + _sourceWidth, TargetElementId(id))); } return; } if (depth > 40) throw new Fail("depth"); - if (c.Cutting) { foreach (var (_, field) in Chain(_source, reference)) ReadField(c, field, depth + 1); } + if (c.Cutting) { foreach (var (d, field) in Chain(_source, reference)) ReadField(c, d.Name, field, depth + 1); } else { bool outer = c.InArray; @@ -747,8 +1423,33 @@ private void ReadReference(Context c, SchemaField f, int depth) } } + private byte[] TargetElementId(long id) => + _targetIdentifierWidth == 8 ? BitConverter.GetBytes(id) : BitConverter.GetBytes(unchecked((int)id)); + + private static bool IsUniqueElementSlot(string? declaring, SchemaField f) => + declaring == "UniqueElementsTracking" && f.Name == "m_elemIds"; + private void ReadInline(Context c, int sourceClass, int depth) => ReadFields(c, sourceClass, depth + 1); + /// + /// ESEntity.m_blob is an owned pointer whose class tag is not written: a null handle + /// is no entity and nothing follows, behind 0xFFFFFFFF stands the 16-byte GUID of the + /// entity's schema and its values. The values are read by the fields of that schema (with the + /// target widths for the classes they name) and queued like an owned object, so the value of + /// the entity survives the downgrade; the handle and the GUID are kept as they are. + /// + private void ReadEntityBlob(Context c) + { + uint handle = U32(c); + if (handle == 0) return; + if (handle != uint.MaxValue || _entityFields is null || _entityIndexOf is null) throw new Fail("entity handle"); + var guid = new Guid(c.D.AsSpan(Take(c, 16), 16)); + if (!_entityIndexOf.TryGetValue(guid, out int layout) || layout < 0 || layout >= _entityFields.Length || _entityFields[layout] is null) + throw new Fail("entity schema not stored"); + if (c.Queue.Count >= 1_000_000) throw new Fail("queue"); + c.Queue.Add((-1 - layout, false)); + } + /// A pointer whose handle is not null: the u16 class tag follows, the object is queued. private void Pointer(Context c, int handleAt) { @@ -779,9 +1480,150 @@ private void Pointer(Context c, int handleAt) [("IndependentTag", "m_taggedEntitiesCell")] = "TaggedEntitiesCell", }; + /// A target field the source release does not have takes this value instead of zero (the 2023 save writes -1). + private static readonly Dictionary<(string Class, string Field), byte[]> DefaultValues = new() + { + [("GeomTable", "m_maxSafeTag")] = BitConverter.GetBytes(-1), + [("GeomTable", "m_lastCheckedKingsUserModificationDate")] = BitConverter.GetBytes(-1), + [("NumericRevisionSettings", "m_incrementSize")] = BitConverter.GetBytes(1), + [("NumericRevisionSettings", "m_startNumber")] = BitConverter.GetBytes(1), + [("AlphanumericRevisionSettings", "m_sequence")] = DefaultRevisionSequence(), + }; + + private static byte[] DefaultRevisionSequence() + { + const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(alphabet.Length); + foreach (char letter in alphabet) + { + writer.Write(1); + writer.Write((ushort)letter); + } + return stream.ToArray(); + } + + /// A field the target release renamed, and whether the 64-bit source scalar takes the place of a 32-bit target one. + private readonly record struct RenamedField(string Name, bool Narrow, string? SubField = null); + + /// Fields renamed between releases; a name cannot be matched by the plain (declaring class, field name) rule. + private static readonly Dictionary<(string Declaring, string Field), RenamedField> RenamedFields = new() + { + // The legacy diameter is the modeled diameter; the target has no separate nominal field. + [("RebarBarType", "m_barModelDiameter")] = new("m_barDiameter", Narrow: false), + // The contour label vectors are serialized as triples of doubles in both layouts. + [("ContourLabelingElemCurveData", "m_textPosXYZ")] = new("m_textPos", Narrow: false), + [("ContourLabelingElemCurveData", "m_textDirXYZ")] = new("m_textDir", Narrow: false), + [("ContourLabelingElemCurveData", "m_textDirPerpXYZ")] = new("m_textDirPerp", Narrow: false), + [("TreeItemData", "m_identifier")] = new("m_id", Narrow: true), + [("TreeItemData", "m_parentOrOtherDataId")] = new("m_parentIdOrOtherData", Narrow: true), + [("ESSchemaStorage", "m_schemaUsageMap")] = new("m_storedSchemas", Narrow: false), + [("NumberingSchema", "m_formatSettings")] = new("m_minimumNumberOfDigits", Narrow: false, SubField: "m_minimumNumberOfDigits"), + }; + + /// The tag cells of 2027 became the tagged-entities cell of 2023 (only in the tag rewriter). + private static readonly Dictionary<(string Declaring, string Field), RenamedField> TagRenamedFields = new() + { + [("ReferenceIdsCellBase", "m_references")] = new("m_taggedEntities", Narrow: false), + [("ReferenceIdBase", "m_referenceIdKey")] = new("m_taggedId", Narrow: false, SubField: "m_hostOrLinkElemId"), + }; + + private static readonly Dictionary TagRenamedClasses = new(StringComparer.Ordinal) + { + ["TagReferencesWithLeaderCell"] = "TaggedEntitiesCell", + ["TagReferenceWithLeader"] = "TaggedElem", + }; + + /// Classes the target release renamed under the same shape (the ES schema pair). + private static readonly Dictionary RenamedClasses = new(StringComparer.Ordinal) + { + ["std::pair< GUIDvalue, SchemaUsageInfo >"] = "std::pair< GUIDvalue, ESSchema >", + }; + + /// A source class the target release has under another name and shape, read from one of its sub-objects. + private sealed record ClassProjection(string TargetClass, string SubField); + + /// The 2027 schema usage entry carries the 2023 stored schema as its m_schema sub-object. + private static readonly Dictionary ProjectedClasses = new(StringComparer.Ordinal) + { + ["SchemaUsageInfo"] = new("ESSchema", "m_schema"), + }; + + private bool TryRenamed(string declaring, string field, out RenamedField rename) => + RenamedFields.TryGetValue((declaring, field), out rename) + || (_tagMapping && TagRenamedFields.TryGetValue((declaring, field), out rename)); + + /// The built-in parameter group element ids of the group type ids a 2027 file stores. + private static readonly Dictionary ParameterGroupElementIds = new(StringComparer.Ordinal) + { + [""] = -1, + ["autodesk.parameter.group:adskModelProperties-1.0.0"] = -5000165, + ["autodesk.parameter.group:analysisResults-1.0.0"] = -5000161, + ["autodesk.parameter.group:constraints-1.0.0"] = -5000119, + ["autodesk.parameter.group:construction-1.0.0"] = -5000103, + ["autodesk.parameter.group:data-1.0.0"] = -5000175, + ["autodesk.parameter.group:dimensions-1.0.0"] = -5000101, + ["autodesk.parameter.group:electricalEngineering-1.0.0"] = -5000110, + ["autodesk.parameter.group:electricalLoads-1.0.0"] = -5000125, + ["autodesk.parameter.group:general-1.0.0"] = -5000173, + ["autodesk.parameter.group:graphics-1.0.0"] = -5000104, + ["autodesk.parameter.group:identityData-1.0.0"] = -5000100, + ["autodesk.parameter.group:ifc-1.0.0"] = -5000131, + ["autodesk.parameter.group:materials-1.0.0"] = -5000105, + ["autodesk.parameter.group:mechanical-1.0.0"] = -5000113, + ["autodesk.parameter.group:overallLegend-1.0.0"] = -5000187, + ["autodesk.parameter.group:primaryEnd-1.0.0"] = -5000213, + ["autodesk.parameter.group:rebarSystemLayers-1.0.0"] = -5000143, + ["autodesk.parameter.group:secondaryEnd-1.0.0"] = -5000214, + ["autodesk.parameter.group:segmentsFittings-1.0.0"] = -5000205, + ["autodesk.parameter.group:structural-1.0.0"] = -5000112, + ["autodesk.parameter.group:structuralAnalysis-1.0.0"] = -5000128, + ["autodesk.parameter.group:text-1.0.0"] = -5000123, + ["autodesk.parameter.group:title-1.0.0"] = -5000149, + ["autodesk.parameter.group:visibility-1.0.0"] = -5000186, + ["autodesk.revit.group:structuralSectionGeometry-1.0.0"] = -5000225, + }; + + /// A default that depends on the object being read: the 2027 ParamDef names its + /// parameter group by a group type id, the 2023 field wants the group element id; the 2027 + /// color fill entry has no lowest-range flag, the 2020 field marks the first entry of a + /// by-range container (as the native files do). + private byte[] DefaultFor(Context c, (SchemaClass Declaring, SchemaField Field) target) + { + if (target is { Declaring.Name: "EnergyAnalysisSchedule", Field.Name: "m_dayScheduleValues" } && + c.DailySchedules?.GetValueOrDefault(c.Slot) is { } schedule) + return schedule; + // The legacy inline settings need a positive increment and a nonempty sequence on upgrade. + if (target.Declaring.Name == "AllProjectRevisions" + && target.Field.Name is "m_numericRevisionSettings" or "m_alphanumericRevisionSettings" + && target.Field.Ref is int revisionSettings) + return Chain(_target, revisionSettings).SelectMany(field => Default(field)).ToArray(); + if (target.Declaring.Name == "ParamDef" && target.Field.Name == "m_groupElemId" && c.GroupElementId is int group) + return BitConverter.GetBytes(group); + if (target.Declaring.Name == "RebarSystemGStep" && target.Field is { Name: "m_totalVolume", Type: 7, Mods: 0 } + && c.RebarSystemVolume is { } volume) + return volume; + if (target.Declaring.Name == "ColorFillData" && target.Field.Name == "m_bIsLowest") + return [(byte)(c.LastByRange == 1 && c.ArrayItemIndex == 0 ? 1 : 0)]; + return Default(target); + } + /// The empty encoding of a 2022 field: zero counts, null pointers, zero scalars. + internal byte[] DefaultOwnFields(int targetClass, IReadOnlySet trueFlags) + { + var type = _target[targetClass]; + return type.Fields.Where(field => field.Stored).SelectMany(field => + trueFlags.Contains(field.Name) && field is { Type: 1, Mods: 0 } + ? new byte[] { 1 } + : Default((type, field))).ToArray(); + } + private byte[] Default((SchemaClass Declaring, SchemaField Field) target, int depth = 0) { + if ((target.Declaring.Name, target.Field.Name) is ("MEPAnalyticalModelCell", "m_baseElementId")) + return TargetElementId(-1); + if (DefaultValues.TryGetValue((target.Declaring.Name, target.Field.Name), out var value)) return value; var f = target.Field; int hi = f.Mods >> 4; if (hi is 5 or 6) return new byte[4]; @@ -811,7 +1653,7 @@ private int DefaultScalarLength(SchemaClass declaring, SchemaField f, int depth) if (lo != 0 || f.Ref is not int reference) return 4; if (ExactReferences.TryGetValue((declaring.Name, f.Name), out string? exact) && _targetByName.TryGetValue(exact, out int exactId)) reference = exactId; - if (_target.TryGetValue(reference, out var c) && c.Name == "ElementId") return 4; + if (_target.TryGetValue(reference, out var c) && c.Name == "ElementId") return _targetIdentifierWidth; int length = 0; foreach (var entry in Chain(_target, reference)) length += Default(entry, depth + 1).Length; return length; diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs index 5cebec88..8ab3766d 100644 --- a/src/RvtIO/Parsing/WideBlockWalker.cs +++ b/src/RvtIO/Parsing/WideBlockWalker.cs @@ -24,11 +24,17 @@ namespace RvtIO.Parsing; internal sealed partial class WideBlockWalker { internal readonly record struct Capture(string Key, CaptureKind Kind, long Integer, double Real, string? Text, bool AtRoot, int QueueIndex, - string DeclaringClass, string Field, int ValueOffset = -1, int QueuePosition = -1); - + string DeclaringClass, string Field, int ValueOffset = -1, int QueuePosition = -1, + int? TargetQueueIndex = null, bool IsElementId = false) + { + internal int Offset => Kind != CaptureKind.PointerClass ? ValueOffset : + TargetQueueIndex.HasValue ? ValueOffset + sizeof(uint) : -1; + } internal enum CaptureKind { Integer, Real, Text, PointerClass } + internal readonly record struct ArchiveKey(int Offset, uint Key, bool Owned); + internal sealed partial class Walk { public bool RootRead; @@ -36,6 +42,7 @@ internal sealed partial class Walk public string? Error; public int Position; public readonly List Queue = []; + internal List? ArchiveKeys; public readonly List Captures = []; public Dictionary? RootPointers; /// Per queued object (same index as ) the first position of its fields, -1 when not reached. @@ -190,9 +197,10 @@ internal bool IsA(int classId, string baseName) /// behind it can be read, inside the payload, from exactly one start position and (walk, index of the first /// object read again) accepts what was read there (RebarShape: the constraints of the edges lie behind the ESEntityCell of the shape; /// their values tell a real start from a misaligned one). - internal Walk Run(byte[] data, int offset, int size, int classId, Func? tailValid = null, bool rootOnly = false) + internal Walk Run(byte[] data, int offset, int size, int classId, Func? tailValid = null, + bool rootOnly = false, bool captureArchiveKeys = false) { - var walk = new Walk(); + var walk = new Walk { ArchiveKeys = captureArchiveKeys ? [] : null }; var ctx = new Context(data, offset + 2, offset + size, walk); int failedAt = -1; try @@ -254,7 +262,8 @@ private bool Resume(Context ctx, int failed, Func tailValid) if (first >= walk.Queue.Count) return false; int failPos = ctx.Pos; int queue = walk.Queue.Count, captures = walk.Captures.Count, records = walk.Records.Count, starts = walk.QueueStart.Count, - ends = walk.QueueEnd.Count, counts = walk.QueueCountAtStart.Count; + ends = walk.QueueEnd.Count, counts = walk.QueueCountAtStart.Count, + keys = walk.ArchiveKeys?.Count ?? 0; void Rollback() { walk.Queue.RemoveRange(queue, walk.Queue.Count - queue); @@ -263,6 +272,7 @@ void Rollback() walk.QueueStart.RemoveRange(starts, walk.QueueStart.Count - starts); walk.QueueEnd.RemoveRange(ends, walk.QueueEnd.Count - ends); walk.QueueCountAtStart.RemoveRange(counts, walk.QueueCountAtStart.Count - counts); + if (walk.ArchiveKeys is { } archiveKeys) archiveKeys.RemoveRange(keys, archiveKeys.Count - keys); } bool TryAt(int position) { @@ -542,6 +552,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri { int offset = c.Pos; uint back = U32(c); + if (back is > 2 and < uint.MaxValue) walk.ArchiveKeys?.Add(new(c.Pos - sizeof(uint), back, Owned: false)); if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, back, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, offset)); if (record != null) record[f.Name] = (long)back; return; @@ -579,8 +590,9 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri } } if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, - c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, handleAt, queuePosition)); + c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, handleAt, queuePosition, TargetQueueIndex: tag != 0 ? walk.Queue.Count - 1 : null)); if (record != null) record[f.Name] = record is EntityFields ? UnavailableEntityValue : (long)tag; + if (handle is > 2 and < uint.MaxValue) walk.ArchiveKeys?.Add(new(handleAt, handle, Owned: tag != 0)); return; } if (f.Ref is int reference) @@ -592,7 +604,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri long id = _idWidth == 8 ? BitConverter.ToInt64(c.D, p) : BitConverter.ToInt32(c.D, p); if (record is EntityFields) { record[f.Name] = ExactEntityInteger(id); return; } if (_ids != null) id = _ids.Key(id); - if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, id, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, p)); + if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, id, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, p, IsElementId: true)); if (record != null) record[f.Name] = id; return; } @@ -628,6 +640,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri return; } { + int handleAt = c.Pos; uint handle = U32(c); int tag = 0; if (handle == 0xFFFFFFFF) @@ -637,7 +650,10 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri if (walk.Queue.Count >= 1_000_000) throw new Fail("queue"); walk.Queue.Add(tag); } - if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, + c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, ValueOffset: handleAt, + TargetQueueIndex: tag != 0 ? walk.Queue.Count - 1 : null)); + if (handle is > 2 and < uint.MaxValue) walk.ArchiveKeys?.Add(new(handleAt, handle, Owned: false)); } } } diff --git a/src/RvtIO/Parsing/WideSolidQuantities.cs b/src/RvtIO/Parsing/WideSolidQuantities.cs index 7b2a3b6b..8f74b2b7 100644 --- a/src/RvtIO/Parsing/WideSolidQuantities.cs +++ b/src/RvtIO/Parsing/WideSolidQuantities.cs @@ -30,7 +30,7 @@ internal readonly record struct Solid(double Volume, double Surface, double? Lar internal WideSolidQuantities(FileSchema schema, IReadOnlyList frames, ElementIdMap? ids = null) { - _geometryLayout = new(schema.Document, GeometrySchema.Value, 8, ids); + _geometryLayout = new(schema.Document, GeometrySchema.Value, 8, ids: ids); var ambiguous = new HashSet(); foreach (var frame in frames) { diff --git a/src/RvtIO/RvtFileReader.R22Layout.cs b/src/RvtIO/RvtFileReader.R22Layout.cs index c269d37e..18a19457 100644 --- a/src/RvtIO/RvtFileReader.R22Layout.cs +++ b/src/RvtIO/RvtFileReader.R22Layout.cs @@ -22,7 +22,7 @@ private static (List Chunks, int PartitionChunkCount, List(chunks.Count); // The unit of work is a stream: each partition stream and each framed stream the rewrite reads. int streamCount = partitionStreams.Count + framedStreams.Count(frame => frame != null); diff --git a/src/RvtIO/Writing/ArchiveContents.cs b/src/RvtIO/Writing/ArchiveContents.cs new file mode 100644 index 00000000..88f0afb6 --- /dev/null +++ b/src/RvtIO/Writing/ArchiveContents.cs @@ -0,0 +1,34 @@ +using System.Buffers.Binary; + +namespace RvtIO.Writing; + +/// +/// The Contents stream holds the archive version and a tagged +/// DocumentStorageIndex. A Revit release can share an archive version with +/// its predecessor while assigning a different class tag to the index. +/// The target profile supplies the compatible header and index together. +/// +internal static class ArchiveContents +{ + internal const uint Magic = 0x05221962; + + private const int VersionOffset = 4; + + /// True when the bytes are an archive header and its version is read. + internal static bool TryReadVersion(byte[]? contents, out uint version) + { + version = 0; + if (contents is null || contents.Length < VersionOffset + 4) return false; + if (BinaryPrimitives.ReadUInt32LittleEndian(contents) != Magic) return false; + version = BinaryPrimitives.ReadUInt32LittleEndian(contents.AsSpan(VersionOffset, 4)); + return true; + } + + /// Uses a recognised profile header of the same or an older archive version. + internal static byte[]? ForTarget(byte[]? sourceContents, byte[]? profileContents) + { + if (!TryReadVersion(profileContents, out uint target)) return sourceContents; + if (!TryReadVersion(sourceContents, out uint source)) return null; + return target <= source ? profileContents : sourceContents; + } +} diff --git a/src/RvtIO/Writing/BasicFileInfoPatcher.cs b/src/RvtIO/Writing/BasicFileInfoPatcher.cs new file mode 100644 index 00000000..3cab6de2 --- /dev/null +++ b/src/RvtIO/Writing/BasicFileInfoPatcher.cs @@ -0,0 +1,94 @@ +using System.Buffers.Binary; +using System.Text; + +namespace RvtIO.Writing; + +/// +/// Patches the raw bytes of the BasicFileInfo stream when a file is downgraded: every UTF-16LE +/// occurrence of the source release year becomes the target year, the stream version dword and the build +/// string are taken from the profile file, and the length-prefixed UTF-16 build value is re-written with +/// its own length prefix (so a profile build of another length is accepted and the following values shift). +/// The key-value text block of the stream is free text and is patched in place. +/// +internal static class BasicFileInfoPatcher +{ + internal static byte[] Patch(byte[] data, int sourceRelease, int targetRelease, byte[]? profileData = null) + { + string from = sourceRelease.ToString(System.Globalization.CultureInfo.InvariantCulture); + string to = targetRelease.ToString(System.Globalization.CultureInfo.InvariantCulture); + if (from.Length != 4 || to.Length != 4) throw new ArgumentException("Releases must be four-digit years."); + byte[] patched = from == to ? [.. data] : ReplaceAll(data, Encoding.Unicode.GetBytes(from), Encoding.Unicode.GetBytes(to), required: true); + + if (profileData is not null) + { + var profileFields = Parsing.BasicFileInfoReader.Parse(profileData); + // Stream version: the first dword of the stream. + if (profileFields.TryGetValue("StreamVersion", out string? streamVersion) && int.TryParse(streamVersion, out int streamVersionValue)) + { + if (patched.Length < 4) throw new InvalidDataException("BasicFileInfo is cut inside its stream version."); + BinaryPrimitives.WriteInt32LittleEndian(patched.AsSpan(0, 4), streamVersionValue); + } + + string? sourceBuild = Parsing.BasicFileInfoReader.Parse(data).GetValueOrDefault("Build"); + if (profileFields.TryGetValue("Build", out string? profileBuild) && sourceBuild is not null && profileBuild != sourceBuild) + { + // The standalone value: [i32 length][UTF-16 chars]; the length prefix is rewritten with it. + patched = ReplaceLengthPrefixed(patched, sourceBuild, profileBuild); + // Any occurrence in the trailing key-value text block. + patched = ReplaceAll(patched, Encoding.Unicode.GetBytes(sourceBuild), Encoding.Unicode.GetBytes(profileBuild), required: false); + } + } + + return patched; + } + + /// Replaces the length-prefixed UTF-16 value with , updating + /// its 32-bit character count and moving every later byte. Returns the input when the value is absent. + private static byte[] ReplaceLengthPrefixed(byte[] data, string oldText, string newText) + { + for (int at = 0; at + 4 <= data.Length; at++) + { + int chars = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(at, 4)); + if (chars != oldText.Length) continue; + long end = at + 4L + 2L * chars; + if (end > data.Length) continue; + if (Encoding.Unicode.GetString(data, at + 4, 2 * chars) != oldText) continue; + + byte[] value = Encoding.Unicode.GetBytes(newText); + var result = new byte[data.Length - (2L * chars) + value.Length]; + Buffer.BlockCopy(data, 0, result, 0, at + 4); + BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(at, 4), newText.Length); + Buffer.BlockCopy(value, 0, result, at + 4, value.Length); + Buffer.BlockCopy(data, (int)end, result, at + 4 + value.Length, data.Length - (int)end); + return result; + } + return data; + } + + private static byte[] ReplaceAll(byte[] data, byte[] oldBytes, byte[] newBytes, bool required) + { + var patched = new byte[data.Length]; + Buffer.BlockCopy(data, 0, patched, 0, data.Length); + int replacements = 0; + for (int at = IndexOf(patched, oldBytes, 0); at >= 0; at = IndexOf(patched, oldBytes, at + newBytes.Length)) + { + newBytes.CopyTo(patched, at); + replacements++; + } + if (replacements == 0 && required) + throw new InvalidDataException($"BasicFileInfo holds no expected '{Encoding.Unicode.GetString(oldBytes)}' value to patch."); + return patched; + } + + private static int IndexOf(byte[] haystack, byte[] needle, int start) + { + for (int i = start; i + needle.Length <= haystack.Length; i++) + { + bool match = true; + for (int j = 0; j < needle.Length; j++) + if (haystack[i + j] != needle[j]) { match = false; break; } + if (match) return i; + } + return -1; + } +} diff --git a/src/RvtIO/Writing/DocumentIncrementFixup.cs b/src/RvtIO/Writing/DocumentIncrementFixup.cs new file mode 100644 index 00000000..fb6224b8 --- /dev/null +++ b/src/RvtIO/Writing/DocumentIncrementFixup.cs @@ -0,0 +1,105 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Refreshes the element totals of the current local increment in a transcoded +/// Global/DocumentIncrementTable stream. The last DocumentIncrement of +/// m_localIncrements (and its version with m_causedByIncrementNumber of -1) +/// carries the element count of the file as it will be saved; after elements are left out +/// of the downgrade that count is stale and an older Revit refuses the epoch whose +/// partition streams hold fewer elements than the table claims. +/// +internal static class DocumentIncrementFixup +{ + internal static byte[] RefreshTotals(byte[] data, SchemaDocument doc, uint totalElements) + { + int rootClass = BinaryPrimitives.ReadUInt16LittleEndian(data); + if (doc.ById.GetValueOrDefault(rootClass)?.Name != "DocumentIncrementTable") return data; + int tableId = rootClass; + int incrementId = doc.Classes.FirstOrDefault(c => c.Name == "DocumentIncrement")?.Id ?? 0; + int versionId = doc.Classes.FirstOrDefault(c => c.Name == "DocumentIncrementVersion")?.Id ?? 0; + if (incrementId == 0 || versionId == 0) return data; + + var rootFields = PayloadSpan.Fields(data, 2, data.Length, doc, tableId); + var local = rootFields.FirstOrDefault(f => f.Name == "m_localIncrements"); + if (local == default || local.End - local.Start < 4) return data; + int count = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(local.Start, 4)); + if (count is <= 0 or > 100_000) return data; + + // inline items of the array, in stored order; the last one is the current increment + var items = new List<(int Start, int End)>(); + int at = local.Start + 4; + for (int i = 0; i < count; i++) + { + var fields = PayloadSpan.Fields(data, at, local.End, doc, incrementId); + if (fields.Count == 0) return data; + int end = fields[^1].End; + if (end <= at || end > local.End) return data; + items.Add((at, end)); + at = end; + } + if (items.Count == 0) return data; + var last = items[^1]; + + var result = data; + bool changed = false; + changed |= PatchU32(ref result, data, last, doc, incrementId, "m_totalElements", totalElements); + + // the versions of the last increment: the one with no causing increment carries the same total + var lastFields = PayloadSpan.Fields(result, last.Start, last.End, doc, incrementId); + var versions = lastFields.FirstOrDefault(f => f.Name == "m_incrementVersions"); + if (versions != default && versions.End - versions.Start >= 4) + { + int versionCount = (int)BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(versions.Start, 4)); + int vat = versions.Start + 4; + for (int i = 0; i < versionCount; i++) + { + var vfields = PayloadSpan.Fields(result, vat, versions.End, doc, versionId); + if (vfields.Count == 0) break; + int vend = vfields[^1].End; + if (vend <= vat || vend > versions.End) break; + long causedBy = -2, total = -1; + int totalAt = -1; + foreach (var (fname, ffrom, fto) in vfields) + { + if (fname == "m_causedByIncrementNumber" && fto - ffrom == 4) + causedBy = BinaryPrimitives.ReadInt32LittleEndian(result.AsSpan(ffrom, 4)); + if (fname == "m_totalElements" && fto - ffrom == 4) + { + total = BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(ffrom, 4)); + totalAt = ffrom; + } + } + if (causedBy == -1 && total >= 0 && (uint)total != totalElements && totalAt >= 0) + { + var next = new byte[result.Length]; + Buffer.BlockCopy(result, 0, next, 0, result.Length); + BinaryPrimitives.WriteUInt32LittleEndian(next.AsSpan(totalAt, 4), totalElements); + result = next; + changed = true; + break; + } + vat = vend; + } + } + return changed ? result : data; + } + + private static bool PatchU32(ref byte[] result, byte[] data, + (int Start, int End) item, SchemaDocument doc, int classId, string field, uint value) + { + foreach (var (name, from, to) in PayloadSpan.Fields(data, item.Start, item.End, doc, classId)) + { + if (name != field || to - from != 4) continue; + if (BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(from, 4)) == value) return false; + var next = new byte[data.Length]; + Buffer.BlockCopy(data, 0, next, 0, data.Length); + BinaryPrimitives.WriteUInt32LittleEndian(next.AsSpan(from, 4), value); + result = next; + return true; + } + return false; + } +} diff --git a/src/RvtIO/Writing/DowngradeAnalytics.cs b/src/RvtIO/Writing/DowngradeAnalytics.cs new file mode 100644 index 00000000..8920c478 --- /dev/null +++ b/src/RvtIO/Writing/DowngradeAnalytics.cs @@ -0,0 +1,220 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text.Json; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// Copies contextual analytical data omitted from a legacy RVT into its downgrade report. +internal static class DowngradeAnalytics +{ + internal sealed record Curve(string Class, IReadOnlyDictionary Fields); + internal sealed record Element( + ulong ElementId, + string Class, + IReadOnlyList PhysicalElementIds, + IReadOnlyList AnalyticalHostIds, + IReadOnlyList Curves, + IReadOnlyList> Contours, + double[]? PointFeet, + IReadOnlyDictionary Fields, + IReadOnlyDictionary SourceRecords, + IReadOnlyDictionary? DependentInstanceRecords, + string? DecodeError); + + internal static IReadOnlyList Read( + SchemaDocument schema, byte[]? latest, int width, PartitionFraming.Tags tags, + IEnumerable<(string Path, byte[] Stored)> partitions, IReadOnlySet omitted, + IReadOnlyDictionary? entitySchemas) + { + var records = new Dictionary>(); + foreach (var (_, raw) in partitions.OrderBy(p => int.Parse(p.Path.AsSpan("Partitions/".Length), CultureInfo.InvariantCulture))) + { + bool success = PartitionFraming.Walk(raw, tags, width, record => + { + if (record.Block != 0 || !omitted.Contains(record.Owner)) return; + if (!records.TryGetValue(record.Owner, out var owner)) + records[record.Owner] = owner = new(); + owner[record.Channel] = record.Body.ToArray(); + }, out var error, out _); + if (!success) throw new InvalidDataException($"Cannot read omitted analytical records: {error}."); + } + + var associations = latest is null ? [] : ReadAssociations(schema, latest, entitySchemas); + var walker = new WideBlockWalker(schema, + (cls, field) => WideBlockWalker.AllItemsKeyPrefix + cls.Name + "." + field.Name, []); + if (entitySchemas is not null) walker.UseEntitySchemas(entitySchemas); + var analysis = new List(); + foreach (var (owner, source) in records.OrderBy(pair => pair.Key)) + { + if (!source.TryGetValue(102, out var body) || body.Length < sizeof(ushort)) continue; + ushort tag = BinaryPrimitives.ReadUInt16LittleEndian(body); + var cls = walker.Class(tag); + if (cls is null || !walker.IsA(tag, "AnalyticalElement") && !walker.IsA(tag, "LoadBCBase")) continue; + walker.StepBudget = 16L * body.Length + 65536; + var walk = walker.Run(body, 0, body.Length, tag); + var captures = walk.Exact ? walk.Captures : []; + long[] hosts = captures.Any(c => c is { DeclaringClass: "ForeignElemRef", Field: "m_id", Integer: not -1 }) + ? [] + : captures.Where(c => c is { DeclaringClass: "ElemPick", Field: "m_elemId", Integer: > 0 }) + .Select(c => c.Integer).Distinct().ToArray(); + var physical = hosts.Append(unchecked((long)owner)).Where(associations.ContainsKey) + .SelectMany(id => associations[id]).Distinct().Order().ToArray(); + var curves = Curves(captures, -1, "AnalyticalMember", "m_oCurve"); + var contours = captures.Where(c => c is + { QueueIndex: -1, DeclaringClass: "AnalyticalSurfaceBase", Field: "m_contourLoops", TargetQueueIndex: not null }) + .Select(c => Curves(captures, c.TargetQueueIndex!.Value, "CurveLoop", "m_curves")).ToArray(); + double[]? point = null; + IReadOnlyDictionary? instance = null; + if (cls.Name == "BoundaryConditions") + { + if (captures.Any(c => c is { DeclaringClass: "BoundaryConditions", Field: "m_type", Integer: 0 }) && + source.TryGetValue(101, out var header) && header.Length >= sizeof(ushort)) + point = ReadPoint(walker, header); + var instanceId = captures.FirstOrDefault(c => c is + { DeclaringClass: "BoundaryConditions", Field: "m_instanceId", Integer: > 0 }).Integer; + if (instanceId > 0 && records.TryGetValue((ulong)instanceId, out var related)) instance = related; + } + + analysis.Add(new Element(owner, cls.Name, physical, hosts, curves, contours, point, + Fields(captures.Where(c => c.DeclaringClass.StartsWith("Analytical", StringComparison.Ordinal) + || c.DeclaringClass is "Pick" or "ElemPick" or "LinearSubPick" or "ForeignElemRef" + or "BoundaryConditions" or "LoadBCBase" or "ParamValueInt" or "ParamValueDouble")), + source, instance, walk.Exact ? null : walk.Error ?? "The source record did not decode to its end.")); + + IReadOnlyList Curves(IReadOnlyList values, int parent, string declaring, string field) => + values.Where(c => c.QueueIndex == parent && c.DeclaringClass == declaring && c.Field == field && c.TargetQueueIndex != null) + .Select(c => + { + int child = c.TargetQueueIndex!.Value; + string name = walker.Class(walk.Queue[child])!.Name; + return new Curve(name, Fields(values.Where(v => v.QueueIndex == child))); + }).ToArray(); + } + var byId = analysis.ToDictionary(element => element.ElementId); + for (int i = 0; i < analysis.Count; i++) + { + var support = analysis[i]; + if (support.Class != "BoundaryConditions" || + support.Fields.GetValueOrDefault("BoundaryConditions.m_type") is not [1L] || + support.Fields.GetValueOrDefault("Pick.m_elemPicks#") is not [1L] || + support.Fields.GetValueOrDefault("ElemPick.m_tags") is not [long edgeTag] || + support.Fields.GetValueOrDefault("LinearSubPick.m_subTag") is not [-1L] || + support.AnalyticalHostIds is not [long hostId] || + !byId.TryGetValue((ulong)hostId, out var host)) continue; + + var edges = host.Contours.SelectMany(loop => loop) + .Where(curve => curve.Fields.GetValueOrDefault("GInfo.m_tag") is [long tag] && tag == edgeTag) + .Take(2).ToArray(); + if (edges.Length == 1) analysis[i] = support with { Curves = edges }; + } + return analysis; + } + + private static double[]? ReadPoint(WideBlockWalker walker, byte[] header) + { + walker.StepBudget = 16L * header.Length + 65536; + var walk = walker.Run(header, 0, header.Length, BinaryPrimitives.ReadUInt16LittleEndian(header)); + return PointFromHeader(walk); + } + + internal static double[]? PointFromHeader(WideBlockWalker.Walk walk) + { + if (!walk.Exact) return null; + var box = walk.Captures.FirstOrDefault(c => c is + { QueueIndex: -1, DeclaringClass: "ElementHeader", Field: "m_pBBox" }).TargetQueueIndex; + if (box is null) return null; + var values = walk.Captures.Where(c => c.QueueIndex == box && c.Kind == WideBlockWalker.CaptureKind.Real && + c.Key.StartsWith(WideBlockWalker.AllItemsKeyPrefix + "Outline.m_minmax@", StringComparison.Ordinal)) + .Select(c => c.Real).ToArray(); + return values.Length == 6 && values.All(double.IsFinite) && + values.AsSpan(0, 3).SequenceEqual(values.AsSpan(3, 3)) ? values[..3] : null; + } + + private static Dictionary Fields(IEnumerable captures) => + captures.Where(c => c.Kind != WideBlockWalker.CaptureKind.PointerClass && + (c.Kind != WideBlockWalker.CaptureKind.Real || double.IsFinite(c.Real))) + .GroupBy(c => + { + string field = c.Key[WideBlockWalker.AllItemsKeyPrefix.Length..]; + int item = field.IndexOf('@'); + return item < 0 ? field : field[..item]; + }) + .ToDictionary(group => group.Key, group => group.Select(c => c.Kind switch + { + WideBlockWalker.CaptureKind.Integer => (object)c.Integer, + WideBlockWalker.CaptureKind.Real => c.Real, + _ => c.Text ?? "", + }).ToArray(), StringComparer.Ordinal); + + private static Dictionary> ReadAssociations( + SchemaDocument schema, byte[] latest, IReadOnlyDictionary? entitySchemas) + { + const string repoPair = "std::pair< AString, GenericRepo >", itemPair = "std::pair< AString, AString >"; + if (latest.Length < sizeof(ushort)) return []; + var walker = new WideBlockWalker(schema, (_, _) => null, [repoPair, itemPair]) + { StepBudget = 16L * latest.Length + 65536 }; + if (entitySchemas is not null) walker.UseEntitySchemas(entitySchemas); + var walk = walker.Run(latest, 0, latest.Length, BinaryPrimitives.ReadUInt16LittleEndian(latest)); + if (!walk.RootRead || walk.Error is not null) return []; + + var repos = new Dictionary>(StringComparer.Ordinal); + var items = new List<(string, string)>(); + foreach (var record in walk.Records) + { + if (record.QueueIndex < 0 || walker.Class(walk.Queue[record.QueueIndex])?.Name != "AppInfoElementsAssociations" || + record.Values.GetValueOrDefault("first") is not string name) continue; + switch (walker.Class(record.ClassId)?.Name) + { + case itemPair when record.Values.GetValueOrDefault("second") is string value: + items.Add((name, value)); + break; + case repoPair: + if (!repos.TryAdd(name, items)) throw new InvalidDataException("Duplicate analytical association repository."); + items = new(); + break; + } + } + return Associations(repos.GetValueOrDefault("LB_Associations"), repos.GetValueOrDefault("LB_References")); + } + + internal static Dictionary> Associations( + IReadOnlyList<(string Key, string Value)>? associations, IReadOnlyList<(string Key, string Value)>? references) + { + var localIds = new HashSet(); + foreach (var (key, json) in references ?? []) + { + if (key != ".") continue; + using var record = ParseRelation(json); + if (Number(record.RootElement, "Id") is long id) localIds.Add(id); + } + var result = new Dictionary>(); + foreach (var (_, json) in associations ?? []) + { + using var record = ParseRelation(json); + var fields = record.RootElement; + if (Number(fields, "ReferenceId") is not long reference || !localIds.Contains(reference) || + !fields.TryGetProperty("IsLocalGroup", out var localGroup) || localGroup.ValueKind != JsonValueKind.False || + !fields.TryGetProperty("IsExternalGroup", out var externalGroup) || externalGroup.ValueKind != JsonValueKind.False || + Number(fields, "ExternalId") is not long analytical || analytical <= 0 || + Number(fields, "LocalId") is not long physical || physical <= 0) continue; + if (!result.TryGetValue(analytical, out var parents)) result[analytical] = parents = []; + parents.Add(physical); + } + return result; + } + + private static JsonDocument ParseRelation(string json) + { + try { return JsonDocument.Parse(json); } + catch (JsonException exception) { throw new InvalidDataException("An analytical association record contains invalid JSON.", exception); } + } + + private static long? Number(JsonElement fields, string name) + { + if (fields.ValueKind != JsonValueKind.Object || !fields.TryGetProperty(name, out var value)) return null; + if (value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out long number)) return number; + return value.ValueKind == JsonValueKind.String && + long.TryParse(value.GetString(), NumberStyles.None, CultureInfo.InvariantCulture, out number) ? number : null; + } +} diff --git a/src/RvtIO/Writing/DowngradeContentDocumentsRewriter.cs b/src/RvtIO/Writing/DowngradeContentDocumentsRewriter.cs new file mode 100644 index 00000000..9baf83fe --- /dev/null +++ b/src/RvtIO/Writing/DowngradeContentDocumentsRewriter.cs @@ -0,0 +1,103 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Transcodes Global/ContentDocuments, the block stream that holds one ADocument per loaded family: +/// block := u16 ContentMarker, u32 pointer, [u16 ContentKey], u32 owners, [16-byte key], u32 length, +/// ADocument (length bytes), u32 length. The framing tags become the profile's and each ADocument is +/// transcoded as a class object (), so the contained family +/// documents carry the target class tags and the older release can read them. +/// +internal static class DowngradeContentDocumentsRewriter +{ + internal static byte[] Rewrite( + byte[] sourceDecompressed, + PartitionFraming.Tags sourceTags, PartitionFraming.Tags targetTags, + R22Transcoder transcoder) + { + using var output = new MemoryStream(sourceDecompressed.Length); + var word = new byte[4]; + int pos = 0; + while (pos < sourceDecompressed.Length) + { + // ContentMarker + Require(pos + 2, sourceDecompressed, "content-marker"); + if (BinaryPrimitives.ReadUInt16LittleEndian(sourceDecompressed.AsSpan(pos, 2)) != sourceTags.ContentMarker) + throw new InvalidDataException("ContentDocuments has no content-marker."); + pos += 2; + // pointer + Require(pos + 4, sourceDecompressed, "content-key-pointer"); + uint pointer = BinaryPrimitives.ReadUInt32LittleEndian(sourceDecompressed.AsSpan(pos, 4)); + pos += 4; + if (pointer != 0) + { + Require(pos + 2, sourceDecompressed, "content-key-class"); + if (BinaryPrimitives.ReadUInt16LittleEndian(sourceDecompressed.AsSpan(pos, 2)) != sourceTags.ContentKey) + throw new InvalidDataException("ContentDocuments has no content-key class."); + pos += 2; + } + // owners + Require(pos + 4, sourceDecompressed, "owner-count"); + uint owners = BinaryPrimitives.ReadUInt32LittleEndian(sourceDecompressed.AsSpan(pos, 4)); + pos += 4; + if (owners == uint.MaxValue && pointer == 0) + { + // Terminal block: marker, a null pointer and the all-ones owner count close the stream. + BinaryPrimitives.WriteUInt16LittleEndian(word, targetTags.ContentMarker); + output.Write(word, 0, 2); + BinaryPrimitives.WriteUInt32LittleEndian(word, pointer); + output.Write(word); + BinaryPrimitives.WriteUInt32LittleEndian(word, owners); + output.Write(word); + break; + } + byte[]? key = null; + if (pointer != 0) + { + Require(pos + 16, sourceDecompressed, "block-key"); + key = sourceDecompressed.AsSpan(pos, 16).ToArray(); + pos += 16; + } + // length, document, length + Require(pos + 4, sourceDecompressed, "document-length"); + int length = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(sourceDecompressed.AsSpan(pos, 4))); + pos += 4; + Require(pos + (long)length + 4, sourceDecompressed, "document"); + byte[] document = sourceDecompressed.AsSpan(pos, length).ToArray(); + pos += length; + if (BinaryPrimitives.ReadUInt32LittleEndian(sourceDecompressed.AsSpan(pos, 4)) != (uint)length) + throw new InvalidDataException("ContentDocuments block length does not close."); + pos += 4; + + byte[] rewritten = transcoder.PayloadWithTail(document, 0, document.Length, out string? failure) + ?? throw new DowngradeRefusedException("contentdocument-transcode-failed", + $"The family document in Global/ContentDocuments cannot be rewritten for the target release: {failure}"); + + BinaryPrimitives.WriteUInt16LittleEndian(word, targetTags.ContentMarker); + output.Write(word[..2]); + BinaryPrimitives.WriteUInt32LittleEndian(word, pointer); + output.Write(word); + if (pointer != 0) + { + BinaryPrimitives.WriteUInt16LittleEndian(word, targetTags.ContentKey); + output.Write(word[..2]); + } + BinaryPrimitives.WriteUInt32LittleEndian(word, owners); + output.Write(word); + if (key is not null) output.Write(key); + BinaryPrimitives.WriteUInt32LittleEndian(word, (uint)rewritten.Length); + output.Write(word); + output.Write(rewritten); + BinaryPrimitives.WriteUInt32LittleEndian(word, (uint)rewritten.Length); + output.Write(word); + } + return output.ToArray(); + } + + private static void Require(long end, byte[] data, string what) + { + if (end > data.Length) throw new InvalidDataException($"ContentDocuments is cut inside its {what}."); + } +} diff --git a/src/RvtIO/Writing/DowngradeElemTableRewriter.cs b/src/RvtIO/Writing/DowngradeElemTableRewriter.cs new file mode 100644 index 00000000..b91b03bd --- /dev/null +++ b/src/RvtIO/Writing/DowngradeElemTableRewriter.cs @@ -0,0 +1,69 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Transcodes a decoded Global/ElemTable stream between element-id widths +/// (40-byte rows with 8-byte ids to 28-byte rows with 4-byte ids, Revit 2024+ to +/// 2020-2023). The stream is the ElemTable class object (the row array followed +/// by the graveyard array, the identifier-source pointer and the flags) and the bytes +/// after it; the object is rewritten by by class and field +/// name, so the row layout, the source identifier and every pointer tag follow the +/// target class table. Rows of owners the partition rewrite left out (their class has +/// no target counterpart) are dropped and the row count follows. +/// +internal static class DowngradeElemTableRewriter +{ + internal static byte[] Rewrite( + byte[] sourceDecompressed, SchemaDocument sourceDoc, SchemaDocument targetDoc, + IReadOnlySet? droppedOwners = null) + { + var source = new FormatsSchema(sourceDoc); + var target = new FormatsSchema(targetDoc); + int? sourceWidth = ElemTableLayout.IdWidth(source); + int? targetWidth = ElemTableLayout.IdWidth(target); + if (sourceWidth is null || targetWidth is null) + throw new InvalidDataException("The element-id width of the source or the target schema is not known."); + + byte[]? rewritten = new R22Transcoder(sourceDoc, targetDoc, sourceWidth.Value) + .PayloadWithTail(sourceDecompressed, 0, sourceDecompressed.Length, out string? failure); + if (rewritten is null) + { + if (failure?.Contains("beyond 32 bits", StringComparison.Ordinal) == true) + throw new DowngradeRefusedException("id-beyond-32-bits", + "An element-table id does not fit in 32 bits and cannot be downgraded to a 4-byte release."); + throw new InvalidDataException($"The element table cannot be rewritten: {failure}."); + } + byte[] transcoded = rewritten; + + var rows = ElemTableLayout.TryParse(transcoded, target) + ?? throw new InvalidDataException("The transcoded element table does not decode by the target schema."); + int targetRowLength = ElemTableLayout.RowLength(target) + ?? throw new InvalidDataException("The target element-table row length is not known."); + + if (droppedOwners is null || droppedOwners.Count == 0) return transcoded; + + var keep = rows.Select(r => !droppedOwners.Contains(unchecked((ulong)r.Id))).ToArray(); + int kept = keep.Count(k => k); + if (kept == rows.Count) return transcoded; + + int restAt = ElemTableLayout.HeaderLength + rows.Count * targetRowLength; + var output = new byte[ElemTableLayout.HeaderLength + kept * targetRowLength + (transcoded.Length - restAt)]; + transcoded.AsSpan(0, 2).CopyTo(output); + BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(2, 4), (uint)kept); + int at = ElemTableLayout.HeaderLength; + for (int i = 0; i < rows.Count; i++) + { + if (!keep[i]) continue; + transcoded.AsSpan(ElemTableLayout.HeaderLength + i * targetRowLength, targetRowLength).CopyTo(output.AsSpan(at)); + at += targetRowLength; + } + transcoded.AsSpan(restAt).CopyTo(output.AsSpan(at)); + + var check = ElemTableLayout.TryParse(output, target); + if (check is null || check.Count != kept) + throw new InvalidDataException("The transcoded element table does not decode by the target schema."); + return output; + } +} diff --git a/src/RvtIO/Writing/DowngradeGlobalRewriter.cs b/src/RvtIO/Writing/DowngradeGlobalRewriter.cs new file mode 100644 index 00000000..fc11c040 --- /dev/null +++ b/src/RvtIO/Writing/DowngradeGlobalRewriter.cs @@ -0,0 +1,65 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Transcodes the single-object Global streams of a cross-width downgrade +/// (Latest, PartitionTable, DocumentIncrementTable) with the same +/// class-and-field-name machinery as the partition records +/// (R22Transcoder.Payload(byte[], int, int, out string?)): the root class tag and every nested class tag +/// are renumbered to the target schema, fields are cut or inserted, and 64-bit scalars +/// are narrowed. A stream whose object cannot be rewritten is refused, because the older +/// release would read the newer class tags. +/// +internal static class DowngradeGlobalRewriter +{ + /// The rewritten object, or an exception naming the stream and the reason. Bytes after the object + /// (Global/Latest holds the class object followed by opaque data) are copied unchanged. A stream whose first + /// 16 bits are not a class of the source schema is not a class object and is returned unchanged. + internal static byte[] Rewrite(string streamName, byte[] sourceDecompressed, SchemaDocument sourceDoc, R22Transcoder transcoder) + { + if (!IsClassObject(sourceDecompressed, sourceDoc)) return sourceDecompressed; + byte[]? rewritten = transcoder.PayloadWithTail(sourceDecompressed, 0, sourceDecompressed.Length, out string? failure); + if (rewritten is null) + throw new DowngradeRefusedException("global-transcode-failed", + $"The class object in Global/{streamName} cannot be rewritten for the target release: {failure}"); + return rewritten; + } + + /// + /// A tag-only patch of a block stream whose layout is not a single class object: + /// the 16-bit class tag at is renumbered when the class + /// exists in both tables, and the stream is otherwise unchanged. + /// + internal static byte[] PatchTag(byte[] data, int tagOffset, SchemaDocument sourceDoc, SchemaDocument targetDoc, string streamName) + { + if (!IsClassObject(data, sourceDoc, tagOffset)) return data; + if (tagOffset < 0 || tagOffset + 2 > data.Length) + throw new DowngradeRefusedException("global-transcode-failed", + $"Global/{streamName} is cut inside its class tag."); + ushort sourceTag = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(tagOffset, 2)); + var sourceByName = sourceDoc.Classes.ToDictionary(c => c.Id, c => c.Name); + var targetById = targetDoc.Classes.ToDictionary(c => c.Id, c => c.Id); + var targetByName = targetDoc.Classes.GroupBy(c => c.Name).ToDictionary(g => g.Key, g => g.First().Id); + if (!sourceByName.TryGetValue(sourceTag, out string? className) || !targetByName.TryGetValue(className, out int targetTag)) + throw new DowngradeRefusedException("global-transcode-failed", + $"Global/{streamName} opens with class {sourceTag}, which the profile class table does not define."); + if (targetTag is < 0 or > ushort.MaxValue) + throw new DowngradeRefusedException("global-transcode-failed", + $"The profile class id {targetTag} of {className} does not fit in 16 bits."); + var patched = new byte[data.Length]; + Buffer.BlockCopy(data, 0, patched, 0, data.Length); + BinaryPrimitives.WriteUInt16LittleEndian(patched.AsSpan(tagOffset, 2), (ushort)targetTag); + _ = targetById; + return patched; + } + + /// True when the 16 bits at name a class of the source schema. + private static bool IsClassObject(byte[] data, SchemaDocument sourceDoc, int tagOffset = 0) + { + if (tagOffset < 0 || tagOffset + 2 > data.Length) return false; + ushort tag = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(tagOffset, 2)); + return sourceDoc.Classes.Any(c => c.Id == tag); + } +} diff --git a/src/RvtIO/Writing/DowngradeHistoryRewriter.cs b/src/RvtIO/Writing/DowngradeHistoryRewriter.cs new file mode 100644 index 00000000..c8ed2e48 --- /dev/null +++ b/src/RvtIO/Writing/DowngradeHistoryRewriter.cs @@ -0,0 +1,32 @@ +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Transcodes a decoded Global/History episode GUID table across releases by +/// remapping its opening class tag from the source DocumentHistory class id to +/// the target's. The rest of the stream (fixed header, GUID slots, extra list, GUID +/// records) is layout-independent and preserved verbatim, so element UniqueIds derived +/// from episode GUIDs and ElemTable histories stay identical to the source file's. +/// +internal static class DowngradeHistoryRewriter +{ + internal static byte[] Rewrite(byte[] sourceDecompressed, SchemaDocument sourceDoc, SchemaDocument targetDoc) + { + int? sourceId = new FormatsSchema(sourceDoc).IdOf("DocumentHistory") + ?? throw new InvalidDataException("The source class table lacks the DocumentHistory class."); + int? targetId = new FormatsSchema(targetDoc).IdOf("DocumentHistory") + ?? throw new InvalidDataException("The profile class table lacks the DocumentHistory class."); + if (sourceId is < 0 or > ushort.MaxValue || targetId is < 0 or > ushort.MaxValue) + throw new InvalidDataException("The DocumentHistory class id does not fit in 16 bits."); + if (sourceDecompressed.Length < 2) + throw new InvalidDataException("The episode table is cut inside its class tag."); + if (System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(sourceDecompressed) != (ushort)sourceId) + throw new InvalidDataException("The episode table does not open with the source DocumentHistory class tag."); + + var output = new byte[sourceDecompressed.Length]; + Buffer.BlockCopy(sourceDecompressed, 0, output, 0, sourceDecompressed.Length); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(output, (ushort)targetId); + return output; + } +} diff --git a/src/RvtIO/Writing/DowngradePartitionRewriter.cs b/src/RvtIO/Writing/DowngradePartitionRewriter.cs new file mode 100644 index 00000000..8ea6c2d7 --- /dev/null +++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs @@ -0,0 +1,607 @@ +using System.Buffers.Binary; +using ICSharpCode.SharpZipLib.Checksum; +using ICSharpCode.SharpZipLib.Zip.Compression; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Rewrites a stored Partitions/<n> stream from a newer release into an older +/// release layout for cross-width downgrades (8-byte element ids to 4-byte, Revit 2024+ +/// to 2020-2023): framing marker tags source to target, owner ids narrowed with range +/// check, record bodies transcoded by class and field name via +/// (tags renumbered, fields cut/inserted, 64-bit scalars narrowed), Adler-32 recomputed, +/// block keys/pointer/owner counts and chain flags/opaque preserved, signatures emptied. +/// Owners whose data class the target table does not define are left out of their block +/// (Revit refuses an unknown class tag), and their ids are reported back so that the +/// element table can drop their rows too. +/// +internal static class DowngradePartitionRewriter +{ + internal const int MaxSegmentBodyBytes = 131_072; + + internal sealed record Addition(ulong Owner, byte[][] Payloads); + internal sealed record ProjectEdits( + IReadOnlyList Additions, IReadOnlyDictionary<(ulong Owner, int Channel), byte[]> Replacements); + + internal static byte[] Rewrite( + byte[] rawStored, + PartitionFraming.Tags sourceTags, int sourceWidth, + PartitionFraming.Tags targetTags, int targetWidth, + R22Transcoder transcoder, + IReadOnlySet? knownDropped, + Func? tagFixer, + out IReadOnlySet droppedOwners, + ProjectEdits? projectEdits = null) + { + if (sourceWidth is not (4 or 8) || targetWidth is not (4 or 8)) + throw new ArgumentOutOfRangeException(nameof(targetWidth), "Element identifier byte width must be 4 or 8."); + + var pageCheck = PageCodec.Verify(rawStored); + if (pageCheck.Status is PageCheckStatus.BadPage or PageCheckStatus.BadTail) + throw new InvalidDataException($"Partition stream fails page parity at page {pageCheck.Page} ({pageCheck.Status})."); + + // Validate source framing first (names failure reasons for diagnostics). + var probe = new List(); + if (!PartitionFraming.Walk(rawStored, sourceTags, sourceWidth, r => probe.Add(r), out string? probeFailure, out _)) + throw new InvalidDataException($"Partition stream framing is invalid: {probeFailure}."); + + byte[] body = PartitionFraming.RemoveTails(rawStored) + ?? throw new InvalidDataException("Partition stream page tails could not be removed."); + + if (body.Length < 8 || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(0, 4)) != 9) + throw new InvalidDataException("Partition stream has no format-9 header."); + + using var rebuilt = new MemoryStream(body.Length); + rebuilt.Write(body, 0, 8); + + ulong sourceTerminator = sourceWidth == 8 ? ulong.MaxValue : uint.MaxValue; + ulong targetTerminator = targetWidth == 8 ? ulong.MaxValue : uint.MaxValue; + var allDropped = knownDropped is HashSet known ? known : knownDropped is null ? [] : new HashSet(knownDropped); + + int pos = 8; + var addedChannels = new HashSet(); + var replacedRecords = new HashSet<(ulong, int)>(); + for (; ; ) + { + int blockStart = pos; + if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); + ushort marker = BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)); + if (marker != sourceTags.ContentMarker) throw new InvalidDataException("Partition stream has no content-marker."); + pos += 2; + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); + uint pointer = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); + pos += 4; + if (pointer != 0) + { + if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); + if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.ContentKey) + throw new InvalidDataException("Partition stream has no content-key class."); + pos += 2; + } + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); + uint expectedOwners = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); + pos += 4; + byte[]? key = null; + if (pointer != 0) + { + if (pos + 16 > body.Length) throw new InvalidDataException("Partition stream ends inside a block key."); + key = body.AsSpan(pos, 16).ToArray(); + pos += 16; + } + + if (expectedOwners == uint.MaxValue) + { + // Terminal: rewrite marker with target tag, copy pointer/owner count verbatim. + var term = new byte[2 + 4 + 4]; + BinaryPrimitives.WriteUInt16LittleEndian(term.AsSpan(0, 2), targetTags.ContentMarker); + BinaryPrimitives.WriteUInt32LittleEndian(term.AsSpan(2, 4), pointer); + BinaryPrimitives.WriteUInt32LittleEndian(term.AsSpan(6, 4), expectedOwners); + rebuilt.Write(term); + break; + } + + var chains = ReadBlockChains(body, ref pos, sourceTags); + int emptySegmentStart = pos - 18; + + // Signature: skip source, write empty target signature. + if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); + if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.SignatureMarker) + throw new InvalidDataException("Partition stream has no signature-marker."); + pos += 2; + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); + uint sigBytes = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); + pos += 4 + checked((int)sigBytes); + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); + uint sigChars = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); + pos += 4 + checked((int)(2L * sigChars)); + + // Owners whose data class the target table does not define, or whose payload cannot be + // rewritten in the target grammar, are left out of the block: Revit refuses an unknown + // class tag and a record body left as 0xFFFE ("can't find PersistentClass"), so the + // element's header, data and geometry records all go and the block owner count follows. + // A payload that only fails once the element universe is set (dangling-id rule) + // is also left out: the known set was built before the universe existed. + var freshDropped = DetectDroppedOwners(chains, transcoder, sourceTerminator, sourceWidth); + HashSet dropOwners; + if (knownDropped is null) dropOwners = freshDropped; + else { dropOwners = new HashSet(knownDropped); dropOwners.UnionWith(freshDropped); } + uint writeOwners = expectedOwners; + if (dropOwners.Count > 0) + { + allDropped.UnionWith(dropOwners); + var kept = new HashSet(); + foreach (var chain in chains) + if (chain.Channel == 101) + foreach (var (owner, _) in ReadRecords(chain.Inflated, 101, sourceWidth)) + if (owner != sourceTerminator && !dropOwners.Contains(owner)) kept.Add(owner); + writeOwners = (uint)kept.Count; + } + if (key is null && projectEdits is not null) + writeOwners = checked(writeOwners + (uint)projectEdits.Additions.Count); + + // Write block header with target tags, the surviving owner count, pointer and key unchanged. + { + var header = new MemoryStream(); + var tag = new byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(tag, targetTags.ContentMarker); + header.Write(tag); + var ptr = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(ptr, pointer); + header.Write(ptr); + if (pointer != 0) + { + BinaryPrimitives.WriteUInt16LittleEndian(tag, targetTags.ContentKey); + header.Write(tag); + } + var own = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(own, writeOwners); + header.Write(own); + if (key != null) header.Write(key); + rebuilt.Write(header.ToArray()); + } + + foreach (var chain in chains) + WriteConvertedChain(rebuilt, chain, targetTags, sourceWidth, targetWidth, transcoder, sourceTerminator, targetTerminator, + dropOwners, tagFixer, key is null ? projectEdits : null, addedChannels, replacedRecords); + + // Empty segment closing the block. + { + var empty = new byte[18]; + BinaryPrimitives.WriteUInt16LittleEndian(empty.AsSpan(0, 2), targetTags.SegmentMarker); + rebuilt.Write(empty); + } + // Empty signature (bytes no longer signed by Revit). + { + var sig = new byte[2 + 4 + 4]; + BinaryPrimitives.WriteUInt16LittleEndian(sig.AsSpan(0, 2), targetTags.SignatureMarker); + rebuilt.Write(sig); + } + + _ = emptySegmentStart; + _ = blockStart; + } + + if (projectEdits is not null && (addedChannels.Count != 3 || replacedRecords.Count != projectEdits.Replacements.Count)) + throw new InvalidDataException("The partition is missing a channel or record required by the project edits."); + byte[] encoded = PageCodec.EncodePadded(rebuilt.ToArray()); + + // Verify with target framing, widths and checksums. + var pageVerify = PageCodec.Verify(encoded); + if (pageVerify.Status != PageCheckStatus.Valid) + throw new InvalidDataException($"Rewritten partition stream failed page parity ({pageVerify.Status} at page {pageVerify.Page})."); + var adler = new Adler32(); + bool ok = PartitionFraming.Walk(encoded, targetTags, targetWidth, record => + { + if (record.Owner == targetTerminator && record.Body.Length == 0) return; + if (record.Channel == 101) return; + adler.Reset(); + adler.Update(record.Body.ToArray()); + if ((uint)adler.Value != record.Extra) + throw new InvalidDataException($"Rewritten record (block {record.Block}, channel {record.Channel}, owner {record.Owner}) has a mismatched Adler-32 checksum."); + }, out string? failure, out _); + if (!ok) throw new InvalidDataException($"Rewritten partition stream failed framing verification: {failure}."); + droppedOwners = allDropped; + return encoded; + } + + /// The owners whose records cannot be carried into the target: their class has no + /// counterpart, or a data or geometry payload cannot be rewritten in the target grammar. + private static HashSet DetectDroppedOwners(List chains, R22Transcoder transcoder, ulong sourceTerminator, int sourceWidth) + { + var dropOwners = new HashSet(); + foreach (var chain in chains) + { + if (chain.Channel is not (102 or 103)) continue; + foreach (var (owner, recordBody) in ReadRecords(chain.Inflated, chain.Channel, sourceWidth)) + { + if (owner == sourceTerminator || recordBody.Length < 2 || dropOwners.Contains(owner)) continue; + int classTag = BinaryPrimitives.ReadUInt16LittleEndian(recordBody.Span); + if (!transcoder.HasSourceClass(classTag)) + { + // A data record must name a class of the file; an unknown geometry tag is + // opaque bytes of a synthetic fixture and keeps the old copy-through. + if (chain.Channel == 102) dropOwners.Add(owner); + continue; + } + if (!transcoder.CanWriteRecord(classTag, isElement: chain.Channel == 102)) + { + dropOwners.Add(owner); + continue; + } + var rewritten = recordBody.ToArray(); + if (transcoder.Payload(rewritten, 0, rewritten.Length, out _) is null) dropOwners.Add(owner); + } + } + return dropOwners; + } + + /// The owners a stored stream holds and the ones a rewrite would leave out. + internal sealed record PartitionState(HashSet Owners, HashSet Dropped); + + /// + /// The element ids a stored stream holds (the channel-101 owners) and the ids the rewrite would + /// leave out, without rewriting it. The writer uses the two sets to know which references in the + /// written file would point at an element that is gone. + /// + internal static PartitionState Inspect( + byte[] rawStored, PartitionFraming.Tags sourceTags, int sourceWidth, R22Transcoder transcoder) + { + byte[] body = PartitionFraming.RemoveTails(rawStored) + ?? throw new InvalidDataException("Partition stream page tails could not be removed."); + if (body.Length < 8 || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(0, 4)) != 9) + throw new InvalidDataException("Partition stream has no format-9 header."); + + ulong sourceTerminator = sourceWidth == 8 ? ulong.MaxValue : uint.MaxValue; + var owners = new HashSet(); + var dropped = new HashSet(); + int pos = 8; + for (; ; ) + { + if (pos + 10 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); + if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.ContentMarker) + throw new InvalidDataException("Partition stream has no content-marker."); + pos += 2; + uint pointer = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); + pos += 4; + if (pointer != 0) + { + if (pos + 2 > body.Length || BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.ContentKey) + throw new InvalidDataException("Partition stream has no content-key class."); + pos += 2; + } + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); + uint ownerCount = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); + pos += 4; + if (pointer != 0) + { + if (pos + 16 > body.Length) throw new InvalidDataException("Partition stream ends inside a block key."); + pos += 16; + } + if (ownerCount == uint.MaxValue) break; + + var chains = ReadBlockChains(body, ref pos, sourceTags); + foreach (var chain in chains) + { + if (chain.Channel is not (101 or 102 or 103)) continue; + foreach (var (owner, _) in ReadRecords(chain.Inflated, chain.Channel, sourceWidth)) + if (owner != sourceTerminator) owners.Add(owner); + } + dropped.UnionWith(DetectDroppedOwners(chains, transcoder, sourceTerminator, sourceWidth)); + + // Signature: skip it as the rewrite does. + if (pos + 2 > body.Length || BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.SignatureMarker) + throw new InvalidDataException("Partition stream has no signature-marker."); + pos += 2; + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); + pos += 4 + checked((int)BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4))); + if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); + pos += 4 + checked((int)(2L * BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)))); + } + return new PartitionState(owners, dropped); + } + + private sealed record ChainSpan(int Channel, uint UpperFlags, uint Opaque, byte[] Inflated); + + /// The records of an inflated chain: owner and body, in stored order. + private static IEnumerable<(ulong Owner, ReadOnlyMemory Body)> ReadRecords(byte[] inflated, int channel, int width) + { + int at = 0; + while (at + width + 4 <= inflated.Length) + { + ulong owner = width == 8 + ? BinaryPrimitives.ReadUInt64LittleEndian(inflated.AsSpan(at, 8)) + : BinaryPrimitives.ReadUInt32LittleEndian(inflated.AsSpan(at, 4)); + at += width + (channel != 101 ? 4 : 0); + if (at + 4 > inflated.Length) yield break; + int size = BinaryPrimitives.ReadUInt32LittleEndian(inflated.AsSpan(at, 4)) is var raw && raw <= int.MaxValue ? (int)raw : -1; + if (size < 0) yield break; + at += 4; + if (at + (long)size + 4 > inflated.Length) yield break; + yield return (owner, new ReadOnlyMemory(inflated, at, size)); + at += size + 4; + } + } + + private static List ReadBlockChains(byte[] body, ref int pos, PartitionFraming.Tags tags) + { + var chains = new List(); + using var inflated = new MemoryStream(); + int channel = 0; + uint firstFlags = 0, firstOpaque = 0; + bool inChain = false; + + while (true) + { + if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment."); + if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != tags.SegmentMarker) + throw new InvalidDataException("Partition stream has no segment-marker."); + pos += 2; + if (pos + 4 + 4 + 4 + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment header."); + uint flags = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; + pos += 4; // count (verified on rewrite, not needed for parsing) + uint size = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; + pos += 4; // unc + if (size == 0) + { + if ((flags & 3) != 0) throw new InvalidDataException("Partition stream empty segment is chained."); + break; + } + if (pos + 8 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment header."); + uint index = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; + uint opaque = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; + int payloadLength = checked((int)size - 8); + if (pos + payloadLength + 6 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment."); + InflateGzipMember(body, pos, payloadLength, inflated, resetFirst: (flags & 3) is 0 or 2); + pos += payloadLength + 6; // SegmentCheckback + size (validated on rewrite) + + uint mode = flags & 3; + if (mode is 0 or 2) + { + if (inChain) throw new InvalidDataException("Partition stream chain starts inside a chain."); + inChain = true; + firstFlags = flags & ~3u; + firstOpaque = opaque; + channel = (int)index; + } + else if (!inChain) throw new InvalidDataException("Partition stream chain continuation starts no chain."); + if (mode is 0 or 1) + { + inChain = false; + chains.Add(new ChainSpan(channel, firstFlags, firstOpaque, inflated.ToArray())); + } + } + if (inChain) throw new InvalidDataException("Partition stream ends inside a chain."); + return chains; + } + + private static void InflateGzipMember(byte[] source, int offset, int length, MemoryStream destination, bool resetFirst) + { + if (resetFirst) + { + destination.SetLength(0); + destination.Position = 0; + } + var inflater = new Inflater(noHeader: true); + inflater.SetInput(source, offset + 10, length - 18); + byte[] buffer = new byte[32_768]; + while (!inflater.IsFinished) + { + int count = inflater.Inflate(buffer); + if (count == 0 && !inflater.IsFinished) + throw new InvalidDataException("Unexpected end of deflate member while reading partition segment."); + destination.Write(buffer, 0, count); + } + } + + private static void WriteConvertedChain( + MemoryStream output, + ChainSpan chain, + PartitionFraming.Tags targetTags, + int sourceWidth, + int targetWidth, + R22Transcoder transcoder, + ulong sourceTerminator, + ulong targetTerminator, + IReadOnlySet dropOwners, + Func? tagFixer, + ProjectEdits? projectEdits, + HashSet addedChannels, + HashSet<(ulong, int)> replacedRecords) + { + var adler = new Adler32(); + using var batch = new MemoryStream(); + uint batchCount = 0; + long batchBodyBytes = 0; + + void FlushBatch() + { + if (batchCount == 0) return; + WriteSegment(output, targetTags, chain.UpperFlags, batchCount, checked((uint)batchBodyBytes), (uint)chain.Channel, chain.Opaque, batch.ToArray()); + batch.SetLength(0); + batch.Position = 0; + batchCount = 0; + batchBodyBytes = 0; + } + + byte[] inf = chain.Inflated; + int at = 0; + while (at < inf.Length) + { + // The owner is written in the width of the whole stream, source and target alike. + if (at + sourceWidth > inf.Length) throw new InvalidDataException("Partition record ends inside its owner."); + ulong owner = sourceWidth == 8 + ? BinaryPrimitives.ReadUInt64LittleEndian(inf.AsSpan(at, 8)) + : BinaryPrimitives.ReadUInt32LittleEndian(inf.AsSpan(at, 4)); + at += sourceWidth; + uint extra = 0; + bool hasExtra = chain.Channel != 101; + if (hasExtra) + { + if (at + 4 > inf.Length) throw new InvalidDataException("Partition record ends inside its checksum."); + extra = BinaryPrimitives.ReadUInt32LittleEndian(inf.AsSpan(at, 4)); + at += 4; + } + if (at + 4 > inf.Length) throw new InvalidDataException("Partition record ends inside its length."); + int bodySize = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(inf.AsSpan(at, 4))); + int bodyAt = at + 4; + if (bodyAt + bodySize + 4 > inf.Length) throw new InvalidDataException("Partition record ends inside its body."); + byte[] body = new byte[bodySize]; + Buffer.BlockCopy(inf, bodyAt, body, 0, bodySize); + at = bodyAt + bodySize + 4; + _ = extra; + + bool isTerminator = owner == sourceTerminator && bodySize == 0; + ulong newOwner; + byte[] newBody; + uint newExtra; + if (isTerminator) + { + if (projectEdits is not null && addedChannels.Add(chain.Channel)) + { + foreach (var addition in projectEdits.Additions) + { + byte[] payload = addition.Payloads[chain.Channel - 101]; + adler.Reset(); + adler.Update(payload); + WriteRecord(addition.Owner, payload, hasExtra ? (uint)adler.Value : 0); + } + } + newOwner = targetTerminator; + newBody = []; + newExtra = 0; + } + else if (dropOwners.Contains(owner)) + { + // The element's class has no counterpart in the target table: leave the record out. + continue; + } + else + { + if (targetWidth == 4 && owner > uint.MaxValue) + throw new DowngradeRefusedException("id-beyond-32-bits", + $"Element id {owner} does not fit in 32 bits and cannot be downgraded to a 4-byte release."); + newOwner = owner; + byte[]? converted; + if (projectEdits?.Replacements.TryGetValue((owner, chain.Channel), out var edit) == true) + { + converted = edit; + replacedRecords.Add((owner, chain.Channel)); + } + else + { + converted = bodySize >= 2 ? transcoder.Payload(body, 0, bodySize, out _) : null; + if (converted is not null && tagFixer is not null && tagFixer(body, converted) is { } fixedBody) + converted = fixedBody; + } + if (converted == null) + { + // A body that cannot be rewritten on its own (an unknown nested structure) keeps its bytes + // behind an unknown class tag; the element stays framed and is left out by readers. + converted = new byte[bodySize >= 2 ? bodySize : 2]; + if (bodySize >= 2) Buffer.BlockCopy(body, 2, converted, 2, bodySize - 2); + BinaryPrimitives.WriteUInt16LittleEndian(converted.AsSpan(0, 2), R22Transcoder.UnknownTag); + } + newBody = converted; + if (chain.Channel == 101) newExtra = 0; + else + { + adler.Reset(); + adler.Update(newBody); + newExtra = (uint)adler.Value; + } + } + + WriteRecord(newOwner, newBody, newExtra); + } + FlushBatch(); + + void WriteRecord(ulong owner, byte[] recordBody, uint checksum) + { + bool hasExtra = chain.Channel != 101; + byte[] header = new byte[targetWidth + (hasExtra ? 4 : 0) + 4]; + int hp = 0; + if (targetWidth == 8) { BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(hp, 8), owner); hp += 8; } + else { BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(hp, 4), (uint)owner); hp += 4; } + if (hasExtra) { BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(hp, 4), checksum); hp += 4; } + BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(hp, 4), (uint)recordBody.Length); + byte[] footer = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(footer, (uint)recordBody.Length); + + int itemLength = header.Length + recordBody.Length + 4; + if (recordBody.Length > MaxSegmentBodyBytes) + { + FlushBatch(); + WriteSplitRecord(output, targetTags, chain, header, recordBody); + } + else + { + if (batchCount > 0 && batch.Length + itemLength > MaxSegmentBodyBytes) FlushBatch(); + batch.Write(header); + batch.Write(recordBody); + batch.Write(footer); + batchCount++; + batchBodyBytes += recordBody.Length; + } + } + } + + private static int DetectSourceWidth(ChainSpan chain, ulong sourceTerminator) => sourceTerminator == ulong.MaxValue ? 8 : 4; + + private static void WriteSplitRecord( + MemoryStream output, + PartitionFraming.Tags tags, + ChainSpan chain, + ReadOnlySpan recordHeader, + ReadOnlySpan recordBody) + { + byte[] firstSlice = new byte[recordHeader.Length + MaxSegmentBodyBytes]; + recordHeader.CopyTo(firstSlice); + recordBody[..MaxSegmentBodyBytes].CopyTo(firstSlice.AsSpan(recordHeader.Length)); + WriteSegment(output, tags, chain.UpperFlags | 2u, 1u, MaxSegmentBodyBytes, (uint)chain.Channel, chain.Opaque, firstSlice); + + int offset = MaxSegmentBodyBytes; + while (recordBody.Length - offset > MaxSegmentBodyBytes) + { + byte[] middleSlice = recordBody.Slice(offset, MaxSegmentBodyBytes).ToArray(); + WriteSegment(output, tags, chain.UpperFlags | 3u, 0u, MaxSegmentBodyBytes, (uint)chain.Channel, chain.Opaque, middleSlice); + offset += MaxSegmentBodyBytes; + } + + int remaining = recordBody.Length - offset; + byte[] lastSlice = new byte[remaining + 4]; + recordBody[offset..].CopyTo(lastSlice); + BinaryPrimitives.WriteUInt32LittleEndian(lastSlice.AsSpan(remaining, 4), (uint)recordBody.Length); + WriteSegment(output, tags, chain.UpperFlags | 1u, 0u, (uint)remaining, (uint)chain.Channel, chain.Opaque, lastSlice); + } + + private static void WriteSegment( + MemoryStream output, + PartitionFraming.Tags tags, + uint flags, + uint recordCount, + uint uncompressedBodyLength, + uint channel, + uint opaque, + ReadOnlySpan inflatedBytes) + { + byte[] gzPayload = GzipMember.Write(inflatedBytes); + uint segmentSize = checked((uint)(gzPayload.Length + 8)); + + Span header = stackalloc byte[26]; + BinaryPrimitives.WriteUInt16LittleEndian(header[0..], tags.SegmentMarker); + BinaryPrimitives.WriteUInt32LittleEndian(header[2..], flags); + BinaryPrimitives.WriteUInt32LittleEndian(header[6..], recordCount); + BinaryPrimitives.WriteUInt32LittleEndian(header[10..], segmentSize); + BinaryPrimitives.WriteUInt32LittleEndian(header[14..], uncompressedBodyLength); + BinaryPrimitives.WriteUInt32LittleEndian(header[18..], channel); + BinaryPrimitives.WriteUInt32LittleEndian(header[22..], opaque); + output.Write(header); + output.Write(gzPayload); + + Span footer = stackalloc byte[6]; + BinaryPrimitives.WriteUInt16LittleEndian(footer[0..], tags.SegmentCheckback); + BinaryPrimitives.WriteUInt32LittleEndian(footer[2..], segmentSize); + output.Write(footer); + } +} diff --git a/src/RvtIO/Writing/DowngradePlanner.cs b/src/RvtIO/Writing/DowngradePlanner.cs index ab433079..fddbfae5 100644 --- a/src/RvtIO/Writing/DowngradePlanner.cs +++ b/src/RvtIO/Writing/DowngradePlanner.cs @@ -65,7 +65,7 @@ internal sealed class DowngradePlan internal static class DowngradePlanner { /// The newest release tested as a source. - internal const int NewestSourceRelease = 2026; + internal const int NewestSourceRelease = 2027; /// The plan from two parsed schemas. maps class names to the elements the source file holds /// (null: not counted). @@ -145,7 +145,8 @@ private static Dictionary ByName(SchemaDocument document, s } /// The outcome of planning two files. - internal sealed record Result(DowngradePlan Plan, int SourceRelease, int TargetRelease, int SourceStreamBytes, int EditedStreamBytes, string? CountFailure); + internal sealed record Result(DowngradePlan Plan, int SourceRelease, int TargetRelease, int SourceStreamBytes, + int EditedStreamBytes, string? CountFailure, int? OmittedContextualMembers); /// Reads the source file and the profile file and plans the edit. Nothing is written. /// A file is missing, not a compound file, cut or damaged, or its Formats/Latest cannot be read. @@ -174,10 +175,16 @@ internal static Result Plan(string sourcePath, string profilePath, GuidRule rule var plan = Compute(sourceSchema, profileSchema, rule); string? countFailure = null; + int? omittedContextualMembers = null; if (countElements) { var counts = ElementCensus.CountByClass(sourceRoot, sourceSchema, out countFailure); - if (counts is not null) plan = Compute(sourceSchema, profileSchema, rule, counts); + if (counts is not null) + { + plan = Compute(sourceSchema, profileSchema, rule, counts); + if (targetRelease == 2022) + omittedContextualMembers = counts.GetValueOrDefault(R22Transcoder.ContextualAnalyticalMember); + } } byte[] edited; @@ -186,7 +193,7 @@ internal static Result Plan(string sourcePath, string profilePath, GuidRule rule { throw new DowngradeRefusedException("edit-not-applicable", $"The planned edit does not apply to the class table of the source: {exception.Message}"); } - return new Result(plan, sourceRelease, targetRelease, sourceStream.Length, edited.Length, countFailure); + return new Result(plan, sourceRelease, targetRelease, sourceStream.Length, edited.Length, countFailure, omittedContextualMembers); } private static byte[] ReadStream(RootStorage root, string role, string path) diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs new file mode 100644 index 00000000..84c1cfd9 --- /dev/null +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -0,0 +1,566 @@ +using OpenMcdf; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Writes a downgraded copy using the target class table. Tagged objects in the +/// partition and global streams are rewritten against that table even when the +/// element identifier width is unchanged, so the copy can be downgraded again. +/// +internal static class DowngradeWriter +{ + internal sealed record DowngradeWriteResult( + string OutputPath, + int SourceRelease, + int TargetRelease, + int EditedClasses, + int ReplacedStreams, + IReadOnlyDictionary? OmittedProjectElements, + IReadOnlyList OmittedRecordOwners, + IReadOnlyList? OmittedAnalyticalData, + IReadOnlyList? RestoredAnalyticalMembers, + IReadOnlyList? RestoredPointSupports, + IReadOnlyList? RestoredAnalyticalPanels, + IReadOnlyList? RestoredAnalyticalOpenings, + IReadOnlyList? RestoredLineSupports, + IReadOnlyList? RestoredAttachedNodes, + int? ArchivedEnergyAnalysisRecords, + IReadOnlyList? RestoredLineLoads); + + internal static DowngradeWriteResult Write( + string sourcePath, string profilePath, string outputPath, GuidRule rule, bool includeOmittedAnalytics = false, + bool restoreLegacyAnalytics = false, bool allowLoss = false) + { + var planResult = DowngradePlanner.Plan(sourcePath, profilePath, rule); + if (restoreLegacyAnalytics && (planResult.SourceRelease < 2023 || planResult.TargetRelease != 2022)) + throw new DowngradeRefusedException("unsupported-analytical-restore", + "Legacy analytical restoration requires a Revit 2023 or newer source and its historical Revit 2022 project as the target profile."); + int sourceWidth = SchemaRelease.IdWidth(planResult.SourceRelease)!.Value; + int targetWidth = SchemaRelease.IdWidth(planResult.TargetRelease)!.Value; + return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth, includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss); + } + + private static DowngradeWriteResult Transcode( + string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult, + int sourceWidth, int targetWidth, bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss) + { + var plan = planResult.Plan; + SchemaDocument sourceDoc, profileDoc; + byte[] sourceSchemaBytes, profileStored, profileSchemaBytes; + byte[] sourceBfi; + byte[]? sourceContents; + bool isProject; + List<(string Path, byte[] Stored)> sourcePartitions = []; + List<(string Name, byte[] Stored)> sourceGlobalStreams = []; + byte[]? sourceElemTableStored = null; + byte[]? sourceHistoryStored = null; + byte[] sourceBfiProfile; + byte[]? profileContents, profileLatest = null; + using (var sourceRoot = RootStorage.OpenRead(sourcePath)) + { + sourceSchemaBytes = PagedGzipStream.Read(sourceRoot, "Formats", "Latest") + ?? throw new RvtInputException("truncated-or-damaged", $"The class table (Formats/Latest) of the source file '{Path.GetFileName(sourcePath)}' is missing or cannot be read."); + sourceDoc = TfSchemaReader.TryParse(sourceSchemaBytes) + ?? throw new RvtInputException("truncated-or-damaged", $"The class table (Formats/Latest) of the source file '{Path.GetFileName(sourcePath)}' does not follow the expected layout."); + sourceBfi = ReadRawStream(sourceRoot, "BasicFileInfo"); + sourceContents = TryReadOptionalStream(sourceRoot, "Contents"); + isProject = sourceRoot.EnumerateEntries().Any(e => e.Type == EntryType.Stream && e.Name == "ProjectInformation"); + if (!sourceRoot.TryOpenStorage("Partitions", out var partStorage)) + throw new DowngradeRefusedException("missing-partitions", "The source file has no Partitions storage to transcode."); + foreach (var entry in partStorage.EnumerateEntries()) + { + if (entry.Type != EntryType.Stream) continue; + if (!int.TryParse(entry.Name, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out _)) continue; + using var s = partStorage.OpenStream(entry.Name); + var raw = new byte[checked((int)s.Length)]; + s.ReadExactly(raw); + sourcePartitions.Add(("Partitions/" + entry.Name, raw)); + } + if (sourceRoot.TryOpenStorage("Global", out var globalStorage)) + { + foreach (var entry in globalStorage.EnumerateEntries()) + { + if (entry.Type != EntryType.Stream) continue; + using var s = globalStorage.OpenStream(entry.Name); + var raw = new byte[checked((int)s.Length)]; + s.ReadExactly(raw); + sourceGlobalStreams.Add((entry.Name, raw)); + if (string.Equals(entry.Name, "ElemTable", StringComparison.OrdinalIgnoreCase)) sourceElemTableStored = raw; + if (string.Equals(entry.Name, "History", StringComparison.OrdinalIgnoreCase)) sourceHistoryStored = raw; + } + } + } + using (var profileRoot = RootStorage.OpenRead(profilePath)) + { + profileSchemaBytes = PagedGzipStream.Read(profileRoot, "Formats", "Latest") + ?? throw new RvtInputException("truncated-or-damaged", $"The class table (Formats/Latest) of the profile file '{Path.GetFileName(profilePath)}' is missing or cannot be read."); + profileDoc = TfSchemaReader.TryParse(profileSchemaBytes) + ?? throw new RvtInputException("truncated-or-damaged", $"The class table (Formats/Latest) of the profile file '{Path.GetFileName(profilePath)}' does not follow the expected layout."); + var profileFormats = profileRoot.OpenStorage("Formats"); + using var ps = profileFormats.OpenStream("Latest"); + profileStored = new byte[checked((int)ps.Length)]; + ps.ReadExactly(profileStored); + sourceBfiProfile = ReadRawStream(profileRoot, "BasicFileInfo"); + profileContents = TryReadOptionalStream(profileRoot, "Contents"); + if (isProject && planResult.TargetRelease == 2021) + profileLatest = PagedGzipStream.Read(profileRoot, "Global", "Latest"); + } + if (sourcePartitions.Count == 0) + throw new DowngradeRefusedException("missing-partitions", "The source file has no numbered partition streams to transcode."); + + var sourceTags = PartitionFraming.TagsOf(new FormatsSchema(sourceDoc)) + ?? throw new DowngradeRefusedException("missing-framing-markers", "The source class table lacks the partition framing marker classes."); + var targetTags = PartitionFraming.TagsOf(new FormatsSchema(profileDoc)) + ?? throw new DowngradeRefusedException("missing-framing-markers", "The profile class table lacks the partition framing marker classes."); + + // Extensible storage: the entity values are read by the schema each entity names; the + // schemas live in the document's Latest. + var latestStored = sourceGlobalStreams + .FirstOrDefault(e => string.Equals(e.Name, "Latest", StringComparison.OrdinalIgnoreCase)).Stored; + var latest = latestStored is null ? null : PagedGzipStream.Decompress(latestStored); + var entitySchemas = latestStored is null ? null : EntitySchemaReader.Read(latest ?? [], sourceDoc); + var transcoder = new R22Transcoder(sourceDoc, profileDoc, sourceWidth, entitySchemas, downgradeRelease: planResult.TargetRelease); + var tagFixer = TagCellRewriter.Create(sourceDoc, profileDoc, entitySchemas, sourceWidth); + + // Clear references at the same transition as the omission, while their old owners are known. + var knownOwners = new HashSet(); + var knownDropped = new HashSet(); + foreach (var (_, raw) in sourcePartitions) + { + var state = DowngradePartitionRewriter.Inspect(raw, sourceTags, sourceWidth, transcoder); + knownOwners.UnionWith(state.Owners); + knownDropped.UnionWith(state.Dropped); + } + transcoder.SetDroppedElementIds(knownDropped); + // Orphaned rows: an element whose owning element is left out cannot stay, or the + // older release reports a missing owner and fails the open. Close over the source + // element table together with payload failures, or the rewrite keeps the orphan. + List<(long Id, long Owning)>? sourceElemRows = null; + if (sourceElemTableStored is not null) + { + try + { + var sourceElemDecompressed = PagedGzipStream.Decompress(sourceElemTableStored); + var sourceElemParsed = sourceElemDecompressed is null ? null + : ElemTableLayout.TryParse(sourceElemDecompressed, new FormatsSchema(sourceDoc)); + if (sourceElemParsed is not null) + sourceElemRows = sourceElemParsed.Select(r => (r.Id, r.OwningId)).ToList(); + } + catch (Exception ex) when (ex is InvalidDataException or ArgumentException or OverflowException) + { + sourceElemRows = null; + } + } + // A payload that only fails once the universe is set (dangling-id rule) leaves + // its owner out as well: close the dropped set before writing, or the rewrite + // keeps an unknown 0xFFFE tag the older release refuses with verifyClass. + for (int iter = 0; iter < 10; iter++) + { + var added = new HashSet(); + foreach (var (_, raw) in sourcePartitions) + { + var restate = DowngradePartitionRewriter.Inspect(raw, sourceTags, sourceWidth, transcoder); + knownOwners.UnionWith(restate.Owners); + foreach (var id in restate.Dropped) + if (!knownDropped.Contains(id)) added.Add(id); + } + if (sourceElemRows is not null) + { + foreach (var (id, owning) in sourceElemRows) + { + if (id <= 0 || owning <= 0) continue; + ulong uid = unchecked((ulong)id), uown = unchecked((ulong)owning); + if (!knownDropped.Contains(uid) && knownDropped.Contains(uown)) added.Add(uid); + } + } + if (added.Count == 0) break; + knownDropped.UnionWith(added); + transcoder.SetDroppedElementIds(knownDropped); + } + + byte[] patchedBfi; + try { patchedBfi = BasicFileInfoPatcher.Patch(sourceBfi, planResult.SourceRelease, planResult.TargetRelease, sourceBfiProfile); } + catch (InvalidDataException exception) + { + throw new DowngradeRefusedException("missing-metadata", exception.Message); + } + + if (plan.Rule == GuidRule.Minimal) + { + var targetGuids = profileDoc.Classes.ToDictionary(c => c.Name, c => c.Guids, StringComparer.Ordinal); + var edits = new List(); + foreach (var c in sourceDoc.Classes) + { + if (!targetGuids.TryGetValue(c.Name, out var targetList)) continue; + var intersection = c.Guids.Where(g => targetList.Contains(g, StringComparer.OrdinalIgnoreCase)).ToArray(); + if (!intersection.SequenceEqual(targetList, StringComparer.OrdinalIgnoreCase)) + edits.Add(new(c.Name, Guids: intersection)); + } + if (edits.Count > 0) + { + profileSchemaBytes = SchemaStreamEditor.Apply(profileSchemaBytes, edits); + profileStored = PagedStreamCodec.Reencode(profileStored, profileSchemaBytes); + } + } + + var replacements = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Formats/Latest"] = profileStored, + ["BasicFileInfo"] = patchedBfi, + }; + if (ArchiveContents.ForTarget(sourceContents, profileContents) is { } contents && contents != sourceContents) + replacements["Contents"] = contents; + // Single-object Global streams: transcode the class object by class and field name. + // A stream that does not open with a class of the source schema holds no class object + // (a synthetic file, or opaque data) and is copied unchanged. + foreach (string name in new[] { "Latest", "PartitionTable", "DocumentIncrementTable" }) + { + var entry = sourceGlobalStreams.FirstOrDefault(e => string.Equals(e.Name, name, StringComparison.OrdinalIgnoreCase)); + if (entry.Stored is null) continue; + byte[] decompressed = PagedGzipStream.Decompress(entry.Stored) + ?? throw new RvtInputException("truncated-or-damaged", $"Global/{name} of the source file '{Path.GetFileName(sourcePath)}' cannot be decompressed."); + byte[] rewritten; + try + { + rewritten = DowngradeGlobalRewriter.Rewrite(name, decompressed, sourceDoc, transcoder); + if (name == "Latest" && profileLatest is not null) + rewritten = LegacySchemaCatalogs.Rewrite(rewritten, profileLatest, profileDoc); + } + catch (DowngradeRefusedException) { throw; } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("global-transcode-failed", + $"Global/{name} cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + if (string.Equals(name, "DocumentIncrementTable", StringComparison.OrdinalIgnoreCase)) + rewritten = DocumentIncrementFixup.RefreshTotals(rewritten, profileDoc, (uint)knownOwners.Count(id => !knownDropped.Contains(id))); + if (ReferenceEquals(rewritten, decompressed)) continue; + replacements["Global/" + entry.Name] = PagedStreamCodec.Encode(PagedStreamCodec.ReadPrefix(entry.Stored), rewritten); + } + // Content documents: a block stream whose blocks open with the ContentMarker class tag. + { + var entry = sourceGlobalStreams.FirstOrDefault(e => string.Equals(e.Name, "ContentDocuments", StringComparison.OrdinalIgnoreCase)); + if (entry.Stored is not null) + { + byte[] decompressed = PagedGzipStream.Decompress(entry.Stored) + ?? throw new RvtInputException("truncated-or-damaged", $"Global/ContentDocuments of the source file '{Path.GetFileName(sourcePath)}' cannot be decompressed."); + byte[] rewritten; + try { rewritten = DowngradeContentDocumentsRewriter.Rewrite(decompressed, sourceTags, targetTags, transcoder); } + catch (DowngradeRefusedException) { throw; } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("contentdocument-transcode-failed", + $"Global/ContentDocuments cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + replacements["Global/" + entry.Name] = PagedStreamCodec.Encode(PagedStreamCodec.ReadPrefix(entry.Stored), rewritten); + } + } + var droppedOwners = knownDropped; + if (sourceElemTableStored is not null) + { + byte[] sourceElemTableDecompressed = PagedGzipStream.Decompress(sourceElemTableStored) + ?? throw new RvtInputException("truncated-or-damaged", $"The element table (Global/ElemTable) of the source file '{Path.GetFileName(sourcePath)}' cannot be decompressed."); + byte[] targetElemTableDecompressed; + try + { + targetElemTableDecompressed = DowngradeElemTableRewriter.Rewrite(sourceElemTableDecompressed, sourceDoc, profileDoc, droppedOwners); + } + catch (DowngradeRefusedException) { throw; } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("elemtable-transcode-failed", + $"The element table cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + byte[] prefix; + try { prefix = PagedStreamCodec.ReadPrefix(sourceElemTableStored); } + catch (InvalidDataException exception) + { + throw new DowngradeRefusedException("elemtable-transcode-failed", + $"The element table cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + replacements["Global/ElemTable"] = PagedStreamCodec.Encode(prefix, targetElemTableDecompressed); + } + if (sourceHistoryStored is not null) + { + byte[] sourceHistoryDecompressed = PagedGzipStream.Decompress(sourceHistoryStored) + ?? throw new RvtInputException("truncated-or-damaged", $"The episode table (Global/History) of the source file '{Path.GetFileName(sourcePath)}' cannot be decompressed."); + byte[] targetHistoryDecompressed; + try + { + targetHistoryDecompressed = DowngradeHistoryRewriter.Rewrite(sourceHistoryDecompressed, sourceDoc, profileDoc); + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("history-transcode-failed", + $"The episode table cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + byte[] historyPrefix; + try { historyPrefix = PagedStreamCodec.ReadPrefix(sourceHistoryStored); } + catch (InvalidDataException exception) + { + throw new DowngradeRefusedException("history-transcode-failed", + $"The episode table cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + replacements["Global/History"] = PagedStreamCodec.Encode(historyPrefix, targetHistoryDecompressed); + } + + LegacyElectricalStyle.Addition? style = null; + LegacyProjectDefaults.Addition? defaults = null; + LegacyUnitFormats.Edit? unitFormats = null; + if (planResult.TargetRelease == 2020 && isProject) + { + try + { + var partitionPaths = sourcePartitions.Select(p => p.Path).ToHashSet(StringComparer.OrdinalIgnoreCase); + style = LegacyElectricalStyle.Restore(profileDoc, replacements, partitionPaths); + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("legacy-style-transcode-failed", exception.Message); + } + } + if (planResult.TargetRelease == 2020 && isProject) + { + try + { + unitFormats = LegacyUnitFormats.Prepare(profilePath, sourceDoc, profileDoc, sourceTags, sourceWidth, + targetTags, sourcePartitions, transcoder, knownDropped); + + } + catch (Exception exception) when (exception is IOException or InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("legacy-unit-formats-transcode-failed", exception.Message); + } + if (sourceElemRows is not null) + { + try + { + EnergyAnalysisTracking.Restore(sourceDoc, profileDoc, sourceTags, sourceWidth, sourcePartitions, + sourceElemRows, knownDropped, replacements); + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("legacy-energy-tracking-failed", exception.Message); + } + } + } + IReadOnlyList analysis = []; + if ((includeOmittedAnalytics || restoreLegacyAnalytics) && planResult.SourceRelease >= 2023 && planResult.TargetRelease <= 2022 && + droppedOwners.Count > 0) + analysis = DowngradeAnalytics.Read(sourceDoc, latest, sourceWidth, sourceTags, sourcePartitions, droppedOwners, entitySchemas); + + LegacyAnalyticalMembers.Result? restored = null; + if (restoreLegacyAnalytics) + { + if (!isProject || sourcePartitions.Count != 1 || sourceElemTableStored is null || sourceHistoryStored is null) + throw new DowngradeRefusedException("unsupported-analytical-restore", + "Legacy analytical restoration requires a project with one numbered partition and its element history."); + try + { + restored = LegacyAnalyticalMembers.Restore(profilePath, sourceDoc, profileDoc, + PagedGzipStream.Decompress(sourceElemTableStored) ?? throw new InvalidDataException("Missing source element table."), + PagedGzipStream.Decompress(sourceHistoryStored) ?? throw new InvalidDataException("Missing source episode history."), + latest, sourcePartitions[0].Stored, sourceWidth, droppedOwners, analysis, transcoder, replacements); + } + catch (Exception exception) when (exception is IOException or InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("legacy-analytical-restore-failed", exception.Message); + } + } + + EnergyAnalysisArchive.Attachment? energyArchive = null; + int? archivedEnergyAnalysisRecords = null; + if (isProject && planResult.SourceRelease >= 2023 && planResult.TargetRelease <= 2023 + && entitySchemas?.ContainsKey(EnergyAnalysisArchive.SchemaId) != true) + { + try + { + if (EnergyAnalysisArchive.Capture(sourceDoc, sourceSchemaBytes, planResult.SourceRelease, sourceWidth, + sourceTags, sourcePartitions) is { } content) + { + energyArchive = EnergyAnalysisArchive.Prepare(content, sourceDoc, profileDoc, sourceTags, sourceWidth, + sourcePartitions, transcoder, replacements, knownDropped); + if (energyArchive is not null) archivedEnergyAnalysisRecords = content.Records.Length; + } + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("energy-archive-transcode-failed", exception.Message); + } + } + + + if (planResult.TargetRelease <= 2025 && isProject) + { + try + { + var partitionPaths = sourcePartitions.Select(p => p.Path).ToHashSet(StringComparer.OrdinalIgnoreCase); + defaults = LegacyProjectDefaults.Restore(profilePath, profileDoc, replacements, partitionPaths, + planResult.TargetRelease); + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("legacy-project-defaults-transcode-failed", exception.Message); + } + } + + Dictionary<(ulong, int), byte[]>? wireReferences = null; + // A single partition supplies the current wire catalogue and element bodies. + if (isProject && sourcePartitions.Count == 1) + { + try + { + wireReferences = LegacyWireReferences.Prepare(sourceDoc, profileDoc, sourceTags, sourceWidth, + sourcePartitions[0].Stored, transcoder, knownDropped); + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("legacy-wire-references-transcode-failed", exception.Message); + } + } + + int plannedDrops = knownDropped.Count; + foreach (var (path, raw) in sourcePartitions) + { + byte[] rewritten; + try + { + var edits = restored?.Edits; + if (isProject && planResult.TargetRelease == 2023 && sourcePartitions.Count == 1) + { + var picks = LegacyAnalyticalMembers.RestoreOpeningEdgePicks(sourceDoc, profileDoc, sourceTags, + sourceWidth, raw, entitySchemas, knownDropped, transcoder); + if (picks.Count != 0) edits = new([], picks); + } + var added = defaults?.PartitionPath == path ? defaults.Elements.AsEnumerable() : []; + if (style?.PartitionPath == path) + added = added.Prepend(new(style.Owner, style.Payloads)); + if (style?.PartitionPath == path || defaults?.PartitionPath == path) + edits = new((edits?.Additions ?? []).Concat(added).ToArray(), + edits?.Replacements ?? new Dictionary<(ulong, int), byte[]>()); + if (energyArchive?.Partition == path || unitFormats?.Partition == path || wireReferences is { Count: > 0 }) + { + var bodies = edits?.Replacements.ToDictionary() ?? []; + if (energyArchive?.Partition == path) bodies.Add((energyArchive.Owner, 102), energyArchive.Body); + if (unitFormats?.Partition == path) bodies.Add((unitFormats.Owner, 102), unitFormats.Body); + if (wireReferences is not null) + foreach (var (key, body) in wireReferences) bodies.Add(key, body); + edits = new(edits?.Additions ?? [], bodies); + } + + rewritten = DowngradePartitionRewriter.Rewrite(raw, sourceTags, sourceWidth, targetTags, targetWidth, + transcoder, knownDropped, tagFixer, out _, edits); + } + catch (DowngradeRefusedException) { throw; } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("partition-transcode-failed", + $"Partition stream '{path}' cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + replacements[path] = rewritten; + } + if (knownDropped.Count != plannedDrops) + throw new DowngradeRefusedException("partition-transcode-failed", + "Additional omitted elements were detected after writing the element table."); + Dictionary? omittedProjectElements = null; + if (droppedOwners.Count != 0 || planResult.TargetRelease <= 2022) + { + using var sourceRoot = RootStorage.OpenRead(sourcePath); + omittedProjectElements = ElementCensus.CountByClass(sourceRoot, sourceDoc, out _, droppedOwners); + } + var omittedOwners = new HashSet(droppedOwners); + if (restored is not null) + { + var restoredIds = restored.Members.Concat(restored.Panels).Select(m => m.SourceElementId) + .Concat(restored.Openings.Select(o => o.SourceElementId)) + .Concat(restored.PointSupports).Concat(restored.LineSupports).Concat(restored.LineLoads).ToHashSet(); + analysis = analysis.Where(e => !restoredIds.Contains((long)e.ElementId)).ToArray(); + omittedOwners.ExceptWith(restoredIds.Concat(restored.Instances).Where(id => id > 0).Select(id => (ulong)id)); + Subtract("AnalyticalMember", restored.Members.Length); + Subtract("AnalyticalPanel", restored.Panels.Length); + Subtract("AnalyticalOpening", restored.Openings.Length); + Subtract("BoundaryConditions", restored.PointSupports.Length + restored.LineSupports.Length); + Subtract("FamilyInstance", restored.Instances.Length); + Subtract("LineLoad", restored.LineLoads.Length); + } + + if (!allowLoss && omittedOwners.Count != 0) + throw new DowngradeRefusedException("loss-not-allowed", + $"The conversion omits records for {omittedOwners.Count} owners. Use --allow-loss with --report to write the file and review the omissions."); + + var rewrite = ContainerRewriter.Rewrite(sourcePath, outputPath, replacements, + temporary => Verify(temporary, planResult.TargetRelease, profileSchemaBytes)); + + return new DowngradeWriteResult(outputPath, planResult.SourceRelease, planResult.TargetRelease, plan.Edits.Count, + rewrite.Replaced, omittedProjectElements, omittedOwners.Order().ToArray(), includeOmittedAnalytics && analysis.Count != 0 ? analysis : null, + restoreLegacyAnalytics ? restored?.Members ?? [] : null, restoreLegacyAnalytics ? restored?.PointSupports ?? [] : null, + restoreLegacyAnalytics ? restored?.Panels ?? [] : null, restoreLegacyAnalytics ? restored?.Openings ?? [] : null, + restoreLegacyAnalytics ? restored?.LineSupports ?? [] : null, + restoreLegacyAnalytics ? restored?.AttachedNodes ?? [] : null, archivedEnergyAnalysisRecords, + restoreLegacyAnalytics ? restored?.LineLoads ?? [] : null); + + void Subtract(string name, int count) + { + if (count == 0 || omittedProjectElements is null) return; + int remaining = omittedProjectElements.GetValueOrDefault(name) - count; + if (remaining > 0) omittedProjectElements[name] = remaining; + else omittedProjectElements.Remove(name); + } + } + + private static void Verify(string outputPath, int release, byte[] expectedSchema) + { + using var root = RootStorage.OpenRead(outputPath); + byte[] outputBytes = PagedGzipStream.Read(root, "Formats", "Latest") + ?? throw new InvalidDataException("The written file has no readable class table."); + var outputSchema = TfSchemaReader.TryParse(outputBytes) + ?? throw new InvalidDataException("The written class table does not parse."); + var layoutSchema = new FormatsSchema(outputSchema); + int? savedRelease = SchemaRelease.Saved(BasicFileInfoReader.Read(root).GetValueOrDefault("RevitVersion")); + if (savedRelease != release || SchemaRelease.FromSchema(layoutSchema) != release + || !outputBytes.AsSpan().SequenceEqual(expectedSchema)) + throw new InvalidDataException("The written file does not carry the expected target release and class table."); + + if (!root.TryOpenStorage("Global", out var global)) return; + foreach (var entry in global.EnumerateEntries()) + { + if (entry.Type != EntryType.Stream) continue; + if (string.Equals(entry.Name, "ElemTable", StringComparison.OrdinalIgnoreCase)) + { + byte[] elemTable = PagedGzipStream.Read(root, "Global", entry.Name) + ?? throw new InvalidDataException("The written element table cannot be decompressed."); + if (ElemTableLayout.TryParse(elemTable, layoutSchema) is null) + throw new InvalidDataException("The written element table does not decode by its class schema."); + } + else if (string.Equals(entry.Name, "History", StringComparison.OrdinalIgnoreCase)) + { + byte[] history = PagedGzipStream.Read(root, "Global", entry.Name) + ?? throw new InvalidDataException("The written episode table cannot be decompressed."); + int? historyTag = layoutSchema.IdOf("DocumentHistory"); + if (historyTag is not null && (history.Length < 2 + || System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(history) != historyTag.Value)) + throw new InvalidDataException("The written episode table does not open with the DocumentHistory class tag of its class schema."); + } + } + } + + private static byte[] ReadRawStream(RootStorage root, string streamName) + { + using var stream = root.OpenStream(streamName); + var bytes = new byte[checked((int)stream.Length)]; + stream.ReadExactly(bytes); + return bytes; + } + + private static byte[]? TryReadOptionalStream(RootStorage root, string streamName) + { + if (!root.TryOpenStream(streamName, out var stream)) return null; + using (stream) + { + var bytes = new byte[checked((int)stream.Length)]; + stream.ReadExactly(bytes); + return bytes; + } + } +} diff --git a/src/RvtIO/Writing/ElementCensus.cs b/src/RvtIO/Writing/ElementCensus.cs index 3d4d0417..cde9d76f 100644 --- a/src/RvtIO/Writing/ElementCensus.cs +++ b/src/RvtIO/Writing/ElementCensus.cs @@ -15,7 +15,7 @@ internal static class ElementCensus /// Elements per class name, or null with the reason in when the count cannot be made from this /// file's layout: the class table has no framing classes, the id width is not known, or there is no partition stream. /// A partition stream is present but its framing does not hold or a record has no class tag. - internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, out string? failure) + internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, out string? failure, IReadOnlySet? onlyOwners = null) { failure = null; var schema = new FormatsSchema(document); @@ -39,7 +39,8 @@ internal static class ElementCensus bool bad = false; bool ok = PartitionFraming.Walk(raw, tags, width, record => { - if (record.Block != 0 || record.Channel != 102 || record.Owner == terminator) return; + if (record.Block != 0 || record.Channel != 102 || record.Owner == terminator + || onlyOwners is not null && !onlyOwners.Contains(record.Owner)) return; if (record.Body.Length < 2) { bad = true; return; } tagOfOwner[record.Owner] = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); }, out string? walkFailure, out _); diff --git a/src/RvtIO/Writing/EnergyAnalysisArchive.cs b/src/RvtIO/Writing/EnergyAnalysisArchive.cs new file mode 100644 index 00000000..8990c663 --- /dev/null +++ b/src/RvtIO/Writing/EnergyAnalysisArchive.cs @@ -0,0 +1,182 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using System.Text.Json; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// Preserves source energy-analysis values in an Extensible Storage entity on ProjectInfo. +internal static class EnergyAnalysisArchive +{ + internal static readonly Guid SchemaId = new("9af961bd-f232-4587-ae0f-4b783cb724c1"); + internal const string SchemaName = "RvtIOEnergyAnalysisArchive"; + internal const string FieldName = "Payload"; + + internal sealed record Record(ulong ElementId, string Class, byte[] Payload); + internal sealed record Content(int Version, int Release, int IdentifierWidth, byte[] ClassTable, Record[] Records) + { + internal string Encode() + { + using var bytes = new MemoryStream(); + using (var gzip = new GZipStream(bytes, CompressionLevel.Optimal, leaveOpen: true)) + JsonSerializer.Serialize(gzip, this); + return Convert.ToBase64String(bytes.ToArray()); + } + } + + internal sealed record Attachment(string Partition, ulong Owner, byte[] Body); + + internal static Content? Capture(SchemaDocument doc, byte[] classTable, int release, int width, + PartitionFraming.Tags tags, IReadOnlyList<(string Path, byte[] Stored)> partitions) + { + // shortcut: one partition supplies an unambiguous current record for each element. + if (partitions.Count != 1) return null; + + var classes = doc.Classes.Where(c => c.Name is "EnergyAnalysisConstruction" or "EnergyAnalysisLayer" + or "EnergyAnalysisMaterial" or "EnergyAnalysisWindowType").ToDictionary(c => c.Id, c => c.Name); + if (classes.Count == 0) return null; + + var records = new Dictionary(); + foreach (var (_, stored) in partitions) + Walk(stored, tags, width, r => + { + if (r.Block == 0 && r.Channel == 102 && r.Body.Length >= 2 + && classes.TryGetValue(BinaryPrimitives.ReadUInt16LittleEndian(r.Body.Span), out string? name)) + records[r.Owner] = new Record(r.Owner, name, r.Body.ToArray()); + }); + return records.Count == 0 ? null : new Content(1, release, width, classTable, [.. records.Values.OrderBy(r => r.ElementId)]); + } + + internal static Attachment? Prepare(Content content, SchemaDocument sourceDoc, SchemaDocument targetDoc, + PartitionFraming.Tags sourceTags, int sourceWidth, IReadOnlyList<(string Path, byte[] Stored)> partitions, + R22Transcoder transcoder, Dictionary replacements, IReadOnlySet? dropped = null) + { + const string latestPath = "Global/Latest"; + if (!replacements.TryGetValue(latestPath, out byte[]? storedLatest) + || PagedGzipStream.Decompress(storedLatest) is not { } latest + || EntitySchemaReader.Read(latest, targetDoc) is not { } schemas + || schemas.ContainsKey(SchemaId) + || new FormatsSchema(sourceDoc).IdOf("ProjectInfo") is not int projectInfo + || LegacyElectricalStyle.QueuedField(latest, targetDoc, "ESSchemaStorage", "m_storedSchemas", readEntities: true) is not { } registry + || EncodeSchema(targetDoc) is not { } entry) + return null; + + var candidates = new Dictionary(); + foreach (var (path, stored) in partitions) + Walk(stored, sourceTags, sourceWidth, r => + { + if (r.Block == 0 && r.Channel == 102 && r.Body.Length >= 2 + && BinaryPrimitives.ReadUInt16LittleEndian(r.Body.Span) == projectInfo) + candidates[r.Owner] = (path, r.Body.ToArray()); + }); + if (candidates.Count != 1) return null; + var (owner, (partition, sourceBody)) = candidates.Single(); + if (dropped?.Contains(owner) == true) return null; + byte[]? body = transcoder.Payload(sourceBody, 0, sourceBody.Length, out _); + return body is null ? null : Attach(content, targetDoc, latest, schemas, registry, entry, + partition, owner, body, replacements, storedLatest); + } + + private static Attachment? Attach(Content content, SchemaDocument doc, byte[] latest, + Dictionary schemas, (int Start, int End) registry, byte[] entry, + string partition, ulong owner, byte[] body, Dictionary replacements, byte[] storedLatest) + { + var walker = new WideBlockWalker(doc, (c, f) => (c.Name, f.Name) switch + { + ("ESEntityCell", "m_entityMap") => f.Name, + ("Element", "m_cellList") => f.Name, + ("ESBlob", FieldName) => f.Name, + _ => null, + }, []); + walker.UseEntitySchemas(schemas, passUnknown: true); + int tag = BinaryPrimitives.ReadUInt16LittleEndian(body); + var walk = walker.Run(body, 0, body.Length, tag); + if (!walk.Exact) return null; + string payload = content.Encode(); + byte[]? attached = PutEntity(body, doc, walk, tag, payload); + if (attached is null) return null; + + int count = BinaryPrimitives.ReadInt32LittleEndian(latest.AsSpan(registry.Start, 4)); + if (count < 0) throw new InvalidDataException("Invalid Extensible Storage schema count."); + byte[] registered = [.. latest.AsSpan(0, registry.End), .. entry, .. latest.AsSpan(registry.End)]; + BinaryPrimitives.WriteInt32LittleEndian(registered.AsSpan(registry.Start, 4), checked(count + 1)); + var extended = EntitySchemaReader.Read(registered, doc); + if (extended?.Count != schemas.Count + 1 || extended.GetValueOrDefault(SchemaId) is not [{ Name: FieldName, Type: 8, Mods: 0x60 }]) + throw new InvalidDataException("The energy archive schema could not be registered."); + walker.UseEntitySchemas(extended, passUnknown: true); + var verified = walker.Run(attached, 0, attached.Length, tag); + if (!verified.Exact || !verified.Captures.Any(c => c.DeclaringClass == "ESBlob" && c.Field == FieldName && c.Text == payload)) + throw new InvalidDataException("The embedded energy archive could not be read back."); + replacements["Global/Latest"] = PagedStreamCodec.Reencode(storedLatest, registered); + return new Attachment(partition, owner, attached); + } + + private static byte[]? PutEntity(byte[] body, SchemaDocument doc, WideBlockWalker.Walk walk, int tag, string payload) + { + byte[] guid = SchemaId.ToByteArray(); + byte[] pair = [.. guid, .. BitConverter.GetBytes(uint.MaxValue), .. guid]; + byte[] blob = Text(payload); + var maps = walk.Captures.Where(c => c.Key == "m_entityMap#").ToArray(); + if (maps is [{ QueueIndex: >= 0 } map]) + { + int cell = map.QueueIndex, count = checked((int)map.Integer); + int start = map.Offset + sizeof(int), end = cell + 1 < walk.Queue.Count ? walk.QueueStart[cell + 1] : walk.Position; + if (map.Offset < 0 || end - (long)start != (long)count * pair.Length + || walk.QueueEnd[cell] - walk.QueueCountAtStart[cell] != count) + return null; + int insert = 0; + while (insert < count && body.AsSpan(start + insert * pair.Length, guid.Length).SequenceCompareTo(guid) < 0) + insert++; + int at = start + insert * pair.Length; + int child = walk.QueueCountAtStart[cell] + insert; + int blobAt = child < walk.Queue.Count ? walk.QueueStart[child] : walk.Position; + if (blobAt < end) return null; + byte[] result = [.. body.AsSpan(0, at), .. pair, .. body.AsSpan(at, blobAt - at), .. blob, .. body.AsSpan(blobAt)]; + BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(map.Offset, sizeof(int)), checked(count + 1)); + return result; + } + + // shortcut: create a cell list only when the holder has no queued objects. Extend queue insertion for other holder layouts. + var format = new FormatsSchema(doc); + if (maps.Length != 0 || walk.Queue.Count != 0 || format.IdOf("CellList") is not int listTag + || format.IdOf("ESEntityCell") is not int entityTag + || PayloadSpan.Find(body, sizeof(ushort), body.Length, doc, tag, "m_cellList") is not { } cellList + || cellList.End - cellList.Start != sizeof(uint) || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(cellList.Start)) != 0) + return null; + return [.. body.AsSpan(0, cellList.Start), .. Pointer(listTag), .. body.AsSpan(cellList.End), + .. BitConverter.GetBytes(1), .. Pointer(entityTag), .. BitConverter.GetBytes(1), .. pair, .. blob]; + } + + internal static byte[]? EncodeSchema(SchemaDocument doc) + { + if (doc.Classes.FirstOrDefault(c => c.Name == "ESSchema") is not { } schema + || doc.Classes.FirstOrDefault(c => c.Name == "ESField") is not { } field + || !schema.Fields.Where(f => f.Stored).Select(f => f.Name).SequenceEqual( + ["m_documentation", "m_fields", "m_schemaName", "m_vendorId", "m_applicationGUID", "m_guid", + "m_readAccessLevel", "m_writeAccessLevel"])) + return null; + string[] fieldNames = [.. field.Fields.Where(f => f.Stored).Select(f => f.Name)]; + bool spec = fieldNames.SequenceEqual(["m_documentation", "m_fieldName", "m_fieldTypeName", "m_specTypeId", + "m_containerType", "m_entryIndex", "m_subSchemaGUID"]); + if (!spec && !fieldNames.SequenceEqual(["m_documentation", "m_fieldName", "m_fieldTypeName", + "m_containerType", "m_entryIndex", "m_subSchemaGUID", "m_unitType"])) + return null; + + byte[] emptyInt = new byte[sizeof(int)], emptyGuid = Guid.Empty.ToByteArray(); + byte[] access = BitConverter.GetBytes(1); // AccessLevel.Public. + byte[] guid = SchemaId.ToByteArray(); + return [.. guid, .. emptyInt, .. BitConverter.GetBytes(1), .. emptyInt, .. Text(FieldName), .. Text("TCHAR"), + .. (spec ? emptyInt : []), .. emptyInt, .. emptyInt, .. emptyGuid, .. (spec ? [] : BitConverter.GetBytes(-2)), + .. Text(SchemaName), .. emptyInt, .. emptyGuid, .. guid, .. access, .. access]; + } + + private static byte[] Text(string value) => [.. BitConverter.GetBytes(value.Length), .. Encoding.Unicode.GetBytes(value)]; + private static byte[] Pointer(int tag) => [.. BitConverter.GetBytes(uint.MaxValue), .. BitConverter.GetBytes(checked((ushort)tag))]; + + private static void Walk(byte[] stored, PartitionFraming.Tags tags, int width, Action visit) + { + if (!PartitionFraming.Walk(stored, tags, width, visit, out var failure, out _)) + throw new InvalidDataException($"Cannot read the energy archive source partition: {failure}."); + } +} diff --git a/src/RvtIO/Writing/EnergyAnalysisTracking.cs b/src/RvtIO/Writing/EnergyAnalysisTracking.cs new file mode 100644 index 00000000..ea5612ed --- /dev/null +++ b/src/RvtIO/Writing/EnergyAnalysisTracking.cs @@ -0,0 +1,106 @@ +using System.Buffers.Binary; +using RvtIO.BuiltIns; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class EnergyAnalysisTracking +{ + private const string Latest = "Global/Latest"; + + internal static void Restore(SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, + IReadOnlyList<(string Path, byte[] Stored)> partitions, IReadOnlyList<(long Id, long Owning)> rows, + IReadOnlySet dropped, Dictionary replacements) + { + if (!replacements.TryGetValue(Latest, out var stored) + || PagedGzipStream.Decompress(stored) is not { } latest + || LegacyElectricalStyle.QueuedField(latest, target, "EnergyAnalysisModelTracker", "m_mainModelId", true) + is not { } modelField || modelField.End - modelField.Start != sizeof(int)) + return; + int modelId = BinaryPrimitives.ReadInt32LittleEndian(latest.AsSpan(modelField.Start)); + if (modelId <= 0 || dropped.Contains((ulong)modelId)) return; + + var members = rows.Where(row => row.Owning == modelId && row.Id > 0 && !dropped.Contains((ulong)row.Id)) + .Select(row => (ulong)row.Id).ToHashSet(); + if (members.Count == 0) return; + var categories = source.Classes.Where(c => c.Name is "EnergyAnalysisSurface" or "EnergyAnalysisOpening" or "EnergyAnalysisSpace") + .ToDictionary(c => c.Id, c => c.Name == "EnergyAnalysisSpace" + ? BuiltInCategory.OST_AnalyticSpaces : BuiltInCategory.OST_AnalyticSurfaces); + if (categories.Count == 0) return; + + var ids = new Dictionary>(); + foreach (var (_, raw) in partitions) + { + if (!PartitionFraming.Walk(raw, tags, width, record => + { + if (record.Block != 0 || record.Channel != 102 || !members.Contains(record.Owner) + || record.Body.Length < sizeof(ushort) + || !categories.TryGetValue(BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span), out var category)) + return; + if (!ids.TryGetValue((int)category, out var group)) ids.Add((int)category, group = []); + group.Add(checked((int)record.Owner)); + }, out string? error, out _)) + throw new InvalidDataException(error); + } + if (ids.Count == 0) return; + + var schema = new FormatsSchema(target); + if (schema.Get("ElementTrackingDataItem") is not { Fields: [ + { Name: "m_categoryId", Type: 14, Mods: 0, Ref: int categoryRef }, + { Name: "m_elemIdSet", Type: 14, Mods: 80, Ref: int memberRef }] } + || schema.Get("ElementId")?.Id != categoryRef || categoryRef != memberRef + || LegacyElectricalStyle.QueuedField(latest, target, "ElementTrackingData", "m_elems", true) + is not { } tracked) + throw new InvalidDataException("Unexpected element tracking layout."); + + // Revit enumerates the tracked categories when exporting a saved energy model. + ReadOnlySpan current = latest.AsSpan(tracked.Start, tracked.End - tracked.Start); + byte[] updated = Register(current, ids); + if (!current.SequenceEqual(updated)) + { + byte[] body = [.. latest.AsSpan(0, tracked.Start), .. updated, .. latest.AsSpan(tracked.End)]; + replacements[Latest] = PagedStreamCodec.Reencode(stored, body); + } + } + + internal static byte[] Register(ReadOnlySpan data, IReadOnlyDictionary> additions) + { + if (data.Length < sizeof(int)) throw new InvalidDataException("Missing tracked category count."); + int count = BinaryPrimitives.ReadInt32LittleEndian(data); + int at = sizeof(int); + if (count < 0 || count > (data.Length - at) / (2 * sizeof(int))) + throw new InvalidDataException("Invalid tracked category count."); + + var groups = new SortedDictionary(); + int previous = int.MinValue; + for (int i = 0; i < count; i++) + { + if (at > data.Length - 2 * sizeof(int)) throw new InvalidDataException("Incomplete tracked category."); + int category = BinaryPrimitives.ReadInt32LittleEndian(data[at..]); + int size = BinaryPrimitives.ReadInt32LittleEndian(data[(at + sizeof(int))..]); + at += 2 * sizeof(int); + if (category <= previous || size < 0 || size > (data.Length - at) / sizeof(int)) + throw new InvalidDataException("Invalid tracked category entry."); + var items = new int[size]; + for (int j = 0; j < items.Length; j++, at += sizeof(int)) + items[j] = BinaryPrimitives.ReadInt32LittleEndian(data[at..]); + groups.Add(category, items); + previous = category; + } + if (at != data.Length) throw new InvalidDataException("Unexpected data after tracked categories."); + + foreach (var (category, members) in additions) + groups[category] = (groups.GetValueOrDefault(category) ?? []).Union(members).Order().ToArray(); + + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(groups.Count); + foreach (var (category, members) in groups) + { + writer.Write(category); + writer.Write(members.Length); + foreach (int id in members) writer.Write(id); + } + return stream.ToArray(); + } +} diff --git a/src/RvtIO/Writing/LegacyAnalyticalMembers.cs b/src/RvtIO/Writing/LegacyAnalyticalMembers.cs new file mode 100644 index 00000000..5ff2396f --- /dev/null +++ b/src/RvtIO/Writing/LegacyAnalyticalMembers.cs @@ -0,0 +1,1436 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// Restores the verified legacy representation from an earlier revision of the same project. +internal static class LegacyAnalyticalMembers +{ + internal sealed record Restored(long SourceElementId, long OutputElementId, long PhysicalElementId); + internal sealed record RestoredNode(long ElementId, long HostElementId); + internal sealed record RestoredOpening(long SourceElementId, long OutputPanelElementId); + internal sealed record Result(DowngradePartitionRewriter.ProjectEdits Edits, Restored[] Members, Restored[] Panels, + RestoredOpening[] Openings, long[] PointSupports, long[] LineSupports, + long[] Instances, RestoredNode[] AttachedNodes, long[] LineLoads); + + private sealed record AttachedNode(long OldHub, long OldPoint, long Hub, long Point, long Host, byte[][] PointRecords); + private sealed record NewSlab(long SettingsHost, long Physical, WideBlockWalker.Walk Body, WideBlockWalker.Walk Geometry, + Dictionary NodeRecords); + private sealed record Candidate( + Restored Member, bool Panel, long[] Openings, HashSet Records, HashSet Peers, long[] Supports, long[] Instances, + byte[] Header, byte[] Body, long MaterialAsset, List AttachedNodes); + + private sealed class Snapshot + { + internal readonly Dictionary Rows; + internal readonly Dictionary Records = []; + internal readonly RvtFileReader.EpisodeTableParseResult History; + internal readonly WideBlockWalker Walker; + internal readonly byte[] Table; + internal readonly int RowWidth; + private readonly Dictionary<(long Id, int Channel), WideBlockWalker.Walk?> _decoded = new(); + + internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? latest, byte[] partition, int width) + { + var formats = new FormatsSchema(schema); + Table = table; + RowWidth = ElemTableLayout.RowLength(formats) ?? throw new InvalidDataException("Missing element row layout."); + Rows = (ElemTableLayout.TryParse(table, formats) ?? throw new InvalidDataException("Invalid element table.")).ToDictionary(row => row.Id); + History = RvtFileReader.ParseEpisodeGuids([history], null, new FileSchema(schema)); + if (History.X != History.Guids.Count || History.Guids.Count == 0) + throw new InvalidDataException("Missing project episode history."); + Walker = new WideBlockWalker(schema, (c, f) => WideBlockWalker.AllItemsKeyPrefix + c.Name + "." + f.Name, []); + if (latest is not null && EntitySchemaReader.Read(latest, schema) is { } entities) + Walker.UseEntitySchemas(entities, passUnknown: true); + var tags = PartitionFraming.TagsOf(formats) ?? throw new InvalidDataException("Missing partition framing classes."); + if (!PartitionFraming.Walk(partition, tags, width, record => + { + if (record.Block != 0 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; + long id = (long)record.Owner; + if (!Records.TryGetValue(id, out var parts)) Records[id] = parts = new byte[3][]; + int index = record.Channel - 101; + if (parts[index] is not null) throw new InvalidDataException("Duplicate project partition record."); + parts[index] = record.Body.ToArray(); + }, out var failure, out _)) throw new InvalidDataException($"Cannot read analytical partition records: {failure}."); + } + + internal string? Class(long id, int channel = 102) + => Records.GetValueOrDefault(id)?[channel - 101] is { } bytes + ? Walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(bytes))?.Name : null; + + internal WideBlockWalker.Walk? Block(long id, int channel = 102) + { + if (_decoded.TryGetValue((id, channel), out var decoded)) return decoded; + return _decoded[(id, channel)] = Records.GetValueOrDefault(id)?[channel - 101] is { } bytes + ? Decode(bytes) : null; + } + + internal WideBlockWalker.Walk? Decode(byte[] bytes, bool captureArchiveKeys = false) => + LegacyAnalyticalMembers.Decode(Walker, bytes, captureArchiveKeys); + } + + internal static Dictionary<(ulong Owner, int Channel), byte[]> RestoreOpeningEdgePicks( + SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, byte[] partition, + IReadOnlyDictionary? entitySchemas, IReadOnlySet dropped, R22Transcoder transcoder) + { + var edits = new Dictionary<(ulong Owner, int Channel), byte[]>(); + var schema = new FormatsSchema(source); + if (schema.IdOf("AnalyticalOpening") is not int openingClass || + schema.IdOf("BoundaryConditions") is not int supportClass) return edits; + + var openings = new Dictionary(); + var supports = new Dictionary(); + if (!PartitionFraming.Walk(partition, tags, width, record => + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort) || + dropped.Contains(record.Owner)) return; + int tag = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + if (tag == openingClass) openings.Add(record.Owner, record.Body.ToArray()); + if (tag == supportClass) supports.Add(record.Owner, record.Body.ToArray()); + }, out var failure, out _)) throw new InvalidDataException($"Cannot read analytical opening supports: {failure}."); + if (openings.Count == 0 || supports.Count == 0) return edits; + + var geometry = new Dictionary(); + if (!PartitionFraming.Walk(partition, tags, width, record => + { + if (record.Block == 0 && record.Channel == 103 && record.Body.Length >= sizeof(ushort) && + (openings.ContainsKey(record.Owner) || supports.ContainsKey(record.Owner))) + geometry.Add(record.Owner, record.Body.ToArray()); + }, out failure, out _)) throw new InvalidDataException($"Cannot read analytical opening geometry: {failure}."); + + var sourceWalker = Walker(source); + if (entitySchemas is not null) sourceWalker.UseEntitySchemas(entitySchemas, passUnknown: true); + var targetWalker = Walker(target); + var openingEdges = new List<(long Panel, ulong Owner, long Tag, DirectedEdge Curve)>(); + foreach (var (owner, body) in openings) + { + if (!geometry.TryGetValue(owner, out var stored) || Decode(sourceWalker, body) is not { } opening || + Id(opening, "AnalyticalOpening", "m_panelId") is not (> 0 and var panel) || + Decode(sourceWalker, stored) is not { } outline) continue; + foreach (var tag in GeometryTags(outline).GroupBy(c => c.Integer)) + if (tag.Take(2).ToArray() is [var match] && + ReadEdge(sourceWalker, outline, match.QueueIndex) is { } edge) + openingEdges.Add((panel, owner, tag.Key, edge)); + } + + foreach (var (owner, body) in supports) + { + if (!geometry.TryGetValue(owner, out var stored) || Decode(sourceWalker, body) is not { } support || + Id(support, "BoundaryConditions", "m_type") != 1 || Id(support, "ElemPick", "m_type") != 0 || + Ids(support, "ElemPick", "m_tags").Length != 0 || !WholeEdgePick(support) || + Ids(support, "ForeignElemRef", "m_id").Any(id => id != -1) || + Id(support, "ElemPick", "m_elemId") is not (> 0 and var panel) || + Decode(sourceWalker, stored) is not { } curve || + GeometryTags(curve).Where(c => c.Integer == 0).Take(2).ToArray() is not [var supportTag] || + ReadEdge(sourceWalker, curve, supportTag.QueueIndex) is not { } edge) continue; + + // Revit 2023 needs a tagged edge on the opening where newer releases store a panel-only pick. + var matches = openingEdges.Where(candidate => candidate.Panel == panel && + SketchEdgesAgree(candidate.Curve, edge)).Take(2).ToArray(); + if (matches is not [var match] || match.Owner > int.MaxValue || + transcoder.Payload(body, 0, body.Length, out _) is not { } converted || + Decode(targetWalker, converted) is not { } pick || + pick.Captures.Where(c => c is { DeclaringClass: "ElemPick", Field: "m_elemId", Offset: >= 0 }) + .Take(2).ToArray() is not [var host] || host.Integer != panel) continue; + + WriteInt(converted, host, (long)match.Owner); + if (RewriteEdgePick(converted, pick, match.Tag) is not { } rewritten || + Decode(targetWalker, rewritten) is not { } bound || + Id(bound, "ElemPick", "m_elemId") != (long)match.Owner || + Id(bound, "ElemPick", "m_type") != 1 || Id(bound, "ElemPick", "m_tags") != match.Tag) + throw new InvalidDataException("The analytical opening edge pick could not be rewritten."); + edits.Add((owner, 102), rewritten); + } + return edits; + + static WideBlockWalker Walker(SchemaDocument schema) => + new(schema, (c, f) => WideBlockWalker.AllItemsKeyPrefix + c.Name + "." + f.Name, []); + } + + private static WideBlockWalker.Walk? Decode(WideBlockWalker walker, byte[] bytes, bool captureArchiveKeys = false) + { + walker.StepBudget = 16L * bytes.Length + 65536; + var walk = walker.Run(bytes, 0, bytes.Length, BinaryPrimitives.ReadUInt16LittleEndian(bytes), + captureArchiveKeys: captureArchiveKeys); + return walk.Exact ? walk : null; + } + + internal static Result? Restore(string profilePath, SchemaDocument sourceSchema, SchemaDocument targetSchema, + byte[] sourceTable, byte[] sourceHistory, byte[]? sourceLatest, byte[] sourcePartition, int sourceWidth, + IReadOnlySet dropped, IReadOnlyList analysis, + R22Transcoder transcoder, Dictionary replacements) + { + using var root = RootStorage.OpenRead(profilePath); + var partitions = root.OpenStorage("Partitions"); + var streams = partitions.EnumerateEntries().Where(e => e.Type == EntryType.Stream && int.TryParse(e.Name, out _)).ToArray(); + if (streams.Length != 1) + throw new InvalidDataException("The historical project must have one numbered partition."); + using var stream = partitions.OpenStream(streams[0].Name); + var raw = new byte[checked((int)stream.Length)]; + stream.ReadExactly(raw); + var current = new Snapshot(sourceSchema, sourceTable, sourceHistory, sourceLatest, sourcePartition, sourceWidth); + var previous = new Snapshot(targetSchema, Read("ElemTable"), Read("History"), Read("Latest"), raw, 4); + if (!current.History.Guids.AsEnumerable().Reverse().Take(previous.History.Guids.Count) + .SequenceEqual(previous.History.Guids.AsEnumerable().Reverse(), StringComparer.OrdinalIgnoreCase)) + throw new InvalidDataException("The target profile is not an earlier revision in the source project history."); + + var oldModels = previous.Rows.Values.Where(row => previous.Class(row.Id) is + "AnalyticalModelBeam" or "AnalyticalModelColumn" or "AnalyticalModelWall" or "AnalyticalModelSlab") + .ToLookup(row => row.OwningId); + var currentModels = analysis.Where(e => e.Class is ("AnalyticalMember" or "AnalyticalPanel") && + e.PhysicalElementIds.Count == 1).ToArray(); + var associations = currentModels.ToLookup(e => e.PhysicalElementIds[0]); + var oldIds = currentModels.Where(e => associations[e.PhysicalElementIds[0]].Count() == 1 && + oldModels[e.PhysicalElementIds[0]].Count() == 1) + .ToDictionary(e => (long)e.ElementId, e => oldModels[e.PhysicalElementIds[0]].Single().Id); + var generatedSlabs = new Dictionary(); + var newElementRecords = new Dictionary(); + foreach (var element in currentModels.Where(e => e.Class == "AnalyticalPanel")) + { + long source = (long)element.ElementId, host = element.PhysicalElementIds[0]; + if (associations[host].Count() != 1 || oldModels[host].Any() || + TryBuildSlab(source, host, out var records) is not { } slab) continue; + oldIds.Add(source, source); + generatedSlabs.Add(source, slab); + newElementRecords.Add(source, records); + } + var openingPanels = new Dictionary(); + foreach (var opening in analysis.Where(e => e.Class == "AnalyticalOpening")) + { + long id = (long)opening.ElementId; + if (current.Block(id) is { } body && Id(body, "AnalyticalOpening", "m_panelId") is > 0 and var panel && + oldIds.ContainsKey(panel) && current.Class(panel) == "AnalyticalPanel" && + current.Block(panel) is { } parent && Ids(parent, "AnalyticalPanel", "m_openingsIds").Contains(id)) + openingPanels.Add(id, panel); + } + long PanelOrSelf(long id) => openingPanels.GetValueOrDefault(id, id); + var oldReferences = oldIds.Concat(openingPanels.Select(pair => KeyValuePair.Create(pair.Key, oldIds[pair.Value]))) + .ToDictionary(pair => pair.Key, pair => pair.Value); + var dependents = analysis.SelectMany(e => e.AnalyticalHostIds.Select(host => (host, e))).ToLookup(x => x.host, x => x.e); + var sourceClasses = sourceSchema.ById; + var supportTranscoder = new Lazy(() => new(sourceSchema, targetSchema, sourceWidth, + sourceLatest is null ? null : EntitySchemaReader.Read(sourceLatest, sourceSchema), downgradeRelease: 2022)); + + var candidates = new Dictionary(); + foreach (var element in currentModels) + { + long source = (long)element.ElementId, host = element.PhysicalElementIds[0]; + var generated = generatedSlabs.GetValueOrDefault(source); + long settingsHost = generated?.SettingsHost ?? host; + if (!oldIds.TryGetValue(source, out long old) || generated is null && !SameElement(host) || + current.Block(source) is not { } member || (generated?.Body ?? previous.Block(old)) is not { } legacy || + current.Block(host) is not { } owner || previous.Block(settingsHost) is not { } oldOwner || + Id(legacy, "AnalyticalModel", "m_ownerElementId") != host) continue; + + string? legacyClass = generated is null ? previous.Class(old) : "AnalyticalModelSlab"; + string dataClass = legacyClass switch + { + "AnalyticalModelBeam" => "StructFramUserData", + "AnalyticalModelColumn" => "StructColumnUserData", + "AnalyticalModelWall" => "StructVWallUserData", + "AnalyticalModelSlab" => "StructFloorUserData", + _ => throw new InvalidDataException("Unknown legacy analytical model class."), + }; + if (generated is null && Id(oldOwner, dataClass, "m_analyticalModelId") != old) continue; + bool panel = element.Class == "AnalyticalPanel"; + long[] openings = []; + double[] sourceAxis = []; + long asset; + if (generated is not null) + { + openings = Ids(member, "AnalyticalPanel", "m_openingsIds"); + asset = Id(legacy, "AnalyticalModel", "m_structuralAssetId"); + } + else if (panel) + { + if (legacyClass is not ("AnalyticalModelWall" or "AnalyticalModelSlab") || + !SamePanel(source, host, member, legacy, owner, oldOwner, legacyClass == "AnalyticalModelWall", + out asset, out openings)) continue; + } + else + { + bool column = legacyClass == "AnalyticalModelColumn"; + if (legacyClass is not ("AnalyticalModelBeam" or "AnalyticalModelColumn") || + current.Class(host) != "FamilyInstance" || previous.Class(host) != "FamilyInstance" || + Id(member, "AnalyticalElement", "m_structuralRole") != (column ? 1 : 0) || + Id(member, "AnalyticalElement", "m_analyzeAs") != Id(legacy, legacyClass, "m_analyzeAs") || + !SameProperties(member, owner, oldOwner, column, out asset) || !SameReleases(member, legacy)) continue; + var currentEdge = CurveEdge(current, member, "AnalyticalMember", "m_oCurve"); + if (currentEdge is null || + !EdgesAgree(currentEdge, CurveEdge(previous, legacy, "AnalyticalCurveCell", "m_oAdjustCurve"))) continue; + sourceAxis = [.. currentEdge.Start, .. currentEdge.End]; + } + + var resources = new HashSet { old }; + var peers = new HashSet(); + var attachedNodes = new List(); + if (generated is null && !MatchNodes(source, member, old, legacy, panel, openings, resources, peers, attachedNodes)) + continue; + + var supports = new List(); + var instances = new List(); + var supportEdges = new HashSet(); + bool supportsMatch = true; + foreach (long hostId in openings.Prepend(source)) + foreach (var support in dependents[hostId]) + { + if (support.Class is "LineLoad" or "AreaLoad") continue; + long id = (long)support.ElementId; + if (support.Class != "BoundaryConditions" || support.AnalyticalHostIds is not [var actual] || actual != hostId || + current.Block(id) is not { } modernSupport || + !(previous.Block(id) is { } historicalSupport + ? MatchSupport(id, hostId, old, panel, sourceAxis, modernSupport, historicalSupport, out long instance) + : panel && TryConvertLineSupport(id, hostId, old, host, modernSupport, legacy, out instance))) + { + supportsMatch = false; + break; + } + if (panel && !supportEdges.Add(Id(previous.Block(id) ?? previous.Decode(newElementRecords[id][1])!, + "ElemPick", "m_tags"))) + { + supportsMatch = false; + break; + } + supports.Add(id); + instances.Add(instance); + resources.Add(id); + resources.Add(instance); + } + if (!supportsMatch || !TryBindHost(host, settingsHost, old, dataClass, out var header, out var body)) continue; + candidates.Add(source, new Candidate(new(source, old, host), panel, openings, resources, peers, [.. supports], [.. instances], + header, body, asset, attachedNodes)); + } + + // Keep whole connected groups and their archive dependencies. Optional regeneration cache links can be discarded. + bool changed; + do + { + changed = false; + var available = candidates.Values.SelectMany(c => c.Records).ToHashSet(); + foreach (var (id, candidate) in candidates.ToArray()) + { + if (candidate.Peers.All(candidates.ContainsKey) && candidate.Records.All(record => CanRestore(record, available))) continue; + candidates.Remove(id); + changed = true; + } + } while (changed); + if (candidates.Count == 0) return null; + + var ordered = candidates.Values.OrderBy(c => c.Member.SourceElementId).ToArray(); + var assets = ordered.ToDictionary(c => c.Member.OutputElementId, c => c.MaterialAsset); + var relocated = ordered.SelectMany(c => c.AttachedNodes).DistinctBy(n => (n.OldHub, n.OldPoint, n.Hub, n.Point)).ToArray(); + var nodePairs = relocated.SelectMany(n => new[] { (Old: n.OldHub, Current: n.Hub), (Old: n.OldPoint, Current: n.Point) }).ToArray(); + if (nodePairs.Select(n => n.Old).Distinct().Count() != nodePairs.Length || + nodePairs.Select(n => n.Current).Distinct().Count() != nodePairs.Length) + throw new InvalidDataException("The analytical node correspondence is ambiguous."); + var nodeIds = nodePairs.ToDictionary(n => n.Old, n => n.Current); + var pointRecords = relocated.ToDictionary(n => n.OldPoint, n => n.PointRecords); + var retained = ordered.SelectMany(c => c.Records).ToHashSet(); + var loadCandidates = ordered.Where(c => !c.Panel).SelectMany(c => dependents[c.Member.SourceElementId] + .Where(e => e.Class == "LineLoad" && MatchLineLoad((long)e.ElementId, c.Member)) + .Select(e => (long)e.ElementId)).Distinct().Order(); + var lineLoads = new List(); + foreach (long id in loadCandidates) + { + retained.Add(id); + if (CanRestore(id, retained)) lineLoads.Add(id); + else retained.Remove(id); + } + var added = retained.Order().ToArray(); + var currentRows = added.Where(newElementRecords.ContainsKey).ToHashSet(); + var edits = new Dictionary<(ulong, int), byte[]>(); + foreach (var selected in ordered) + { + edits.Add(((ulong)selected.Member.PhysicalElementId, 101), selected.Header); + edits.Add(((ulong)selected.Member.PhysicalElementId, 102), selected.Body); + if (generatedSlabs.TryGetValue(selected.Member.SourceElementId, out var slab)) + foreach (var (id, parts) in slab.NodeRecords) + for (int c = 0; c < parts.Length; c++) edits.Add(((ulong)id, c + 101), parts[c]); + } + var additions = new List(); + foreach (long id in added) + { + if (pointRecords.TryGetValue(id, out var modern)) + { + for (int c = 0; c < modern.Length; c++) edits.Add(((ulong)nodeIds[id], c + 101), modern[c]); + continue; + } + var parts = newElementRecords.GetValueOrDefault(id) ?? previous.Records[id]; + var header = RewriteParents(parts[0], previous.Decode(parts[0])!, "m_regenOnly", + ids => ids.Where(value => retained.Contains(value) || IsRetained(value))); + if (header is null || previous.Decode(header) is null) + throw new InvalidDataException("A restored analytical element has an invalid regeneration list."); + byte[] body = parts[1]; + if (assets.TryGetValue(id, out long asset) && previous.Block(id) is { } model && + Id(model, "AnalyticalModel", "m_structuralAssetId") is long oldAsset && oldAsset != asset) + { + var field = PayloadSpan.Find(body, 2, model.QueueStart[0], targetSchema, + BinaryPrimitives.ReadUInt16LittleEndian(body), "m_structuralAssetId"); + if (field is not { } range || range.End - range.Start != 4 || previous.Decode(header) is not { } decoded) + throw new InvalidDataException("Cannot write the current material asset to a legacy analytical element."); + body = body.ToArray(); + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(range.Start), checked((int)asset)); + if (oldAsset > 0) + header = RewriteParents(header, decoded, "m_deletion", + ids => ids.Where(value => value != oldAsset || asset > 0).Select(value => value == oldAsset ? checked((int)asset) : value) + .Distinct().Order()) ?? throw new InvalidDataException("Invalid analytical material dependency."); + if (previous.Decode(body) is null || previous.Decode(header) is null) + throw new InvalidDataException("Cannot verify the restored analytical material dependency."); + } + byte[][] revised = [header, body, parts[2]]; + if (nodeIds.Count != 0) + { + for (int c = 0; c < revised.Length; c++) + { + if (previous.Decode(revised[c]) is not { } decoded) + throw new InvalidDataException("Cannot read a restored analytical dependency."); + revised[c] = revised[c].ToArray(); + RemapIds(revised[c], decoded, nodeIds, sizeof(int)); + if (c == 2 && nodeIds.TryGetValue(id, out long newId)) + { + var tag = decoded.Captures.SingleOrDefault(f => IsGeometryOwner(f, id)); + if (IsGeometryOwner(tag, id)) WriteInt(revised[c], tag, newId); + } + } + } + if (nodeIds.TryGetValue(id, out long replacement)) + { + for (int c = 0; c < revised.Length; c++) edits.Add(((ulong)replacement, c + 101), revised[c]); + } + else additions.Add(new((ulong)id, revised)); + } + AddRows(previous, targetSchema, replacements, added.Where(id => !nodeIds.ContainsKey(id)).ToArray(), currentRows, + currentRows.Count == 0 ? null : DowngradeElemTableRewriter.Rewrite(sourceTable, sourceSchema, targetSchema), + generatedSlabs.Where(pair => retained.Contains(pair.Key)).ToDictionary(pair => pair.Key, pair => pair.Value.Physical)); + + return new Result(new(additions, edits), + ordered.Where(c => !c.Panel).Select(c => c.Member).ToArray(), + ordered.Where(c => c.Panel).Select(c => c.Member).ToArray(), + ordered.SelectMany(c => c.Openings.Select(id => new RestoredOpening(id, c.Member.OutputElementId))).ToArray(), + ordered.Where(c => !c.Panel).SelectMany(c => c.Supports).ToArray(), + ordered.Where(c => c.Panel).SelectMany(c => c.Supports).ToArray(), + ordered.SelectMany(c => c.Instances).ToArray(), + relocated.Select(n => new RestoredNode(n.Point, n.Host)).ToArray(), lineLoads.ToArray()); + + byte[] Read(string name) => PagedGzipStream.Read(root, "Global", name) + ?? throw new InvalidDataException($"The historical project lacks Global/{name}."); + + bool SameElement(long id) => previous.Rows.TryGetValue(id, out var old) && current.Rows.TryGetValue(id, out var now) && + old.OriginalId == now.OriginalId && old.CreationDate == now.CreationDate; + + bool IsRetained(long id) => (current.Rows.ContainsKey(id) || current.Records.ContainsKey(id)) && !dropped.Contains((ulong)id); + + bool MatchLineLoad(long id, Restored member) + { + if (!SameElement(id) || previous.Class(id) != "LineLoad" || + !OwnedBy(current, id, -1) || !OwnedBy(previous, id, -1) || + current.Block(id) is not { } now || previous.Block(id) is not { } before || + !Ids(now, "ElemPick", "m_elemId").SequenceEqual([member.SourceElementId]) || + !Ids(before, "ElemPick", "m_elemId").SequenceEqual([member.OutputElementId]) || + Id(now, "ElemPick", "m_type") != 0 || Id(before, "ElemPick", "m_type") != 1 || + !Ids(now, "ElemPick", "m_tags").SequenceEqual([0L]) || + !Ids(before, "ElemPick", "m_tags").SequenceEqual([1L, 1L]) || + !WholeEdgePick(now) || !WholeEdgePick(before) || + Ids(now, "ForeignElemRef", "m_id").Any(value => value != -1) || + Ids(before, "ForeignElemRef", "m_id").Any(value => value != -1) || + Id(now, "LineLoad", "m_sketchPlaneId") != -1 || Id(before, "LineLoad", "m_sketchPlaneId") != -1) + return false; + if (Axis(current, now, "LineLoad", "m_oCurve") is { Length: > 0 } curve && + !CoordinatesAgree(curve, Axis(current, current.Block(member.SourceElementId)!, "AnalyticalMember", "m_oCurve"))) + return false; + + return new[] { "m_force_1", "m_force_2", "m_moment_1", "m_moment_2" }.All(field => + Reals(now, "LineLoad", field) is { Length: 3 } values && + values.SequenceEqual(Reals(before, "LineLoad", field))) && + new[] { "m_xVec", "m_yVec", "m_zVec" }.All(field => + Reals(now, "LoadBCBase", field).SequenceEqual(Reals(before, "LoadBCBase", field))) && + new[] { "m_loadCaseId", "m_symbolId", "m_isReaction" }.All(field => + Ids(now, "LoadBase", field).SequenceEqual(Ids(before, "LoadBase", field))) && + Parameters(now).SequenceEqual(Parameters(before)); + } + + NewSlab? TryBuildSlab(long id, long physical, out byte[][] panelRecords) + { + panelRecords = []; + if (!dropped.Contains((ulong)id) || previous.Rows.ContainsKey(id) || !OwnedBy(current, id, -1) || + !IsRetained(physical) || current.Class(physical) != "Floor" || + current.Block(physical) is not { } floor || current.Block(id) is not { } panel || + Id(panel, "AnalyticalElement", "m_structuralRole") != 5 || + Id(panel, "AnalyticalSurfaceBase", "m_sketchId") != -1 || + Contours(current, panel, "AnalyticalSurfaceBase", "m_contourLoops") is not [var outer]) return null; + var openingIds = Ids(panel, "AnalyticalPanel", "m_openingsIds"); + if (openingIds.Distinct().Count() != openingIds.Length) return null; + var loops = new List { outer }; + foreach (long opening in openingIds) + { + if (current.Class(opening) != "AnalyticalOpening" || current.Block(opening) is not { } hole || + Id(hole, "AnalyticalOpening", "m_panelId") != id || + Contours(current, hole, "AnalyticalSurfaceBase", "m_contourLoops") is not [var contour]) return null; + loops.Add(contour); + } + long type = Id(floor, "Floor", "m_floorAttributesId"), sketch = Id(floor, "ExtrusionHelper", "m_sketchId"); + long material = Id(panel, "AnalyticalElement", "m_materialId"); + if (!SameElement(type) || !SameElement(material) || !IsRetained(material) || !IsRetained(sketch) || + current.Block(type) is not { } section || previous.Block(type) is not { } historicalSection || + !SamePanelSection(panel, section, material) || !SamePanelSection(panel, historicalSection, material)) return null; + + var hubs = Ids(panel, "ConnectorId", "m_id").Select(hub => (Hub: hub, Owner: id)) + .Concat(openingIds.SelectMany(owner => Ids(current.Block(owner)!, "ConnectorId", "m_id") + .Select(hub => (Hub: hub, Owner: owner)))).ToArray(); + if (hubs.Select(pair => pair.Hub).Distinct().Count() != hubs.Length) return null; + var currentNodes = new Dictionary(); + foreach (var (hub, owner) in hubs) + { + if (current.Class(hub) != "Hub" || current.Block(hub) is not { } node || !IsRetained(hub) || + !Ids(node, "ConnectorId", "m_id").SequenceEqual([owner])) return null; + long point = Id(node, "HubByPointCell", "m_pointId"); + if (!OwnedBy(current, point, hub) || !IsRetained(point) || current.Class(point) != "ReferencePoint" || + current.Block(point) is not { } pointBody || Ids(pointBody, "GeomRef", "m_elemId").Any(v => v > 0) || + Point(current, point) is not { } coordinates) return null; + currentNodes.Add(hub, (point, coordinates)); + } + long spanDirection = Id(floor, "LineSystemCell", "m_directionId"); + var sketchCurves = current.Rows.Values.Where(row => row.OwningId == sketch && row.Id != spanDirection && + IsRetained(row.Id) && + current.Class(row.Id) == "CurveElem").Select(row => (row.Id, Edge: SketchEdge(current, row.Id))).ToArray(); + if (sketchCurves.Length != loops.Sum(loop => loop.Length) || sketchCurves.Any(curve => curve.Edge is null)) + return null; + + foreach (var candidate in oldModels.SelectMany(group => group).OrderBy(row => row.Id)) + { + long old = candidate.Id, owner = candidate.OwningId; + if (previous.Class(old) != "AnalyticalModelSlab" || previous.Block(old) is not { } template || + previous.Block(owner) is not { } oldFloor || Id(oldFloor, "Floor", "m_floorAttributesId") != type || + Id(oldFloor, "Element", "m_createdPhaseId") != Id(floor, "Element", "m_createdPhaseId") || + Id(template, "AnalyticalFloorCell", "m_analyzesAs") != Id(panel, "AnalyticalElement", "m_analyzeAs") || + Id(template, "AnalyticalModel", "m_isAnalyticalGeometryInvalid") != 0 || + Id(template, "AnalyticalModel", "m_structuralAssetId") is not (> 0 and var asset) || !IsRetained(asset) || + Ids(template, "AnalyticalSurfaceCell", "m_excludedOpenings").Length != 0 || + template.Captures.Any(capture => capture.DeclaringClass == "AnalyticalChainRef" || + capture is { DeclaringClass: "AnalyticalModelCell", Field: "m_oTrf", TargetQueueIndex: not null }) || + Reals(template, "std::pair< int, XYZ >", "second").Any(value => value != 0)) + continue; + var oldLoops = Contours(previous, template, "AnalyticalSurfaceCell", "m_adjustedLoops"); + if (FindSlabPlacement(oldLoops, loops) is not { } placement) continue; + var oldSketch = Id(oldFloor, "ExtrusionHelper", "m_sketchId"); + if (oldSketch <= 0) continue; + var map = new Dictionary { [old] = id, [owner] = physical, [oldSketch] = sketch }; + var refs = template.Captures.Where(c => c.IsElementId && c.Integer > 0 && + c.DeclaringClass == "std::pair< int, ElementId >" && c.Field == "second") + .Select(c => c.Integer).Distinct().ToArray(); + if (refs.Length != oldLoops.Sum(loop => loop.Length)) continue; + foreach (long curve in refs) + { + if (!OwnedBy(previous, curve, oldSketch) || SketchEdge(previous, curve) is not { } original) break; + var moved = placement.Edge(original); + var found = sketchCurves.Where(part => SketchEdgesAgree(moved, part.Edge)).Take(2).ToArray(); + if (found is not [var match] || map.ContainsValue(match.Id)) break; + map.Add(curve, match.Id); + } + if (refs.Any(curve => !map.ContainsKey(curve))) continue; + + var nodeIds = new List(); + var originalHubs = Ids(template, "ConnectorId", "m_id"); + if (originalHubs.Length != currentNodes.Count) continue; + foreach (long hub in originalHubs) + { + if (previous.Block(hub) is not { } body || !Ids(body, "ConnectorId", "m_id").SequenceEqual([old]) || + Point(previous, hub) is not { } position) break; + long point = Id(body, "HubByPointCell", "m_pointId"); + if (!OwnedBy(previous, point, hub) || previous.Block(point) is not { } pointBody || + Ids(pointBody, "GeomRef", "m_elemId").Any(v => v > 0) || + !SamePoint(previous, hub, previous, point)) break; + var target = placement.Point(position); + var matches = currentNodes.Where(pair => CoordinatesAgree(target, pair.Value.Coordinates)).Take(2).ToArray(); + if (matches is not [var match] || map.ContainsValue(match.Key)) break; + map.Add(hub, match.Key); + map.Add(point, match.Value.Point); + nodeIds.AddRange([hub, point]); + } + if (nodeIds.Count != 2 * currentNodes.Count) continue; + + var allowed = map.Values.ToHashSet(); + var nodeRecords = new Dictionary(); + foreach (long node in nodeIds) + { + if (PlaceRecords(node, false) is not { } placed) break; + nodeRecords.Add(map[node], placed); + } + if (nodeRecords.Count != nodeIds.Count || PlaceRecords(old, true) is not { } records || + previous.Decode(records[1]) is not { } placedBody || previous.Decode(records[2]) is not { } placedGeometry || + !SlabLoopsAgree(Contours(previous, placedBody, "AnalyticalSurfaceCell", "m_adjustedLoops"), loops)) + continue; + panelRecords = records; + return new(owner, physical, placedBody, placedGeometry, nodeRecords); + + byte[][]? PlaceRecords(long original, bool surface) + { + var result = new byte[3][]; + for (int c = 0; c < result.Length; c++) + { + if (previous.Records.GetValueOrDefault(original)?[c] is not { } record || + previous.Decode(record, captureArchiveKeys: true) is not { ArchiveKeys: { } keys } walk) + return null; + var ownedKeys = keys.Where(key => key.Owned).Select(key => key.Key).ToArray(); + if (ownedKeys.Distinct().Count() != ownedKeys.Length || + keys.Any(key => !ownedKeys.Contains(key.Key))) return null; + var bytes = record.ToArray(); + RemapIds(bytes, walk, map, sizeof(int)); + var ownerTag = walk.Captures.SingleOrDefault(field => IsGeometryOwner(field, original)); + if (IsGeometryOwner(ownerTag, original)) WriteInt(bytes, ownerTag, map[original]); + if (!PlaceSlabGeometry(bytes, walk, previous.Walker, placement, surface) || + previous.Decode(bytes) is not { } rewritten || + rewritten.Captures.Any(field => field.IsElementId && field.Integer > 0 && + !allowed.Contains(field.Integer) && !(IsRetained(field.Integer) && SameElement(field.Integer)))) + return null; + if (c == 0) + { + foreach (string list in new[] { "m_deletion", "m_regenOnly", "m_appearanceParents" }) + { + if (RewriteParents(bytes, rewritten, list, ids => ids.Distinct().Order()) is not { } ordered || + previous.Decode(ordered) is not { } checkedHeader) return null; + bytes = ordered; + rewritten = checkedHeader; + } + } + result[c] = bytes; + } + return result; + } + } + return null; + } + + bool CanRestore(long id, HashSet available) + { + bool fromCurrent = newElementRecords.TryGetValue(id, out var records); + bool RetainedReference(long reference) => IsRetained(reference) && (fromCurrent || SameElement(reference)); + if (!(fromCurrent ? current.Rows : previous.Rows).TryGetValue(id, out var row) || IsRetained(id) || + !fromCurrent && current.Rows.ContainsKey(id) && !SameElement(id) || row.PartitionId != 0 || + row.OwningId > 0 && !available.Contains(row.OwningId) && !RetainedReference(row.OwningId)) + return false; + for (int channel = 101; channel <= 103; channel++) + { + var block = records is null ? previous.Block(id, channel) : previous.Decode(records[channel - 101]); + if (block is null || block.Captures.Any(c => + c.IsElementId && c.Integer > 0 && !(c.DeclaringClass == "ElementParents" && c.Field == "m_regenOnly") && + !available.Contains(c.Integer) && !RetainedReference(c.Integer))) return false; + } + return true; + } + + bool SameProperties(WideBlockWalker.Walk member, WideBlockWalker.Walk owner, + WideBlockWalker.Walk oldOwner, bool column, out long asset) + { + asset = -1; + long symbol = Id(owner, "InstInfoBase", "m_symbolId"); + long section = Id(member, "AnalyticalMember", "m_sectionType"); + long material = Id(member, "AnalyticalElement", "m_materialId"); + static long PhysicalMaterial(WideBlockWalker.Walk w) + { + var values = w.Captures.Zip(w.Captures.Skip(1)).Where(pair => + pair.First is { DeclaringClass: "NamedParam", Field: "m_elemId", IsElementId: true } && + pair.Second is { DeclaringClass: "NamedParam", Field: "m_paramId", + Integer: (int)BuiltInParameter.STRUCTURAL_MATERIAL_PARAM } && + pair.First.QueueIndex == pair.Second.QueueIndex).Select(pair => pair.First.Integer).ToArray(); + return values is [var materialId] ? materialId : -1; + } + if (symbol <= 0 || Id(oldOwner, "InstInfoBase", "m_symbolId") != symbol || + PhysicalMaterial(owner) != material || PhysicalMaterial(oldOwner) != material || + !SameElement(symbol) || !SameElement(section) || !SameElement(material) || + current.Block(symbol) is not { } currentSymbol || previous.Block(symbol) is not { } oldSymbol || + current.Block(material) is not { } currentMaterial || previous.Block(material) is not { } oldMaterial || + Id(currentMaterial, "Material", "m_structuralPropertySetId") != Id(oldMaterial, "Material", "m_structuralPropertySetId")) + return false; + asset = Id(currentMaterial, "Material", "m_structuralPropertySetId"); + if (asset != -1 && !(asset > 0 && IsRetained(asset) && current.Class(asset) == "PropertySetElement")) return false; + + long Master(WideBlockWalker.Walk b) => Id(b, "FamilySymbol", "m_masterId") is > 0 and long id ? id : symbol; + if (Master(currentSymbol) != section || Master(oldSymbol) != section) return false; + + return SameTransform(owner, oldOwner) && Reals(member, "AnalyticalMember", "m_crossSectionRotation") is [var roll] && + (roll == 0 || column && Math.Abs(Math.Abs(roll) - Math.PI) <= 1e-10 && + HasHalfTurnSymmetry(current, member)); + } + + bool SamePanel(long source, long host, WideBlockWalker.Walk panel, WideBlockWalker.Walk legacy, + WideBlockWalker.Walk owner, WideBlockWalker.Walk oldOwner, bool wall, out long asset, out long[] openings) + { + openings = Ids(panel, "AnalyticalPanel", "m_openingsIds"); + asset = Id(legacy, "AnalyticalModel", "m_structuralAssetId"); + string hostClass = wall ? "SWall" : "Floor"; + string typeClass = wall ? "VWall" : "Floor"; + string typeField = wall ? "m_WallAttributesId" : "m_floorAttributesId"; + long type = Id(owner, typeClass, typeField); + long material = Id(panel, "AnalyticalElement", "m_materialId"); + if (current.Class(host) != hostClass || previous.Class(host) != hostClass || + type <= 0 || type != Id(oldOwner, typeClass, typeField) || !SameElement(type) || + material <= 0 || !IsRetained(material) || !SameElement(material) || + asset <= 0 || !IsRetained(asset) || !SameElement(asset) || current.Class(asset) != "PropertySetElement" || + current.Block(type) is not { } currentType || previous.Block(type) is not { } oldType || + Id(panel, "AnalyticalElement", "m_structuralRole") != (wall ? 6 : 5) || + Id(panel, "AnalyticalElement", "m_analyzeAs") != (wall + ? Id(legacy, "AnalyticalModelWall", "m_analyzeAs") + : Id(legacy, "AnalyticalFloorCell", "m_analyzesAs")) || + openings.Distinct().Count() != openings.Length || + Id(panel, "AnalyticalSurfaceBase", "m_sketchId") != -1 || + !SamePanelSection(panel, currentType, material) || !SamePanelSection(panel, oldType, material)) return false; + + var outer = Contours(current, panel, "AnalyticalSurfaceBase", "m_contourLoops"); + var adjusted = Contours(previous, legacy, "AnalyticalSurfaceCell", "m_adjustedLoops"); + if (outer is not [var boundary] || adjusted.Length != openings.Length + 1 || + !LoopsAgree(boundary, adjusted[0])) return false; + var remaining = adjusted.Skip(1).ToList(); + foreach (long id in openings) + { + if (openingPanels.GetValueOrDefault(id) != source || current.Block(id) is not { } opening || + Id(opening, "AnalyticalSurfaceBase", "m_sketchId") != -1 || + Contours(current, opening, "AnalyticalSurfaceBase", "m_contourLoops") is not [var hole] || + remaining.Where(loop => LoopsAgree(hole, loop)).Take(2).ToArray() is not [var match]) return false; + remaining.Remove(match); + } + return true; + } + + bool MatchNodes(long source, WideBlockWalker.Walk member, long old, WideBlockWalker.Walk legacy, bool panel, + long[] openings, HashSet resources, HashSet peers, List attachedNodes) + { + var modernLinks = Ids(member, "ConnectorId", "m_id").Select(hub => (hub, source)) + .Concat(openings.SelectMany(id => Ids(current.Block(id)!, "ConnectorId", "m_id").Select(hub => (hub, id)))) + .ToArray(); + long[] from = modernLinks.Select(link => link.hub).ToArray(), to = Ids(legacy, "ConnectorId", "m_id"); + if (from.Length != to.Length || from.Distinct().Count() != from.Length || to.Distinct().Count() != to.Length) + return false; + if (panel) + { + if (from.Length < 3) return false; + var ordered = new long[from.Length]; + for (int i = 0; i < ordered.Length; i++) + { + if (to.Where(id => SamePoint(current, from[i], previous, id)).ToArray() is not [var hub]) return false; + ordered[i] = hub; + } + if (ordered.Distinct().Count() != ordered.Length) return false; + to = ordered; + } + else if (from.Length != 2 || + !Ids(member, "AnalyticalMemberEndConnectorPosition", "m_endIndex").SequenceEqual([0L, 1L]) || + !Ids(legacy, "AnalyticalEndConnectorPosition", "m_endIndex").SequenceEqual([0L, 1L])) return false; + for (int end = 0; end < from.Length; end++) + { + if (current.Class(from[end]) != "Hub" || previous.Class(to[end]) != "Hub" || + current.Block(from[end]) is not { } modernHub || previous.Block(to[end]) is not { } oldHub) return false; + long[] modernPeers = Ids(modernHub, "ConnectorId", "m_id"), oldPeers = Ids(oldHub, "ConnectorId", "m_id"); + if (!modernPeers.Contains(modernLinks[end].Item2) || !oldPeers.Contains(old) || + !modernPeers.Select(id => oldReferences.GetValueOrDefault(id, -1)).Order().SequenceEqual(oldPeers.Order())) return false; + long modernPoint = Id(modernHub, "HubByPointCell", "m_pointId"), oldPoint = Id(oldHub, "HubByPointCell", "m_pointId"); + if (current.Class(modernPoint) != "ReferencePoint" || previous.Class(oldPoint) != "ReferencePoint") return false; + bool hasPanelAttachment = false; + if (panel) + { + if (current.Block(modernPoint) is not { } point) return false; + hasPanelAttachment = Ids(point, "GeomRef", "m_elemId").Any(id => id > 0); + } + if (hasPanelAttachment || !SamePoint(current, modernPoint, previous, oldPoint)) + { + var attachment = RestoreAttachment(from[end], modernPoint, to[end], oldPoint, peers); + if (attachment is null) return false; + attachedNodes.Add(attachment); + } + peers.UnionWith(modernPeers.Select(PanelOrSelf)); + resources.Add(to[end]); + resources.Add(oldPoint); + } + return true; + } + + AttachedNode? RestoreAttachment(long hub, long point, long oldHub, long oldPoint, HashSet peers) + { + if (!IsRetained(hub) || !IsRetained(point) || + !OwnedBy(current, hub, -1) || !OwnedBy(current, point, hub) || + !OwnedBy(previous, oldHub, -1) || !OwnedBy(previous, oldPoint, oldHub) || + current.Block(point) is not { } node || Point(current, point) is not { } position || + Id(node, "OwnedPointCell", "m_ownerId") != hub || + Ids(node, "ForeignElemRef", "m_id").Any(id => id != -1) || + Ids(node, "GeomRef", "m_elemId") is not [-1, var host] || + Ids(node, "GeomRef", "m_geomTag") is not [-1, var sourceTag] || + Ids(node, "GeomRef", "m_subTag") is not [-1, -1] || + Ids(node, "GeomRef", "m_ownerDBViewId") is not [-1, -1] || + Ids(node, "GeomRef", "m_flags") is not [0, 0] || + Ids(node, "GeomRef", "m_isLazyRef") is not [0, 0] || + node.Captures.Any(c => c is { DeclaringClass: "GeomRef", Field: "m_intermediateTags" } && c.Integer != 0) || + !oldReferences.TryGetValue(host, out long restoredHost)) return null; + long legacyTag; + if (FindSlot(node, current, "PointOnCurveElementData", out _) && + Id(node, "PointLocationOnCurve", "m_measurementType") == 2 && + Id(node, "PointLocationOnCurve", "m_measureFrom") == 1 && + Reals(node, "PointLocationOnCurve", "m_measurementValue") is [>= 0 and <= 1 and var fraction]) + { + var edge = TaggedEdge(current, host, sourceTag); + if (edge is null || !CoordinatesAgree(position, edge.At(fraction)) || + previous.Block(restoredHost, 103) is not { } geometry || + GeometryTags(geometry).Where(c => EdgesAgree(edge, ReadEdge(previous.Walker, geometry, c.QueueIndex))) + .ToArray() is not [var matched]) return null; + if (current.Class(host) == "AnalyticalMember" && + (edge.Arc is not null || current.Block(host) is not { } modern || + previous.Block(restoredHost) is not { } legacy || + !CoordinatesAgree([.. edge.Start, .. edge.End], Axis(current, modern, "AnalyticalMember", "m_oCurve")) || + !CoordinatesAgree([.. edge.Start, .. edge.End], Axis(previous, legacy, "AnalyticalCurveCell", "m_oAdjustCurve")))) + return null; + legacyTag = matched.Integer; + } + else if (current.Class(host) == "AnalyticalPanel" && + FindSlot(node, current, "PointOnFaceRef", out _) && + current.Block(host, 103) is { } sourceGeometry && previous.Block(restoredHost, 103) is { } targetGeometry && + FindSlot(sourceGeometry, current, "Face", out int sourceFace) && + FindSlot(targetGeometry, previous, "Face", out int targetFace)) + { + var from = FacePlane(sourceGeometry, sourceFace); + var to = FacePlane(targetGeometry, targetFace); + if (from.Length != 10 || !CoordinatesAgree(from, to) || + !CoordinatesAgree(position, Reals(node, "PointOnFaceRef", "m_xyzPt")) || + Reals(node, "PointOnFaceRef", "m_uv") is not [var u, var v] || + !CoordinatesAgree(position, Enumerable.Range(0, 3).Select(i => from[i] + u * from[i + 3] + v * from[i + 6]).ToArray()) || + GeometryTags(sourceGeometry).SingleOrDefault(c => c.QueueIndex == sourceFace).Integer != sourceTag || + GeometryTags(targetGeometry).Where(c => c.QueueIndex == targetFace).ToArray() is not [var matched]) + return null; + legacyTag = matched.Integer; + } + else return null; + var tags = node.Captures.Where(c => c is { DeclaringClass: "GeomRef", Field: "m_geomTag" }).ToArray(); + if (tags is not [_, { Offset: >= 0 } tag]) return null; + + // Keep the current point, its constraint and its cache. Only the IDs and the target curve's tag change. + var preserved = new byte[3][]; + for (int channel = 101; channel <= 103; channel++) + { + if (current.Block(point, channel) is not { } block) return null; + var data = current.Records[point][channel - 101].ToArray(); + foreach (var reference in block.Captures.Where(c => c.IsElementId && c.Integer > 0)) + { + if (oldReferences.ContainsKey(reference.Integer)) peers.Add(PanelOrSelf(reference.Integer)); + else if (!IsRetained(reference.Integer)) return null; + } + RemapIds(data, block, oldReferences, sourceWidth); + if (channel == 102) + { + WriteInt(data, tag, legacyTag); + if (!UseLegacyPointCells(data, block)) return null; + } + if (transcoder.Payload(data, 0, data.Length, out _) is not { } payload || previous.Decode(payload) is null) return null; + preserved[channel - 101] = payload; + } + var result = previous.Decode(preserved[1])!; + if (Ids(result, "GeomRef", "m_elemId") is not [-1, var target] || target != restoredHost || + Id(result, "OwnedPointCell", "m_ownerId") != hub || + Ids(result, "GeomRef", "m_geomTag") is not [-1, var writtenTag] || writtenTag != legacyTag) + return null; + return new(oldHub, oldPoint, hub, point, restoredHost, preserved); + } + + static bool OwnedBy(Snapshot snapshot, long id, long owner) => + snapshot.Rows.TryGetValue(id, out var row) && row.PartitionId == 0 && row.OwningId == owner; + + bool UseLegacyPointCells(byte[] data, WideBlockWalker.Walk block) + { + foreach (var cell in block.Captures.Where(c => c is { DeclaringClass: "CellList", Field: "m_cells", TargetQueueIndex: not null })) + { + if (!sourceClasses.TryGetValue((int)cell.Integer, out var derived)) return false; + string? expected = derived.Name switch + { + "HubOwnedPointCellEx" => "HubOwnedPointCell", + "AnalyticalLevelAssociationCell" => "LevelAssociationCell", + "AnalyticalReferencePointGridNetTrackerCell" => "ReferencePointGridNetTrackerCell", + _ => null, + }; + if (expected is null) continue; + if (cell.Offset < 0 || derived.Fields.Any(f => f.Stored) || + !sourceClasses.TryGetValue(derived.Base, out var parent) || parent.Name != expected) return false; + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(cell.Offset), checked((ushort)parent.Id)); + } + return true; + } + + bool MatchSupport(long id, long source, long old, bool line, double[] axis, + WideBlockWalker.Walk modern, WideBlockWalker.Walk legacy, + out long instance) + { + instance = Id(modern, "BoundaryConditions", "m_instanceId"); + long end = Id(modern, "LinearSubPick", "m_subTag"); + if (!SameElement(id) || !SameElement(instance) || current.Class(instance) != "FamilyInstance" || + previous.Class(instance) != "FamilyInstance" || previous.Rows[instance].OwningId != id || + !dropped.Contains((ulong)instance) || Id(legacy, "BoundaryConditions", "m_instanceId") != instance || + !Ids(modern, "ElemPick", "m_elemId").SequenceEqual([source]) || + !Ids(legacy, "ElemPick", "m_elemId").SequenceEqual([old]) || + Id(modern, "BoundaryConditions", "m_type") != (line ? 1 : 0) || + Ids(modern, "ForeignElemRef", "m_id").Any(value => value != -1) || + Ids(legacy, "ForeignElemRef", "m_id").Any(value => value != -1)) return false; + if (line) + { + long tag = Id(legacy, "ElemPick", "m_tags"); + if (!WholeEdgePick(modern) || !WholeEdgePick(legacy) || Id(legacy, "ElemPick", "m_type") != 1 || + TaggedEdge(previous, old, tag) is not { } edge || + !EdgesAgree(edge, TaggedEdge(previous, id, 0)) || !EdgesAgree(edge, TaggedEdge(current, id, 0))) + return false; + long pick = Id(modern, "ElemPick", "m_type"); + if (pick == 1) + { + if (!EdgesAgree(edge, TaggedEdge(current, source, Id(modern, "ElemPick", "m_tags")))) return false; + } + else if (pick != 0 || Ids(modern, "ElemPick", "m_tags").Length != 0 || + !MatchesOpeningEdge(source, old, tag, edge)) return false; + } + else if (end is not (0 or 1) || Id(legacy, "LinearSubPick", "m_subTag") != end || + Point(current, id) is not { } point || !CoordinatesAgree(point, axis.Skip(3 * (int)end).Take(3).ToArray()) || + !SamePoint(current, id, previous, id)) return false; + return CaptureValues(modern, "BoundaryConditions", "m_instanceId") + .SequenceEqual(CaptureValues(legacy, "BoundaryConditions", "m_instanceId")) && + CaptureValues(modern, "LoadBCBase", "m_oPick").SequenceEqual(CaptureValues(legacy, "LoadBCBase", "m_oPick")) && + Parameters(modern).SequenceEqual(Parameters(legacy)); + } + + bool MatchesOpeningEdge(long source, long old, long tag, DirectedEdge edge) + { + // Revit upgrades an opening-edge pick to a panel pick with no geometry tag. + if (current.Class(source) != "AnalyticalPanel" || + (generatedSlabs.GetValueOrDefault(old)?.Body ?? previous.Block(old)) is not { } archived) return false; + var original = Contours(previous, archived, "AnalyticalSurfaceCell", "m_adjustedLoops").Skip(1) + .SelectMany(loop => loop).Where(e => e.Tag == tag).Take(2).ToArray(); + if (original is not [var restoredEdge] || !EdgesAgree(edge, restoredEdge)) return false; + return openingPanels.Where(pair => pair.Value == source) + .SelectMany(pair => Contours(current, current.Block(pair.Key)!, "AnalyticalSurfaceBase", "m_contourLoops")) + .SelectMany(loop => loop).Where(e => EdgesAgree(edge, e)).Take(2).Count() == 1; + } + + bool TryConvertLineSupport(long id, long source, long old, long physical, WideBlockWalker.Walk support, + WideBlockWalker.Walk legacyPanel, out long instance) + { + instance = Id(support, "BoundaryConditions", "m_instanceId"); + if (instance <= 0 || previous.Rows.ContainsKey(id) || previous.Rows.ContainsKey(instance) || + previous.Records.ContainsKey(id) || previous.Records.ContainsKey(instance) || + !dropped.Contains((ulong)id) || !dropped.Contains((ulong)instance) || + !OwnedBy(current, id, -1) || !OwnedBy(current, instance, id) || + current.Class(instance) != "FamilyInstance" || current.Block(instance) is not { } marker || + Id(marker, "InsertableInst", "m_hostId") != id || + Id(support, "BoundaryConditions", "m_type") != 1 || !WholeEdgePick(support) || + !Ids(support, "ElemPick", "m_elemId").SequenceEqual([source]) || + Ids(support, "ForeignElemRef", "m_id").Any(value => value != -1) || + TaggedEdge(current, id, 0) is not { } edge) return false; + + long panel = PanelOrSelf(source); + long pick = Id(support, "ElemPick", "m_type"); + var legacyLoops = Contours(previous, legacyPanel, "AnalyticalSurfaceCell", "m_adjustedLoops"); + bool inner = source != panel || pick == 0; + var matches = (inner ? legacyLoops.Skip(1) : legacyLoops.Take(1)).SelectMany(loop => loop) + .Where(candidate => EdgesAgree(edge, candidate)).Take(2).ToArray(); + if (matches is not [{ Tag: >= 0 and var tag }] || + !EdgesAgree(edge, TaggedEdge(previous, generatedSlabs.GetValueOrDefault(old)?.Geometry ?? previous.Block(old, 103), tag))) + return false; + if (pick == 1) + { + if (!EdgesAgree(edge, TaggedEdge(current, source, Id(support, "ElemPick", "m_tags")))) return false; + } + else if (pick != 0 || source != panel || Ids(support, "ElemPick", "m_tags").Length != 0 || + !MatchesOpeningEdge(panel, old, tag, edge)) return false; + + var map = new Dictionary { [source] = old, [panel] = old }; + if (ConvertRecords(id) is not { } supportParts || ConvertRecords(instance) is not { } markerParts || + previous.Decode(supportParts[1]) is not { } converted || + RewriteEdgePick(supportParts[1], converted, tag) is not { } body || + previous.Decode(body) is not { } bound || + Id(bound, "ElemPick", "m_elemId") != old || Id(bound, "ElemPick", "m_type") != 1 || + Id(bound, "ElemPick", "m_tags") != tag || !WholeEdgePick(bound) || + Id(bound, "BoundaryConditions", "m_instanceId") != instance || + !SameFields("BoundaryConditions", "m_instanceId") || !SameFields("LoadBCBase", "m_oPick") || + !Parameters(bound).SequenceEqual(Parameters(support)) || + previous.Decode(supportParts[0]) is not { } decodedHeader || + RewriteParents(supportParts[0], decodedHeader, "m_regenOnly", + ids => ids.Append(checked((int)physical)).Distinct().Order()) is not { } header) return false; + + newElementRecords.Add(id, [header, body, supportParts[2]]); + newElementRecords.Add(instance, markerParts); + return true; + + bool SameFields(string type, string exclude) + { + var fields = CaptureValues(bound, type, exclude).ToArray(); + var keys = fields.Select(field => field.Key).ToHashSet(StringComparer.Ordinal); + return fields.SequenceEqual(CaptureValues(support, type, exclude).Where(field => keys.Contains(field.Key))); + } + + byte[][]? ConvertRecords(long owner) + { + var result = new byte[3][]; + for (int i = 0; i < result.Length; i++) + { + if (current.Block(owner, i + 101) is not { } walk) return null; + var bytes = current.Records[owner][i].ToArray(); + RemapIds(bytes, walk, map, sourceWidth); + if (supportTranscoder.Value.Payload(bytes, 0, bytes.Length, out _) is not { } convertedBytes || + previous.Decode(convertedBytes) is null) return null; + result[i] = convertedBytes; + } + return result; + } + } + + bool TryBindHost(long host, long settingsHost, long model, string dataClass, out byte[] header, out byte[] body) + { + header = []; + body = []; + var oldParts = previous.Records[settingsHost]; + var oldOwner = previous.Block(settingsHost)!; + if (Id(oldOwner, "AnalyticalSettingsCell", "m_enableAnalyticalModel") != 1 || + !FindSlot(oldOwner, previous, "AnalyticalSettingsCell", out int settingsSlot)) return false; + var sourceParts = current.Records[host]; + if (transcoder.Payload(sourceParts[0], 0, sourceParts[0].Length, out _) is not { } head || + transcoder.Payload(sourceParts[1], 0, sourceParts[1].Length, out _) is not { } data || + previous.Decode(head) is not { } convertedHeader || previous.Decode(data) is not { } convertedBody || + Id(convertedBody, dataClass, "m_analyticalModelId") != -1 || + !FindSlot(convertedBody, previous, dataClass, out int userDataSlot) || + !FindSlot(convertedBody, previous, "CellList", out int cellListSlot) || + Ids(convertedBody, "AnalyticalSettingsCell", "m_enableAnalyticalModel").Length != 0) return false; + var cell = convertedBody.Captures.FirstOrDefault(c => + c.QueueIndex == cellListSlot && c.Field == "m_cells" && c.TargetQueueIndex is not null); + if (cell.TargetQueueIndex is not int firstSlot || + FindField(data, convertedBody, userDataSlot, "m_analyticalModelId") is not { } idField || + idField.End - idField.Start != sizeof(int) || + FindField(data, convertedBody, cellListSlot, "m_cells") is not { } listField) return false; + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(idField.Start), checked((int)model)); + int start = listField.Start, first = convertedBody.QueueStart[firstSlot]; + int count = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(start)); + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(start), checked(count + 1)); + int settingsAt = oldOwner.QueueStart[settingsSlot]; + var settings = oldParts[1].AsSpan(settingsAt, End(oldOwner, settingsSlot) - settingsAt); + body = [.. data.AsSpan(0, start + 4), .. BitConverter.GetBytes(uint.MaxValue), + .. BitConverter.GetBytes((ushort)oldOwner.Queue[settingsSlot]), .. data.AsSpan(start + 4, first - start - 4), + .. settings, .. data.AsSpan(first)]; + header = RewriteParents(head, convertedHeader, "m_deletion", ids => ids.Append(checked((int)model)).Distinct().Order()) ?? []; + return header.Length != 0 && previous.Decode(header) is not null && previous.Decode(body) is { } bound && + Id(bound, dataClass, "m_analyticalModelId") == model && + Id(bound, "AnalyticalSettingsCell", "m_enableAnalyticalModel") == 1; + } + + byte[]? RewriteParents(byte[] bytes, WideBlockWalker.Walk walk, string field, Func, IEnumerable> update) + { + if (!FindSlot(walk, previous, "ElementParents", out int slot) || + FindField(bytes, walk, slot, field) is not { } range || + range.End - range.Start < 4) return null; + var values = System.Runtime.InteropServices.MemoryMarshal.Cast(bytes.AsSpan(range.Start, range.End - range.Start)); + if (values[0] != values.Length - 1) return null; + var result = update(values[1..].ToArray()).ToArray(); + return [.. bytes.AsSpan(0, range.Start), .. BitConverter.GetBytes(result.Length), + .. System.Runtime.InteropServices.MemoryMarshal.AsBytes(result.AsSpan()), .. bytes.AsSpan(range.End)]; + } + + (int Start, int End)? FindField(byte[] bytes, WideBlockWalker.Walk walk, int slot, string field) + => PayloadSpan.Find(bytes, walk.QueueStart[slot], End(walk, slot), targetSchema, walk.Queue[slot], field); + } + + private static int End(WideBlockWalker.Walk w, int slot) => slot + 1 < w.QueueStart.Count ? w.QueueStart[slot + 1] : w.Position; + + private static bool FindSlot(WideBlockWalker.Walk walk, Snapshot snapshot, string kind, out int slot) + { + slot = -1; + for (int i = 0; i < walk.Queue.Count; i++) + { + if (snapshot.Walker.Class(walk.Queue[i])?.Name != kind) continue; + if (slot >= 0) return false; + slot = i; + } + return slot >= 0; + } + + private static long[] Ids(WideBlockWalker.Walk w, string cls, string field) => w.Captures + .Where(c => c.DeclaringClass == cls && c.Field == field && c.Kind == WideBlockWalker.CaptureKind.Integer && !c.Key.EndsWith('#')) + .Select(c => c.Integer).ToArray(); + + private static long Id(WideBlockWalker.Walk w, string cls, string field) => Ids(w, cls, field) is [var id] ? id : long.MinValue; + + private static bool WholeEdgePick(WideBlockWalker.Walk w) => + w.Captures.Where(c => c is { DeclaringClass: "ElemPick", Field: "m_subPick" }).ToArray() switch + { + [{ Integer: 0, TargetQueueIndex: null }] => true, + [{ TargetQueueIndex: int slot }] => w.Captures.Any(c => + c.QueueIndex == slot && c is { DeclaringClass: "LinearSubPick", Field: "m_subTag", Integer: -1 }), + _ => false, + }; + + private static byte[]? RewriteEdgePick(byte[] body, WideBlockWalker.Walk w, long tag) + { + var kind = w.Captures.SingleOrDefault(c => c is { DeclaringClass: "ElemPick", Field: "m_type", Offset: >= 0 }); + var tags = w.Captures.Where(c => c is { DeclaringClass: "ElemPick", Field: "m_tags", Offset: >= 0 }).ToArray(); + if (kind.Field is null || tags.Length == 0 || + !tags[0].Key.EndsWith('#') || tags[0].Integer != tags.Length - 1) return null; + WriteInt(body, kind, 1); + if (tags is [_, var oldTag]) + { + WriteInt(body, oldTag, tag); + return body; + } + if (tags is not [var count]) return null; + return [.. body.AsSpan(0, count.Offset), .. BitConverter.GetBytes(1), .. BitConverter.GetBytes(checked((int)tag)), + .. body.AsSpan(count.Offset + sizeof(int))]; + } + + private static double[] Reals(WideBlockWalker.Walk w, string cls, string field) => w.Captures + .Where(c => c.DeclaringClass == cls && c.Field == field && c.Kind == WideBlockWalker.CaptureKind.Real).Select(c => c.Real).ToArray(); + + private static IEnumerable<(string Key, long Integer, double Real, string? Text)> CaptureValues( + WideBlockWalker.Walk block, string cls, string exclude) + => block.Captures.Where(c => c.DeclaringClass == cls && c.Field != exclude && c.Kind != WideBlockWalker.CaptureKind.PointerClass) + .Select(c => (c.Key, c.Integer, c.Real, c.Text)); + + private static IEnumerable<(long Id, double Value)> Parameters(WideBlockWalker.Walk w) => + Ids(w, "ParamValueInt", "m_paramId").Zip(Ids(w, "ParamValueInt", "m_value"), (id, v) => (id, (double)v)) + // The legacy generic preset can retain its default; the actual m_preset is checked separately. + .Where(pair => pair.id != (int)BuiltInParameter.BOUNDARY_PARAM_PRESET + || Id(w, "BoundaryConditions", "m_preset") == long.MinValue) + .Concat(Ids(w, "ParamValueDouble", "m_paramId").Zip(Reals(w, "ParamValueDouble", "m_value"))) + .OrderBy(p => p.Item1); + + private static bool SameReleases(WideBlockWalker.Walk member, WideBlockWalker.Walk legacy) + { + if (member.Captures.Any(c => c.DeclaringClass == "AnalyticalMemberForcesCell" && c.Kind == WideBlockWalker.CaptureKind.Real && c.Real != 0) + || legacy.Captures.Any(c => c.DeclaringClass == "MemberForcesCell" && c.Kind == WideBlockWalker.CaptureKind.Real && c.Real != 0)) + return false; + string[] fields = ["m_releaseType", "m_Fx", "m_Fy", "m_Fz", "m_Mx", "m_My", "m_Mz"]; + var from = Ids(member, "AnalyticalReleaseConditionsCell", "m_start"); + var to = Ids(legacy, "StructRelease", "m_bTopOrStart"); + if (from is not [1L, 0L] || to is not [0L, 1L]) return false; + return fields.All(f => Ids(member, "AnalyticalReleaseConditionsCell", f) is [var start, var end] + && Ids(legacy, "StructRelease", f).SequenceEqual([end, start])); + } + + private static bool SameTransform(WideBlockWalker.Walk a, WideBlockWalker.Walk b) + { + static double[] Basis(WideBlockWalker.Walk w) + { + int? slot = w.Captures.FirstOrDefault(c => c is { DeclaringClass: "Instance", Field: "m_pInstanceInfo", + QueueIndex: -1, TargetQueueIndex: not null }).TargetQueueIndex; + return w.Captures.Where(c => c.QueueIndex == slot && c.Kind == WideBlockWalker.CaptureKind.Real && + c.Key.StartsWith(WideBlockWalker.AllItemsKeyPrefix + "Trf.m_3x3@", StringComparison.Ordinal)).Select(c => c.Real).ToArray(); + } + return Basis(a) is { Length: 9 } x && Basis(b) is { Length: 9 } y && x.SequenceEqual(y); + } + + private static double[] Axis(Snapshot snapshot, WideBlockWalker.Walk w, string cls, string field) + { + int? slot = w.Captures.FirstOrDefault(c => c.DeclaringClass == cls && c.Field == field).TargetQueueIndex; + return slot is int curve ? Line(snapshot.Walker, w, curve) : []; + } + + private static DirectedEdge? CurveEdge(Snapshot snapshot, WideBlockWalker.Walk w, string cls, string field) => + w.Captures.FirstOrDefault(c => c.DeclaringClass == cls && c.Field == field).TargetQueueIndex is int curve + ? ReadEdge(snapshot.Walker, w, curve) : null; + + internal sealed record CircularArc(double[] Center, double[] Radial, double[] Tangent, double Radius, double Sweep) + { + internal double[] At(double fraction) + { + double angle = fraction * Sweep; + return Enumerable.Range(0, 3).Select(i => + Center[i] + Radius * (Radial[i] * Math.Cos(angle) + Tangent[i] * Math.Sin(angle))).ToArray(); + } + } + + internal sealed record DirectedEdge(double[] Start, double[] End, CircularArc? Arc = null, long Tag = -1) + { + internal double[] At(double fraction) => Arc?.At(fraction) ?? Start.Zip(End, (a, b) => a + fraction * (b - a)).ToArray(); + } + + internal static bool LoopsAgree(DirectedEdge[] a, DirectedEdge[] b) => + a.Length != 0 && a.Length == b.Length && + Enumerable.Range(0, b.Length).Any(start => Enumerable.Range(0, a.Length) + .All(i => EdgesAgree(a[i], b[(start + i) % b.Length]))); + + private static bool EdgesAgree(DirectedEdge a, DirectedEdge? b) + { + if (b is null || !CoordinatesAgree(a.Start, b.Start) || !CoordinatesAgree(a.End, b.End)) return false; + if (a.Arc is not { } x) return b.Arc is null; + return b.Arc is { } y && CoordinatesAgree(x.Center, y.Center) && + Math.Abs(x.Radius - y.Radius) <= 1e-7 && + Math.Abs(x.Sweep - y.Sweep) * Math.Max(x.Radius, y.Radius) <= 1e-7 && + CoordinatesAgree(x.Tangent.Zip(y.Tangent, (u, v) => (u - v) * x.Radius).ToArray(), [0, 0, 0]); + } + + internal sealed record SlabPlacement(double Scale, double[] Shift) + { + internal double[] Point(double[] point) => point.Zip(Shift, (value, origin) => value * Scale + origin).ToArray(); + + internal DirectedEdge Edge(DirectedEdge edge) => edge with + { + Start = Point(edge.Start), + End = Point(edge.End), + Arc = edge.Arc is { } arc ? arc with { Center = Point(arc.Center), Radius = arc.Radius * Scale } : null, + }; + } + + internal static SlabPlacement? FindSlabPlacement(DirectedEdge[][] template, List current) + { + // shortcut: planar slabs with a matching prototype under translation and uniform positive scale. + if (template.Length == 0 || template.Length != current.Count || + current[0].FirstOrDefault(edge => edge.Arc is not null) is not { Arc: { } targetArc } target) + return null; + foreach (var edge in template[0].Where(edge => edge.Arc is not null)) + { + double scale = targetArc.Radius / edge.Arc!.Radius; + if (!(scale > 0 && double.IsFinite(scale))) continue; + var placement = new SlabPlacement(scale, target.Start.Zip(edge.Start, (a, b) => a - b * scale).ToArray()); + if (SlabLoopsAgree(template.Select(loop => loop.Select(placement.Edge).ToArray()).ToArray(), current)) + return placement; + } + return null; + } + + private static bool SlabLoopsAgree(DirectedEdge[][] template, List current) + { + if (template.Length == 0 || template.Length != current.Count || !LoopsAgree(template[0], current[0])) + return false; + var holes = template.Skip(1).ToList(); + foreach (var loop in current.Skip(1)) + { + if (holes.Where(hole => LoopsAgree(hole, loop)).Take(2).ToArray() is not [var match]) return false; + holes.Remove(match); + } + return true; + } + + private static bool SamePanelSection(WideBlockWalker.Walk panel, WideBlockWalker.Walk type, long material) + { + long index = Id(type, "CompoundStructure", "m_structuralMaterialLayerIndex"); + var materials = Ids(type, "CompoundStructureLayer", "m_materialId"); + var widths = Reals(type, "CompoundStructureLayer", "m_layerWidth"); + var functions = Ids(type, "CompoundStructureLayer", "m_layerFunction"); + const long structuralLayer = 1; + return Id(type, "CompoundStructure", "m_variableLayerIdx") == -1 && + index >= 0 && index < materials.Length && materials[index] == material && + functions.Length == materials.Length && widths.Length == functions.Length && + Reals(panel, "AnalyticalPanel", "m_thickness") is [> 0 and var thickness] && + Math.Abs(thickness - widths.Where((_, i) => functions[i] == structuralLayer).Sum()) <= 1e-7; + } + + private static DirectedEdge? SketchEdge(Snapshot snapshot, long id) => + snapshot.Block(id) is { } body && + body.Captures.Where(c => c is { DeclaringClass: "CurveDriver", Field: "m_pCrv", TargetQueueIndex: not null }) + .ToArray() is [{ TargetQueueIndex: int curve }] + ? ReadEdge(snapshot.Walker, body, curve) : null; + + private static bool SketchEdgesAgree(DirectedEdge edge, DirectedEdge? other) => + EdgesAgree(edge, other) || other is not null && (edge.Arc is null) == (other.Arc is null) && + CoordinatesAgree(edge.Start, other.End) && CoordinatesAgree(edge.End, other.Start) && + CoordinatesAgree(edge.At(0.5), other.At(0.5)); + + private static bool PlaceSlabGeometry(byte[] bytes, WideBlockWalker.Walk walk, WideBlockWalker walker, + SlabPlacement placement, bool surface) + { + foreach (var capture in walk.Captures.Where(field => field.Kind == WideBlockWalker.CaptureKind.Real)) + { + double value = capture.Real; + switch (capture) + { + case { DeclaringClass: "GLine", Field: "m_origin" }: + case { DeclaringClass: "GArc", Field: "m_center" }: + case { DeclaringClass: "Plane", Field: "m_origin" }: + case { DeclaringClass: "GPoint", Field: "m_coord" }: + case { DeclaringClass: "Trf", Field: "m_or" }: + case { DeclaringClass: "Outline", Key: var key } when key.Contains(".m_minmax@"): + case { DeclaringClass: "GRep", Field: "", Key: var box } when box.Contains(".m_bBox@") || + box.Contains(".m_tightbBox@"): + int axis = capture.Key[^1] - '0'; + if (axis is < 0 or > 2) return false; + value = value * placement.Scale + placement.Shift[axis]; + break; + case { DeclaringClass: "GArc", Field: "m_radius" }: + case { DeclaringClass: "EdgePnt", Field: "" }: + value *= placement.Scale; + break; + case { DeclaringClass: "GCurve", Field: "m_endParams", QueueIndex: >= 0 } when + walker.Class(walk.Queue[capture.QueueIndex])?.Name == "GLine": + value *= placement.Scale; + break; + case { DeclaringClass: "Envelope", Field: "", QueueIndex: >= 0 } + when surface && !walk.Captures.Any(field => field.TargetQueueIndex == capture.QueueIndex && + field is { DeclaringClass: "AnalyticalSurfaceCell", Field: "m_oProjectionPlane" }): + value *= placement.Scale; + break; + case { DeclaringClass: "Envelope" or "XYZ" or "std::pair< int, XYZ >" or "PointElement" or "Trf" or "Plane" or "GArc" or "GLine" or "GCurve" }: + continue; + default: + return false; + } + if (capture.Offset < 0 || !double.IsFinite(value)) return false; + BinaryPrimitives.WriteDoubleLittleEndian(bytes.AsSpan(capture.Offset), value); + } + return true; + } + + private static DirectedEdge[][] Contours(Snapshot snapshot, WideBlockWalker.Walk w, string cls, string field) + { + var loops = new List(); + foreach (var entry in w.Captures.Where(c => c.DeclaringClass == cls && c.Field == field && !c.Key.EndsWith('#'))) + { + if (entry.TargetQueueIndex is not int slot || + !w.Captures.Any(c => c.QueueIndex == slot && c is { DeclaringClass: "CurveLoop", Field: "m_open", Integer: 0 })) + return []; + var edges = new List(); + foreach (var curve in w.Captures.Where(c => c.QueueIndex == slot && c is + { DeclaringClass: "CurveLoop", Field: "m_curves" } && !c.Key.EndsWith('#'))) + { + if (curve.TargetQueueIndex is not int index || ReadEdge(snapshot.Walker, w, index) is not { } edge) return []; + var tags = GeometryTags(w).Where(c => c.QueueIndex == index).Take(2).ToArray(); + edges.Add(edge with { Tag = tags is [var tag] ? tag.Integer : -1 }); + } + if (edges.Count == 0 || edges.Where((edge, i) => !CoordinatesAgree(edge.End, edges[(i + 1) % edges.Count].Start)).Any()) + return []; + loops.Add([.. edges]); + } + return [.. loops]; + } + + private static IEnumerable GeometryTags(WideBlockWalker.Walk w) => + w.Captures.Where(c => c is { DeclaringClass: "GInfo", Field: "m_tag", QueueIndex: >= 0, Integer: >= 0 }); + + private static DirectedEdge? TaggedEdge(Snapshot snapshot, long id, long tag) + => TaggedEdge(snapshot, snapshot.Block(id, 103), tag); + + private static DirectedEdge? TaggedEdge(Snapshot snapshot, WideBlockWalker.Walk? block, long tag) + => block is not null && + GeometryTags(block).Where(c => c.Integer == tag).ToArray() is [var matched] + ? ReadEdge(snapshot.Walker, block, matched.QueueIndex) : null; + + private static DirectedEdge? ReadEdge(WideBlockWalker walker, WideBlockWalker.Walk w, int slot) + { + if (Line(walker, w, slot) is { Length: 6 } line) + return line.All(double.IsFinite) && !line[..3].SequenceEqual(line[3..]) ? new(line[..3], line[3..]) : null; + // shortcut: straight edges and bounded circular arcs, extend for other curve types. + if (walker.Class(w.Queue[slot])?.Name != "GArc" || + Values("m_endParams") is not [var start, var end] || Values("m_center") is not { Length: 3 } center || + Values("m_xVec") is not { Length: 3 } x || Values("m_yVec") is not { Length: 3 } y || + Values("m_radius") is not [> 0 and var radius] || !double.IsFinite(radius)) return null; + double sweep = Math.Abs(end - start); + if (!(sweep > 0 && sweep <= 2 * Math.PI + 1e-10)) return null; + double cos = Math.Cos(start), sin = Math.Sin(start), direction = Math.Sign(end - start); + var arc = new CircularArc(center, x.Zip(y, (a, b) => a * cos + b * sin).ToArray(), + x.Zip(y, (a, b) => direction * (b * cos - a * sin)).ToArray(), radius, sweep); + return new(arc.At(0), arc.At(1), arc); + + double[] Values(string name) => w.Captures.Where(c => c.QueueIndex == slot && c.Field == name && + c.Kind == WideBlockWalker.CaptureKind.Real).Select(c => c.Real).ToArray(); + } + + private static double[] FacePlane(WideBlockWalker.Walk geometry, int face) + { + var surface = geometry.Captures.FirstOrDefault(c => c.QueueIndex == face && + c is { DeclaringClass: "Face", Field: "m_pSurf" }).TargetQueueIndex; + if (surface is not int slot) return []; + return geometry.Captures.Where(c => c.QueueIndex == slot && c.DeclaringClass == "Plane") + .Select(c => c.Real).Concat(geometry.Captures.Where(c => c.QueueIndex == slot && + c is { DeclaringClass: "Surface", Field: "m_orientFlag" }).Select(c => (double)c.Integer)).ToArray(); + } + + private static double[] Line(WideBlockWalker walker, WideBlockWalker.Walk w, int slot) + { + if (walker.Class(w.Queue[slot])?.Name != "GLine") return []; + double[] Values(string name) => w.Captures.Where(c => c.QueueIndex == slot && c.Field == name && + c.Kind == WideBlockWalker.CaptureKind.Real).Select(c => c.Real).ToArray(); + if (Values("m_endParams") is not [var start, var end] || Values("m_origin") is not { Length: 3 } origin || + Values("m_dirVec") is not { Length: 3 } direction) return []; + return [.. origin.Zip(direction, (o, d) => o + start * d), .. origin.Zip(direction, (o, d) => o + end * d)]; + } + + private static bool HasHalfTurnSymmetry(Snapshot snapshot, WideBlockWalker.Walk member) + { + int? profile = member.Captures.FirstOrDefault(c => + c is { DeclaringClass: "AnalyticalMember", Field: "m_oCrossSectionProfile" }).TargetQueueIndex; + if (profile is null) return false; + var edges = member.Captures.Where(c => c.QueueIndex == profile && c.DeclaringClass == "CurveLoop" && + c.Field == "m_curves" && c.TargetQueueIndex is not null) + .Select(c => ReadEdge(snapshot.Walker, member, c.TargetQueueIndex!.Value)).ToArray(); + return IsHalfTurnSymmetric(edges); + } + + internal static bool IsHalfTurnSymmetric(IReadOnlyList edges) + { + static double[] Flip(double[] p) => [p[0], -p[1], -p[2]]; + return edges.Count >= 2 && edges.All(edge => edge is not null && edges.Any(partner => EdgesAgree( + new DirectedEdge(Flip(edge.Start), Flip(edge.End), edge.Arc is { } arc + ? new CircularArc(Flip(arc.Center), Flip(arc.Radial), Flip(arc.Tangent), arc.Radius, arc.Sweep) + : null), partner))); + } + + private static void RemapIds(byte[] bytes, WideBlockWalker.Walk block, IReadOnlyDictionary map, int width) + { + foreach (var id in block.Captures) + { + if (!id.IsElementId || !map.TryGetValue(id.Integer, out long replacement)) continue; + if (width == sizeof(long)) BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(id.Offset), replacement); + else WriteInt(bytes, id, replacement); + } + } + + private static bool IsGeometryOwner(WideBlockWalker.Capture field, long id) => + field is { QueueIndex: -1, DeclaringClass: "GInfo", Field: "m_tag", Offset: >= 0 } && field.Integer == id; + + private static void WriteInt(byte[] bytes, WideBlockWalker.Capture field, long value) + => BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(field.Offset), checked((int)value)); + + private static double[]? Point(Snapshot snapshot, long id) + => snapshot.Block(id, 101) is { } walk ? DowngradeAnalytics.PointFromHeader(walk) : null; + + private static bool SamePoint(Snapshot current, long id, Snapshot previous, long old) + => Point(current, id) is { } a && Point(previous, old) is { } b && CoordinatesAgree(a, b); + + private static bool CoordinatesAgree(double[] a, double[] b) + => a.Length == b.Length && a.Zip(b, (x, y) => Math.Abs(x - y) <= 1e-7).All(ok => ok); + + private static void AddRows(Snapshot previous, SchemaDocument targetSchema, Dictionary replacements, long[] added, + IReadOnlySet fromCurrent, byte[]? currentTable, IReadOnlyDictionary generatedOwners) + { + const string elemPath = "Global/ElemTable", incrementPath = "Global/DocumentIncrementTable"; + var schema = new FormatsSchema(targetSchema); + if (!replacements.TryGetValue(elemPath, out var stored) || + PagedGzipStream.Decompress(stored) is not { } bytes || + ElemTableLayout.TryParse(bytes, schema) is not { } rows || + !replacements.TryGetValue(incrementPath, out var incrementStored) || + PagedGzipStream.Decompress(incrementStored) is not { } increments || + DocumentIncrementTable.TryParse(increments, schema, out _) is not { Local: { Count: > 0 } } document || + rows.Count == 0 || rows.Any(row => row.PartitionId != 0)) + throw new InvalidDataException("Cannot register legacy analytical elements in the target partition."); + + var selected = added.ToHashSet(); + int width = previous.RowWidth; + int offset = ElemTableLayout.HeaderLength; + var current = currentTable is null ? [] : ElemTableLayout.TryParse(currentTable, schema) + ?? throw new InvalidDataException("Cannot read the current element rows."); + var merged = rows.Select((r, i) => (r.Id, Bytes: bytes.AsMemory(offset + i * width, width))) + .Concat(previous.Rows.Keys.Order().Select((id, i) => (Id: id, Index: i)) + .Where(row => selected.Contains(row.Id) && !fromCurrent.Contains(row.Id)) + .Select(row => (row.Id, Bytes: previous.Table.AsMemory(offset + row.Index * width, width)))) + .Concat(current.Select((row, i) => (row.Id, Index: i)).Where(row => fromCurrent.Contains(row.Id)) + .Select(row => (row.Id, Bytes: currentTable!.AsMemory(offset + row.Index * width, width)))) + .OrderBy(row => row.Id).ToArray(); + long maxAllowed = current.Count == 0 ? rows[^1].Id : current[^1].Id; + if (merged.Length != rows.Count + added.Length || merged[^1].Id > maxAllowed) + throw new InvalidDataException("Legacy analytical records exceed the current identifier range."); + var updated = new byte[checked(bytes.Length + added.Length * width)]; + bytes.AsSpan(0, offset).CopyTo(updated); + BinaryPrimitives.WriteInt32LittleEndian(updated.AsSpan(sizeof(ushort)), merged.Length); + foreach (var row in merged) + { + row.Bytes.Span.CopyTo(updated.AsSpan(offset)); + if (generatedOwners.TryGetValue(row.Id, out long owner) && + !ElemTableLayout.TrySetLegacyOwner(updated.AsSpan(offset, width), schema, owner)) + throw new InvalidDataException("Cannot bind the generated legacy panel to its physical owner."); + offset += width; + } + bytes.AsSpan(ElemTableLayout.HeaderLength + rows.Count * width).CopyTo(updated.AsSpan(offset)); + if (ElemTableLayout.TryParse(updated, schema)?.Count != merged.Length) + throw new InvalidDataException("The restored element table could not be verified."); + replacements[elemPath] = PagedStreamCodec.Reencode(stored, updated); + replacements[incrementPath] = PagedStreamCodec.Reencode(incrementStored, DocumentIncrementFixup.RefreshTotals( + increments, targetSchema, checked((uint)(document.Local[^1].TotalElements + added.Length)))); + } +} diff --git a/src/RvtIO/Writing/LegacyElectricalStyle.cs b/src/RvtIO/Writing/LegacyElectricalStyle.cs new file mode 100644 index 00000000..6b2b710e --- /dev/null +++ b/src/RvtIO/Writing/LegacyElectricalStyle.cs @@ -0,0 +1,133 @@ +using System.Buffers.Binary; +using RvtIO.BuiltIns; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// Restores the projection style that Revit 2020 expects for internal electrical circuits. +internal static class LegacyElectricalStyle +{ + private const int Category = (int)BuiltInCategory.OST_ElectricalInternalCircuits; + private const int Projection = 1; + private const int StyleEntrySize = 3 * sizeof(int); + + internal sealed record Addition(string PartitionPath, uint Owner, byte[][] Payloads); + + internal static Addition? Restore( + SchemaDocument doc, Dictionary replacements, IReadOnlySet partitionPaths) + { + const string latestPath = "Global/Latest", elemPath = "Global/ElemTable", incrementPath = "Global/DocumentIncrementTable"; + if (!replacements.TryGetValue(latestPath, out var latestStored) + || PagedGzipStream.Decompress(latestStored) is not { } latest + || QueuedField(latest, doc, "CategoryTracking", "m_gstyleData", readEntities: true) is not { } styles) + return null; + + var schema = new FormatsSchema(doc); + if (schema.Get("GStyleDataItem")?.Fields.Select(f => f.Name).SequenceEqual( + ["m_categoryId", "m_gstyleType", "m_gstyleId"]) != true + || styles.End - styles.Start < sizeof(int)) + throw new InvalidDataException("Unexpected graphics style table layout."); + + int count = BinaryPrimitives.ReadInt32LittleEndian(latest.AsSpan(styles.Start)); + int first = styles.Start + sizeof(int), insert = styles.End, existing = -1; + if (count < 0 || styles.End - first != (long)count * StyleEntrySize) + throw new InvalidDataException("Invalid graphics style table count."); + for (int at = first; at < styles.End; at += StyleEntrySize) + { + int category = BinaryPrimitives.ReadInt32LittleEndian(latest.AsSpan(at)); + int type = BinaryPrimitives.ReadInt32LittleEndian(latest.AsSpan(at + sizeof(int))); + if (category == Category && type == Projection) + { + if (existing >= 0) throw new InvalidDataException("Duplicate internal electrical circuit projection style."); + existing = at; + } + if (insert == styles.End && (category > Category || (category == Category && type > Projection))) + insert = at; + } + + if (!replacements.TryGetValue(elemPath, out var elemStored) + || PagedGzipStream.Decompress(elemStored) is not { } elem + || ElemTableLayout.TryParse(elem, schema) is not { } rows) + throw new InvalidDataException("Missing element table for the internal electrical circuit style."); + if (existing >= 0 && rows.Any(r => r.Id == BinaryPrimitives.ReadInt32LittleEndian(latest.AsSpan(existing + 2 * sizeof(int))))) + return null; + + if (!replacements.TryGetValue(incrementPath, out var incrementStored) + || PagedGzipStream.Decompress(incrementStored) is not { } increments + || DocumentIncrementTable.TryParse(increments, schema, out _, allowUnpairedHistory: true) is not { Local: { Count: > 0 } } table) + throw new InvalidDataException("Missing active document increment for the internal electrical circuit style."); + string partition = FormattableString.Invariant($"Partitions/{table.Local.Count - 1}"); + if (!partitionPaths.Contains(partition)) + throw new InvalidDataException("The active document increment has no partition for the internal electrical circuit style."); + + if (ElemTableLayout.RowLength(schema) != 7 * sizeof(int) + || schema.Get("ElemRec") is not { Version: 10 } + || QueuedField(elem, doc, "IdentifierSource", "m_last") is not { } allocator + || allocator.End - allocator.Start != sizeof(int)) + throw new InvalidDataException("Unexpected element identifier allocation layout."); + int last = BinaryPrimitives.ReadInt32LittleEndian(elem.AsSpan(allocator.Start)); + int id = checked((int)(Math.Max(last, rows.Count == 0 ? 0 : rows[^1].Id) + 1)); + int episode = checked((int)table.Local[^1].Greatest); + + byte[] styleEntry = Integers(Category, Projection, id); + byte[] registered = existing >= 0 + ? [.. latest.AsSpan(0, existing), .. styleEntry, .. latest.AsSpan(existing + StyleEntrySize)] + : [.. latest.AsSpan(0, insert), .. styleEntry, .. latest.AsSpan(insert)]; + if (existing < 0) + BinaryPrimitives.WriteInt32LittleEndian(registered.AsSpan(styles.Start), checked(count + 1)); + + int rowEnd = ElemTableLayout.HeaderLength + rows.Count * 7 * sizeof(int); + byte[] row = Integers(id, id, episode, episode, episode, 0, -1); + byte[] withRow = [.. elem.AsSpan(0, rowEnd), .. row, .. elem.AsSpan(rowEnd)]; + BinaryPrimitives.WriteInt32LittleEndian(withRow.AsSpan(sizeof(ushort)), rows.Count + 1); + BinaryPrimitives.WriteInt32LittleEndian(withRow.AsSpan(allocator.Start + row.Length), id); + byte[][] payloads = CreatePayloads(doc, schema, id); + + replacements[latestPath] = PagedStreamCodec.Reencode(latestStored, registered); + replacements[elemPath] = PagedStreamCodec.Reencode(elemStored, withRow); + replacements[incrementPath] = PagedStreamCodec.Reencode(incrementStored, + DocumentIncrementFixup.RefreshTotals(increments, doc, checked((uint)(table.Local[^1].TotalElements + 1)))); + return new Addition(partition, (uint)id, payloads); + } + + internal static (int Start, int End)? QueuedField(byte[] data, SchemaDocument doc, string name, string field, bool readEntities = false) + { + if (data.Length < sizeof(ushort) || doc.Classes.FirstOrDefault(c => c.Name == name) is not { } type) + return null; + var walker = new WideBlockWalker(doc, (_, _) => null, []) { StepBudget = 16L * data.Length + 65536 }; + if (readEntities && EntitySchemaReader.Read(data, doc) is { } entities) + walker.UseEntitySchemas(entities, passUnknown: true); + var walk = walker.Run(data, 0, data.Length, BinaryPrimitives.ReadUInt16LittleEndian(data)); + int slot = walk.Queue.IndexOf(type.Id); + if (slot < 0 || !walk.RootRead || walk.Error is not null) return null; + int end = slot + 1 < walk.QueueStart.Count ? walk.QueueStart[slot + 1] : walk.Position; + return PayloadSpan.Find(data, walk.QueueStart[slot], end, doc, type.Id, field); + } + + private static byte[][] CreatePayloads(SchemaDocument doc, FormatsSchema schema, int id) + { + ushort Tag(string name) => checked((ushort)(schema.IdOf(name) + ?? throw new InvalidDataException($"Missing class {name} for the internal electrical circuit style."))); + ushort header = Tag("ElementHeader"), style = Tag("GStyleElem"), dummy = Tag("SerializedDummy"); + // A document-owned style has no view, bounding box, geometry or regeneration history. + byte[] headerBody = [.. BitConverter.GetBytes(header), + .. Integers(0, -1, -1, -1, -1, -1, -1, unchecked((int)0xFFFF8000), 0x0400200E), + .. BitConverter.GetBytes(style), .. Integers(0, -1), .. BitConverter.GetBytes(Tag("ElementParents")), + .. Integers(1, id, 0, 0, 0, 0, 0, 0, 0), 0]; + byte[] styleBody = [.. BitConverter.GetBytes(style), + .. Integers(0, 0, 0, 0, 0, 0, 0, 0, 1, id, -1, -1, -1, -1, -1, -1, -1), 0, 0, 0, + .. Integers(-1), .. BitConverter.GetBytes(Tag("GStyle")), .. Integers(Category, -1, Projection, 1, 0, -1, -1), 0]; + var walker = new WideBlockWalker(doc, (_, _) => null, []); + if (!walker.Run(headerBody, 0, headerBody.Length, header).Exact || !walker.Run(styleBody, 0, styleBody.Length, style).Exact) + throw new InvalidDataException("The default internal electrical circuit style does not fit the target schema."); + return [headerBody, styleBody, BitConverter.GetBytes(dummy)]; + } + + private static byte[] Integers(params int[] values) + { + var bytes = new byte[sizeof(int) * values.Length]; + for (int i = 0; i < values.Length; i++) + BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(i * sizeof(int)), values[i]); + return bytes; + } +} diff --git a/src/RvtIO/Writing/LegacyProjectDefaults.cs b/src/RvtIO/Writing/LegacyProjectDefaults.cs new file mode 100644 index 00000000..9ee958bf --- /dev/null +++ b/src/RvtIO/Writing/LegacyProjectDefaults.cs @@ -0,0 +1,226 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// Registers the legacy document settings missing from projects created in a newer template. +internal static class LegacyProjectDefaults +{ + private const string Latest = "Global/Latest", ElemTable = "Global/ElemTable", Increments = "Global/DocumentIncrementTable"; + private static readonly (int Slot, string Class)[] AnalyticalSettings = + [ + (6, "AnalyticalSupportTracker"), (12, "AnalyticalSetTracker"), (13, "AnalyticalAutofixTracker"), + (14, "AnalyticalOctreeTracker"), + ]; + private static readonly (int Slot, string Class) WireSizes = (55, "RbsWireSizesElem"); + private static readonly HashSet OutOfDate = ["m_outOfDate", "m_bOutOfDate"]; + + internal sealed record Addition(string PartitionPath, DowngradePartitionRewriter.Addition[] Elements); + + internal static Addition? Restore(string profilePath, SchemaDocument doc, + Dictionary replacements, IReadOnlySet partitionPaths, int targetRelease) + { + (int Slot, string Class)[] settings = targetRelease switch + { + 2020 => [.. AnalyticalSettings, WireSizes, (76, "LynxTracker")], + 2021 or 2022 or 2023 => [.. AnalyticalSettings, WireSizes, (80, "ForgeConnectionTracker")], + _ => [WireSizes], + }; + var added = RestoreSettings(profilePath, doc, replacements, partitionPaths, settings); + return added ?? (targetRelease is >= 2021 and <= 2023 + ? RestoreSettings(profilePath, doc, replacements, partitionPaths, [WireSizes]) + : null); + } + + private static Addition? RestoreSettings(string profilePath, SchemaDocument doc, + Dictionary replacements, IReadOnlySet partitionPaths, (int Slot, string Class)[] settings) + { + var schema = new FormatsSchema(doc); + if (ElemTableLayout.IdWidth(schema) is not int width) return null; + var defaultClasses = settings.Select(s => s.Class).ToHashSet(StringComparer.Ordinal); + defaultClasses.UnionWith(["RbsWireMaterialType", "RbsWireInsulationType", "RbsWireTemperatureRatingType"]); + int lastSlot = settings.Max(s => s.Slot); + if (!replacements.TryGetValue(Latest, out var latestStored) + || PagedGzipStream.Decompress(latestStored) is not { } latest + || Registry(latest, doc, width, lastSlot) is not int registry) + return null; + + if (!replacements.TryGetValue(ElemTable, out var stored) + || PagedGzipStream.Decompress(stored) is not { } elem + || ElemTableLayout.TryParse(elem, schema) is not { } rows) + return null; + var existing = rows.Select(row => row.Id).ToHashSet(); + var missing = settings.Where(s => !existing.Contains(ReadSlot(latest, registry, s.Slot, width))).ToArray(); + if (missing.Length == 0) return null; + + using var profile = RootStorage.OpenRead(profilePath); + var profileLatest = PagedGzipStream.Read(profile, "Global", "Latest"); + if (profileLatest is null || Registry(profileLatest, doc, width, lastSlot) is not int profileRegistry) + return null; + + var mapped = new Dictionary(); + var pending = new Dictionary(); + foreach (var (slot, type) in settings) + { + long id = ReadSlot(profileLatest, profileRegistry, slot, width); + long current = ReadSlot(latest, registry, slot, width); + if (id <= 0) continue; + if (existing.Contains(current)) mapped.Add(id, current); + else pending.Add(id, type); + } + if (pending.Count == 0) return null; + var profileRows = ElemTableLayout.TryParse(PagedGzipStream.Read(profile, "Global", "ElemTable") ?? [], schema); + if (profileRows is null) return null; + var independent = profileRows.Where(r => r.OwningId <= 0).Select(r => r.Id).ToHashSet(); + + var tags = PartitionFraming.TagsOf(schema) ?? throw new InvalidDataException("Missing legacy partition markers."); + var records = new Dictionary(); + var ambiguous = new HashSet(); + var partitions = profile.OpenStorage("Partitions"); + foreach (var entry in partitions.EnumerateEntries().Where(e => e.Type == EntryType.Stream)) + { + using var stream = partitions.OpenStream(entry.Name); + byte[] raw = new byte[checked((int)stream.Length)]; + stream.ReadExactly(raw); + if (!PartitionFraming.Walk(raw, tags, width, record => + { + if (record.Block != 0 || record.Body.Length < 2 || record.Owner > long.MaxValue + || !independent.Contains((long)record.Owner)) return; + long id = (long)record.Owner; + if (!records.TryGetValue(id, out var bodies)) records.Add(id, bodies = new byte[3][]); + if (bodies[record.Channel - 101] is not null) + ambiguous.Add(id); + else bodies[record.Channel - 101] = record.Body.ToArray(); + }, out var failure, out _)) + throw new InvalidDataException($"Cannot read legacy settings from the target profile: {failure}."); + } + + var walker = new WideBlockWalker(doc, (c, f) => WideBlockWalker.AllItemsKeyPrefix + c.Name + "." + f.Name, []); + var prune = new R22Transcoder(doc, doc, width); + var dependencies = new Dictionary>(); + var queue = pending.Keys.ToList(); + for (int i = 0; i < queue.Count; i++) + { + long id = queue[i]; + if (ambiguous.Contains(id) || !records.TryGetValue(id, out var bodies) || bodies.Any(b => b is null) + || walker.Class(BitConverter.ToUInt16(bodies[1]))?.Name is not { } type + || !defaultClasses.Contains(type) || (pending.TryGetValue(id, out var expected) && type != expected)) + return null; // The profile contains project data outside the standalone settings group. + var references = new List<(byte[], WideBlockWalker.Capture)>(); + for (int channel = 0; channel < bodies.Length; channel++) + { + var payload = bodies[channel]; + var walk = walker.Run(payload, 0, payload.Length, BitConverter.ToUInt16(payload)); + if (!walk.Exact) return null; + if (type is "AnalyticalSupportTracker" or "AnalyticalSetTracker" or "AnalyticalAutofixTracker" or "AnalyticalOctreeTracker") + { + // A tracker copied into another document must discard references to the profile's model. + var external = ElementReferences(walk, id).Where(f => f.Integer != id && + !pending.ContainsKey(f.Integer) && !mapped.ContainsKey(f.Integer)) + .Select(f => (ulong)f.Integer).ToHashSet(); + if (external.Count != 0) + { + prune.SetDroppedElementIds(external); + byte[]? pruned; + if (channel == 1 && doc.ById[BitConverter.ToUInt16(payload)] is { } tracker && + tracker.Fields.FirstOrDefault(f => f.Stored) is { } first && + PayloadSpan.Find(payload, 2, payload.Length, doc, tracker.Id, first.Name) is { } field) + { + pruned = [.. payload.AsSpan(0, field.Start), .. prune.DefaultOwnFields(tracker.Id, OutOfDate)]; + } + else pruned = prune.Payload(payload, 0, payload.Length, out _); + if (pruned is null) return null; + walk = walker.Run(pruned, 0, pruned.Length, BitConverter.ToUInt16(pruned)); + if (!walk.Exact || ElementReferences(walk, id).Any(f => external.Contains((ulong)f.Integer))) return null; + payload = bodies[channel] = pruned; + } + } + foreach (var field in ElementReferences(walk, id)) + { + references.Add((payload, field)); + if (!mapped.ContainsKey(field.Integer) && !queue.Contains(field.Integer)) queue.Add(field.Integer); + } + } + dependencies.Add(id, references); + } + + if (!replacements.TryGetValue(Increments, out var incrementStored) + || PagedGzipStream.Decompress(incrementStored) is not { } increments + || DocumentIncrementTable.TryParse(increments, schema, out _, allowUnpairedHistory: true) is not { Local: { Count: > 0 } } table + || ElemTableLayout.RowLength(schema) is not int rowSize || schema.Get("ElemRec") is not { } record + || LegacyElectricalStyle.QueuedField(elem, doc, "IdentifierSource", "m_last") is not { } allocator + || allocator.End - allocator.Start != width) + throw new InvalidDataException("Cannot register the legacy document settings."); + + string partition = FormattableString.Invariant($"Partitions/{table.Local.Count - 1}"); + if (!partitionPaths.Contains(partition)) throw new InvalidDataException("The active legacy settings partition is missing."); + long last = Math.Max(ReadId(elem, allocator.Start, width), rows.Count == 0 ? 0 : rows[^1].Id); + int episode = checked((int)table.Local[^1].Greatest); + foreach (long id in queue) mapped.Add(id, checked(++last)); + + foreach (long id in queue) + foreach (var (payload, field) in dependencies[id]) + WriteId(payload.AsSpan(field.Offset), mapped[field.Integer], field.IsElementId ? width : sizeof(int)); + + foreach (var (slot, _) in missing) + if (mapped.TryGetValue(ReadSlot(profileLatest, profileRegistry, slot, width), out long replacement)) + WriteId(latest.AsSpan(registry + sizeof(int) + width * slot), replacement, width); + + int idAt = Offset("m_id"); + int originalAt = Offset("m_history", "m_originalElementId"); + int createdAt = Offset("m_history", "m_creationDate"); + int modifiedAt = Offset("m_history", "m_lastModificationDate"); + int userModifiedAt = Offset("m_history", "m_lastUserModificationDate"); + int ownerAt = Offset("m_OwningElementId"); + int rowEnd = ElemTableLayout.HeaderLength + rows.Count * rowSize; + byte[] newRows = new byte[checked(queue.Count * rowSize)]; + for (int i = 0; i < queue.Count; i++) + { + long id = mapped[queue[i]]; + var row = newRows.AsSpan(i * rowSize, rowSize); + WriteId(row[idAt..], id, width); + WriteId(row[originalAt..], id, width); + BinaryPrimitives.WriteInt32LittleEndian(row[createdAt..], episode); + BinaryPrimitives.WriteInt32LittleEndian(row[modifiedAt..], episode); + BinaryPrimitives.WriteInt32LittleEndian(row[userModifiedAt..], episode); + WriteId(row[ownerAt..], -1, width); + } + byte[] registered = [.. elem.AsSpan(0, rowEnd), .. newRows, .. elem.AsSpan(rowEnd)]; + BinaryPrimitives.WriteInt32LittleEndian(registered.AsSpan(sizeof(ushort)), checked(rows.Count + queue.Count)); + WriteId(registered.AsSpan(allocator.Start + newRows.Length), last, width); + replacements[Latest] = PagedStreamCodec.Reencode(latestStored, latest); + replacements[ElemTable] = PagedStreamCodec.Reencode(stored, registered); + replacements[Increments] = PagedStreamCodec.Reencode(incrementStored, + DocumentIncrementFixup.RefreshTotals(increments, doc, checked((uint)(table.Local[^1].TotalElements + queue.Count)))); + return new Addition(partition, queue.Select(id => new DowngradePartitionRewriter.Addition((ulong)mapped[id], records[id])).ToArray()); + + int Offset(params string[] path) => ElemTableLayout.Offset(schema, record, path) + ?? throw new InvalidDataException($"Missing field {string.Join(".", path)} in the element table."); + } + + private static int? Registry(byte[] latest, SchemaDocument doc, int width, int lastSlot) + { + if (LegacyElectricalStyle.QueuedField(latest, doc, "UniqueElementsTracking", "m_elemIds", readEntities: true) is not { } span + || span.End - span.Start < sizeof(int)) + return null; + int count = BitConverter.ToInt32(latest, span.Start); + return count > lastSlot && span.End - span.Start == sizeof(int) + (long)width * count ? span.Start : null; + } + + private static long ReadSlot(byte[] latest, int registry, int slot, int width) + => ReadId(latest, registry + sizeof(int) + width * slot, width); + + private static IEnumerable ElementReferences(WideBlockWalker.Walk walk, long owner) + => walk.Captures.Where(f => f.Offset >= 0 && f.Integer > 0 && + (f.IsElementId || (f.DeclaringClass == "GInfo" && f.Field == "m_tag" && f.Integer == owner))); + + private static long ReadId(byte[] data, int offset, int width) + => width == sizeof(long) ? BitConverter.ToInt64(data, offset) : BitConverter.ToInt32(data, offset); + + private static void WriteId(Span data, long value, int width) + { + if (width == sizeof(long)) BinaryPrimitives.WriteInt64LittleEndian(data, value); + else BinaryPrimitives.WriteInt32LittleEndian(data, checked((int)value)); + } +} diff --git a/src/RvtIO/Writing/LegacySchemaCatalogs.cs b/src/RvtIO/Writing/LegacySchemaCatalogs.cs new file mode 100644 index 00000000..dcb51fb3 --- /dev/null +++ b/src/RvtIO/Writing/LegacySchemaCatalogs.cs @@ -0,0 +1,72 @@ +using System.Text; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// Uses the target release's built-in Forge catalogs and carries the project's custom definitions forward. +internal static class LegacySchemaCatalogs +{ + internal static byte[] Rewrite(byte[] source, byte[] profile, SchemaDocument doc) + { + foreach (string field in new[] { "m_storedParameterSchemas", "m_storedForgeSchemas" }) + { + if (LegacyElectricalStyle.QueuedField(source, doc, "ESSchemaStorage", field, readEntities: true) is not { } from) + continue; + var to = LegacyElectricalStyle.QueuedField(profile, doc, "ESSchemaStorage", field, readEntities: true) + ?? throw new InvalidDataException($"The target profile has no {field} catalog."); + var combined = Merge(source.AsSpan(from.Start, from.End - from.Start), + profile.AsSpan(to.Start, to.End - to.Start)); + source = [.. source.AsSpan(0, from.Start), .. combined, .. source.AsSpan(from.End)]; + } + return source; + } + + internal static byte[] Merge(ReadOnlySpan source, ReadOnlySpan profile) + { + var targetEntries = Read(profile); + var entries = Read(source).Where(entry => !IsBuiltIn(entry.Key)) + .Concat(targetEntries.Where(entry => IsBuiltIn(entry.Key))) + .OrderBy(entry => entry.Key, StringComparer.Ordinal).ToArray(); + using var output = new MemoryStream(); + using var writer = new BinaryWriter(output, Encoding.Unicode, leaveOpen: true); + writer.Write(entries.Length); + foreach (var (key, value) in entries) + { + WriteString(key); + WriteString(value); + } + return output.ToArray(); + + void WriteString(string value) + { + writer.Write(value.Length); + writer.Write(Encoding.Unicode.GetBytes(value)); + } + } + + private static bool IsBuiltIn(string key) => key.StartsWith("autodesk.", StringComparison.Ordinal); + + private static Dictionary Read(ReadOnlySpan data) + { + using var input = new MemoryStream(data.ToArray(), writable: false); + using var reader = new BinaryReader(input, Encoding.Unicode); + int count = reader.ReadInt32(); + if (count < 0 || count > (input.Length - input.Position) / (2 * sizeof(int))) + throw new InvalidDataException("Invalid Forge schema catalog count."); + var entries = new Dictionary(count, StringComparer.Ordinal); + for (int i = 0; i < count; i++) + if (!entries.TryAdd(ReadString(), ReadString())) + throw new InvalidDataException("Duplicate Forge schema identifier."); + if (input.Position != input.Length) + throw new InvalidDataException("Unexpected trailing bytes in the Forge schema catalog."); + return entries; + + string ReadString() + { + int chars = reader.ReadInt32(); + if (chars < 0 || chars > (input.Length - input.Position) / sizeof(char)) + throw new InvalidDataException("Invalid Forge schema catalog string."); + return Encoding.Unicode.GetString(reader.ReadBytes(chars * sizeof(char))); + } + } +} diff --git a/src/RvtIO/Writing/LegacyUnitFormats.cs b/src/RvtIO/Writing/LegacyUnitFormats.cs new file mode 100644 index 00000000..58afae0f --- /dev/null +++ b/src/RvtIO/Writing/LegacyUnitFormats.cs @@ -0,0 +1,109 @@ +using OpenMcdf; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class LegacyUnitFormats +{ + internal sealed record Edit(string Partition, ulong Owner, byte[] Body); + + internal static Edit? Prepare(string profilePath, SchemaDocument source, SchemaDocument profile, + PartitionFraming.Tags sourceTags, int sourceWidth, PartitionFraming.Tags profileTags, + IReadOnlyList<(string Path, byte[] Stored)> sourcePartitions, R22Transcoder transcoder, + IReadOnlySet dropped) + { + if (sourcePartitions.Count != 1 || + source.Classes.FirstOrDefault(c => c.Name == "AUnits")?.Fields.Any(f => f.Name == "m_formatOptionsMap") != true || + profile.Classes.FirstOrDefault(c => c.Name == "AUnits")?.Fields.Any(f => f is { Name: "m_formatOptionsArr", Type: 14, Mods: 81 }) != true || + source.Classes.FirstOrDefault(c => c.Name == "UnitsElem") is not { } sourceClass || + profile.Classes.FirstOrDefault(c => c.Name == "UnitsElem") is not { } profileClass) + return null; + + var (path, raw) = sourcePartitions[0]; + var element = FindUnits(raw, sourceTags, sourceWidth, sourceClass.Id); + if (element is not { } current || dropped.Contains(current.Owner) || + transcoder.Payload(current.Body, 0, current.Body.Length, out _) is not { } projected) + return null; + + using var storage = RootStorage.OpenRead(profilePath); + if (!storage.TryOpenStorage("Partitions", out var partitions)) return null; + var entries = partitions.EnumerateEntries().Where(e => e.Type == EntryType.Stream && + int.TryParse(e.Name, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out _)).ToArray(); + if (entries.Length != 1) return null; + using var stream = partitions.OpenStream(entries[0].Name); + var bytes = new byte[checked((int)stream.Length)]; + stream.ReadExactly(bytes); + var savedFormats = FindUnits(bytes, profileTags, sizeof(int), profileClass.Id); + return savedFormats is { } saved && Fill(profile, projected, saved.Body) is { } body + ? new(path, current.Owner, body) : null; + } + + private static (ulong Owner, byte[] Body)? FindUnits(byte[] partition, PartitionFraming.Tags tags, int width, int classId) + { + (ulong Owner, byte[] Body)? result = null; + bool repeated = false; + if (!PartitionFraming.Walk(partition, tags, width, record => + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort) || + BitConverter.ToUInt16(record.Body.Span) != classId) return; + if (result is not null) repeated = true; + else result = (record.Owner, record.Body.ToArray()); + }, out var error, out _)) + throw new InvalidDataException(error); + return repeated ? null : result; + } + + // Revit 2020 indexes the array even when the document is opened without Audit. + // The profile supplies only the display options, while the source retains its own UnitsElem and separators. + internal static byte[]? Fill(SchemaDocument schema, byte[] projected, byte[] saved) + { + var walker = new WideBlockWalker(schema, (c, f) => WideBlockWalker.AllItemsKeyPrefix + c.Name + "." + f.Name, []); + var current = walker.Run(projected, 0, projected.Length, BitConverter.ToUInt16(projected)); + var profile = walker.Run(saved, 0, saved.Length, BitConverter.ToUInt16(saved)); + if (!current.Exact || !profile.Exact || walker.Class(BitConverter.ToUInt16(projected))?.Name != "UnitsElem" || + BitConverter.ToUInt16(projected) != BitConverter.ToUInt16(saved)) return null; + var currentCount = Root(current, "m_formatOptionsArr#"); + var currentSystem = Root(current, "m_universalUnitSystem"); + var profileCount = Root(profile, "m_formatOptionsArr#"); + var profileSystem = Root(profile, "m_universalUnitSystem"); + if (currentCount is not { Integer: 0, Offset: >= 0 } empty || + currentSystem is not { } system || system.Offset != empty.Offset + sizeof(int) || + profileCount is not { Integer: > 0, Offset: >= 0 } populated || + profileSystem is not { } other || other.Integer != system.Integer) + return null; + + var entries = profile.Captures.Where(c => c.QueueIndex == -1 && c.DeclaringClass == "AUnits" && + c.Field == "m_formatOptionsArr" && c.TargetQueueIndex.HasValue).ToArray(); + if (entries.Length != populated.Integer || + other.Offset - populated.Offset != sizeof(int) + entries.Length * (sizeof(uint) + sizeof(ushort))) + return null; + int from = entries[0].TargetQueueIndex!.Value, end = from + entries.Length; + for (int i = from; i < end; i++) + { + var pointer = entries[i - from]; + if (pointer.TargetQueueIndex != i || walker.Class(profile.Queue[i])?.Name != "FormatOptions" || + profile.QueueCountAtStart[i] != profile.QueueEnd[i] || + BitConverter.ToUInt32(saved, pointer.Offset - sizeof(uint)) != uint.MaxValue) return null; + } + + int prefixQueueCount = current.Queue.Count == 0 ? 0 : current.QueueCountAtStart[0]; + var rootPointers = current.Captures.Where(c => c is { QueueIndex: -1, TargetQueueIndex: not null }).ToArray(); + if (!rootPointers.Select(p => p.TargetQueueIndex!.Value).SequenceEqual(Enumerable.Range(0, prefixQueueCount))) + return null; + int before = rootPointers.Count(p => p.Offset < empty.Offset); + int insertAt = before < current.Queue.Count ? current.QueueStart[before] : projected.Length; + int profileEnd = end < profile.Queue.Count ? profile.QueueStart[end] : saved.Length; + byte[] restored = [.. projected.AsSpan(0, empty.Offset), .. saved.AsSpan(populated.Offset, other.Offset - populated.Offset), + .. projected.AsSpan(system.Offset, insertAt - system.Offset), + .. saved.AsSpan(profile.QueueStart[from], profileEnd - profile.QueueStart[from]), .. projected.AsSpan(insertAt)]; + var check = walker.Run(restored, 0, restored.Length, BitConverter.ToUInt16(restored)); + return check.Exact && Root(check, "m_formatOptionsArr#")?.Integer == entries.Length ? restored : null; + } + + private static WideBlockWalker.Capture? Root(WideBlockWalker.Walk walk, string name) + { + var fields = walk.Captures.Where(c => c.QueueIndex == -1 && + c.Key == WideBlockWalker.AllItemsKeyPrefix + "AUnits." + name).ToArray(); + return fields.Length == 1 ? fields[0] : null; + } +} diff --git a/src/RvtIO/Writing/LegacyWireReferences.cs b/src/RvtIO/Writing/LegacyWireReferences.cs new file mode 100644 index 00000000..5f237c56 --- /dev/null +++ b/src/RvtIO/Writing/LegacyWireReferences.cs @@ -0,0 +1,117 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class LegacyWireReferences +{ + private static readonly (string Field, string Modern, string Legacy)[] Definitions = + [ + ("m_idMaterial", "RbsConductorMaterial", "RbsWireMaterialType"), + ("m_idTempratureRating", "RbsConductorTemperatureRating", "RbsWireTemperatureRatingType"), + ("m_idInsulation", "RbsConductorInsulationMaterial", "RbsWireInsulationType"), + ]; + + internal static Dictionary<(ulong, int), byte[]> Prepare( + SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, + byte[] partition, R22Transcoder transcoder, IReadOnlySet dropped) + { + var edits = new Dictionary<(ulong, int), byte[]>(); + var sourceWire = source.Classes.FirstOrDefault(c => c.Name == "RbsWireType"); + var targetWire = target.Classes.FirstOrDefault(c => c.Name == "RbsWireType"); + if (width != sizeof(long) || + sourceWire?.Fields.Any(f => f.Name == "m_idMaxConductorSize") != true || + targetWire?.Fields.Any(f => f.Name == "m_strMaxConductorSize") != true || + ElemTableLayout.IdWidth(new FormatsSchema(target)) != sizeof(int)) + return edits; + + var reader = new WideBlockWalker(source, Capture, []); + var targetReader = new WideBlockWalker(target, Capture, []); + var modern = new Dictionary(); + var legacy = new Dictionary(); + var wires = new Dictionary(); + var catalogues = new Dictionary(); + if (!PartitionFraming.Walk(partition, tags, width, record => + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort)) return; + int tag = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + var name = reader.Class(tag)?.Name; + bool isLegacy = Definitions.Any(d => d.Legacy == name); + if (name is not ("RbsWireType" or "RbsWireSizesElem" or "CustomElement") && !isLegacy) return; + + long id = unchecked((long)record.Owner); + bool omitted = dropped.Contains(record.Owner); + if (id <= 0 || (name == "CustomElement") != omitted) return; + byte[] body = record.Body.ToArray(); + if (name == "RbsWireType") + { + wires[record.Owner] = body; + return; + } + + var walk = reader.Run(body, 0, body.Length, tag); + if (!walk.Exact) return; + if (name == "RbsWireSizesElem") catalogues[record.Owner] = walk; + else if (isLegacy && Text(walk, "SymbolInfo", "m_name") is { Length: > 0 } legacyName) + legacy[id] = (name!, legacyName); + else if (name == "CustomElement" && walk.Queue.Select(t => reader.Class(t)?.Name).ToArray() + is ["CellList", string kind, "NamingCell"] && Definitions.Any(d => d.Modern == kind) && + Text(walk, "NamingCell", "m_name") is { Length: > 0 } modernName) + modern[id] = (kind, modernName); + }, out var error, out _)) + throw new InvalidDataException(error); + if (catalogues.Count != 1 || modern.Count == 0) return edits; + + var registered = catalogues.Values.Single().Captures + .Where(c => c.IsElementId && c.Integer > 0).Select(c => c.Integer).ToHashSet(); + foreach (var (owner, body) in wires) + { + var input = reader.Run(body, 0, body.Length, sourceWire.Id); + // shortcut: a separate conductor-size reference needs conversion to an inline size before rebinding it. + if (!input.Exact || WireId(input, "m_idMaxConductorSize") is not { Integer: <= 0 }) continue; + long[] ids = Definitions.Select(d => WireId(input, d.Field)?.Integer ?? -1).ToArray(); + if (!ids.Any(modern.ContainsKey)) continue; + long[] resolved = Definitions.Select((definition, i) => Resolve(ids[i], definition)).ToArray(); + if (resolved.Contains(0) || transcoder.Payload(body, 0, body.Length, out _) is not { } converted) continue; + + var output = targetReader.Run(converted, 0, converted.Length, targetWire.Id); + if (!output.Exact) continue; + var slots = Definitions.Select(d => WireId(output, d.Field)).ToArray(); + if (slots.Any(c => c is not { Offset: >= 0 }) || + Enumerable.Range(0, Definitions.Length).Any(i => slots[i]!.Value.Integer != (modern.ContainsKey(ids[i]) ? -1 : ids[i]))) + continue; + for (int i = 0; i < Definitions.Length; i++) + BinaryPrimitives.WriteInt32LittleEndian(converted.AsSpan(slots[i]!.Value.Offset), checked((int)resolved[i])); + edits.Add((owner, 102), converted); + } + return edits; + + long Resolve(long id, (string Field, string Modern, string Legacy) definition) + { + if (id <= 0 || legacy.GetValueOrDefault(id).Class == definition.Legacy) return id; + if (!modern.TryGetValue(id, out var entry) || entry.Class != definition.Modern) return 0; + var matches = legacy.Where(row => row.Value == (definition.Legacy, entry.Name) && registered.Contains(row.Key)) + .Select(row => row.Key).Take(2).ToArray(); + return matches.Length == 1 ? matches[0] : 0; + } + } + + private static string? Capture(SchemaClass c, SchemaField f) => c.Name switch + { + "RbsWireType" when f.Name == "m_idMaxConductorSize" || Definitions.Any(d => d.Field == f.Name) => f.Name, + "NamingCell" or "SymbolInfo" when f.Name == "m_name" => f.Name, + "std::pair< ElementId, RbsWireMaterialInfo >" when f.Name == "first" => "material", + "std::pair< ElementId, RbsWireTemperatureRatingInfo >" when f.Name == "first" => "rating", + "RbsWireTemperatureRatingInfo" when f.Name == "m_setInsulationIds" => WideBlockWalker.AllItemsKeyPrefix + f.Name, + _ => null, + }; + + private static string? Text(WideBlockWalker.Walk walk, string kind, string field) => + walk.Captures.FirstOrDefault(c => c.DeclaringClass == kind && c.Field == field && + c.Kind == WideBlockWalker.CaptureKind.Text).Text; + + private static WideBlockWalker.Capture? WireId(WideBlockWalker.Walk walk, string field) => + walk.Captures.Where(c => c.AtRoot && c.IsElementId && c.Key == field) + .Select(c => (WideBlockWalker.Capture?)c).FirstOrDefault(); + +} diff --git a/src/RvtIO/Writing/TagCellRewriter.cs b/src/RvtIO/Writing/TagCellRewriter.cs new file mode 100644 index 00000000..51c02bac --- /dev/null +++ b/src/RvtIO/Writing/TagCellRewriter.cs @@ -0,0 +1,399 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +/// +/// Moves the tagged-entities cell of an IndependentTag tag from its 2027 place to the +/// 2023 place. In 2027 the tag owns a CellList (Element.m_cellList) whose +/// TagReferencesWithLeaderCell holds the references as TagReferenceWithLeader +/// objects; in 2023 the references are TaggedElem objects of a TaggedEntitiesCell +/// stored inline in IndependentTag.m_taggedEntitiesCell and the cell list is null. The +/// rewriter builds that inline cell, converts the references with the tag class map, drops the +/// cell list from the queue and puts the converted tagged elements before the orientation cell. +/// +internal static class TagCellRewriter +{ + internal static Func? Create( + SchemaDocument sourceDoc, SchemaDocument targetDoc, IReadOnlyDictionary? entitySchemas, int sourceWidth) + { + var target = new FormatsSchema(targetDoc); + if (target.Get("IndependentTag") is not { } tag) + return null; + if (target.Get("RoomBoundingItem") is { Fields.Count: 2 } && + tag.Fields.Any(f => f.Name == "m_taggedElementId") && + sourceDoc.Classes.FirstOrDefault(c => c.Name == "FabricReinSpanSymbol") is { } fabricSymbol && + !sourceDoc.Classes.Any(c => c.Name == "IndependentTag" && c.Fields.Any(f => f.Name == "m_taggedElementId"))) + return (source, generic) => source.Length >= sizeof(ushort) && + BinaryPrimitives.ReadUInt16LittleEndian(source) == fabricSymbol.Id + ? RewriteFabricHost(source, generic, sourceDoc, targetDoc, entitySchemas, sourceWidth, fabricSymbol.Id) + : null; + if (tag.Fields.All(f => f.Name != "m_taggedEntitiesCell") || + target.Get("TaggedEntitiesCell") is not { } targetCell || + target.Get("TaggedElem") is not { } taggedElem) + return null; + if (sourceDoc.Classes.All(c => c.Name != "TagReferencesWithLeaderCell")) return null; + var transcoder = new R22Transcoder(sourceDoc, targetDoc, sourceWidth, entitySchemas, tagMapping: true); + var sourceWalker = new WideBlockWalker(sourceDoc, (d, f) => d.Name + "." + f.Name, []); + if (entitySchemas is not null) sourceWalker.UseEntitySchemas(entitySchemas, passUnknown: true); + var tags = sourceDoc.Classes.Where(c => sourceWalker.IsA(c.Id, "IndependentTag")).Select(c => c.Id).ToHashSet(); + return (source, generic) => source.Length >= sizeof(ushort) && tags.Contains(BinaryPrimitives.ReadUInt16LittleEndian(source)) + ? Rewrite(source, generic, sourceWalker, targetDoc, transcoder, targetCell, (ushort)taggedElem.Id) + : null; + } + + private static byte[]? Fail(string reason) => null; + + private static byte[]? Rewrite( + byte[] source, byte[] generic, WideBlockWalker sourceWalker, SchemaDocument targetDoc, R22Transcoder transcoder, + FormatsSchema.ClassDef targetCell, ushort taggedElemClass) + { + if (source.Length < 2 || generic.Length < 2) return Fail("short"); + int rootClass = BinaryPrimitives.ReadUInt16LittleEndian(source); + var sourceWalk = sourceWalker.Run(source, 0, source.Length, rootClass); + if (!sourceWalk.RootRead) return Fail("tag walk"); + + int cellAt = -1; + var referenceAt = new List(); + for (int i = 0; i < sourceWalk.Queue.Count; i++) + { + string? name = sourceWalker.Class(sourceWalk.Queue[i])?.Name; + if (name == "TagReferencesWithLeaderCell") cellAt = i; + else if (name == "TagReferenceWithLeader") referenceAt.Add(i); + } + if (cellAt < 0) return Fail("no tagged cell"); + if (referenceAt.Count == 0) return Fail("no references"); + + static long Value(WideBlockWalker.Walk walk, string key, long fallback) => + walk.Captures.Where(c => c.Key == key && c.Kind == WideBlockWalker.CaptureKind.Integer) + .Select(c => c.Integer).FirstOrDefault(fallback); + + if (Value(sourceWalk, "TagReferencesWithLeaderCell.m_targetToCategoryForAutoTagging#", 0) != 0) + return Fail("category map not empty"); + var leaderEnd = (uint)Value(sourceWalk, "TagReferencesWithLeaderCell.m_leaderEndCondition", 0); + if (leaderEnd != 0 && targetCell.Fields.All(f => f.Name != "m_leaderEndCondition")) + return Fail("leader end condition"); + uint leadersMode = (uint)Value(sourceWalk, "TagReferencesWithLeaderCell.m_leadersPresentationMode", 0); + byte mergeElbows = (byte)Value(sourceWalk, "TagReferencesWithLeaderCell.m_mergeElbows", 0); + + // the references, converted to the 2023 TaggedElem layout + var children = new List(); + var starts = sourceWalk.QueueStart; + foreach (int qi in referenceAt) + { + int start = starts[qi]; + int next = int.MaxValue; + foreach (int other in starts) if (other > start && other < next) next = other; + int end = next == int.MaxValue ? source.Length : next; + if (start < 2 || start >= end || end > source.Length) return Fail("reference range"); + var payload = new byte[2 + (end - start)]; + BinaryPrimitives.WriteUInt16LittleEndian(payload, (ushort)sourceWalk.Queue[qi]); + Buffer.BlockCopy(source, start, payload, 2, end - start); + var converted = transcoder.Payload(payload, 0, payload.Length, out string? failure); + if (converted is null) return Fail("TaggedElem: " + failure); + children.Add(converted); + } + + // the inline TaggedEntitiesCell + using var cell = new MemoryStream(); + WriteU32(cell, (uint)children.Count); + foreach (var _ in children) + { + WriteU32(cell, uint.MaxValue); + WriteU16(cell, taggedElemClass); + } + foreach (var field in targetCell.Fields.Where(f => f.Name != "m_taggedEntities")) + switch (field.Name) + { + case "m_targetToCategoryForAutoTagging": WriteU32(cell, 0); break; + case "m_leaderEndCondition": WriteU32(cell, leaderEnd); break; + case "m_leadersPresentationMode": WriteU32(cell, leadersMode); break; + case "m_mergeElbows": cell.WriteByte(mergeElbows); break; + default: return Fail("unrecognised tagged entities field"); + } + byte[] cellBytes = cell.ToArray(); + + int targetRoot = BinaryPrimitives.ReadUInt16LittleEndian(generic); + var targetWalker = new WideBlockWalker(targetDoc, (_, _) => null, []); + var targetWalk = targetWalker.Run(generic, 0, generic.Length, targetRoot); + int genericRootEnd = targetWalk.QueueStart.Count > 0 ? targetWalk.QueueStart[0] : generic.Length; + var cellSpan = PayloadSpan.Find(generic, 2, genericRootEnd, targetDoc, targetRoot, "m_taggedEntitiesCell"); + var cellListSpan = PayloadSpan.Find(generic, 2, genericRootEnd, targetDoc, targetRoot, "m_cellList"); + if (cellSpan is null) return Fail("no inline cell field"); + if (cellListSpan is null) return Fail("no cell list field"); + + // generic root with the inline cell and a null cell-list pointer + var root = new MemoryStream(genericRootEnd + cellBytes.Length); + int at = 0; + foreach (var (start, end, replacement) in new[] + { + (cellSpan.Value.Start, cellSpan.Value.End, cellBytes), + (cellListSpan.Value.Start, cellListSpan.Value.End, new byte[4]), + }.OrderBy(x => x.Start)) + { + if (start < at || end < start || end > genericRootEnd) return Fail("overlapping fields"); + root.Write(generic, at, start - at); + root.Write(replacement); + at = end; + } + root.Write(generic, at, genericRootEnd - at); + + // queue: the generic objects without the cell list, with the converted tagged elements + // inserted where the inline cell queues them (before the tag orientation cell, the next pointer field) + using var queue = new MemoryStream(); + int genericQueue = genericRootEnd; + var classNames = targetDoc.ById; + int cellListIndex = targetWalk.Queue.FindIndex(t => classNames.GetValueOrDefault(t)?.Name == "CellList"); + int cellListStart = cellListIndex >= 0 ? targetWalk.QueueStart[cellListIndex] : -1; + int cellListEnd = cellListIndex >= 0 + ? (cellListIndex + 1 < targetWalk.QueueStart.Count ? targetWalk.QueueStart[cellListIndex + 1] : generic.Length) + : -1; + int orientationIndex = targetWalk.Queue.FindIndex(t => classNames.GetValueOrDefault(t)?.Name == "TagOrientationCell"); + int insertAt = orientationIndex >= 0 ? targetWalk.QueueStart[orientationIndex] : generic.Length; + + void Copy(int from, int to) + { + if (to > from) queue.Write(generic, from, to - from); + } + + if (cellListIndex < 0) + { + Copy(genericQueue, insertAt); + foreach (var child in children) queue.Write(child, 2, child.Length - 2); + Copy(insertAt, generic.Length); + } + else if (cellListStart < insertAt) + { + Copy(genericQueue, cellListStart); + Copy(cellListEnd, insertAt); + foreach (var child in children) queue.Write(child, 2, child.Length - 2); + Copy(insertAt, generic.Length); + } + else + { + Copy(genericQueue, insertAt); + foreach (var child in children) queue.Write(child, 2, child.Length - 2); + Copy(insertAt, cellListStart); + Copy(cellListEnd, generic.Length); + } + + byte[] result = [.. root.ToArray(), .. queue.ToArray()]; + var check = new WideBlockWalker(targetDoc, (_, _) => null, []).Run(result, 0, result.Length, targetRoot); + if (!check.Exact || check.Error != null) return Fail("result walk: " + check.Error); + return result; + } + + private static byte[]? RewriteFabricHost(byte[] source, byte[] target, SchemaDocument sourceDoc, + SchemaDocument targetDoc, IReadOnlyDictionary? entitySchemas, int sourceWidth, + int tag) + { + var walker = new WideBlockWalker(sourceDoc, (_, _) => null, []); + if (entitySchemas is not null) walker.UseEntitySchemas(entitySchemas, passUnknown: true); + var walk = walker.Run(source, 0, source.Length, tag); + var references = walk.Queue.Select((id, i) => (Name: walker.Class(id)?.Name, Index: i)) + .Where(item => item.Name is "TaggedElem" or "TagReferenceWithLeader").ToArray(); + if (!walk.Exact || references.Length != 1) + return null; + var reference = references[0]; + int start = walk.QueueStart[reference.Index]; + int end = reference.Index + 1 < walk.QueueStart.Count ? walk.QueueStart[reference.Index + 1] : source.Length; + var host = PayloadSpan.Find(source, start, end, sourceDoc, walk.Queue[reference.Index], + reference.Name == "TaggedElem" ? "m_taggedId" : "m_referenceIdKey"); + if (reference.Name == "TagReferenceWithLeader" && host is { } key && + sourceDoc.Classes.FirstOrDefault(c => c.Name == "ReferenceIdKey") is { } keyType) + host = PayloadSpan.Find(source, key.Start, key.End, sourceDoc, keyType.Id, "m_hostOrLinkElemId"); + var material = PayloadSpan.Find(source, start, end, sourceDoc, walk.Queue[reference.Index], "m_materialElemId"); + if (host is not { } hostSpan || material is not { } materialSpan) + return null; + int targetTag = BinaryPrimitives.ReadUInt16LittleEndian(target); + if (PayloadSpan.Find(target, 2, target.Length, targetDoc, targetTag, "m_taggedElementId") is not { } targetHost || + PayloadSpan.Find(target, 2, target.Length, targetDoc, targetTag, "m_materialElemId") is not { } targetMaterial || + targetHost.End - targetHost.Start != 8 || targetMaterial.End - targetMaterial.Start != 8) + return null; + if (ReadLink(hostSpan, positiveHost: true) is not { } hostLink || + ReadLink(materialSpan, positiveHost: false) is not { } materialLink) + return null; + WriteLink(targetHost.Start, hostLink); + WriteLink(targetMaterial.Start, materialLink); + return target; + + (int Local, int Linked)? ReadLink((int Start, int End) from, bool positiveHost) + { + if (from.End - from.Start != 2 * sourceWidth) return null; + long local = Read(from.Start), linked = Read(from.Start + sourceWidth); + if ((positiveHost && local <= 0) || local is < -1 or > int.MaxValue || linked is < -1 or > int.MaxValue) + return null; + return ((int)local, (int)linked); + } + + void WriteLink(int offset, (int Local, int Linked) link) + { + BinaryPrimitives.WriteInt32LittleEndian(target.AsSpan(offset), link.Local); + BinaryPrimitives.WriteInt32LittleEndian(target.AsSpan(offset + sizeof(int)), link.Linked); + } + + long Read(int offset) => sourceWidth == 8 + ? BinaryPrimitives.ReadInt64LittleEndian(source.AsSpan(offset)) + : BinaryPrimitives.ReadInt32LittleEndian(source.AsSpan(offset)); + } + + private static void WriteU32(Stream s, uint value) + { + Span b = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, value); + s.Write(b); + } + + private static void WriteU16(Stream s, ushort value) + { + Span b = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(b, value); + s.Write(b); + } +} + +/// Byte spans of a named field at the root of a class object, by the class grammar. +internal static class PayloadSpan +{ + internal static List<(string Name, int Start, int End)> Fields(byte[] data, int start, int end, SchemaDocument doc, int classId) + { + var classes = doc.ById; + var list = new List<(string, int, int)>(); + int at = start; + foreach (var c in Chain(classes, classId)) + { + foreach (var f in c.Fields.Where(f => f.Stored)) + { + int from = at; + at = SkipField(data, at, end, classes, f); + if (at < 0 || at > end) return list; + list.Add((f.Name, from, at)); + } + } + return list; + } + + internal static (int Start, int End)? Find(byte[] data, int start, int end, SchemaDocument doc, int classId, string field) + { + var classes = doc.ById; + int at = start; + foreach (var c in Chain(classes, classId)) + { + foreach (var f in c.Fields.Where(f => f.Stored)) + { + int from = at; + at = SkipField(data, at, end, classes, f); + if (at < 0 || at > end) return null; + if (f.Name == field) return (from, at); + } + } + return null; + } + + private static List Chain(IReadOnlyDictionary classes, int classId) + { + var order = new List(); + for (int id = classId, guard = 0; id != 0 && guard < 64; guard++) + { + if (!classes.TryGetValue(id, out var c)) break; + order.Add(c); + id = c.Base; + } + order.Reverse(); + return order; + } + + private static int SkipField(byte[] d, int p, int end, IReadOnlyDictionary classes, SchemaField f) + { + int hi = f.Mods >> 4; + if (hi == 6) return SkipScalar(d, p, end, classes, f); + if (hi == 1) + { + for (int i = 0; i < (f.Fixed ?? 0); i++) p = SkipScalar(d, p, end, classes, f); + return p; + } + if (hi == 5) + { + if (p + 4 > end) return -1; + uint n = BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p, 4)); + if (n == 0xFFFFFFFF) n = 0; + p += 4; + if (f.Type is 1 or 2 && (f.Mods & 15) == 0) + { + if (p + (long)n > end) return -1; + return p + (int)n; + } + if (n > 5_000_000) return -1; + for (uint i = 0; i < n; i++) p = SkipScalar(d, p, end, classes, f); + return p; + } + return SkipScalar(d, p, end, classes, f); + } + + private static int SkipScalar(byte[] d, int p, int end, IReadOnlyDictionary classes, SchemaField f) + { + switch (f.Type) + { + case 1: case 2: return p + 1; + case 3: return p + 2; + case 4: case 5: case 6: return p + 4; + case 7: case 11: return p + 8; + case 10: return p + 2; + case 9: return p + 16; + case 8: + { + if (p + 4 > end) return -1; + uint len = BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p, 4)); + if (2L * len > end - p - 4) return -1; + return p + 4 + 2 * (int)len; + } + case 13: + { + if (f.Args is not { Count: 1 } args || args[0].Fixed is not int count) return -1; + var item = args[0] with { Mods = (byte)(args[0].Mods & 15) }; + for (int i = 0; i < count; i++) p = SkipScalar(d, p, end, classes, item); + return p; + } + case 14: + { + int lo = f.Mods & 15; + if (lo == 3) return p + 4; + if (lo is 1 or 2 or 4) + { + if (p + 4 > end) return -1; + uint handle = BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p, 4)); + p += 4; + if (handle != 0) + { + if (p + 2 > end) return -1; + p += 2; + } + return p; + } + if (f.Ref is int reference) + { + int at = p; + foreach (var c in Chain(classes, reference)) + { + foreach (var nested in c.Fields.Where(x => x.Stored)) + { + at = SkipField(d, at, end, classes, nested); + if (at < 0 || at > end) return -1; + } + } + return at; + } + if (p + 4 > end) return -1; + uint raw = BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p, 4)); + p += 4; + if (raw == 0xFFFFFFFF) + { + if (p + 2 > end) return -1; + p += 2; + } + return p; + } + default: return -1; + } + } +} diff --git a/tests/RvtIO.Tests/ArchiveContentsTests.cs b/tests/RvtIO.Tests/ArchiveContentsTests.cs new file mode 100644 index 00000000..ba4ebc61 --- /dev/null +++ b/tests/RvtIO.Tests/ArchiveContentsTests.cs @@ -0,0 +1,54 @@ +using System.Buffers.Binary; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class ArchiveContentsTests +{ + private static byte[] Header(uint version, byte marker = 0) + { + var bytes = new byte[12]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, ArchiveContents.Magic); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), version); + bytes[8] = marker; + return bytes; + } + + [Theory] + [InlineData(26u)] + [InlineData(31u)] + public void ForTarget_TakesTheProfileHeader_WhenItsVersionIsOlderOrEqual(uint targetVersion) + { + byte[] source = Header(31, 1); + byte[] profile = Header(targetVersion, 2); + + Assert.Same(profile, ArchiveContents.ForTarget(source, profile)); + } + + [Fact] + public void ForTarget_KeepsTheSourceHeader_WhenTheProfileIsNewer() + { + byte[] source = Header(26, 1); + byte[] profile = Header(27, 2); + + Assert.Same(source, ArchiveContents.ForTarget(source, profile)); + } + + [Fact] + public void ForTarget_WithoutAProfileHeader_KeepsTheSourceHeader() + { + byte[] source = Header(31); + Assert.Same(source, ArchiveContents.ForTarget(source, null)); + Assert.Null(ArchiveContents.ForTarget(null, Header(26))); + Assert.Null(ArchiveContents.ForTarget([1, 2, 3], Header(26))); + } + + [Fact] + public void TryReadVersion_RejectsForeignBytes() + { + Assert.False(ArchiveContents.TryReadVersion([0x62, 0x19, 0x22, 0x06, 0, 0, 0, 26], out _)); + Assert.True(ArchiveContents.TryReadVersion(Header(28), out uint version)); + Assert.Equal(28u, version); + } +} diff --git a/tests/RvtIO.Tests/DocumentIncrementFixupTests.cs b/tests/RvtIO.Tests/DocumentIncrementFixupTests.cs new file mode 100644 index 00000000..99827cbc --- /dev/null +++ b/tests/RvtIO.Tests/DocumentIncrementFixupTests.cs @@ -0,0 +1,33 @@ +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class DocumentIncrementFixupTests +{ + private static readonly byte[] Schema = RecordRoutingTests.Schema(); + + [Fact] + public void RefreshTotals_UpdatesOnlyTheCurrentLocalCountAndItsOwnVersion() + { + byte[] data = RecordRoutingTests.Table([(3, 7, [(-1, 7)]), (4, 5, [(-1, 5), (2, 4)])]); + var patched = DocumentIncrementFixup.RefreshTotals(data, TfSchemaReader.Parse(Schema), 6); + var schema = FormatsSchema.TryParse(Schema)!; + var before = DocumentIncrementTable.TryParse(data, schema, out _)!; + var after = DocumentIncrementTable.TryParse(patched, schema, out _)!; + + Assert.True(before.Increments.Zip(after.Increments).All(pair => pair.First.SameRouting(pair.Second))); + Assert.True(before.Local[0].SameRouting(after.Local[0])); + Assert.Equal(5, before.Local[^1].TotalElements); + Assert.Equal(6, after.Local[^1].TotalElements); + Assert.Equal([new(-1, 6), new(2, 4)], after.Local[^1].Versions); + } + + [Fact] + public void RefreshTotals_LeavesConsistentTableUntouched() + { + byte[] data = RecordRoutingTests.Table([(3, 7, [(-1, 7)])]); + Assert.Same(data, DocumentIncrementFixup.RefreshTotals(data, TfSchemaReader.Parse(Schema), 7)); + } +} diff --git a/tests/RvtIO.Tests/DowngradeAnalyticsTests.cs b/tests/RvtIO.Tests/DowngradeAnalyticsTests.cs new file mode 100644 index 00000000..5c021cbb --- /dev/null +++ b/tests/RvtIO.Tests/DowngradeAnalyticsTests.cs @@ -0,0 +1,422 @@ +using System.Text.Json; +using OpenMcdf; +using RvtIO.Cli; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class DowngradeAnalyticsTests +{ + [Fact] + public void Contours_MatchCyclicStartAndRejectDifferentArcsAndDirection() + { + var semicircle = new LegacyAnalyticalMembers.CircularArc([0, 0, 0], [1, 0, 0], [0, 1, 0], 1, Math.PI); + var arc = new LegacyAnalyticalMembers.DirectedEdge([1, 0, 0], [-1, 0, 0], semicircle); + var chord = new LegacyAnalyticalMembers.DirectedEdge([-1, 0, 0], [1, 0, 0]); + Assert.True(LegacyAnalyticalMembers.LoopsAgree([arc, chord], [chord, arc])); + Assert.Equal(1, arc.At(0.5)[1], 12); + Assert.False(LegacyAnalyticalMembers.LoopsAgree([arc, chord], + [chord, arc with { Arc = semicircle with { Tangent = [0, -1, 0] } }])); + Assert.False(LegacyAnalyticalMembers.LoopsAgree([arc, chord], + [chord, arc with { Arc = semicircle with { Sweep = 2 * Math.PI } }])); + Assert.False(LegacyAnalyticalMembers.LoopsAgree([arc, chord], + [chord, arc with { Arc = null }])); + Assert.False(LegacyAnalyticalMembers.LoopsAgree([arc, chord], + [arc with { Start = arc.End, End = arc.Start }, chord with { Start = chord.End, End = chord.Start }])); + } + + [SkippableFact] + public void LegacyRestoration_ClosesAGroupWithCurvedMembersAndRoundColumns() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_ROUND_COLUMNS_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_ROUND_COLUMNS_PROFILE"); + string output = TestFiles.Scratch("restored-round-columns.rvt"); + try + { + var original = ReadRows(source); + var result = DowngradeWriter.Write(source, profile, output, GuidRule.Exact, restoreLegacyAnalytics: true, allowLoss: true); + var written = ReadRows(output); + var points = result.RestoredPointSupports!; + Assert.NotEmpty(points); + Assert.False(result.OmittedProjectElements!.ContainsKey("BoundaryConditions")); + foreach (long point in points) + { + var marker = Assert.Single(original.Values, row => row.OwningId == point); + Assert.Equal(original[point].CreationDate, written[point].CreationDate); + Assert.Equal(marker.OriginalId, written[marker.Id].OriginalId); + Assert.Equal(marker.CreationDate, written[marker.Id].CreationDate); + Assert.Equal(point, written[marker.Id].OwningId); + } + } + finally + { + File.Delete(output); + } + } + + [Fact] + public void HalfTurnMatchesCircularButNotOffCenterSections() + { + var arc = new LegacyAnalyticalMembers.CircularArc([0, 0, 0], [0, 1, 0], [0, 0, 1], 1, Math.PI); + var opposite = arc with { Radial = [0, -1, 0], Tangent = [0, 0, -1] }; + LegacyAnalyticalMembers.DirectedEdge Edge(LegacyAnalyticalMembers.CircularArc curve) => + new(curve.At(0), curve.At(1), curve); + + Assert.True(LegacyAnalyticalMembers.IsHalfTurnSymmetric([Edge(arc), Edge(opposite)])); + Assert.False(LegacyAnalyticalMembers.IsHalfTurnSymmetric([Edge(arc), Edge(opposite with { Center = [0, .5, 0] })])); + } + + [SkippableFact] + public void LegacyRestoration_PreservesMatchedLineLoadsAndSupportInstances() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_LINE_LOADS_SOURCE"); + string profile22 = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_LINE_LOADS_PROFILE"); + string profile21 = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_LINE_LOADS_PROFILE_2021"); + string stage = TestFiles.Scratch("restored-line-loads-2022.rvt"); + string output = TestFiles.Scratch("restored-line-loads-2021.rvt"); + try + { + var result = DowngradeWriter.Write(source, profile22, stage, GuidRule.Exact, restoreLegacyAnalytics: true, allowLoss: true); + DowngradeWriter.Write(stage, profile21, output, GuidRule.Exact, allowLoss: true); + + Assert.NotEmpty(result.RestoredLineLoads!); + Assert.NotEmpty(result.RestoredPointSupports!); + Assert.NotEmpty(result.RestoredLineSupports!); + var originals = ReadRows(source); + var written = ReadRows(output); + foreach (long id in result.RestoredLineLoads!.Concat(result.RestoredPointSupports!).Concat(result.RestoredLineSupports!)) + { + Assert.Equal(originals[id].OriginalId, written[id].OriginalId); + Assert.Equal(originals[id].CreationDate, written[id].CreationDate); + foreach (var symbol in originals.Values.Where(row => row.OwningId == id)) + { + Assert.Equal(symbol.OriginalId, written[symbol.Id].OriginalId); + Assert.Equal(symbol.CreationDate, written[symbol.Id].CreationDate); + Assert.Equal(id, written[symbol.Id].OwningId); + } + } + } + finally + { + File.Delete(stage); + File.Delete(output); + } + } + + [SkippableFact] + public void LegacyRestoration_ReconstructsANewSlabAndItsSupports() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_NEW_PANEL_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_CONTOURS_PROFILE"); + string output = TestFiles.Scratch("new-panel.rvt"); + string report = TestFiles.Scratch("new-panel.json"); + try + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", + "--report", report, "--restore-legacy-analytics"], TextWriter.Null, errors); + Assert.True(exit == 0, errors.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + var result = json.RootElement; + var restoredPanels = result.GetProperty("restoredAnalyticalPanels").EnumerateArray().ToArray(); + Assert.Equal(15, restoredPanels.Length); + var newPanel = Assert.Single(restoredPanels, panel => + panel.GetProperty("sourceElementId").GetInt64() == panel.GetProperty("outputElementId").GetInt64()); + long id = newPanel.GetProperty("outputElementId").GetInt64(); + long owner = newPanel.GetProperty("physicalElementId").GetInt64(); + Assert.Equal(2, result.GetProperty("restoredAnalyticalOpenings").EnumerateArray() + .Count(opening => opening.GetProperty("outputPanelElementId").GetInt64() == id)); + var archived = ReadRows(profile); + Assert.DoesNotContain(id, archived.Keys); + Assert.DoesNotContain(owner, archived.Keys); + var written = ReadRows(output); + Assert.Equal(owner, written[id].OwningId); + var supports = result.GetProperty("restoredLineSupports").EnumerateArray().Select(s => s.GetInt64()).ToArray(); + Assert.Equal(8, supports.Length); + var newSupports = supports.Where(support => !archived.ContainsKey(support)).ToArray(); + Assert.Equal(3, newSupports.Length); + Assert.All(newSupports, support => Assert.Single(written.Values, row => row.OwningId == support)); + Assert.Equal(0, CoverageCensus.Read(output).Totals.ChecksumMismatches); + } + finally + { + File.Delete(output); + File.Delete(report); + } + } + + [Fact] + public void SlabPlacement_RequiresTheSameTransformForAllContours() + { + var arc = new LegacyAnalyticalMembers.CircularArc([0, 0, 0], [1, 0, 0], [0, 1, 0], 4, Math.PI); + var exterior = new LegacyAnalyticalMembers.DirectedEdge[] { new(arc.At(0), arc.At(1), arc), new(arc.At(1), arc.At(0)) }; + var a = new double[] { 0, 1, 0 }; + var b = new double[] { 1, 1, 0 }; + var c = new double[] { 0, 2, 0 }; + var hole = new LegacyAnalyticalMembers.DirectedEdge[] { new(a, b), new(b, c), new(c, a) }; + var move = new LegacyAnalyticalMembers.SlabPlacement(1.25, [10, 12, 4]); + var movedExterior = exterior.Select(move.Edge).ToArray(); + var movedHole = hole.Select(move.Edge).ToArray(); + Assert.NotNull(LegacyAnalyticalMembers.FindSlabPlacement([exterior, hole], [movedExterior, movedHole])); + Assert.Null(LegacyAnalyticalMembers.FindSlabPlacement([exterior, hole], [movedExterior, + hole.Select(new LegacyAnalyticalMembers.SlabPlacement(1.25, [10, 12.5, 4]).Edge).ToArray()])); + } + + [SkippableFact] + public void LegacyRestoration_WritesNewLineSupportsUsingCurrentElementRows() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_MODERN_SUPPORTS_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_CONTOURS_PROFILE"); + string output = TestFiles.Scratch("new-edge-supports.rvt"); + string report = TestFiles.Scratch("new-edge-supports.json"); + try + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", + "--report", report, "--restore-legacy-analytics"], TextWriter.Null, errors); + Assert.True(exit == 0, errors.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + var root = json.RootElement; + var archived = ReadRows(profile); + var input = ReadRows(source); + var written = ReadRows(output); + var supports = root.GetProperty("restoredLineSupports").EnumerateArray().Select(s => s.GetInt64()).ToArray(); + Assert.Equal(9, supports.Length); + var added = supports.Where(id => !archived.ContainsKey(id)).ToArray(); + Assert.Equal(4, added.Length); + Assert.All(added, id => + { + Assert.Equal(input[id], written[id]); + var marker = Assert.Single(input.Values, row => row.OwningId == id); + Assert.DoesNotContain(marker.Id, archived.Keys); + Assert.Equal(marker, written[marker.Id]); + }); + Assert.False(root.GetProperty("omittedProjectElements").TryGetProperty("BoundaryConditions", out _)); + Assert.Equal(0, CoverageCensus.Read(output).Totals.ChecksumMismatches); + } + finally + { + File.Delete(output); + File.Delete(report); + } + + } + + private static Dictionary ReadRows(string path) + { + using var file = RootStorage.OpenRead(path); + var schema = new FormatsSchema(TfSchemaReader.Read(file)!); + return ElemTableLayout.TryParse(PagedGzipStream.Read(file, "Global", "ElemTable")!, schema)! + .ToDictionary(row => row.Id); + } + + [SkippableFact] + public void LegacyRestoration_WritesLineSupportsOnArcsAndOpeningEdges() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_SUPPORTS_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_SUPPORTS_PROFILE"); + string output = TestFiles.Scratch("restored-edge-supports.rvt"); + string report = TestFiles.Scratch("restored-edge-supports.json"); + try + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", + "--report", report, "--restore-legacy-analytics"], TextWriter.Null, errors); + Assert.True(exit == 0, errors.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + var root = json.RootElement; + var supports = root.GetProperty("restoredLineSupports").EnumerateArray() + .Select(support => support.GetInt64()).ToArray(); + Assert.Equal(10, supports.Distinct().Count()); + Assert.Equal(14, root.GetProperty("restoredAnalyticalPanels").GetArrayLength()); + Assert.Equal(3, root.GetProperty("restoredAnalyticalOpenings").GetArrayLength()); + Assert.False(root.GetProperty("omittedProjectElements").TryGetProperty("BoundaryConditions", out _)); + + using var rvt = RootStorage.OpenRead(output); + var schema = new FormatsSchema(TfSchemaReader.Read(rvt)!); + var rows = ElemTableLayout.TryParse(PagedGzipStream.Read(rvt, "Global", "ElemTable")!, schema)!; + Assert.All(supports, id => + { + Assert.Contains(rows, row => row.Id == id); + Assert.Single(rows, row => row.OwningId == id); + }); + Assert.Equal(0, CoverageCensus.Read(output).Totals.ChecksumMismatches); + } + finally + { + File.Delete(output); + File.Delete(report); + } + } + + [SkippableFact] + public void LegacyRestoration_RegistersOpeningsAsContoursOfTheirPanels() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_CONTOURS_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_CONTOURS_PROFILE"); + string output = TestFiles.Scratch("restored-contours.rvt"); + string report = TestFiles.Scratch("restored-contours.json"); + try + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", + "--report", report, "--restore-legacy-analytics"], TextWriter.Null, errors); + Assert.True(exit == 0, errors.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + var root = json.RootElement; + var openings = root.GetProperty("restoredAnalyticalOpenings").EnumerateArray().ToArray(); + Assert.Equal(3, openings.Select(o => o.GetProperty("sourceElementId").GetInt64()).Distinct().Count()); + var panelIds = root.GetProperty("restoredAnalyticalPanels").EnumerateArray() + .Select(panel => panel.GetProperty("outputElementId").GetInt64()).ToHashSet(); + Assert.All(openings, opening => Assert.Contains(opening.GetProperty("outputPanelElementId").GetInt64(), panelIds)); + Assert.Equal(new[] { 1, 2 }, openings.GroupBy(o => o.GetProperty("outputPanelElementId").GetInt64()) + .Select(group => group.Count()).Order()); + Assert.False(root.GetProperty("omittedProjectElements").TryGetProperty("AnalyticalOpening", out _)); + Assert.Equal(0, CoverageCensus.Read(output).Totals.ChecksumMismatches); + } + finally + { + File.Delete(output); + File.Delete(report); + } + } + + [Fact] + public void LegacyRestoration_RequiresAWrite() + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run(["new.rvt", "--target-profile", "old.rvt", "--check", "--restore-legacy-analytics"], + TextWriter.Null, errors); + Assert.Equal(1, exit); + Assert.Contains("--restore-legacy-analytics requires --output", errors.ToString()); + } + + [SkippableFact] + public void LegacyRestoration_WritesMembersPanelsSupportsAndAttachments() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_SOURCE"); + string profile = TestFiles.Find("rstbasic22.rvt"); + string output = TestFiles.Scratch("restored-analytics.rvt"); + string report = TestFiles.Scratch("restored-analytics.json"); + try + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", + "--restore-legacy-analytics", "--report", report], TextWriter.Null, errors); + Assert.True(exit == 0, errors.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + var result = json.RootElement; + var members = result.GetProperty("restoredAnalyticalMembers").EnumerateArray().ToArray(); + var panels = result.GetProperty("restoredAnalyticalPanels").EnumerateArray().ToArray(); + var points = result.GetProperty("restoredPointSupports").EnumerateArray().Select(e => e.GetInt64()).ToArray(); + var lines = result.GetProperty("restoredLineSupports").EnumerateArray().Select(e => e.GetInt64()).ToArray(); + Assert.Equal(90, members.Length); + Assert.Equal(12, panels.Length); + Assert.Equal(15, points.Length); + Assert.Equal(5, lines.Length); + Assert.Equal(0, result.GetProperty("omittedContextualAnalyticalMembers").GetInt32()); + var omissions = result.GetProperty("omittedProjectElements"); + Assert.False(omissions.TryGetProperty("AnalyticalPanel", out _)); + Assert.False(omissions.TryGetProperty("BoundaryConditions", out _)); + + using var rvt = RootStorage.OpenRead(output); + var schema = new FormatsSchema(TfSchemaReader.Read(rvt)!); + var rows = ElemTableLayout.TryParse(PagedGzipStream.Read(rvt, "Global", "ElemTable")!, schema)! + .ToDictionary(row => row.Id); + var restored = members.Concat(panels).ToArray(); + Assert.All(restored, item => + { + Assert.Equal(item.GetProperty("physicalElementId").GetInt64(), + rows[item.GetProperty("outputElementId").GetInt64()].OwningId); + }); + Assert.All(points.Concat(lines), id => Assert.Contains(id, rows.Keys)); + var panelIds = panels.Select(x => x.GetProperty("outputElementId").GetInt64()).ToHashSet(); + var memberIds = members.Select(x => x.GetProperty("outputElementId").GetInt64()).ToHashSet(); + var attachments = result.GetProperty("restoredAttachedNodes").EnumerateArray().ToArray(); + Assert.Equal(17, attachments.Count(a => panelIds.Contains(a.GetProperty("hostElementId").GetInt64()))); + Assert.Single(attachments, a => memberIds.Contains(a.GetProperty("hostElementId").GetInt64())); + Assert.All(attachments, a => Assert.Contains(a.GetProperty("elementId").GetInt64(), rows.Keys)); + Assert.Equal(0, CoverageCensus.Read(output).Totals.ChecksumMismatches); + } + finally + { + File.Delete(output); + File.Delete(report); + } + } + + [Fact] + public void Associations_OnlyIncludesExplicitLocalElementPairs() + { + var relations = DowngradeAnalytics.Associations( + [ + ("a", """{"ReferenceId":1,"ExternalId":"9","LocalId":"10","IsLocalGroup":false,"IsExternalGroup":false}"""), + ("b", """{"ReferenceId":2,"ExternalId":"9","LocalId":"20","IsLocalGroup":false,"IsExternalGroup":false}"""), + ("c", """{"ReferenceId":1,"ExternalId":9,"LocalId":30,"IsLocalGroup":true,"IsExternalGroup":false}"""), + ("d", """{"ReferenceId":1,"ExternalId":9,"LocalId":40,"IsLocalGroup":false,"IsExternalGroup":true}"""), + ("e", """{"ReferenceId":1,"ExternalId":"9","LocalId":"10","IsLocalGroup":false,"IsExternalGroup":false}"""), + ("f", """{"ReferenceId":1,"ExternalId":"0","LocalId":"50","IsLocalGroup":false,"IsExternalGroup":false}"""), + ], + [(".", """{"Id":1}"""), ("linked.rvt", """{"Id":2}""")]); + + Assert.Equal(9, Assert.Single(relations).Key); + Assert.Equal(10, Assert.Single(relations[9])); + } + + [Fact] + public void Associations_RejectsMalformedLocalReference() + { + Assert.Throws(() => DowngradeAnalytics.Associations([], [(".", "{")])); + } + + [SkippableFact] + public void WriteReport_ContainsOmittedAnalyticsAndDependentInstanceRecords() + { + string source = TestFiles.FileFromEnvironment("RVTIO_ANALYTICS_SOURCE"); + string profile = TestFiles.Find("rstbasic22.rvt"); + string output = TestFiles.Scratch("legacy-analytics.rvt"); + string report = TestFiles.Scratch("legacy-analytics.json"); + try + { + using var errors = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", "--report", report], + TextWriter.Null, errors); + Assert.True(exit == 0, errors.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + var root = json.RootElement; + var omissions = root.GetProperty("omittedProjectElements"); + var analytics = root.GetProperty("omittedAnalyticalData").EnumerateArray().ToArray(); + foreach (var (className, geometry) in new[] + { + ("AnalyticalMember", "curves"), ("AnalyticalPanel", "contours"), ("BoundaryConditions", null), + }) + { + var elements = analytics.Where(element => element.GetProperty("class").GetString() == className).ToArray(); + Assert.NotEmpty(elements); + Assert.Equal(omissions.GetProperty(className).GetInt32(), elements.Length); + Assert.All(elements, element => + { + Assert.NotEmpty(element.GetProperty("physicalElementIds").EnumerateArray()); + if (geometry is not null) Assert.NotEmpty(element.GetProperty(geometry).EnumerateArray()); + Assert.NotEmpty(element.GetProperty("sourceRecords").GetProperty("102").GetBytesFromBase64()); + Assert.False(element.TryGetProperty("decodeError", out _)); + if (className == "BoundaryConditions") + { + Assert.Single(element.GetProperty("analyticalHostIds").EnumerateArray()); + Assert.NotEmpty(element.GetProperty("dependentInstanceRecords").GetProperty("102").GetBytesFromBase64()); + int type = element.GetProperty("fields").GetProperty("BoundaryConditions.m_type")[0].GetInt32(); + if (type == 0) Assert.Equal(3, element.GetProperty("pointFeet").GetArrayLength()); + if (type == 1) Assert.Single(element.GetProperty("curves").EnumerateArray()); + } + }); + } + } + finally + { + File.Delete(output); + File.Delete(report); + } + } +} diff --git a/tests/RvtIO.Tests/DowngradeCommandTests.cs b/tests/RvtIO.Tests/DowngradeCommandTests.cs index 59203d63..a732abb1 100644 --- a/tests/RvtIO.Tests/DowngradeCommandTests.cs +++ b/tests/RvtIO.Tests/DowngradeCommandTests.cs @@ -190,7 +190,6 @@ public void Check_WithoutReport_WritesNothingAtAll() // ---- refusals ---------------------------------------------------------------------------------------------------------------- [Theory] - [InlineData(Marker2027, Marker2025, "source-too-new")] [InlineData(Marker2025, Marker2025, "profile-not-older")] [InlineData(Marker2026, Marker2026, "profile-not-older")] [InlineData(Marker2025, Marker2026, "profile-not-older")] @@ -359,6 +358,10 @@ public void UsageErrors_ExitWith1_AndWriteNothing() [source, "--target-profile", profile, "--check", "--report", source], [source, "--target-profile", profile, "--check", "--report", profile], ["--target-profile", profile, "--check"], + [source, "--target-profile", profile, "--output", source], + [source, "--target-profile", profile, "--output", profile], + [source, "--target-profile", profile, "--output", P("same.rvt"), "--report", P("same.rvt")], + [source, "--target-profile", profile, "--allow-loss", "--output", P("out.rvt")], ]; foreach (var args in bad) { @@ -372,11 +375,12 @@ public void UsageErrors_ExitWith1_AndWriteNothing() } [Fact] - public void WithoutCheck_NoFileCanBeWritten_AndTheMessageSaysSo() + public void WithoutCheckOrOutput_NoFileCanBeWritten_AndTheMessageSaysSo() { var (exit, _, error) = Run(Source(), "--target-profile", Profile()); Assert.Equal(1, exit); - Assert.Contains("add --check", error); + Assert.Contains("--check", error); + Assert.Contains("--output", error); } } diff --git a/tests/RvtIO.Tests/DowngradeElemTableRewriterTests.cs b/tests/RvtIO.Tests/DowngradeElemTableRewriterTests.cs new file mode 100644 index 00000000..2deda996 --- /dev/null +++ b/tests/RvtIO.Tests/DowngradeElemTableRewriterTests.cs @@ -0,0 +1,175 @@ +using System.Text; +using OpenMcdf; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +/// Transcoding a decoded Global/ElemTable stream between element-id widths +/// (40-byte rows with 8-byte ids to 28-byte rows with 4-byte ids). +public sealed class DowngradeElemTableRewriterTests +{ + /// Writes top-level class definitions of the Formats/Latest grammar; ids start at 12. + private sealed class SchemaBuilder + { + private readonly MemoryStream _stream = new(); + private readonly BinaryWriter _w; + public SchemaBuilder() { _w = new BinaryWriter(_stream); } + + public SchemaBuilder Class(string name, int baseId, uint version, params (string Name, byte Type, byte Mods, int Ref)[] fields) => + ClassWithExtra(name, baseId, version, [.. fields.Select(f => (f.Name, f.Type, f.Mods, f.Ref, (ushort)0))]); + + public SchemaBuilder ClassWithExtra(string name, int baseId, uint version, params (string Name, byte Type, byte Mods, int Ref, ushort Extra)[] fields) + { + _w.Write((ushort)0); + Name16(name); + _w.Write((ushort)baseId); + _w.Write(version); + _w.Write((uint)fields.Length); + foreach (var f in fields) + { + _w.Write((uint)f.Name.Length); + _w.Write(Encoding.ASCII.GetBytes(f.Name)); + _w.Write(f.Type); _w.Write(f.Mods); _w.Write(f.Extra); + if (f.Type == 0x0E && (f.Mods & 0x0F) == 0) _w.Write((ushort)f.Ref); + } + _w.Write(0u); + return this; + } + + private void Name16(string name) { _w.Write((ushort)name.Length); _w.Write(Encoding.ASCII.GetBytes(name)); } + + public byte[] Build(int padding = 8) => [.. _stream.ToArray(), .. new byte[padding]]; + } + + /// The classes the ElemTable layout needs, in Revit 2022 shape (28-byte rows) + /// or Revit 2024+ shape (40-byte rows, m_history declared first). + private static byte[] ElemTableSchema(bool wideIds) + { + byte idType = wideIds ? (byte)0x0B : (byte)0x04; + string idName = wideIds ? "m_id64" : "m_id"; + var b = new SchemaBuilder() + .Class("Identifier", 0, 1, (idName, idType, 0, 0)) // 12 + .Class("ElementId", 0, 1, ("m_id", 0x0E, 0, 12)) // 13 + .Class("OriginalElementId", 0, 1, (idName, idType, 0, 0)) // 14 + .Class("EpisodeId", 0, 1, ("m_id", 0x04, 0, 0)) // 15 + .Class("ElementHistory", 0, 8, ("m_originalElementId", 0x0E, 0, 14), ("m_creationDate", 0x0E, 0, 15), + ("m_lastModificationDate", 0x0E, 0, 15), ("m_lastUserModificationDate", 0x0E, 0, 15)) // 16 + .Class("PartitionId", 0, 1, ("m_id", 0x04, 0, 0)); // 17 + return (wideIds + ? b.Class("ElemRec", 0, 10, ("m_history", 0x0E, 0, 16), ("m_id", 0x0E, 0, 13), ("m_OwningElementId", 0x0E, 0, 13), ("m_partitionId", 0x0E, 0, 17)) + : b.Class("ElemRec", 0, 10, ("m_id", 0x0E, 0, 13), ("m_history", 0x0E, 0, 16), ("m_partitionId", 0x0E, 0, 17), ("m_OwningElementId", 0x0E, 0, 13))) // 18 + .Class("ElemTable", 0, 9, ("m_elemArr", 0x0E, 0x50, 18), ("m_bExpandAllOnLoad", 0x01, 0, 0)) // 19 + .Build(); + } + + private static byte[] WideRows(params (long Id, long Original, int Created, int Partition, long Owner)[] rows) + { + var s = new MemoryStream(); var w = new BinaryWriter(s); + w.Write((ushort)19); w.Write((uint)rows.Length); + foreach (var r in rows) + { + w.Write(r.Original); w.Write(r.Created); w.Write(r.Created + 1); w.Write(r.Created + 2); + w.Write(r.Id); w.Write(r.Owner); w.Write(r.Partition); + } + w.Write(new byte[19]); // trailing rest preserved verbatim + return s.ToArray(); + } + + [Fact] + public void Transcode_PreservesEveryValue_AndRemapsTheTableId() + { + var sourceDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: true))!; + var targetDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: false))!; + byte[] source = WideRows((101, 101, 5, 1, -1), (202, 200, 9, 2, 101), (700, 700, 3, 1, -1)); + + byte[] target = DowngradeElemTableRewriter.Rewrite(source, sourceDoc, targetDoc); + + var rows = ElemTableLayout.TryParse(target, new FormatsSchema(targetDoc)); + Assert.NotNull(rows); + Assert.Equal(3, rows.Count); + Assert.Equal(new ElemTableLayout.Row(101, 101, 5, 1, -1, 6), rows[0]); + Assert.Equal(new ElemTableLayout.Row(202, 200, 9, 2, 101, 10), rows[1]); + Assert.Equal(new ElemTableLayout.Row(700, 700, 3, 1, -1, 4), rows[2]); + // Class id remapped, count kept, trailing rest preserved. + Assert.Equal(19, BitConverter.ToUInt16(target, 0)); + Assert.Equal(3u, BitConverter.ToUInt32(target, 2)); + Assert.Equal(source[^19..], target[^19..]); + Assert.Equal(6 + 3 * 28 + 19, target.Length); + } + + [Fact] + public void Transcode_WithInMemoryPointerFields_StillGives40ByteSourceRows() + { + // Revit 2027 declares m_pElement, m_pGRep and m_pHeader in ElemRec; they take no bytes. + var b = new SchemaBuilder() + .Class("Identifier", 0, 2, ("m_id64", 0x0B, 0, 0)) + .Class("ElementId", 0, 1, ("m_id", 0x0E, 0, 12)) + .Class("OriginalElementId", 0, 1, ("m_id64", 0x0B, 0, 0)) + .Class("EpisodeId", 0, 1, ("m_id", 0x04, 0, 0)) + .Class("ElementHistory", 0, 8, ("m_originalElementId", 0x0E, 0, 14), ("m_creationDate", 0x0E, 0, 15), + ("m_lastModificationDate", 0x0E, 0, 15), ("m_lastUserModificationDate", 0x0E, 0, 15)) + .Class("PartitionId", 0, 1, ("m_id", 0x04, 0, 0)) + .ClassWithExtra("ElemRec", 0, 10, + ("m_pElement", 0x0E, 1, 0, (ushort)2), ("m_pGRep", 0x0E, 1, 0, (ushort)2), ("m_pHeader", 0x0E, 2, 0, (ushort)2), + ("m_history", 0x0E, 0, 16, (ushort)0), ("m_id", 0x0E, 0, 13, (ushort)0), ("m_OwningElementId", 0x0E, 0, 13, (ushort)0), ("m_partitionId", 0x0E, 0, 17, (ushort)0)) + .Class("ElemTable", 0, 9, ("m_elemArr", 0x0E, 0x50, 18), ("m_bExpandAllOnLoad", 0x01, 0, 0)); + var sourceDoc = TfSchemaReader.Parse(b.Build())!; + var targetDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: false))!; + // Rows follow the declared field order: m_history(20) m_id(8) m_OwningElementId(8) m_partitionId(4). + var s = new MemoryStream(); var w = new BinaryWriter(s); + w.Write((ushort)19); w.Write(1u); + w.Write(101L); w.Write(0); w.Write(1); w.Write(2); w.Write(101L); w.Write(-1L); w.Write(7); + w.Write((byte)0); // m_bExpandAllOnLoad + byte[] target = DowngradeElemTableRewriter.Rewrite(s.ToArray(), sourceDoc, targetDoc); + var rows = ElemTableLayout.TryParse(target, new FormatsSchema(targetDoc)); + Assert.NotNull(rows); + Assert.Single(rows); + Assert.Equal(new ElemTableLayout.Row(101, 101, 0, 7, -1, 1), rows[0]); + } + + [Fact] + public void Transcode_DroppedOwners_LoseTheirRows_AndTheCountFollows() + { + var sourceDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: true))!; + var targetDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: false))!; + byte[] source = WideRows((101, 101, 5, 1, -1), (202, 200, 9, 2, 101), (700, 700, 3, 1, -1)); + + byte[] target = DowngradeElemTableRewriter.Rewrite(source, sourceDoc, targetDoc, new HashSet { 202 }); + + var rows = ElemTableLayout.TryParse(target, new FormatsSchema(targetDoc)); + Assert.NotNull(rows); + Assert.Equal([101L, 700L], rows.Select(r => r.Id).ToArray()); + Assert.Equal(2u, BitConverter.ToUInt32(target, 2)); + Assert.Equal(source[^19..], target[^19..]); + Assert.Equal(6 + 2 * 28 + 19, target.Length); + } + + [Fact] + public void Transcode_RefusesIdsBeyond32Bits_WithStableCode() + { + var sourceDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: true))!; + var targetDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: false))!; + byte[] source = WideRows((5_000_000_000L, 9, 3, 1, -1)); + + var ex = Assert.Throws(() => DowngradeElemTableRewriter.Rewrite(source, sourceDoc, targetDoc)); + Assert.Equal("id-beyond-32-bits", ex.Kind); + } + + [Theory] + [InlineData("truncated")] + [InlineData("unordered")] + [InlineData("wrong class id")] + public void MalformedSourceTable_IsRejected(string mode) + { + var sourceDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: true))!; + var targetDoc = TfSchemaReader.Parse(ElemTableSchema(wideIds: false))!; + byte[] source = WideRows((10, 10, 0, 0, -1), (20, 20, 0, 0, -1)); + if (mode == "truncated") source = source[..(6 + 40 + 39)]; + if (mode == "unordered") BitConverter.GetBytes(5L).CopyTo(source, 6 + 40 + 20); + if (mode == "wrong class id") source[0] = 20; + + Assert.Throws(() => DowngradeElemTableRewriter.Rewrite(source, sourceDoc, targetDoc)); + } +} diff --git a/tests/RvtIO.Tests/DowngradeHistoryRewriterTests.cs b/tests/RvtIO.Tests/DowngradeHistoryRewriterTests.cs new file mode 100644 index 00000000..5fc8bfb6 --- /dev/null +++ b/tests/RvtIO.Tests/DowngradeHistoryRewriterTests.cs @@ -0,0 +1,64 @@ +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; +using Cls = RvtIO.Tests.SchemaStreamEditorTests.Cls; +using Fld = RvtIO.Tests.SchemaStreamEditorTests.Fld; +using NoRef = RvtIO.Tests.SchemaStreamEditorTests.NoRef; + +namespace RvtIO.Tests; + +/// Transcoding a Global/History episode table across releases remaps only its +/// opening DocumentHistory class tag; every other byte is preserved verbatim. +public sealed class DowngradeHistoryRewriterTests +{ + private static SchemaDocument Doc(params Cls[] classes) => + TfSchemaReader.Parse(SchemaStreamEditorTests.Write([.. classes]).Data); + + private static byte[] Table(ushort tag, params byte[] rest) + { + var payload = new byte[2 + rest.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload, tag); + rest.CopyTo(payload, 2); + return payload; + } + + [Fact] + public void Rewrite_SwapsOnlyTheOpeningTag() + { + // Different DocumentHistory ids: filler pushes the target class to id 13. + var source = Doc(new Cls("DocumentHistory", new NoRef(), 1, [new Fld("m_x", 0x04)], [])); + var target = Doc( + new Cls("Filler", new NoRef(), 1, [], []), + new Cls("DocumentHistory", new NoRef(), 1, [new Fld("m_x", 0x04)], [])); + byte[] rest = [1, 0, 0, 0, 0, 0, 0, 0, 0xA2, 0xB3, 0xC4]; + byte[] result = DowngradeHistoryRewriter.Rewrite(Table(12, rest), source, target); + Assert.Equal(Table(13, rest), result); + } + + [Fact] + public void Rewrite_EqualIds_IsAVerbatimCopy() + { + var source = Doc(new Cls("DocumentHistory", new NoRef(), 1, [], [])); + var target = Doc(new Cls("DocumentHistory", new NoRef(), 1, [], [])); + byte[] payload = Table(12, [1, 2, 3, 4]); + Assert.Equal(payload, DowngradeHistoryRewriter.Rewrite(payload, source, target)); + } + + [Fact] + public void Rewrite_WrongOpeningTag_IsRejected() + { + var source = Doc(new Cls("DocumentHistory", new NoRef(), 1, [], [])); + var target = Doc(new Cls("DocumentHistory", new NoRef(), 1, [], [])); + Assert.Throws(() => DowngradeHistoryRewriter.Rewrite(Table(99, [1, 2]), source, target)); + Assert.Throws(() => DowngradeHistoryRewriter.Rewrite([0x12], source, target)); + } + + [Fact] + public void Rewrite_MissingDocumentHistoryClass_IsRejected() + { + var with = Doc(new Cls("DocumentHistory", new NoRef(), 1, [], [])); + var without = Doc(new Cls("Other", new NoRef(), 1, [], [])); + Assert.Throws(() => DowngradeHistoryRewriter.Rewrite(Table(12, [1, 2]), without, with)); + Assert.Throws(() => DowngradeHistoryRewriter.Rewrite(Table(12, [1, 2]), with, without)); + } +} diff --git a/tests/RvtIO.Tests/DowngradeSampleTests.cs b/tests/RvtIO.Tests/DowngradeSampleTests.cs index 3e5d2a20..0ed4d99b 100644 --- a/tests/RvtIO.Tests/DowngradeSampleTests.cs +++ b/tests/RvtIO.Tests/DowngradeSampleTests.cs @@ -145,11 +145,10 @@ public void ElementCensus_CountsEveryElementOnce_InEachRelease() } [SkippableFact] - public void ARelease2027Source_AndASourceNotNewerThanTheProfile_AreRefused() + public void ASourceNotNewerThanTheProfile_IsRefused() { string profile = Find(2025); - Assert.Equal("source-too-new", Assert.Throws(() => DowngradePlanner.Plan(Find(2027), profile, GuidRule.Exact)).Kind); Assert.Equal("profile-not-older", Assert.Throws(() => DowngradePlanner.Plan(profile, profile, GuidRule.Exact)).Kind); Assert.Equal("profile-not-older", Assert.Throws(() => DowngradePlanner.Plan(profile, Find(2026), GuidRule.Exact)).Kind); } diff --git a/tests/RvtIO.Tests/DowngradeWriterTests.cs b/tests/RvtIO.Tests/DowngradeWriterTests.cs new file mode 100644 index 00000000..30888056 --- /dev/null +++ b/tests/RvtIO.Tests/DowngradeWriterTests.cs @@ -0,0 +1,643 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Cli; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class DowngradeWriterTests : IDisposable +{ + private readonly string _folder = Path.Combine(Path.GetTempPath(), "rvtio-downgrade-write-" + Guid.NewGuid().ToString("N")); + + public DowngradeWriterTests() => Directory.CreateDirectory(_folder); + + public void Dispose() => Directory.Delete(_folder, recursive: true); + + private string P(string name) => Path.Combine(_folder, name); + + private static string Hash(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); + + [SkippableFact] + public void RestoresMissingInternalElectricalProjectionStyleWithoutDuplicatingAnExistingStyle() + { + using var root = RootStorage.OpenRead(TestFiles.Find("rstbasic20.rvt")); + var doc = TfSchemaReader.Read(root)!; + var schema = new FormatsSchema(doc); + var parts = root.OpenStorage("Partitions").EnumerateEntries().Where(e => e.Type == EntryType.Stream) + .Select(e => "Partitions/" + e.Name).ToHashSet(); + var global = root.OpenStorage("Global"); + var streams = new Dictionary(); + foreach (var name in new[] { "Latest", "ElemTable", "DocumentIncrementTable" }) + { + using var stream = global.OpenStream(name); + var stored = new byte[stream.Length]; + stream.ReadExactly(stored); + streams["Global/" + name] = stored; + } + Assert.Null(LegacyElectricalStyle.Restore(doc, streams, parts)); + + var latest = PagedGzipStream.Decompress(streams["Global/Latest"])!; + var walker = new WideBlockWalker(doc, (_, _) => null, []); + walker.UseEntitySchemas(EntitySchemaReader.Read(root, doc), passUnknown: true); + var walk = walker.Run(latest, 0, latest.Length, BitConverter.ToUInt16(latest)); + int trackingId = schema.IdOf("CategoryTracking")!.Value; + int slot = walk.Queue.IndexOf(trackingId); + var styles = PayloadSpan.Find(latest, walk.QueueStart[slot], walk.QueueStart[slot + 1], + doc, trackingId, "m_gstyleData")!.Value; + int count = BitConverter.ToInt32(latest, styles.Start); + const int entrySize = 3 * sizeof(int); + int item = Assert.Single(Enumerable.Range(0, count).Select(i => styles.Start + sizeof(int) + i * entrySize) + .Where(at => BitConverter.ToInt32(latest, at) == (int)BuiltInCategory.OST_ElectricalInternalCircuits + && BitConverter.ToInt32(latest, at + sizeof(int)) == 1)); + byte[] missing = [.. latest.AsSpan(0, item), .. latest.AsSpan(item + entrySize)]; + BitConverter.GetBytes(count - 1).CopyTo(missing, styles.Start); + streams["Global/Latest"] = PagedStreamCodec.Reencode(streams["Global/Latest"], missing); + var originalRows = ElemTableLayout.TryParse(PagedGzipStream.Decompress(streams["Global/ElemTable"])!, schema)!; + var originalIncrements = DocumentIncrementTable.TryParse( + PagedGzipStream.Decompress(streams["Global/DocumentIncrementTable"])!, schema, out _)!; + + var addition = Assert.IsType(LegacyElectricalStyle.Restore(doc, streams, parts)); + var rows = ElemTableLayout.TryParse(PagedGzipStream.Decompress(streams["Global/ElemTable"])!, schema)!; + var increments = DocumentIncrementTable.TryParse( + PagedGzipStream.Decompress(streams["Global/DocumentIncrementTable"])!, schema, out _)!; + Assert.Contains(addition.PartitionPath, parts); + Assert.Equal(3, addition.Payloads.Length); + Assert.Equal(originalRows.Count + 1, rows.Count); + Assert.Equal((long)addition.Owner, rows[^1].Id); + Assert.Equal(increments.Local[^1].Greatest, rows[^1].LastModificationDate!.Value); + Assert.Equal(originalIncrements.Local[^1].TotalElements + 1, increments.Local[^1].TotalElements); + Assert.Null(LegacyElectricalStyle.Restore(doc, streams, parts)); + } + + [SkippableFact] + public void RegistersMissingLegacyProjectDefaultsFromStandaloneProfile() + { + var source = TestFiles.FileFromEnvironment("RVTIO_DEFAULTS_SOURCE"); + var profile = TestFiles.FileFromEnvironment("RVTIO_DEFAULTS_PROFILE"); + string output = P("legacy-defaults.rvt"); + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + AssertRegisteredSettings(output, new Dictionary + { + [6] = "AnalyticalSupportTracker", + [12] = "AnalyticalSetTracker", + [13] = "AnalyticalAutofixTracker", + [14] = "AnalyticalOctreeTracker", + [55] = "RbsWireSizesElem", + [76] = "LynxTracker", + }); + } + + [SkippableFact] + public void RegistersAnalyticalAndForgeProjectDefaultsFor2023() + { + var source = TestFiles.FileFromEnvironment("RVTIO_DEFAULTS_2023_SOURCE"); + var profile = TestFiles.FileFromEnvironment("RVTIO_DEFAULTS_2023_PROFILE"); + string output = P("legacy-defaults-2023.rvt"); + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + AssertRegisteredSettings(output, new Dictionary + { + [6] = "AnalyticalSupportTracker", + [12] = "AnalyticalSetTracker", + [13] = "AnalyticalAutofixTracker", + [14] = "AnalyticalOctreeTracker", + [55] = "RbsWireSizesElem", + [80] = "ForgeConnectionTracker", + }); + } + + [SkippableTheory] + [InlineData(2021)] + [InlineData(2022)] + public void RegistersAnalyticalAndForgeProjectDefaultsForLegacyTarget(int release) + { + var source = TestFiles.FileFromEnvironment($"RVTIO_DEFAULTS_{release}_SOURCE"); + var profile = TestFiles.FileFromEnvironment($"RVTIO_DEFAULTS_{release}_PROFILE"); + string output = P($"legacy-defaults-{release}.rvt"); + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + AssertRegisteredSettings(output, new Dictionary + { + [6] = "AnalyticalSupportTracker", + [12] = "AnalyticalSetTracker", + [13] = "AnalyticalAutofixTracker", + [14] = "AnalyticalOctreeTracker", + [80] = "ForgeConnectionTracker", + }); + } + + [SkippableFact] + public void DirectDowngradeFromOriginalProjectPreservesRequiredUniqueIds() + { + string source = TestFiles.FileFromEnvironment("RVTIO_DIRECT_IDENTITY_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_DIRECT_IDENTITY_PROFILE"); + string identities = TestFiles.FileFromEnvironment("RVTIO_DIRECT_IDENTITY_EXPECTED"); + var expected = File.ReadLines(identities).Select(line => line.Split('|')) + .ToDictionary(fields => long.Parse(fields[0], System.Globalization.CultureInfo.InvariantCulture), + fields => fields[1]); + Assert.NotEmpty(expected); + string inputHash = Hash(source); + string output = P("direct-downgrade.rvt"); + + var result = DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + Assert.Equal(2021, result.TargetRelease); + Assert.Equal(inputHash, Hash(source)); + AssertIdentities(source); + AssertIdentities(output); + + void AssertIdentities(string path) + { + using var root = RootStorage.OpenRead(path); + var doc = TfSchemaReader.Read(root)!; + var rows = ElemTableLayout.TryParse(PagedGzipStream.Read(root, "Global", "ElemTable")!, + new FormatsSchema(doc))!.ToDictionary(row => row.Id); + var history = PagedGzipStream.Read(root, "Global", "History")!; + var episodes = RvtFileReader.ParseEpisodeGuids([history], null, new FileSchema(doc)); + Assert.Equal((uint)episodes.Guids.Count, episodes.X); + foreach (var (id, uniqueId) in expected) + { + Assert.True(rows.TryGetValue(id, out var row), $"Missing element {id}."); + uint originalId = unchecked((uint)row.OriginalId); + var elementHistory = new ElemRecHistory(originalId, row.CreationDate); + var episode = ElementExportIds.EpisodeGuid(elementHistory, episodes.Guids, episodes.X); + Assert.True(episode.HasValue, $"Missing creation episode for element {id}."); + Assert.Equal(uniqueId, ElementExportIds.UniqueId(episode.Value, originalId)); + } + } + } + + [SkippableFact] + public void RestoresWireTypeReferencesFromTheProjectsLegacyCatalog() + { + string source = TestFiles.FileFromEnvironment("RVTIO_LEGACY_WIRE_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_LEGACY_WIRE_PROFILE"); + string legacy = TestFiles.FileFromEnvironment("RVTIO_LEGACY_WIRE_REFERENCE"); + string output = P("legacy-wire-references.rvt"); + var expected = ReadWireReferences(legacy); + var original = ReadWireReferences(source); + Assert.NotEmpty(expected); + Assert.Contains(expected, pair => original.TryGetValue(pair.Key, out var ids) && !ids.SequenceEqual(pair.Value)); + + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + var actual = ReadWireReferences(output); + foreach (var (id, references) in expected) + { + Assert.True(actual.TryGetValue(id, out var written), $"Missing wire type {id}."); + Assert.All(references, reference => Assert.True(reference > 0)); + Assert.Equal(references, written); + } + + static Dictionary ReadWireReferences(string path) + { + using var root = RootStorage.OpenRead(path); + var doc = TfSchemaReader.Read(root)!; + var schema = new FormatsSchema(doc); + var wireTag = schema.IdOf("RbsWireType")!.Value; + string[] fields = ["m_idMaterial", "m_idTempratureRating", "m_idInsulation"]; + var walker = new WideBlockWalker(doc, (c, f) => + c.Name == "RbsWireType" && fields.Contains(f.Name) ? f.Name : null, []); + var result = new Dictionary(); + var partitions = root.OpenStorage("Partitions"); + foreach (var entry in partitions.EnumerateEntries().Where(e => e.Type == EntryType.Stream && int.TryParse(e.Name, out _))) + { + using var stream = partitions.OpenStream(entry.Name); + var bytes = new byte[stream.Length]; + stream.ReadExactly(bytes); + Assert.True(PartitionFraming.Walk(bytes, PartitionFraming.TagsOf(schema)!.Value, + ElemTableLayout.IdWidth(schema)!.Value, record => + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort) || + BitConverter.ToUInt16(record.Body.Span) != wireTag) return; + var body = record.Body.ToArray(); + var walk = walker.Run(body, 0, body.Length, wireTag); + Assert.True(walk.Exact, walk.Error); + result[record.Owner] = fields.Select(f => Assert.Single(walk.Captures, c => + c.AtRoot && c.IsElementId && c.Field == f).Integer).ToArray(); + }, out var failure, out _), failure); + } + return result; + } + } + + [SkippableFact] + public void WritesTaggedOpeningSupportsFor2023AndKeepsTheirElementIds() + { + string source = TestFiles.FileFromEnvironment("RVTIO_OPENING_SUPPORTS_SOURCE"); + string profile = TestFiles.FileFromEnvironment("RVTIO_OPENING_SUPPORTS_PROFILE"); + string output = P("opening-supports.rvt"); + var before = ReadPicks(source); + Assert.Contains(before.Picks, pair => pair.Value.Kind == 0); + + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + var after = ReadPicks(output); + Assert.Equal(before.Picks.Keys.Order(), after.Picks.Keys.Order()); + foreach (var (owner, pick) in before.Picks) + { + var written = after.Picks[owner]; + if (pick.Kind == 0) + { + Assert.Equal(1, written.Kind); + Assert.True(written.Tag >= 0); + Assert.Equal(pick.Host, after.Openings[written.Host]); + } + else Assert.Equal(pick, written); + } + + static (Dictionary Picks, Dictionary Openings) + ReadPicks(string path) + { + using var root = RootStorage.OpenRead(path); + var doc = TfSchemaReader.Read(root)!; + var schema = new FormatsSchema(doc); + var walker = new WideBlockWalker(doc, (c, f) => WideBlockWalker.AllItemsKeyPrefix + c.Name + "." + f.Name, []); + var picks = new Dictionary(); + var openings = new Dictionary(); + var storage = root.OpenStorage("Partitions"); + var entry = Assert.Single(storage.EnumerateEntries().Where(e => e.Type == EntryType.Stream)); + using var stream = storage.OpenStream(entry.Name); + byte[] partition = new byte[stream.Length]; + stream.ReadExactly(partition); + Assert.True(PartitionFraming.Walk(partition, PartitionFraming.TagsOf(schema)!.Value, + ElemTableLayout.IdWidth(schema)!.Value, record => + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort)) return; + int tag = BitConverter.ToUInt16(record.Body.Span); + string? name = walker.Class(tag)?.Name; + if (name is not ("AnalyticalOpening" or "BoundaryConditions")) return; + var body = record.Body.ToArray(); + var walk = walker.Run(body, 0, body.Length, tag); + Assert.True(walk.Exact, walk.Error); + long Value(string field) => walk.Captures.Where(c => c.Key == WideBlockWalker.AllItemsKeyPrefix + field) + .Select(c => c.Integer).SingleOrDefault(-1); + if (name == "AnalyticalOpening") + openings.Add((long)record.Owner, Value("AnalyticalOpening.m_panelId")); + else if (Value("BoundaryConditions.m_type") == 1) + picks.Add(record.Owner, (Value("ElemPick.m_type"), Value("ElemPick.m_elemId"), Value("ElemPick.m_tags@0"))); + }, out var error, out _), error); + return (picks, openings); + } + } + + [SkippableFact] + public void RegistersLegacyWireSizesInAnEightByteIntermediateRelease() + { + var source = TestFiles.FileFromEnvironment("RVTIO_WIRE_DEFAULTS_SOURCE"); + var profile = TestFiles.FileFromEnvironment("RVTIO_WIRE_DEFAULTS_PROFILE"); + string output = P("wire-defaults.rvt"); + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + AssertRegisteredSettings(output, new Dictionary { [55] = "RbsWireSizesElem" }, sizeof(long)); + } + + private static void AssertRegisteredSettings(string output, IReadOnlyDictionary settings, + int expectedWidth = sizeof(int)) + { + using var root = RootStorage.OpenRead(output); + var doc = TfSchemaReader.Read(root)!; + var schema = new FormatsSchema(doc); + var latest = PagedGzipStream.Read(root, "Global", "Latest")!; + var registry = LegacyElectricalStyle.QueuedField(latest, doc, "UniqueElementsTracking", "m_elemIds", readEntities: true)!.Value; + var rows = ElemTableLayout.TryParse(PagedGzipStream.Read(root, "Global", "ElemTable")!, schema)!; + int idWidth = ElemTableLayout.IdWidth(schema)!.Value; + Assert.Equal(expectedWidth, idWidth); + var expected = settings.ToDictionary(setting => IdAt(setting.Key), setting => setting.Value); + var channels = expected.Keys.ToDictionary(id => id, _ => new HashSet()); + var storage = root.OpenStorage("Partitions"); + foreach (var part in storage.EnumerateEntries().Where(entry => entry.Type == EntryType.Stream)) + { + using var stored = storage.OpenStream(part.Name); + byte[] partition = new byte[stored.Length]; + stored.ReadExactly(partition); + Assert.True(PartitionFraming.Walk(partition, PartitionFraming.TagsOf(schema)!.Value, idWidth, record => + { + if (record.Block != 0 || !expected.TryGetValue(record.Owner, out string? type)) + return; + Assert.True(channels[record.Owner].Add(record.Channel)); + if (record.Channel == 102) + Assert.Equal(type, doc.ById[BitConverter.ToUInt16(record.Body.Span)].Name); + }, out var failure, out _), failure); + } + foreach (ulong id in expected.Keys) + { + Assert.Contains(rows, row => row.Id == (long)id); + Assert.Equal(new[] { 101, 102, 103 }, channels[id].Order()); + } + + ulong IdAt(int slot) + { + int at = registry.Start + sizeof(int) + idWidth * slot; + return idWidth == sizeof(long) ? BitConverter.ToUInt64(latest, at) : BitConverter.ToUInt32(latest, at); + } + } + + private string Synthetic(int release, string name, bool includeElemTable = false) + { + string path = P(name); + RvtWriterTests.CreateSyntheticRevitFile(path, new RvtWriterTests.SyntheticFileOptions + { + FileName = name, + Kind = RvtFileKind.Project, + SchemaRelease = release, + SavedRelease = release, + IncludeElemTable = includeElemTable, + }); + return path; + } + + [Fact] + public void BasicFileInfoPatcher_ReplacesEveryYearOccurrence_KeepingLength() + { + byte[] data = RvtWriterTests.BuildBasicFileInfoBytes(2026); + byte[] patched = BasicFileInfoPatcher.Patch(data, 2026, 2025); + + Assert.Equal(data.Length, patched.Length); + var info = BasicFileInfoReader.Parse(patched); + Assert.Equal("2025", info["RevitVersion"]); + Assert.DoesNotContain(Encoding.Unicode.GetBytes("2026"), patched); + } + + [Fact] + public void Write_SameWidth_LowersBasicFileInfo_AndReplanningGivesNoEdits() + { + string source = Synthetic(2026, "source2026.rvt"); + string profile = Synthetic(2025, "profile2025.rvt"); + string sourceHash = Hash(source), profileHash = Hash(profile); + string output = P("downgraded.rvt"); + + var result = DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + Assert.Equal(2026, result.SourceRelease); + Assert.Equal(2025, result.TargetRelease); + Assert.True(File.Exists(output)); + Assert.Equal(sourceHash, Hash(source)); + Assert.Equal(profileHash, Hash(profile)); + + using (var root = RootStorage.OpenRead(output)) + { + var bfi = BasicFileInfoReader.Read(root); + Assert.Equal("2025", bfi["RevitVersion"]); + } + + byte[] outputSchemaBytes, profileSchemaBytes; + using (var outRoot = RootStorage.OpenRead(output)) + outputSchemaBytes = PagedGzipStream.Read(outRoot, "Formats", "Latest")!; + using (var profRoot = RootStorage.OpenRead(profile)) + profileSchemaBytes = PagedGzipStream.Read(profRoot, "Formats", "Latest")!; + var replan = DowngradePlanner.Compute( + TfSchemaReader.TryParse(outputSchemaBytes)!, + TfSchemaReader.TryParse(profileSchemaBytes)!, + GuidRule.Exact); + Assert.Empty(replan.Edits); + Assert.Empty(replan.HigherVersions); + } + + [Fact] + public void Write_SevenAdjacentDowngrades_UseThePreviousOutput() + { + string input = Synthetic(2027, "chain-2027.rvt", includeElemTable: true); + for (int year = 2026; year >= 2020; year--) + { + string profile = Synthetic(year, $"profile-{year}.rvt"); + string output = P($"chain-{year}.rvt"); + var result = DowngradeWriter.Write(input, profile, output, GuidRule.Exact, allowLoss: true); + Assert.Equal((year + 1, year), (result.SourceRelease, result.TargetRelease)); + + var caps = RvtWriter.InspectCapabilities(output); + Assert.Equal(year, caps.SavedRelease); + Assert.Equal(year, caps.SchemaRelease); + Assert.Equal(year >= 2024 ? 8 : 4, caps.ElementIdWidth); + var coverage = CoverageCensus.Read(output); + Assert.Null(coverage.RecordsFailure); + Assert.Equal(0, coverage.Totals.ChecksumMismatches); + Assert.Equal("ok", Assert.Single(coverage.Streams, s => s.Path == "Partitions/1").Framing); + var ids = RvtDocument.Open(output).Elements.Select(e => e.Id).ToArray(); + Assert.Contains(101, ids); + Assert.DoesNotContain(202, ids); + input = output; + } + } + + [Fact] + public void Write_MinimalRule_DoesNotAddProfileGuidsToSharedClasses() + { + string source = Synthetic(2026, "minimal-source.rvt"); + string profileBase = Synthetic(2025, "minimal-profile-base.rvt"); + string profile = P("minimal-profile.rvt"); + const string existing = "00112233445566778899aabbccddeeff"; + const string added = "ffeeddccbbaa99887766554433221100"; + byte[] edited; + using (var root = RootStorage.OpenRead(profileBase)) + { + byte[] schema = PagedGzipStream.Read(root, "Formats", "Latest")!; + edited = SchemaStreamEditor.Apply(schema, [new SchemaEdit("SyntheticItem", Guids: [existing, added])]); + } + ContainerRewriter.Rewrite(profileBase, profile, new Dictionary + { + ["Formats/Latest"] = PagedStreamCodec.Encode([], edited), + }); + + string output = P("minimal-output.rvt"); + DowngradeWriter.Write(source, profile, output, GuidRule.Minimal, allowLoss: true); + + using var written = RootStorage.OpenRead(output); + var schemaClass = TfSchemaReader.Read(written)!.Classes.Single(c => c.Name == "SyntheticItem"); + Assert.Equal([existing], schemaClass.Guids); + Assert.Equal(2025, RvtWriter.InspectCapabilities(output).SchemaRelease); + } + + [Fact] + public void Write_CrossWidth_TranscodesPartitions_AndValidates() + { + string source = Synthetic(2027, "source2027x.rvt", includeElemTable: true); + string profile = Synthetic(2020, "profile2020x.rvt"); + string output = P("cross_out.rvt"); + + var result = DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + Assert.Equal((2027, 2020), (result.SourceRelease, result.TargetRelease)); + Assert.True(File.Exists(output)); + + using (var root = RootStorage.OpenRead(output)) + { + Assert.Equal("2020", BasicFileInfoReader.Read(root)["RevitVersion"]); + } + + // Schema is the profile's: replan is empty, release reads as target. + byte[] outputSchemaBytes, profileSchemaBytes; + using (var outRoot = RootStorage.OpenRead(output)) + outputSchemaBytes = PagedGzipStream.Read(outRoot, "Formats", "Latest")!; + using (var profRoot = RootStorage.OpenRead(profile)) + profileSchemaBytes = PagedGzipStream.Read(profRoot, "Formats", "Latest")!; + var replan = DowngradePlanner.Compute( + TfSchemaReader.TryParse(outputSchemaBytes)!, + TfSchemaReader.TryParse(profileSchemaBytes)!, + GuidRule.Exact); + Assert.Empty(replan.Edits); + + var caps = RvtWriter.InspectCapabilities(output); + Assert.Equal(2020, caps.SavedRelease); + Assert.Equal(2020, caps.SchemaRelease); + Assert.Equal(2020, caps.EffectiveRelease); + Assert.Equal(4, caps.ElementIdWidth); + Assert.True(caps.Supports(RvtWriteOperation.SaveAs)); + + var doc = RvtDocument.Open(output); + Assert.NotNull(doc.RawData); + var census = CoverageCensus.Read(output); + Assert.Null(census.RecordsFailure); + Assert.Equal(0, census.Totals.ChecksumMismatches); + Assert.Equal("ok", census.Streams.Single(s => s.Path == "Partitions/1").Framing); + + // Content check: owners narrowed to 4-byte, SyntheticItem tag remapped by name, + // m_code payload preserved; the unknown-class owner is left out of the block. + SchemaDocument targetDoc; + using (var profRoot = RootStorage.OpenRead(profile)) + targetDoc = TfSchemaReader.Read(profRoot)!; + var targetTags = PartitionFraming.TagsOf(new FormatsSchema(targetDoc))!.Value; + ushort syntheticTarget = (ushort)targetDoc.Classes.Single(c => c.Name == "SyntheticItem").Id; + var recs = new List(); + byte[] outStored; + using (var outRoot = RootStorage.OpenRead(output)) + using (var ps = outRoot.OpenStorage("Partitions").OpenStream("1")) + { + outStored = new byte[ps.Length]; + ps.ReadExactly(outStored); + } + Assert.True(PartitionFraming.Walk(outStored, targetTags, 4, + r => recs.Add(r with { Body = r.Body.ToArray(), Item = r.Item.ToArray() }), + out string? walkFailure, out int walkBlocks), walkFailure); + var ch102 = recs.Where(r => r.Block == 0 && r.Channel == 102 && r.Owner != uint.MaxValue).ToList(); + Assert.Equal([101UL], ch102.Select(r => r.Owner).OrderBy(o => o).ToArray()); + var item101 = ch102.Single(r => r.Owner == 101UL); + Assert.Equal(syntheticTarget, System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(item101.Body.Span)); + Assert.Equal(100, System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(item101.Body.Span[2..])); + Assert.DoesNotContain(recs, r => r.Block == 0 && r.Channel == 102 && r.Owner == 202UL); + + // Element-table parity: the 2020-layout table decodes with the target schema and + // carries the histories of the surviving source elements (the row of the dropped + // unknown-class owner goes with it). + List outRows, srcRows; + using (var outRoot = RootStorage.OpenRead(output)) + outRows = ElemTableLayout.TryParse(PagedGzipStream.Read(outRoot, "Global", "ElemTable")!, new FormatsSchema(targetDoc))!; + SchemaDocument sourceDoc; + using (var srcRoot = RootStorage.OpenRead(source)) + sourceDoc = TfSchemaReader.Read(srcRoot)!; + using (var srcRoot = RootStorage.OpenRead(source)) + srcRows = ElemTableLayout.TryParse(PagedGzipStream.Read(srcRoot, "Global", "ElemTable")!, new FormatsSchema(sourceDoc))!; + Assert.NotNull(outRows); + Assert.NotNull(srcRows); + var sourceIds = RvtDocument.Open(source).Elements.Select(e => e.Id).ToHashSet(); + var outputIds = doc.Elements.Select(e => e.Id).ToHashSet(); + Assert.Contains(101, outputIds); + Assert.DoesNotContain(202, outputIds); + var surviving = srcRows.Where(r => outputIds.Contains((int)r.Id)).ToList(); + Assert.Equal(srcRows.Count(r => r.Id != 202), surviving.Count); + Assert.Equal(surviving.Count, outRows.Count); + Assert.Equal( + surviving.Select(r => (r.Id, r.OriginalId, r.CreationDate, r.PartitionId, r.OwningId)).ToArray(), + outRows.Select(r => (r.Id, r.OriginalId, r.CreationDate, r.PartitionId, r.OwningId)).ToArray()); + Assert.DoesNotContain(outRows, r => r.Id == 202); + + // Element decode parity: every element known to the source ElemTable and kept by + // the rewrite decodes in the downgraded file with the same id. (Block-only heuristic + // discoveries on the synthetic payloads may differ by scan chance and are not compared.) + foreach (var r in surviving) + { + Assert.Contains((int)r.Id, sourceIds); + Assert.Contains((int)r.Id, outputIds); + } + } + + [Fact] + public void Write_DowngradedFile_StillOpens_InRvtIO() + { + string source = Synthetic(2026, "openable2026.rvt"); + string profile = Synthetic(2025, "openable2025.rvt"); + string output = P("openable_out.rvt"); + + DowngradeWriter.Write(source, profile, output, GuidRule.Exact, allowLoss: true); + + var doc = RvtDocument.Open(output); + Assert.NotNull(doc.RawData); + var census = CoverageCensus.Read(output); + Assert.Equal(0, census.Totals.ChecksumMismatches); + } + + [Fact] + public void Cli_Output_WritesFile_AndReportHoldsOutput() + { + string source = Synthetic(2026, "cli_source.rvt"); + string profile = Synthetic(2025, "cli_profile.rvt"); + string output = P("cli_out.rvt"); + string report = P("cli_report.json"); + + var stdout = new StringWriter(); + var stderr = new StringWriter(); + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", "--report", report], stdout, stderr); + + Assert.Equal(0, exit); + Assert.True(File.Exists(output)); + Assert.True(File.Exists(report)); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + Assert.Equal("rvtio-downgrade/1", json.RootElement.GetProperty("schema").GetString()); + Assert.Equal("ok", json.RootElement.GetProperty("status").GetString()); + Assert.Equal("cli_out.rvt", json.RootElement.GetProperty("output").GetProperty("file").GetString()); + Assert.Contains("Downgraded:", stdout.ToString()); + } + + [Fact] + public void Plan_2027Source_2020Profile_IsAllowed_ForCheck_AndWriteSucceeds() + { + string source = Synthetic(2027, "plan2027.rvt"); + string profile = Synthetic(2020, "plan2020.rvt"); + + var plan = DowngradePlanner.Plan(source, profile, GuidRule.Exact, countElements: false); + Assert.Equal((2027, 2020), (plan.SourceRelease, plan.TargetRelease)); + + var stdout = new StringWriter(); + var stderr = new StringWriter(); + int checkExit = DowngradeCommand.Run([source, "--target-profile", profile, "--check"], stdout, stderr); + Assert.Equal(0, checkExit); + Assert.Contains("release 2027", stdout.ToString()); + Assert.Contains("release 2020", stdout.ToString()); + } + + [Fact] + public void Cli_Output_CrossWidth_WritesFile_WithExit0() + { + string source = Synthetic(2027, "cli_src27.rvt"); + string profile = Synthetic(2020, "cli_prof20.rvt"); + string output = P("cli_cross.rvt"); + string report = P("cli_cross_report.json"); + + var stdout = new StringWriter(); + var stderr = new StringWriter(); + int refusal = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--report", report], stdout, stderr); + Assert.Equal(DowngradeCommand.Refused, refusal); + Assert.False(File.Exists(output)); + Assert.Contains("loss-not-allowed", File.ReadAllText(report)); + + int exit = DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", "--report", report], stdout, stderr); + + Assert.Equal(0, exit); + Assert.True(File.Exists(output)); + Assert.Contains("Downgraded:", stdout.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + Assert.Equal("ok", json.RootElement.GetProperty("status").GetString()); + Assert.Contains("202", json.RootElement.GetProperty("omittedRecordOwners").EnumerateArray().Select(owner => owner.GetString())); + Assert.Equal("cli_cross.rvt", json.RootElement.GetProperty("output").GetProperty("file").GetString()); + Assert.Equal(2020, json.RootElement.GetProperty("output").GetProperty("release").GetInt32()); + + var caps = RvtWriter.InspectCapabilities(output); + Assert.Equal(2020, caps.EffectiveRelease); + var doc = RvtDocument.Open(output); + Assert.NotNull(doc.RawData); + } +} diff --git a/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs b/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs new file mode 100644 index 00000000..e7cae094 --- /dev/null +++ b/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs @@ -0,0 +1,77 @@ +using System.IO.Compression; +using System.Text.Json; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; +using static RvtIO.Tests.PartitionStreamEditorTests; + +namespace RvtIO.Tests; + +public sealed class EnergyAnalysisArchiveTests +{ + [Fact] + public void KeepsTheOriginalRecordAndClassTableInsideAProjectInformationEntity() + { + static SchemaField Field(string name, byte type, byte mods = 0, int? reference = null) => + new(name, type, mods, 0, null, reference, null, null); + + var doc = new SchemaDocument + { + Classes = + [ + new(12, "GUIDvalue", 0, 1, [Field("value", 9)], []), + new(13, "ESField", 0, 1, + [Field("m_documentation", 8, 0x60), Field("m_fieldName", 8, 0x60), Field("m_fieldTypeName", 8, 0x60), + Field("m_containerType", 4), Field("m_entryIndex", 4), Field("m_subSchemaGUID", 14, 0, 12), + Field("m_unitType", 4)], []), + new(14, "ESSchema", 0, 3, + [Field("m_documentation", 8, 0x60), Field("m_fields", 14, 0x50, 13), Field("m_schemaName", 8, 0x60), + Field("m_vendorId", 8, 0x60), Field("m_applicationGUID", 14, 0, 12), Field("m_guid", 14, 0, 12), + Field("m_readAccessLevel", 4), Field("m_writeAccessLevel", 4)], []), + new(15, "std::pair< GUIDvalue, ESSchema >", 0, 0, [Field("first", 14, 0, 12), Field("second", 14, 0, 14)], []), + new(16, "ESSchemaStorage", 0, 3, [Field("m_storedSchemas", 14, 0x50, 15)], []), + new(17, "ADocument", 0, 1, [Field("m_storage", 14, 1)], []), + new(18, "ESEntity", 0, 1, [Field("m_blob", 14, 1)], []), + new(19, "std::pair< GUIDvalue, ESEntity >", 0, 0, [Field("first", 14, 0, 12), Field("second", 14, 0, 18)], []), + new(20, "ESEntityCell", 0, 3, [Field("m_entityMap", 14, 0x50, 19)], []), + new(21, "CellList", 0, 3, [Field("m_cells", 14, 0x51)], []), + new(22, "Element", 0, 1, [Field("m_cellList", 14, 1)], []), + new(23, "ProjectInfo", 22, 3, [], []), + new(24, "EnergyAnalysisMaterial", 22, 5, [Field("m_thermalValue", 4)], []), + ], + }; + const string partition = "Partitions/0"; + const string latestPath = "Global/Latest"; + var tags = new PartitionFraming.Tags(200, 201, 202, 203, 204); + byte[] original = TaggedBody(24, [0, 0, 0, 0, 7, 0, 0, 0]); + byte[] project = TaggedBody(23, [0, 0, 0, 0]); + byte[] latest = TaggedBody(17, [255, 255, 255, 255, 16, 0, 0, 0, 0, 0]); + var partitions = new[] { (partition, BuildPartitionStream(4, tags, new SpecBlock(false, + [ + new SpecChain(101, [new(2, project), new(3, original), new(uint.MaxValue, [])]), + new SpecChain(102, [new(2, project), new(3, original), new(uint.MaxValue, [])]), + new SpecChain(103, [new(2, project), new(3, original), new(uint.MaxValue, [])]), + ]))) }; + byte[] classTable = [19, 83, 255, 32]; + var content = Assert.IsType( + EnergyAnalysisArchive.Capture(doc, classTable, 2023, 4, tags, partitions)); + var replacements = new Dictionary { [latestPath] = PageCodec.EncodePadded(GzipMember.Write(latest)) }; + var transcoder = new R22Transcoder(doc, doc, 4); + var attachment = Assert.IsType(EnergyAnalysisArchive.Prepare( + content, doc, doc, tags, 4, partitions, transcoder, replacements)); + + Assert.Equal((partition, 2ul), (attachment.Partition, attachment.Owner)); + var walker = new WideBlockWalker(doc, (c, f) => c.Name == "ESBlob" ? f.Name : null, []); + walker.UseEntitySchemas(EntitySchemaReader.Read(PagedGzipStream.Decompress(replacements[latestPath])!, doc)!); + var walk = walker.Run(attachment.Body, 0, attachment.Body.Length, 23); + Assert.True(walk.Exact, walk.Error); + string payload = Assert.Single(walk.Captures).Text!; + using var gzip = new GZipStream(new MemoryStream(Convert.FromBase64String(payload)), CompressionMode.Decompress); + var recovered = JsonSerializer.Deserialize(gzip)!; + Assert.Equal(classTable, recovered.ClassTable); + var record = Assert.Single(recovered.Records); + Assert.Equal((3ul, "EnergyAnalysisMaterial"), (record.ElementId, record.Class)); + Assert.Equal(original, record.Payload); + Assert.Null(EnergyAnalysisArchive.Prepare(content, doc, doc, tags, 4, partitions, transcoder, replacements)); + } +} diff --git a/tests/RvtIO.Tests/EnergyAnalysisTrackingTests.cs b/tests/RvtIO.Tests/EnergyAnalysisTrackingTests.cs new file mode 100644 index 00000000..fbee5e53 --- /dev/null +++ b/tests/RvtIO.Tests/EnergyAnalysisTrackingTests.cs @@ -0,0 +1,34 @@ +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class EnergyAnalysisTrackingTests +{ + [Fact] + public void AddsMissingCategoriesAndMergesMembersWithoutChangingOtherCategories() + { + byte[] original = Integers(3, -20, 1, 11, -10, 2, 7, 9, -2, 1, 12); + var additions = new Dictionary> { [-15] = [31, 22], [-10] = [9, 19] }; + byte[] expected = Integers(4, -20, 1, 11, -15, 2, 22, 31, -10, 3, 7, 9, 19, -2, 1, 12); + + byte[] registered = EnergyAnalysisTracking.Register(original, additions); + Assert.Equal(expected, registered); + Assert.Equal(registered, EnergyAnalysisTracking.Register(registered, additions)); + } + + [Fact] + public void RejectsTruncatedCategoriesInsteadOfDiscardingTheExistingIndex() + { + Assert.Throws(() => + EnergyAnalysisTracking.Register(Integers(1, -20, 2, 11), new Dictionary>())); + } + + private static byte[] Integers(params int[] values) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + foreach (int value in values) writer.Write(value); + return stream.ToArray(); + } +} diff --git a/tests/RvtIO.Tests/LegacySchemaCatalogsTests.cs b/tests/RvtIO.Tests/LegacySchemaCatalogsTests.cs new file mode 100644 index 00000000..3703189f --- /dev/null +++ b/tests/RvtIO.Tests/LegacySchemaCatalogsTests.cs @@ -0,0 +1,44 @@ +using System.IO; +using System.Text; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class LegacySchemaCatalogsTests +{ + [Fact] + public void UsesBuiltinDefinitionsFromProfileAndCustomDefinitionsFromSource() + { + var source = Catalog(("autodesk.parameter:group-2.0.0", "new"), + ("custom.parameter:description-1.0.0", "project \u2605")); + var profile = Catalog(("custom.parameter:other-1.0.0", "profile"), + ("autodesk.parameter:group-1.0.0", "old")); + + Assert.Equal(Catalog(("autodesk.parameter:group-1.0.0", "old"), + ("custom.parameter:description-1.0.0", "project \u2605")), LegacySchemaCatalogs.Merge(source, profile)); + } + + [Fact] + public void RejectsDuplicateKeysAndTrailingBytes() + { + var duplicate = Catalog(("autodesk.unit:example", "first"), ("autodesk.unit:example", "second")); + Assert.Throws(() => LegacySchemaCatalogs.Merge(duplicate, Catalog())); + Assert.Throws(() => LegacySchemaCatalogs.Merge(Catalog(), [.. Catalog(), 0])); + } + + private static byte[] Catalog(params (string Key, string Value)[] entries) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.Unicode, leaveOpen: true); + writer.Write(entries.Length); + foreach (var (key, value) in entries) + { + writer.Write(key.Length); + writer.Write(Encoding.Unicode.GetBytes(key)); + writer.Write(value.Length); + writer.Write(Encoding.Unicode.GetBytes(value)); + } + return stream.ToArray(); + } +} diff --git a/tests/RvtIO.Tests/LegacyUnitFormatsTests.cs b/tests/RvtIO.Tests/LegacyUnitFormatsTests.cs new file mode 100644 index 00000000..1dc9239f --- /dev/null +++ b/tests/RvtIO.Tests/LegacyUnitFormatsTests.cs @@ -0,0 +1,68 @@ +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class LegacyUnitFormatsTests +{ + [Fact] + public void RestoresTheFormatArrayWithoutReplacingOtherUnitData() + { + var schema = Schema(); + byte[] current = Units(1, 9, 18, 23, []); + byte[] profile = Units(1, 0, null, 75, [31, 45]); + + Assert.Equal(Units(1, 9, 18, 23, [31, 45]), LegacyUnitFormats.Fill(schema, current, profile)); + } + + [Fact] + public void LeavesExistingFormatsAndDifferentUnitSystemsAlone() + { + var schema = Schema(); + byte[] profile = Units(1, 2, null, null, [31, 45]); + + Assert.Null(LegacyUnitFormats.Fill(schema, Units(1, 2, null, null, [7]), profile)); + Assert.Null(LegacyUnitFormats.Fill(schema, Units(0, 2, null, null, []), profile)); + Assert.Null(LegacyUnitFormats.Fill(schema, Units(1, 2, null, null, []), profile[..^1])); + } + + private static SchemaDocument Schema() + { + static SchemaField Field(string name, byte type, byte mods = 0, int? reference = null) => + new(name, type, mods, 0, null, reference, null, null); + return new() + { + Classes = + [ + new(20, "UnitsElem", 0, 1, [Field("before", 14, 1), Field("m_units", 14, 0, 21), Field("after", 14, 1)], []), + new(21, "AUnits", 0, 1, [Field("m_formatOptionsArr", 14, 81), Field("m_universalUnitSystem", 4), + Field("m_decimalSymbol", 4)], []), + new(22, "FormatOptions", 0, 1, [Field("m_displayUnits", 4)], []), + new(23, "OtherCell", 0, 1, [Field("value", 4)], []), + ], + }; + } + + private static byte[] Units(int system, int decimalSymbol, int? before, int? after, int[] formats) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + void Pointer(bool exists, ushort type) + { + writer.Write(exists ? uint.MaxValue : 0); + if (exists) writer.Write(type); + } + writer.Write((ushort)20); + Pointer(before.HasValue, 23); + writer.Write(formats.Length); + foreach (int _ in formats) Pointer(true, 22); + writer.Write(system); + writer.Write(decimalSymbol); + Pointer(after.HasValue, 23); + if (before is int left) writer.Write(left); + foreach (int option in formats) writer.Write(option); + if (after is int right) writer.Write(right); + return stream.ToArray(); + } +} diff --git a/tests/RvtIO.Tests/R22TranscoderQueueDrainTests.cs b/tests/RvtIO.Tests/R22TranscoderQueueDrainTests.cs new file mode 100644 index 00000000..a75eab1e --- /dev/null +++ b/tests/RvtIO.Tests/R22TranscoderQueueDrainTests.cs @@ -0,0 +1,664 @@ +using System.Buffers.Binary; +using RvtIO.Parsing; +using Xunit; +using Cls = RvtIO.Tests.SchemaStreamEditorTests.Cls; +using Fld = RvtIO.Tests.SchemaStreamEditorTests.Fld; +using NoRef = RvtIO.Tests.SchemaStreamEditorTests.NoRef; + +namespace RvtIO.Tests; + +/// A trailing default field value appended to one queued object must survive the cut +/// of the queued object that follows it: the cut discards only the edits strictly inside +/// its own byte range, never a zero-width insertion exactly at its start. +public sealed class R22TranscoderQueueDrainTests +{ + private static SchemaDocument Doc(params Cls[] classes) => + TfSchemaReader.Parse(SchemaStreamEditorTests.Write([.. classes]).Data); + + // Source: R { a: i32, pv: pointer to V, p: pointer to X }, V { d: i32 }, X { x: i32 }. + // Target: R { a, pv, p }, V { d, e: i32 (missing in source, written empty) }, no X. + private static readonly Cls[] SourceModel = + [ + new("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("pv", 0x0E, 1), new Fld("p", 0x0E, 1)], []), + new("V", new NoRef(), 1, [new Fld("d", 0x04)], []), + new("X", new NoRef(), 1, [new Fld("x", 0x04)], []), + ]; + + private static readonly Cls[] TargetModel = + [ + new("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("pv", 0x0E, 1), new Fld("p", 0x0E, 1)], []), + new("V", new NoRef(), 1, [new Fld("d", 0x04), new Fld("e", 0x04)], []), + ]; + + private static byte[] U32(uint v) { var b = new byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(b, v); return b; } + private static byte[] I32(int v) { var b = new byte[4]; BinaryPrimitives.WriteInt32LittleEndian(b, v); return b; } + + [Theory] + [InlineData(2023)] + [InlineData(2025)] + public void PropagationRuleForLayerShadowIsRemovedOnlyForRevit2023(int release) + { + var rule = new Cls("OneDependencyPropagationFilterData", new NoRef(), 1, + [new Fld("m_otherData", 0x04), new Fld("m_atomType", 0x03)], []); + var model = Doc(rule, new Cls("PropagationFilterData", new NoRef(), 1, + [new Fld("m_data", 0x0E, 0x50, 0, null, new SchemaStreamEditorTests.Back(12)), new Fld("tail", 0x04)], [])); + byte[] compatibleRule = [.. I32(-1), .. BitConverter.GetBytes((ushort)1414)]; + byte[] newerRule = [.. I32(-1), .. BitConverter.GetBytes((ushort)1568)]; + byte[] followingRule = [.. I32(-1140103), .. BitConverter.GetBytes((ushort)4)]; + byte[] input = [13, 0, .. I32(3), .. compatibleRule, .. newerRule, .. followingRule, .. I32(42)]; + byte[] expected = release == 2023 + ? [13, 0, .. I32(2), .. compatibleRule, .. followingRule, .. I32(42)] + : input; + var transcoder = new R22Transcoder(model, model, sourceIdWidth: 4, downgradeRelease: release); + + Assert.Equal(expected, transcoder.Payload(input, 0, input.Length, out var failure)); + Assert.Null(failure); + } + + [Theory] + [InlineData("", -2)] + [InlineData("autodesk.spec:custom-1.0.0", -1)] + [InlineData("autodesk.spec.aec:length-2.0.1", 0)] + [InlineData("autodesk.spec.aec.structural:stress-1.0.0", 45)] + [InlineData("autodesk.spec.aec.structural:unmapped-1.0.0", null)] + public void ExtensibleStorageFieldKeepsItsLegacyUnit(string spec, int? expectedUnit) + { + var entryIndex = new Fld("m_entryIndex", 0x04); + var unit = new Fld("m_unitType", 0x04); + var source = Doc( + new Cls("ForgeTypeId", new NoRef(), 1, [new Fld("m_typeId", 0x08)], []), + new Cls("ESField", new NoRef(), 2, + [new Fld("m_specTypeId", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12)), entryIndex], [])); + var target = Doc(new Cls("ESField", new NoRef(), 1, [entryIndex, unit], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + byte[] payload = [13, 0, .. I32(spec.Length), .. System.Text.Encoding.Unicode.GetBytes(spec), .. I32(7)]; + byte[]? converted = transcoder.Payload(payload, 0, payload.Length, out var failure); + + if (expectedUnit is null) + { + Assert.Null(converted); + Assert.Contains(spec, failure); + return; + } + + Assert.Null(failure); + byte[] expected = [12, 0, .. I32(7), .. I32(expectedUnit.Value)]; + Assert.Equal(expected, converted); + var legacy = new R22Transcoder(target, target, sourceIdWidth: 4); + Assert.Equal(expected, legacy.Payload(expected, 0, expected.Length, out _)); + } + + [Theory] + [InlineData(1)] + [InlineData(4)] + [InlineData(10)] + public void NumberingFormatKeepsTheMinimumDigitsInTheLegacyLayout(int digits) + { + var minimumDigits = new Fld("m_minimumNumberOfDigits", 0x04); + var numberingParameter = new Fld("m_numberingParameterId", 0x04); + var source = Doc( + new Cls("NumberingFormatSettings", new NoRef(), 1, + [new Fld("m_firstNumberFormattingOption", 0x04), minimumDigits, new Fld("m_increment", 0x04)], []), + new Cls("NumberingSchema", new NoRef(), 8, + [new Fld("m_formatSettings", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12)), numberingParameter], [])); + var target = Doc(new Cls("NumberingSchema", new NoRef(), 5, [numberingParameter, minimumDigits], [])); + byte[] payload = [13, 0, .. I32(0), .. I32(digits), .. I32(2), .. I32(-1154616)]; + byte[] expected = [12, 0, .. I32(-1154616), .. I32(digits)]; + + var legacy = new R22Transcoder(source, target, sourceIdWidth: 4); + Assert.Equal(expected, legacy.Payload(payload, 0, payload.Length, out var failure)); + Assert.Null(failure); + var current = new R22Transcoder(source, source, sourceIdWidth: 4); + Assert.Equal(payload, current.Payload(payload, 0, payload.Length, out _)); + } + + [Fact] + public void DowngradeDistinguishesElementsFromSameNamedInlineValues() + { + var data = new Fld("value", 0x04); + var element = new Cls("Element", new NoRef(), 1, [], []); + var source = Doc(element, new Cls("EnergyAnalysisMaterial", new SchemaStreamEditorTests.Back(12), 2, [data], [])); + var target = Doc(element, new Cls("EnergyAnalysisMaterial", new NoRef(), 1, [data], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + + Assert.False(transcoder.CanWriteRecord(13, isElement: true)); + Assert.True(transcoder.CanWriteRecord(13, isElement: false)); + Assert.True(transcoder.CanWriteRecord(12, isElement: true)); + Assert.False(transcoder.CanWriteRecord(14, isElement: true)); + byte[] payload = [13, 0, .. I32(7)]; + Assert.Equal(payload, transcoder.Payload(payload, 0, payload.Length, out _)); + + var legacy = new R22Transcoder(target, target, sourceIdWidth: 4); + Assert.False(legacy.CanWriteRecord(13, isElement: true)); + } + + [Fact] + public void NoPointer_DefaultAppended() + { + // No queue at all: R { a } -> R { a, e }. Pins down basic Default insertion. + var source = Doc( + new Cls("R", new NoRef(), 1, [new Fld("a", 0x04)], [])); + var target = Doc( + new Cls("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("e", 0x04)], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + byte[] full = [12, 0, 7, 0, 0, 0]; + byte[]? converted = transcoder.Payload(full, 0, full.Length, out string? failure); + Assert.True(converted != null, "Payload failed: " + failure); + Assert.Equal(new byte[] { 12, 0, 7, 0, 0, 0, 0, 0, 0, 0 }, converted); + } + + [Fact] + public void AddedElementIdInWideTarget_OccupiesEightBytes() + { + var source = Doc(new Cls("Root", new NoRef(), 1, [new Fld("tail", 0x04)], [])); + var target = Doc( + new Cls("Identifier", new NoRef(), 1, [new Fld("m_id64", 0x0B)], []), + new Cls("ElementId", new NoRef(), 1, [new Fld("m_id", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12))], []), + new Cls("Root", new NoRef(), 1, + [new Fld("id", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), new Fld("tail", 0x04)], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 8); + byte[] payload = [12, 0, .. I32(7), 0xAA]; + byte[]? converted = transcoder.PayloadWithTail(payload, 0, payload.Length, out string? failure); + Assert.Null(failure); + Assert.Equal(new byte[] { 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0xAA }, converted); + } + + [Theory] + [InlineData(4)] + [InlineData(8)] + public void MissingMepBaseElementIdUsesTheTargetWidth(int width) + { + var field = new Fld("tail", 0x04); + var source = Doc(new Cls("MEPAnalyticalModelCell", new NoRef(), 1, [field], [])); + var id = width == 8 ? new Fld("m_id64", 0x0B) : new Fld("m_id", 0x04); + var target = Doc( + new Cls("Identifier", new NoRef(), 1, [id], []), + new Cls("ElementId", new NoRef(), 1, [new Fld("m_id", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12))], []), + new Cls("MEPAnalyticalModelCell", new NoRef(), 1, + [new Fld("m_baseElementId", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), field], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 8); + byte[] sourceCell = [12, 0, .. I32(321)]; + byte[] targetCell = [14, 0, .. Enumerable.Repeat((byte)0xFF, width), .. I32(321)]; + + Assert.Equal(targetCell, transcoder.PayloadWithTail(sourceCell, 0, sourceCell.Length, out var failure)); + Assert.Null(failure); + } + + [Fact] + public void AddedInlineRevisionSettings_HaveValidDefaults() + { + var tail = new Fld("tail", 0x04); + var source = Doc(new Cls("AllProjectRevisions", new NoRef(), 1, [tail], [])); + var target = Doc( + new Cls("NumericRevisionSettings", new NoRef(), 1, + [new Fld("m_incrementSize", 0x04), new Fld("m_startNumber", 0x04)], []), + new Cls("AlphanumericRevisionSettings", new NoRef(), 1, [new Fld("m_sequence", 0x08, 0x50)], []), + new Cls("AllProjectRevisions", new NoRef(), 1, + [new Fld("m_numericRevisionSettings", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12)), + new Fld("m_alphanumericRevisionSettings", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), tail], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + byte[] payload = [12, 0, .. I32(7)]; + byte[]? converted = transcoder.PayloadWithTail(payload, 0, payload.Length, out string? failure); + Assert.Null(failure); + Assert.NotNull(converted); + Assert.Equal(new byte[] { 14, 0, 1, 0, 0, 0, 1, 0, 0, 0, 26, 0, 0, 0 }, converted[..14]); + Assert.Equal(1, BinaryPrimitives.ReadInt32LittleEndian(converted.AsSpan(14))); + Assert.Equal((ushort)'A', BinaryPrimitives.ReadUInt16LittleEndian(converted.AsSpan(18))); + Assert.Equal((ushort)'Z', BinaryPrimitives.ReadUInt16LittleEndian(converted.AsSpan(14 + 25 * 6 + 4))); + Assert.Equal(I32(7), converted[^4..]); + } + + [Theory] + [InlineData("AnalyticalMember", "AnalyticalMemberGStep")] + [InlineData("AnalyticalPanel", "AnalyticalPanelGStep")] + public void DowngradeClearsBothGeometryPointersWhenAnalyticalStepIsUnavailable(string elementClass, string stepClass) + { + var element = new Cls("Element", new NoRef(), 1, + [new Fld("m_geomSteps", 0x0E, 1), new Fld("m_pGeomTable", 0x0E, 1), new Fld("m_other", 0x0E, 1)], []); + var analytical = new Cls(elementClass, new SchemaStreamEditorTests.Back(12), 1, [new Fld("coordinate", 0x04)], []); + var steps = new Cls("GeomStepList", new NoRef(), 1, [new Fld("step", 0x0E, 1)], []); + var table = new Cls("GeomTable", new NoRef(), 1, [new Fld("count", 0x04)], []); + var other = new Cls("Other", new NoRef(), 1, [new Fld("value", 0x04)], []); + var source = Doc(element, analytical, steps, table, other, + new Cls(stepClass, new NoRef(), 1, [new Fld("id", 0x04)], [])); + var target = Doc(element, analytical, steps, table, other); + byte[] payload = [13, 0, .. U32(1), 14, 0, .. U32(2), 15, 0, .. U32(3), 16, 0, .. I32(7), + .. U32(4), 17, 0, .. I32(9), .. I32(10), .. I32(11)]; + + var downgrade = new R22Transcoder(source, target, sourceIdWidth: 4, downgradeRelease: 2026); + byte[]? converted = downgrade.Payload(payload, 0, payload.Length, out string? failure); + Assert.Null(failure); + byte[] expected = [13, 0, .. U32(0), .. U32(0), .. U32(3), 16, 0, .. I32(7), .. I32(10)]; + Assert.Equal(expected, converted); + + var current = new R22Transcoder(source, source, sourceIdWidth: 4, downgradeRelease: 2026); + Assert.Equal(payload, current.Payload(payload, 0, payload.Length, out _)); + } + + [Fact] + public void IncompatibleContextualMemberIsOmittedWithoutDroppingLegacyAnalyticalClass() + { + var schema = Doc( + new Cls("AnalyticalMember", new NoRef(), 1, [], []), + new Cls("AnalyticalModelBeam", new NoRef(), 1, [], [])); + var legacy = new R22Transcoder(schema, schema, sourceIdWidth: 4, downgradeRelease: 2022); + byte[] contextualMember = [12, 0]; + byte[] legacyBeam = [13, 0]; + Assert.Null(legacy.Payload(contextualMember, 0, contextualMember.Length, out _)); + Assert.Equal(legacyBeam, legacy.Payload(legacyBeam, 0, legacyBeam.Length, out _)); + + var current = new R22Transcoder(schema, schema, sourceIdWidth: 4); + Assert.Equal(contextualMember, current.Payload(contextualMember, 0, contextualMember.Length, out _)); + } + + [Theory] + [InlineData(2020, 78)] + [InlineData(2021, 81)] + [InlineData(2022, 83)] + [InlineData(2023, 85)] + public void LegacyUniqueSettingsKeepIndicesAndTrimNewSlots(int release, int slots) + { + var schema = Doc( + new Cls("ElementId", new NoRef(), 1, [new Fld("m_id", 0x04)], []), + new Cls("UniqueElementsTracking", new NoRef(), 1, + [new Fld("m_elemIds", 0x0E, 0x50, 0, null, new SchemaStreamEditorTests.Back(12)), new Fld("tail", 0x04)], [])); + var transcoder = new R22Transcoder(schema, schema, sourceIdWidth: 4, downgradeRelease: release); + transcoder.SetDroppedElementIds(new HashSet { 19 }); + byte[] ids = Enumerable.Range(0, slots + 1).SelectMany(i => I32(i == 1 ? 19 : 11)).ToArray(); + byte[] payload = [13, 0, .. I32(slots + 1), .. ids, .. I32(777)]; + + byte[]? result = transcoder.Payload(payload, 0, payload.Length, out string? failure); + + Assert.Null(failure); + Assert.NotNull(result); + Assert.Equal(slots, BinaryPrimitives.ReadInt32LittleEndian(result.AsSpan(2))); + Assert.Equal(-1, BinaryPrimitives.ReadInt32LittleEndian(result.AsSpan(10))); + Assert.Equal(11, BinaryPrimitives.ReadInt32LittleEndian(result.AsSpan(14))); + Assert.Equal(777, BinaryPrimitives.ReadInt32LittleEndian(result.AsSpan(6 + 4 * slots))); + Assert.Equal(10 + 4 * slots, result.Length); + } + + [Fact] + public void PreservesContourLabelVectorsWhenRewritingLegacyLists() + { + string[] fields = ["m_textPos", "m_textDir", "m_textDirPerp"]; + var source = Doc( + new Cls("XYZ", new NoRef(), 1, [new Fld("m_xyz", 7, 0x10, Fixed: 3)], []), + new Cls("ContourLabelingElemCurveData", new NoRef(), 2, fields + .Select(name => new Fld(name + "XYZ", 14, 0x50, Target: new SchemaStreamEditorTests.Back(12))).ToArray(), [])); + var target = Doc(new Cls("ContourLabelingElemCurveData", new NoRef(), 1, fields + .Select(name => new Fld(name, 13, 0x50, Args: [new Fld("", 7, 0x10, Fixed: 3)])).ToArray(), []), + new Cls("XYZ", new NoRef(), 1, [new Fld("m_xyz", 7, 0x10, Fixed: 3)], [])); + byte[] vectors = [.. I32(1), .. BitConverter.GetBytes(1.25), .. BitConverter.GetBytes(2.5), .. BitConverter.GetBytes(-3.75)]; + byte[] payload = [13, 0, .. vectors, .. vectors, .. vectors]; + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + + byte[]? result = transcoder.Payload(payload, 0, payload.Length, out var failure); + + Assert.Null(failure); + Assert.Equal(new byte[] { 12, 0 }.Concat(payload.Skip(2)), result); + } + + [Fact] + public void MovesDeferredSurfaceContourPolylinesToLegacyInlineArrays() + { + var source = Doc( + new Cls("XYZ", new NoRef(), 1, [new Fld("m_xyz", 7, 0x10, Fixed: 3)], []), + new Cls("ContourPolylineWrapper", new NoRef(), 2, + [new Fld("m_arrXYZ", 14, 0x50, Target: new SchemaStreamEditorTests.Back(12))], []), + new Cls("SurfaceContourData", new NoRef(), 1, + [new Fld("m_arr", 14, 0x50, Target: new SchemaStreamEditorTests.Back(13))], []), + new Cls("ContourWrapper", new NoRef(), 2, [new Fld("m_pData", 14, 1), new Fld("m_facets", 4, 0x50)], []), + new Cls("SiteSurface", new NoRef(), 1, + [new Fld("contours", 14, 0x50, Target: new SchemaStreamEditorTests.Back(15))], [])); + var target = Doc( + new Cls("ContourPolylineWrapper", new NoRef(), 1, + [new Fld("m_arr", 13, 0x50, Args: [new Fld("", 7, 0x10, Fixed: 3)])], []), + new Cls("ContourWrapper", new NoRef(), 1, + [new Fld("m_arr", 14, 0x50, Target: new SchemaStreamEditorTests.Back(12)), new Fld("m_facets", 4, 0x50)], []), + new Cls("SiteSurface", new NoRef(), 1, + [new Fld("contours", 14, 0x50, Target: new SchemaStreamEditorTests.Back(13))], [])); + byte[] lines = [.. I32(1), .. I32(1), .. BitConverter.GetBytes(1.25), .. BitConverter.GetBytes(2.5), .. BitConverter.GetBytes(-3.75)]; + byte[] payload = [16, 0, .. I32(2), .. I32(0), .. I32(0), .. U32(3), 14, 0, .. I32(1), .. I32(19), .. lines]; + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + + byte[]? result = transcoder.Payload(payload, 0, payload.Length, out var failure); + + Assert.Null(failure); + byte[] expected = [14, 0, .. I32(2), .. I32(0), .. I32(0), .. lines, .. I32(1), .. I32(19)]; + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("BoundaryConditions", 2022, true)] + [InlineData("AreaLoad", 2022, true)] + [InlineData("AreaLoad", 2021, false)] + [InlineData("LineLoad", 2021, true)] + [InlineData("PointLoad", 2023, false)] + public void LegacyAnalyticalLoadIsOmittedOnlyWhenItsHostWasOmitted(string name, int release, bool omit) + { + var schema = Doc( + new Cls("ElementId", new NoRef(), 1, [new Fld("m_id", 0x04)], []), + new Cls("ElemPick", new NoRef(), 1, + [new Fld("m_elemId", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12))], []), + new Cls("LoadBCBase", new NoRef(), 1, + [new Fld("pick", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13))], []), + new Cls(name, new SchemaStreamEditorTests.Back(14), 1, [], [])); + var transcoder = new R22Transcoder(schema, schema, sourceIdWidth: 4, downgradeRelease: release); + transcoder.SetDroppedElementIds(new HashSet { 19 }); + byte[] dangling = [15, 0, .. I32(19)]; + byte[] kept = [15, 0, .. I32(11)]; + byte[] unhosted = [15, 0, .. I32(-1)]; + + var rewritten = transcoder.Payload(dangling, 0, dangling.Length, out var failure); + if (omit) + { + Assert.Null(rewritten); + Assert.Contains("no host in the target", failure); + } + else Assert.Equal(unhosted, rewritten); + Assert.Equal(kept, transcoder.Payload(kept, 0, kept.Length, out _)); + Assert.Equal(unhosted, transcoder.Payload(unhosted, 0, unhosted.Length, out _)); + } + + [Theory] + [InlineData("NOBLE_SecondaryDataStorage", "m_data")] + [InlineData("NobleDocWarnings", "m_nobleWarningsMap")] + public void DroppedMapKeyRemovesItsQueuedValueAndKeepsOtherItems(string owner, string map) + { + var schema = Doc( + new Cls("ElementId", new NoRef(), 1, [new Fld("m_id", 0x04)], []), + new Cls("MapEntry", new NoRef(), 1, + [new Fld("key", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12)), new Fld("value", 0x0E, 1)], []), + new Cls("Value", new NoRef(), 1, [new Fld("data", 0x04)], []), + new Cls(owner, new NoRef(), 1, + [new Fld(map, 0x0E, 0x50, 0, null, new SchemaStreamEditorTests.Back(13)), new Fld("tail", 0x04)], [])); + var transcoder = new R22Transcoder(schema, schema, sourceIdWidth: 4); + transcoder.SetDroppedElementIds(new HashSet { 19 }); + byte[] payload = [15, 0, .. I32(2), .. I32(19), .. U32(uint.MaxValue), 14, 0, + .. I32(20), .. U32(uint.MaxValue), 14, 0, .. I32(5), .. I32(100), .. I32(200)]; + byte[] expected = [15, 0, .. I32(1), .. I32(20), .. U32(uint.MaxValue), 14, 0, .. I32(5), .. I32(200)]; + + Assert.Equal(expected, transcoder.PayloadWithTail(payload, 0, payload.Length, out var failure)); + Assert.Null(failure); + } + + [Fact] + public void WideDowngradeClearsReferencesToOmittedElements() + { + var schema = Doc( + new Cls("Identifier", new NoRef(), 1, [new Fld("m_id64", 0x0B)], []), + new Cls("ElementId", new NoRef(), 1, + [new Fld("m_id", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12))], []), + new Cls("Root", new NoRef(), 1, + [new Fld("setting", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), + new Fld("dependencies", 0x0E, 0x50, 0, null, new SchemaStreamEditorTests.Back(13))], [])); + const long omitted = (long)uint.MaxValue + 49; + const long retained = omitted + 1; + var transcoder = new R22Transcoder(schema, schema, sourceIdWidth: 8, downgradeRelease: 2025); + transcoder.SetDroppedElementIds(new HashSet { (ulong)omitted }); + byte[] payload = [14, 0, .. BitConverter.GetBytes(omitted), .. I32(2), + .. BitConverter.GetBytes(omitted), .. BitConverter.GetBytes(retained)]; + byte[] expected = [14, 0, .. BitConverter.GetBytes(-1L), .. I32(1), .. BitConverter.GetBytes(retained)]; + Assert.Equal(expected, transcoder.Payload(payload, 0, payload.Length, out var failure)); + Assert.Null(failure); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BrowserOrganizationMapKeepsItsLegacySelections(bool omitSheets) + { + var identifier = new Cls("Identifier", new NoRef(), 1, [new Fld("m_id64", 0x0B)], []); + var elementId = new Cls("ElementId", new NoRef(), 1, + [new Fld("m_id", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(12))], []); + var item = new Cls("std::pair< int, ElementId >", new NoRef(), 0, + [new Fld("first", 0x04), new Fld("second", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13))], []); + var tail = new Fld("m_lastUsedId", 0x04); + var source = Doc(identifier, elementId, item, + new Cls("BrowserOrganizationTracking", new NoRef(), 6, + [tail, new Fld("m_currentBrOrgTypeToBrOrgMap", 0x0E, 0x50, 0, null, new SchemaStreamEditorTests.Back(14))], [])); + var target = Doc(identifier, elementId, item, + new Cls("BrowserOrganizationTracking", new NoRef(), 5, + [new Fld("m_currentBrOrgSchedules", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), + new Fld("m_currentBrOrgSheets", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), + new Fld("m_currentBrOrgViews", 0x0E, 0, 0, null, new SchemaStreamEditorTests.Back(13)), tail], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 8); + if (omitSheets) transcoder.SetDroppedElementIds(new HashSet { 200 }); + byte[] payload = [15, 0, .. I32(777), .. I32(4), .. I32(0), .. BitConverter.GetBytes(100L), + .. I32(4), .. BitConverter.GetBytes(400L), .. I32(3), .. BitConverter.GetBytes(300L), + .. I32(1), .. BitConverter.GetBytes(200L)]; + byte[] expected = [15, 0, .. BitConverter.GetBytes(300L), .. BitConverter.GetBytes(omitSheets ? -1L : 200L), + .. BitConverter.GetBytes(100L), .. I32(777)]; + Assert.Equal(expected, transcoder.Payload(payload, 0, payload.Length, out var failure)); + Assert.Null(failure); + } + + [Theory] + [InlineData(2021)] + [InlineData(2020)] + public void LegacyRebarSystemRekeysSurvivingArchiveObjectsAndTheirReferences(int release) + { + var curve = new Cls("GLine", new NoRef(), 1, [new Fld("m_coord", 0x04)], []); + var root = new Cls("RebarSystem", new SchemaStreamEditorTests.Back(13), 1, + [new Fld("m_curveRef", 0x0E, 3), new Fld("m_documentRef", 0x0E, 3), new Fld("m_curve", 0x0E, 1)], []); + var source = Doc(curve, new Cls("RebarSystemLayer", new NoRef(), 1, [new Fld("m_uncutCurves", 0x0E, 1)], []), root); + var target = Doc(curve, new Cls("RebarSystemLayer", new NoRef(), 1, [], []), root); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4, downgradeRelease: release); + byte[] payload = [14, 0, .. U32(3), 12, 0, .. U32(4), .. U32(1), .. U32(4), 12, 0, .. I32(100), .. I32(200)]; + byte[] expected = [14, 0, .. U32(3), .. U32(1), .. U32(3), 12, 0, .. I32(200)]; + + Assert.Equal(expected, transcoder.Payload(payload, 0, payload.Length, out var failure)); + Assert.Null(failure); + + BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(8), 3); + Assert.Null(transcoder.Payload(payload, 0, payload.Length, out failure)); + Assert.Contains("unresolved archive key 3", failure); + } + + [Fact] + public void LegacyRebarSystemWritesVolumeInItsGeometryStep() + { + var field = new Fld("m_totalVolume", 0x07); + var step = new Fld("step", 0x0E, 1); + var source = Doc( + new Cls("RebarSystemBase", new NoRef(), 2, [step, field], []), + new Cls("RebarSystemGStep", new NoRef(), 2, [], [])); + var target = Doc( + new Cls("RebarSystemBase", new NoRef(), 1, [step], []), + new Cls("RebarSystemGStep", new NoRef(), 1, [field], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4, downgradeRelease: 2021); + byte[] volume = BitConverter.GetBytes(0.1875); + byte[] payload = [12, 0, .. U32(1), 13, 0, .. volume]; + + byte[]? converted = transcoder.Payload(payload, 0, payload.Length, out string? failure); + + Assert.Null(failure); + Assert.Equal(payload, converted); + var walk = new WideBlockWalker(target, (d, f) => d.Name + "." + f.Name, []) + .Run(converted!, 0, converted!.Length, 12); + Assert.True(walk.Exact, walk.Error); + Assert.Equal(0.1875, Assert.Single(walk.Captures, c => c.Key == "RebarSystemGStep.m_totalVolume").Real); + } + + [Fact] + public void LegacyRebarBarTypeKeepsModelDiameter() + { + var source = Doc(new Cls("RebarBarType", new NoRef(), 2, + [new Fld("m_barModelDiameter", 0x07), new Fld("m_barNominalDiameter", 0x07)], [])); + var target = Doc(new Cls("RebarBarType", new NoRef(), 1, [new Fld("m_barDiameter", 0x07)], [])); + byte[] model = BitConverter.GetBytes(0.075); + byte[] payload = [12, 0, .. model, .. BitConverter.GetBytes(0.0625)]; + + var downgrade = new R22Transcoder(source, target, sourceIdWidth: 4, downgradeRelease: 2026); + byte[]? converted = downgrade.Payload(payload, 0, payload.Length, out string? failure); + Assert.Null(failure); + byte[] expected = [12, 0, .. model]; + Assert.Equal(expected, converted); + + var current = new R22Transcoder(source, source, sourceIdWidth: 4, downgradeRelease: 2026); + Assert.Equal(payload, current.Payload(payload, 0, payload.Length, out _)); + } + + [Theory] + [InlineData(1, 1)] + [InlineData(0, 1)] + [InlineData(1, 0)] + public void LegacyRebarKeepsInclusionOfFirstAndLastBars(byte first, byte last) + { + var count = new Fld("m_numberOfBarPositions", 0x04); + var source = Doc(new Cls("RebarInstBase", new NoRef(), 2, + [new Fld("m_includedBars", 0x01, 0x50), count], [])); + var target = Doc(new Cls("RebarInstBase", new NoRef(), 1, + [count, new Fld("m_includeFirstBar", 0x01), new Fld("m_includeLastBar", 0x01)], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + byte[] payload = [12, 0, .. U32(3), first, 1, last, .. I32(3)]; + + byte[]? converted = transcoder.Payload(payload, 0, payload.Length, out string? failure); + Assert.Null(failure); + byte[] expected = [12, 0, .. I32(3), first, last]; + Assert.Equal(expected, converted); + } + + [Fact] + public void DroppedQueuedObjectAlone_Transcodes() + { + // R { a, p->X }, X missing in target: p nulled, X payload cut, no defaults involved. + var source = Doc( + new Cls("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("p", 0x0E, 1)], []), + new Cls("X", new NoRef(), 1, [new Fld("x", 0x04)], [])); + var target = Doc( + new Cls("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("p", 0x0E, 1)], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + var root = new byte[2 + 4 + 4 + 2]; + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(0, 2), 12); + BinaryPrimitives.WriteInt32LittleEndian(root.AsSpan(2, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(root.AsSpan(6, 4), 45); + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(10, 2), 13); + byte[] full = [.. root, .. I32(3)]; + byte[]? converted = transcoder.Payload(full, 0, full.Length, out string? failure); + Assert.True(converted != null, "Payload failed: " + failure); + var expected = new MemoryStream(); + void Tag(int id) { var t = new byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(t, (ushort)id); expected.Write(t); } + Tag(12); expected.Write(I32(1)); expected.Write(new byte[4]); + Assert.Equal(expected.ToArray(), converted); + } + + [Fact] + public void PointerQueueAlone_Transcodes() + { + // Sanity: R { a, pv->V }, V { d } round-trips with tag remap and no edits. + var source = Doc( + new("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("pv", 0x0E, 1)], []), + new("V", new NoRef(), 1, [new Fld("d", 0x04)], [])); + var target = Doc( + new("R", new NoRef(), 1, [new Fld("a", 0x04), new Fld("pv", 0x0E, 1)], []), + new("V", new NoRef(), 1, [new Fld("d", 0x04)], [])); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + var root = new byte[2 + 4 + 4 + 2]; + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(0, 2), 12); + BinaryPrimitives.WriteInt32LittleEndian(root.AsSpan(2, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(root.AsSpan(6, 4), 44); + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(10, 2), 13); + byte[] full = [.. root, .. I32(2)]; + byte[]? converted = transcoder.Payload(full, 0, full.Length, out string? failure); + Assert.True(converted != null, "Payload failed: " + failure); + Assert.Equal(2 + 4 + 4 + 2 + 4, converted.Length); + } + + [Fact] + public void TruncatedInputsFailAndFullObjectTranscodes() + { + var source = Doc(SourceModel); + var target = Doc(TargetModel); + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + var root = new byte[2 + 4 + 4 + 2 + 4 + 2]; + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(0, 2), 12); + BinaryPrimitives.WriteInt32LittleEndian(root.AsSpan(2, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(root.AsSpan(6, 4), 44); + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(10, 2), 13); + BinaryPrimitives.WriteUInt32LittleEndian(root.AsSpan(12, 4), 45); + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(16, 2), 14); + var queuedV = I32(2); + var queuedX = I32(3); + byte[] full = [.. root, .. queuedV, .. queuedX]; + // Prefixes end inside the object: the walk stops, either short of the end or past it. + foreach (int size in new[] { 6, 10, 12, 16, 18, 22 }) + Assert.Null(transcoder.Payload(full, 0, size, out _)); + // The whole object transcodes: dropped pointer nulled, queued V kept with its default tail, X cut. + byte[]? converted = transcoder.Payload(full, 0, full.Length, out string? failure); + Assert.True(converted != null, "Payload failed: " + failure); + Assert.Equal(24, converted.Length); + } + + [Fact] + public void LeadingDefaultStaysWithTheQueuedObjectThatDeclaresIt() + { + var root = new Cls("R", new NoRef(), 1, [new Fld("first", 0x0E, 1), new Fld("second", 0x0E, 1)], []); + var value = new Cls("V", new NoRef(), 1, [new Fld("value", 0x04)], []); + var source = Doc(root, value); + var target = Doc(root, value with { Fields = [new Fld("before", 0x04), new Fld("value", 0x04)] }); + byte[] header = [12, 0, .. U32(44), 13, 0, .. U32(45), 13, 0]; + byte[] input = [.. header, .. I32(4), .. I32(8)]; + + var converted = new R22Transcoder(source, target, sourceIdWidth: 4).Payload(input, 0, input.Length, out var failure); + + Assert.Null(failure); + byte[] expected = [.. header, .. I32(0), .. I32(4), .. I32(0), .. I32(8)]; + Assert.Equal(expected, converted); + } + + [Theory] + [InlineData(1, 31, true)] + [InlineData(2, 31, false)] + [InlineData(1, 30, false)] + public void LegacyDailyScheduleRequiresTheWholeCalendarYear(int firstDay, int lastDay, bool supported) + { + var start = new DateTimeOffset(2024, 1, firstDay, 12, 0, 0, TimeSpan.Zero); + var end = new DateTimeOffset(2024, 12, lastDay, 12, 0, 0, TimeSpan.Zero); + + Assert.Equal(supported, LegacyEnergySchedules.IsCalendarYear(start.ToUnixTimeSeconds(), end.ToUnixTimeSeconds())); + } + + [Fact] + public void TrailingDefaultSurvivesTheCutOfTheNextQueuedObject() + { + var source = Doc(SourceModel); + var target = Doc(TargetModel); + // Class ids: source R=12 V=13 X=14, target R=12 V=13. + var transcoder = new R22Transcoder(source, target, sourceIdWidth: 4); + + // Root R: a=1, pv=(handle 44)->V, p=(handle 45)->X; queued V { d=2 }, queued X { x=3 }. + // Root inline bytes: tag R, a, pv-handle, pv-tag, p-handle, p-tag; queued payloads carry no leading tag. + var root = new byte[2 + 4 + 4 + 2 + 4 + 2]; + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(0, 2), 12); + BinaryPrimitives.WriteInt32LittleEndian(root.AsSpan(2, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(root.AsSpan(6, 4), 44); + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(10, 2), 13); + BinaryPrimitives.WriteUInt32LittleEndian(root.AsSpan(12, 4), 45); + BinaryPrimitives.WriteUInt16LittleEndian(root.AsSpan(16, 2), 14); + var queuedV = I32(2); + var queuedX = I32(3); + byte[] full = [.. root, .. queuedV, .. queuedX]; + + // Payload() takes one object: feed the root object alone is not how the queue works, + // so instead build a single object whose queued V is followed by a dropped X. + // Root2 { a, pv->V } with V { d } + X dropped right after V: + // use the same R: pv->V known (queued), p->X dropped (queued right after V's payload). + byte[]? converted = transcoder.Payload(full, 0, full.Length, out string? failure); + Assert.True(converted != null, "Payload failed: " + failure); + + // Expected: tag R'(12), a=1, pv-handle 44, pv-tag V'(13), p-handle 0 (nulled), + // V payload d=2 plus the default e=0; the X payload is cut out. + var expected = new MemoryStream(); + void Tag(int id) { var t = new byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(t, (ushort)id); expected.Write(t); } + Tag(12); expected.Write(I32(1)); expected.Write(U32(44)); Tag(13); expected.Write(U32(0)); + expected.Write(I32(2)); expected.Write(I32(0)); + Assert.Equal(expected.ToArray(), converted); + + // And the result walks to its last byte under the target schema. + var walker = new WideBlockWalker(target, (d, f) => d.Name + "." + f.Name, []); + var walk = walker.Run(converted, 0, converted.Length, 12); + Assert.True(walk.Exact, walk.Error + " @ " + walk.StopField); + } +} diff --git a/tests/RvtIO.Tests/R22TranscoderTests.cs b/tests/RvtIO.Tests/R22TranscoderTests.cs index 79c5ea07..f165415f 100644 --- a/tests/RvtIO.Tests/R22TranscoderTests.cs +++ b/tests/RvtIO.Tests/R22TranscoderTests.cs @@ -49,6 +49,47 @@ private static byte[] Bytes(Action body) private static void Owned(BinaryWriter w, int tag) { w.Write(0xFFFFFFFFu); w.Write((ushort)tag); } + [Fact] + public void Payload_PrunesExplicitlyDroppedIdsFromSameWidthRecords() + { + var schema = new SchemaDocument + { + Classes = + [ + new(1, "Identifier", 0, 1, [Field("m_id", 4)], []), + new(2, "ElementId", 0, 1, [Field("m_id", 14, 0, 1)], []), + new(30, "Holder", 0, 1, [Field("m_host", 14, 0, 2), Field("m_members", 14, 0x50, 2)], []), + ], + }; + var record = Bytes(writer => + { + writer.Write((ushort)30); + writer.Write(7); + writer.Write(2u); + writer.Write(7); + writer.Write(42); + }); + var transcoder = new R22Transcoder(schema, schema, 4); + Assert.Equal(record, transcoder.Payload(record, 0, record.Length)); + + var walker = new WideBlockWalker(schema, (owner, field) => WideBlockWalker.AllItemsKeyPrefix + owner.Name + "." + field.Name, []); + var walk = walker.Run(record, 0, record.Length, 30); + Assert.True(walk.Exact, walk.Error); + Assert.Collection(walk.Captures.Where(c => c.IsElementId), + first => { Assert.Equal(7, first.Integer); Assert.Equal(2, first.Offset); }, + second => { Assert.Equal(7, second.Integer); Assert.Equal(10, second.Offset); }, + third => { Assert.Equal(42, third.Integer); Assert.Equal(14, third.Offset); }); + + transcoder.SetDroppedElementIds(new HashSet { 7 }); + var expected = Bytes(writer => + { + writer.Write((ushort)30); + writer.Write(-1); + writer.Write(1u); + writer.Write(42); + }); + Assert.Equal(expected, transcoder.Payload(record, 0, record.Length)); + } [Fact] public void Payload_RenumbersCutsInsertsAndLeavesOutUnknownObjects() { @@ -90,6 +131,51 @@ public void Payload_WritesFieldsInTheOrderOfThe2022Class() Assert.Equal(expected, new R22Transcoder(Source(), Target(), 8).Payload(block, 0, block.Length)); } + [Fact] + public void Payload_TakesARenamedNarrowedFieldFromTheSource() + { + var source = new SchemaDocument + { + Classes = + [ + new(1, "Identifier", 0, 2, [Field("m_id64", 11)], []), + new(2, "ElementId", 0, 1, [Field("m_id", 14, 0, 1)], []), + new(30, "Holder", 0, 1, [Field("m_nodes", 14, 0x50, 31)], []), + new(31, "TreeItemData", 0, 1, [Field("m_identifier", 11), Field("m_parentOrOtherDataId", 11), Field("m_type", 4)], []), + ], + }; + var target = new SchemaDocument + { + Classes = + [ + new(1, "Identifier", 0, 1, [Field("m_id", 4)], []), + new(2, "ElementId", 0, 1, [Field("m_id", 14, 0, 1)], []), + new(40, "Holder", 0, 1, [Field("m_nodes", 14, 0x50, 41)], []), + new(41, "TreeItemData", 0, 1, [Field("m_id", 4), Field("m_parentIdOrOtherData", 4), Field("m_type", 4)], []), + ], + }; + var block = Bytes(w => + { + w.Write((ushort)30); + w.Write(2u); + w.Write(1069808L); w.Write(1069828L); w.Write(5); + w.Write(1069463L); w.Write(1069433L); w.Write(1); + }); + var expected = Bytes(w => + { + w.Write((ushort)40); + w.Write(2u); + w.Write(1069808); w.Write(1069828); w.Write(5); + w.Write(1069463); w.Write(1069433); w.Write(1); + }); + + var result = new R22Transcoder(source, target, 8).Payload(block, 0, block.Length); + + Assert.Equal(expected, result); + var walk = new WideBlockWalker(target, (_, _) => null, []).Run(result!, 0, result!.Length, 40); + Assert.True(walk.Exact, walk.Error); + } + [Fact] public void Payload_BytesAfterTheObjectAreNotRewritten_AndSayWhy() { @@ -352,7 +438,7 @@ public void Edits_AreAppliedInTheOrderOfTheirPlaces_WhateverOrderTheyComeIn() expected.AddRange(data[source..end]); var given = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(editType))!; - foreach (var e in edits) given.Add(Activator.CreateInstance(editType, e.Start, e.End, e.Replacement)); + foreach (var e in edits) given.Add(Activator.CreateInstance(editType, e.Start, e.End, e.Replacement, null)); Assert.Equal(expected.ToArray(), (byte[])apply.Invoke(null, [data, start, end, given])!); } @@ -360,7 +446,7 @@ public void Edits_AreAppliedInTheOrderOfTheirPlaces_WhateverOrderTheyComeIn() foreach (var overlapping in new[] { new[] { (2, 6), (4, 8) }, new[] { (4, 8), (2, 6) } }) { var given = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(editType))!; - foreach (var (from, to) in overlapping) given.Add(Activator.CreateInstance(editType, from, to, Array.Empty())); + foreach (var (from, to) in overlapping) given.Add(Activator.CreateInstance(editType, from, to, Array.Empty(), null)); var refused = Assert.Throws(() => apply.Invoke(null, [new byte[10], 0, 10, given])); Assert.Equal("overlapping edits", refused.InnerException!.Message); } diff --git a/tests/RvtIO.Tests/RecordRoutingTests.cs b/tests/RvtIO.Tests/RecordRoutingTests.cs index c23f80a6..3c584daa 100644 --- a/tests/RvtIO.Tests/RecordRoutingTests.cs +++ b/tests/RvtIO.Tests/RecordRoutingTests.cs @@ -9,7 +9,7 @@ namespace RvtIO.Tests; /// stream, and the removal of the records that are not the current copy. public class RecordRoutingTests { - private static byte[] Schema(bool emptyRows = false) + internal static byte[] Schema(bool emptyRows = false) { var stream = new MemoryStream(); var w = new BinaryWriter(stream); @@ -39,7 +39,7 @@ void Class(string name, params (string Name, byte Type, byte Mods, int Ref)[] fi } /// One increment: greatest episode, element count, versions as (cause, count). - private static byte[] Table(IEnumerable<(int Greatest, int Total, (int Cause, int Count)[] Versions)> rows, string user = "u") + internal static byte[] Table(IEnumerable<(int Greatest, int Total, (int Cause, int Count)[] Versions)> rows, string user = "u", int? localCount = null) { var stream = new MemoryStream(); var w = new BinaryWriter(stream); @@ -47,8 +47,9 @@ private static byte[] Table(IEnumerable<(int Greatest, int Total, (int Cause, in var list = rows.ToList(); for (int pass = 0; pass < 2; pass++) { - w.Write((uint)list.Count); - foreach (var (greatest, total, versions) in list) + int rowCount = pass == 1 ? localCount ?? list.Count : list.Count; + w.Write((uint)rowCount); + foreach (var (greatest, total, versions) in list.TakeLast(rowCount)) { w.Write((uint)versions.Length); foreach (var (cause, count) in versions) { w.Write(cause); w.Write(count); } @@ -113,6 +114,21 @@ public void ARedirectBeyondTheIntRangeEndsTheWalk() Assert.Null(DocumentIncrementTable.Route(table, 1)); } + [Fact] + public void ReadsTheActiveLocalIncrementWhenCentralHistoryHasMoreRows() + { + var schema = FormatsSchema.TryParse(Schema())!; + var data = Table(Rows, localCount: 1); + + Assert.Null(DocumentIncrementTable.TryParse(data, schema, out var routingFailure)); + Assert.Equal("global/local row count", routingFailure); + var table = DocumentIncrementTable.TryParse(data, schema, out var failure, allowUnpairedHistory: true); + Assert.Null(failure); + Assert.Equal(Rows.Length, table!.Increments.Count); + Assert.Equal(847, Assert.Single(table.Local).Greatest); + Assert.Null(DocumentIncrementTable.TryParse(data[..^6], schema, out _, allowUnpairedHistory: true)); + } + [Fact] public void ATableThatDoesNotFollowTheSchemaIsRejected() { diff --git a/tests/RvtIO.Tests/RvtWriterTests.cs b/tests/RvtIO.Tests/RvtWriterTests.cs index 1dd27bac..21a63a5a 100644 --- a/tests/RvtIO.Tests/RvtWriterTests.cs +++ b/tests/RvtIO.Tests/RvtWriterTests.cs @@ -9,6 +9,7 @@ using Cls = RvtIO.Tests.SchemaStreamEditorTests.Cls; using Fld = RvtIO.Tests.SchemaStreamEditorTests.Fld; using NoRef = RvtIO.Tests.SchemaStreamEditorTests.NoRef; +using Back = RvtIO.Tests.SchemaStreamEditorTests.Back; namespace RvtIO.Tests; @@ -66,6 +67,9 @@ internal static byte[] BuildSchemaBytesForRelease(int release, bool includeFrami // Sample domain class with one int32 field (type 0x05) so WideBlockWalker walks it cleanly! writer.Top(new Cls("SyntheticItem", new NoRef(), 2, [new Fld("m_code", 0x05)], ["00112233445566778899aabbccddeeff"])); writer.Top(new Cls("RvtLinkSymbol", new NoRef(), 1, [new Fld("m_code", 0x05)], ["112233445566778899aabbccddeeff00"])); + // Element-table support classes so Global/ElemTable streams decode by the file's own + // schema (28-byte rows with 4-byte ids up to 2023, 40-byte rows with 8-byte ids from 2024). + AddElemTableClasses(writer, wideIds: release >= 2024); } domainClasses?.Invoke(writer); @@ -76,6 +80,44 @@ internal static byte[] BuildSchemaBytesForRelease(int release, bool includeFrami return writer.Build(); } + /// Appends Identifier/ElementId/OriginalElementId/EpisodeId/ElementHistory/PartitionId/ElemRec/ElemTable + /// after the classes above (all references point backward). Names, field order and widths follow + /// FormatsSchemaTests for the narrow (28-byte) and wide (40-byte) layouts. + internal static void AddElemTableClasses(SchemaStreamEditorTests.Writer writer, bool wideIds) + { + int NextId() => 12 + writer.Placed.Count; + byte idType = wideIds ? (byte)0x0B : (byte)0x04; + string idName = wideIds ? "m_id64" : "m_id"; + + int identifierId = NextId(); + writer.Top(new Cls("Identifier", new NoRef(), 1, [new Fld(idName, idType)], [])); + int elementIdId = NextId(); + writer.Top(new Cls("ElementId", new NoRef(), 1, [new Fld("m_id", 0x0E, 0, 0, null, new Back(identifierId))], [])); + int originalIdId = NextId(); + writer.Top(new Cls("OriginalElementId", new NoRef(), 1, [new Fld(idName, idType)], [])); + int episodeIdId = NextId(); + writer.Top(new Cls("EpisodeId", new NoRef(), 1, [new Fld("m_id", 0x04)], [])); + int historyId = NextId(); + writer.Top(new Cls("ElementHistory", new NoRef(), 8, + [new Fld("m_originalElementId", 0x0E, 0, 0, null, new Back(originalIdId)), + new Fld("m_creationDate", 0x0E, 0, 0, null, new Back(episodeIdId)), + new Fld("m_lastModificationDate", 0x0E, 0, 0, null, new Back(episodeIdId)), + new Fld("m_lastUserModificationDate", 0x0E, 0, 0, null, new Back(episodeIdId))], [])); + int partitionIdId = NextId(); + writer.Top(new Cls("PartitionId", new NoRef(), 1, [new Fld("m_id", 0x04)], [])); + int elemRecId = NextId(); + Fld historyField = new("m_history", 0x0E, 0, 0, null, new Back(historyId)); + Fld idField = new("m_id", 0x0E, 0, 0, null, new Back(elementIdId)); + Fld ownerField = new("m_OwningElementId", 0x0E, 0, 0, null, new Back(elementIdId)); + Fld partitionField = new("m_partitionId", 0x0E, 0, 0, null, new Back(partitionIdId)); + writer.Top(new Cls("ElemRec", new NoRef(), 10, + wideIds ? [historyField, idField, ownerField, partitionField] : [idField, historyField, partitionField, ownerField], [])); + int elemTableId = NextId(); + writer.Top(new Cls("ElemTable", new NoRef(), 9, + [new Fld("m_elemArr", 0x0E, 0x50, 0, null, new Back(elemRecId)), new Fld("m_bExpandAllOnLoad", 0x01)], [])); + _ = elemTableId; + } + internal static byte[] BuildBasicFileInfoBytes( int? savedRelease, string? worksharing = "Not enabled", @@ -144,6 +186,9 @@ internal sealed class SyntheticFileOptions public bool IncludeSchema { get; init; } = true; public bool IncludeFramingMarkers { get; init; } = true; public bool IncludePartitions { get; init; } = true; + /// Writes Global/ElemTable with rows for the project-block owners, encoded by the file's own schema + /// (requires schema classes). Default false keeps existing fixtures byte-identical. + public bool IncludeElemTable { get; init; } public string? LinkedPath { get; init; } = @"links\Arch_Link.rvt"; public string LinkedPathType { get; init; } = "Relative"; public string LinkedLoadState { get; init; } = "Loaded"; @@ -271,9 +316,56 @@ internal static string CreateSyntheticRevitFile(string path, SyntheticFileOption p1.Write(partBytes); } + // Element table (opt-in): one row per project-block owner, encoded in the file's own ElemRec layout. + if (opt.IncludeElemTable && parsedSchema is not null && opt.IncludeFramingMarkers && opt.SchemaRelease >= 2020) + { + var elemSchema = new FormatsSchema(parsedSchema); + if (elemSchema.Get("ElemRec") is { } elemRec + && elemSchema.Get("ElemTable") is { } elemTable + && ElemTableLayout.RowLength(elemSchema) is int elemRowLength + && ElemTableLayout.IdWidth(elemSchema) is int elemWidth) + { + var owners = new List { 101UL, 202UL }; + if (opt.IncludeRevitLinkRecord) owners.Add(501UL); + using var ms = new MemoryStream(); + using var bw = new BinaryWriter(ms); + bw.Write((ushort)elemTable.Id); + bw.Write((uint)owners.Count); + foreach (ulong owner in owners) + WriteElemTableRow(bw, elemSchema, elemRec, elemRowLength, elemWidth, owner); + bw.Write((byte)0); // m_bExpandAllOnLoad + using var et = global.CreateStream("ElemTable"); + et.Write(PagedStreamCodec.Encode([0, 0, 0, 0, 0, 0, 0, 0], ms.ToArray())); + } + } + return path; } + internal static void WriteElemTableRow(BinaryWriter bw, FormatsSchema schema, FormatsSchema.ClassDef rec, int rowLength, int idWidth, ulong id) + { + byte[] row = new byte[rowLength]; + void PutId(string[] path, long value) + { + int off = ElemTableLayout.Offset(schema, rec, path)!.Value; + if (idWidth == 8) BinaryPrimitives.WriteInt64LittleEndian(row.AsSpan(off, 8), value); + else BinaryPrimitives.WriteUInt32LittleEndian(row.AsSpan(off, 4), unchecked((uint)value)); + } + void PutInt(string[] path, int value) + { + int off = ElemTableLayout.Offset(schema, rec, path)!.Value; + BinaryPrimitives.WriteInt32LittleEndian(row.AsSpan(off, 4), value); + } + PutId(["m_id"], (long)id); + PutId(["m_history", "m_originalElementId"], (long)id); + PutInt(["m_history", "m_creationDate"], 0); + PutInt(["m_history", "m_lastModificationDate"], 0); + PutInt(["m_history", "m_lastUserModificationDate"], 0); + PutInt(["m_partitionId"], 1); + PutId(["m_OwningElementId"], -1); + bw.Write(row); + } + private static string FileSha256(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); [Theory] diff --git a/tests/RvtIO.Tests/TagCellRewriterTests.cs b/tests/RvtIO.Tests/TagCellRewriterTests.cs new file mode 100644 index 00000000..e6766741 --- /dev/null +++ b/tests/RvtIO.Tests/TagCellRewriterTests.cs @@ -0,0 +1,59 @@ +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class TagCellRewriterTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WritesTheLocalHostAndForeignSentinelIntoLegacyFabricTag(bool wide) + { + const int identifier = 20, elementId = 21, foreign = 22, link = 23; + const int independent = 30, fabric = 31, reference = 32, key = 33; + var source = Schema(wide, + Class(independent, "IndependentTag", 0, Field("m_reference", 14)), + Class(fabric, "FabricReinSpanSymbol", independent), + wide + ? Class(reference, "TagReferenceWithLeader", 0, Field("m_referenceIdKey", 14, key), Field("m_materialElemId", 14, link)) + : Class(reference, "TaggedElem", 0, Field("m_materialElemId", 14, link), Field("m_taggedId", 14, link)), + Class(key, "ReferenceIdKey", 0, Field("m_subkey", 4), Field("m_hostOrLinkElemId", 14, link))); + var target = Schema(false, + Class(independent, "IndependentTag", 0, Field("m_taggedElementId", 14, link), Field("m_materialElemId", 14, link)), + Class(fabric, "FabricReinSpanSymbol", independent)); + byte[] referenceFields = wide + ? [.. BitConverter.GetBytes(0), .. BitConverter.GetBytes(75L), .. BitConverter.GetBytes(-1L), + .. BitConverter.GetBytes(-1L), .. BitConverter.GetBytes(-1L)] + : [.. BitConverter.GetBytes(-1), .. BitConverter.GetBytes(-1), + .. BitConverter.GetBytes(75), .. BitConverter.GetBytes(-1)]; + byte[] payload = [.. BitConverter.GetBytes((ushort)fabric), .. BitConverter.GetBytes(uint.MaxValue), + .. BitConverter.GetBytes((ushort)reference), .. referenceFields]; + byte[] legacy = [.. BitConverter.GetBytes((ushort)fabric), .. new byte[16]]; + + var rewrite = TagCellRewriter.Create(source, target, entitySchemas: null, wide ? 8 : 4); + Assert.NotNull(rewrite); + var converted = Assert.IsType(rewrite(payload, legacy)); + Assert.Equal(new[] { 75, -1, -1, -1 }, + Enumerable.Range(0, 4).Select(i => BitConverter.ToInt32(converted, 2 + i * 4))); + + static SchemaDocument Schema(bool wide, params SchemaClass[] classes) => new() + { + Classes = + [ + Class(identifier, "Identifier", 0, Field("m_id", wide ? (byte)11 : (byte)4)), + Class(elementId, "ElementId", identifier), + Class(foreign, "ForeignElemRef", 0, Field("m_id", wide ? (byte)11 : (byte)4)), + Class(link, "RoomBoundingItem", 0, Field("m_linkInstOrHostId", 14, elementId), Field("m_linkRef", 14, foreign)), + .. classes + ] + }; + } + + private static SchemaClass Class(int id, string name, int parent, params SchemaField[] fields) + => new(id, name, parent, 0, [.. fields], []); + + private static SchemaField Field(string name, byte type, int? reference = null) + => new(name, type, 0, 0, null, reference, null, null); +} diff --git a/tests/RvtIO.Tests/TranscoderPointerMismatchTests.cs b/tests/RvtIO.Tests/TranscoderPointerMismatchTests.cs new file mode 100644 index 00000000..15e78c2b --- /dev/null +++ b/tests/RvtIO.Tests/TranscoderPointerMismatchTests.cs @@ -0,0 +1,50 @@ +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class TranscoderPointerMismatchTests +{ + private static SchemaField Field(string name, byte type, byte mods = 0, int? reference = null) => + new(name, type, mods, 0, null, reference, null, null); + + [Fact] + public void DetectsWrongDerivedClass() + { + // source: Holder owns a Base pointer holding a Derived (Derived : Base) + var source = new SchemaDocument + { + Classes = + [ + new(1, "Identifier", 0, 2, [Field("m_id64", 11)], []), + new(2, "ElementId", 0, 1, [Field("m_id", 14, 0, 1)], []), + new(10, "Base", 0, 1, [], []), + new(11, "Derived", 10, 1, [], []), + new(12, "Holder", 0, 1, [Field("m_child", 14, 1, 10)], []), + ], + }; + // target: Derived does NOT derive from Base (flat hierarchy) + var target = new SchemaDocument + { + Classes = + [ + new(1, "Identifier", 0, 1, [Field("m_id", 4)], []), + new(2, "ElementId", 0, 1, [Field("m_id", 14, 0, 1)], []), + new(20, "Base", 0, 1, [], []), + new(21, "Derived", 0, 1, [], []), + new(22, "Holder", 0, 1, [Field("m_child", 14, 1, 20)], []), + ], + }; + var transcoder = new R22Transcoder(source, target, 8); + // Holder payload: root tag + handle + tag(Derived); the queued Derived object + // has no fields, so nothing follows (its tag is consumed when the pointer is read) + var body = new List(); + void U16(ushort v) { body.AddRange(BitConverter.GetBytes(v)); } + void U32(uint v) { body.AddRange(BitConverter.GetBytes(v)); } + void U64(ulong v) { body.AddRange(BitConverter.GetBytes(v)); } + U16(12); U32(1); U16(11); + var result = transcoder.Payload([.. body], 0, body.Count, out string? failure); + Assert.True(result is not null, "payload null: " + failure); + Assert.True(transcoder.PointerMismatches.Count > 0, "expected a mismatch"); + } +} diff --git a/tools/verify-downgrade-chain.ps1 b/tools/verify-downgrade-chain.ps1 new file mode 100644 index 00000000..8737e92c --- /dev/null +++ b/tools/verify-downgrade-chain.ps1 @@ -0,0 +1,90 @@ +param( + [Parameter(Mandatory)][string]$Cli, + [Parameter(Mandatory)][string]$Source, + [Parameter(Mandatory)][hashtable]$Profiles, + [Parameter(Mandatory)][string]$Output, + [switch]$RestoreLegacyAnalytics +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +function Invoke-RvtIO { + & dotnet $cliPath @args | Out-Host + if ($LASTEXITCODE -ne 0) { + throw "rvtio $($args[0]) exited with code $LASTEXITCODE." + } +} + +$cliPath = (Get-Item -LiteralPath $Cli).FullName +$inputFile = (Get-Item -LiteralPath $Source).FullName +$profileFiles = @{} +foreach ($year in 2026..2020) { + if (!$Profiles.ContainsKey($year)) { throw "Missing profile for Revit $year." } + $profileFiles[$year] = (Get-Item -LiteralPath $Profiles[$year]).FullName +} + +$folder = (New-Item -ItemType Directory -Path $Output).FullName +$manifest = Join-Path $folder 'chain.jsonl' +$cliHash = (Get-FileHash -LiteralPath $cliPath -Algorithm SHA256).Hash +$libraryPath = Join-Path (Split-Path $cliPath) 'RvtIO.dll' +$libraryHash = (Get-FileHash -LiteralPath $libraryPath -Algorithm SHA256).Hash +$previousHash = $null +foreach ($year in 2026..2020) { + $profile = $profileFiles[$year] + $result = Join-Path $folder "$year.rvt" + $writeReport = Join-Path $folder "$year.downgrade.json" + $coverageReport = Join-Path $folder "$year.coverage.json" + $inputHash = (Get-FileHash -LiteralPath $inputFile -Algorithm SHA256).Hash + if ($previousHash -and $inputHash -ne $previousHash) { + throw "The output of the previous step changed before the downgrade to $year." + } + $profileHash = (Get-FileHash -LiteralPath $profile -Algorithm SHA256).Hash + + $restore = @(if ($RestoreLegacyAnalytics -and $year -eq 2022) { '--restore-legacy-analytics' }) + Invoke-RvtIO downgrade $inputFile --target-profile $profile --output $result --allow-loss --report $writeReport @restore + $write = Get-Content -LiteralPath $writeReport -Raw | ConvertFrom-Json + if ($write.source.release -ne ($year + 1) -or $write.profile.release -ne $year) { + throw "The write report does not describe the expected step $($year + 1) to $year." + } + + Invoke-RvtIO coverage $result --report $coverageReport --top 0 + $coverage = Get-Content -LiteralPath $coverageReport -Raw | ConvertFrom-Json + $partitions = @($coverage.streams | Where-Object kind -eq 'partition') + $width = if ($year -ge 2024) { 8 } else { 4 } + if ($coverage.savedRelease -ne $year -or $coverage.schemaRelease -ne $year -or $coverage.idWidth -ne $width -or + $partitions.Count -eq 0 -or @($partitions | Where-Object framing -ne 'ok').Count -gt 0 -or + !$coverage.PSObject.Properties['records'] -or $coverage.records.totals.checksumMismatches -ne 0) { + throw "Structural verification failed for $year. See $coverageReport." + } + if ((Get-FileHash -LiteralPath $inputFile -Algorithm SHA256).Hash -ne $inputHash -or + (Get-FileHash -LiteralPath $profile -Algorithm SHA256).Hash -ne $profileHash) { + throw "An input file changed during the downgrade to $year." + } + + $previousHash = (Get-FileHash -LiteralPath $result -Algorithm SHA256).Hash + [ordered]@{ + sourceRelease = $year + 1 + source = $inputFile + sourceSha256 = $inputHash + targetRelease = $year + profile = $profile + profileSha256 = $profileHash + output = $result + outputSha256 = $previousHash + cliSha256 = $cliHash + librarySha256 = $libraryHash + idWidth = $width + partitions = $partitions.Count + checksums = 'ok' + } | ConvertTo-Json -Compress | Add-Content -LiteralPath $manifest -Encoding UTF8 + + $inputFile = $result +} + +if ((Get-FileHash -LiteralPath $cliPath -Algorithm SHA256).Hash -ne $cliHash -or + (Get-FileHash -LiteralPath $libraryPath -Algorithm SHA256).Hash -ne $libraryHash) { + throw "The CLI or library changed during the downgrade chain." +} + +Write-Output $manifest From 5676436af2b14e0ae566d4d76ed788b0b3b7e68a Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:30:01 +0300 Subject: [PATCH 2/3] Preserve the existing Revit 2022 layout reader --- src/RvtIO/Parsing/R22Transcoder.cs | 27 +++++++++++++++--------- src/RvtIO/Parsing/WideSolidQuantities.cs | 2 +- src/RvtIO/RvtFileReader.R22Layout.cs | 2 +- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index 78c97314..b86e5e9b 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -42,6 +42,7 @@ private sealed class Fail(string message) : Exception(message); private readonly int _sourceWidth; private readonly int _sourceIdentifier; private readonly ElementIdMap? _ids; + private readonly bool _forReader; private readonly int _targetIdentifierWidth; private readonly bool _tagMapping; private readonly bool _clearAnalyticalMemberGeometry; @@ -63,9 +64,10 @@ private sealed record Plan((SchemaClass Declaring, SchemaField Field)[] Source, int[] TargetIndex, bool[] TargetPresent, bool Reordered, bool[] Narrow); internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceIdWidth, - IReadOnlyDictionary? entitySchemas = null, bool tagMapping = false, int? downgradeRelease = null, ElementIdMap? ids = null) + IReadOnlyDictionary? entitySchemas = null, bool tagMapping = false, int? downgradeRelease = null, ElementIdMap? ids = null, bool forReader = false) { _tagMapping = tagMapping; + _forReader = forReader; _uniqueElementSlots = downgradeRelease switch { 2020 => 78, 2021 => 81, 2022 => 83, 2023 => 85, _ => null }; if (downgradeRelease == 2023) _legacyPropagationRule = source.Classes.FirstOrDefault(c => c.Name == "OneDependencyPropagationFilterData" @@ -97,9 +99,9 @@ internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceI // The 2022 table declares this preview class, but released Revit 2022 rejects its instances. if (downgradeRelease == 2022 && c.Name == ContextualAnalyticalMember) continue; if (_targetByName.TryGetValue(c.Name, out int id) - || (RenamedClasses.TryGetValue(c.Name, out string? renamedClass) && _targetByName.TryGetValue(renamedClass, out id)) + || (!_forReader && RenamedClasses.TryGetValue(c.Name, out string? renamedClass) && _targetByName.TryGetValue(renamedClass, out id)) || (_tagMapping && TagRenamedClasses.TryGetValue(c.Name, out string? renamed) && _targetByName.TryGetValue(renamed, out id)) - || (ProjectedClasses.TryGetValue(c.Name, out var projection) && _targetByName.TryGetValue(projection.TargetClass, out id))) + || (!_forReader && ProjectedClasses.TryGetValue(c.Name, out var projection) && _targetByName.TryGetValue(projection.TargetClass, out id))) _tagMap[c.Id] = id; } if (downgradeRelease is <= 2022 && source.Classes.FirstOrDefault(c => c.Name == "LoadBCBase") is { } loadBase) @@ -634,7 +636,7 @@ private sealed class Context(byte[] data, int pos, int end) c.Cutting = true; ReadObject(c, tag); c.Cutting = false; - c.Edits.RemoveAll(e => e.Start > start || (e.Start == start && e.End > start)); + c.Edits.RemoveAll(e => e.Start > start || (e.Start == start && (_forReader || e.End > start))); c.Edits.Add(new(start, c.Pos, [])); for (int j = mark; j < c.Queue.Count; j++) c.Queue[j] = (c.Queue[j].Tag, true); c.Slot = -1; @@ -652,6 +654,9 @@ private sealed class Context(byte[] data, int pos, int end) } try { + // The reader uses the shipped schema, which lacks template arguments needed for archive validation. + if (_forReader) return Apply(data, offset, c.Pos, c.Edits); + byte[] assembled = Assemble(c, offset, c.Pos); if (_inlineContourSiteSurface != 0 && IsKindOf(_source, rootClass, _inlineContourSiteSurface)) { @@ -854,7 +859,7 @@ private Plan PlanOf(int sourceClass) var index = new Dictionary<(string, string), int>(); for (int i = 0; i < target.Length; i++) index[(target[i].Declaring.Name, target[i].Field.Name)] = i; string TargetName(string declaring, string field) => - !index.ContainsKey((declaring, field)) && TryRenamed(declaring, field, out var rename) ? rename.Name : field; + !_forReader && !index.ContainsKey((declaring, field)) && TryRenamed(declaring, field, out var rename) ? rename.Name : field; var sourceKeys = source.Select(s => (s.Declaring.Name, TargetName(s.Declaring.Name, s.Field.Name))).ToHashSet(); var targetIndex = source.Select(s => index.GetValueOrDefault((s.Declaring.Name, TargetName(s.Declaring.Name, s.Field.Name)), -1)).ToArray(); // Revit 2024 widened some 32-bit fields to 64 bits under a new name ("m_id" became "m_id64", "m_otherInt" "m_otherInt64"): @@ -887,6 +892,7 @@ string TargetName(string declaring, string field) => // A field the target declares in another class of the chain (a base class renamed between // the releases): match it by its own name when the type and modifiers agree and it is the // only free target field of that name. + if (!_forReader) { var claimed = new HashSet(targetIndex.Where(k => k >= 0)); var unmatched = Enumerable.Range(0, source.Length).Where(i => targetIndex[i] < 0).ToList(); @@ -953,16 +959,16 @@ private void ReadObject(Context c, int sourceClass) private void ReadFields(Context c, int sourceClass, int depth) { string sourceName = _source[sourceClass].Name; - if (!_targetByName.ContainsKey(sourceName) && ProjectedClasses.TryGetValue(sourceName, out var projected)) + if (!_forReader && !_targetByName.ContainsKey(sourceName) && ProjectedClasses.TryGetValue(sourceName, out var projected)) { ReadProjectedClass(c, sourceClass, projected.SubField, depth); return; } var plan = PlanOf(sourceClass); - bool projectBrowserMap = sourceName == "BrowserOrganizationTracking" + bool projectBrowserMap = !_forReader && sourceName == "BrowserOrganizationTracking" && plan.Source.Any(f => f.Field.Name == "m_currentBrOrgTypeToBrOrgMap") && !plan.Target.Any(f => f.Field.Name == "m_currentBrOrgTypeToBrOrgMap"); - bool projectEsUnit = sourceName == "ESField" + bool projectEsUnit = !_forReader && sourceName == "ESField" && plan.Target.Any(f => f.Field.Name == "m_unitType") && !plan.Source.Any(f => f.Field.Name == "m_unitType"); bool composeFields = plan.Reordered || projectBrowserMap || projectEsUnit; @@ -1076,7 +1082,7 @@ byte[] MissingField(int index) { // the objects of the pointers follow in the order of the fields; at the top level // the queue is put into the order of the target fields when the payload is assembled - if (depth > 0 && k < lastQueuing) throw new Fail("pointer fields change their order"); + if ((_forReader || depth > 0) && k < lastQueuing) throw new Fail("pointer fields change their order"); if (depth == 0 && k < lastQueuing) c.NeedsValidation = true; if (k >= 0) { @@ -1400,7 +1406,8 @@ private void ReadReference(Context c, string? declaring, SchemaField f, int dept id = -1; c.DiagMinusOne++; } - if (narrow && (id < int.MinValue || id > uint.MaxValue)) throw new Fail("id beyond 32 bits: " + id); + long maximum = _forReader ? int.MaxValue : uint.MaxValue; + if (narrow && (id < int.MinValue || id > maximum)) throw new Fail("id beyond 32 bits: " + id); if (narrow || (dangling && id == -1)) c.Edits.Add(new(p, p + _sourceWidth, TargetElementId(id))); } diff --git a/src/RvtIO/Parsing/WideSolidQuantities.cs b/src/RvtIO/Parsing/WideSolidQuantities.cs index 8f74b2b7..3a88df4b 100644 --- a/src/RvtIO/Parsing/WideSolidQuantities.cs +++ b/src/RvtIO/Parsing/WideSolidQuantities.cs @@ -30,7 +30,7 @@ internal readonly record struct Solid(double Volume, double Surface, double? Lar internal WideSolidQuantities(FileSchema schema, IReadOnlyList frames, ElementIdMap? ids = null) { - _geometryLayout = new(schema.Document, GeometrySchema.Value, 8, ids: ids); + _geometryLayout = new(schema.Document, GeometrySchema.Value, 8, ids: ids, forReader: true); var ambiguous = new HashSet(); foreach (var frame in frames) { diff --git a/src/RvtIO/RvtFileReader.R22Layout.cs b/src/RvtIO/RvtFileReader.R22Layout.cs index 18a19457..3960ef7d 100644 --- a/src/RvtIO/RvtFileReader.R22Layout.cs +++ b/src/RvtIO/RvtFileReader.R22Layout.cs @@ -22,7 +22,7 @@ private static (List Chunks, int PartitionChunkCount, List(chunks.Count); // The unit of work is a stream: each partition stream and each framed stream the rewrite reads. int streamCount = partitionStreams.Count + framedStreams.Count(frame => frame != null); From fb5f17e2a31b89bc5affcb558acb51d0eb5912d1 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:46:29 +0300 Subject: [PATCH 3/3] Reject incomplete unit profiles for legacy project downgrades --- CHANGELOG.md | 2 +- README.md | 4 ++++ src/RvtIO/Writing/DowngradeWriter.cs | 10 ++++++-- tests/RvtIO.Tests/DowngradeWriterTests.cs | 28 +++++++++++++++++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20a84cc4..a3cb948d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ API between minor releases. ### Added -- Add experimental native RVT downgrade output using a target-release profile. The CLI writes a separate file and can report known omissions. +- Add experimental native RVT downgrade output using a target-release profile. The CLI writes a separate file and can report known omissions. Writing projects for Revit 2020 or 2021 requires a complete target project with unit data. - Report progress while reading a Revit file: `RvtReadProgress` (phase, completed and total units), `RvtReaderOptions.Progress` and `RvtSceneOptions.ReadProgress` (for `RvtSceneReader.Read(path)`). The reader calls diff --git a/README.md b/README.md index f69282e8..8fda94eb 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,10 @@ rvtio downgrade project2027.rvt --target-profile profile2026.rvt --output projec Use a profile saved by the target release. `--check` compares class versions, stored fields, and upgrade identifiers and writes only the optional report. +When writing a project for Revit 2020 or 2021, use a complete `.rvt` saved by +that release. The writer uses project unit formats for 2020 and unit schema +catalogs for 2021. A profile containing only a class table is usable with +`--check`. `--guid-rule exact` is the default. `--guid-rule minimal` keeps identifiers that both tables declare. `--output` writes a separate RVT and leaves the original and profile intact. For a chain across multiple releases, use the output of diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs index 84c1cfd9..b850cb76 100644 --- a/src/RvtIO/Writing/DowngradeWriter.cs +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -103,8 +103,14 @@ private static DowngradeWriteResult Transcode( ps.ReadExactly(profileStored); sourceBfiProfile = ReadRawStream(profileRoot, "BasicFileInfo"); profileContents = TryReadOptionalStream(profileRoot, "Contents"); - if (isProject && planResult.TargetRelease == 2021) - profileLatest = PagedGzipStream.Read(profileRoot, "Global", "Latest"); + if (isProject && planResult.TargetRelease == 2021 && + profileDoc.Classes.Any(c => c.Name == "ESSchemaStorage" && c.Fields.Any(f => f.Name == "m_storedForgeSchemas"))) + profileLatest = PagedGzipStream.Read(profileRoot, "Global", "Latest") + ?? throw new DowngradeRefusedException("profile-missing-unit-data", + "Writing a Revit 2021 project requires a complete RVT saved in Revit 2021 with its unit schema catalogs (Global/Latest)."); + if (isProject && planResult.TargetRelease == 2020 && !profileRoot.TryOpenStorage("Partitions", out _)) + throw new DowngradeRefusedException("profile-missing-unit-data", + "Writing a Revit 2020 project requires a complete RVT saved in Revit 2020 with its project unit formats (Partitions)."); } if (sourcePartitions.Count == 0) throw new DowngradeRefusedException("missing-partitions", "The source file has no numbered partition streams to transcode."); diff --git a/tests/RvtIO.Tests/DowngradeWriterTests.cs b/tests/RvtIO.Tests/DowngradeWriterTests.cs index 30888056..4e256ceb 100644 --- a/tests/RvtIO.Tests/DowngradeWriterTests.cs +++ b/tests/RvtIO.Tests/DowngradeWriterTests.cs @@ -22,6 +22,34 @@ public sealed class DowngradeWriterTests : IDisposable private static string Hash(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); + [SkippableTheory] + [InlineData(2020)] + [InlineData(2021)] + public void LegacyProjectWriteRequiresUnitDataFromTheProfile(int release) + { + string source = TestFiles.Find("rstbasic22.rvt"); + string projectProfile = TestFiles.Find($"rstbasic{release - 2000}.rvt"); + string classTableProfile = P("class-table.rvt"); + using (var project = RootStorage.OpenRead(projectProfile)) + using (var stripped = RootStorage.Create(classTableProfile, OpenMcdf.Version.V3)) + { + using var basicInfo = project.OpenStream("BasicFileInfo"); + using var targetInfo = stripped.CreateStream("BasicFileInfo"); + basicInfo.CopyTo(targetInfo); + using var formats = project.OpenStorage("Formats").OpenStream("Latest"); + using var targetFormats = stripped.CreateStorage("Formats").CreateStream("Latest"); + formats.CopyTo(targetFormats); + } + + string output = P("output.rvt"); + Assert.Equal(release, DowngradePlanner.Plan(source, classTableProfile, GuidRule.Exact).TargetRelease); + var refused = Assert.Throws(() => + DowngradeWriter.Write(source, classTableProfile, output, GuidRule.Exact, allowLoss: true)); + Assert.Equal("profile-missing-unit-data", refused.Kind); + Assert.False(File.Exists(output)); + Assert.Equal(release, DowngradeWriter.Write(source, projectProfile, output, GuidRule.Exact, allowLoss: true).TargetRelease); + } + [SkippableFact] public void RestoresMissingInternalElectricalProjectionStyleWithoutDuplicatingAnExistingStyle() {