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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ API between minor releases.
- Report the required byte count and the limit when an HTML export exceeds its binary buffer capacity.
- Save HTML to a temporary sibling file and replace the destination after a complete write. Report invalid coordinates,
duplicate element IDs, missing textures and conflicting legacy mesh arrays before publishing the output.
- Virtualize long clash lists. Show the existing localized messages for malformed model metadata and scenes without
drawable geometry, and set the model title when WebGL 2 is unavailable.

## [0.3.1] - 2026-11-13

Expand Down
2 changes: 1 addition & 1 deletion docs/startup-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Set `PERF_STARTUP_ONLY=1` when running `npm run perf` from `src/IOViewer/Viewer`
over `file://` and stops after the first render. It writes JSON and a Markdown summary to `PERF_OUT`. Set `PERF_PROFILE=1`
for a Chromium CPU profile. Run the timing comparison with CPU profiling off.

The report measures META parsing, BIN decoding, `ModelScene` construction and the first renderer call in milliseconds.
The report measures META parsing and validation, BIN decoding, `ModelScene` construction and the first renderer call in milliseconds.
Open time starts at navigation and ends when the viewer resolves `ready`, after submitting the first frame. It includes
HTML parsing and browser startup work. On browsers with Long Tasks reporting, blocking time sums the portion above
50 ms for each reported task before `ready`. The heap figure is the largest JavaScript heap sample at the phase
Expand Down
370 changes: 185 additions & 185 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

