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
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ system dependencies with `npx playwright install --with-deps chromium firefox` a
`npm run perf` runs the manual performance harness in a visible Chromium
window (for example `PERF_LADDER=25000,200000` measures synthetic models made
by `tools/SyntheticModel`); its settings are described at the top of
`test/perf/orbit.perf.js`. It is not part of CI; include its numbers in the
`test/perf/orbit.perf.js`. Set `PERF_STARTUP_ONLY=1` to [measure the first frame](docs/startup-performance.md).
The harness runs outside CI. Include its numbers in the
pull request when a change can affect rendering speed. npm dependencies are
pinned to exact versions. When updating three.js (for example a Dependabot pull
request), also rebuild and commit `dist/viewer.js` and update the version in
Expand Down
54 changes: 54 additions & 0 deletions docs/startup-performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
title: Viewer startup performance
---

# Viewer startup performance

Set `PERF_STARTUP_ONLY=1` when running `npm run perf` from `src/IOViewer/Viewer`. The harness opens the exported pages
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.
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
boundaries. Brief allocations between samples and GPU memory are outside that measurement.

## Reference workloads

- Generate the deterministic 200,000-element fixture with `PERF_LADDER=200000`. It has 200,000 instances and
19,200,000 triangles. Alternatively generate it from the root with
`dotnet run tools/SyntheticModel/SyntheticModel.cs -c Release -- --elements 200000 --out Synthetic-200k.html`.
- Export Schependomlaan with `dotnet run --project src/IOViewer.Cli -c Release -f net10.0 -- Schependomlaan.ifc -o Schependomlaan.html`
and set `PERF_MODELS` to the HTML path. The measured export has 3,337 elements, 3,277 instances and 247,472 triangles.
The IFC SHA-256 is `2c3565ca1904f2aa61adab92024cf3755b2c5b21a498144d3094d7cb58cebec7`.
[Pinned IFC source](https://github.com/openBIMstandards/Archive-DataSetSchependomlaan/blob/e6971d897b60f04ea28b4e3f2acf80d05f269197/Design%20model%20IFC/IFC%20Schependomlaan.ifc)

To compare builds, export or assemble one set of pages per build, giving every page a unique filename. List all pages
in `PERF_MODELS` in a single run and reverse the order of the two builds on alternating runs. Assign a new `PERF_LABEL`
to each run. The timing below used identical page data for each pair and changed only the embedded viewer bundle.

## Affine instance bounds

Before used commit `c6fc7dee05514c43c30dc298f75193202ad8a8b9`, which already had the same profiling hooks.
After computes each axis range directly from the affine matrix and the local box. This avoids transforming eight corners
and constructing a matrix view for every instance.

Nine paired runs used headed Chromium 158.0.8127.18 on Windows 11 build 26300, Ryzen 9 9900X3D, GeForce RTX 4080
driver 32.0.16.2124 (ANGLE D3D11), viewport 1920×1080, device pixel ratio 1.

| Median metric | Synthetic before | Synthetic after | Schependomlaan before | Schependomlaan after |
| --- | ---: | ---: | ---: | ---: |
| META parse, ms | 35.4 | 34.7 | 2.6 | 2.5 |
| BIN decode, ms | 3.7 | 3.7 | 0.4 | 0.4 |
| Scene preparation, ms | 726.7 | 684.5 | 41.6 | 41.5 |
| First render call, ms | 320.3 | 301.0 | 15.7 | 14.8 |
| Open, ms | 1,970.7 | 1,274.6 | 171.5 | 174.4 |
| Longest startup task, ms | 1,547 | 843 | 107 | 106 |
| Startup blocking, ms | 1,763.4 | 1,029.7 | 57 | 56 |
| Sampled peak JS heap, MiB | 406.7 | 406.9 | 19.3 | 20.4 |

Scene preparation had the highest median among the timed phases. The median within-pair change in scene preparation
was −12.4 ms for the synthetic workload and −1.6 ms for Schependomlaan. Synthetic open times ranged from 1,225 to
2,126 ms before and 1,213 to 2,006 ms after. A separate seven-run series gave open-time medians of 1,458 ms before and
1,622 ms after. The variation leaves the end-to-end effect unresolved. No timing threshold is set from these runs.
2 changes: 2 additions & 0 deletions docs/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
items:
- name: Public API
href: public-api.md
- name: Viewer startup performance
href: startup-performance.md
- name: API reference
href: api/
- name: GitHub
Expand Down
358 changes: 179 additions & 179 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion src/IOViewer/Viewer/src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,16 @@ 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) {
export function loadModelData(doc = document, startup) {
let meta, bin;
try {
startup?.('metadataStart');
meta = JSON.parse(block(doc, 'ioviewer-meta'));
startup?.('metadataEnd');
const binElement = doc.getElementById('ioviewer-bin');
if (!binElement) throw new Error("Data block 'ioviewer-bin' is missing.");
bin = decodeBase64(binElement);
startup?.('binaryEnd');
} catch (error) {
throw new ModelDataError(error.message, { cause: error });
}
Expand Down
34 changes: 24 additions & 10 deletions src/IOViewer/Viewer/src/engine/modelScene.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,29 @@ const finiteBox = (boxes, i) => {
for (let k = i * 6; k < i * 6 + 6; k++) if (!Number.isFinite(boxes[k])) return false;
return true;
};

// Each row of an affine transform reaches its extrema at the sum of its per-axis extrema.
function writeInstanceBox(matrices, i, { min, max }, boxes) {
const offset = i * 12;
const box = i * 6;
if (min[0] > max[0] || min[1] > max[1] || min[2] > max[2]) {
boxes.set(min, box);
boxes.set(max, box + 3);
return;
}
for (let row = 0; row < 3; row++) {
const a = matrices[offset + row];
const b = matrices[offset + row + 3];
const c = matrices[offset + row + 6];
const t = matrices[offset + row + 9];
const x0 = a * min[0], x1 = a * max[0];
const y0 = b * min[1], y1 = b * max[1];
const z0 = c * min[2], z1 = c * max[2];
boxes[box + row] = Math.min(x0, x1) + Math.min(y0, y1) + Math.min(z0, z1) + t;
boxes[box + row + 3] = Math.max(x0, x1) + Math.max(y0, y1) + Math.max(z0, z1) + t;
}
}

const colorBytes = (color) => {
const hex = color.getHex(THREE.SRGBColorSpace);
return [(hex >> 16) & 255, (hex >> 8) & 255, hex & 255];
Expand Down Expand Up @@ -111,17 +134,8 @@ export class ModelScene {
this._buckets = this._createBuckets(meta, materialOf, noHideBranch);
this._indexElements();

const matrix = new THREE.Matrix4();
const box = new THREE.Box3();
for (let i = 0; i < count; i++) {
const m = matrices.subarray(i * 12, i * 12 + 12);
matrix.set(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2], m[5], m[8], m[11], 0, 0, 0, 1);
const local = meta.geometries[geometryOf[i]].bbox;
box.min.fromArray(local.min);
box.max.fromArray(local.max);
box.applyMatrix4(matrix);
box.min.toArray(this._boxes, i * 6);
box.max.toArray(this._boxes, i * 6 + 3);
writeInstanceBox(matrices, i, meta.geometries[geometryOf[i]].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
15 changes: 12 additions & 3 deletions src/IOViewer/Viewer/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { mountLinks } from './ui/linksPanel.js';

document.documentElement.lang = lang;
const canvas = document.getElementById('ioviewer-canvas');
const testOptions = window.IOVIEWER_TEST ?? {};
const startup = testOptions.startup;

function showMessage(text) {
const message = document.getElementById('ioviewer-message');
Expand All @@ -36,7 +38,7 @@ const context = canvas.getContext('webgl2', { antialias: true });
if (!context) showMessage(t('noWebGL'));
else {
try {
start(loadModelData(), context);
start(loadModelData(document, startup), context);
} catch (error) {
if (!(error instanceof ModelDataError)) throw error;
showMessage(t('badData'));
Expand Down Expand Up @@ -66,9 +68,10 @@ function start(data, context) {
world.add(camera);

// Test-only engine options (e2e and the performance harness): chunkVertices, noHideBranch, pickFloat, slotLimit,
// mergedCap, minRepeats, cellExtent.
const testOptions = window.IOVIEWER_TEST ?? {};
// mergedCap, minRepeats, cellExtent, startup (optional phase samples).
startup?.('sceneStart');
const scene = createScene();
startup?.('sceneEnd');
data.releaseBinary(); // the scene has copied what it needs
// Starting at the whole model's cost, a GPU that draws it in time orbits at full detail; a slower one shrinks it.
// Larger models start at about what an integrated GPU draws at 30 fps (a 200k-element model, 19.2e6): from a 1M one's
Expand Down Expand Up @@ -107,6 +110,7 @@ function start(data, context) {

let resolveReady;
const ready = new Promise((resolve) => (resolveReady = resolve));
let firstRender = startup;
let frameRequested = false;
function requestRender() {
if (frameRequested || contextLost) return;
Expand All @@ -121,7 +125,12 @@ function start(data, context) {
measure.update(controls.camera, rect);
grids.update(controls.camera, rect);
motionDetail.begin(controls.camera, rect.height, performance.now());
firstRender?.('renderStart');
renderer.render(world, controls.camera);
if (firstRender) {
firstRender('renderEnd');
firstRender = undefined;
}
motionDetail.end(performance.now());
viewCube.update();
resolveReady();
Expand Down
15 changes: 15 additions & 0 deletions src/IOViewer/Viewer/test/e2e/smoke.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,21 @@ test('empty document shows "no geometry"', async ({ page }) => {
expect(requests).toEqual([]);
});

test('startup profiling samples load and first render once', async ({ page }) => {
await page.addInitScript(() => {
window.startupSamples = [];
window.IOVIEWER_TEST = { startup: (sample) => window.startupSamples.push(sample) };
});
const { errors, requests } = await open(page, 'building');
await page.evaluate(() => window.__ioviewer.controls.resize());
await nextFrame(page);
expect(await page.evaluate(() => window.startupSamples)).toEqual([
'metadataStart', 'metadataEnd', 'binaryEnd', 'sceneStart', 'sceneEnd', 'renderStart', 'renderEnd',
]);
expect(errors).toEqual([]);
expect(requests).toEqual([]);
});

test('ModelScene addresses elements by index across meshes and materials', async ({ page }) => {
const { errors } = await open(page, 'building');
const duct = building.Elements.findIndex((e) => e.Name === 'Supply Duct SA-1');
Expand Down
86 changes: 66 additions & 20 deletions src/IOViewer/Viewer/test/perf/orbit.perf.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// textures (textures mode; ladder pages are generated with --textured), nohidebranch (IOVIEWER_TEST.noHideBranch);
// PERF_OUT: where JSON results go (default <os temp>/ioviewer-perf); PERF_LABEL names the run (e.g. baseline);
// PERF_PROFILE=1 also writes a CPU profile of each model's whole run; PERF_GPU: see playwright.perf.config.js.
// PERF_STARTUP_ONLY=1 stops after the first rendered frame and writes only the startup measurements.
// After all runs, one table across them is printed and written with every result to <PERF_OUT>/ladder-<label>.{md,json}.
import { test } from '@playwright/test';
import { execFileSync } from 'node:child_process';
Expand All @@ -21,6 +22,7 @@ const LADDER = list(process.env.PERF_LADDER).map(Number);
const MODELS = list(process.env.PERF_MODELS ?? (LADDER.length ? '' : path.join(OUT, 'synthetic-200k.html')));
const VARIANTS = list(process.env.PERF_VARIANTS);
const LABEL = process.env.PERF_LABEL ?? 'run';
const STARTUP_ONLY = process.env.PERF_STARTUP_ONLY === '1';
const ORBIT_MS = 5000;
const REPO = fileURLToPath(new URL('../../../../../', import.meta.url));
const LIBRARY = path.join(REPO, 'src', 'IOViewer');
Expand Down Expand Up @@ -223,16 +225,43 @@ for (const run of RUNS) {
const file = run.page(run.variant === 'textures');
const name = path.basename(file, '.html') + (run.variant ? `-${run.variant}` : '');
const result = { label: LABEL, run: runName, model: name, variant: run.variant, htmlMB: statSync(file).size / 1048576, gpu: process.env.PERF_GPU ?? 'default' };
// Test-only engine options are read by the viewer from IOVIEWER_TEST (an engine without the option ignores it).
if (run.variant === 'nohidebranch') await page.addInitScript(() => (window.IOVIEWER_TEST = { noHideBranch: true }));
const cdp = process.env.PERF_PROFILE ? await page.context().newCDPSession(page) : null;
if (cdp) {
await cdp.send('Profiler.enable');
await cdp.send('Profiler.setSamplingInterval', { interval: 200 });
await cdp.send('Profiler.start');
}
// Time `ready` resolves, taken as it resolves (main.js publishes window.__ioviewer before the first frame).
await page.addInitScript(() => {
await page.addInitScript((variant) => {
const samples = {};
window.IOVIEWER_TEST = {
noHideBranch: variant === 'nohidebranch',
startup(name) {
samples[name] = { at: performance.now(), heap: performance.memory?.usedJSHeapSize };
},
};
const entries = [];
const observer = PerformanceObserver.supportedEntryTypes.includes('longtask')
? new PerformanceObserver((list) => entries.push(...list.getEntries()))
: null;
observer?.observe({ type: 'longtask', buffered: true });
window.__perfStartup = (readyMs) => {
if (observer) entries.push(...observer.takeRecords());
observer?.disconnect();
const tasks = entries.map((entry) => Math.min(entry.duration, readyMs - entry.startTime)).filter((ms) => ms >= 50);
const duration = (from, to) => samples[from] && samples[to] ? samples[to].at - samples[from].at : null;
const heap = Object.values(samples).map((sample) => sample.heap).filter(Number.isFinite);
return {
metaMs: duration('metadataStart', 'metadataEnd'),
binMs: duration('metadataEnd', 'binaryEnd'),
sceneMs: duration('sceneStart', 'sceneEnd'),
renderCallMs: duration('renderStart', 'renderEnd'),
sampledHeapPeakMiB: heap.length ? Math.max(...heap) / 1048576 : null,
longTasks: observer ? tasks.length : null,
longestTaskMs: observer ? Math.max(0, ...tasks) : null,
blockingMs: observer ? tasks.reduce((sum, ms) => sum + ms - 50, 0) : null,
};
};
// main.js publishes window.__ioviewer before the first frame.
let value;
Object.defineProperty(window, '__ioviewer', {
configurable: true,
Expand All @@ -242,21 +271,24 @@ for (const run of RUNS) {
v.ready.then(() => (window.__perfReady = performance.now()));
},
});
});
}, run.variant);
const errors = [];
page.on('pageerror', (e) => errors.push(String(e)));
page.on('crash', () => console.log(`${name}: the page crashed`));
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()));
await page.goto(pathToFileURL(file).href, { timeout: 10 * 60 * 1000 });
await page.waitForFunction(() => window.__perfReady, null, { timeout: 10 * 60 * 1000, polling: 100 });
const load = await page.evaluate(() => {
const load = await page.evaluate(async () => {
// The long-task entry for first render becomes available after that task ends.
await new Promise((resolve) => setTimeout(resolve, 0));
const nav = performance.getEntriesByType('navigation')[0];
const gl = document.createElement('canvas').getContext('webgl2');
const info = gl.getExtension('WEBGL_debug_renderer_info');
const { scene } = window.__ioviewer;
const triangles = scene.memory().triangles;
return {
readyMs: window.__perfReady,
startup: window.__perfStartup(window.__perfReady),
domContentLoadedMs: nav.domContentLoadedEventStart,
renderer: info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER),
elements: scene.elementCount,
Expand All @@ -267,7 +299,21 @@ for (const run of RUNS) {
canvas: [innerWidth, innerHeight],
};
});
Object.assign(result, load);
Object.assign(result, load, { browserVersion: page.context().browser().version() });
const finish = async () => {
result.errors = errors;
if (cdp) {
const { profile } = await cdp.send('Profiler.stop');
mkdirSync(OUT, { recursive: true });
writeFileSync(path.join(OUT, `profile-${LABEL}-${name}.cpuprofile`), JSON.stringify(profile));
}
save(result);
if (!STARTUP_ONLY) console.log(table(result));
};
if (STARTUP_ONLY) {
await finish();
return;
}
await installTimer(page);
if (run.variant === 'sections') await page.evaluate(() => window.__ioviewer.sections.setMode('box')); // box = the shown model
if (run.variant === 'textures') await page.evaluate(() => window.__ioviewer.scene.setDisplayMode('textures'));
Expand All @@ -279,9 +325,7 @@ for (const run of RUNS) {
result.orbitFull = fps(await orbit(page, ORBIT_MS, 1, true));
if (run.variant) {
result.heapEndMB = await page.evaluate(() => performance.memory.usedJSHeapSize / 1048576);
result.errors = errors;
save(result);
console.log(table(result));
await finish();
return;
}
result.orbitZoomed = fps(await orbit(page, ORBIT_MS, 0.25));
Expand Down Expand Up @@ -354,15 +398,7 @@ for (const run of RUNS) {
await step('fourDClose', 'fourD', 'close');
}
result.heapEndMB = await page.evaluate(() => performance.memory.usedJSHeapSize / 1048576);
result.errors = errors;

if (cdp) {
const { profile } = await cdp.send('Profiler.stop');
mkdirSync(OUT, { recursive: true });
writeFileSync(path.join(OUT, `profile-${LABEL}-${name}.cpuprofile`), JSON.stringify(profile));
}
save(result);
console.log(table(result));
await finish();
});
}

Expand All @@ -379,10 +415,20 @@ test.afterAll(() => {
const op = (o) => (o ? `${n(o.frameMs, 0)}${o.full === false ? ' (partial)' : ''}` : '—');
const orbitCell = (o) => (o ? `${n(o.medianFps)} / ${n(o.p95Fps)} (${n(o.drawnMedian * 100, 0)} %)` : '—');
const still = (s) => (s ? `${n(s.medianMs)} (${n(s.maxMs, 0)})${s.full ? '' : ' (partial)'}` : '—');
const rows = [
const startupRows = [
['elements / M triangles', (r) => `${r.elements} / ${n(r.triangles / 1e6, 2)}`],
['HTML MB', (r) => n(r.htmlMB)],
['open ms', (r) => n(r.readyMs, 0)],
['META parse ms', (r) => n(r.startup.metaMs)],
['BIN decode ms', (r) => n(r.startup.binMs)],
['scene preparation ms', (r) => n(r.startup.sceneMs)],
['first render call ms', (r) => n(r.startup.renderCallMs)],
['startup long tasks / longest ms', (r) => `${n(r.startup.longTasks, 0)} / ${n(r.startup.longestTaskMs)}`],
['startup blocking ms (over 50 ms)', (r) => n(r.startup.blockingMs)],
['sampled peak startup JS heap MiB', (r) => n(r.startup.sampledHeapPeakMiB, 0)],
];
const rows = STARTUP_ONLY ? startupRows : [
...startupRows,
['full-detail still frame ms, median (max of 10)', (r) => still(r.stillFrame)],
['draw calls (still frame)', (r) => String(r.stillFrame?.calls ?? '—')],
['orbit adaptive fps median / p95 (drawn)', (r) => orbitCell(r.orbit)],
Expand Down
Loading
Loading