From 20398d1702de59204a747028bc2d1f7d74ffab6c Mon Sep 17 00:00:00 2001 From: Samuel Arsenault-Brassard Date: Tue, 20 Oct 2026 18:55:16 -0400 Subject: [PATCH] Differential updates: patch a VIM with a partial export (VimPatchService, export fingerprint header values) - WIP, Fable audit pass, not reviewed Co-Authored-By: Claude Opus 5.5 --- src/cpp/vim/object-model.h | 72 ++ src/cs/vim/Vim.Format.Core/DocumentBuilder.cs | 8 + .../vim/Vim.Format.Core/SerializableHeader.cs | 26 + .../Vim.Format.Tests/VimPatchServiceTests.cs | 176 +++++ src/cs/vim/Vim.Format/Merge/RowPlanWriter.cs | 365 +++++++++ src/cs/vim/Vim.Format/Merge/TablePlan.cs | 84 +++ .../vim/Vim.Format/Merge/VimPatchOptions.cs | 89 +++ .../vim/Vim.Format/Merge/VimPatchService.cs | 702 ++++++++++++++++++ src/cs/vim/Vim.Format/Merge/VimTables.cs | 143 ++++ .../vim/Vim.Format/ObjectModel/ObjectModel.cs | 24 +- .../ObjectModel/ObjectModelBuilder.cs | 8 +- .../ObjectModel/ObjectModelGenerated.cs | 28 + .../ObjectModel/ObjectModelStore.cs | 4 +- src/ts/src/objectModel.ts | 32 + 14 files changed, 1755 insertions(+), 6 deletions(-) create mode 100644 src/cs/vim/Vim.Format.Tests/VimPatchServiceTests.cs create mode 100644 src/cs/vim/Vim.Format/Merge/RowPlanWriter.cs create mode 100644 src/cs/vim/Vim.Format/Merge/TablePlan.cs create mode 100644 src/cs/vim/Vim.Format/Merge/VimPatchOptions.cs create mode 100644 src/cs/vim/Vim.Format/Merge/VimPatchService.cs create mode 100644 src/cs/vim/Vim.Format/Merge/VimTables.cs diff --git a/src/cpp/vim/object-model.h b/src/cpp/vim/object-model.h index 674f8b73..cbc59280 100644 --- a/src/cpp/vim/object-model.h +++ b/src/cpp/vim/object-model.h @@ -1001,6 +1001,7 @@ namespace Vim std::string mCreator; std::string mLastChangedBy; std::string mOwner; + std::string mChangeToken; int mLevelIndex; Level* mLevel; @@ -1057,6 +1058,7 @@ namespace Vim element->mCreator = GetCreator(elementIndex); element->mLastChangedBy = GetLastChangedBy(elementIndex); element->mOwner = GetOwner(elementIndex); + element->mChangeToken = GetChangeToken(elementIndex); element->mLevelIndex = GetLevelIndex(elementIndex); element->mPhaseCreatedIndex = GetPhaseCreatedIndex(elementIndex); element->mPhaseDemolishedIndex = GetPhaseDemolishedIndex(elementIndex); @@ -1085,6 +1087,7 @@ namespace Vim bool existsCreator = mEntityTable.column_exists("string:Creator"); bool existsLastChangedBy = mEntityTable.column_exists("string:LastChangedBy"); bool existsOwner = mEntityTable.column_exists("string:Owner"); + bool existsChangeToken = mEntityTable.column_exists("string:ChangeToken"); bool existsLevel = mEntityTable.column_exists("index:Vim.Level:Level"); bool existsPhaseCreated = mEntityTable.column_exists("index:Vim.Phase:PhaseCreated"); bool existsPhaseDemolished = mEntityTable.column_exists("index:Vim.Phase:PhaseDemolished"); @@ -1146,6 +1149,8 @@ namespace Vim const std::vector& ownerData = mEntityTable.column_exists("string:Owner") ? mEntityTable.mStringColumns["string:Owner"] : std::vector(); + const std::vector& changeTokenData = mEntityTable.column_exists("string:ChangeToken") ? mEntityTable.mStringColumns["string:ChangeToken"] : std::vector(); + const std::vector& levelData = mEntityTable.column_exists("index:Vim.Level:Level") ? mEntityTable.mIndexColumns["index:Vim.Level:Level"] : std::vector(); const std::vector& phaseCreatedData = mEntityTable.column_exists("index:Vim.Phase:PhaseCreated") ? mEntityTable.mIndexColumns["index:Vim.Phase:PhaseCreated"] : std::vector(); const std::vector& phaseDemolishedData = mEntityTable.column_exists("index:Vim.Phase:PhaseDemolished") ? mEntityTable.mIndexColumns["index:Vim.Phase:PhaseDemolished"] : std::vector(); @@ -1186,6 +1191,8 @@ namespace Vim entity.mLastChangedBy = std::string(reinterpret_cast(mStrings[lastChangedByData[i]])); if (existsOwner) entity.mOwner = std::string(reinterpret_cast(mStrings[ownerData[i]])); + if (existsChangeToken) + entity.mChangeToken = std::string(reinterpret_cast(mStrings[changeTokenData[i]])); entity.mLevelIndex = existsLevel ? levelData[i] : -1; entity.mPhaseCreatedIndex = existsPhaseCreated ? phaseCreatedData[i] : -1; entity.mPhaseDemolishedIndex = existsPhaseDemolished ? phaseDemolishedData[i] : -1; @@ -1561,6 +1568,35 @@ namespace Vim return result; } + std::string GetChangeToken(int elementIndex) + { + if (elementIndex < 0 || elementIndex >= GetCount()) + return {}; + + if (mEntityTable.column_exists("string:ChangeToken")) { + return std::string(reinterpret_cast(mStrings[mEntityTable.mStringColumns["string:ChangeToken"][elementIndex]])); + } + + return {}; + } + + std::vector* GetAllChangeToken() + { + const auto count = GetCount(); + + const std::vector& changeTokenData = mEntityTable.column_exists("string:ChangeToken") ? mEntityTable.mStringColumns["string:ChangeToken"] : std::vector(); + + std::vector* result = new std::vector(); + result->reserve(count); + + for (int i = 0; i < count; ++i) + { + result->push_back(std::string(reinterpret_cast(mStrings[changeTokenData[i]]))); + } + + return result; + } + int GetLevelIndex(int elementIndex) { if (!mEntityTable.column_exists("index:Vim.Level:Level")) { @@ -3257,6 +3293,7 @@ namespace Vim bool mIsMetric; std::string mGuid; int mNumSaves; + std::string mIdentity; bool mIsLinked; bool mIsDetached; bool mIsWorkshared; @@ -3316,6 +3353,7 @@ namespace Vim bimDocument->mIsMetric = GetIsMetric(bimDocumentIndex); bimDocument->mGuid = GetGuid(bimDocumentIndex); bimDocument->mNumSaves = GetNumSaves(bimDocumentIndex); + bimDocument->mIdentity = GetIdentity(bimDocumentIndex); bimDocument->mIsLinked = GetIsLinked(bimDocumentIndex); bimDocument->mIsDetached = GetIsDetached(bimDocumentIndex); bimDocument->mIsWorkshared = GetIsWorkshared(bimDocumentIndex); @@ -3354,6 +3392,7 @@ namespace Vim bool existsIsMetric = mEntityTable.column_exists("byte:IsMetric"); bool existsGuid = mEntityTable.column_exists("string:Guid"); bool existsNumSaves = mEntityTable.column_exists("int:NumSaves"); + bool existsIdentity = mEntityTable.column_exists("string:Identity"); bool existsIsLinked = mEntityTable.column_exists("byte:IsLinked"); bool existsIsDetached = mEntityTable.column_exists("byte:IsDetached"); bool existsIsWorkshared = mEntityTable.column_exists("byte:IsWorkshared"); @@ -3403,6 +3442,8 @@ namespace Vim memcpy(numSavesData, mEntityTable.mDataColumns["int:NumSaves"].begin(), count * sizeof(int)); } + const std::vector& identityData = mEntityTable.column_exists("string:Identity") ? mEntityTable.mStringColumns["string:Identity"] : std::vector(); + bfast::byte* isLinkedData = new bfast::byte[count]; if (mEntityTable.column_exists("byte:IsLinked")) { memcpy(isLinkedData, mEntityTable.mDataColumns["byte:IsLinked"].begin(), count * sizeof(bfast::byte)); @@ -3494,6 +3535,8 @@ namespace Vim entity.mGuid = std::string(reinterpret_cast(mStrings[guidData[i]])); if (existsNumSaves) entity.mNumSaves = numSavesData[i]; + if (existsIdentity) + entity.mIdentity = std::string(reinterpret_cast(mStrings[identityData[i]])); if (existsIsLinked) entity.mIsLinked = isLinkedData[i]; if (existsIsDetached) @@ -3679,6 +3722,35 @@ namespace Vim return result; } + std::string GetIdentity(int bimDocumentIndex) + { + if (bimDocumentIndex < 0 || bimDocumentIndex >= GetCount()) + return {}; + + if (mEntityTable.column_exists("string:Identity")) { + return std::string(reinterpret_cast(mStrings[mEntityTable.mStringColumns["string:Identity"][bimDocumentIndex]])); + } + + return {}; + } + + std::vector* GetAllIdentity() + { + const auto count = GetCount(); + + const std::vector& identityData = mEntityTable.column_exists("string:Identity") ? mEntityTable.mStringColumns["string:Identity"] : std::vector(); + + std::vector* result = new std::vector(); + result->reserve(count); + + for (int i = 0; i < count; ++i) + { + result->push_back(std::string(reinterpret_cast(mStrings[identityData[i]]))); + } + + return result; + } + bool GetIsLinked(int bimDocumentIndex) { if (bimDocumentIndex < 0 || bimDocumentIndex >= GetCount()) diff --git a/src/cs/vim/Vim.Format.Core/DocumentBuilder.cs b/src/cs/vim/Vim.Format.Core/DocumentBuilder.cs index a906e95e..5dc31efe 100644 --- a/src/cs/vim/Vim.Format.Core/DocumentBuilder.cs +++ b/src/cs/vim/Vim.Format.Core/DocumentBuilder.cs @@ -31,6 +31,14 @@ public DocumentBuilder( Header = new SerializableHeader(generator, schema, versionString, optionalHeaderValues); } + /// + /// A builder which writes the given header (for example ). + /// + public DocumentBuilder(SerializableHeader header) + { + Header = header ?? throw new ArgumentNullException(nameof(header)); + } + public EntityTableBuilder GetTableBuilderOrCreate(string name) { if (!Tables.ContainsKey(name)) diff --git a/src/cs/vim/Vim.Format.Core/SerializableHeader.cs b/src/cs/vim/Vim.Format.Core/SerializableHeader.cs index c1c3a97c..66b19a10 100644 --- a/src/cs/vim/Vim.Format.Core/SerializableHeader.cs +++ b/src/cs/vim/Vim.Format.Core/SerializableHeader.cs @@ -93,6 +93,32 @@ public SerializableHeader(string generator, SerializableVersion schema, string v AddOptionalValues(values ?? new Dictionary(), versionString)) { } + /// + /// The header of a new revision of an existing VIM file (for example a file patched by a differential update): + /// the Id is kept, the Revision and the creation date are new (see ). The optional + /// values of the prior header are kept; are added or replace them. + /// + public static SerializableHeader CreateRevisionOf( + SerializableHeader prior, + string generator, + SerializableVersion schema, + IReadOnlyDictionary values = null) + { + var d = prior.Values?.ToDictionary(kv => kv.Key, kv => kv.Value) ?? new Dictionary(); + if (values != null) + foreach (var kv in values) + d[kv.Key] = kv.Value; + + return new SerializableHeader( + CurrentVimFormatVersion, + prior.Id == Guid.Empty ? Guid.NewGuid() : prior.Id, + Guid.NewGuid(), + generator, + DateTime.UtcNow, + schema ?? prior.Schema, + d); + } + /// /// Parses the input. Throws exceptions if the input does not define a correctly formatted header. /// diff --git a/src/cs/vim/Vim.Format.Tests/VimPatchServiceTests.cs b/src/cs/vim/Vim.Format.Tests/VimPatchServiceTests.cs new file mode 100644 index 00000000..49dd51bc --- /dev/null +++ b/src/cs/vim/Vim.Format.Tests/VimPatchServiceTests.cs @@ -0,0 +1,176 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using NUnit.Framework; +using Vim.Format.Merge; +using Vim.Format.ObjectModel; +using Vim.Format.SceneBuilder; +using Vim.LinqArray; +using Vim.Math3d; +using Vim.Util.Tests; + +namespace Vim.Format.Tests +{ + /// + /// VimPatchService, the file half of a differential update: a base file patched with a partial file of the same + /// document. The partial holds a changed wall, a new element, its own temporary 3D view (aliased onto the base's export + /// view) and the door as context; the base loses one deleted element. + /// + [TestFixture] + public static class VimPatchServiceTests + { + private sealed class Doc + { + public readonly ObjectModelStore Store = new ObjectModelStore(); + public ObjectModelBuilder Omb => Store.ObjectModelBuilder; + public readonly int View; + public readonly ParameterDescriptor Mark; + + public Doc(string viewUid, string viewName, string projectName = "Patch", string path = "C:\\patch.rvt") + { + var bimDocument = new BimDocument { Name = projectName, Title = Path.GetFileNameWithoutExtension(path), PathName = path, Identity = "creation-guid" }; + var holder = Omb.ElementBuilder.Add(bimDocument.CreateParameterHolderElement()).Entity; + bimDocument._Element.Index = holder.Index; + holder._BimDocument.Index = Omb.BimDocumentBuilder.Add(bimDocument).Entity.Index; + var viewElement = AddElement(1000, viewName, viewUid); + View = Omb.ViewBuilder.Add(new View { Title = viewName, _Element = { Index = viewElement } }).Entity.Index; + var unit = Omb.DisplayUnitBuilder.Add(new DisplayUnit { Spec = "text", Type = "text", Label = "text" }).Entity; + Mark = Omb.ParameterDescriptorBuilder.Add(new ParameterDescriptor { Name = "Mark", Group = "Identity Data", _DisplayUnit = { Index = unit.Index } }).Entity; + } + + public int AddElement(long id, string name, string uid) + => Omb.ElementBuilder.Add(new Element { Id = id, Name = name, UniqueId = uid, ChangeToken = uid + "-v1", _BimDocument = { Index = 0 } }).Entity.Index; + + /// An element with a 1 ft triangle at x, a Mark parameter and an ElementInView row. + public int AddBox(long id, string uid, float x, string mark) + { + var e = AddElement(id, uid, uid); + var mesh = Store.Meshes.Count; + Store.Meshes.Add(new DocumentBuilder.Mesh( + new List { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(0, 1, 0) }, + new List { 0, 1, 2 })); + Store.Instances.Add(new DocumentBuilder.Instance { Transform = Matrix4x4.CreateTranslation(x, 0, 0), MeshIndex = mesh, ParentIndex = -1 }); + Omb.NodeBuilder.AddUntracked(new Node { _Element = { Index = e } }); + Omb.ParameterBuilder.AddUntracked(new Parameter { Value = mark, _ParameterDescriptor = { Index = Mark.Index }, _Element = { Index = e } }); + Omb.ElementInViewBuilder.AddUntracked(new ElementInView { _Element = { Index = e }, _View = { Index = View } }); + return e; + } + + public string Write(string dir, string name) + { + var path = Path.Combine(dir, name); + Store.ToDocumentBuilder(nameof(VimPatchServiceTests), "0.0.0").Write(path); + return path; + } + } + + [Test] + public static void TestPatchReplacesAddsDeletesAndKeepsTheRest() + { + var ctx = new CallerTestContext(); + var dir = ctx.PrepareDirectory(); + + // Base: a wall, a door hosted by the wall, an element deleted later. + var b = new Doc("view-all", "VIM-ALL"); + var wall = b.AddBox(1, "wall", 0, "A"); + var door = b.AddBox(2, "door", 5, "D"); + b.Omb.FamilyInstanceBuilder.AddUntracked(new FamilyInstance { _Element = { Index = door }, _Host = { Index = wall } }); + b.AddBox(3, "old", 9, "O"); + var basePath = b.Write(dir, "base.vim"); + + // Partial (exported through a temporary 3D view): the wall moved to x = 2 with Mark B, a new element, the door + // as context. + var p = new Doc("temp-view", "_VIM_EXPORT_1234"); + var pWall = p.AddBox(1, "wall", 2, "B"); + var pDoor = p.AddBox(2, "door", 5, "D"); + p.Omb.FamilyInstanceBuilder.AddUntracked(new FamilyInstance { _Element = { Index = pDoor }, _Host = { Index = pWall } }); + p.AddBox(4, "new", 7, "N"); + var partialPath = p.Write(dir, "partial.vim"); + + var outPath = Path.Combine(dir, "patched.vim"); + var result = VimPatchService.Patch(basePath, partialPath, outPath, new VimPatchOptions + { + ChangedUniqueIds = new HashSet { "wall", "new" }, + DeletedUniqueIds = new HashSet { "old" }, + UniqueIdAliases = new Dictionary { { "temp-view", "view-all" } }, + HeaderValues = new Dictionary { { "test.value", "42" } }, + }); + + Assert.AreEqual(2, result.Changed, "the wall, and the document's holder (Project Information is always refreshed)"); + Assert.AreEqual(1, result.Added); + Assert.AreEqual(1, result.Deleted); + Assert.IsEmpty(result.ChangedButNotInPartial); + + var vim = VimScene.LoadVim(outPath); + vim.Validate(); + Assert.AreEqual("42", vim.Document.Header.Values["test.value"]); + var dm = vim.DocumentModel; + var uids = Enumerable.Range(0, dm.NumElement).Select(i => dm.GetElement(i).UniqueId).ToList(); + CollectionAssert.DoesNotContain(uids, "old"); + CollectionAssert.DoesNotContain(uids, "temp-view"); + Assert.AreEqual(1, uids.Count(u => u == "view-all")); + var wallIndex = uids.IndexOf("wall"); + var doorIndex = uids.IndexOf("door"); + var newIndex = uids.IndexOf("new"); + Assert.AreEqual(wall, wallIndex, "a changed element keeps its index"); + Assert.AreEqual(1, dm.NumBimDocument, "one document, not one per file"); + + // Parameters: the wall's replaced, the door's kept; one descriptor. + var marks = Enumerable.Range(0, dm.NumParameter).Select(i => dm.GetParameter(i)).GroupBy(x => x.Element.UniqueId, x => x.Value).ToDictionary(x => x.Key, x => x.ToArray()); + CollectionAssert.AreEqual(new[] { "B" }, marks["wall"]); + CollectionAssert.AreEqual(new[] { "D" }, marks["door"]); + CollectionAssert.AreEqual(new[] { "N" }, marks["new"]); + Assert.AreEqual(1, dm.NumParameterDescriptor); + + // Geometry: one node per element, the wall at its new place, aligned with the instances. + var g = vim.Document.Geometry; + Assert.AreEqual(dm.NumNode, g.InstanceTransforms.Count); + var nodesOf = Enumerable.Range(0, dm.NumNode).GroupBy(i => dm.GetNode(i).Element.UniqueId).ToDictionary(x => x.Key, x => x.ToArray()); + Assert.AreEqual(2f, g.InstanceTransforms[nodesOf["wall"].Single()].Translation.X); + Assert.AreEqual(5f, g.InstanceTransforms[nodesOf["door"].Single()].Translation.X); + Assert.AreEqual(7f, g.InstanceTransforms[nodesOf["new"].Single()].Translation.X); + + // The door still hosted by the wall; the new element shown in the base's export view. + var fi = Enumerable.Range(0, dm.NumFamilyInstance).Select(dm.GetFamilyInstance).Single(); + Assert.AreEqual(doorIndex, fi._Element.Index); + Assert.AreEqual(wallIndex, fi._Host.Index); + var eiv = Enumerable.Range(0, dm.NumElementInView).Select(dm.GetElementInView).ToList(); + Assert.AreEqual(1, dm.NumView); + Assert.IsTrue(eiv.Any(x => x._Element.Index == newIndex && x.View.Title == "VIM-ALL")); + Assert.AreEqual(1, eiv.Count(x => x._Element.Index == wallIndex)); + } + + [Test] + public static void TestPatchKeysTheHostByDocumentNotByProjectNameOrPath() + { + var ctx = new CallerTestContext(); + var dir = ctx.PrepareDirectory(); + + var b = new Doc("view-all", "VIM-ALL", "Tower", "C:\\a\\TowerS.rvt"); + b.AddBox(1, "wall", 0, "A"); + var basePath = b.Write(dir, "base.vim"); + + // Exported from another local copy (other path, other title) after Project Information was renamed: the holder's + // UniqueId (made from the project name) differs, the element is the same. + var p = new Doc("temp-view", "_VIM_EXPORT_1", "Tower renamed", "D:\\b\\TowerS_sam.rvt"); + p.AddBox(1, "wall", 3, "B"); + var partialPath = p.Write(dir, "partial.vim"); + + var outPath = Path.Combine(dir, "patched.vim"); + var result = VimPatchService.Patch(basePath, partialPath, outPath, new VimPatchOptions + { + ChangedUniqueIds = new HashSet { "wall" }, + UniqueIdAliases = new Dictionary { { "temp-view", "view-all" } }, + }); + + Assert.AreEqual(1, result.HoldersMatched); + var vim = VimScene.LoadVim(outPath); + vim.Validate(); + var dm = vim.DocumentModel; + Assert.AreEqual(1, dm.NumBimDocument); + Assert.AreEqual("Tower renamed", dm.GetBimDocument(0).Name, "Project Information refreshed in place"); + Assert.AreEqual(1, Enumerable.Range(0, dm.NumElement).Count(i => dm.GetElement(i).UniqueId == "wall")); + Assert.AreEqual(3, dm.NumElement, "the holder, the view and the wall: no element added"); + } + } +} diff --git a/src/cs/vim/Vim.Format/Merge/RowPlanWriter.cs b/src/cs/vim/Vim.Format/Merge/RowPlanWriter.cs new file mode 100644 index 00000000..de9d37c6 --- /dev/null +++ b/src/cs/vim/Vim.Format/Merge/RowPlanWriter.cs @@ -0,0 +1,365 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Vim.BFast; +using Vim.Format.ObjectModel; +using Vim.G3d; +using Vim.LinqArray; +using Vim.Math3d; + +namespace Vim.Format.Merge +{ + public sealed class RowPlanWriteStats + { + public int MeshesFromSource0; + public int MeshesFromOtherSources; + public int MeshesReused; + public int Instances; + public int Shapes; + public int Materials; + } + + /// + /// Writes table plans over several source files into a DocumentBuilder: every column of every table (the union of + /// the sources' columns, missing ones filled with defaults), every relation re-pointed, and the G3D geometry kept + /// aligned with its tables (Node rows = instances, Shape rows = shapes, Material rows = materials; meshes are the + /// ones the written instances use). + /// + public static class RowPlanWriter + { + public static DocumentBuilder Write( + IReadOnlyList sources, + IReadOnlyDictionary plans, + SerializableHeader header, + bool deduplicateMeshes, + RowPlanWriteStats stats = null) + { + stats = stats ?? new RowPlanWriteStats(); + var db = new DocumentBuilder(header); + + foreach (var plan in plans.Values) + { + if (VimConstants.ComputedTableNames.Contains(plan.Name)) + continue; + db.Tables.Add(plan.Name, WriteTable(sources, plans, plan)); + } + + WriteGeometry(sources, plans, db, deduplicateMeshes, stats); + + // Assets: every source's buffers, the first source winning on a repeated name. + foreach (var src in sources) + foreach (var asset in src.Document.Assets ?? Array.Empty()) + db.AddAsset(asset); + + return db; + } + + private static EntityTableBuilder WriteTable(IReadOnlyList sources, IReadOnlyDictionary plans, TablePlan plan) + { + var tb = new EntityTableBuilder(plan.Name); + var tables = sources.Select(s => s.GetTable(plan.Name)).ToArray(); + var n = plan.Count; + var src = plan.Source; + var rows = plan.Row; + + // Index columns + foreach (var name in tables.Where(t => t != null).SelectMany(t => t.IndexColumns.Select(c => c.Name)).Distinct().OrderBy(x => x, StringComparer.Ordinal)) + { + var cols = tables.Select(t => t?.IndexColumns.FirstOrDefault(c => c.Name == name)?.Array).ToArray(); + var related = ColumnExtensions.GetRelatedTableNameFromColumnName(name); + plans.TryGetValue(related, out var relatedPlan); + var values = new int[n]; + for (var i = 0; i < n; ++i) + { + var col = cols[src[i]]; + var v = col == null ? -1 : col[rows[i]]; + values[i] = v < 0 ? v : relatedPlan?.Lookup(src[i], v) ?? -1; + } + tb.AddIndexColumn(name, values); + } + + // String columns + foreach (var name in tables.Where(t => t != null).SelectMany(t => t.StringColumns.Select(c => c.Name)).Distinct().OrderBy(x => x, StringComparer.Ordinal)) + { + var cols = tables.Select(t => t?.StringColumns.FirstOrDefault(c => c.Name == name)?.Array).ToArray(); + var values = new string[n]; + for (var i = 0; i < n; ++i) + { + var col = cols[src[i]]; + values[i] = col == null ? "" : sources[src[i]].Str(col[rows[i]]); + } + tb.AddStringColumn(name, values); + } + + // Data columns + foreach (var name in tables.Where(t => t != null).SelectMany(t => t.DataColumns.Select(c => c.Name)).Distinct().OrderBy(x => x, StringComparer.Ordinal)) + { + var cols = tables.Select(t => t?.DataColumns.FirstOrDefault(c => c.Name == name)?.Data).ToArray(); + tb.AddDataColumn(name, GatherData(name.GetTypePrefix(), cols, src, rows)); + } + + return tb; + } + + private static IBuffer GatherData(string typePrefix, Array[] cols, List src, List rows) + { + switch (typePrefix) + { + case VimConstants.IntColumnNameTypePrefix: return Gather(cols, src, rows).ToBuffer(); + case VimConstants.LongColumnNameTypePrefix: return Gather(cols, src, rows).ToBuffer(); + case VimConstants.ByteColumnNameTypePrefix: return Gather(cols, src, rows).ToBuffer(); + case VimConstants.FloatColumnNameTypePrefix: return Gather(cols, src, rows).ToBuffer(); + case VimConstants.DoubleColumnNameTypePrefix: return Gather(cols, src, rows).ToBuffer(); + default: throw new Exception($"Unknown data column type prefix {typePrefix}"); + } + } + + private static T[] Gather(Array[] cols, List src, List rows) where T : unmanaged + { + var typed = cols.Select(c => c as T[]).ToArray(); + var r = new T[src.Count]; + for (var i = 0; i < r.Length; ++i) + { + var col = typed[src[i]]; + r[i] = col == null ? default : col[rows[i]]; + } + return r; + } + + // --------------------------------------------------------------------------------------------------------- + // Geometry + // --------------------------------------------------------------------------------------------------------- + + private sealed class G3dArrays + { + public Vector3[] Vertices; + public int[] Indices; + public int[] MeshVertexOffsets, MeshIndexOffsets, MeshSubmeshOffsets; + public int[] SubmeshIndexOffsets, SubmeshMaterials; + public int NumMeshes; + public Matrix4x4[] InstanceTransforms; + public int[] InstanceMeshes, InstanceParents; + public ushort[] InstanceFlags; + public Vector3[] ShapeVertices; + public int[] ShapeVertexOffsets; + public Vector4[] ShapeColors; + public float[] ShapeWidths; + public Vector4[] MaterialColors; + public float[] MaterialGlossiness, MaterialSmoothness; + + public G3dArrays(G3D g) + { + Vertices = g?.Vertices?.ToArray() ?? Array.Empty(); + Indices = g?.Indices?.ToArray() ?? Array.Empty(); + MeshSubmeshOffsets = g?.MeshSubmeshOffset?.ToArray() ?? Array.Empty(); + NumMeshes = MeshSubmeshOffsets.Length; + MeshVertexOffsets = g?.MeshVertexOffsets?.ToArray() ?? Array.Empty(); + MeshIndexOffsets = g?.MeshIndexOffsets?.ToArray() ?? Array.Empty(); + SubmeshIndexOffsets = g?.SubmeshIndexOffsets?.ToArray() ?? Array.Empty(); + SubmeshMaterials = g?.SubmeshMaterials?.ToArray() ?? Array.Empty(); + InstanceTransforms = g?.InstanceTransforms?.ToArray() ?? Array.Empty(); + InstanceMeshes = g?.InstanceMeshes?.ToArray() ?? Array.Empty(); + InstanceParents = g?.InstanceParents?.ToArray() ?? Array.Empty(); + InstanceFlags = g?.InstanceFlags?.ToArray() ?? Array.Empty(); + ShapeVertices = g?.ShapeVertices?.ToArray() ?? Array.Empty(); + ShapeVertexOffsets = g?.ShapeVertexOffsets?.ToArray() ?? Array.Empty(); + ShapeColors = g?.ShapeColors?.ToArray() ?? Array.Empty(); + ShapeWidths = g?.ShapeWidths?.ToArray() ?? Array.Empty(); + MaterialColors = g?.MaterialColors?.ToArray() ?? Array.Empty(); + MaterialGlossiness = g?.MaterialGlossiness?.ToArray() ?? Array.Empty(); + MaterialSmoothness = g?.MaterialSmoothness?.ToArray() ?? Array.Empty(); + } + + public (int Start, int End) VertexRange(int m) + => (MeshVertexOffsets[m], m + 1 < NumMeshes ? MeshVertexOffsets[m + 1] : Vertices.Length); + + public (int Start, int End) IndexRange(int m) + => (MeshIndexOffsets[m], m + 1 < NumMeshes ? MeshIndexOffsets[m + 1] : Indices.Length); + + public (int Start, int End) SubmeshRange(int m) + => (MeshSubmeshOffsets[m], m + 1 < NumMeshes ? MeshSubmeshOffsets[m + 1] : SubmeshIndexOffsets.Length); + + public (int Start, int End) ShapeRange(int s) + => (ShapeVertexOffsets[s], s + 1 < ShapeVertexOffsets.Length ? ShapeVertexOffsets[s + 1] : ShapeVertices.Length); + } + + private static DocumentBuilder.SubdividedMesh ToSubdividedMesh(G3dArrays g, int m, TablePlan materialPlan, int source) + { + var (v0, v1) = g.VertexRange(m); + var (i0, i1) = g.IndexRange(m); + var (s0, s1) = g.SubmeshRange(m); + var vertices = new List(v1 - v0); + for (var i = v0; i < v1; ++i) vertices.Add(g.Vertices[i]); + var indices = new List(i1 - i0); + for (var i = i0; i < i1; ++i) indices.Add(g.Indices[i] - v0); + var offsets = new List(s1 - s0); + var materials = new List(s1 - s0); + for (var i = s0; i < s1; ++i) + { + offsets.Add(g.SubmeshIndexOffsets[i] - i0); + var mat = g.SubmeshMaterials[i]; + materials.Add(mat < 0 || materialPlan == null ? mat : materialPlan.Lookup(source, mat)); + } + return new DocumentBuilder.SubdividedMesh(indices, vertices, offsets, materials); + } + + private static unsafe int Bits(float f) => *(int*)&f; + + private static ulong MeshHash(DocumentBuilder.SubdividedMesh m) + { + const ulong prime = 1099511628211UL; + var h = 14695981039346656037UL; + void Add(int x) { h = (h ^ (uint)x) * prime; } + Add(m.Vertices.Count); + foreach (var v in m.Vertices) + { + Add(Bits(v.X)); + Add(Bits(v.Y)); + Add(Bits(v.Z)); + } + Add(m.Indices.Count); + foreach (var i in m.Indices) Add(i); + foreach (var i in m.SubmeshesIndexOffset) Add(i); + foreach (var i in m.SubmeshMaterials) Add(i); + return h; + } + + private static void WriteGeometry(IReadOnlyList sources, IReadOnlyDictionary plans, DocumentBuilder db, bool dedupe, RowPlanWriteStats stats) + { + var g3ds = sources.Select(s => new G3dArrays(s.Geometry)).ToArray(); + plans.TryGetValue(TableNames.Material, out var materialPlan); + plans.TryGetValue(TableNames.Node, out var nodePlan); + plans.TryGetValue(TableNames.Shape, out var shapePlan); + + // Materials: one renderable material per Material row, from the row's source. + if (materialPlan != null) + { + for (var i = 0; i < materialPlan.Count; ++i) + { + var s = materialPlan.Source[i]; + var r = materialPlan.Row[i]; + var g = g3ds[s]; + if (g.MaterialColors.Length == sources[s].NumRows(TableNames.Material) && r < g.MaterialColors.Length) + { + db.Materials.Add(new DocumentBuilder.Material + { + Color = g.MaterialColors[r], + Glossiness = r < g.MaterialGlossiness.Length ? g.MaterialGlossiness[r] : 0, + Smoothness = r < g.MaterialSmoothness.Length ? g.MaterialSmoothness[r] : 0, + }); + } + else + { + double D(string col) { var d = sources[s].Data(TableNames.Material, col); return d != null && r < d.Length ? d[r] : 0; } + db.Materials.Add(ObjectModelStore.ConvertMaterialEntityFieldsToRenderableMaterial( + D("double:Color.X"), D("double:Color.Y"), D("double:Color.Z"), + D("double:Transparency"), D("double:Glossiness"), D("double:Smoothness"))); + } + } + } + stats.Materials = db.Materials.Count; + + // Meshes used by the written instances, in source order (source 0 first, then the others). + var meshMaps = new int[sources.Count][]; + var hashToMeshes = dedupe ? new Dictionary>() : null; + for (var s = 0; s < sources.Count; ++s) + { + var g = g3ds[s]; + var used = new bool[g.NumMeshes]; + if (nodePlan != null) + { + for (var i = 0; i < nodePlan.Count; ++i) + { + if (nodePlan.Source[i] != s) continue; + var r = nodePlan.Row[i]; + var mesh = r < g.InstanceMeshes.Length ? g.InstanceMeshes[r] : -1; + if (mesh >= 0 && mesh < used.Length) used[mesh] = true; + } + } + var map = new int[g.NumMeshes]; + for (var m = 0; m < g.NumMeshes; ++m) + { + map[m] = -1; + if (!used[m]) continue; + var sm = ToSubdividedMesh(g, m, materialPlan, s); + if (dedupe) + { + var h = MeshHash(sm); + if (s > 0 && hashToMeshes.TryGetValue(h, out var candidates)) + { + var found = -1; + foreach (var c in candidates) + if (db.Meshes[c].IsEquivalentTo(sm)) { found = c; break; } + if (found >= 0) + { + map[m] = found; + stats.MeshesReused++; + continue; + } + } + if (!hashToMeshes.TryGetValue(h, out var list)) + hashToMeshes[h] = list = new List(); + list.Add(db.Meshes.Count); + } + map[m] = db.Meshes.Count; + db.Meshes.Add(sm); + if (s == 0) stats.MeshesFromSource0++; else stats.MeshesFromOtherSources++; + } + meshMaps[s] = map; + } + + // Instances: one per Node row, in Node order. + if (nodePlan != null) + { + for (var i = 0; i < nodePlan.Count; ++i) + { + var s = nodePlan.Source[i]; + var r = nodePlan.Row[i]; + var g = g3ds[s]; + if (r >= g.InstanceTransforms.Length) + { + // A Node row without an instance: keep the alignment with an empty instance. + db.AddInstance(Matrix4x4.Identity, -1, 0); + continue; + } + var mesh = g.InstanceMeshes[r]; + var parent = r < g.InstanceParents.Length ? g.InstanceParents[r] : -1; + db.Instances.Add(new DocumentBuilder.Instance + { + Transform = g.InstanceTransforms[r], + MeshIndex = mesh < 0 || mesh >= meshMaps[s].Length ? -1 : meshMaps[s][mesh], + ParentIndex = parent < 0 ? -1 : nodePlan.Lookup(s, parent), + InstanceFlags = (InstanceFlags)(r < g.InstanceFlags.Length ? g.InstanceFlags[r] : (ushort)0), + }); + } + } + stats.Instances = db.Instances.Count; + + // Shapes: one per Shape row, in Shape order. + if (shapePlan != null) + { + for (var i = 0; i < shapePlan.Count; ++i) + { + var s = shapePlan.Source[i]; + var r = shapePlan.Row[i]; + var g = g3ds[s]; + if (r >= g.ShapeVertexOffsets.Length) + { + db.Shapes.Add(new DocumentBuilder.Shape { Vertices = new List(), Color = Vector4.Zero, Width = 0 }); + continue; + } + var (a, b) = g.ShapeRange(r); + var pts = new List(b - a); + for (var k = a; k < b; ++k) pts.Add(g.ShapeVertices[k]); + db.Shapes.Add(new DocumentBuilder.Shape + { + Vertices = pts, + Color = r < g.ShapeColors.Length ? g.ShapeColors[r] : Vector4.Zero, + Width = r < g.ShapeWidths.Length ? g.ShapeWidths[r] : 0, + }); + } + } + stats.Shapes = db.Shapes.Count; + } + } +} diff --git a/src/cs/vim/Vim.Format/Merge/TablePlan.cs b/src/cs/vim/Vim.Format/Merge/TablePlan.cs new file mode 100644 index 00000000..5ab4bd7e --- /dev/null +++ b/src/cs/vim/Vim.Format/Merge/TablePlan.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; + +namespace Vim.Format.Merge +{ + /// + /// The rows one output table takes from one or more source files, in output order, and where every source row + /// went (-1 = not written). Relations are re-pointed through when the table is written + /// (). + /// + public sealed class TablePlan + { + public string Name { get; } + + /// The source file of each output row. + public List Source { get; } = new List(); + + /// The row of that source file each output row copies. + public List Row { get; } = new List(); + + /// Per source file: source row -> output row (-1 = not written). + public int[][] Map { get; } + + public TablePlan(string name, IReadOnlyList sources) + { + Name = name; + Map = new int[sources.Count][]; + for (var s = 0; s < sources.Count; ++s) + { + var m = new int[sources[s].NumRows(name)]; + for (var i = 0; i < m.Length; ++i) + m[i] = -1; + Map[s] = m; + } + } + + public int Count => Source.Count; + + /// Appends a row whose content comes from (source, row) and maps that source row to it. + public int Add(int source, int row) + { + var i = Source.Count; + Source.Add(source); + Row.Add(row); + Map[source][row] = i; + return i; + } + + /// Maps another source row to an existing output row (its own content is not used). + public void Alias(int source, int row, int outRow) + => Map[source][row] = outRow; + + /// The output row of a source row, or -1. + public int Lookup(int source, int row) + { + if (row < 0) return -1; + var m = Map[source]; + return row < m.Length ? m[row] : -1; + } + + /// Removes the output rows for which remove is true; the rows after them move up and Map follows. + public int RemoveWhere(Func remove) + { + var newIndex = new int[Source.Count]; + var src = new List(); + var row = new List(); + for (var i = 0; i < Source.Count; ++i) + { + if (remove(i)) { newIndex[i] = -1; continue; } + newIndex[i] = src.Count; + src.Add(Source[i]); + row.Add(Row[i]); + } + var removed = Source.Count - src.Count; + if (removed == 0) return 0; + Source.Clear(); Source.AddRange(src); + Row.Clear(); Row.AddRange(row); + foreach (var m in Map) + for (var i = 0; i < m.Length; ++i) + if (m[i] >= 0) m[i] = newIndex[m[i]]; + return removed; + } + } +} diff --git a/src/cs/vim/Vim.Format/Merge/VimPatchOptions.cs b/src/cs/vim/Vim.Format/Merge/VimPatchOptions.cs new file mode 100644 index 00000000..98ee77d0 --- /dev/null +++ b/src/cs/vim/Vim.Format/Merge/VimPatchOptions.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Vim.Format.Merge +{ + /// What replaces, adds and removes. + public class VimPatchOptions + { + /// + /// UniqueIds of the elements that changed (added or modified). Null = every element of the partial file counts + /// as changed. An element of the partial file which is not in this list is context (a type, a level, a view the + /// export writes along with the changed elements): the base keeps its own rows for it, and the partial's rows + /// only serve to re-point relations. + /// + public ICollection ChangedUniqueIds { get; set; } + + /// UniqueIds of the elements deleted since the base was written. + public ICollection DeletedUniqueIds { get; set; } = new HashSet(); + + /// + /// Titles of the linked models the partial file holds whole: every base element of such a document is replaced + /// by the partial's, and the ones the partial does not hold are deleted. + /// + public ICollection ReplacedDocumentTitles { get; set; } = new HashSet(); + + /// + /// UniqueId of a partial element -> UniqueId of the base element it stands for. A differential export draws the + /// changed elements through a temporary 3D view: its rows (ElementInView...) land on the base's export view. + /// + public IDictionary UniqueIdAliases { get; set; } = new Dictionary(); + + /// UniqueIds of partial elements which are never written, with every row they own. + public ICollection ExcludedUniqueIds { get; set; } = new HashSet(); + + /// A partial mesh equal to one the base already has is not written twice. + public bool DeduplicateMeshes { get; set; } = true; + + /// Header values written in the patched file (added to, or replacing, the base header's). + public IReadOnlyDictionary HeaderValues { get; set; } + + public string Generator { get; set; } = "Vim.Format.Patch"; + } + + /// What did. + public class VimPatchResult + { + public int BaseElements, PartialElements, OutputElements; + public int Kept, Changed, Added, Deleted, Context, Excluded; + + /// UniqueIds listed as changed which the partial file does not hold: their base rows were kept. + public List ChangedButNotInPartial = new List(); + + /// UniqueIds listed as deleted which the base file does not hold. + public List DeletedButNotInBase = new List(); + + /// Base Element row -> output Element row (-1 = deleted). Element rows only move for deletions. + public int[] ElementIndexMap; + + /// Per table: rows in the base, in the partial, in the output. + public Dictionary TableRows = new Dictionary(); + + /// Document, site and building holders of the partial matched to the base's by document and kind. + public int HoldersMatched; + + /// Rows nothing points at any more (warnings, wall layer structures, cameras), removed. + public int OrphanRowsRemoved; + + public RowPlanWriteStats Geometry = new RowPlanWriteStats(); + public long LoadMs, PlanMs, BuildMs, WriteMs; + + public override string ToString() + { + var sb = new StringBuilder(); + sb.AppendLine($"Elements: base {BaseElements}, partial {PartialElements}, output {OutputElements}"); + sb.AppendLine($" kept {Kept}, changed {Changed}, added {Added}, deleted {Deleted}, context {Context}, excluded {Excluded}"); + if (ChangedButNotInPartial.Count > 0) sb.AppendLine($" changed but not in the partial (base kept): {ChangedButNotInPartial.Count}"); + if (DeletedButNotInBase.Count > 0) sb.AppendLine($" deleted but not in the base: {DeletedButNotInBase.Count}"); + if (HoldersMatched > 0) sb.AppendLine($" document / site / building holders matched: {HoldersMatched}"); + if (OrphanRowsRemoved > 0) sb.AppendLine($" rows nothing points at any more, removed: {OrphanRowsRemoved}"); + sb.AppendLine($"Geometry: meshes from base {Geometry.MeshesFromSource0}, from partial {Geometry.MeshesFromOtherSources}, reused {Geometry.MeshesReused}; instances {Geometry.Instances}, shapes {Geometry.Shapes}, materials {Geometry.Materials}"); + sb.Append($"Timings (ms): load {LoadMs}, plan {PlanMs}, build {BuildMs}, write {WriteMs}"); + foreach (var kv in TableRows.Where(kv => kv.Value.Base != kv.Value.Output).OrderBy(k => k.Key, StringComparer.Ordinal)) + sb.AppendLine().Append($" {kv.Key}: base {kv.Value.Base}, partial {kv.Value.Partial}, output {kv.Value.Output}"); + return sb.ToString(); + } + } +} diff --git a/src/cs/vim/Vim.Format/Merge/VimPatchService.cs b/src/cs/vim/Vim.Format/Merge/VimPatchService.cs new file mode 100644 index 00000000..2b06a62a --- /dev/null +++ b/src/cs/vim/Vim.Format/Merge/VimPatchService.cs @@ -0,0 +1,702 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Text; +using Vim.Format.ObjectModel; +using Vim.Util; + +namespace Vim.Format.Merge +{ + /// + /// Patches a base VIM file with a partial VIM file exported from the same source document (only the elements that + /// changed, plus what they point at): changed elements are replaced, new ones appended, deleted ones removed; every + /// other row of the base is kept and every relation is re-pointed. This is the second half of a differential update + /// (the first half, finding what changed and exporting it, belongs to the exporter). + /// Rules, per table: + /// + /// Element: identity = document + UniqueId, where the document is "the host model" for every BimDocument that is + /// not a link (whatever its title, path or project name) and the title for a linked model. A changed element keeps its + /// row index (its content comes from the partial); new elements are appended; deleted ones are removed. + /// Tables owned by an element with at most one row per element (FamilyInstance, Level, Room, View, Material, + /// BimDocument...): the row follows its element, in place. + /// Tables with several rows per element (Parameter, Node, Shape, ElementInView, MaterialInElement, + /// ElementInSystem, ElementInWarning): a changed element's base rows are replaced by the partial's (for + /// ElementInView: only the rows of the views the partial writes). + /// Other tables (Category, DisplayUnit, ParameterDescriptor, Workset, associations): the base rows stay; a + /// partial row equal to a base row (by key or by content) is that row, otherwise it is appended; an association row + /// whose end is gone is removed. Warning rows of the partial are appended; warnings, wall layer structures and cameras + /// nothing points at any more are removed. + /// Geometry: Node rows = instances, Shape rows = shapes, Material rows = materials; meshes are the ones the + /// written instances use. + /// + /// + public static class VimPatchService + { + private enum Role { None = 0, Changed, Context, New, Excluded } + + private const string HostDocumentKey = "\u0001host"; + private const string SharedDocumentKey = "\u0002shared"; + + /// + /// Tables whose rows are relations between rows of other tables (X in Y), plus the tables whose rows belong to + /// the row their first relation points at: a row whose end is gone goes with it. + /// + private static readonly HashSet AssociationTables = new HashSet + { + TableNames.ShapeInShapeCollection, TableNames.PhaseOrderInBimDocument, TableNames.ElementInView, + TableNames.ShapeInView, TableNames.AssetInView, TableNames.AssetInViewSheet, TableNames.LevelInView, + TableNames.DisplayUnitInBimDocument, TableNames.ElementInSystem, TableNames.ElementInWarning, + TableNames.MaterialInElement, TableNames.ViewSheetInViewSheetSet, TableNames.ViewInViewSheetSet, + TableNames.ViewInViewSheet, + TableNames.ScheduleColumn, TableNames.ScheduleCell, TableNames.CompoundStructureLayer, + }; + + /// Element-owned tables which can hold several rows per element, whatever a given file holds. + private static readonly HashSet ManyRowsPerElementTables = new HashSet + { + TableNames.Node, TableNames.Shape, TableNames.Parameter, TableNames.ElementInView, TableNames.MaterialInElement, + TableNames.ElementInSystem, TableNames.ElementInWarning, TableNames.ShapeCollection, + }; + + /// + /// Rows the Revit exporter writes once per export whatever the document (system families, system family types, + /// unassigned systems): they are filed under the first document that needed one, which differs between a full + /// and a partial export, so their UniqueId alone identifies them. + /// + private static readonly HashSet SharedSyntheticTypes = new HashSet(StringComparer.Ordinal) + { + VimConstants.SystemFamilyElementType, VimConstants.SystemFamilyTypeElementType, VimConstants.UnassignedSystem, + }; + + /// The rows the exporter writes for a document as a whole; their UniqueId is made from the project name. + private static readonly HashSet HolderTypes = new HashSet(StringComparer.Ordinal) + { + VimConstants.BimDocumentParameterHolderElementType, VimConstants.SiteParameterHolderElementType, VimConstants.BuildingParameterHolderElementType, + }; + + /// Patches the files and writes the result. Returns the counts and timings. + public static VimPatchResult Patch(string baseVimPath, string partialVimPath, string outputVimPath, VimPatchOptions options = null) + { + var sw = Stopwatch.StartNew(); + var baseTables = VimTables.Load(baseVimPath); + var partialTables = VimTables.Load(partialVimPath); + var loadMs = sw.ElapsedMilliseconds; + + var (db, result) = Patch(baseTables, partialTables, options); + result.LoadMs = loadMs; + + sw.Restart(); + db.Write(outputVimPath); + result.WriteMs = sw.ElapsedMilliseconds; + return result; + } + + /// Patches in memory; the returned builder writes the patched file. + public static (DocumentBuilder Builder, VimPatchResult Result) Patch(VimTables baseVim, VimTables partialVim, VimPatchOptions options = null) + { + options = options ?? new VimPatchOptions(); + var result = new VimPatchResult(); + var sw = Stopwatch.StartNew(); + + var baseSchema = baseVim.Header?.Schema; + var partialSchema = partialVim.Header?.Schema; + if (baseSchema != null && partialSchema != null && baseSchema.Major != partialSchema.Major) + throw new HResultException((int)ErrorCode.VimMergeObjectModelMajorVersionMismatch, + $"Object model major version mismatch: base {baseSchema}, partial {partialSchema}"); + + var sources = new[] { baseVim, partialVim }; + var tableNames = baseVim.Tables.Keys.Concat(partialVim.Tables.Keys) + .Where(n => !VimConstants.ComputedTableNames.Contains(n)) + .Distinct() + .OrderBy(n => n, StringComparer.Ordinal) + .ToArray(); + var plans = tableNames.ToDictionary(n => n, n => new TablePlan(n, sources)); + + // 1. Elements. + var (partialRole, baseChanged) = PlanElements(baseVim, partialVim, options, plans[TableNames.Element], result); + + // 2. Element-owned tables (ElementInView last: its scope needs the View rows). + var elementOwned = tableNames.Where(n => baseVim.IsElementOwned(n) || partialVim.IsElementOwned(n)).ToList(); + var ordered = elementOwned.Where(n => n != TableNames.ElementInView).ToList(); + if (elementOwned.Contains(TableNames.ElementInView)) + ordered.Add(TableNames.ElementInView); + foreach (var table in ordered) + PlanElementOwnedTable(table, sources, plans, partialRole, baseChanged); + + // 3. Other tables, referees before referrers. + var others = tableNames.Where(n => n != TableNames.Element && !elementOwned.Contains(n)).ToList(); + var (order, cyclic) = TopologicalOrder(others, sources); + foreach (var table in order) + PlanDictionaryTable(table, sources, plans, cyclic.Contains(table)); + + // 4. Rows nothing points at any more: a full export would not write them (a warning naming no exported + // element, a replaced type's wall layers, a camera of a view that is gone). + result.OrphanRowsRemoved += PruneUnreferenced(TableNames.Warning, null, sources, plans); + result.OrphanRowsRemoved += PruneUnreferenced(TableNames.CompoundStructure, TableNames.CompoundStructureLayer, sources, plans); + result.OrphanRowsRemoved += PruneLayersOfRemovedStructures(sources, plans); + result.OrphanRowsRemoved += PruneUnreferenced(TableNames.Camera, null, sources, plans); + + result.PlanMs = sw.ElapsedMilliseconds; + sw.Restart(); + + // 5. Write. + var schema = baseSchema; + if (schema == null || (partialSchema != null && partialSchema.Major == schema.Major && partialSchema.Minor > schema.Minor)) + schema = partialSchema ?? SchemaVersion.Current; + var values = new Dictionary + { + { "patched", DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture) }, + }; + foreach (var kv in options.HeaderValues ?? new Dictionary()) + values[kv.Key] = kv.Value; + var header = baseVim.Header != null + ? SerializableHeader.CreateRevisionOf(baseVim.Header, options.Generator, schema, values) + : new SerializableHeader(options.Generator, schema, "", values); + + var db = RowPlanWriter.Write(sources, plans, header, options.DeduplicateMeshes, result.Geometry); + foreach (var kv in plans) + result.TableRows[kv.Key] = (baseVim.NumRows(kv.Key), partialVim.NumRows(kv.Key), kv.Value.Count); + result.BuildMs = sw.ElapsedMilliseconds; + return (db, result); + } + + /// + /// Decides, element by element, what the output holds: the base row (kept, or context), the partial's row in its + /// place (changed), a partial row appended (new), or nothing (deleted, excluded). + /// + private static (Role[] PartialRole, bool[] BaseChanged) PlanElements(VimTables baseVim, VimTables partialVim, + VimPatchOptions options, TablePlan elementPlan, VimPatchResult result) + { + var aliases = options.UniqueIdAliases ?? new Dictionary(); + Func alias = u => u != null && aliases.TryGetValue(u, out var a) ? a : u; + var baseKeys = ElementKeys(baseVim, null); + var partialKeys = ElementKeys(partialVim, alias); + var forceChanged = new bool[baseKeys.Length]; + result.HoldersMatched = MatchHolders(baseVim, partialVim, baseKeys, partialKeys, forceChanged); + var baseUids = baseVim.Strs(TableNames.Element, "string:UniqueId") ?? new string[baseKeys.Length]; + var partialUids = partialVim.Strs(TableNames.Element, "string:UniqueId") ?? new string[partialKeys.Length]; + var baseDocTitles = baseVim.ElementDocumentTitles(); + + var changedSet = options.ChangedUniqueIds == null ? null : new HashSet(options.ChangedUniqueIds); + var deletedSet = new HashSet(options.DeletedUniqueIds ?? Array.Empty()); + var excludedSet = new HashSet(options.ExcludedUniqueIds ?? Array.Empty()); + var replacedDocs = new HashSet(options.ReplacedDocumentTitles ?? Array.Empty()); + var aliasTargets = new HashSet(aliases.Values); + + var partialByKey = new Dictionary(); + for (var i = 0; i < partialKeys.Length; ++i) + partialByKey[partialKeys[i]] = i; + + var partialRole = new Role[partialKeys.Length]; + var baseChanged = new bool[baseKeys.Length]; + var seenDeleted = new HashSet(); + + for (var b = 0; b < baseKeys.Length; ++b) + { + var uid = baseUids[b] ?? ""; + var inReplacedDoc = replacedDocs.Contains(baseDocTitles[b]); + var hasPartial = partialByKey.TryGetValue(baseKeys[b], out var p); + if (deletedSet.Contains(uid) || (inReplacedDoc && !hasPartial)) + { + if (deletedSet.Contains(uid)) seenDeleted.Add(uid); + result.Deleted++; + continue; + } + if (!hasPartial) + { + if (changedSet != null && changedSet.Contains(uid)) result.ChangedButNotInPartial.Add(uid); + elementPlan.Add(0, b); + result.Kept++; + continue; + } + var isAliasTarget = aliasTargets.Contains(uid) && aliases.ContainsKey(partialUids[p] ?? ""); + var changed = !isAliasTarget && !excludedSet.Contains(partialUids[p] ?? "") + && (changedSet == null || changedSet.Contains(uid) || inReplacedDoc || forceChanged[b]); + if (changed) + { + baseChanged[b] = true; + partialRole[p] = Role.Changed; + elementPlan.Alias(0, b, elementPlan.Add(1, p)); + result.Changed++; + } + else + { + partialRole[p] = Role.Context; + elementPlan.Alias(1, p, elementPlan.Add(0, b)); + result.Context++; + result.Kept++; + } + } + + var baseOutByKey = new Lazy>(() => + { + var d = new Dictionary(); + for (var b = 0; b < baseKeys.Length; ++b) + { + var o = elementPlan.Lookup(0, b); + if (o >= 0) d[baseKeys[b]] = o; + } + return d; + }); + for (var p = 0; p < partialKeys.Length; ++p) + { + if (partialRole[p] != Role.None) continue; + var uid = partialUids[p] ?? ""; + if (aliasTargets.Contains(uid) && partialKeys[p].Contains("#") + && baseOutByKey.Value.TryGetValue(partialKeys[p].Substring(0, partialKeys[p].LastIndexOf('#')), out var twin)) + { + // The element an alias stands for, held by the partial as well (the export view, next to the + // temporary view aliased onto it): the same element, as context. + partialRole[p] = Role.Context; + elementPlan.Alias(1, p, twin); + result.Context++; + continue; + } + if (excludedSet.Contains(uid) || aliases.ContainsKey(uid) || deletedSet.Contains(uid)) + { + // Excluded, deleted, or an alias whose target the base does not hold: not written. + partialRole[p] = Role.Excluded; + result.Excluded++; + continue; + } + partialRole[p] = Role.New; + elementPlan.Add(1, p); + result.Added++; + } + + result.DeletedButNotInBase = deletedSet.Where(u => !seenDeleted.Contains(u)).ToList(); + result.BaseElements = baseKeys.Length; + result.PartialElements = partialKeys.Length; + result.OutputElements = elementPlan.Count; + result.ElementIndexMap = (int[])elementPlan.Map[0].Clone(); + return (partialRole, baseChanged); + } + + /// + /// The document part of the element keys, per BimDocument row: every document that is not a link is the host, + /// whatever its title, path or project name (the same model is saved as several local files, renamed, moved); + /// a linked model is its title plus its ordinal among the rows with that title. + /// + private static string[] DocumentKeys(VimTables t) + { + var titles = t.Strs(TableNames.BimDocument, "string:Title") ?? new string[t.NumRows(TableNames.BimDocument)]; + var host = t.HostBimDocuments(); + var seen = new Dictionary(); + var keys = new string[titles.Length]; + for (var i = 0; i < titles.Length; ++i) + { + if (i < host.Length && host[i]) { keys[i] = HostDocumentKey; continue; } + var title = titles[i] ?? ""; + seen.TryGetValue(title, out var ordinal); + seen[title] = ordinal + 1; + keys[i] = title + "|" + ordinal; + } + return keys; + } + + /// + /// One identity per Element row: document key + UniqueId (after the aliases). A key repeated in the same file + /// gets "#n" appended to its later occurrences. A row given another element's UniqueId by an alias takes the plain + /// key first (pass 0), so the element it stands for, when the partial holds it too, is the duplicate. + /// + private static string[] ElementKeys(VimTables t, Func alias) + { + var docKeys = DocumentKeys(t); + var count = t.NumRows(TableNames.Element); + var keys = new string[count]; + var docs = t.Index(TableNames.Element, VimTables.BimDocumentColumn); + var uids = t.Strs(TableNames.Element, "string:UniqueId") ?? new string[count]; + var ids = t.Data(TableNames.Element, "long:Id"); + var types = t.Strs(TableNames.Element, "string:Type"); + var dup = new Dictionary(); + for (var pass = 0; pass < 2; ++pass) + { + for (var i = 0; i < count; ++i) + { + var raw = uids[i] ?? ""; + var u = alias == null ? raw : alias(raw) ?? raw; + var aliased = !string.Equals(u, raw, StringComparison.Ordinal); + if ((pass == 0) != aliased) continue; + var d = docs != null && docs[i] >= 0 && docs[i] < docKeys.Length ? docKeys[docs[i]] : ""; + if (ids != null && types != null && ids[i] == VimConstants.SyntheticElementId && SharedSyntheticTypes.Contains(types[i] ?? "")) + d = SharedDocumentKey; + var k = d + "\u001f" + u; + if (dup.TryGetValue(k, out var c)) { dup[k] = c + 1; k = k + "#" + c; } else dup[k] = 1; + keys[i] = k; + } + } + return keys; + } + + /// + /// The rows the exporter writes for a whole document - its parameter holder (the Element of BimDocument, which + /// carries Project Information) and its site and building holders - have a UniqueId made from the project name. + /// The project name is data, not identity: a partial holder is the base holder of the same kind in the same + /// document, whatever its name, and it is always written as changed, so the BimDocument row and Project + /// Information are refreshed in place. Rewrites partialKeys, marks forceChanged (base rows), returns the count. + /// + private static int MatchHolders(VimTables baseVim, VimTables partialVim, string[] baseKeys, string[] partialKeys, bool[] forceChanged) + { + var bIds = baseVim.Data(TableNames.Element, "long:Id"); + var pIds = partialVim.Data(TableNames.Element, "long:Id"); + var bTypes = baseVim.Strs(TableNames.Element, "string:Type"); + var pTypes = partialVim.Strs(TableNames.Element, "string:Type"); + var bUids = baseVim.Strs(TableNames.Element, "string:UniqueId"); + var pUids = partialVim.Strs(TableNames.Element, "string:UniqueId"); + var bDocs = baseVim.Index(TableNames.Element, VimTables.BimDocumentColumn); + var pDocs = partialVim.Index(TableNames.Element, VimTables.BimDocumentColumn); + if (bIds == null || pIds == null || bTypes == null || pTypes == null || bDocs == null || pDocs == null || bUids == null || pUids == null) + return 0; + var bDocKeys = DocumentKeys(baseVim); + var pDocKeys = DocumentKeys(partialVim); + string DocOf(string[] dk, int[] docs, int e) => docs[e] >= 0 && docs[e] < dk.Length ? dk[docs[e]] : ""; + bool IsHolder(long[] ids, string[] types, int e) => ids[e] == VimConstants.SyntheticElementId && HolderTypes.Contains(types[e] ?? ""); + + var baseByKey = new Dictionary(); + for (var b = 0; b < baseKeys.Length; ++b) baseByKey[baseKeys[b]] = b; + + var claimed = new HashSet(); + var matched = 0; + var pending = new List(); + for (var p = 0; p < partialKeys.Length; ++p) + { + if (!IsHolder(pIds, pTypes, p)) continue; + if (baseByKey.TryGetValue(partialKeys[p], out var b)) + { + claimed.Add(b); + forceChanged[b] = true; + matched++; + } + else + { + pending.Add(p); + } + } + if (pending.Count == 0) + return matched; + + var baseHolders = new Dictionary>(); + var baseHoldersByUid = new Dictionary(); + for (var b = 0; b < baseKeys.Length; ++b) + { + if (!IsHolder(bIds, bTypes, b)) continue; + var k = DocOf(bDocKeys, bDocs, b) + "\u001f" + bTypes[b]; + if (!baseHolders.TryGetValue(k, out var l)) baseHolders[k] = l = new List(); + l.Add(b); + if (!baseHoldersByUid.ContainsKey(bUids[b] ?? "")) baseHoldersByUid[bUids[b] ?? ""] = b; + } + foreach (var p in pending) + { + var b = -1; + if (baseHolders.TryGetValue(DocOf(pDocKeys, pDocs, p) + "\u001f" + pTypes[p], out var l)) + foreach (var x in l) + if (!claimed.Contains(x)) { b = x; break; } + if (b >= 0) + { + claimed.Add(b); + partialKeys[p] = baseKeys[b]; + forceChanged[b] = true; + matched++; + continue; + } + // A site or building holder shared with another document of the same project name: the base row is it. + if (pTypes[p] != VimConstants.BimDocumentParameterHolderElementType + && baseHoldersByUid.TryGetValue(pUids[p] ?? "", out var shared) && !claimed.Contains(shared)) + { + partialKeys[p] = baseKeys[shared]; + matched++; + } + } + return matched; + } + + private static void PlanElementOwnedTable(string table, VimTables[] sources, Dictionary plans, + Role[] partialRole, bool[] baseChanged) + { + var baseVim = sources[0]; + var partialVim = sources[1]; + var plan = plans[table]; + var elementPlan = plans[TableNames.Element]; + var baseOwner = baseVim.Index(table, VimTables.ElementColumn) ?? new int[baseVim.NumRows(table)]; + var partialOwner = partialVim.Index(table, VimTables.ElementColumn) ?? new int[partialVim.NumRows(table)]; + + // ElementInView: only the rows of the views the partial writes are replaced (rows for other views stay). + Func inScope = (s, r) => true; + if (table == TableNames.ElementInView) + { + var viewPlan = plans.TryGetValue(TableNames.View, out var vp) ? vp : null; + var viewColumn = "index:" + TableNames.View + ":View"; + var views = sources.Select(s => s.Index(table, viewColumn)).ToArray(); + var scopeViews = new HashSet(); + if (viewPlan != null && views[1] != null) + for (var r = 0; r < partialOwner.Length; ++r) + { + var e = partialOwner[r]; + if (e < 0 || (partialRole[e] != Role.Changed && partialRole[e] != Role.New)) continue; + var ov = viewPlan.Lookup(1, views[1][r]); + if (ov >= 0) scopeViews.Add(ov); + } + inScope = (s, r) => + { + var v = views[s] == null ? -1 : views[s][r]; + var ov = viewPlan?.Lookup(s, v) ?? -1; + return ov >= 0 && scopeViews.Contains(ov); + }; + } + + var oneRowPerElement = !ManyRowsPerElementTables.Contains(table) && IsOneRowPerElement(baseOwner) && IsOneRowPerElement(partialOwner); + if (oneRowPerElement) + { + // Rows follow their element, in place. + var partialRowByOutElement = new Dictionary(); + for (var r = 0; r < partialOwner.Length; ++r) + { + var e = partialOwner[r]; + if (e < 0) continue; + var oe = elementPlan.Lookup(1, e); + if (oe >= 0) partialRowByOutElement[oe] = r; + } + for (var r = 0; r < baseOwner.Length; ++r) + { + var e = baseOwner[r]; + if (e < 0) { plan.Add(0, r); continue; } + var oe = elementPlan.Lookup(0, e); + if (oe < 0) continue; // element deleted + if (!partialRowByOutElement.TryGetValue(oe, out var pr)) { plan.Add(0, r); continue; } + if (baseChanged[e]) plan.Alias(0, r, plan.Add(1, pr)); + else plan.Alias(1, pr, plan.Add(0, r)); + } + // Two partial elements standing for one output element (the export view and the temporary view aliased + // onto it) share that element's row. + var rowOfOutElement = new Dictionary(); + for (var i = 0; i < plan.Count; ++i) + { + var src = plan.Source[i]; + var e = (src == 0 ? baseOwner : partialOwner)[plan.Row[i]]; + var oe = e < 0 ? -1 : elementPlan.Lookup(src, e); + if (oe >= 0 && !rowOfOutElement.ContainsKey(oe)) rowOfOutElement[oe] = i; + } + for (var r = 0; r < partialOwner.Length; ++r) + { + if (plan.Map[1][r] >= 0) continue; + var e = partialOwner[r]; + if (e < 0) { plan.Add(1, r); continue; } + if (partialRole[e] == Role.Excluded || partialRole[e] == Role.None) continue; + var oe = elementPlan.Lookup(1, e); + if (oe < 0) continue; + if (rowOfOutElement.TryGetValue(oe, out var existing)) plan.Alias(1, r, existing); + else rowOfOutElement[oe] = plan.Add(1, r); + } + return; + } + + // Several rows per element: a changed element's base rows (in scope) give way to the partial's. + for (var r = 0; r < baseOwner.Length; ++r) + { + var e = baseOwner[r]; + if (e < 0) { plan.Add(0, r); continue; } + if (elementPlan.Lookup(0, e) < 0) continue; // element deleted + if (baseChanged[e] && inScope(0, r)) continue; // replaced by the partial's rows + plan.Add(0, r); + } + for (var r = 0; r < partialOwner.Length; ++r) + { + var e = partialOwner[r]; + if (e < 0) continue; + var role = partialRole[e]; + if (role != Role.New && !(role == Role.Changed && inScope(1, r))) continue; + // A new element's row for a view the output does not hold (the temporary view, unaliased). + if (table == TableNames.ElementInView && !inScope(1, r)) + { + var views = partialVim.Index(table, "index:" + TableNames.View + ":View"); + var v = views == null ? -1 : views[r]; + if ((plans.TryGetValue(TableNames.View, out var vp) ? vp.Lookup(1, v) : -1) < 0) continue; + } + plan.Add(1, r); + } + } + + private static bool IsOneRowPerElement(int[] owner) + { + var seen = new HashSet(); + foreach (var e in owner) + if (e >= 0 && !seen.Add(e)) + return false; + return true; + } + + private static (List Order, HashSet Cyclic) TopologicalOrder(List tables, VimTables[] sources) + { + var set = new HashSet(tables); + var deps = tables.ToDictionary(t => t, t => new HashSet( + sources.SelectMany(s => s.IndexRelations(t)).Select(r => r.Related).Where(r => r != t && set.Contains(r)))); + var order = new List(); + var done = new HashSet(); + bool progress; + do + { + progress = false; + foreach (var t in tables) + { + if (done.Contains(t) || !deps[t].All(done.Contains)) continue; + order.Add(t); + done.Add(t); + progress = true; + } + } while (progress); + var cyclic = new HashSet(tables.Where(t => !done.Contains(t))); + order.AddRange(tables.Where(cyclic.Contains)); + return (order, cyclic); + } + + private static bool IsAssociation(string table) + => AssociationTables.Contains(table); + + /// Base rows stay (associations lose rows whose ends are gone); partial rows dedupe by key or content. + private static void PlanDictionaryTable(string table, VimTables[] sources, Dictionary plans, bool cyclic) + { + var plan = plans[table]; + var assoc = IsAssociation(table); + var relations = sources.SelectMany(s => s.IndexRelations(table)).Distinct().OrderBy(r => r.Column, StringComparer.Ordinal).ToList(); + + bool EndsAlive(int s, int r) + { + if (!assoc) return true; + foreach (var (col, related) in relations) + { + var c = sources[s].Index(table, col); + if (c == null || c[r] < 0 || related == table) continue; + if (!plans.TryGetValue(related, out var rp) || rp.Lookup(s, c[r]) < 0) return false; + } + return true; + } + + var nb = sources[0].NumRows(table); + for (var r = 0; r < nb; ++r) + if (EndsAlive(0, r)) + plan.Add(0, r); + + var np = sources[1].NumRows(table); + if (np == 0) return; + + // Two warnings with the same text are two warnings (they name different elements): the partial's are + // appended; the ones no element names any more are pruned afterwards. + if (cyclic || table == TableNames.Warning) + { + for (var r = 0; r < np; ++r) + if (EndsAlive(1, r)) + plan.Add(1, r); + return; + } + + var keyOf = KeyFunction(table, sources, plans, relations); + var baseIndex = new Dictionary(); + for (var i = 0; i < plan.Count; ++i) + { + var bk = keyOf(0, plan.Row[i]); + if (!baseIndex.ContainsKey(bk)) baseIndex[bk] = i; + } + for (var r = 0; r < np; ++r) + { + if (!EndsAlive(1, r)) continue; + var k = keyOf(1, r); + if (baseIndex.TryGetValue(k, out var o)) { plan.Alias(1, r, o); continue; } + baseIndex[k] = plan.Add(1, r); + } + } + + /// + /// What makes two rows of a dictionary table the same row: a few key columns for the tables that have a natural + /// key, otherwise every column with relations re-pointed. A parameter descriptor ignores IsReadOnly: the exporter + /// gives a descriptor the IsReadOnly of the first parameter it meets (Revit's flag is per element), which a + /// partial export meets in another order - the base's row is the descriptor. + /// + private static Func KeyFunction(string table, VimTables[] sources, Dictionary plans, + List<(string Column, string Related)> relations) + { + string[] keyStringColumns = null; + switch (table) + { + case TableNames.Category: keyStringColumns = new[] { "string:Name", "string:BuiltInCategory" }; break; + case TableNames.DisplayUnit: keyStringColumns = new[] { "string:Spec", "string:Type", "string:Label" }; break; + case TableNames.Asset: keyStringColumns = new[] { "string:BufferName" }; break; + } + var ignoredDataColumns = table == TableNames.ParameterDescriptor + ? new HashSet { "byte:IsReadOnly" } + : new HashSet(); + + var stringCols = keyStringColumns ?? sources.SelectMany(s => s.GetTable(table)?.StringColumns.Select(c => c.Name) ?? Enumerable.Empty()) + .Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray(); + var dataCols = keyStringColumns != null ? Array.Empty() : sources.SelectMany(s => s.GetTable(table)?.DataColumns.Select(c => c.Name) ?? Enumerable.Empty()) + .Where(c => !ignoredDataColumns.Contains(c)) + .Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray(); + var indexCols = keyStringColumns != null ? new List<(string Column, string Related)>() : relations.Where(r => r.Related != table).ToList(); + + var strs = sources.Select(s => stringCols.Select(c => s.StringIndices(table, c)).ToArray()).ToArray(); + var datas = sources.Select(s => dataCols.Select(c => s.Data(table, c)?.Data).ToArray()).ToArray(); + var idxs = sources.Select(s => indexCols.Select(c => s.Index(table, c.Column)).ToArray()).ToArray(); + + return (s, r) => + { + var sb = new StringBuilder(); + for (var i = 0; i < stringCols.Length; ++i) + { + var c = strs[s][i]; + sb.Append(c == null ? "" : sources[s].Str(c[r])).Append('\u001f'); + } + for (var i = 0; i < dataCols.Length; ++i) + { + var c = datas[s][i]; + sb.Append(c == null ? "0" : Convert.ToString(c.GetValue(r), CultureInfo.InvariantCulture)).Append('\u001f'); + } + for (var i = 0; i < indexCols.Count; ++i) + { + var c = idxs[s][i]; + var v = c == null ? -1 : c[r]; + var o = v < 0 ? v : (plans.TryGetValue(indexCols[i].Related, out var rp) ? rp.Lookup(s, v) : -1); + sb.Append(o).Append('\u001f'); + } + return sb.ToString(); + }; + } + + /// Removes the rows of a table which no written row of another table (except ignoredReferrer) points at. + private static int PruneUnreferenced(string table, string ignoredReferrer, VimTables[] sources, Dictionary plans) + { + if (!plans.TryGetValue(table, out var plan) || plan.Count == 0) return 0; + var used = new bool[plan.Count]; + foreach (var referrer in plans.Values) + { + if (referrer.Name == table || referrer.Name == ignoredReferrer) continue; + foreach (var (column, related) in sources.SelectMany(s => s.IndexRelations(referrer.Name)).Distinct()) + { + if (related != table) continue; + var cols = sources.Select(s => s.Index(referrer.Name, column)).ToArray(); + for (var i = 0; i < referrer.Count; ++i) + { + var c = cols[referrer.Source[i]]; + var o = plan.Lookup(referrer.Source[i], c == null ? -1 : c[referrer.Row[i]]); + if (o >= 0) used[o] = true; + } + } + } + return plan.RemoveWhere(i => !used[i]); + } + + /// The wall layers of a removed wall layer structure go with it. + private static int PruneLayersOfRemovedStructures(VimTables[] sources, Dictionary plans) + { + if (!plans.TryGetValue(TableNames.CompoundStructureLayer, out var layers) || !plans.TryGetValue(TableNames.CompoundStructure, out var structures)) + return 0; + var column = sources.Select(s => s.Index(TableNames.CompoundStructureLayer, "index:" + TableNames.CompoundStructure + ":CompoundStructure")).ToArray(); + return layers.RemoveWhere(i => + { + var c = column[layers.Source[i]]; + var v = c == null ? -1 : c[layers.Row[i]]; + return v >= 0 && structures.Lookup(layers.Source[i], v) < 0; + }); + } + } +} diff --git a/src/cs/vim/Vim.Format/Merge/VimTables.cs b/src/cs/vim/Vim.Format/Merge/VimTables.cs new file mode 100644 index 00000000..bf9aa461 --- /dev/null +++ b/src/cs/vim/Vim.Format/Merge/VimTables.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Vim.BFast; +using Vim.G3d; + +namespace Vim.Format.Merge +{ + /// + /// A VIM file held as its raw entity tables, string table, assets and G3D geometry. No DocumentModel is built, so + /// loading a large file costs only the deserialization (TowerS, 224 MB: about 0.2 s). Used by + /// and by the callers that decide what to patch. + /// + public sealed class VimTables + { + public const string ElementColumn = "index:" + TableNames.Element + ":Element"; + public const string BimDocumentColumn = "index:" + TableNames.BimDocument + ":BimDocument"; + + public SerializableDocument Document { get; } + public string[] Strings { get; } + public Dictionary Tables { get; } + public G3D Geometry { get; } + + private readonly Dictionary _numRows = new Dictionary(); + + public VimTables(SerializableDocument document) + { + Document = document ?? throw new ArgumentNullException(nameof(document)); + Strings = document.StringTable ?? Array.Empty(); + Tables = document.EntityTables.ToDictionary(t => t.Name, t => t); + Geometry = document.Geometry; + } + + public static VimTables Load(string vimFilePath) + => new VimTables(Serializer.Deserialize(vimFilePath)); + + public SerializableHeader Header => Document.Header; + + public SerializableEntityTable GetTable(string table) + => Tables.TryGetValue(table, out var t) ? t : null; + + public int NumRows(string table) + { + if (_numRows.TryGetValue(table, out var n)) + return n; + var first = GetTable(table)?.IndexColumns.Cast() + .Concat(GetTable(table).StringColumns) + .Concat(GetTable(table).DataColumns) + .FirstOrDefault(); + n = first?.NumElements() ?? 0; + _numRows[table] = n; + return n; + } + + /// The values of an index column, or null when the table or the column is absent. + public int[] Index(string table, string column) + => GetTable(table)?.IndexColumns.FirstOrDefault(c => c.Name == column)?.Array; + + /// The string-table indices of a string column, or null. + public int[] StringIndices(string table, string column) + => GetTable(table)?.StringColumns.FirstOrDefault(c => c.Name == column)?.Array; + + /// The resolved values of a string column, or null. + public string[] Strs(string table, string column) + => StringIndices(table, column)?.Select(Str).ToArray(); + + public string Str(int stringIndex) + => stringIndex >= 0 && stringIndex < Strings.Length ? Strings[stringIndex] ?? "" : ""; + + public INamedBuffer Data(string table, string column) + => GetTable(table)?.DataColumns.FirstOrDefault(c => c.Name == column); + + public T[] Data(string table, string column) where T : unmanaged + => Data(table, column)?.Data as T[]; + + /// Element-owned tables have an "index:Vim.Element:Element" column (Element itself excluded). + public bool IsElementOwned(string table) + => table != TableNames.Element && GetTable(table)?.IndexColumns.Any(c => c.Name == ElementColumn) == true; + + /// The table each index column of the table points at. + public IEnumerable<(string Column, string Related)> IndexRelations(string table) + => (GetTable(table)?.IndexColumns ?? new List>()) + .Select(c => (c.Name, ColumnExtensions.GetRelatedTableNameFromColumnName(c.Name))); + + /// + /// For each BimDocument row: true when it is the host model rather than a linked one (IsLinked = 0; without that + /// column, a row with no parent document). + /// + public bool[] HostBimDocuments() + { + var n = NumRows(TableNames.BimDocument); + var linked = Data(TableNames.BimDocument, "byte:IsLinked"); + var parents = Index(TableNames.BimDocument, "index:" + TableNames.BimDocument + ":Parent"); + var r = new bool[n]; + for (var i = 0; i < n; ++i) + r[i] = linked != null && i < linked.Length + ? linked[i] == 0 + : parents == null || i >= parents.Length || parents[i] < 0; + return r; + } + + /// For each Element row: true when its BimDocument is the host model. + public bool[] HostElements() + { + var host = HostBimDocuments(); + var docs = Index(TableNames.Element, BimDocumentColumn); + var r = new bool[NumRows(TableNames.Element)]; + for (var i = 0; i < r.Length; ++i) + { + var d = docs == null ? -1 : docs[i]; + r[i] = d >= 0 && d < host.Length && host[d]; + } + return r; + } + + /// The BimDocument title of each Element row ("" when none). + public string[] ElementDocumentTitles() + { + var titles = Strs(TableNames.BimDocument, "string:Title") ?? Array.Empty(); + var docs = Index(TableNames.Element, BimDocumentColumn); + var r = new string[NumRows(TableNames.Element)]; + for (var i = 0; i < r.Length; ++i) + r[i] = docs != null && docs[i] >= 0 && docs[i] < titles.Length ? titles[docs[i]] ?? "" : ""; + return r; + } + + /// + /// The host model's elements held more than once (same UniqueId). A full export holds none; a file in which some + /// are must not be patched. + /// + public int HostElementsHeldTwice() + { + var host = HostElements(); + var uids = Strs(TableNames.Element, "string:UniqueId") ?? Array.Empty(); + var seen = new HashSet(StringComparer.Ordinal); + var twice = 0; + for (var i = 0; i < uids.Length; ++i) + if (host[i] && !string.IsNullOrEmpty(uids[i]) && !seen.Add(uids[i])) + twice++; + return twice; + } + } +} diff --git a/src/cs/vim/Vim.Format/ObjectModel/ObjectModel.cs b/src/cs/vim/Vim.Format/ObjectModel/ObjectModel.cs index ddcf8846..68b8d34c 100644 --- a/src/cs/vim/Vim.Format/ObjectModel/ObjectModel.cs +++ b/src/cs/vim/Vim.Format/ObjectModel/ObjectModel.cs @@ -14,6 +14,11 @@ public static class SchemaVersion // ReSharper disable MemberHidesStaticFromOuterClass public static class History { + // Schema additions + // Vim.Element__string:ChangeToken + // Vim.BimDocument__string:Identity + public const string v5_8_0 = "5.8.0"; + // Schema additions // Vim.Element__string:Creator // Vim.Element__string:LastChangedBy @@ -186,7 +191,8 @@ public static class History // ReSharper enable MemberHidesStaticFromOuterClass // [MAINTAIN] Add more object model SerializableVersions below and update the current one. - public static SerializableVersion Current => v5_7_0; + public static SerializableVersion Current => v5_8_0; + public static SerializableVersion v5_8_0 => SerializableVersion.Parse(History.v5_8_0); public static SerializableVersion v5_7_0 => SerializableVersion.Parse(History.v5_7_0); public static SerializableVersion v5_6_0 => SerializableVersion.Parse(History.v5_6_0); public static SerializableVersion v5_5_0 => SerializableVersion.Parse(History.v5_5_0); @@ -800,6 +806,14 @@ public Vector3 Location public string LastChangedBy; public string Owner; + /// + /// An opaque token which changes whenever the element changes in its source document; empty when unknown. + /// A differential update compares it with the source to find what changed since this file was written. + /// Revit: Element.VersionGuid (2021+); a linked model's RevitLinkInstance or RevitLinkType, which Revit + /// re-versions every time it reloads the link, holds a hash of its parameters and placement instead. + /// + public string ChangeToken; + public Relation _Level; public Relation _PhaseCreated; public Relation _PhaseDemolished; @@ -939,6 +953,14 @@ public partial class BimDocument : EntityWithElement public string Guid; public int NumSaves; + + /// + /// Identifies the document across saves, Save As of a local copy and reopenings, unlike Guid (its version). + /// Never derived from the project name. Revit: Document.CreationGUID (2024+; before that, the UniqueId of the + /// ProjectInformation element), followed by "|cloud:" and the cloud model GUID for a cloud model. + /// + public string Identity; + public bool IsLinked; public bool IsDetached; public bool IsWorkshared; diff --git a/src/cs/vim/Vim.Format/ObjectModel/ObjectModelBuilder.cs b/src/cs/vim/Vim.Format/ObjectModel/ObjectModelBuilder.cs index ad2952d4..1eb151af 100644 --- a/src/cs/vim/Vim.Format/ObjectModel/ObjectModelBuilder.cs +++ b/src/cs/vim/Vim.Format/ObjectModel/ObjectModelBuilder.cs @@ -1,4 +1,6 @@ -namespace Vim.Format.ObjectModel +using System.Collections.Generic; + +namespace Vim.Format.ObjectModel { /// /// This class makes it easy to fill out the entity tables of a VIM, by allowing the user to specify a mapping @@ -8,7 +10,7 @@ /// public partial class ObjectModelBuilder { - public DocumentBuilder ToDocumentBuilder(string generator, string versionString) - => AddEntityTableSets(new DocumentBuilder(generator, SchemaVersion.Current, versionString)); + public DocumentBuilder ToDocumentBuilder(string generator, string versionString, IReadOnlyDictionary optionalHeaderValues = null) + => AddEntityTableSets(new DocumentBuilder(generator, SchemaVersion.Current, versionString, optionalHeaderValues)); } } diff --git a/src/cs/vim/Vim.Format/ObjectModel/ObjectModelGenerated.cs b/src/cs/vim/Vim.Format/ObjectModel/ObjectModelGenerated.cs index 8df50365..68a237f3 100644 --- a/src/cs/vim/Vim.Format/ObjectModel/ObjectModelGenerated.cs +++ b/src/cs/vim/Vim.Format/ObjectModel/ObjectModelGenerated.cs @@ -194,6 +194,7 @@ public override bool FieldsAreEqual(object obj) (Creator == other.Creator) && (LastChangedBy == other.LastChangedBy) && (Owner == other.Owner) && + (ChangeToken == other.ChangeToken) && (_Level?.Index == other._Level?.Index) && (_PhaseCreated?.Index == other._PhaseCreated?.Index) && (_PhaseDemolished?.Index == other._PhaseDemolished?.Index) && @@ -485,6 +486,7 @@ public override bool FieldsAreEqual(object obj) (Title == other.Title) && (IsMetric == other.IsMetric) && (NumSaves == other.NumSaves) && + (Identity == other.Identity) && (IsLinked == other.IsLinked) && (IsDetached == other.IsDetached) && (IsWorkshared == other.IsWorkshared) && @@ -2143,6 +2145,8 @@ public Parameter GetParameter(int n) public String GetElementLastChangedBy(int index, String defaultValue = "") => ElementLastChangedBy?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; public IArray ElementOwner { get; } public String GetElementOwner(int index, String defaultValue = "") => ElementOwner?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; + public IArray ElementChangeToken { get; } + public String GetElementChangeToken(int index, String defaultValue = "") => ElementChangeToken?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; public IArray ElementLevelIndex { get; } public int GetElementLevelIndex(int index) => ElementLevelIndex?.ElementAtOrDefault(index, EntityRelation.None) ?? EntityRelation.None; public IArray ElementPhaseCreatedIndex { get; } @@ -2185,6 +2189,7 @@ public Element GetElement(int n) r.Creator = ElementCreator.ElementAtOrDefault(n); r.LastChangedBy = ElementLastChangedBy.ElementAtOrDefault(n); r.Owner = ElementOwner.ElementAtOrDefault(n); + r.ChangeToken = ElementChangeToken.ElementAtOrDefault(n); r._Level = new Relation(GetElementLevelIndex(n), GetLevel); r._PhaseCreated = new Relation(GetElementPhaseCreatedIndex(n), GetPhase); r._PhaseDemolished = new Relation(GetElementPhaseDemolishedIndex(n), GetPhase); @@ -2429,6 +2434,8 @@ public Room GetRoom(int n) public String GetBimDocumentGuid(int index, String defaultValue = "") => BimDocumentGuid?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; public IArray BimDocumentNumSaves { get; } public Int32 GetBimDocumentNumSaves(int index, Int32 defaultValue = default) => BimDocumentNumSaves?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; + public IArray BimDocumentIdentity { get; } + public String GetBimDocumentIdentity(int index, String defaultValue = "") => BimDocumentIdentity?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; public IArray BimDocumentIsLinked { get; } public Boolean GetBimDocumentIsLinked(int index, Boolean defaultValue = default) => BimDocumentIsLinked?.ElementAtOrDefault(index, defaultValue) ?? defaultValue; public IArray BimDocumentIsDetached { get; } @@ -2499,6 +2506,7 @@ public BimDocument GetBimDocument(int n) r.IsMetric = BimDocumentIsMetric.ElementAtOrDefault(n); r.Guid = BimDocumentGuid.ElementAtOrDefault(n); r.NumSaves = BimDocumentNumSaves.ElementAtOrDefault(n); + r.Identity = BimDocumentIdentity.ElementAtOrDefault(n); r.IsLinked = BimDocumentIsLinked.ElementAtOrDefault(n); r.IsDetached = BimDocumentIsDetached.ElementAtOrDefault(n); r.IsWorkshared = BimDocumentIsWorkshared.ElementAtOrDefault(n); @@ -4076,6 +4084,7 @@ public DocumentModel(Document d, bool inParallel = true) ElementCreator = ElementEntityTable?.GetStringColumnValues("string:Creator") ?? Array.Empty().ToIArray(); ElementLastChangedBy = ElementEntityTable?.GetStringColumnValues("string:LastChangedBy") ?? Array.Empty().ToIArray(); ElementOwner = ElementEntityTable?.GetStringColumnValues("string:Owner") ?? Array.Empty().ToIArray(); + ElementChangeToken = ElementEntityTable?.GetStringColumnValues("string:ChangeToken") ?? Array.Empty().ToIArray(); WorksetId = WorksetEntityTable?.GetDataColumnValues("int:Id") ?? Array.Empty().ToIArray(); WorksetName = WorksetEntityTable?.GetStringColumnValues("string:Name") ?? Array.Empty().ToIArray(); WorksetKind = WorksetEntityTable?.GetStringColumnValues("string:Kind") ?? Array.Empty().ToIArray(); @@ -4105,6 +4114,7 @@ public DocumentModel(Document d, bool inParallel = true) BimDocumentIsMetric = BimDocumentEntityTable?.GetDataColumnValues("byte:IsMetric") ?? Array.Empty().ToIArray(); BimDocumentGuid = BimDocumentEntityTable?.GetStringColumnValues("string:Guid") ?? Array.Empty().ToIArray(); BimDocumentNumSaves = BimDocumentEntityTable?.GetDataColumnValues("int:NumSaves") ?? Array.Empty().ToIArray(); + BimDocumentIdentity = BimDocumentEntityTable?.GetStringColumnValues("string:Identity") ?? Array.Empty().ToIArray(); BimDocumentIsLinked = BimDocumentEntityTable?.GetDataColumnValues("byte:IsLinked") ?? Array.Empty().ToIArray(); BimDocumentIsDetached = BimDocumentEntityTable?.GetDataColumnValues("byte:IsDetached") ?? Array.Empty().ToIArray(); BimDocumentIsWorkshared = BimDocumentEntityTable?.GetDataColumnValues("byte:IsWorkshared") ?? Array.Empty().ToIArray(); @@ -5218,6 +5228,7 @@ public ElementTable(SerializableEntityTable rawTable, string[] stringTable, Enti Column_Creator = GetStringColumnValues("string:Creator") ?? Array.Empty(); Column_LastChangedBy = GetStringColumnValues("string:LastChangedBy") ?? Array.Empty(); Column_Owner = GetStringColumnValues("string:Owner") ?? Array.Empty(); + Column_ChangeToken = GetStringColumnValues("string:ChangeToken") ?? Array.Empty(); Column_LevelIndex = GetIndexColumnValues("index:Vim.Level:Level") ?? Array.Empty(); Column_PhaseCreatedIndex = GetIndexColumnValues("index:Vim.Phase:PhaseCreated") ?? Array.Empty(); Column_PhaseDemolishedIndex = GetIndexColumnValues("index:Vim.Phase:PhaseDemolished") ?? Array.Empty(); @@ -5255,6 +5266,8 @@ public ElementTable(SerializableEntityTable rawTable, string[] stringTable, Enti public String GetLastChangedBy(int index, String @default = "") => Column_LastChangedBy.ElementAtOrDefault(index, @default); public String[] Column_Owner { get; } public String GetOwner(int index, String @default = "") => Column_Owner.ElementAtOrDefault(index, @default); + public String[] Column_ChangeToken { get; } + public String GetChangeToken(int index, String @default = "") => Column_ChangeToken.ElementAtOrDefault(index, @default); public int[] Column_LevelIndex { get; } public int GetLevelIndex(int index) => Column_LevelIndex.ElementAtOrDefault(index, EntityRelation.None); public Level GetLevel(int index) => _GetReferencedLevel(GetLevelIndex(index)); @@ -5317,6 +5330,7 @@ public Element Get(int index) r.Creator = GetCreator(index); r.LastChangedBy = GetLastChangedBy(index); r.Owner = GetOwner(index); + r.ChangeToken = GetChangeToken(index); r._Level = new Relation(GetLevelIndex(index), _GetReferencedLevel); r._PhaseCreated = new Relation(GetPhaseCreatedIndex(index), _GetReferencedPhaseCreated); r._PhaseDemolished = new Relation(GetPhaseDemolishedIndex(index), _GetReferencedPhaseDemolished); @@ -5716,6 +5730,7 @@ public BimDocumentTable(SerializableEntityTable rawTable, string[] stringTable, Column_IsMetric = GetDataColumnValues("byte:IsMetric") ?? Array.Empty(); Column_Guid = GetStringColumnValues("string:Guid") ?? Array.Empty(); Column_NumSaves = GetDataColumnValues("int:NumSaves") ?? Array.Empty(); + Column_Identity = GetStringColumnValues("string:Identity") ?? Array.Empty(); Column_IsLinked = GetDataColumnValues("byte:IsLinked") ?? Array.Empty(); Column_IsDetached = GetDataColumnValues("byte:IsDetached") ?? Array.Empty(); Column_IsWorkshared = GetDataColumnValues("byte:IsWorkshared") ?? Array.Empty(); @@ -5755,6 +5770,8 @@ public BimDocumentTable(SerializableEntityTable rawTable, string[] stringTable, public String GetGuid(int index, String @default = "") => Column_Guid.ElementAtOrDefault(index, @default); public Int32[] Column_NumSaves { get; } public Int32 GetNumSaves(int index, Int32 @default = default) => Column_NumSaves.ElementAtOrDefault(index, @default); + public String[] Column_Identity { get; } + public String GetIdentity(int index, String @default = "") => Column_Identity.ElementAtOrDefault(index, @default); public Boolean[] Column_IsLinked { get; } public Boolean GetIsLinked(int index, Boolean @default = default) => Column_IsLinked.ElementAtOrDefault(index, @default); public Boolean[] Column_IsDetached { get; } @@ -5831,6 +5848,7 @@ public BimDocument Get(int index) r.IsMetric = GetIsMetric(index); r.Guid = GetGuid(index); r.NumSaves = GetNumSaves(index); + r.Identity = GetIdentity(index); r.IsLinked = GetIsLinked(index); r.IsDetached = GetIsDetached(index); r.IsWorkshared = GetIsWorkshared(index); @@ -8300,6 +8318,11 @@ public static EntityTableBuilder ToElementTableBuilder(this EntitySetBuilder Instances { get; } = new List(); public List Shapes { get; } = new List(); - public DocumentBuilder ToDocumentBuilder(string generator, string versionString) + public DocumentBuilder ToDocumentBuilder(string generator, string versionString, IReadOnlyDictionary optionalHeaderValues = null) { - return ObjectModelBuilder.ToDocumentBuilder(generator, versionString) + return ObjectModelBuilder.ToDocumentBuilder(generator, versionString, optionalHeaderValues) .AddMeshes(Meshes.Select(g => g.Subdivide())) .AddInstances(Instances) .AddShapes(Shapes) diff --git a/src/ts/src/objectModel.ts b/src/ts/src/objectModel.ts index c0a5ea4f..ae35393d 100644 --- a/src/ts/src/objectModel.ts +++ b/src/ts/src/objectModel.ts @@ -623,6 +623,7 @@ export interface IElement { creator?: string lastChangedBy?: string owner?: string + changeToken?: string levelIndex?: number level?: ILevel @@ -677,6 +678,8 @@ export interface IElementTable { getAllLastChangedBy(): Promise getOwner(elementIndex: number): Promise getAllOwner(): Promise + getChangeToken(elementIndex: number): Promise + getAllChangeToken(): Promise getLevelIndex(elementIndex: number): Promise getAllLevelIndex(): Promise @@ -727,6 +730,7 @@ export class Element implements IElement { creator?: string lastChangedBy?: string owner?: string + changeToken?: string levelIndex?: number level?: ILevel @@ -768,6 +772,7 @@ export class Element implements IElement { table.getCreator(index).then(v => result.creator = v), table.getLastChangedBy(index).then(v => result.lastChangedBy = v), table.getOwner(index).then(v => result.owner = v), + table.getChangeToken(index).then(v => result.changeToken = v), table.getLevelIndex(index).then(v => result.levelIndex = v), table.getPhaseCreatedIndex(index).then(v => result.phaseCreatedIndex = v), table.getPhaseDemolishedIndex(index).then(v => result.phaseDemolishedIndex = v), @@ -826,6 +831,7 @@ export class ElementTable implements IElementTable { let creator: string[] | undefined let lastChangedBy: string[] | undefined let owner: string[] | undefined + let changeToken: string[] | undefined let levelIndex: number[] | undefined let phaseCreatedIndex: number[] | undefined let phaseDemolishedIndex: number[] | undefined @@ -851,6 +857,7 @@ export class ElementTable implements IElementTable { (async () => { creator = (await localTable.getStringArray("string:Creator")) })(), (async () => { lastChangedBy = (await localTable.getStringArray("string:LastChangedBy")) })(), (async () => { owner = (await localTable.getStringArray("string:Owner")) })(), + (async () => { changeToken = (await localTable.getStringArray("string:ChangeToken")) })(), (async () => { levelIndex = (await localTable.getNumberArray("index:Vim.Level:Level")) })(), (async () => { phaseCreatedIndex = (await localTable.getNumberArray("index:Vim.Phase:PhaseCreated")) })(), (async () => { phaseDemolishedIndex = (await localTable.getNumberArray("index:Vim.Phase:PhaseDemolished")) })(), @@ -882,6 +889,7 @@ export class ElementTable implements IElementTable { creator: creator ? creator[i] : undefined, lastChangedBy: lastChangedBy ? lastChangedBy[i] : undefined, owner: owner ? owner[i] : undefined, + changeToken: changeToken ? changeToken[i] : undefined, levelIndex: levelIndex ? levelIndex[i] : undefined, phaseCreatedIndex: phaseCreatedIndex ? phaseCreatedIndex[i] : undefined, phaseDemolishedIndex: phaseDemolishedIndex ? phaseDemolishedIndex[i] : undefined, @@ -995,6 +1003,14 @@ export class ElementTable implements IElementTable { return (await this.entityTable.getStringArray("string:Owner")) } + async getChangeToken(elementIndex: number): Promise { + return (await this.entityTable.getString(elementIndex, "string:ChangeToken")) + } + + async getAllChangeToken(): Promise { + return (await this.entityTable.getStringArray("string:ChangeToken")) + } + async getLevelIndex(elementIndex: number): Promise { return await this.entityTable.getNumber(elementIndex, "index:Vim.Level:Level") } @@ -2415,6 +2431,7 @@ export interface IBimDocument { isMetric?: boolean guid?: string numSaves?: number + identity?: string isLinked?: boolean isDetached?: boolean isWorkshared?: boolean @@ -2464,6 +2481,8 @@ export interface IBimDocumentTable { getAllGuid(): Promise getNumSaves(bimDocumentIndex: number): Promise getAllNumSaves(): Promise + getIdentity(bimDocumentIndex: number): Promise + getAllIdentity(): Promise getIsLinked(bimDocumentIndex: number): Promise getAllIsLinked(): Promise getIsDetached(bimDocumentIndex: number): Promise @@ -2535,6 +2554,7 @@ export class BimDocument implements IBimDocument { isMetric?: boolean guid?: string numSaves?: number + identity?: string isLinked?: boolean isDetached?: boolean isWorkshared?: boolean @@ -2579,6 +2599,7 @@ export class BimDocument implements IBimDocument { table.getIsMetric(index).then(v => result.isMetric = v), table.getGuid(index).then(v => result.guid = v), table.getNumSaves(index).then(v => result.numSaves = v), + table.getIdentity(index).then(v => result.identity = v), table.getIsLinked(index).then(v => result.isLinked = v), table.getIsDetached(index).then(v => result.isDetached = v), table.getIsWorkshared(index).then(v => result.isWorkshared = v), @@ -2647,6 +2668,7 @@ export class BimDocumentTable implements IBimDocumentTable { let isMetric: boolean[] | undefined let guid: string[] | undefined let numSaves: number[] | undefined + let identity: string[] | undefined let isLinked: boolean[] | undefined let isDetached: boolean[] | undefined let isWorkshared: boolean[] | undefined @@ -2682,6 +2704,7 @@ export class BimDocumentTable implements IBimDocumentTable { (async () => { isMetric = (await localTable.getBooleanArray("byte:IsMetric")) })(), (async () => { guid = (await localTable.getStringArray("string:Guid")) })(), (async () => { numSaves = (await localTable.getNumberArray("int:NumSaves")) })(), + (async () => { identity = (await localTable.getStringArray("string:Identity")) })(), (async () => { isLinked = (await localTable.getBooleanArray("byte:IsLinked")) })(), (async () => { isDetached = (await localTable.getBooleanArray("byte:IsDetached")) })(), (async () => { isWorkshared = (await localTable.getBooleanArray("byte:IsWorkshared")) })(), @@ -2723,6 +2746,7 @@ export class BimDocumentTable implements IBimDocumentTable { isMetric: isMetric ? isMetric[i] : undefined, guid: guid ? guid[i] : undefined, numSaves: numSaves ? numSaves[i] : undefined, + identity: identity ? identity[i] : undefined, isLinked: isLinked ? isLinked[i] : undefined, isDetached: isDetached ? isDetached[i] : undefined, isWorkshared: isWorkshared ? isWorkshared[i] : undefined, @@ -2790,6 +2814,14 @@ export class BimDocumentTable implements IBimDocumentTable { return (await this.entityTable.getNumberArray("int:NumSaves")) } + async getIdentity(bimDocumentIndex: number): Promise { + return (await this.entityTable.getString(bimDocumentIndex, "string:Identity")) + } + + async getAllIdentity(): Promise { + return (await this.entityTable.getStringArray("string:Identity")) + } + async getIsLinked(bimDocumentIndex: number): Promise { return (await this.entityTable.getBoolean(bimDocumentIndex, "byte:IsLinked")) }