76 changes: 70 additions & 6 deletions src/IOViewer/Viewer/src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,76 @@ function decodeInto(bytes, offset, text) {
// The page's data blocks are missing, malformed or do not fit together, as in a truncated or damaged file.
export class ModelDataError extends Error {}

export function loadModelData(doc = document, startup) {
let meta, bin;
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
const records = (value) => Array.isArray(value) && value.every(object);
const vector = (value) => Array.isArray(value) && value.length === 3 && value.every((n) => typeof n === 'number');
const box = (value) => object(value) && vector(value.min) && vector(value.max);

function validateMeta(meta) {
if (!object(meta) || !records(meta.elements) || !records(meta.geometries) || !records(meta.materials) || !object(meta.instances)) {
throw new ModelDataError('META must describe elements, geometries, materials and instances.');
}
if (meta.title != null && typeof meta.title !== 'string') throw new ModelDataError('Invalid META title.');
const { instances } = meta;
if (!Number.isSafeInteger(instances.count) || instances.count < 0) throw new ModelDataError('Invalid META instance count.');
for (const [name, type, length] of [
['geometry', 'u32', instances.count], ['material', 'u32', instances.count],
['element', 'i32', instances.count], ['matrix', 'f32', instances.count * 12],
]) {
if (instances[name]?.t !== type || instances[name].n !== length) {
throw new ModelDataError(`Invalid META instance ${name} view.`);
}
}
for (const g of meta.geometries) {
const q = g.q;
if (!box(g.bbox) || !['u16', 'u32'].includes(g.indices?.t)
|| g.positions?.t !== (q ? 'u16' : 'f32')
|| (q && (!vector(q.o) || typeof q.s !== 'number'))
|| (g.normals != null && !['f32', 'i16'].includes(g.normals.t))
|| (g.uvs != null && g.uvs.t !== 'f32')) {
throw new ModelDataError('Invalid META geometry.');
}
}
for (const name of ['textures', 'grids', 'viewpoints', 'clashTests', 'linkedFiles']) {
if (meta[name] != null && !records(meta[name])) throw new ModelDataError(`Invalid META ${name} list.`);
}
for (const material of meta.materials) {
const index = material.texture;
if (!vector(material.color) || typeof material.opacity !== 'number'
|| (index != null && (!Number.isInteger(index) || index < 0 || index >= (meta.textures?.length ?? 0)))) {
throw new ModelDataError('Invalid META material.');
}
}
if (meta.grids?.some((grid) => !vector(grid.start) || !vector(grid.end))
|| meta.viewpoints?.some((view) => !vector(view.camera?.position) || !vector(view.camera?.target))
|| meta.clashTests?.some((test) => !records(test.clashes) || test.clashes.some((clash) => !vector(clash.point)))) {
throw new ModelDataError('Invalid META grids, viewpoints or clashes.');
}
const { sections } = meta;
if (sections != null && (!object(sections) || !records(sections.planes)
|| sections.planes.some((plane) => !vector(plane.normal) || typeof plane.offset !== 'number')
|| (sections.box != null && !box(sections.box)))) {
throw new ModelDataError('Invalid META sections.');
}
}

export function readModelMeta(doc = document, startup) {
let meta;
startup?.('metadataStart');
try {
startup?.('metadataStart');
meta = JSON.parse(block(doc, 'ioviewer-meta'));
startup?.('metadataEnd');
} catch (error) {
throw new ModelDataError(error.message, { cause: error });
}
validateMeta(meta);
startup?.('metadataEnd');
return meta;
}

export function loadModelData(doc = document, startup, meta = readModelMeta(doc, startup)) {
let bin;
try {
startup?.('binaryStart');
const binElement = doc.getElementById('ioviewer-bin');
if (!binElement) throw new Error("Data block 'ioviewer-bin' is missing.");
bin = decodeBase64(binElement);
Expand All @@ -58,8 +122,8 @@ export function loadModelData(doc = document, startup) {
meta,
view(v) {
if (!bin) throw new Error('The binary data has been released.');
const Type = VIEW_TYPES[v.t];
if (!Type) throw new ModelDataError(`Unknown view type '${v.t}'.`);
const Type = VIEW_TYPES[v?.t];
if (!Type) throw new ModelDataError(`Unknown view type '${v?.t}'.`);
const size = Type.BYTES_PER_ELEMENT;
if (!(Number.isInteger(v.o) && Number.isInteger(v.n) && v.o >= 0 && v.n >= 0 && v.o % size === 0 && v.o + v.n * size <= bin.length)) {
throw new ModelDataError(`View ${JSON.stringify(v)} is outside the ${bin.length} bytes of binary data.`);
Expand Down
13 changes: 9 additions & 4 deletions src/IOViewer/Viewer/src/engine/modelScene.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as THREE from 'three';
import { ModelDataError } from '../data.js';
import { detailThreshold, frustumPlanes, outsideFrustum, viewMetrics } from './culling.js';
import { GRID, normalsView, octEncodeInto, positionsView } from './quantize.js';
import {
Expand Down Expand Up @@ -98,7 +99,7 @@ const colorBytes = (color) => {
* options (tests and the performance harness, from window.IOVIEWER_TEST): chunkVertices, noHideBranch, slotLimit,
* mergedCap, minRepeats, cellExtent; and maxTextureSize (the renderer's). A model over the slot limit throws
* ModelTooLargeError.
* Instances with a non-finite box (NaN or infinite matrix or geometry box) get no slot and take no part in the bounds.
* Instances with non-finite bounds or without drawable triangles get no slot.
*/
export class ModelScene {
constructor(data, options = {}) {
Expand Down Expand Up @@ -135,7 +136,9 @@ export class ModelScene {
this._indexElements();

for (let i = 0; i < count; i++) {
writeInstanceBox(matrices, i, meta.geometries[geometryOf[i]].bbox, this._boxes);
const geometry = meta.geometries[geometryOf[i]];
if (!geometry) throw new ModelDataError(`Instance ${i} references missing geometry ${geometryOf[i]}.`);
writeInstanceBox(matrices, i, geometry.bbox, this._boxes);
}
const limit = Math.min(2 ** 24 - 1, ROW * (options.maxTextureSize ?? Infinity), options.slotLimit ?? Infinity);
this._build(data, geometryOf, matrices, options, limit);
Expand Down Expand Up @@ -458,6 +461,7 @@ export class ModelScene {
const indices = data.view(geometry.indices);
const uvs = geometry.uvs ? data.view(geometry.uvs) : null;
s = bakeSource(positionsView(data, geometry), geometry.q ?? null, normalsView(data, geometry), indices, uvs);
s.drawable = s.indices.length >= 3 && s.min.every(Number.isFinite) && s.max.every(Number.isFinite);
sources.set(g, s);
}
return s;
Expand All @@ -472,7 +476,7 @@ export class ModelScene {
const b = this._boxes;
for (let i = 0; i < count; i++) {
const s = source(geometryOf[i]);
if (s.vertices === 0 || !finiteBox(b, i)) continue;
if (!s.drawable || !finiteBox(b, i)) continue;
kind[i] = placeSlot(matrices, i, s, origins.subarray(i * 3, i * 3 + 3));
mirrored[i] = isMirrored(matrices, i) ? 1 : 0;
weight[i] = s.vertices;
Expand Down Expand Up @@ -825,11 +829,12 @@ export class ModelScene {
let bucket = byMaterial.get(m);
if (!bucket) {
const source = meta.materials[m];
if (!source) throw new ModelDataError(`Instance ${i} references missing material ${m}.`);
bucket = {
index: buckets.length,
bytes: source.color.map((c) => Math.round(c * 255)), // META colours are bytes / 255: exact
opacity: source.opacity,
texture: source.texture,
texture: source.texture ?? null,
// The material colour stays white: the slot colour multiplies it in the shader.
material: patchLambert(new THREE.MeshLambertMaterial({ side: THREE.DoubleSide }), this.slotUniforms, noHideBranch),
// The same for the instanced cells in wireframe mode (three's own wireframe of their triangles).
Expand Down
26 changes: 13 additions & 13 deletions src/IOViewer/Viewer/src/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as THREE from 'three';
import { loadModelData, ModelDataError } from './data.js';
import { loadModelData, ModelDataError, readModelMeta } from './data.js';
import { ModelScene, ModelTooLargeError } from './engine/modelScene.js';
import { lang, t } from './i18n.js';
import { NavigationControls } from './nav/controls.js';
Expand Down Expand Up @@ -34,19 +34,18 @@ function showMessage(text) {

// The context is asked for here, with the attributes three would ask for, so that without WebGL 2 the page says so
// instead of three logging an error; damaged model data is reported on the page too.
const context = canvas.getContext('webgl2', { antialias: true });
if (!context) showMessage(t('noWebGL'));
else {
try {
start(loadModelData(document, startup), context);
} catch (error) {
if (!(error instanceof ModelDataError)) throw error;
showMessage(t('badData'));
}
try {
const meta = readModelMeta(document, startup);
if (meta.title) document.title = meta.title;
const context = canvas.getContext('webgl2', { antialias: true });
if (context) start(loadModelData(document, startup, meta), context);
else showMessage(t('noWebGL'));
} catch (error) {
if (!(error instanceof ModelDataError)) throw error;
showMessage(t('badData'));
}

function start(data, context) {
if (data.meta.title) document.title = data.meta.title;
const renderer = new THREE.WebGLRenderer({ canvas, context, antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.localClippingEnabled = true;
Expand Down Expand Up @@ -90,7 +89,9 @@ function start(data, context) {
// A model over what the viewer can draw opens without geometry and says why; the tree and properties still work.
function createScene() {
try {
return new ModelScene(data, { ...testOptions, maxTextureSize: renderer.capabilities.maxTextureSize });
const model = new ModelScene(data, { ...testOptions, maxTextureSize: renderer.capabilities.maxTextureSize });
if (model.totalCost === 0) showMessage(t('noGeometry'));
return model;
} catch (error) {
if (!(error instanceof ModelTooLargeError)) throw error;
showMessage(t('tooLarge').replace('{count}', error.count).replace('{limit}', error.limit));
Expand All @@ -99,7 +100,6 @@ function start(data, context) {
return new ModelScene({ ...data, meta: { ...data.meta, instances } });
}
}
if (data.meta.instances.count === 0) showMessage(t('noGeometry'));
// The model's GPU buffers keep no CPU copy, so a lost context cannot be rebuilt, not even when the browser restores
// it: say so instead of a blank page, and draw nothing more (the picker stops too).
let contextLost = false;
Expand Down
61 changes: 56 additions & 5 deletions src/IOViewer/Viewer/src/ui/clashesPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import { formatDistance } from '../tools/measure.js';
import { icons } from './icons.js';
import { el } from './dom.js';
import { rowButton } from './viewsPanel.js';
import { visibleRange } from './tree.js';

const STATUSES = ['New', 'Active', 'Reviewed', 'Approved', 'Resolved'];
const ROW_STRIDE = 27; // 26 px row plus the panel's 1 px gap
const OVERSCAN = 8;
const MARKER_PX = 14;
const MIN_DISTANCE = 2; // m from the clash point
const FALLBACK_DIRECTION = new THREE.Vector3(1, -1, 0.8).normalize();
Expand All @@ -29,11 +32,13 @@ export function mountClashes({ shell, tests, elements, scene, controls, selectio
group.add(marker);
group.visible = false;
let activeRow = null;
let activeClash = null;

function hideMarker() {
group.visible = false;
activeRow?.removeAttribute('aria-current');
activeRow = null;
activeClash = null;
controls.setExtraBounds('clash', null); // also renders
}

Expand All @@ -58,6 +63,7 @@ export function mountClashes({ shell, tests, elements, scene, controls, selectio
group.visible = true;
activeRow?.removeAttribute('aria-current');
activeRow = row;
activeClash = clash;
row.setAttribute('aria-current', 'true');
controls.setExtraBounds('clash', new THREE.Box3(point.clone(), point.clone()));
}
Expand All @@ -71,11 +77,15 @@ export function mountClashes({ shell, tests, elements, scene, controls, selectio
// A distance the source does not report is null: nothing is shown.
const distance = typeof clash.distance === 'number' ? formatDistance(clash.distance) : '';
row.append(status, el('span', 'ioviewer-clash-distance', distance));
if (clash === activeClash) {
activeRow = row;
row.setAttribute('aria-current', 'true');
}
row.addEventListener('click', () => show(clash, row));
return row;
}

function testGroup(test) {
function testGroup(test, refresh) {
const box = el('div', 'ioviewer-clash-test');
const header = el('button', 'ioviewer-row ioviewer-clash-header');
header.type = 'button';
Expand All @@ -84,21 +94,62 @@ export function mountClashes({ shell, tests, elements, scene, controls, selectio
header.setAttribute('title', title);
header.insertAdjacentHTML('afterbegin', icons.chevron); // static icon markup
header.append(el('span', 'ioviewer-row-name', title));
const list = el('div', 'ioviewer-row-list');
list.append(...test.clashes.map(clashRow));
const list = el('div', 'ioviewer-clash-list');
list.style.height = `${Math.max(0, test.clashes.length * ROW_STRIDE - 1)}px`;
header.addEventListener('click', () => {
list.hidden = !list.hidden;
header.setAttribute('aria-expanded', String(!list.hidden));
refresh();
});
box.append(header, list);
return box;
return { box, list, clashes: test.clashes, rows: new Map() };
}

function renderRows({ list, clashes, rows }, { start, end }) {
for (const [index, row] of rows) {
if (index < start || index >= end) {
row.remove();
rows.delete(index);
}
}
let next = null;
for (let i = end - 1; i >= start; i--) {
let row = rows.get(i);
if (!row) {
row = clashRow(clashes[i]);
row.style.top = `${i * ROW_STRIDE}px`;
list.insertBefore(row, next);
rows.set(i, row);
}
next = row;
}
}

function renderPanel(body) {
if (!tests.length) return;
body.classList.add('ioviewer-clashes-body');
const groups = tests.map((test) => testGroup(test, refresh));
for (const entry of groups) body.append(entry.box);

function refresh() {
const top = body.scrollTop;
const height = body.clientHeight;
// Read every offset before replacing any rows so each scroll has one layout read.
const ranges = groups.map(({ list, clashes }) => height && !list.hidden
? visibleRange(top - list.offsetTop, ROW_STRIDE, height, clashes.length, OVERSCAN)
: { start: 0, end: 0 });
groups.forEach((entry, i) => renderRows(entry, ranges[i]));
}

body.addEventListener('scroll', refresh);
new ResizeObserver(refresh).observe(body);
}

shell.registerPanel('clashes', {
icon: icons.clashes,
title: t('panel.clashes'),
visible: tests.length > 0,
render: (body) => body.append(...tests.map(testGroup)),
render: renderPanel,
onClose: () => group.visible && hideMarker(),
});

Expand Down
11 changes: 11 additions & 0 deletions src/IOViewer/Viewer/styles/viewer.css
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,17 @@ label.ioviewer-row:hover {
}

/* Clashes: test headers fold their clashes; the status is a coloured chip */
.ioviewer-clashes-body,
.ioviewer-clash-list {
position: relative;
}

.ioviewer-clash-list > .ioviewer-clash {
position: absolute;
left: 0;
height: 26px;
}

.ioviewer-clash-header {
color: var(--text);
font-weight: 600;
Expand Down
19 changes: 19 additions & 0 deletions src/IOViewer/Viewer/test/e2e/global-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'node:path';
export const viewerDir = path.resolve(import.meta.dirname, '../..');
export const fixturesDir = path.resolve(viewerDir, '../../../tests/fixtures/viewer');
export const LARGE_ELEMENTS = 20000;
export const LARGE_CLASHES = 130000;

// Exports a JSON document to test-results/<name>.html with the CLI, as a user would; `options` are extra CLI flags.
function exportHtml(jsonPath, name, options = []) {
Expand Down Expand Up @@ -97,4 +98,22 @@ export default function globalSetup() {
const bin = /(<script id="ioviewer-bin" type="application\/octet-stream">)([^<]*)/;
if (!bin.test(html)) throw new Error('building.html has no BIN block.');
writeFileSync(path.join(results, 'damaged.html'), html.replace(bin, (_, open, data) => open + data.slice(0, (data.length >> 1) & ~3)));

const metaBlock = /(<script id="ioviewer-meta" type="application\/json">)([^<]*)/;
const meta = JSON.parse(html.match(metaBlock)[2]);
const withMeta = (changes) => html.replace(metaBlock, (_, open) => open + JSON.stringify({ ...meta, ...changes }));
writeFileSync(path.join(results, 'malformed-meta.html'), withMeta({ instances: [] }));
writeFileSync(path.join(results, 'missing-geometry.html'), withMeta({ geometries: [] }));
writeFileSync(path.join(results, 'zero-vertices.html'), withMeta({
geometries: meta.geometries.map((g) => ({ ...g, positions: { ...g.positions, n: 0 }, indices: { ...g.indices, n: 0 } })),
}));
const invalidMatrices = Buffer.from(html.match(bin)[2], 'base64');
const { o, n } = meta.instances.matrix;
for (let i = 0; i < n; i += 12) invalidMatrices.writeFloatLE(NaN, o + i * 4);
writeFileSync(path.join(results, 'non-finite-instances.html'), html.replace(bin, (_, open) => open + invalidMatrices.toString('base64')));
const clash = meta.clashTests[0].clashes[0];
const clashes = Array.from({ length: LARGE_CLASHES }, (_, i) => ({ ...clash, id: String(i), name: `Clash ${i + 1}` }));
writeFileSync(path.join(results, 'large-clashes.html'), withMeta({
clashTests: [{ name: 'Large test', clashes }, { name: 'Tail test', clashes: [{ ...clash, name: 'Tail clash' }] }],
}));
}
Loading
Loading