diff --git a/CHANGELOG.md b/CHANGELOG.md index c613092..cbe28d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +### Added +- Optional preview projects for reading GLB and OBJ, writing GLB, measuring geometry, checking triangle surface intersections, comparing revisions, querying grids and exporting BCF. + ### Changed - `docs/keys.md`: the namespace `nwc:` is registered for `NwcIO.Scene`; its formats are fixed from the first release of the package, 0.12.0. The `nwc` source format names `NwcIO.Scene` as its producer. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de887b3..c71b892 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,6 +49,10 @@ dotnet build -p:RestoreAdditionalProjectSources= Do not commit a `nuget.config` that points to a local feed. +`src/IOScene.Formats` and `src/IOCoord` are optional preview projects that consume the public IOScene 0.1 API. +Their tests are in `tests/IOScene.Tools.Tests`. Packing the solution creates local preview packages. +Core release tags publish the IOScene package. The optional previews have their own release setup pending. + ## Changing the contract The rules are in section 5 of [docs/contract.md](docs/contract.md). In short: diff --git a/Directory.Packages.props b/Directory.Packages.props index 53f2a59..61ad90c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,6 +3,7 @@ true + diff --git a/IOScene.slnx b/IOScene.slnx index e586b00..6e5f174 100644 --- a/IOScene.slnx +++ b/IOScene.slnx @@ -1,4 +1,7 @@ + + + diff --git a/README.md b/README.md index 3f0b364..c5657b9 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ fills the same lists directly: `Models`, `Geometries`, `Elements`, `Instances`, - [docs/contract.md][contract]: purpose and invariants, every type, the decisions behind them, what is left out, how the contract changes, the file format, the validation codes and the unit grammar. - [docs/keys.md][keys]: the registry of property key namespaces and `SourceFormat` values. +- [Optional tools](docs/tools.md) describes format conversion and coordination built on IOScene. - [CHANGELOG.md][changelog], [CONTRIBUTING.md][contributing] and [SECURITY.md][security]. ## License diff --git a/docs/tools.md b/docs/tools.md new file mode 100644 index 0000000..65e61ab --- /dev/null +++ b/docs/tools.md @@ -0,0 +1,70 @@ +# Optional IOScene tools + +`IOScene.Formats` and `IOCoord` consume the public IOScene 0.1 API. They ship separately from the scene contract +and do not depend on a source-format engine. Both are available as local preview packages from this solution. + +## GLB and OBJ + +```csharp +using IOScene; +using IOScene.Formats; + +var scene = SceneJson.Load("model.scene.json"); +GlbSceneWriter.Save(scene, "model.glb"); +``` + +`GlbSceneReader.Load` reads embedded float32 positions and normals, unsigned indices and base material colours. +It flattens the node placements into one model and imports triangle, line and point primitives. Files declaring +required glTF extensions are rejected. The OBJ reader `ObjSceneReader.Load` groups faces by object and assumes +metres with Z up. + +The writer emits [glTF 2.0 binary](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) with the element tree, +indexed and non-indexed triangles, lines and points, shared mesh buffers, and placements with rotation, translation, +scale or reflection. The scene root rotates the metre-based geometry from Z up to glTF Y up. Materials carry +linear base colours, opacity and PBR factors. PNG and JPEG textures are embedded with their UV repeat scales. + +The output contains geometry, transforms, appearance, element names, source ids and IFC GlobalIds. +The IOScene file is the source for property sets, schedules, saved viewpoints and clash results. The writer rejects +sheared placements, textures without UVs and coordinates outside the float32 range. It omits normals when a geometry +carries a degenerate normal so readers can generate their own. + +## Measurements + +```csharp +using IOCoord; +using IOScene; + +var scene = SceneJson.Load("model.scene.json"); +var measurement = SceneMeasure.PointToElement(scene, elementId: 42, new Vector3d(1, 2, 3)); +``` + +`SceneMeasure` measures distances and path lengths in metres, angles in degrees, and the closest point on the +triangles, lines and points placed for an element. An element without geometry returns null. Element ids are local +to a scene. + +## Clash checks, revision comparison, grids and BCF + +`SceneClash.FindSurfaceIntersections` tests the placed triangle surfaces of two element selections. Its bounding +box hierarchy narrows the triangle pairs, and a surface check finds a contact point for each intersecting element +pair. It returns a `SceneClashTest` for export or review, with a contact tolerance of one nanometre. Solid +containment, penetration depth and clearance require different queries. + +`SceneDiff.Compare` matches elements by model key and source id. It compares names and types, ordered property sets, +and ordered vertices and indices in scene coordinates. It reports elements without an identity separately and refuses +duplicate persistent ids. The comparison uses exact geometry values. + +`SceneGrid.NearestLine` and `SceneGrid.NearestIntersection` query axes in the XY plane in metres. These methods use +the coordinates stored in the scene. + +`BcfClashWriter.Write` writes existing `SceneClashTest` results as [BCF 2.1](https://github.com/buildingSMART/BCF-XML/blob/release_2_1/Documentation/README.md) +topics. The caller supplies the author and creation timestamp. Components use the scene's IFC GlobalIds. A viewpoint +with components carries selection and visibility. Camera positions and snapshots are outside this initial exporter. + +## Preview packages + +```sh +dotnet pack IOScene.slnx -c Release -o ./artifacts +``` + +This builds the core and both optional preview packages for local testing. Existing RvtIO, NwcIO and viewer commands +continue to use their current implementations while replacement coverage is developed and verified. diff --git a/src/IOCoord/BcfClashWriter.cs b/src/IOCoord/BcfClashWriter.cs new file mode 100644 index 0000000..9b9fffc --- /dev/null +++ b/src/IOCoord/BcfClashWriter.cs @@ -0,0 +1,85 @@ +using System.IO.Compression; +using System.Xml; +using System.Xml.Linq; +using IOScene; + +namespace IOCoord; + +/// Writes IOScene clash results as buildingSMART BCF 2.1 topics. +public static class BcfClashWriter +{ + /// Writes a BCFZIP archive with one topic per clash. The output stream remains open. + /// Scene containing the results and the corresponding IFC GlobalIds. + /// Writable stream. + /// BCF creation author. + /// Creation timestamp for the exported topics. + public static void Write(SceneDocument scene, Stream output, string author, DateTimeOffset createdAt) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentNullException.ThrowIfNull(output); + ArgumentException.ThrowIfNullOrWhiteSpace(author); + XmlConvert.VerifyXmlChars(author); + if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } error) + throw new InvalidDataException($"Invalid scene ({error.Code}): {error.Message}"); + + var elements = scene.Elements.ToDictionary(element => element.Id); + using var zip = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true); + WriteXml(zip, "bcf.version", new XElement("Version", new XAttribute("VersionId", "2.1"))); + foreach (var test in scene.ClashTests) + { + foreach (var clash in test.Clashes) + { + string topicId = Guid.NewGuid().ToString("D"); + string folder = topicId + "/"; + zip.CreateEntry(folder, CompressionLevel.NoCompression); + + SceneElement? first = clash.Element1Id is long firstId ? elements[firstId] : null; + SceneElement? second = clash.Element2Id is long secondId ? elements[secondId] : null; + var topic = new XElement("Topic", + new XAttribute("Guid", topicId), + new XAttribute("TopicType", "Clash"), + new XAttribute("TopicStatus", clash.Status.ToString()), + new XElement("Title", string.IsNullOrWhiteSpace(clash.Name) ? test.Name : clash.Name), + new XElement("CreationDate", XmlConvert.ToString(createdAt.UtcDateTime, XmlDateTimeSerializationMode.Utc)), + new XElement("CreationAuthor", author), + new XElement("Description", Describe(test, clash, first, second))); + var markup = new XElement("Markup", topic); + + var ids = new[] { first?.IfcGuid, second?.IfcGuid }.Where(IsIfcGuid).Distinct(StringComparer.Ordinal).ToArray(); + if (ids.Length != 0) + { + string viewpointId = Guid.NewGuid().ToString("D"); + markup.Add(new XElement("Viewpoints", new XAttribute("Guid", viewpointId), + new XElement("Viewpoint", "viewpoint.bcfv"))); + WriteXml(zip, folder + "viewpoint.bcfv", new XElement("VisualizationInfo", + new XAttribute("Guid", viewpointId), + new XElement("Components", + new XElement("Selection", ids.Select(id => new XElement("Component", new XAttribute("IfcGuid", id!)))), + new XElement("Visibility", new XAttribute("DefaultVisibility", true))))); + } + WriteXml(zip, folder + "markup.bcf", markup); + } + } + } + + private static string Describe(SceneClashTest test, SceneClashResult clash, SceneElement? first, SceneElement? second) + { + string a = string.IsNullOrEmpty(clash.Element1Name) ? first?.Name ?? string.Empty : clash.Element1Name; + string b = string.IsNullOrEmpty(clash.Element2Name) ? second?.Name ?? string.Empty : clash.Element2Name; + string location = FormattableString.Invariant( + $"{test.Name}\n{a} / {b}\nPoint (m): {clash.Point.X:R}, {clash.Point.Y:R}, {clash.Point.Z:R}"); + return clash.Distance is double distance + ? location + FormattableString.Invariant($"\nDistance (m): {distance:R}") + : location; + } + + private static bool IsIfcGuid(string? value) => + value is { Length: 22 } && value[0] is >= '0' and <= '3' + && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '$'); + + private static void WriteXml(ZipArchive zip, string path, XElement root) + { + using var stream = zip.CreateEntry(path).Open(); + root.Save(stream, SaveOptions.DisableFormatting); + } +} diff --git a/src/IOCoord/IOCoord.csproj b/src/IOCoord/IOCoord.csproj new file mode 100644 index 0000000..8aac93f --- /dev/null +++ b/src/IOCoord/IOCoord.csproj @@ -0,0 +1,18 @@ + + + + 0.1.0-preview.1 + IOCoord + Measurements, triangle clash checks, revision comparison, grid queries and BCF export for IOScene models. + true + + $(NoWarn);NU5104 + + + + + + + + + diff --git a/src/IOCoord/SceneClash.cs b/src/IOCoord/SceneClash.cs new file mode 100644 index 0000000..c1aef88 --- /dev/null +++ b/src/IOCoord/SceneClash.cs @@ -0,0 +1,205 @@ +using IOScene; + +namespace IOCoord; + +/// Finds surface intersections between the triangle meshes of scene elements. +public static class SceneClash +{ + // The same rounding tolerance is used for the bounds, plane distances and edge distances. + private const double Tolerance = 1e-9; + private const int LeafSize = 8; + + /// Finds one contact point per intersecting pair from the two supplied element selections. + /// The scene whose placed triangles are tested. + /// Ids of elements in the first selection. + /// Ids of elements in the second selection. + /// Cancellation token for the query. + /// A clash test with the intersections. The input scene is unchanged. + /// Tests triangle surfaces in metres. A contact tolerance of one nanometre covers rounding. + /// Penetration depth, clearance and solids enclosed without surface contact are outside this query. + public static SceneClashTest FindSurfaceIntersections(SceneDocument scene, IEnumerable first, IEnumerable second, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + cancellationToken.ThrowIfCancellationRequested(); + if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } error) + throw new InvalidDataException($"Invalid scene ({error.Code}): {error.Message}"); + + var left = first.ToHashSet(); + var right = second.ToHashSet(); + var elements = scene.Elements.ToDictionary(element => element.Id); + if (left.Concat(right).Any(id => !elements.ContainsKey(id))) + throw new ArgumentException("The selections must contain ids of elements in the scene."); + + var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); + var leftTriangles = new List(); + var rightTriangles = new List(); + foreach (var instance in scene.Instances) + { + bool inLeft = left.Contains(instance.ElementId), inRight = right.Contains(instance.ElementId); + if (!inLeft && !inRight) continue; + var geometry = geometries[instance.GeometryId]; + if (geometry.Topology != SceneTopology.Triangles) continue; + var transform = instance.Transform ?? Transform3d.Identity; + var indices = geometry.Indices; + bool indexed = indices.Count > 0; + int count = indexed ? indices.Count : geometry.Vertices.Count; + for (int offset = 0; offset < count; offset += 3) + { + cancellationToken.ThrowIfCancellationRequested(); + var a = WorldVertex(offset); + var b = WorldVertex(offset + 1); + var c = WorldVertex(offset + 2); + var faceNormal = Vector3d.Cross(b - a, c - a); + double length = faceNormal.Length; + if (!double.IsFinite(length)) throw new InvalidDataException("A triangle normal is outside the finite range."); + if (length == 0) continue; + var normal = faceNormal / length; + var bounds = BoundingBox3d.Empty.Encapsulate(a).Encapsulate(b).Encapsulate(c); + var triangle = new Triangle(instance.ElementId, a, b, c, normal, bounds); + if (inLeft) leftTriangles.Add(triangle); + if (inRight) rightTriangles.Add(triangle); + } + + Vector3d WorldVertex(int index) + { + var point = transform.Apply(geometry.Vertices[indexed ? indices[index] : index]); + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z)) + throw new InvalidDataException("The transformed coordinates are outside the finite range."); + return point; + } + } + + var test = new SceneClashTest { Name = "Surface intersections" }; + if (leftTriangles.Count == 0 || rightTriangles.Count == 0) return test; + Triangle[] aTriangles = leftTriangles.ToArray(), bTriangles = rightTriangles.ToArray(); + var aRoot = Build(aTriangles, 0, aTriangles.Length, cancellationToken); + var bRoot = Build(bTriangles, 0, bTriangles.Length, cancellationToken); + var contacts = new Dictionary<(long First, long Second), Vector3d>(); + var pending = new Stack<(Node First, Node Second)>(); + pending.Push((aRoot, bRoot)); + while (pending.TryPop(out var pair)) + { + cancellationToken.ThrowIfCancellationRequested(); + var (a, b) = pair; + if (!Overlaps(a.Bounds, b.Bounds)) continue; + if (a.First is not null && (b.First is null || a.Count >= b.Count)) + { + pending.Push((a.First, b)); + pending.Push((a.Second!, b)); + } + else if (b.First is not null) + { + pending.Push((a, b.First)); + pending.Push((a, b.Second!)); + } + else + { + for (int i = a.Start; i < a.Start + a.Count; i++) + { + var one = aTriangles[i]; + for (int j = b.Start; j < b.Start + b.Count; j++) + { + var two = bTriangles[j]; + if (one.ElementId == two.ElementId || !Overlaps(one.Bounds, two.Bounds)) continue; + var key = (Math.Min(one.ElementId, two.ElementId), Math.Max(one.ElementId, two.ElementId)); + if (!contacts.ContainsKey(key) && Contact(one, two) is { } point) + contacts.Add(key, point); + } + } + } + } + + foreach (var (key, point) in contacts.OrderBy(pair => pair.Key)) + { + string firstName = elements[key.First].Name; + string secondName = elements[key.Second].Name; + test.Clashes.Add(new SceneClashResult + { + Id = FormattableString.Invariant($"{key.First}:{key.Second}"), + Name = $"{firstName} / {secondName}", + Element1Id = key.First, + Element2Id = key.Second, + Element1Name = firstName, + Element2Name = secondName, + Point = point, + Status = SceneClashStatus.New, + }); + } + return test; + } + + private static Node Build(Triangle[] triangles, int start, int count, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + var bounds = BoundingBox3d.Empty; + for (int i = start; i < start + count; i++) bounds = bounds.Encapsulate(triangles[i].Bounds); + if (count <= LeafSize) return new(bounds, start, count); + Vector3d extent = bounds.Size; + var comparer = extent.X >= extent.Y && extent.X >= extent.Z ? ByX : extent.Y >= extent.Z ? ByY : ByZ; + Array.Sort(triangles, start, count, comparer); + int half = count / 2; + var left = Build(triangles, start, half, token); + var right = Build(triangles, start + half, count - half, token); + return new(bounds, start, count, left, right); + } + + private static bool Overlaps(BoundingBox3d a, BoundingBox3d b) => + a.Min.X <= b.Max.X + Tolerance && b.Min.X <= a.Max.X + Tolerance + && a.Min.Y <= b.Max.Y + Tolerance && b.Min.Y <= a.Max.Y + Tolerance + && a.Min.Z <= b.Max.Z + Tolerance && b.Min.Z <= a.Max.Z + Tolerance; + + private static Vector3d? Contact(Triangle a, Triangle b) => + EdgeContact(a.A, a.B, b) ?? EdgeContact(a.B, a.C, b) ?? EdgeContact(a.C, a.A, b) + ?? EdgeContact(b.A, b.B, a) ?? EdgeContact(b.B, b.C, a) ?? EdgeContact(b.C, b.A, a); + + private static Vector3d? EdgeContact(Vector3d from, Vector3d to, Triangle triangle) + { + double start = Vector3d.Dot(from - triangle.A, triangle.Normal); + double end = Vector3d.Dot(to - triangle.A, triangle.Normal); + bool startOnPlane = Math.Abs(start) <= Tolerance, endOnPlane = Math.Abs(end) <= Tolerance; + if (startOnPlane && Inside(from, triangle)) return from; + if (endOnPlane && Inside(to, triangle)) return to; + if (startOnPlane && endOnPlane) + { + return CoplanarCrossing(from, to, triangle.A, triangle.B, triangle.Normal) + ?? CoplanarCrossing(from, to, triangle.B, triangle.C, triangle.Normal) + ?? CoplanarCrossing(from, to, triangle.C, triangle.A, triangle.Normal); + } + if ((start < 0) == (end < 0)) return null; + Vector3d point = from + (to - from) * (start / (start - end)); + return Inside(point, triangle) ? point : null; + } + + private static bool Inside(Vector3d point, Triangle triangle) + { + return HasLeftSide(triangle.A, triangle.B) && HasLeftSide(triangle.B, triangle.C) && HasLeftSide(triangle.C, triangle.A); + + bool HasLeftSide(Vector3d from, Vector3d to) + { + var edge = to - from; + return Vector3d.Dot(Vector3d.Cross(edge, point - from), triangle.Normal) >= -Tolerance * edge.Length; + } + } + + private static Vector3d? CoplanarCrossing(Vector3d a, Vector3d b, Vector3d c, Vector3d d, Vector3d normal) + { + var u = b - a; + var v = d - c; + var delta = c - a; + double denominator = Vector3d.Dot(Vector3d.Cross(u, v), normal); + if (denominator == 0) return null; + double t = Vector3d.Dot(Vector3d.Cross(delta, v), normal) / denominator; + double s = Vector3d.Dot(Vector3d.Cross(delta, u), normal) / denominator; + return t is >= 0 and <= 1 && s is >= 0 and <= 1 ? a + u * t : null; + } + + private static readonly Comparer ByX = Comparer.Create((a, b) => a.Bounds.Center.X.CompareTo(b.Bounds.Center.X)); + private static readonly Comparer ByY = Comparer.Create((a, b) => a.Bounds.Center.Y.CompareTo(b.Bounds.Center.Y)); + private static readonly Comparer ByZ = Comparer.Create((a, b) => a.Bounds.Center.Z.CompareTo(b.Bounds.Center.Z)); + + private readonly record struct Triangle(long ElementId, Vector3d A, Vector3d B, Vector3d C, Vector3d Normal, BoundingBox3d Bounds); + private sealed record Node(BoundingBox3d Bounds, int Start, int Count, Node? First = null, Node? Second = null); +} diff --git a/src/IOCoord/SceneDiff.cs b/src/IOCoord/SceneDiff.cs new file mode 100644 index 0000000..382f024 --- /dev/null +++ b/src/IOCoord/SceneDiff.cs @@ -0,0 +1,127 @@ +using IOScene; + +namespace IOCoord; + +/// The outcome of comparing an element across two scenes. +public enum SceneChangeKind +{ + /// The element occurs in the revision only. + Added, + + /// The element occurs in the baseline only. + Removed, + + /// The element occurs in both scenes and has changed. + Modified, +} + +/// A comparison finding keyed by the element's persistent source identity. +/// Stable key of the model that owns the element. +/// Id of the element in that source. +/// Kind of finding. +/// Name, category, type name, kind or IFC GlobalId changed. +/// Property sets or properties changed. +/// Ordered world vertices, indices or topology of the placements changed. +public sealed record SceneElementChange(string ModelKey, string SourceId, SceneChangeKind Kind, + bool MetadataChanged = false, bool PropertiesChanged = false, bool GeometryChanged = false); + +/// The findings and counts of elements without a persistent identity. +/// Added, removed and modified elements. +/// Elements without a source id in the baseline. +/// Elements without a source id in the revision. +public sealed record SceneComparison(IReadOnlyList Changes, int UnidentifiedBaseline, int UnidentifiedRevision); + +/// Compares revisions of an IOScene using model keys and persistent source ids. +public static class SceneDiff +{ + /// Compares element metadata, displayed properties and placed geometry. + /// Earlier scene. + /// Later scene. + /// A scene is invalid or an element identity is ambiguous. + public static SceneComparison Compare(SceneDocument baseline, SceneDocument revision) + { + ArgumentNullException.ThrowIfNull(baseline); + ArgumentNullException.ThrowIfNull(revision); + var before = new SceneIndex(baseline); + var after = new SceneIndex(revision); + var changes = new List(); + foreach (var (key, element) in before.Elements) + { + if (!after.Elements.TryGetValue(key, out var current)) + { + changes.Add(new(key.ModelKey, key.SourceId, SceneChangeKind.Removed)); + continue; + } + + bool metadata = element.Name != current.Name || element.Category != current.Category || element.TypeName != current.TypeName + || element.Kind != current.Kind || element.IfcGuid != current.IfcGuid; + bool properties = !SameProperties(before, element, after, current); + bool geometry = !SameGeometry(before, element, after, current); + if (metadata || properties || geometry) + changes.Add(new(key.ModelKey, key.SourceId, SceneChangeKind.Modified, metadata, properties, geometry)); + } + foreach (var key in after.Elements.Keys) + if (!before.Elements.ContainsKey(key)) + changes.Add(new(key.ModelKey, key.SourceId, SceneChangeKind.Added)); + return new(changes.AsReadOnly(), baseline.Elements.Count - before.Elements.Count, revision.Elements.Count - after.Elements.Count); + } + + private static bool SameProperties(SceneIndex first, SceneElement a, SceneIndex second, SceneElement b) + { + if (a.PropertySetIds.Count != b.PropertySetIds.Count) return false; + for (int i = 0; i < a.PropertySetIds.Count; i++) + { + var one = first.PropertySets[a.PropertySetIds[i]]; + var two = second.PropertySets[b.PropertySetIds[i]]; + if (one.Name != two.Name || one.Key != two.Key) return false; + if (!one.Properties.Select(Property).SequenceEqual(two.Properties.Select(Property))) return false; + } + return true; + + static (string Name, string? Key, SceneValue Value) Property(SceneProperty p) => (p.Name, p.Key, p.Value); + } + + private static bool SameGeometry(SceneIndex first, SceneElement a, SceneIndex second, SceneElement b) + { + var before = first.Instances[a.Id]; + var after = second.Instances[b.Id]; + using var left = before.GetEnumerator(); + using var right = after.GetEnumerator(); + while (left.MoveNext()) + { + if (!right.MoveNext()) return false; + var i = left.Current; + var j = right.Current; + var one = first.Geometries[i.GeometryId]; + var two = second.Geometries[j.GeometryId]; + if (one.Topology != two.Topology || !one.Indices.SequenceEqual(two.Indices)) return false; + var leftTransform = i.Transform ?? Transform3d.Identity; + var rightTransform = j.Transform ?? Transform3d.Identity; + if (!one.Vertices.Select(leftTransform.Apply).SequenceEqual(two.Vertices.Select(rightTransform.Apply))) return false; + } + return !right.MoveNext(); + } + + private sealed class SceneIndex + { + public readonly Dictionary<(string ModelKey, string SourceId), SceneElement> Elements = new(); + public readonly Dictionary PropertySets; + public readonly Dictionary Geometries; + public readonly ILookup Instances; + + public SceneIndex(SceneDocument scene) + { + if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } error) + throw new InvalidDataException($"Invalid scene ({error.Code}): {error.Message}"); + var modelKeys = scene.Models.ToDictionary(model => model.Id, model => model.Key); + foreach (var element in scene.Elements) + { + if (!string.IsNullOrEmpty(element.SourceId) && !Elements.TryAdd((modelKeys[element.ModelId], element.SourceId), element)) + throw new InvalidDataException("Two elements in one model share a source id."); + } + PropertySets = scene.PropertySets.ToDictionary(set => set.Id); + Geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); + Instances = scene.Instances.ToLookup(instance => instance.ElementId); + } + } +} diff --git a/src/IOCoord/SceneGrid.cs b/src/IOCoord/SceneGrid.cs new file mode 100644 index 0000000..5a1385e --- /dev/null +++ b/src/IOCoord/SceneGrid.cs @@ -0,0 +1,90 @@ +using IOScene; + +namespace IOCoord; + +/// A grid axis and the distance to it in the XY plane. +/// The nearest axis. +/// Distance in metres. +public readonly record struct GridLineMatch(SceneGridLine Line, double Distance); + +/// A unique intersection of two axes in the XY plane. +/// First axis. +/// Second axis. +/// The intersection in scene XY coordinates. +/// Distance from the query in metres. +public readonly record struct GridIntersection(SceneGridLine First, SceneGridLine Second, Vector2d Point, double Distance); + +/// Queries the projected XY axes of a scene grid. +public static class SceneGrid +{ + /// Finds the nearest axis in the XY plane, or null when the grid has no axes of nonzero length. + /// The scene grid to search. + /// Query point in scene metres. + /// Use the stored segment lengths instead of extending axes. + public static GridLineMatch? NearestLine(SceneGridSystem grid, Vector2d point, bool segmentOnly = false) + { + ArgumentNullException.ThrowIfNull(grid); + RequireFinite(point); + GridLineMatch? best = null; + foreach (var line in grid.Lines) + { + var start = XY(line.Start); + var direction = XY(line.End - line.Start); + double lengthSquared = Dot(direction, direction); + if (lengthSquared == 0) continue; + double t = Dot(new(point.X - start.X, point.Y - start.Y), direction) / lengthSquared; + if (segmentOnly) t = Math.Clamp(t, 0, 1); + double distance = Distance(point, new(start.X + t * direction.X, start.Y + t * direction.Y)); + if (best is null || distance < best.Value.Distance) best = new(line, distance); + } + return best; + } + + /// Finds the nearest crossing of extended axes in the XY plane, or null when there is no crossing. + /// The scene grid to search. + /// Query point in scene metres. + public static GridIntersection? NearestIntersection(SceneGridSystem grid, Vector2d point) + { + ArgumentNullException.ThrowIfNull(grid); + RequireFinite(point); + GridIntersection? best = null; + for (int i = 0; i < grid.Lines.Count; i++) + { + var first = grid.Lines[i]; + var a = XY(first.Start); + var u = XY(first.End - first.Start); + for (int j = i + 1; j < grid.Lines.Count; j++) + { + var second = grid.Lines[j]; + var b = XY(second.Start); + var v = XY(second.End - second.Start); + double denominator = Cross(u, v); + if (denominator == 0) continue; + double t = Cross(new(b.X - a.X, b.Y - a.Y), v) / denominator; + var intersection = new Vector2d(a.X + t * u.X, a.Y + t * u.Y); + double distance = Distance(point, intersection); + if (best is null || distance < best.Value.Distance) best = new(first, second, intersection, distance); + } + } + return best; + } + + private static Vector2d XY(Vector3d point) + { + var xy = new Vector2d(point.X, point.Y); + RequireFinite(xy); + return xy; + } + + private static void RequireFinite(Vector2d point) + { + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y)) + throw new ArgumentException("Grid coordinates must be finite."); + } + + private static double Distance(Vector2d a, Vector2d b) => SceneMeasure.Distance(new(a.X, a.Y, 0), new(b.X, b.Y, 0)); + + private static double Dot(Vector2d a, Vector2d b) => a.X * b.X + a.Y * b.Y; + + private static double Cross(Vector2d a, Vector2d b) => a.X * b.Y - a.Y * b.X; +} diff --git a/src/IOCoord/SceneMeasure.cs b/src/IOCoord/SceneMeasure.cs new file mode 100644 index 0000000..414fefb --- /dev/null +++ b/src/IOCoord/SceneMeasure.cs @@ -0,0 +1,170 @@ +using IOScene; + +namespace IOCoord; + +/// Result of measuring from a point to the placed geometry of one element, in metres. +/// Closest point on the element in scene coordinates. +/// Distance to that point in metres. +public readonly record struct PointMeasurement(Vector3d ClosestPoint, double Distance); + +/// Measurements on the metre-based geometry of an IOScene document. +public static class SceneMeasure +{ + /// Returns the straight-line distance between two points in metres. + /// First point. + /// Second point. + public static double Distance(Vector3d a, Vector3d b) + { + RequireFinite(a, nameof(a)); + RequireFinite(b, nameof(b)); + return Length(a - b); + } + + /// Returns the sum of the lengths of consecutive segments in metres. + /// The points of an open path in order. + public static double PathLength(IEnumerable points) + { + ArgumentNullException.ThrowIfNull(points); + using var iterator = points.GetEnumerator(); + if (!iterator.MoveNext()) return 0; + Vector3d previous = iterator.Current; + RequireFinite(previous, nameof(points)); + double length = 0; + while (iterator.MoveNext()) + { + var point = iterator.Current; + RequireFinite(point, nameof(points)); + length += Length(point - previous); + previous = point; + } + if (!double.IsFinite(length)) throw new InvalidDataException("The path length is outside the finite range."); + return length; + } + + /// Returns the angle at a vertex in degrees, or zero for a segment of length zero. + /// First endpoint. + /// Common endpoint. + /// Second endpoint. + public static double AngleDegrees(Vector3d a, Vector3d vertex, Vector3d b) + { + RequireFinite(a, nameof(a)); + RequireFinite(vertex, nameof(vertex)); + RequireFinite(b, nameof(b)); + var first = a - vertex; + var second = b - vertex; + double firstLength = Length(first), secondLength = Length(second); + if (firstLength == 0 || secondLength == 0) return 0; + var x = first / firstLength; + var y = second / secondLength; + return Math.Atan2(Length(Vector3d.Cross(x, y)), Vector3d.Dot(x, y)) * (180 / Math.PI); + } + + /// Measures to the nearest triangle, line segment or point placed for an element. + /// The scene to measure. + /// The scene-local id of the element. + /// Query point in scene coordinates. + /// The closest point and distance, or null when the element has no measurable geometry. + /// The scene has no element with the supplied id. + /// The scene fails structural validation or the transformed coordinates overflow. + public static PointMeasurement? PointToElement(SceneDocument scene, long elementId, Vector3d point) + { + ArgumentNullException.ThrowIfNull(scene); + RequireFinite(point, nameof(point)); + if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } error) + throw new InvalidDataException($"Invalid scene ({error.Code}): {error.Message}"); + if (!scene.Elements.Any(element => element.Id == elementId)) + throw new ArgumentOutOfRangeException(nameof(elementId), elementId, "The scene has no such element."); + + var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); + PointMeasurement? best = null; + foreach (var instance in scene.Instances) + { + if (instance.ElementId != elementId) continue; + + var geometry = geometries[instance.GeometryId]; + var transform = instance.Transform ?? Transform3d.Identity; + bool indexed = geometry.Indices.Count > 0; + int count = indexed ? geometry.Indices.Count : geometry.Vertices.Count; + int step = geometry.Topology switch + { + SceneTopology.Points => 1, + SceneTopology.Lines => 2, + SceneTopology.Triangles => 3, + _ => throw new InvalidDataException($"Geometry {geometry.Id} has an unsupported topology."), + }; + for (int offset = 0; offset < count; offset += step) + { + Vector3d a = WorldVertex(offset); + Vector3d nearest = step switch + { + 1 => a, + 2 => ClosestOnSegment(point, a, WorldVertex(offset + 1)), + _ => ClosestOnTriangle(point, a, WorldVertex(offset + 1), WorldVertex(offset + 2)), + }; + double distance = Length(point - nearest); + if (best is null || distance < best.Value.Distance) best = new(nearest, distance); + } + + Vector3d WorldVertex(int index) + { + Vector3d world = transform.Apply(geometry.Vertices[indexed ? geometry.Indices[index] : index]); + if (!IsFinite(world)) throw new InvalidDataException("The transformed coordinates are outside the finite range."); + return world; + } + } + return best; + } + + private static Vector3d ClosestOnSegment(Vector3d point, Vector3d a, Vector3d b) + { + var vector = b - a; + double length = Length(vector); + if (length == 0) return a; + var unit = vector / length; + double along = Math.Clamp(Vector3d.Dot(point - a, unit), 0, length); + return a + unit * along; + } + + private static Vector3d ClosestOnTriangle(Vector3d point, Vector3d a, Vector3d b, Vector3d c) + { + var ab = b - a; + var ac = c - a; + double scale = Math.Max(Length(ab), Length(ac)); + if (scale == 0) return a; + + var normal = Vector3d.Cross(ab / scale, ac / scale); + double normalLength = Length(normal); + if (normalLength > 0) + { + normal /= normalLength; + var projection = point - normal * Vector3d.Dot(point - a, normal); + if (OnInside(a, b) && OnInside(b, c) && OnInside(c, a)) return projection; + + bool OnInside(Vector3d start, Vector3d end) => + Vector3d.Dot(Vector3d.Cross((end - start) / scale, (projection - start) / scale), normal) >= 0; + } + + var closest = ClosestOnSegment(point, a, b); + var next = ClosestOnSegment(point, b, c); + if (Length(next - point) < Length(closest - point)) closest = next; + next = ClosestOnSegment(point, c, a); + return Length(next - point) < Length(closest - point) ? next : closest; + } + + private static double Length(Vector3d vector) + { + double scale = Math.Max(Math.Abs(vector.X), Math.Max(Math.Abs(vector.Y), Math.Abs(vector.Z))); + if (scale == 0) return 0; + double length = (vector / scale).Length * scale; + if (!double.IsFinite(length)) throw new InvalidDataException("The distance is outside the finite range."); + return length; + } + + private static void RequireFinite(Vector3d value, string parameter) + { + if (!IsFinite(value)) throw new ArgumentException("Point coordinates must be finite.", parameter); + } + + private static bool IsFinite(Vector3d value) => + double.IsFinite(value.X) && double.IsFinite(value.Y) && double.IsFinite(value.Z); +} diff --git a/src/IOScene.Formats/GlbSceneReader.cs b/src/IOScene.Formats/GlbSceneReader.cs new file mode 100644 index 0000000..27a8aba --- /dev/null +++ b/src/IOScene.Formats/GlbSceneReader.cs @@ -0,0 +1,420 @@ +using System.Buffers.Binary; +using System.Text; +using System.Text.Json; + +namespace IOScene.Formats; + +/// +/// Imports standard glTF 2.0 Binary (.glb) files into a scene with one model: one geometry per +/// mesh primitive, one element per node that draws a mesh, and one instance per primitive of that node, with the +/// node's world transform converted from glTF's Y-up to the scene's Z-up. +/// +public static class GlbSceneReader +{ + private const uint GlbMagic = 0x46546C67; // "glTF" + private const uint ChunkJson = 0x4E4F534A; // "JSON" + private const uint ChunkBin = 0x004E4942; // "BIN\0" + + /// Reads a GLB file into an IOScene document. + /// Path to the file. + public static SceneDocument Load(string filePath) + { + ArgumentNullException.ThrowIfNull(filePath); + using var fs = File.OpenRead(filePath); + return Load(fs, Path.GetFileNameWithoutExtension(filePath), Path.GetFileName(filePath), filePath); + } + + /// Reads a GLB from a seekable stream. The stream remains open. + /// Stream positioned at the GLB header. + /// Name of the resulting scene. + public static SceneDocument Load(Stream stream, string documentTitle = "Imported GLB Model") + { + ArgumentNullException.ThrowIfNull(stream); + return Load(stream, documentTitle, "model", null); + } + + private static SceneDocument Load(Stream stream, string documentTitle, string modelKey, string? path) + { + if (!stream.CanSeek) throw new NotSupportedException("GLB input must be seekable."); + long start = stream.Position; + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); + + // Header: 12 bytes + uint magic = reader.ReadUInt32(); + if (magic != GlbMagic) + { + throw new InvalidDataException("Invalid GLB header: magic signature mismatch."); + } + + uint version = reader.ReadUInt32(); + if (version != 2) + { + throw new NotSupportedException($"Unsupported glTF version: {version}. Only glTF 2.0 is supported."); + } + + uint totalLength = reader.ReadUInt32(); + if (totalLength < 20 || totalLength > stream.Length - start) + throw new InvalidDataException("The GLB length is outside the input stream."); + long containerEnd = start + totalLength; + + // Chunk 0: JSON + uint jsonChunkLength = reader.ReadUInt32(); + uint jsonChunkType = reader.ReadUInt32(); + if (jsonChunkType != ChunkJson) + { + throw new InvalidDataException("Expected JSON chunk as first chunk in GLB file."); + } + + byte[] jsonBytes = ReadChunk(jsonChunkLength); + + // Chunk 1: BIN (optional) + byte[]? binBuffer = null; + if (stream.Position < containerEnd) + { + if (containerEnd - stream.Position < 8) + throw new InvalidDataException("The GLB chunk header is truncated."); + uint binChunkLength = reader.ReadUInt32(); + uint binChunkType = reader.ReadUInt32(); + if (binChunkType == ChunkBin) + { + binBuffer = ReadChunk(binChunkLength); + } + } + + byte[] ReadChunk(uint length) + { + if (length > Array.MaxLength || length > containerEnd - stream.Position || length % 4 != 0) + throw new InvalidDataException("The GLB chunk length is outside the container."); + byte[] data = reader.ReadBytes((int)length); + if (data.Length != length) throw new EndOfStreamException("The GLB chunk is truncated."); + return data; + } + + var doc = new SceneDocument { Title = documentTitle }; + doc.Models.Add(new SceneModel { Id = 1, Key = modelKey, Name = documentTitle, Path = path, SourceFormat = "glb" }); + + using var jsonDoc = JsonDocument.Parse(jsonBytes); + var root = jsonDoc.RootElement; + if (root.TryGetProperty("extensionsRequired", out var requiredExtensions) && + requiredExtensions.GetArrayLength() > 0) + { + throw new NotSupportedException($"Required glTF extension is unsupported: {requiredExtensions[0].GetString()}."); + } + + // Parse accessors & bufferViews + if (!root.TryGetProperty("accessors", out var accessorsEl) || + !root.TryGetProperty("bufferViews", out var bufferViewsEl) || + binBuffer is null) + { + return doc; + } + + var bufferViews = bufferViewsEl.EnumerateArray().ToArray(); + var accessors = accessorsEl.EnumerateArray().ToArray(); + + // Parse Materials + var materials = new List(); + if (root.TryGetProperty("materials", out var materialsEl)) + { + int matIdx = 0; + foreach (var matEl in materialsEl.EnumerateArray()) + { + var mat = new SceneMaterial + { + Id = matIdx++, + Name = matEl.TryGetProperty("name", out var mn) ? mn.GetString() ?? "Material" : $"Material {matIdx}" + }; + + if (matEl.TryGetProperty("pbrMetallicRoughness", out var pbr)) + { + if (pbr.TryGetProperty("baseColorFactor", out var bcf) && bcf.GetArrayLength() >= 4) + { + // glTF's factor is linear; a scene colour has sRGB channels and a straight linear alpha. + var arr = bcf.EnumerateArray().ToArray(); + mat.Color = new RgbaColor(Srgb(arr[0].GetDouble()), Srgb(arr[1].GetDouble()), Srgb(arr[2].GetDouble()), Byte(arr[3].GetDouble())); + } + } + materials.Add(mat); + doc.Materials.Add(mat); + } + } + + // Parse meshes lazily: one geometry per (mesh, primitive), one instance per primitive of a node occurrence. + var meshElements = root.TryGetProperty("meshes", out var meshesEl) ? meshesEl.EnumerateArray().ToArray() : []; + var geometryIds = new Dictionary<(int Mesh, int Primitive), int?>(); + int meshCounter = 0; + + // One element per node occurrence: all primitives of its mesh select, hide and list as one object. + void Instantiate(int meshIndex, Transform3d world, string? nodeName) + { + if (meshIndex < 0 || meshIndex >= meshElements.Length) + { + throw new InvalidDataException($"glTF node references missing mesh {meshIndex}."); + } + + var meshEl = meshElements[meshIndex]; + string meshName = meshEl.TryGetProperty("name", out var mn) ? mn.GetString() ?? $"Mesh {meshCounter + 1}" : $"Mesh {meshCounter + 1}"; + if (!meshEl.TryGetProperty("primitives", out var primsEl)) return; + + SceneElement? element = null; + int primIndex = -1; + foreach (var prim in primsEl.EnumerateArray()) + { + primIndex++; + if (!prim.TryGetProperty("attributes", out var attrs) || + !attrs.TryGetProperty("POSITION", out var posAccIdx)) + { + continue; + } + + if (!geometryIds.TryGetValue((meshIndex, primIndex), out int? geometryId)) + { + var positions = ReadVec3Accessor(posAccIdx.GetInt32(), accessors, bufferViews, binBuffer); + if (positions.Count == 0) + { + geometryId = null; + } + else + { + List indices; + if (prim.TryGetProperty("indices", out var indAccIdx)) + { + indices = ReadIndicesAccessor(indAccIdx.GetInt32(), accessors, bufferViews, binBuffer); + } + else + { + indices = new List(positions.Count); + for (int i = 0; i < positions.Count; i++) indices.Add(i); + } + + List? normals = null; + if (attrs.TryGetProperty("NORMAL", out var normAccIdx)) + { + normals = ReadVec3Accessor(normAccIdx.GetInt32(), accessors, bufferViews, binBuffer); + } + + int mode = prim.TryGetProperty("mode", out var modeProperty) ? modeProperty.GetInt32() : 4; + SceneTopology topology = mode switch + { + 0 => SceneTopology.Points, + 1 => SceneTopology.Lines, + 4 => SceneTopology.Triangles, + _ => throw new NotSupportedException($"GLB primitive mode {mode} is unsupported."), + }; + int groupSize = mode == 4 ? 3 : mode == 1 ? 2 : 1; + if (indices.Count % groupSize != 0 || indices.Any(index => (uint)index >= positions.Count)) + throw new InvalidDataException("GLB primitive indices are invalid."); + if (normals is not null && normals.Count != positions.Count) + throw new InvalidDataException("GLB normal and position counts differ."); + geometryId = doc.Geometries.Count; + doc.Geometries.Add(new SceneGeometry + { + Id = geometryId.Value, + Topology = topology, + Vertices = positions, + Indices = indices, + Normals = normals + }); + } + + geometryIds[(meshIndex, primIndex)] = geometryId; + } + + if (geometryId is null) continue; + + int? matId = null; + if (prim.TryGetProperty("material", out var mProp)) + { + int mid = mProp.GetInt32(); + if (mid >= 0 && mid < materials.Count) matId = mid; + } + + if (element is null) + { + element = new SceneElement { Id = doc.Elements.Count + 1, ModelId = 1, Name = string.IsNullOrEmpty(nodeName) ? meshName : nodeName, Category = "GLB" }; + doc.Elements.Add(element); + } + + ++meshCounter; + doc.Instances.Add(new SceneInstance + { + ElementId = element.Id, + GeometryId = geometryId.Value, + Transform = world.Then(YupToZup), + MaterialId = matId, + Color = matId is null ? new RgbaColor(200, 200, 200) : null, + Name = meshName, + }); + } + } + + if (root.TryGetProperty("scenes", out var scenesEl) && root.TryGetProperty("nodes", out var nodesEl)) + { + var nodes = nodesEl.EnumerateArray().ToArray(); + var scenes = scenesEl.EnumerateArray().ToArray(); + int sceneIndex = root.TryGetProperty("scene", out var sceneProp) ? sceneProp.GetInt32() : 0; + if (sceneIndex >= 0 && sceneIndex < scenes.Length && + scenes[sceneIndex].TryGetProperty("nodes", out var rootNodes)) + { + // glTF node hierarchy is a strict tree: reaching a node twice (shared child, repeated root, cycle) is invalid. + var visited = new HashSet(); + var stack = new Stack<(int Node, Transform3d ParentWorld)>(); + foreach (var rootNode in rootNodes.EnumerateArray().Reverse()) stack.Push((rootNode.GetInt32(), Transform3d.Identity)); + + while (stack.Count > 0) + { + var (nodeIndex, parentWorld) = stack.Pop(); + if (nodeIndex < 0 || nodeIndex >= nodes.Length) + { + throw new InvalidDataException($"glTF references missing node {nodeIndex}."); + } + + if (!visited.Add(nodeIndex)) + { + throw new InvalidDataException($"glTF node {nodeIndex} is referenced more than once; the node hierarchy must be a tree."); + } + + var node = nodes[nodeIndex]; + var world = ReadNodeTransform(node).Then(parentWorld); + if (node.TryGetProperty("mesh", out var meshProp)) + { + Instantiate(meshProp.GetInt32(), world, node.TryGetProperty("name", out var nodeName) ? nodeName.GetString() : null); + } + + if (node.TryGetProperty("children", out var children)) + { + foreach (var child in children.EnumerateArray().Reverse()) stack.Push((child.GetInt32(), world)); + } + } + } + } + else + { + // No scene graph: import every mesh once without a node transform. + for (int i = 0; i < meshElements.Length; i++) Instantiate(i, Transform3d.Identity, null); + } + + return doc; + } + + // The sRGB byte of a linear channel: the standard sRGB transfer function, then the nearest byte. + private static byte Srgb(double linear) + { + double c = Math.Clamp(linear, 0, 1); + return Byte(c <= 0.0031308 ? 12.92 * c : 1.055 * Math.Pow(c, 1 / 2.4) - 0.055); + } + + private static byte Byte(double value) => (byte)Math.Round(Math.Clamp(value, 0, 1) * 255, MidpointRounding.AwayFromZero); + + // glTF is Y-up; the viewer model is Z-up: (x, y, z) becomes (x, -z, y). + private static readonly Transform3d YupToZup = new(new Vector3d(1, 0, 0), new Vector3d(0, 0, 1), new Vector3d(0, -1, 0), Vector3d.Zero); + + private static Transform3d ReadNodeTransform(JsonElement node) + { + if (node.TryGetProperty("matrix", out var m)) + { + var v = m.EnumerateArray().Select(e => e.GetDouble()).ToArray(); + if (v.Length != 16) throw new InvalidDataException("glTF node matrix must have 16 elements."); + // Column-major: columns 0..2 are the axes, column 3 the translation. + return new Transform3d(new(v[0], v[1], v[2]), new(v[4], v[5], v[6]), new(v[8], v[9], v[10]), new(v[12], v[13], v[14])); + } + + var t = ReadVector(node, "translation", 3, [0, 0, 0]); + var r = ReadVector(node, "rotation", 4, [0, 0, 0, 1]); + var s = ReadVector(node, "scale", 3, [1, 1, 1]); + + double len = Math.Sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2] + r[3] * r[3]); + if (len < 1e-12) throw new InvalidDataException("glTF node rotation quaternion has zero length."); + double x = r[0] / len, y = r[1] / len, z = r[2] / len, w = r[3] / len; + + return new Transform3d( + new Vector3d(1 - 2 * (y * y + z * z), 2 * (x * y + z * w), 2 * (x * z - y * w)) * s[0], + new Vector3d(2 * (x * y - z * w), 1 - 2 * (x * x + z * z), 2 * (y * z + x * w)) * s[1], + new Vector3d(2 * (x * z + y * w), 2 * (y * z - x * w), 1 - 2 * (x * x + y * y)) * s[2], + new Vector3d(t[0], t[1], t[2])); + } + + private static double[] ReadVector(JsonElement node, string name, int length, double[] fallback) + { + if (!node.TryGetProperty(name, out var el)) return fallback; + var v = el.EnumerateArray().Select(e => e.GetDouble()).ToArray(); + if (v.Length != length) throw new InvalidDataException($"glTF node {name} must have {length} elements."); + return v; + } + + private static List ReadVec3Accessor(int index, JsonElement[] accessors, JsonElement[] views, byte[] data) + { + var accessor = GetAccessor(accessors, index, "VEC3"); + if (accessor.GetProperty("componentType").GetInt32() != 5126) + throw new NotSupportedException("GLB positions and normals must be float32."); + var (offset, count, stride) = GetRange(accessor, views, data.Length, 12); + var vertices = new List(count); + for (int i = 0; i < count; i++, offset += stride) + { + var bytes = data.AsSpan(offset, 12); + var point = new Vector3d(BinaryPrimitives.ReadSingleLittleEndian(bytes), + BinaryPrimitives.ReadSingleLittleEndian(bytes[4..]), BinaryPrimitives.ReadSingleLittleEndian(bytes[8..])); + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z)) + throw new InvalidDataException("A GLB vertex component is outside the finite range."); + vertices.Add(point); + } + return vertices; + } + + private static List ReadIndicesAccessor(int index, JsonElement[] accessors, JsonElement[] views, byte[] data) + { + var accessor = GetAccessor(accessors, index, "SCALAR"); + int size = accessor.GetProperty("componentType").GetInt32() switch + { + 5121 => 1, + 5123 => 2, + 5125 => 4, + _ => throw new NotSupportedException("GLB indices must use an unsigned integer format."), + }; + var (offset, count, stride) = GetRange(accessor, views, data.Length, size); + var indices = new List(count); + for (int i = 0; i < count; i++, offset += stride) + { + var bytes = data.AsSpan(offset, size); + uint value = size switch + { + 1 => bytes[0], + 2 => BinaryPrimitives.ReadUInt16LittleEndian(bytes), + _ => BinaryPrimitives.ReadUInt32LittleEndian(bytes), + }; + if (value > int.MaxValue) throw new InvalidDataException("A GLB index exceeds the supported range."); + indices.Add((int)value); + } + return indices; + } + + private static JsonElement GetAccessor(JsonElement[] accessors, int index, string shape) + { + if ((uint)index >= accessors.Length) throw new InvalidDataException("A GLB accessor is missing."); + var accessor = accessors[index]; + if (accessor.GetProperty("type").GetString() != shape || accessor.TryGetProperty("sparse", out _)) + throw new NotSupportedException($"Expected a non-sparse GLB accessor of type {shape}."); + return accessor; + } + + private static (int Offset, int Count, int Stride) GetRange(JsonElement accessor, JsonElement[] views, int length, int size) + { + int viewIndex = accessor.GetProperty("bufferView").GetInt32(); + if ((uint)viewIndex >= views.Length) throw new InvalidDataException("A GLB buffer view is missing."); + var view = views[viewIndex]; + if (view.GetProperty("buffer").GetInt32() != 0) + throw new NotSupportedException("GLB accessors must reference the embedded buffer."); + + int start = view.TryGetProperty("byteOffset", out var viewOffset) ? viewOffset.GetInt32() : 0; + int viewLength = view.GetProperty("byteLength").GetInt32(); + int offset = accessor.TryGetProperty("byteOffset", out var accessorOffset) ? accessorOffset.GetInt32() : 0; + int count = accessor.GetProperty("count").GetInt32(); + int stride = view.TryGetProperty("byteStride", out var viewStride) ? viewStride.GetInt32() : size; + if (start < 0 || viewLength < 0 || (long)start + viewLength > length || offset < 0 || count < 0 || stride < size + || offset + (count == 0 ? 0L : (long)(count - 1) * stride + size) > viewLength) + { + throw new InvalidDataException("A GLB accessor is outside its buffer view."); + } + return (start + offset, count, stride); + } +} diff --git a/src/IOScene.Formats/GlbSceneWriter.cs b/src/IOScene.Formats/GlbSceneWriter.cs new file mode 100644 index 0000000..5afd82a --- /dev/null +++ b/src/IOScene.Formats/GlbSceneWriter.cs @@ -0,0 +1,340 @@ +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace IOScene.Formats; + +/// Writes a self-contained glTF 2.0 binary scene. +public static class GlbSceneWriter +{ + /// Writes the scene to a file, replacing it after the full export has succeeded. + /// The scene to export. + /// Path to the GLB file. + public static void Save(SceneDocument scene, string path) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrWhiteSpace(path); + string fullPath = Path.GetFullPath(path); + string temporaryPath = Path.Combine(Path.GetDirectoryName(fullPath)!, $".{Guid.NewGuid():N}.glb.tmp"); + var file = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); + try + { + using (file) Write(scene, file); + File.Move(temporaryPath, fullPath, overwrite: true); + } + finally + { + File.Delete(temporaryPath); + } + } + + /// Writes the scene to an open stream. The stream remains open. + /// The scene to export, in metres with Z up. + /// Writable output stream. + /// The scene is invalid or has data that cannot be represented in GLB. + public static void Write(SceneDocument scene, Stream output) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentNullException.ThrowIfNull(output); + if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } failure) + throw new InvalidDataException($"Invalid scene ({failure.Code}): {failure.Message}"); + + string spoolPath = Path.Combine(Path.GetTempPath(), $"ioscene-{Guid.NewGuid():N}.tmp"); + using var binary = new FileStream(spoolPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, + bufferSize: 65536, FileOptions.DeleteOnClose | FileOptions.SequentialScan); + using var writer = new BinaryWriter(binary); + var manifest = new Payload(scene, writer).Build(); + using var json = new MemoryStream(); + using (var jsonWriter = new Utf8JsonWriter(json)) + manifest.WriteTo(jsonWriter); + + uint jsonPadding = (uint)((4 - json.Length % 4) % 4); + long binLength = binary.Length; + long length = 12 + 8 + json.Length + jsonPadding + (binLength == 0 ? 0 : 8 + binLength); + if (length > uint.MaxValue) + throw new InvalidDataException("The scene exceeds the size limit of a GLB container."); + + using var glb = new BinaryWriter(output, System.Text.Encoding.UTF8, leaveOpen: true); + glb.Write(0x46546C67u); + glb.Write(2u); + glb.Write((uint)length); + glb.Write((uint)json.Length + jsonPadding); + glb.Write(0x4E4F534Au); + json.Position = 0; + json.CopyTo(output); + for (int i = 0; i < jsonPadding; i++) glb.Write((byte)' '); + if (binLength == 0) return; + glb.Write((uint)binLength); + glb.Write(0x004E4942u); + binary.Position = 0; + binary.CopyTo(output); + } + + private sealed class Payload(SceneDocument scene, BinaryWriter binary) + { + private readonly JsonArray _nodes = new(); + private readonly JsonArray _meshes = new(); + private readonly JsonArray _materials = new(); + private readonly JsonArray _accessors = new(); + private readonly JsonArray _views = new(); + private readonly JsonArray _images = new(); + private readonly JsonArray _textures = new(); + + private readonly Dictionary _geometryById = scene.Geometries.ToDictionary(item => item.Id); + private readonly Dictionary _materialById = scene.Materials.ToDictionary(item => item.Id); + private readonly Dictionary _textureById = scene.Textures.ToDictionary(item => item.Id); + private readonly Dictionary _elementNodes = new(); + private readonly Dictionary _geometryBuffers = new(); + private readonly Dictionary<(int GeometryId, double ScaleX, double ScaleY), int> _uvBuffers = new(); + private readonly Dictionary<(int? MaterialId, RgbaColor? Color), int> _materialIndices = new(); + private readonly Dictionary _textureIndices = new(); + private readonly Dictionary<(int GeometryId, int? Material), int> _meshIndices = new(); + + public JsonObject Build() + { + // This rotation maps Z up to Y up and keeps the coordinate system right-handed. + _nodes.Add(new JsonObject { ["matrix"] = Matrix(new(Vector3d.UnitX, -Vector3d.UnitZ, Vector3d.UnitY, Vector3d.Zero)) }); + foreach (var element in scene.Elements) + { + _elementNodes.Add(element.Id, _nodes.Count); + var node = new JsonObject { ["name"] = element.Name }; + if (element.SourceId is not null || element.IfcGuid is not null) + { + var extras = new JsonObject(); + if (element.SourceId is not null) extras["sourceId"] = element.SourceId; + if (element.IfcGuid is not null) extras["ifcGuid"] = element.IfcGuid; + node["extras"] = extras; + } + _nodes.Add(node); + } + foreach (var element in scene.Elements) + AddChild(element.ParentId is { } parentId ? _elementNodes[parentId] : 0, _elementNodes[element.Id]); + + foreach (var instance in scene.Instances) + { + var geometry = _geometryById[instance.GeometryId]; + if (geometry.Vertices.Count == 0) continue; + var mesh = GetMesh(geometry, instance); + var node = new JsonObject { ["mesh"] = mesh }; + if (instance.Transform is { } transform && transform != Transform3d.Identity) node["matrix"] = Matrix(transform); + if (instance.Name is not null) node["name"] = instance.Name; + AddChild(_elementNodes[instance.ElementId], _nodes.Count); + _nodes.Add(node); + } + + var manifest = new JsonObject + { + ["asset"] = new JsonObject { ["version"] = "2.0", ["generator"] = "IOScene.Formats" }, + ["scene"] = 0, + ["scenes"] = new JsonArray(new JsonObject { ["name"] = scene.Title, ["nodes"] = new JsonArray(0) }), + ["nodes"] = _nodes, + }; + if (_meshes.Count > 0) manifest["meshes"] = _meshes; + if (_materials.Count > 0) manifest["materials"] = _materials; + if (_images.Count > 0) + { + manifest["images"] = _images; + manifest["textures"] = _textures; + } + if (_accessors.Count > 0) manifest["accessors"] = _accessors; + if (_views.Count > 0) + { + manifest["bufferViews"] = _views; + manifest["buffers"] = new JsonArray(new JsonObject { ["byteLength"] = binary.BaseStream.Length }); + } + return manifest; + } + + private void AddChild(int parent, int child) + { + var node = _nodes[parent]!.AsObject(); + if (node["children"] is not JsonArray children) + node["children"] = children = new JsonArray(); + children.Add(child); + } + + private int GetMesh(SceneGeometry geometry, SceneInstance instance) + { + SceneMaterial? material = instance.MaterialId is { } id ? _materialById[id] : null; + SceneTexture? texture = material?.TextureId is { } textureId ? _textureById[textureId] : null; + int? materialIndex = GetMaterial(instance, material, texture); + if (_meshIndices.TryGetValue((geometry.Id, materialIndex), out int mesh)) return mesh; + + if (!_geometryBuffers.TryGetValue(geometry.Id, out var buffer)) + { + buffer = AddGeometry(geometry); + _geometryBuffers.Add(geometry.Id, buffer); + } + var attributes = new JsonObject { ["POSITION"] = buffer.Position }; + if (buffer.Normal is { } normal) attributes["NORMAL"] = normal; + if (geometry.UVs is not null) attributes["TEXCOORD_0"] = GetUvs(geometry, texture?.ScaleX ?? 1, texture?.ScaleY ?? 1); + else if (texture is not null) throw new InvalidDataException($"Geometry {geometry.Id} has a texture without UVs."); + var primitive = new JsonObject + { + ["attributes"] = attributes, + ["mode"] = geometry.Topology switch + { + SceneTopology.Points => 0, + SceneTopology.Lines => 1, + SceneTopology.Triangles => 4, + _ => throw new InvalidDataException($"Geometry {geometry.Id} has an unsupported topology."), + }, + }; + if (buffer.Indices is { } indices) primitive["indices"] = indices; + if (materialIndex is { } index) primitive["material"] = index; + mesh = _meshes.Count; + _meshIndices.Add((geometry.Id, materialIndex), mesh); + _meshes.Add(new JsonObject { ["primitives"] = new JsonArray(primitive) }); + return mesh; + } + + private GeometryBuffer AddGeometry(SceneGeometry geometry) + { + long start = binary.BaseStream.Position; + var bounds = BoundingBox3d.Empty; + foreach (var vertex in geometry.Vertices) + { + Vector3d point = new(Float(vertex.X), Float(vertex.Y), Float(vertex.Z)); + WriteVector(point); + bounds = bounds.Encapsulate(point); + } + int position = Accessor(start, geometry.Vertices.Count, "VEC3", 5126, 34962); + var accessor = _accessors[position]!.AsObject(); + accessor["min"] = Numbers(bounds.Min.X, bounds.Min.Y, bounds.Min.Z); + accessor["max"] = Numbers(bounds.Max.X, bounds.Max.Y, bounds.Max.Z); + + int? normal = null; + if (geometry.Normals is { } normals && normals.All(value => value.LengthSquared > 1e-24 && double.IsFinite(value.LengthSquared))) + { + start = binary.BaseStream.Position; + foreach (var value in normals) WriteVector(value.Normalized()); + normal = Accessor(start, normals.Count, "VEC3", 5126, 34962); + } + int? indices = null; + if (geometry.Indices.Count != 0) + { + start = binary.BaseStream.Position; + foreach (var index in geometry.Indices) binary.Write((uint)index); + indices = Accessor(start, geometry.Indices.Count, "SCALAR", 5125, 34963); + } + return new(position, normal, indices); + } + + private int GetUvs(SceneGeometry geometry, double scaleX, double scaleY) + { + var key = (geometry.Id, scaleX, scaleY); + if (_uvBuffers.TryGetValue(key, out int index)) return index; + long start = binary.BaseStream.Position; + foreach (var uv in geometry.UVs!) + { + binary.Write(Float(uv.X / scaleX)); + binary.Write(Float(1 - uv.Y / scaleY)); + } + index = Accessor(start, geometry.UVs!.Count, "VEC2", 5126, 34962); + _uvBuffers.Add(key, index); + return index; + } + + private int? GetMaterial(SceneInstance instance, SceneMaterial? material, SceneTexture? texture) + { + if (material is null && instance.Color is null) return null; + var key = (instance.MaterialId, instance.Color); + if (_materialIndices.TryGetValue(key, out int index)) return index; + RgbaColor color = instance.Color ?? material!.Color; + double roughness = material?.Roughness ?? 0.5; + double metalness = material?.Metalness ?? 0.1; + if (roughness is < 0 or > 1 || metalness is < 0 or > 1) + throw new InvalidDataException("GLB material roughness and metalness must be between 0 and 1."); + + var pbr = new JsonObject + { + ["baseColorFactor"] = Numbers(Linear(color.Rf), Linear(color.Gf), Linear(color.Bf), color.Af), + ["roughnessFactor"] = roughness, + ["metallicFactor"] = metalness, + }; + if (texture is not null) pbr["baseColorTexture"] = new JsonObject { ["index"] = GetTexture(texture) }; + var item = new JsonObject { ["pbrMetallicRoughness"] = pbr, ["doubleSided"] = true }; + if (material is not null) item["name"] = material.Name; + if (color.A != 255 || texture?.MimeType == "image/png") item["alphaMode"] = "BLEND"; + index = _materials.Count; + _materialIndices.Add(key, index); + _materials.Add(item); + return index; + } + + private int GetTexture(SceneTexture texture) + { + if (_textureIndices.TryGetValue(texture.Id, out int index)) return index; + if (texture.MimeType is not ("image/png" or "image/jpeg") || texture.Data.Length == 0) + throw new InvalidDataException($"Texture {texture.Id} must contain an embedded PNG or JPEG."); + if (!double.IsFinite(texture.ScaleX) || !double.IsFinite(texture.ScaleY) || texture.ScaleX <= 0 || texture.ScaleY <= 0) + throw new InvalidDataException($"Texture {texture.Id} must have positive repeat scales."); + + long start = binary.BaseStream.Position; + binary.Write(texture.Data); + int view = View(start); + while (binary.BaseStream.Position % 4 != 0) binary.Write((byte)0); + int image = _images.Count; + _images.Add(new JsonObject { ["mimeType"] = texture.MimeType, ["bufferView"] = view }); + index = _textures.Count; + _textures.Add(new JsonObject { ["source"] = image }); + _textureIndices.Add(texture.Id, index); + return index; + } + + private int Accessor(long start, int count, string shape, int component, int target) + { + int index = _accessors.Count; + _accessors.Add(new JsonObject + { + ["bufferView"] = View(start, target), + ["type"] = shape, + ["componentType"] = component, + ["count"] = count, + }); + return index; + } + + private int View(long start, int? target = null) + { + int index = _views.Count; + var view = new JsonObject { ["buffer"] = 0, ["byteOffset"] = start, ["byteLength"] = binary.BaseStream.Position - start }; + if (target is { } value) view["target"] = value; + _views.Add(view); + return index; + } + + private void WriteVector(Vector3d vector) + { + binary.Write(Float(vector.X)); + binary.Write(Float(vector.Y)); + binary.Write(Float(vector.Z)); + } + + private static JsonArray Matrix(Transform3d transform) + { + var (x, y, z, t) = transform; + if (!Orthogonal(x, y) || !Orthogonal(y, z) || !Orthogonal(z, x)) + throw new InvalidDataException("GLB cannot store a sheared instance transform."); + return Numbers(Float(x.X), Float(x.Y), Float(x.Z), 0, Float(y.X), Float(y.Y), Float(y.Z), 0, + Float(z.X), Float(z.Y), Float(z.Z), 0, Float(t.X), Float(t.Y), Float(t.Z), 1); + } + + private static bool Orthogonal(Vector3d a, Vector3d b) => + a.Length == 0 || b.Length == 0 || Math.Abs(Vector3d.Dot(a / a.Length, b / b.Length)) <= 1e-8; + + private static float Float(double value) + { + float result = (float)value; + if (!float.IsFinite(result)) + throw new InvalidDataException("GLB coordinates must be representable as finite 32-bit floats."); + return result; + } + + private static double Linear(double encoded) => encoded <= 0.04045 + ? encoded / 12.92 : Math.Pow((encoded + 0.055) / 1.055, 2.4); + + private static JsonArray Numbers(params double[] values) => new(values.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()); + + private readonly record struct GeometryBuffer(int Position, int? Normal, int? Indices); + } +} diff --git a/src/IOScene.Formats/IOScene.Formats.csproj b/src/IOScene.Formats/IOScene.Formats.csproj new file mode 100644 index 0000000..e6cbf01 --- /dev/null +++ b/src/IOScene.Formats/IOScene.Formats.csproj @@ -0,0 +1,18 @@ + + + + 0.1.0-preview.1 + IOScene.Formats + GLB and OBJ import and GLB export for IOScene models. + true + + $(NoWarn);NU5104 + + + + + + + + + diff --git a/src/IOScene.Formats/ObjSceneReader.cs b/src/IOScene.Formats/ObjSceneReader.cs new file mode 100644 index 0000000..de74249 --- /dev/null +++ b/src/IOScene.Formats/ObjSceneReader.cs @@ -0,0 +1,139 @@ +using System.Globalization; + +namespace IOScene.Formats; + +/// +/// Imports Wavefront OBJ models (.obj) into a scene with one model: each object or group +/// (o/g) becomes one element drawn by one geometry with the vertices its faces use, without changing +/// the up axis. Material (.mtl) files are not read. +/// +public static class ObjSceneReader +{ + /// Reads an OBJ file and takes its coordinates as metres with Z up. + /// Path to the file. + public static SceneDocument Load(string filePath) + { + ArgumentNullException.ThrowIfNull(filePath); + using var fs = File.OpenRead(filePath); + return Load(fs, Path.GetFileNameWithoutExtension(filePath), Path.GetFileName(filePath), filePath); + } + + /// Reads an OBJ stream and closes it when done. + /// Stream positioned at the first OBJ record. + /// Name of the resulting scene. + public static SceneDocument Load(Stream stream, string documentTitle = "Imported OBJ Model") + { + ArgumentNullException.ThrowIfNull(stream); + return Load(stream, documentTitle, "model", null); + } + + private static SceneDocument Load(Stream stream, string documentTitle, string modelKey, string? path) + { + using var reader = new StreamReader(stream, System.Text.Encoding.UTF8); + + var vertices = new List(); + var meshIndices = new List(); + var currentMeshName = "DefaultMesh"; + var doc = new SceneDocument { Title = documentTitle }; + doc.Models.Add(new SceneModel { Id = 1, Key = modelKey, Name = documentTitle, Path = path, SourceFormat = "obj" }); + int meshCounter = 0; + + string? line; + while ((line = reader.ReadLine()) is not null) + { + var span = line.AsSpan().Trim(); + if (span.IsEmpty || span[0] == '#') continue; + + if (span.StartsWith("v ") || span.StartsWith("v\t")) + { + var parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + if (parts.Length >= 4 && + double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double x) && + double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double y) && + double.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out double z)) + { + if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z)) + throw new InvalidDataException("An OBJ vertex coordinate is outside the finite range."); + vertices.Add(new Vector3d(x, y, z)); + } + } + else if (span.StartsWith("f ") || span.StartsWith("f\t")) + { + var parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + if (parts.Length >= 4) + { + // Triangle or fan triangulation + int v0 = ParseFaceVertex(parts[1], vertices.Count); + int v1 = ParseFaceVertex(parts[2], vertices.Count); + + for (int i = 3; i < parts.Length; i++) + { + int v2 = ParseFaceVertex(parts[i], vertices.Count); + if (v0 >= 0 && v1 >= 0 && v2 >= 0) + { + meshIndices.Add(v0); + meshIndices.Add(v1); + meshIndices.Add(v2); + } + v1 = v2; + } + } + } + else if (span.StartsWith("o ") || span.StartsWith("g ") || span.StartsWith("o\t") || span.StartsWith("g\t")) + { + AddMesh(); + currentMeshName = span[2..].Trim().ToString(); + } + } + + AddMesh(); + + return doc; + + // One mesh and one element per OBJ object or group, so the viewer can list, select and hide it. + void AddMesh() + { + if (meshIndices.Count == 0) return; + + int id = ++meshCounter; + + // Keep only the vertices this object's faces use, so its bounds cover the object and not the file so far. + var meshVertices = new List(); + var localIndex = new Dictionary(); + var indices = new int[meshIndices.Count]; + for (int i = 0; i < indices.Length; i++) + { + int v = meshIndices[i]; + if (v >= vertices.Count) + { + throw new InvalidDataException($"OBJ object '{currentMeshName}': face vertex {v + 1} is outside the {vertices.Count} vertices read so far."); + } + + if (!localIndex.TryGetValue(v, out int local)) + { + local = meshVertices.Count; + localIndex.Add(v, local); + meshVertices.Add(vertices[v]); + } + indices[i] = local; + } + + doc.Elements.Add(new SceneElement { Id = id, ModelId = 1, Name = currentMeshName, Category = "OBJ" }); + doc.Geometries.Add(new SceneGeometry { Id = id, Vertices = meshVertices, Indices = indices }); + doc.Instances.Add(new SceneInstance { ElementId = id, GeometryId = id, Color = new RgbaColor(180, 180, 180), Name = currentMeshName }); + meshIndices.Clear(); + } + } + + private static int ParseFaceVertex(string token, int totalVerts) + { + int slash = token.IndexOf('/'); + string numStr = slash >= 0 ? token.Substring(0, slash) : token; + if (int.TryParse(numStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out int idx)) + { + if (idx > 0) return idx - 1; // 1-based + if (idx < 0) return totalVerts + idx; // negative relative + } + return -1; + } +} diff --git a/tests/IOScene.Tools.Tests/CoordinationTests.cs b/tests/IOScene.Tools.Tests/CoordinationTests.cs new file mode 100644 index 0000000..b8c216c --- /dev/null +++ b/tests/IOScene.Tools.Tests/CoordinationTests.cs @@ -0,0 +1,97 @@ +using System.IO.Compression; +using System.Xml.Linq; +using IOCoord; + +namespace IOScene.Tools.Tests; + +public class CoordinationTests +{ + [Fact] + public void Grid_FindsExtendedCrossingAndUsesSegmentBoundsOnRequest() + { + var grid = new SceneGridSystem + { + Lines = + [ + new() { Name = "A", Start = new(0, 0, 3), End = new(1, 0, 3) }, + new() { Name = "1", Start = new(2, 0.5, 3), End = new(2, 2, 3) }, + ] + }; + var crossing = SceneGrid.NearestIntersection(grid, new(2, 0.25)); + Assert.NotNull(crossing); + Assert.Equal(new Vector2d(2, 0), crossing.Value.Point); + Assert.Equal(0.25, crossing.Value.Distance); + Assert.Equal("A", SceneGrid.NearestLine(grid, new(1.7, 0.1))?.Line.Name); + Assert.Equal("1", SceneGrid.NearestLine(grid, new(1.7, 0.1), segmentOnly: true)?.Line.Name); + } + + [Fact] + public void Diff_MatchesPersistentIdentityAndReportsMovementIndependentlyOfIdOrder() + { + var before = new SceneDocument(); + before.AddMesh("Panel", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]).SourceId = "panel"; + var after = new SceneDocument(); + after.AddMesh("Unidentified", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]); + after.AddMesh("Panel", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]).SourceId = "panel"; + Assert.Empty(SceneDiff.Compare(before, after).Changes); + + after.Instances[1].Transform = Transform3d.Translate(Vector3d.UnitZ); + var comparison = SceneDiff.Compare(before, after); + var change = Assert.Single(comparison.Changes); + Assert.Equal(SceneChangeKind.Modified, change.Kind); + Assert.False(change.MetadataChanged); + Assert.True(change.GeometryChanged); + Assert.Equal("panel", change.SourceId); + Assert.Equal(1, comparison.UnidentifiedRevision); + } + + [Fact] + public void Diff_RejectsDuplicatePersistentIdentity() + { + var scene = new SceneDocument(); + scene.AddMesh("One", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]).SourceId = "ambiguous"; + scene.AddMesh("Two", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]).SourceId = "ambiguous"; + Assert.Throws(() => SceneDiff.Compare(scene, scene)); + } + + [Fact] + public void Bcf_WritesTopicAndSelectsOnlyKnownIfcComponents() + { + var scene = new SceneDocument(); + var element = scene.AddMesh("Beam", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]); + element.IfcGuid = "0" + new string('A', 21); + scene.ClashTests.Add(new SceneClashTest + { + Name = "Structure", + Clashes = + [ + new() { Id = "local", Name = "Beam / wall", Element1Id = element.Id, Element2Name = "Wall", + Point = new(1, 2, 3), Status = SceneClashStatus.Reviewed } + ] + }); + using var output = new MemoryStream(); + BcfClashWriter.Write(scene, output, "Author", new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + output.Position = 0; + using var zip = new ZipArchive(output, ZipArchiveMode.Read); + Assert.Equal("2.1", (string?)Load(zip.GetEntry("bcf.version")!).Attribute("VersionId")); + var markupEntry = Assert.Single(zip.Entries, item => item.Name == "markup.bcf"); + var markup = Load(markupEntry); + var topic = markup.Element("Topic")!; + string topicId = (string)topic.Attribute("Guid")!; + Assert.True(Guid.TryParseExact(topicId, "D", out _)); + Assert.NotNull(zip.GetEntry(topicId + "/")); + Assert.Equal("Reviewed", (string?)topic.Attribute("TopicStatus")); + Assert.Equal("Author", (string?)topic.Element("CreationAuthor")); + Assert.Contains("Point (m): 1, 2, 3", (string?)topic.Element("Description")); + var viewpoint = Load(zip.GetEntry(topicId + "/viewpoint.bcfv")!); + var component = Assert.Single(viewpoint.Descendants("Component")); + Assert.Equal(element.IfcGuid, (string?)component.Attribute("IfcGuid")); + Assert.Equal((string?)markup.Element("Viewpoints")!.Attribute("Guid"), (string?)viewpoint.Attribute("Guid")); + + static XElement Load(ZipArchiveEntry entry) + { + using var stream = entry.Open(); + return XElement.Load(stream); + } + } +} diff --git a/tests/IOScene.Tools.Tests/GlbSceneWriterTests.cs b/tests/IOScene.Tools.Tests/GlbSceneWriterTests.cs new file mode 100644 index 0000000..87e90bb --- /dev/null +++ b/tests/IOScene.Tools.Tests/GlbSceneWriterTests.cs @@ -0,0 +1,175 @@ +using System.Buffers.Binary; +using System.Text; +using System.Text.Json; +using IOScene.Formats; + +namespace IOScene.Tools.Tests; + +public class GlbSceneWriterTests +{ + [Fact] + public void Write_PreservesHierarchyAndSharesGeometryAcrossMirroredPlacements() + { + var scene = new SceneDocument { Title = "Test" }; + var element = scene.AddMesh("Panel", [new(1, 2, 3), new(2, 2, 3), new(1, 3, 3)], [0, 1, 2]); + scene.Elements.Add(new SceneElement { Id = 7, ModelId = element.ModelId, Name = "Assembly" }); + element.ParentId = 7; + element.SourceId = "panel-id"; + scene.Instances.Add(new SceneInstance + { + ElementId = element.Id, + GeometryId = scene.Geometries[0].Id, + Transform = new(-Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, new(10, 20, 30)), + }); + + byte[] bytes = Export(scene); + using var json = ReadJson(bytes, out int binStart); + var root = json.RootElement; + Assert.Single(root.GetProperty("meshes").EnumerateArray()); + var nodes = root.GetProperty("nodes"); + Assert.Equal(2, nodes[0].GetProperty("children")[0].GetInt32()); + Assert.Equal(1, nodes[2].GetProperty("children")[0].GetInt32()); + Assert.Equal("panel-id", nodes[1].GetProperty("extras").GetProperty("sourceId").GetString()); + var children = nodes[1].GetProperty("children"); + Assert.Equal(2, children.GetArrayLength()); + Assert.All(children.EnumerateArray(), child => Assert.Equal(0, nodes[child.GetInt32()].GetProperty("mesh").GetInt32())); + var mirror = nodes[children[1].GetInt32()].GetProperty("matrix"); + Assert.Equal(-1, mirror[0].GetDouble()); + Assert.Equal(30, mirror[14].GetDouble()); + Assert.Equal(1, nodes[0].GetProperty("matrix")[9].GetDouble()); + Assert.Equal(-1, nodes[0].GetProperty("matrix")[6].GetDouble()); + Assert.Equal(1, BinaryPrimitives.ReadSingleLittleEndian(bytes.AsSpan(binStart))); + Assert.Equal(2, BinaryPrimitives.ReadSingleLittleEndian(bytes.AsSpan(binStart + 4))); + Assert.Equal(3, BinaryPrimitives.ReadSingleLittleEndian(bytes.AsSpan(binStart + 8))); + } + + [Fact] + public void Write_EmbedsTextureAndUsesLinearOverrideAndScaledUv() + { + var scene = new SceneDocument(); + scene.AddMesh("Textured", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]); + scene.Geometries[0].UVs = [new(1, 0.5), new(0, 0), new(1, 1)]; + scene.Materials.Add(new SceneMaterial { Id = 2, TextureId = 3, Color = RgbaColor.White }); + byte[] png = Convert.FromBase64String( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jOgcAAAAASUVORK5CYII="); + scene.Textures.Add(new SceneTexture { Id = 3, Data = png, ScaleX = 2, ScaleY = 2 }); + scene.Instances[0].MaterialId = 2; + scene.Instances[0].Color = new RgbaColor(128, 0, 255, 128); + + byte[] bytes = Export(scene); + using var json = ReadJson(bytes, out int binStart); + var root = json.RootElement; + var material = root.GetProperty("materials")[0]; + var factor = material.GetProperty("pbrMetallicRoughness").GetProperty("baseColorFactor"); + Assert.Equal(0.2158605001, factor[0].GetDouble(), 9); + Assert.Equal(128 / 255d, factor[3].GetDouble(), 12); + Assert.Equal("BLEND", material.GetProperty("alphaMode").GetString()); + Assert.Equal(0, material.GetProperty("pbrMetallicRoughness").GetProperty("baseColorTexture").GetProperty("index").GetInt32()); + var image = root.GetProperty("images")[0]; + Assert.Equal("image/png", image.GetProperty("mimeType").GetString()); + var imageView = root.GetProperty("bufferViews")[image.GetProperty("bufferView").GetInt32()]; + Assert.Equal(png, bytes.AsSpan(binStart + imageView.GetProperty("byteOffset").GetInt32(), imageView.GetProperty("byteLength").GetInt32()).ToArray()); + + int uvIndex = root.GetProperty("meshes")[0].GetProperty("primitives")[0].GetProperty("attributes").GetProperty("TEXCOORD_0").GetInt32(); + int uvViewIndex = root.GetProperty("accessors")[uvIndex].GetProperty("bufferView").GetInt32(); + int uvStart = binStart + root.GetProperty("bufferViews")[uvViewIndex].GetProperty("byteOffset").GetInt32(); + Assert.Equal(0.5f, BinaryPrimitives.ReadSingleLittleEndian(bytes.AsSpan(uvStart))); + Assert.Equal(0.75f, BinaryPrimitives.ReadSingleLittleEndian(bytes.AsSpan(uvStart + 4))); + } + + [Theory] + [InlineData(SceneTopology.Points, 0)] + [InlineData(SceneTopology.Lines, 1)] + public void Write_EmitsNonTriangleTopologies(SceneTopology topology, int expected) + { + var scene = new SceneDocument(); + scene.AddMesh("Primitive", [Vector3d.Zero, Vector3d.UnitX], []); + scene.Geometries[0].Topology = topology; + + byte[] bytes = Export(scene); + using var json = ReadJson(bytes, out _); + Assert.Equal(expected, json.RootElement.GetProperty("meshes")[0].GetProperty("primitives")[0].GetProperty("mode").GetInt32()); + using var stream = new MemoryStream(bytes); + Assert.Equal(topology, Assert.Single(GlbSceneReader.Load(stream).Geometries).Topology); + } + + [Fact] + public void Load_RoundTripsWorldPositionsAndDetectsATruncatedContainer() + { + var scene = new SceneDocument(); + scene.AddMesh("Panel", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitZ], [0, 1, 2]); + scene.Instances[0].Transform = Transform3d.Translate(new(1, 2, 3)); + byte[] bytes = Export(scene); + using var stream = new MemoryStream(bytes); + var result = GlbSceneReader.Load(stream); + var placement = Assert.Single(result.Instances).Transform!.Value; + var vertices = Assert.Single(result.Geometries).Vertices; + Assert.Equal(new Vector3d(1, 2, 4), placement.Apply(vertices[2])); + + using var truncated = new MemoryStream(bytes[..^1]); + Assert.Throws(() => GlbSceneReader.Load(truncated)); + } + + [Fact] + public void Load_RejectsAnUnsupportedRequiredExtension() + { + const string json = """ + {"asset":{"version":"2.0"},"extensionsUsed":["KHR_mesh_quantization"],"extensionsRequired":["KHR_mesh_quantization"]} + """; + byte[] manifest = Encoding.UTF8.GetBytes(json.PadRight((json.Length + 3) / 4 * 4)); + using var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(0x46546C67u); + writer.Write(2u); + writer.Write(20 + manifest.Length); + writer.Write(manifest.Length); + writer.Write(0x4E4F534Au); + writer.Write(manifest); + } + + stream.Position = 0; + var error = Assert.Throws(() => GlbSceneReader.Load(stream)); + Assert.Contains("KHR_mesh_quantization", error.Message); + } + + [Fact] + public void Save_InvalidTransformPreservesExistingOutput() + { + var scene = new SceneDocument(); + scene.AddMesh("Panel", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], [0, 1, 2]); + scene.Instances[0].Transform = new(Vector3d.UnitX, new(1, 1, 0), Vector3d.UnitZ, Vector3d.Zero); + string path = Path.Combine(Path.GetTempPath(), $"test-{Guid.NewGuid():N}.glb"); + try + { + File.WriteAllBytes(path, [1, 2, 3]); + Assert.Throws(() => GlbSceneWriter.Save(scene, path)); + Assert.Equal([1, 2, 3], File.ReadAllBytes(path)); + } + finally + { + File.Delete(path); + } + } + + private static byte[] Export(SceneDocument scene) + { + using var output = new MemoryStream(); + GlbSceneWriter.Write(scene, output); + return output.ToArray(); + } + + private static JsonDocument ReadJson(byte[] bytes, out int binStart) + { + Assert.Equal(0x46546C67u, BinaryPrimitives.ReadUInt32LittleEndian(bytes)); + Assert.Equal(2, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(4))); + Assert.Equal(bytes.Length, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(8))); + int jsonLength = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(12)); + Assert.Equal(0, jsonLength % 4); + Assert.Equal(0x4E4F534Au, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(16))); + binStart = 28 + jsonLength; + Assert.Equal(0x004E4942u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(binStart - 4))); + Assert.Equal(bytes.Length - binStart, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(binStart - 8))); + return JsonDocument.Parse(bytes.AsMemory(20, jsonLength)); + } +} diff --git a/tests/IOScene.Tools.Tests/IOScene.Tools.Tests.csproj b/tests/IOScene.Tools.Tests/IOScene.Tools.Tests.csproj new file mode 100644 index 0000000..b39e15d --- /dev/null +++ b/tests/IOScene.Tools.Tests/IOScene.Tools.Tests.csproj @@ -0,0 +1,20 @@ + + + + false + $(NoWarn);CA1707;CA1861 + + + + + + + + + + + + + + + diff --git a/tests/IOScene.Tools.Tests/ObjSceneReaderTests.cs b/tests/IOScene.Tools.Tests/ObjSceneReaderTests.cs new file mode 100644 index 0000000..bc62c19 --- /dev/null +++ b/tests/IOScene.Tools.Tests/ObjSceneReaderTests.cs @@ -0,0 +1,31 @@ +using System.Text; +using IOScene.Formats; + +namespace IOScene.Tools.Tests; + +public class ObjSceneReaderTests +{ + [Fact] + public void Load_ResolvesRelativeIndicesAndCompactsEachObjectsVertices() + { + const string obj = """ + v 0 0 0 + v 1 0 0 + v 1 1 0 + v 0 1 0 + o Quad + f -4 -3 -2 -1 + g Face + f 2 3 4 + """; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)); + + var scene = ObjSceneReader.Load(stream); + + Assert.Empty(scene.Validate()); + Assert.Equal(["Quad", "Face"], scene.Elements.Select(element => element.Name)); + Assert.Equal([0, 1, 2, 0, 2, 3], scene.Geometries[0].Indices); + Assert.Equal(3, scene.Geometries[1].Vertices.Count); + Assert.Equal(Vector3d.UnitX, scene.Geometries[1].Vertices[0]); + } +} diff --git a/tests/IOScene.Tools.Tests/SceneClashTests.cs b/tests/IOScene.Tools.Tests/SceneClashTests.cs new file mode 100644 index 0000000..72819ff --- /dev/null +++ b/tests/IOScene.Tools.Tests/SceneClashTests.cs @@ -0,0 +1,47 @@ +using IOCoord; + +namespace IOScene.Tools.Tests; + +public class SceneClashTests +{ + [Fact] + public void Intersections_UsePlacedTrianglesAndReportOneResultPerPair() + { + var scene = new SceneDocument(); + var horizontal = scene.AddMesh("Slab", [new(0, 0, 0), new(2, 0, 0), new(0, 2, 0)], [0, 1, 2]); + var vertical = scene.AddMesh("Panel", [new(0, 0, -1), new(0, 0, 1), new(0, 1, 0.5)], [0, 1, 2]); + scene.Instances[1].Transform = Transform3d.Translate(new(0.5, 0.5, 0)); + for (int i = 1; i <= 12; i++) + { + scene.Instances.Add(new SceneInstance + { + ElementId = horizontal.Id, + GeometryId = scene.Geometries[0].Id, + Transform = Transform3d.Translate(new(i * 5, 0, 0)), + }); + } + + var test = SceneClash.FindSurfaceIntersections(scene, [horizontal.Id, vertical.Id], [vertical.Id, horizontal.Id]); + + var contact = Assert.Single(test.Clashes); + Assert.Equal(horizontal.Id, contact.Element1Id); + Assert.Equal(vertical.Id, contact.Element2Id); + Assert.Equal(new Vector3d(0.5, 0.5, 0), contact.Point); + Assert.Empty(scene.ClashTests); + } + + [Fact] + public void Intersections_CheckCoplanarCrossingsAndRejectOverlappingBoundsAlone() + { + var scene = new SceneDocument(); + var slab = scene.AddMesh("Slab", [new(0, 0, 0), new(4, 0, 0), new(2, 4, 0)], [0, 1, 2]); + var crossing = scene.AddMesh("Crossing", [new(0, 3, 0), new(4, 3, 0), new(2, -1, 0)], [0, 1, 2]); + var outside = scene.AddMesh("Outside", [new(3.5, 3.5, 0), new(5, 3.5, 0), new(4, 5, 0)], [0, 1, 2]); + + var test = SceneClash.FindSurfaceIntersections(scene, [slab.Id], [crossing.Id, outside.Id]); + + var contact = Assert.Single(test.Clashes); + Assert.Equal(crossing.Id, contact.Element2Id); + Assert.Equal(0, contact.Point.Z); + } +} diff --git a/tests/IOScene.Tools.Tests/SceneMeasureTests.cs b/tests/IOScene.Tools.Tests/SceneMeasureTests.cs new file mode 100644 index 0000000..f4760b8 --- /dev/null +++ b/tests/IOScene.Tools.Tests/SceneMeasureTests.cs @@ -0,0 +1,53 @@ +using IOCoord; + +namespace IOScene.Tools.Tests; + +public class SceneMeasureTests +{ + [Fact] + public void MeasuresDistanceAngleAndPathInSceneUnits() + { + Assert.Equal(5, SceneMeasure.Distance(Vector3d.Zero, new(3, 4, 0))); + Assert.Equal(90, SceneMeasure.AngleDegrees(Vector3d.UnitX, Vector3d.Zero, Vector3d.UnitZ)); + Assert.Equal(7, SceneMeasure.PathLength([Vector3d.Zero, new(3, 4, 0), new(3, 4, 2)])); + Assert.Equal(0, SceneMeasure.PathLength([])); + } + + [Fact] + public void PointToElement_UsesWorldCoordinatesAndTheClosestPlacement() + { + var scene = new SceneDocument(); + var element = scene.AddMesh("Panel", [Vector3d.Zero, new(2, 0, 0), new(0, 2, 0)], [0, 1, 2]); + scene.Instances.Add(new SceneInstance + { + ElementId = element.Id, + GeometryId = scene.Geometries[0].Id, + Transform = new(-Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, new(10, 10, 5)), + }); + + var result = SceneMeasure.PointToElement(scene, element.Id, new(9.5, 10.5, 7)); + + Assert.Equal(new PointMeasurement(new(9.5, 10.5, 5), 2), result); + } + + [Fact] + public void PointToElement_MeasuresDegenerateTriangleAsSegments() + { + var scene = new SceneDocument(); + var element = scene.AddMesh("Line", [Vector3d.Zero, Vector3d.UnitX, new(2, 0, 0)], []); + Assert.Equal(new PointMeasurement(new(1, 0, 0), 1), SceneMeasure.PointToElement(scene, element.Id, new(1, 1, 0))); + Assert.Equal(new PointMeasurement(new(2, 0, 0), 1), SceneMeasure.PointToElement(scene, element.Id, new(3, 0, 0))); + + scene.Instances.Clear(); + Assert.Null(SceneMeasure.PointToElement(scene, element.Id, Vector3d.Zero)); + } + + [Fact] + public void PointToElement_RejectsInvalidGeometry() + { + var scene = new SceneDocument(); + var element = scene.AddMesh("Broken", [Vector3d.Zero], [0, 0, 2]); + Assert.Throws(() => SceneMeasure.PointToElement(scene, element.Id, Vector3d.Zero)); + Assert.Throws(() => SceneMeasure.Distance(Vector3d.Zero, new(double.NaN, 0, 0))); + } +} diff --git a/tools/pack-release.ps1 b/tools/pack-release.ps1 index 07615e6..c217ccf 100644 --- a/tools/pack-release.ps1 +++ b/tools/pack-release.ps1 @@ -54,7 +54,8 @@ if ($LASTEXITCODE -ne 0) { throw "git archive failed with exit code $LASTEXITCOD # 3. Pack NuGet packages Write-Host "Packing NuGet packages..." -Invoke-DotNet pack (Join-Path $root 'IOScene.slnx') -c Release --no-build -o $Output +# The optional previews are packed by CI for testing. Core release tags publish IOScene only. +Invoke-DotNet pack (Join-Path $root 'src\IOScene\IOScene.csproj') -c Release --no-build -o $Output # 4. Checksums Write-Host "Calculating SHA-256 sums..."