Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ API between minor releases.
### Added

- `ioviewer` reads Navisworks `.nwc` caches through `NwcIO.Scene` 0.13.0.
- Standalone HTML opens with the section box or cutting planes saved in `ViewerDocument`.

## [0.3.1] - 2026-11-13

Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ The documentation site with API references and guides is at <https://ioextend.gi
- `HtmlViewerOptions.MaxMeshVertices` is unlimited by default. When a lower limit cuts the model, the viewer shows a banner with the number of meshes written.
- The viewer needs WebGL 2; without it the page says so. If the browser drops the graphics context, the page shows a message asking to reload it.
- Transparent objects are sorted per chunk of merged geometry (or per cell of instanced copies), not per object, so overlapping transparent objects in the same chunk can blend in the wrong order.
- Section planes and section boxes stored in `ViewerDocument` are kept in viewer JSON but are not applied by the HTML viewer when it opens.
- The viewer draws triangles only. Instances of line or point geometry are skipped, and the CLI prints a warning with their number.
- The OBJ importer reads geometry only; `.mtl` material files are not read.

Expand Down
8 changes: 6 additions & 2 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ The model data is the IOScene scene model, referenced by the `IOViewer` package.

- `ViewerDocument`: a `Scene` plus what only the viewer uses: `SectionPlanes`, `SectionBox` and `HiddenModelKeys`, the
keys of the linked models hidden at start. `Title` reads and writes `Scene.Title`.
- `ViewerSectionPlane`: Cutting plane defined by axis or normal vector with offset and flip direction.
- `ViewerSectionBox`: 6-sided 3D clipping volume. Section planes and boxes are kept in viewer JSON; the HTML viewer does not apply them when it opens.
- `ViewerSectionPlane`: Cutting plane defined by axis or custom normal. `Offset` is the signed distance in metres
from the scene origin along its unit normal. By default the plane cuts the side the normal points to. `Inverted`
cuts the opposite side.
- `ViewerSectionBox`: 6-sided clipping volume in scene coordinates. `Inverted` cuts inside the box.
Exported HTML opens in box mode when the box is enabled, or in planes mode with the first six enabled planes.
Both are available if the document supplies both. Editing handles start hidden.

### Exporters (`IOViewer.Exporters`)

Expand Down
62 changes: 62 additions & 0 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ namespace IOViewer.Exporters;
internal sealed class ViewerPayloadWriter
{
private const int FlushThreshold = 1 << 16;
private const int MaxSectionPlanes = 6; // Matches the viewer's MAX_PLANES.
private static readonly RgbaColor DefaultColor = new(200, 200, 200);

private readonly SceneDocument _scene;
Expand All @@ -40,6 +41,8 @@ internal sealed class ViewerPayloadWriter
private readonly List<uint> _instanceMaterial = [];
private readonly List<int> _instanceElement = [];
private readonly List<float> _instanceMatrix = [];
private readonly List<(string Axis, Vector3d Normal, double Offset, bool Flipped)> _sectionPlanes = [];
private (BoundingBox3d Bounds, bool Inverted)? _sectionBox;
private BoundingBox3d _bounds;
private Vector3d _rtcOffset;
private int _drawable;
Expand All @@ -60,9 +63,44 @@ public static ViewerPayloadWriter Create(ViewerDocument doc, HtmlViewerOptions o
{
var writer = new ViewerPayloadWriter(doc, options);
writer.Build();
writer.BuildSections(doc);
return writer;
}

private void BuildSections(ViewerDocument doc)
{
foreach (var plane in doc.SectionPlanes ?? [])
{
if (plane is not { Enabled: true }) continue;
var (axis, normal) = plane.Axis switch
{
ViewerSectionAxis.X => ("x", Vector3d.UnitX),
ViewerSectionAxis.Y => ("y", Vector3d.UnitY),
ViewerSectionAxis.Z => ("z", Vector3d.UnitZ),
ViewerSectionAxis.Custom => ("custom", plane.Normal),
_ => throw new InvalidDataException($"Unknown section plane axis: {plane.Axis}."),
};
double scale = Math.Max(Math.Abs(normal.X), Math.Max(Math.Abs(normal.Y), Math.Abs(normal.Z)));
if (!double.IsFinite(scale) || scale == 0)
throw new InvalidDataException("The section plane normal must be finite and nonzero.");
normal = new Vector3d(normal.X / scale, normal.Y / scale, normal.Z / scale).Normalized();

// n·p = offset in scene coordinates, and p = rtcPoint + rtcOffset.
double offset = plane.Offset - Vector3d.Dot(normal, _rtcOffset);
if (!double.IsFinite(offset)) throw new InvalidDataException("The section plane offset must be finite in viewer coordinates.");
_sectionPlanes.Add((axis, normal, offset, plane.Inverted));
if (_sectionPlanes.Count == MaxSectionPlanes) break;
}

if (doc.SectionBox is not { Enabled: true } box) return;
var bounds = new BoundingBox3d(box.Min - _rtcOffset, box.Max - _rtcOffset);
if (bounds.IsEmpty || !IsFinite(bounds.Min) || !IsFinite(bounds.Max))
throw new InvalidDataException("The section box must have finite bounds with Min at or below Max on each axis.");
_sectionBox = (bounds, box.Inverted);
}

private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z);

/// <summary>Counts the instances the viewer does not draw because their geometry is not made of triangles.</summary>
public static int UndrawnInstances(SceneDocument scene)
{
Expand Down Expand Up @@ -594,6 +632,7 @@ public void WriteMeta(Stream output)
}
w.WriteEndArray();

WriteSections(w);
WriteViewpoints(w);
WriteGrids(w);
WriteTimeLiner(w);
Expand All @@ -603,6 +642,29 @@ public void WriteMeta(Stream output)
w.WriteEndObject();
}

