From 7fcdb6f09e0d5c8c33803c482f8250b39cb69298 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:30:07 +0300 Subject: [PATCH] Honor indexed points and line bounds in standalone HTML --- CHANGELOG.md | 5 ++ src/IOViewer/Exporters/ViewerPayloadWriter.cs | 87 +++++++++++++++++-- src/IOViewer/Viewer/test/e2e/cad.spec.js | 37 ++++++++ tests/IOViewer.Tests/LinePayloadTests.cs | 33 +++++++ tests/IOViewer.Tests/PointPayloadTests.cs | 33 +++++++ tests/IOViewer.Tests/ViewerHtml.cs | 1 + tests/fixtures/viewer/cad-indexed.json | 23 +++++ 7 files changed, 211 insertions(+), 8 deletions(-) create mode 100644 tests/fixtures/viewer/cad-indexed.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 3417264..d608a22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ API between minor releases. ## [Unreleased] +### Fixed + +- Standalone HTML follows point indices and keeps each selected point's color and intensity. +- Unused vertices in indexed points and lines no longer affect framing. + ## [0.4.3] - 2026-12-02 ### Added diff --git a/src/IOViewer/Exporters/ViewerPayloadWriter.cs b/src/IOViewer/Exporters/ViewerPayloadWriter.cs index 6369f97..0c85418 100644 --- a/src/IOViewer/Exporters/ViewerPayloadWriter.cs +++ b/src/IOViewer/Exporters/ViewerPayloadWriter.cs @@ -271,7 +271,7 @@ private void ValidateMetadata() } } - /// Counts the instances the viewer does not draw because their geometry is neither triangles nor points. + /// Counts instances that use a topology the standalone viewer does not draw. public static int UndrawnInstances(SceneDocument scene) { var topology = new Dictionary(); @@ -283,18 +283,31 @@ public static int UndrawnInstances(SceneDocument scene) private Dictionary Build() { var geometries = new Dictionary(); + bool hasVertexSelection = false; foreach (var geometry in _scene.Geometries) { if (!geometries.TryAdd(geometry.Id, geometry)) { throw new InvalidDataException($"Geometry id {geometry.Id} is used by more than one geometry."); } - if (geometry.Topology == SceneTopology.Triangles) CheckIndices(geometry.Indices, geometry.Vertices.Count, $"Geometry {geometry.Id}"); - else if (geometry.Topology == SceneTopology.Lines) + if (geometry.Topology is SceneTopology.Triangles or SceneTopology.Lines or SceneTopology.Points) { CheckIndices(geometry.Indices, geometry.Vertices.Count, $"Geometry {geometry.Id}"); + } + if (geometry.Topology == SceneTopology.Lines) + { int segVerts = geometry.Indices.Count > 0 ? geometry.Indices.Count : geometry.Vertices.Count; if (segVerts % 2 != 0) throw new InvalidDataException($"Line geometry {geometry.Id} has an odd vertex count."); + if (geometry.Indices.Count > 0) + { + var compact = CompactLineVertices(geometry); + geometries[geometry.Id] = compact; + hasVertexSelection |= !ReferenceEquals(compact, geometry); + } + } + else if (geometry.Topology == SceneTopology.Points && geometry.Indices.Count > 0) + { + hasVertexSelection = true; } if (!geometry.Vertices.All(IsFinite) || geometry.Normals?.All(IsFinite) == false || geometry.UVs?.All(uv => double.IsFinite(uv.X) && double.IsFinite(uv.Y)) == false) @@ -351,7 +364,7 @@ private Dictionary Build() if (!elementIndex.TryAdd(id, i)) throw new InvalidDataException($"Element id {id} is used by more than one element."); } - _bounds = _scene.ComputeBounds(); + _bounds = hasVertexSelection ? ComputeSelectedBounds(geometries) : _scene.ComputeBounds(); _rtcOffset = _bounds.IsEmpty ? Vector3d.Zero : _bounds.Center; if (!IsFinite(_rtcOffset) || !_bounds.IsEmpty && (!IsFinite(_bounds.Min - _rtcOffset) || !IsFinite(_bounds.Max - _rtcOffset))) throw new InvalidDataException("The scene bounds are not finite in viewer coordinates."); @@ -430,6 +443,50 @@ private Dictionary Build() return elementIndex; } + private BoundingBox3d ComputeSelectedBounds(Dictionary geometries) + { + var bounds = BoundingBox3d.Empty; + foreach (var instance in _scene.Instances) + { + var geometry = geometries[instance.GeometryId]; + var transform = instance.Transform ?? Transform3d.Identity; + if (geometry.Topology == SceneTopology.Points && geometry.Indices.Count > 0) + { + foreach (int index in geometry.Indices) bounds = bounds.Encapsulate(transform.Apply(geometry.Vertices[index])); + } + else + { + foreach (var vertex in geometry.Vertices) bounds = bounds.Encapsulate(transform.Apply(vertex)); + } + } + return bounds; + } + + // Line vertices outside the index list must not move the geometry's Float32 origin. + private static SceneGeometry CompactLineVertices(SceneGeometry geometry) + { + var remap = new int[geometry.Vertices.Count]; + int count = 0; + foreach (int index in geometry.Indices) + { + if (remap[index] == 0) remap[index] = ++count; + } + if (count == geometry.Vertices.Count) return geometry; + + var vertices = new Vector3d[count]; + for (int i = 0; i < remap.Length; i++) + { + if (remap[i] != 0) vertices[remap[i] - 1] = geometry.Vertices[i]; + } + return new SceneGeometry + { + Id = geometry.Id, + Topology = geometry.Topology, + Vertices = vertices, + Indices = geometry.Indices.Select(index => remap[index] - 1).ToArray(), + }; + } + // CAD vector lines (especially 1:100 paper sheets) contain sub-millimetre details that would be // distorted by the 1/1024 m triangle grid, so store local Float32 coordinates relative to min. private void AddLineInstance( @@ -492,18 +549,20 @@ private static IReadOnlyList LineIndices(SceneGeometry geometry) => private void AddPointInstance(SceneGeometry geometry, SceneInstance instance, Dictionary elementIndex) { var transform = instance.Transform ?? Transform3d.Identity; - var rtc = new Vector3d[geometry.Vertices.Count]; + var indices = geometry.Indices; + bool indexed = indices.Count > 0; + var rtc = new Vector3d[indexed ? indices.Count : geometry.Vertices.Count]; var box = BoundingBox3d.Empty; for (int i = 0; i < rtc.Length; i++) { - rtc[i] = transform.Apply(geometry.Vertices[i]) - _rtcOffset; + rtc[i] = transform.Apply(geometry.Vertices[indexed ? indices[i] : i]) - _rtcOffset; box = box.Encapsulate(rtc[i]); } int geometryIndex; Vector3d translation; - byte[]? colors = _pointColors.GetValueOrDefault(geometry.Id); - byte[]? intensities = _pointIntensities.GetValueOrDefault(geometry.Id); + byte[]? colors = SelectPointSamples(_pointColors.GetValueOrDefault(geometry.Id), indices, 3); + byte[]? intensities = SelectPointSamples(_pointIntensities.GetValueOrDefault(geometry.Id), indices, 1); if (GeometryQuantizer.TryQuantize(rtc, out var origin, out var q)) { var local = box.IsEmpty ? box : new BoundingBox3d(box.Min - origin, box.Max - origin); @@ -526,6 +585,18 @@ private void AddPointInstance(SceneGeometry geometry, SceneInstance instance, Di AddMatrix(Transform3d.Identity, translation, _pointMatrix); } + private static byte[]? SelectPointSamples(byte[]? samples, IReadOnlyList indices, int stride) + { + if (samples is null || indices.Count == 0) return samples; + + var selected = new byte[checked(indices.Count * stride)]; + for (int i = 0; i < indices.Count; i++) + { + samples.AsSpan(indices[i] * stride, stride).CopyTo(selected.AsSpan(i * stride, stride)); + } + return selected; + } + private static void CheckIndices(IReadOnlyList indices, int vertexCount, string owner) { for (int i = 0; i < indices.Count; i++) diff --git a/src/IOViewer/Viewer/test/e2e/cad.spec.js b/src/IOViewer/Viewer/test/e2e/cad.spec.js index 6519f34..c9ba462 100644 --- a/src/IOViewer/Viewer/test/e2e/cad.spec.js +++ b/src/IOViewer/Viewer/test/e2e/cad.spec.js @@ -45,3 +45,40 @@ test('text-only spaces fit and draw their annotations, including wrapped and hid expect(await mode()).toBe(false); expect(errors).toEqual([]); }); + +test('indexed points keep their colors and unused vertices do not frame points or lines', async ({ page }) => { + await page.goto(pathToFileURL(path.join(viewerDir, 'test-results/cad-indexed.html')).href); + await page.evaluate(() => window.__ioviewer.ready); + + const result = await page.evaluate(() => { + const { scene, controls, points, lines } = window.__ioviewer; + const offsetX = JSON.parse(document.getElementById('ioviewer-meta').textContent).rtcOffset[0]; + const worldTargetX = () => controls.target.x + offsetX; + const initialTarget = worldTargetX(); + const pointGeometry = points.root.children[0].geometry; + const lineGeometry = lines.root.children[0].geometry; + const fitElement = (element) => { + scene.isolate([element]); + const bounds = scene.visibleBox(); + controls.fitBox(bounds, false); + return { width: bounds.max.x - bounds.min.x, target: worldTargetX() }; + }; + return { + pointCount: pointGeometry.getAttribute('position').count, + colors: Array.from(pointGeometry.getAttribute('color').array), + lineVertexCount: lineGeometry.getAttribute('position').count, + initialTarget, + pointFrame: fitElement(0), + lineFrame: fitElement(1), + }; + }); + + expect(result).toEqual({ + pointCount: 2, + colors: [0, 0, 1, 1, 0, 0], + lineVertexCount: 2, + initialTarget: 1, + pointFrame: { width: 2, target: 1 }, + lineFrame: { width: 2, target: 1 }, + }); +}); diff --git a/tests/IOViewer.Tests/LinePayloadTests.cs b/tests/IOViewer.Tests/LinePayloadTests.cs index 66c9b55..936f1ff 100644 --- a/tests/IOViewer.Tests/LinePayloadTests.cs +++ b/tests/IOViewer.Tests/LinePayloadTests.cs @@ -128,6 +128,39 @@ public void Annotations_And_Sheets_Are_Serialized_With_Centered_Coordinates() Assert.Equal("#14171c", sheets[1].GetProperty("background").GetString()); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Indexed_Lines_Use_Referenced_Vertices_For_Local_And_Scene_Bounds(bool shared) + { + var scene = CadDrawing(); + var geometry = scene.Geometries[0]; + geometry.Vertices = [new(0, 0, 0), new(-10_000, 0, 0), new(2, 1, 0)]; + geometry.Indices = [2, 0]; + scene.Instances.RemoveAt(1); + + if (shared) + { + scene.Instances.Add(new SceneInstance + { + ElementId = 2, + GeometryId = 1, + Transform = Transform3d.Translate(new(1, 0, 0)), + }); + } + + var view = ViewerHtml.Export(new ViewerDocument(scene)); + var line = view.Geometries[0]; + var positions = view.Positions(line); + var indices = view.Read(line.GetProperty("indices")); + Assert.Equal(2, indices.Length); + Assert.Equal(2, positions[(int)indices[0] * 3]); + Assert.Equal(0, positions[(int)indices[1] * 3]); + Assert.Equal([2, 1, 0], line.GetProperty("bbox").GetProperty("max").EnumerateArray().Select(v => v.GetDouble())); + Assert.Equal([shared ? 1.5 : 1, 0.5, 0], + view.Meta.GetProperty("rtcOffset").EnumerateArray().Select(v => v.GetDouble())); + } + [Fact] public void Lines_Preserve_SubMillimetre_PaperSheet_Precision() { diff --git a/tests/IOViewer.Tests/PointPayloadTests.cs b/tests/IOViewer.Tests/PointPayloadTests.cs index e083aa2..813acc0 100644 --- a/tests/IOViewer.Tests/PointPayloadTests.cs +++ b/tests/IOViewer.Tests/PointPayloadTests.cs @@ -41,6 +41,39 @@ public void Points_Are_Written_As_Format4_Points_And_Not_Skipped() Assert.Equal([0, 0, 0, 1, 0, 0, 0, 1, 0], view.Positions(view.Geometries[0])); } + [Fact] + public void Indexed_Points_Keep_Selected_Color_And_Intensity_Order_And_Fit_Their_Bounds() + { + var scene = Cloud(); + var geometry = scene.Geometries[0]; + geometry.Vertices = [new(0, 0, 0), new(10_000, 0, 0), new(2, 1, 0)]; + geometry.Indices = [2, 0]; + var doc = new ViewerDocument(scene) + { + PointColors = new() { [1] = [255, 0, 0, 0, 255, 0, 0, 0, 255] }, + PointIntensities = new() { [1] = [11, 22, 33] }, + }; + + var view = ViewerHtml.Export(doc); + var points = view.Geometries[0]; + + Assert.Equal([2, 1, 0, 0, 0, 0], view.Positions(points)); + Assert.Equal([0, 0, 255, 255, 0, 0], view.Read(points.GetProperty("colors"))); + Assert.Equal([33, 11], view.Read(points.GetProperty("intensities"))); + Assert.Equal([1, 0.5, 0], view.Meta.GetProperty("rtcOffset").EnumerateArray().Select(v => v.GetDouble())); + Assert.Equal([-1, -0.5, 0], view.Meta.GetProperty("bbox").GetProperty("min").EnumerateArray().Select(v => v.GetDouble())); + Assert.Equal([1, 0.5, 0], view.Meta.GetProperty("bbox").GetProperty("max").EnumerateArray().Select(v => v.GetDouble())); + } + + [Fact] + public void Point_Indices_Must_Reference_Existing_Vertices() + { + var scene = Cloud(); + scene.Geometries[0].Indices = [2, 3]; + + Assert.Throws(() => ViewerHtml.Export(new ViewerDocument(scene))); + } + [Fact] public void Point_Rgb_And_Panorama_Roundtrip_And_Use_The_Viewer_Binary_Block() { diff --git a/tests/IOViewer.Tests/ViewerHtml.cs b/tests/IOViewer.Tests/ViewerHtml.cs index a93250d..a514d9e 100644 --- a/tests/IOViewer.Tests/ViewerHtml.cs +++ b/tests/IOViewer.Tests/ViewerHtml.cs @@ -48,6 +48,7 @@ public double[] Read(JsonElement view) result[i] = type switch { "f32" => BinaryPrimitives.ReadSingleLittleEndian(span[(i * 4)..]), + "u8" => span[i], "u16" => BinaryPrimitives.ReadUInt16LittleEndian(span[(i * 2)..]), "i16" => BinaryPrimitives.ReadInt16LittleEndian(span[(i * 2)..]), "u32" => BinaryPrimitives.ReadUInt32LittleEndian(span[(i * 4)..]), diff --git a/tests/fixtures/viewer/cad-indexed.json b/tests/fixtures/viewer/cad-indexed.json new file mode 100644 index 0000000..d0aa291 --- /dev/null +++ b/tests/fixtures/viewer/cad-indexed.json @@ -0,0 +1,23 @@ +{ + "Kind": "ioviewer", + "Format": 2, + "Scene": { + "Kind": "ioscene", + "Format": 1, + "Title": "Indexed CAD primitives", + "Models": [{"Id": 1, "Key": "fixture", "Name": "Fixture"}], + "Elements": [ + {"Id": 1, "Name": "Points", "ModelId": 1}, + {"Id": 2, "Name": "Line", "ModelId": 1} + ], + "Geometries": [ + {"Id": 1, "Topology": 2, "Vertices": [0, 0, 0, 10000, 0, 0, 2, 1, 0], "Indices": [2, 0]}, + {"Id": 2, "Topology": 1, "Vertices": [0, 0, 0, -10000, 0, 0, 2, 1, 0], "Indices": [2, 0]} + ], + "Instances": [ + {"ElementId": 1, "GeometryId": 1}, + {"ElementId": 2, "GeometryId": 2} + ] + }, + "PointColors": {"1": "/wAAAP8AAAD/"} +}