private void WriteSections(Utf8JsonWriter w)
{
if (_sectionPlanes.Count == 0 && _sectionBox is null) return;
w.WriteStartObject("sections");
w.WriteStartArray("planes");
foreach (var plane in _sectionPlanes)
{
w.WriteStartObject();
w.WriteString("axis", plane.Axis);
WriteVector(w, "normal", plane.Normal);
w.WriteNumber("offset", plane.Offset);
w.WriteBoolean("flipped", plane.Flipped);
w.WriteEndObject();
}
w.WriteEndArray();
if (_sectionBox is { } box)
{
WriteBox(w, "box", box.Bounds, Vector3d.Zero);
w.WriteBoolean("cutInside", box.Inverted);
}
w.WriteEndObject();
}

private void WriteViewpoints(Utf8JsonWriter w)
{
w.WriteStartArray("viewpoints");
Expand Down
8 changes: 8 additions & 0 deletions src/IOViewer/Model/ViewerSection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,15 @@ public enum ViewerSectionAxis
public sealed class ViewerSectionPlane
{
public ViewerSectionAxis Axis { get; set; } = ViewerSectionAxis.X;

/// <summary>The plane direction when <see cref="Axis"/> is <see cref="ViewerSectionAxis.Custom"/>.</summary>
public Vector3d Normal { get; set; } = Vector3d.UnitX;

/// <summary>Signed distance in metres along the unit normal from the scene origin to the plane.</summary>
public double Offset { get; set; }
public bool Enabled { get; set; } = true;

/// <summary>Cut the side opposite the normal instead of the side it points to.</summary>
public bool Inverted { get; set; }

public ViewerSectionPlane() { }
Expand Down Expand Up @@ -46,6 +52,8 @@ public sealed class ViewerSectionBox
public Vector3d Min { get; set; } = new(-10, -10, -10);
public Vector3d Max { get; set; } = new(10, 10, 10);
public bool Enabled { get; set; } = true;

/// <summary>Cut the inside of the box and keep the outside.</summary>
public bool Inverted { get; set; }

public ViewerSectionBox() { }
Expand Down
40 changes: 20 additions & 20 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/IOViewer/Viewer/src/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const dictionaries = {
'sections.addPlane': 'Добавить плоскость',
'sections.noPlanes': 'Плоскостей нет',
'sections.rotated': 'повёрнута',
'sections.custom': 'Произвольная',
'sections.position': 'Положение плоскости',
'sections.flip': 'Сменить сторону',
'sections.enabled': 'Вкл',
Expand Down Expand Up @@ -182,6 +183,7 @@ const dictionaries = {
'sections.addPlane': 'Add plane',
'sections.noPlanes': 'No planes',
'sections.rotated': 'rotated',
'sections.custom': 'Custom',
'sections.position': 'Plane position',
'sections.flip': 'Flip side',
'sections.enabled': 'On',
Expand Down
2 changes: 1 addition & 1 deletion src/IOViewer/Viewer/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function start(data, context) {
const motionDetail = new MotionDetail(scene, requestRender, Math.min(scene.totalCost, 20e6));
world.add(scene.root);
// Sections never change which elements are shown, so they leave the bounds (orbit pivot, near/far) as they are.
const sections = new Sections(scene, scene.visibleBox());
const sections = new Sections(scene, scene.visibleBox(), data.meta.sections);
const sectionGizmo = new SectionGizmo(sections, canvas);
world.add(sectionGizmo.group); // outside scene.root: the picking id pass renders only the model
const uiRoot = document.getElementById('ioviewer-ui');
Expand Down
20 changes: 18 additions & 2 deletions src/IOViewer/Viewer/src/tools/sections.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const Z = new THREE.Vector3(0, 0, 1);
* Dispatches 'change' after every change.
*/
export class Sections extends EventTarget {
constructor(scene, modelBox) {
constructor(scene, modelBox, initial) {
super();
this.scene = scene;
this.modelBox = modelBox.clone();
Expand All @@ -25,6 +25,22 @@ export class Sections extends EventTarget {
this.boxMode = 'keepInside';
this.gizmoVisible = true;
this._mode = 'off';
if (!initial || modelBox.isEmpty()) return;

this.planes = initial.planes.map(({ axis, normal: components, offset, flipped }) => {
const normal = new THREE.Vector3().fromArray(components);
const quaternion = new THREE.Quaternion().setFromUnitVectors(Z, normal);
// The payload measures from the RTC origin. The controls measure from the model centre.
return { axis, quaternion, offset: offset - normal.dot(this.center), flipped, enabled: true, rotated: false };
});
if (this.planes.length) this.active = 0;
if (initial.box) {
const { min, max } = initial.box;
this.box = new THREE.Box3(new THREE.Vector3().fromArray(min), new THREE.Vector3().fromArray(max));
this.boxMode = initial.cutInside ? 'cutInside' : 'keepInside';
}
this.gizmoVisible = false;
this.setMode(this.box ? 'box' : 'planes');
}

get mode() {
Expand Down Expand Up @@ -69,7 +85,7 @@ export class Sections extends EventTarget {
if (enabled !== undefined) plane.enabled = !!enabled;
if (quaternion) {
plane.quaternion.copy(quaternion).normalize();
plane.rotated = this.normal(i).angleTo(axisVector(plane.axis)) > 1e-6;
plane.rotated = plane.axis !== 'custom' && this.normal(i).angleTo(axisVector(plane.axis)) > 1e-6;
}
this._changed(true);
}
Expand Down
9 changes: 4 additions & 5 deletions src/IOViewer/Viewer/src/ui/sectionsPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,14 @@ function planeRow(sections, i) {
const update = () => {
const plane = sections.planes[i];
const rotated = plane.rotated ? ` (${t('sections.rotated')})` : '';
name.textContent = `${i + 1}. ${plane.axis.toUpperCase()}${rotated}`;
const axis = plane.axis === 'custom' ? t('sections.custom') : plane.axis.toUpperCase();
name.textContent = `${i + 1}. ${axis}${rotated}`;
row.classList.toggle('active', sections.active === i);
flip.setAttribute('aria-pressed', String(plane.flipped));
enabled.input.checked = plane.enabled;
const extent = sections.extent(i);
slider.min = String(-extent);
slider.max = String(extent);
slider.min = String(Math.min(-extent, plane.offset));
slider.max = String(Math.max(extent, plane.offset));
slider.value = String(plane.offset);
};
return { element: row, update };
Expand Down Expand Up @@ -130,8 +131,6 @@ export function mountSections({ root, shell, toolbar, contextMenu, sections, sel
update();
updateFit();

toolbar.setActive('plane', false);
toolbar.setActive('box', false);
if (sections.modelBox.isEmpty()) return;
const open = () => shell.openPanel('sections');
toolbar.setHandler('plane', () => {
Expand Down
26 changes: 18 additions & 8 deletions src/IOViewer/Viewer/test/e2e/global-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ function shearModel() {
return model;
}

// Exports every committed fixture, the building again opening in white mode, a generated large model for the
// tree virtualization test, the sheared model, the building without the survey marker's element and a copy of the
// building whose binary block is cut in half, as in a truncated file.
// Exports the committed fixtures and variants for initial display, clipping, large scenes and damaged data.
export default function globalSetup() {
for (const file of readdirSync(fixturesDir).filter((f) => f.endsWith('.json'))) {
exportHtml(path.join(fixturesDir, file), path.basename(file, '.json'));
Expand All @@ -63,14 +61,26 @@ export default function globalSetup() {
const shear = path.join(viewerDir, 'test-results', 'shear.json');
writeFileSync(shear, JSON.stringify(shearModel()));
exportHtml(shear, 'shear');

const results = path.join(viewerDir, 'test-results');
const building = JSON.parse(readFileSync(path.join(fixturesDir, 'building.json'), 'utf8'));
const planes = [{ Axis: 3, Normal: [0, 0, 2], Offset: 2 }, { Axis: 0, Offset: -100, Enabled: false }];
for (const [name, box] of [
['building-section-planes', null],
['building-section-keep', { Min: [17.6, 5.6, -0.1], Max: [18.4, 6.4, 3.5], Inverted: false }],
['building-section-cut', { Min: [17.6, 5.6, -0.1], Max: [18.4, 6.4, 3.5], Inverted: true }],
]) {
const json = path.join(results, `${name}.json`);
writeFileSync(json, JSON.stringify({ ...building, SectionPlanes: planes, SectionBox: box }));
exportHtml(json, name);
}

// Its instance then names no element: Validate() rejects such a scene, but the page still draws it, as element -1.
const orphan = JSON.parse(readFileSync(path.join(fixturesDir, 'building.json'), 'utf8'));
orphan.Scene.Elements = orphan.Scene.Elements.filter((e) => e.Name !== 'Survey Marker');
const orphanPath = path.join(viewerDir, 'test-results', 'orphan.json');
writeFileSync(orphanPath, JSON.stringify(orphan));
building.Scene.Elements = building.Scene.Elements.filter((e) => e.Name !== 'Survey Marker');
const orphanPath = path.join(results, 'orphan.json');
writeFileSync(orphanPath, JSON.stringify(building));
exportHtml(orphanPath, 'orphan');

const results = path.join(viewerDir, 'test-results');
const html = readFileSync(path.join(results, 'building.html'), 'utf8');
const bin = /(<script id="ioviewer-bin" type="application\/octet-stream">)([^<]*)/;
if (!bin.test(html)) throw new Error('building.html has no BIN block.');
Expand Down
34 changes: 34 additions & 0 deletions src/IOViewer/Viewer/test/e2e/sections.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,40 @@ async function drag(page, from, to, steps = 8) {
await page.mouse.up();
}

test('exported HTML opens with the saved plane applied and the gizmo hidden', async ({ page }) => {
const errors = await open(page, 'building-section-planes');
await expect(tool(page, 'plane')).toHaveAttribute('aria-pressed', 'true');
const state = await page.evaluate(() => {
const { sections, sectionGizmo } = window.__ioviewer;
const { rtcOffset } = JSON.parse(document.getElementById('ioviewer-meta').textContent);
return { axes: sections.planes.map((plane) => plane.axis), z: sections.origin(0).z + rtcOffset[2], gizmo: sectionGizmo.planeGizmo.visible };
});
expect(state).toMatchObject({ axes: ['custom'], gizmo: false });
expect(state.z).toBeCloseTo(2, 9);
const roof = await indexOf(page, 'Roof Slab');
const ground = await indexOf(page, 'Ground Slab');
expect(await pickAt(page, await screenAt(page, roof, [0.5, 0.95, 1]))).not.toBe(roof);
expect(await pickAt(page, await screenAt(page, ground, [0.985, 0.5, 1]))).toBe(ground);
expect(errors).toEqual([]);
});

for (const inverted of [false, true]) {
test(`exported HTML opens in section box mode (${inverted ? 'cut inside' : 'keep inside'})`, async ({ page }) => {
const errors = await open(page, inverted ? 'building-section-cut' : 'building-section-keep');
await expect(tool(page, 'box')).toHaveAttribute('aria-pressed', 'true');
const state = await page.evaluate(() => {
const { sections, sectionGizmo } = window.__ioviewer;
return { mode: sections.mode, boxMode: sections.boxMode, planes: sections.planes.length, handles: sectionGizmo.boxHandles.some((h) => h.visible) };
});
expect(state).toEqual({ mode: 'box', boxMode: inverted ? 'cutInside' : 'keepInside', planes: 1, handles: false });
const inside = await indexOf(page, 'Column D2 Level 1');
const outside = await indexOf(page, 'Column D1 Level 1');
expect(await pickAt(page, await screenAt(page, inside)) === inside).toBe(!inverted);
expect(await pickAt(page, await screenAt(page, outside)) === outside).toBe(inverted);
expect(errors).toEqual([]);
});
}

test('a Z plane through the middle cuts the roof away; flipping it brings the roof back and cuts the ground slab; reset restores', async ({ page }) => {
const errors = await open(page);
await page.evaluate(() => window.__ioviewer.grids.setVisible(false)); // axis 2 runs across the sampled slab rim
Expand Down
Loading
Loading