diff --git a/docs/public-api.md b/docs/public-api.md
index 16b36de..6a0e8e3 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -72,6 +72,9 @@ and visibility.
Embedded element IDs and their clash and schedule references use decimal strings outside JavaScript's safe integer range.
- `HtmlViewerOptions`: Title, which data to include (properties, viewpoints, grids, 4D schedule, clashes), the initial display mode (`InitialWireframe`, `InitialWhiteMode`), and `MaxMeshVertices`, which is unlimited by default; when a lower limit leaves meshes out, the viewer shows how many were written.
- `JsonViewerExporter`: Writes a `ViewerDocument` as viewer JSON (`"Kind": "ioviewer"`, `"Format": 2`). A scene alone is written with IOScene's `SceneJson`.
+- `ClusterSourceWriter.Export(document, stream, options)`: Writes the triangle records and review metadata for the
+ clustered viewer into an empty, writable, seekable stream and returns the number of triangles written. The caller
+ retains ownership of the stream.
### Compute and export clash results
diff --git a/src/IOViewer/Exporters/ClusterSourceWriter.cs b/src/IOViewer/Exporters/ClusterSourceWriter.cs
index 2a1f786..207855f 100644
--- a/src/IOViewer/Exporters/ClusterSourceWriter.cs
+++ b/src/IOViewer/Exporters/ClusterSourceWriter.cs
@@ -6,8 +6,8 @@
namespace IOViewer.Exporters;
-// Disk-backed handoff to the offline LOD builder. A record is at most 8,192 triangles.
-internal static class ClusterSourceWriter
+/// Writes a seekable mesh source for the clustered viewer's page builder.
+public static class ClusterSourceWriter
{
private const int RecordIndices = 8192 * 3;
private const uint Signature = 0x33534d49; // IMS3
@@ -25,8 +25,7 @@ internal static long Save(ViewerDocument doc, string target, HtmlViewerOptions o
{
long triangles;
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536))
- using (var writer = new BinaryWriter(stream))
- triangles = Write(doc, writer, options);
+ triangles = Export(doc, stream, options);
File.Move(temporary, path);
return triangles;
}
@@ -36,6 +35,19 @@ internal static long Save(ViewerDocument doc, string target, HtmlViewerOptions o
}
}
+ /// Writes an IMS mesh source and returns the number of triangles. The fresh destination must be
+ /// writable and seekable. The caller retains ownership of the stream.
+ public static long Export(ViewerDocument document, Stream destination, HtmlViewerOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(document);
+ ArgumentNullException.ThrowIfNull(destination);
+ if (!destination.CanWrite || !destination.CanSeek || destination.Length != 0 || destination.Position != 0)
+ throw new ArgumentException("Use an empty, writable, seekable stream.", nameof(destination));
+
+ using var writer = new BinaryWriter(destination, System.Text.Encoding.UTF8, leaveOpen: true);
+ return Write(document, writer, options ?? new HtmlViewerOptions());
+ }
+
private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOptions options)
{
var scene = doc.Scene;
diff --git a/src/IOViewer/Viewer/build-mesh-pages.js b/src/IOViewer/Viewer/build-mesh-pages.js
index 8ee17b6..5938cf2 100644
--- a/src/IOViewer/Viewer/build-mesh-pages.js
+++ b/src/IOViewer/Viewer/build-mesh-pages.js
@@ -1,396 +1,29 @@
import { closeSync, fstatSync, mkdirSync, openSync, readSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { MeshoptSimplifier } from 'meshoptimizer/simplifier';
-import { splitCells, unitNormals } from './src/engine/chunks.js';
-import { ELEMENT_FIELDS, INSTANCE_BYTES, isBounds, isPoint, MAX_ELEMENT_BYTES, MESH_FORMAT, MESH_MANIFEST_BYTES, PAGE_TRIANGLES, ROOT_BYTES, pageBytes, residentBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './src/stream/meshPages.js';
-import { validateReviewMeta } from './src/data.js';
+import { buildMeshPagesFromSource } from './src/stream/meshBuilder.js';
-const HEADER = 28, RECORD = 40;
-const channel = Array.from({ length: 256 }, (_, i) => {
- const x = i / 255;
- return Math.round(255 * (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4));
-});
-const linearColor = (color) => [channel[color & 255], channel[(color >>> 8) & 255], channel[(color >>> 16) & 255], color >>> 24];
-
-function read(fd, bytes, offset) {
- const buffer = new ArrayBuffer(bytes), data = new Uint8Array(buffer);
- for (let at = 0; at < bytes;) {
- const read = readSync(fd, data, at, bytes - at, offset + at);
- if (!read) throw new Error('Truncated geometry source.');
- at += read;
- }
- return buffer;
-}
-
-function recordsOf(fd, includeBim) {
- const header = new DataView(read(fd, HEADER, 0));
- const version = header.getUint32(0, true);
- const sharedFormat = version === 0x34534d49;
- const reviewFormat = sharedFormat || version === 0x33534d49;
- const annotated = reviewFormat || version === 0x32534d49;
- if (!annotated && version !== 0x31534d49) throw new Error('Expected an IOViewer .ivmesh source.');
- const origin = [4, 12, 20].map((i) => header.getFloat64(i, true));
- if (!isPoint(origin)) throw new Error('Invalid source origin.');
- const records = [];
- const size = fstatSync(fd).size;
- const start = HEADER + (annotated ? 8 : 0), recordSize = RECORD + (sharedFormat ? 36 : reviewFormat ? 16 : annotated ? 8 : 0);
- const end = annotated ? Number(new DataView(read(fd, 8, HEADER)).getBigInt64(0, true)) : size;
- if (!Number.isSafeInteger(end) || end < start || end > size) throw new Error('Invalid geometry directory offset.');
- const meta = new Float32Array(recordSize / 4), data = new Uint8Array(meta.buffer), counts = new Uint32Array(meta.buffer);
- const recordView = new DataView(meta.buffer);
- const slots = new Map(), elements = [], prototypes = new Map();
- let review, propertiesStart = end, textureCount = 0;
- if (reviewFormat) {
- const length = new DataView(read(fd, 4, end)).getUint32(0, true);
- propertiesStart += 4 + length;
- if (!length || length > MESH_MANIFEST_BYTES || propertiesStart > size) throw new Error('Invalid cluster review size.');
- if (includeBim) {
- const { elements: sourceElements, ...fields } = JSON.parse(Buffer.from(read(fd, length, end + 4)).toString('utf8'));
- validateReviewMeta({ ...fields, elements: sourceElements });
- review = fields;
- textureCount = fields.textures?.length ?? 0;
- for (const input of sourceElements) {
- const id = String(input.id);
- if (!/^-?\d+$/.test(id) || slots.has(id)) throw new Error('Invalid review element ID.');
- slots.set(id, elements.length);
- elements.push({ ...Object.fromEntries(Object.entries(input).filter(([, value]) => value != null)), id });
- }
- }
- }
- for (let offset = start; offset < end;) {
- const recordOffset = offset;
- if (offset + recordSize > end || readSync(fd, data, 0, recordSize, offset) !== recordSize) throw new Error('Truncated mesh record.');
- const min = [...meta.subarray(0, 3)], max = [...meta.subarray(3, 6)];
- const [vertices, indices, rgba, normals] = counts.subarray(6);
- const texture = reviewFormat ? recordView.getInt32(RECORD + 8, true) : -1;
- const flags = reviewFormat ? recordView.getUint32(RECORD + 12, true) : 0;
- const uv = sharedFormat ? Boolean(flags & 2) : texture >= 0;
- const shape = sharedFormat ? Number(recordView.getBigInt64(RECORD + 16, true)) : -1;
- const shift = shape >= 0 ? [...meta.subarray((RECORD + 24) / 4)] : undefined;
- const bytes = vertices * (12 * (1 + normals) + (uv ? 8 : 0)) + indices * 4;
- offset += recordSize;
- const first = shape === recordOffset;
- const prototype = prototypes.get(shape);
- const inline = first || shape === -1;
- if (!isBounds({ min, max }) || !vertices || vertices > indices || !indices || indices % 3 || indices > PAGE_TRIANGLES * 3
- || normals > 1 || flags > (sharedFormat ? 3 : 1) || texture < -1 || (texture >= 0 && !uv)
- || (includeBim && texture >= textureCount) || (inline && bytes > end - offset)
- || (shape !== -1 && (!isPoint(shift) || (!first && (!prototype || prototype.vertices !== vertices
- || prototype.indices !== indices || prototype.normals !== normals || prototype.flags !== flags))))) throw new Error('Invalid mesh record.');
- if (first) prototypes.set(shape, { offset, vertices, indices, normals, flags });
- let element;
- if (annotated && includeBim) {
- const id = recordView.getBigInt64(RECORD, true).toString();
- element = slots.get(id);
- if (element === undefined) {
- element = elements.length;
- slots.set(id, element);
- elements.push({ id });
- }
- const bounds = elements[element];
- if (!bounds.min) Object.assign(bounds, { min: [...min], max: [...max] });
- else {
- for (let i = 0; i < 3; i++) {
- bounds.min[i] = Math.min(bounds.min[i], min[i]);
- bounds.max[i] = Math.max(bounds.max[i], max[i]);
- }
- }
- }
- records.push({ min, max, vertices, indices, rgba, normals, offset: inline ? offset : prototype.offset, bytes, element, texture,
- solid: Boolean(flags & 1), uv, includeBim, shape, shift });
- if (inline) offset += bytes;
- }
- if (!records.length) throw new Error('The source contains no triangle geometry.');
- const metadata = new Map();
- for (let at = propertiesStart; includeBim && at < size;) {
- const prefix = new DataView(read(fd, 12, at));
- const id = prefix.getBigInt64(0, true).toString(), length = prefix.getUint32(8, true);
- at += 12;
- if (!slots.has(id) || metadata.has(id) || !length || length > MAX_ELEMENT_BYTES || at + length > size) throw new Error('Invalid element property record.');
- metadata.set(id, { at, length });
- at += length;
- }
- return { origin, records, elements, metadata, review };
-}
-
-function aggregateBounds(children) {
- const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
- for (const child of children) for (let i = 0; i < 3; i++) {
- min[i] = Math.min(min[i], child.min[i]);
- max[i] = Math.max(max[i], child.max[i]);
- }
- return { min, max };
-}
-
-// The initial camera fits the middle 98% of triangle-weighted record centres. The full bounds drive Fit All.
-export function focusBounds(records, bounds) {
- const total = records.reduce((sum, record) => sum + record.indices, 0);
- const min = [], max = [];
- for (let axis = 0; axis < 3; axis++) {
- const centre = (entry) => (entry.min[axis] + entry.max[axis]) / 2;
- const ordered = [...records].sort((a, b) => centre(a) - centre(b));
- let weight = 0, low, high;
- for (const record of ordered) {
- weight += record.indices;
- if (low === undefined && weight >= total * 0.01) low = centre(record);
- if (weight >= total * 0.99) { high = centre(record); break; }
- }
- min.push(low < high ? low : bounds.min[axis]);
- max.push(low < high ? high : bounds.max[axis]);
- }
- return { min, max };
-}
-
-function assemble(parts, tagged = false, leaf = false) {
- const vertices = parts.reduce((sum, part) => sum + part.position.length / 3, 0);
- const position = new Float32Array(vertices * 3), normal = new Int16Array(vertices * 3), color = new Uint8Array(vertices * 4);
- const uv = leaf && parts.some((part) => part.uv) ? new Float32Array(vertices * 2) : null;
- const groups = leaf && parts.some((part) => part.solid || part.texture !== undefined);
- const solidGroups = [], blendedGroups = [];
- const opaque = [], blended = [];
- const opaqueTags = [], blendedTags = [];
- if (groups) parts.sort((a, b) => (a.texture ?? -1) - (b.texture ?? -1) || Number(a.solid) - Number(b.solid));
- let at = 0;
- for (const part of parts) {
- position.set(part.position, at * 3);
- normal.set(part.normal, at * 3);
- color.set(part.color, at * 4);
- if (part.uv && uv) uv.set(part.uv, at * 2);
- if (groups) {
- const entries = part.opaque ? solidGroups : blendedGroups;
- const previous = entries.at(-1);
- const closed = part.solid || undefined, texture = part.texture;
- if (previous && previous.closed === closed && previous.texture === texture) previous.count += part.index.length;
- else entries.push({ count: part.index.length, closed, texture });
- }
- for (let j = 0; j < part.index.length; j++) {
- const solid = j < part.opaque;
- (solid ? opaque : blended).push(at + part.index[j]);
- if (tagged && j % 3 === 0) (solid ? opaqueTags : blendedTags).push(part.element);
- }
- at += part.position.length / 3;
- }
- return { position, normal, color, uv, groups: groups ? [...solidGroups, ...blendedGroups] : undefined,
- opaque: Uint32Array.from(opaque), blended: Uint32Array.from(blended),
- tags: tagged ? Uint32Array.from([...opaqueTags, ...blendedTags]) : null };
-}
-
-function partFromRecord(fd, record, local = false) {
- const buffer = read(fd, record.bytes, record.offset), n = record.vertices * 3;
- const position = new Float32Array(buffer, 0, n);
- const index = new Uint32Array(buffer, n * 4 * (1 + record.normals), record.indices);
- if (index.some((i) => i >= record.vertices) || position.some((n) => !Number.isFinite(n))) throw new Error('Invalid mesh positions or indices.');
- const normals = record.normals ? new Float32Array(buffer, n * 4, n) : unitNormals({ positions: position, indices: index });
- if (normals.some((n) => !Number.isFinite(n))) throw new Error('Invalid mesh normal.');
- const normal = Int16Array.from(normals, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 32767));
- const color = new Uint8Array(record.vertices * 4), a = record.rgba >>> 24;
- const rgba = linearColor(record.rgba);
- for (let i = 0; i < color.length; i += 4) color.set(rgba, i);
- const texture = record.includeBim && record.texture >= 0 ? record.texture : undefined;
- const uv = record.uv && (texture !== undefined || local)
- ? new Float32Array(buffer, index.byteOffset + index.byteLength, record.vertices * 2) : null;
- if (uv?.some((value) => !Number.isFinite(value))) throw new Error('Invalid mesh UV.');
- if (!local && record.shift) for (let i = 0; i < position.length; i++) position[i] += record.shift[i % 3];
- return { position, normal, color, index, uv, texture, solid: record.solid,
- opaque: a === 255 ? index.length : 0, element: record.element };
-}
-
-function reducedIndices(mesh, target, bounds) {
- const { position, normal, color } = mesh;
- const scale = Math.max(...bounds.max.map((n, i) => n - bounds.min[i]));
- const attributes = new Float32Array(position.length / 3 * 7);
- for (let i = 0, j = 0; j < color.length; i += 7, j += 4) {
- attributes[i] = color[j] / 255;
- attributes[i + 1] = color[j + 1] / 255;
- attributes[i + 2] = color[j + 2] / 255;
- attributes[i + 3] = color[j + 3] / 255;
- for (let a = 0; a < 3; a++) attributes[i + 4 + a] = normal[j / 4 * 3 + a] / 32767;
- }
- let error = 0;
- const n = mesh.opaque.length + mesh.blended.length;
- const output = ['opaque', 'blended'].map((kind) => {
- const input = mesh[kind];
- if (!input.length) return input;
- const limit = Math.max(3, Math.floor(target * input.length / n / 3) * 3);
- if (input.length <= limit) return input;
- let [indices, deviation] = MeshoptSimplifier.simplifyWithAttributes(input, position, 3, attributes, 7,
- [0.25, 0.25, 0.25, 0.5, 0.1, 0.1, 0.1], null, limit, scale, ['ErrorAbsolute', 'LockBorder', 'Sparse']);
- if (indices.length > limit) {
- // shortcut: preserve cuts where simplification allows it; relax borders on a page that otherwise cannot fit.
- [indices, deviation] = MeshoptSimplifier.simplifyWithAttributes(input, position, 3, attributes, 7,
- [0.25, 0.25, 0.25, 0.5, 0.1, 0.1, 0.1], null, limit, scale, ['ErrorAbsolute', 'Permissive', 'Sparse']);
- }
- if (indices.length > limit) {
- // shortcut: grid simplification handles disconnected triangle soup; revisit for continuous locked borders.
- [indices, deviation] = MeshoptSimplifier.simplifySloppy(input, position, 3, null, limit, 1);
- deviation *= scale;
- }
- if (!indices.length) {
- // The cluster still has a surface and the full original remains available in its children.
- indices = input.slice(0, 3);
- deviation = scale;
- }
- if (indices.length > limit) {
- indices = indices.slice(0, limit);
- deviation = scale;
- }
- if (indices.length < input.length) deviation = Math.max(deviation, scale * 1e-5);
- error = Math.max(error, deviation);
- return indices;
- });
- return { opaque: output[0], blended: output[1], error };
-}
-
-function pack(mesh, opaque, blended, tags = null) {
- const index = new Uint32Array(opaque.length + blended.length);
- index.set(opaque);
- index.set(blended, opaque.length);
- const [remap, vertices] = MeshoptSimplifier.compactMesh(index);
- const pick = tags ? true : undefined;
- const uv = mesh.uv ? true : undefined;
- const buffer = new ArrayBuffer(pageBytes(vertices, index.length, pick, uv));
- const output = viewsOfPage(buffer, { vertices, indices: index.length, pick, uv });
- for (let old = 0; old < remap.length; old++) {
- const next = remap[old];
- if (next >= vertices) continue;
- for (let axis = 0; axis < 3; axis++) {
- output.position[next * 3 + axis] = mesh.position[old * 3 + axis];
- output.normal[next * 3 + axis] = mesh.normal[old * 3 + axis];
- }
- for (let c = 0; c < 4; c++) output.color[next * 4 + c] = mesh.color[old * 4 + c];
- if (uv) {
- output.uv[next * 2] = mesh.uv[old * 2];
- output.uv[next * 2 + 1] = mesh.uv[old * 2 + 1];
- }
- }
- output.index.set(index);
- if (tags) output.tags.set(tags);
- return { buffer, vertices, indices: index.length, opaque: opaque.length, pick, uv,
- members: tags ? [...new Set(tags)].sort((a, b) => a - b) : undefined, groups: mesh.groups };
-}
+export { focusBounds } from './src/stream/meshBuilder.js';
export async function buildMeshPages(source, destination, includeBim = true) {
- await MeshoptSimplifier.ready;
const input = openSync(source, 'r');
- let output, shapeFile;
+ let created = false;
try {
- const { origin, records, elements, metadata, review } = recordsOf(input, includeBim);
- mkdirSync(destination);
- output = openSync(join(destination, 'meshes.bin'), 'wx+');
- const pages = [];
- const shared = new Map(), shapes = [], instances = new Map();
- const weights = Uint32Array.from(records, ({ indices }) => indices / 3);
- const centres = Float64Array.from(records.flatMap(({ min, max }) => min.map((n, i) => (n + max[i]) / 2)));
- let bytes = 0;
- function write({ buffer, ...sizes }, bounds, error, children) {
- writeFileSync(output, new Uint8Array(buffer));
- pages.push({ ...bounds, ...sizes, error, children, offset: bytes });
- bytes += buffer.byteLength;
- return pages.length - 1;
- }
- const batches = new Map(), ordinary = [];
- for (const [id, record] of records.entries()) {
- if (record.shape === -1) { ordinary.push(id); continue; }
- const key = `${record.shape}/${includeBim ? record.texture : -1}/${record.rgba >>> 24 === 255}`;
- if (!batches.has(key)) batches.set(key, []);
- batches.get(key).push(id);
- }
- const leaves = splitCells(centres, weights, ordinary, PAGE_TRIANGLES);
- let roots = [];
- for (const leaf of leaves) {
- const parts = [...leaf].map((i) => records[i]);
- const mesh = assemble(parts.map((part) => partFromRecord(input, part)), elements.length > 0, true);
- roots.push(write(pack(mesh, mesh.opaque, mesh.blended, mesh.tags), aggregateBounds(parts), 0, []));
- }
- let shapeBytes = 0;
- for (const batch of batches.values()) for (const leaf of splitCells(centres, weights, batch, PAGE_TRIANGLES)) {
- const parts = [...leaf].map((id) => records[id]);
- const record = parts[0];
- let shape = shared.get(record.shape);
- if (shape === undefined) {
- const part = partFromRecord(input, record, true);
- const mesh = { ...part, color: new Uint8Array(part.color.length).fill(255) };
- const { buffer, vertices, indices, uv } = pack(mesh, part.index, []);
- shapeFile ??= openSync(join(destination, 'shapes.bin'), 'wx');
- writeFileSync(shapeFile, new Uint8Array(buffer));
- shape = shapes.length;
- shapes.push({ vertices, indices, uv, offset: shapeBytes });
- shapeBytes += buffer.byteLength;
- shared.set(record.shape, shape);
- }
- const { vertices, indices, uv } = shapes[shape];
- const buffer = new ArrayBuffer(parts.length * INSTANCE_BYTES), data = new DataView(buffer);
- for (const [i, part] of parts.entries()) {
- const at = i * INSTANCE_BYTES;
- for (let axis = 0; axis < 3; axis++) data.setFloat32(at + 4 * axis, part.shift[axis], true);
- data.setUint32(at + 12, part.element ?? 0, true);
- new Uint8Array(buffer, at + 16, 4).set(linearColor(part.rgba));
- }
- const pick = elements.length > 0 ? true : undefined;
- const members = pick ? [...new Set(parts.map((part) => part.element))].sort((a, b) => a - b) : undefined;
- const texture = includeBim && record.texture >= 0 ? record.texture : undefined;
- const opaque = record.rgba >>> 24 === 255 ? indices : 0;
- const id = write({ buffer, vertices, indices, uv, opaque, pick, members, shape, count: parts.length,
- groups: [{ count: indices, closed: record.solid || undefined, texture }] }, aggregateBounds(parts), 0, []);
- roots.push(id);
- instances.set(id, parts);
- }
- if (instances.size && roots.length > 1) {
- const pageCentres = Float64Array.from(pages.flatMap(({ min, max }) => min.map((n, i) => (n + max[i]) / 2)));
- roots = splitCells(pageCentres, new Uint32Array(pages.length).fill(1), roots, 1).map((ids) => ids[0]);
- }
- console.log(`${roots.length} full-resolution mesh pages`);
- const triangles = weights.reduce((sum, n) => sum + n, 0);
- while (roots.length > 48 || roots.reduce((sum, id) => sum + residentBytes(pages[id], shapes), 0) > ROOT_BYTES / 2) {
- const next = [];
- // Separate instance batches can push a level just over the root count limit.
- const fanout = instances.size && roots.length > 48 ? Math.min(4, Math.ceil(roots.length / 48)) : 4;
- for (let i = 0; i < roots.length; i += fanout) {
- const children = roots.slice(i, i + fanout);
- if (children.length === 1) { next.push(children[0]); continue; }
- const group = children.map((id) => pages[id]);
- const bounds = aggregateBounds(group);
- const mesh = assemble(children.flatMap((id) => {
- const page = pages[id];
- const copies = instances.get(id);
- return copies ? copies.map((record) => partFromRecord(input, record))
- : [{ ...viewsOfPage(read(output, sizeOfPage(page), page.offset), page), opaque: page.opaque }];
- }));
- const limit = Math.min(PAGE_TRIANGLES * 3 - 3, Math.max(6, (mesh.opaque.length + mesh.blended.length) / 5));
- const { opaque, blended, error } = reducedIndices(mesh, limit, bounds);
- next.push(write(pack(mesh, opaque, blended), bounds, error + Math.max(...group.map((p) => p.error)), children));
- }
- roots = next;
- console.log(`${roots.length} pages at the next level`);
- }
- const bounds = aggregateBounds(records);
- let propertyBytes = 0;
- const props = metadata.size ? openSync(join(destination, 'elements.bin'), 'wx') : null;
- try {
- for (const element of elements) {
- if (!element.min) Object.assign(element, { min: [0, 0, 0], max: [0, 0, 0], noGeometry: true });
- const record = metadata.get(element.id);
- element.offset = propertyBytes;
- element.size = record?.length ?? 0;
- if (record) {
- const encoded = new Uint8Array(read(input, record.length, record.at));
- const meta = JSON.parse(Buffer.from(encoded.buffer).toString('utf-8'));
- if (meta?.id !== element.id) throw new Error('Mismatched element ID in properties.');
- for (const field of ELEMENT_FIELDS) if (typeof meta[field] === 'string' && meta[field]) element[field] = meta[field];
- writeFileSync(props, encoded);
- }
- propertyBytes += element.size;
+ return await buildMeshPagesFromSource({
+ length: fstatSync(input).size,
+ read: (buffer, offset) => readSync(input, buffer, 0, buffer.length, offset),
+ }, (name) => {
+ if (!created) {
+ mkdirSync(destination);
+ created = true;
}
- } finally { if (props !== null) closeSync(props); }
- const manifest = validateMeshPages({ format: MESH_FORMAT, origin, ...bounds, focus: focusBounds(records, bounds), pages, roots, bytes, triangles,
- ...(shapes.length ? { shapes, shapeBytes } : {}),
- ...((elements.length || review) ? { elements, propertyBytes } : {}), ...(review ? { review } : {}) });
- writeFileSync(join(destination, 'manifest.json'), JSON.stringify(manifest), { flag: 'wx' });
- console.log(`${triangles} triangles, ${pages.length} total pages, ${bytes} bytes`);
- return manifest;
+ const file = openSync(join(destination, name), 'wx+');
+ return {
+ read: (buffer, offset) => readSync(file, buffer, 0, buffer.length, offset),
+ write: (buffer) => writeFileSync(file, buffer),
+ close: () => closeSync(file),
+ };
+ }, includeBim);
} finally {
- if (shapeFile !== undefined) closeSync(shapeFile);
- if (output !== undefined) closeSync(output);
closeSync(input);
}
}
diff --git a/src/IOViewer/Viewer/src/stream/meshBuilder.js b/src/IOViewer/Viewer/src/stream/meshBuilder.js
new file mode 100644
index 0000000..a37f757
--- /dev/null
+++ b/src/IOViewer/Viewer/src/stream/meshBuilder.js
@@ -0,0 +1,412 @@
+import { MeshoptSimplifier } from 'meshoptimizer/simplifier';
+import { splitCells, unitNormals } from '../engine/chunks.js';
+import { ELEMENT_FIELDS, INSTANCE_BYTES, isBounds, isPoint, MAX_ELEMENT_BYTES, MESH_FORMAT, MESH_MANIFEST_BYTES, PAGE_TRIANGLES, ROOT_BYTES, pageBytes, residentBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './meshPages.js';
+import { validateReviewMeta } from '../data.js';
+
+const HEADER = 28, RECORD = 40;
+const utf8 = new TextDecoder('utf-8', { ignoreBOM: true });
+const channel = Array.from({ length: 256 }, (_, i) => {
+ const x = i / 255;
+ return Math.round(255 * (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4));
+});
+const linearColor = (color) => [channel[color & 255], channel[(color >>> 8) & 255], channel[(color >>> 16) & 255], color >>> 24];
+
+function fill(source, target, offset, error) {
+ for (let at = 0; at < target.length;) {
+ const count = source.read(target.subarray(at), offset + at);
+ if (!Number.isInteger(count) || count <= 0 || count > target.length - at) throw new Error(error);
+ at += count;
+ }
+}
+
+function read(source, bytes, offset) {
+ const buffer = new ArrayBuffer(bytes);
+ fill(source, new Uint8Array(buffer), offset, 'Truncated geometry source.');
+ return buffer;
+}
+
+function recordsOf(source, includeBim) {
+ const header = new DataView(read(source, HEADER, 0));
+ const version = header.getUint32(0, true);
+ const sharedFormat = version === 0x34534d49;
+ const reviewFormat = sharedFormat || version === 0x33534d49;
+ const annotated = reviewFormat || version === 0x32534d49;
+ if (!annotated && version !== 0x31534d49) throw new Error('Expected an IOViewer .ivmesh source.');
+ const origin = [4, 12, 20].map((i) => header.getFloat64(i, true));
+ if (!isPoint(origin)) throw new Error('Invalid source origin.');
+ const records = [];
+ const size = source.length;
+ const start = HEADER + (annotated ? 8 : 0), recordSize = RECORD + (sharedFormat ? 36 : reviewFormat ? 16 : annotated ? 8 : 0);
+ const end = annotated ? Number(new DataView(read(source, 8, HEADER)).getBigInt64(0, true)) : size;
+ if (!Number.isSafeInteger(end) || end < start || end > size) throw new Error('Invalid geometry directory offset.');
+ const meta = new Float32Array(recordSize / 4), data = new Uint8Array(meta.buffer), counts = new Uint32Array(meta.buffer);
+ const recordView = new DataView(meta.buffer);
+ const slots = new Map(), elements = [], prototypes = new Map();
+ let review, propertiesStart = end, textureCount = 0;
+ if (reviewFormat) {
+ const length = new DataView(read(source, 4, end)).getUint32(0, true);
+ propertiesStart += 4 + length;
+ if (!length || length > MESH_MANIFEST_BYTES || propertiesStart > size) throw new Error('Invalid cluster review size.');
+ if (includeBim) {
+ const { elements: sourceElements, ...fields } = JSON.parse(utf8.decode(read(source, length, end + 4)));
+ validateReviewMeta({ ...fields, elements: sourceElements });
+ review = fields;
+ textureCount = fields.textures?.length ?? 0;
+ for (const input of sourceElements) {
+ const id = String(input.id);
+ if (!/^-?\d+$/.test(id) || slots.has(id)) throw new Error('Invalid review element ID.');
+ slots.set(id, elements.length);
+ elements.push({ ...Object.fromEntries(Object.entries(input).filter(([, value]) => value != null)), id });
+ }
+ }
+ }
+ for (let offset = start; offset < end;) {
+ const recordOffset = offset;
+ if (offset + recordSize > end) throw new Error('Truncated mesh record.');
+ fill(source, data, offset, 'Truncated mesh record.');
+ const min = [...meta.subarray(0, 3)], max = [...meta.subarray(3, 6)];
+ const [vertices, indices, rgba, normals] = counts.subarray(6);
+ const texture = reviewFormat ? recordView.getInt32(RECORD + 8, true) : -1;
+ const flags = reviewFormat ? recordView.getUint32(RECORD + 12, true) : 0;
+ const uv = sharedFormat ? Boolean(flags & 2) : texture >= 0;
+ const shape = sharedFormat ? Number(recordView.getBigInt64(RECORD + 16, true)) : -1;
+ const shift = shape >= 0 ? [...meta.subarray((RECORD + 24) / 4)] : undefined;
+ const bytes = vertices * (12 * (1 + normals) + (uv ? 8 : 0)) + indices * 4;
+ offset += recordSize;
+ const first = shape === recordOffset;
+ const prototype = prototypes.get(shape);
+ const inline = first || shape === -1;
+ if (!isBounds({ min, max }) || !vertices || vertices > indices || !indices || indices % 3 || indices > PAGE_TRIANGLES * 3
+ || normals > 1 || flags > (sharedFormat ? 3 : 1) || texture < -1 || (texture >= 0 && !uv)
+ || (includeBim && texture >= textureCount) || (inline && bytes > end - offset)
+ || (shape !== -1 && (!isPoint(shift) || (!first && (!prototype || prototype.vertices !== vertices
+ || prototype.indices !== indices || prototype.normals !== normals || prototype.flags !== flags))))) throw new Error('Invalid mesh record.');
+ if (first) prototypes.set(shape, { offset, vertices, indices, normals, flags });
+ let element;
+ if (annotated && includeBim) {
+ const id = recordView.getBigInt64(RECORD, true).toString();
+ element = slots.get(id);
+ if (element === undefined) {
+ element = elements.length;
+ slots.set(id, element);
+ elements.push({ id });
+ }
+ const bounds = elements[element];
+ if (!bounds.min) Object.assign(bounds, { min: [...min], max: [...max] });
+ else {
+ for (let i = 0; i < 3; i++) {
+ bounds.min[i] = Math.min(bounds.min[i], min[i]);
+ bounds.max[i] = Math.max(bounds.max[i], max[i]);
+ }
+ }
+ }
+ records.push({ min, max, vertices, indices, rgba, normals, offset: inline ? offset : prototype.offset, bytes, element, texture,
+ solid: Boolean(flags & 1), uv, includeBim, shape, shift });
+ if (inline) offset += bytes;
+ }
+ if (!records.length) throw new Error('The source contains no triangle geometry.');
+ const metadata = new Map();
+ for (let at = propertiesStart; includeBim && at < size;) {
+ const prefix = new DataView(read(source, 12, at));
+ const id = prefix.getBigInt64(0, true).toString(), length = prefix.getUint32(8, true);
+ at += 12;
+ if (!slots.has(id) || metadata.has(id) || !length || length > MAX_ELEMENT_BYTES || at + length > size) throw new Error('Invalid element property record.');
+ metadata.set(id, { at, length });
+ at += length;
+ }
+ return { origin, records, elements, metadata, review };
+}
+
+function aggregateBounds(children) {
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
+ for (const child of children) for (let i = 0; i < 3; i++) {
+ min[i] = Math.min(min[i], child.min[i]);
+ max[i] = Math.max(max[i], child.max[i]);
+ }
+ return { min, max };
+}
+
+// The initial camera fits the middle 98% of triangle-weighted record centres. The full bounds drive Fit All.
+export function focusBounds(records, bounds) {
+ const total = records.reduce((sum, record) => sum + record.indices, 0);
+ const min = [], max = [];
+ for (let axis = 0; axis < 3; axis++) {
+ const centre = (entry) => (entry.min[axis] + entry.max[axis]) / 2;
+ const ordered = [...records].sort((a, b) => centre(a) - centre(b));
+ let weight = 0, low, high;
+ for (const record of ordered) {
+ weight += record.indices;
+ if (low === undefined && weight >= total * 0.01) low = centre(record);
+ if (weight >= total * 0.99) { high = centre(record); break; }
+ }
+ min.push(low < high ? low : bounds.min[axis]);
+ max.push(low < high ? high : bounds.max[axis]);
+ }
+ return { min, max };
+}
+
+function assemble(parts, tagged = false, leaf = false) {
+ const vertices = parts.reduce((sum, part) => sum + part.position.length / 3, 0);
+ const position = new Float32Array(vertices * 3), normal = new Int16Array(vertices * 3), color = new Uint8Array(vertices * 4);
+ const uv = leaf && parts.some((part) => part.uv) ? new Float32Array(vertices * 2) : null;
+ const groups = leaf && parts.some((part) => part.solid || part.texture !== undefined);
+ const solidGroups = [], blendedGroups = [];
+ const opaque = [], blended = [];
+ const opaqueTags = [], blendedTags = [];
+ if (groups) parts.sort((a, b) => (a.texture ?? -1) - (b.texture ?? -1) || Number(a.solid) - Number(b.solid));
+ let at = 0;
+ for (const part of parts) {
+ position.set(part.position, at * 3);
+ normal.set(part.normal, at * 3);
+ color.set(part.color, at * 4);
+ if (part.uv && uv) uv.set(part.uv, at * 2);
+ if (groups) {
+ const entries = part.opaque ? solidGroups : blendedGroups;
+ const previous = entries.at(-1);
+ const closed = part.solid || undefined, texture = part.texture;
+ if (previous && previous.closed === closed && previous.texture === texture) previous.count += part.index.length;
+ else entries.push({ count: part.index.length, closed, texture });
+ }
+ for (let j = 0; j < part.index.length; j++) {
+ const solid = j < part.opaque;
+ (solid ? opaque : blended).push(at + part.index[j]);
+ if (tagged && j % 3 === 0) (solid ? opaqueTags : blendedTags).push(part.element);
+ }
+ at += part.position.length / 3;
+ }
+ return { position, normal, color, uv, groups: groups ? [...solidGroups, ...blendedGroups] : undefined,
+ opaque: Uint32Array.from(opaque), blended: Uint32Array.from(blended),
+ tags: tagged ? Uint32Array.from([...opaqueTags, ...blendedTags]) : null };
+}
+
+function partFromRecord(source, record, local = false) {
+ const buffer = read(source, record.bytes, record.offset), n = record.vertices * 3;
+ const position = new Float32Array(buffer, 0, n);
+ const index = new Uint32Array(buffer, n * 4 * (1 + record.normals), record.indices);
+ if (index.some((i) => i >= record.vertices) || position.some((n) => !Number.isFinite(n))) throw new Error('Invalid mesh positions or indices.');
+ const normals = record.normals ? new Float32Array(buffer, n * 4, n) : unitNormals({ positions: position, indices: index });
+ if (normals.some((n) => !Number.isFinite(n))) throw new Error('Invalid mesh normal.');
+ const normal = Int16Array.from(normals, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 32767));
+ const color = new Uint8Array(record.vertices * 4), a = record.rgba >>> 24;
+ const rgba = linearColor(record.rgba);
+ for (let i = 0; i < color.length; i += 4) color.set(rgba, i);
+ const texture = record.includeBim && record.texture >= 0 ? record.texture : undefined;
+ const uv = record.uv && (texture !== undefined || local)
+ ? new Float32Array(buffer, index.byteOffset + index.byteLength, record.vertices * 2) : null;
+ if (uv?.some((value) => !Number.isFinite(value))) throw new Error('Invalid mesh UV.');
+ if (!local && record.shift) for (let i = 0; i < position.length; i++) position[i] += record.shift[i % 3];
+ return { position, normal, color, index, uv, texture, solid: record.solid,
+ opaque: a === 255 ? index.length : 0, element: record.element };
+}
+
+function reducedIndices(mesh, target, bounds) {
+ const { position, normal, color } = mesh;
+ const scale = Math.max(...bounds.max.map((n, i) => n - bounds.min[i]));
+ const attributes = new Float32Array(position.length / 3 * 7);
+ for (let i = 0, j = 0; j < color.length; i += 7, j += 4) {
+ attributes[i] = color[j] / 255;
+ attributes[i + 1] = color[j + 1] / 255;
+ attributes[i + 2] = color[j + 2] / 255;
+ attributes[i + 3] = color[j + 3] / 255;
+ for (let a = 0; a < 3; a++) attributes[i + 4 + a] = normal[j / 4 * 3 + a] / 32767;
+ }
+ let error = 0;
+ const n = mesh.opaque.length + mesh.blended.length;
+ const output = ['opaque', 'blended'].map((kind) => {
+ const input = mesh[kind];
+ if (!input.length) return input;
+ const limit = Math.max(3, Math.floor(target * input.length / n / 3) * 3);
+ if (input.length <= limit) return input;
+ let [indices, deviation] = MeshoptSimplifier.simplifyWithAttributes(input, position, 3, attributes, 7,
+ [0.25, 0.25, 0.25, 0.5, 0.1, 0.1, 0.1], null, limit, scale, ['ErrorAbsolute', 'LockBorder', 'Sparse']);
+ if (indices.length > limit) {
+ // shortcut: preserve cuts where simplification allows it; relax borders on a page that otherwise cannot fit.
+ [indices, deviation] = MeshoptSimplifier.simplifyWithAttributes(input, position, 3, attributes, 7,
+ [0.25, 0.25, 0.25, 0.5, 0.1, 0.1, 0.1], null, limit, scale, ['ErrorAbsolute', 'Permissive', 'Sparse']);
+ }
+ if (indices.length > limit) {
+ // shortcut: grid simplification handles disconnected triangle soup; revisit for continuous locked borders.
+ [indices, deviation] = MeshoptSimplifier.simplifySloppy(input, position, 3, null, limit, 1);
+ deviation *= scale;
+ }
+ if (!indices.length) {
+ // The cluster still has a surface and the full original remains available in its children.
+ indices = input.slice(0, 3);
+ deviation = scale;
+ }
+ if (indices.length > limit) {
+ indices = indices.slice(0, limit);
+ deviation = scale;
+ }
+ if (indices.length < input.length) deviation = Math.max(deviation, scale * 1e-5);
+ error = Math.max(error, deviation);
+ return indices;
+ });
+ return { opaque: output[0], blended: output[1], error };
+}
+
+function pack(mesh, opaque, blended, tags = null) {
+ const index = new Uint32Array(opaque.length + blended.length);
+ index.set(opaque);
+ index.set(blended, opaque.length);
+ const [remap, vertices] = MeshoptSimplifier.compactMesh(index);
+ const pick = tags ? true : undefined;
+ const uv = mesh.uv ? true : undefined;
+ const buffer = new ArrayBuffer(pageBytes(vertices, index.length, pick, uv));
+ const output = viewsOfPage(buffer, { vertices, indices: index.length, pick, uv });
+ for (let old = 0; old < remap.length; old++) {
+ const next = remap[old];
+ if (next >= vertices) continue;
+ for (let axis = 0; axis < 3; axis++) {
+ output.position[next * 3 + axis] = mesh.position[old * 3 + axis];
+ output.normal[next * 3 + axis] = mesh.normal[old * 3 + axis];
+ }
+ for (let c = 0; c < 4; c++) output.color[next * 4 + c] = mesh.color[old * 4 + c];
+ if (uv) {
+ output.uv[next * 2] = mesh.uv[old * 2];
+ output.uv[next * 2 + 1] = mesh.uv[old * 2 + 1];
+ }
+ }
+ output.index.set(index);
+ if (tags) output.tags.set(tags);
+ return { buffer, vertices, indices: index.length, opaque: opaque.length, pick, uv,
+ members: tags ? [...new Set(tags)].sort((a, b) => a - b) : undefined, groups: mesh.groups };
+}
+
+export async function buildMeshPagesFromSource(input, createFile, includeBim = true, onProgress) {
+ await MeshoptSimplifier.ready;
+ let output, shapeFile;
+ try {
+ const { origin, records, elements, metadata, review } = recordsOf(input, includeBim);
+ output = createFile('meshes.bin');
+ const pages = [];
+ const shared = new Map(), shapes = [], instances = new Map();
+ const weights = Uint32Array.from(records, ({ indices }) => indices / 3);
+ const triangles = weights.reduce((sum, n) => sum + n, 0);
+ const centres = Float64Array.from(records.flatMap(({ min, max }) => min.map((n, i) => (n + max[i]) / 2)));
+ let bytes = 0;
+ let writtenTriangles = 0;
+ function write({ buffer, ...sizes }, bounds, error, children) {
+ output.write(new Uint8Array(buffer));
+ pages.push({ ...bounds, ...sizes, error, children, offset: bytes });
+ bytes += buffer.byteLength;
+ if (onProgress && children.length === 0) {
+ writtenTriangles += sizes.indices / 3 * (sizes.count ?? 1);
+ onProgress({ phase: 'triangles', completed: writtenTriangles, total: triangles });
+ }
+ return pages.length - 1;
+ }
+ const batches = new Map(), ordinary = [];
+ for (const [id, record] of records.entries()) {
+ if (record.shape === -1) { ordinary.push(id); continue; }
+ const key = `${record.shape}/${includeBim ? record.texture : -1}/${record.rgba >>> 24 === 255}`;
+ if (!batches.has(key)) batches.set(key, []);
+ batches.get(key).push(id);
+ }
+ const leaves = splitCells(centres, weights, ordinary, PAGE_TRIANGLES);
+ let roots = [];
+ onProgress?.({ phase: 'triangles', completed: 0, total: triangles });
+ for (const leaf of leaves) {
+ const parts = [...leaf].map((i) => records[i]);
+ const mesh = assemble(parts.map((part) => partFromRecord(input, part)), elements.length > 0, true);
+ roots.push(write(pack(mesh, mesh.opaque, mesh.blended, mesh.tags), aggregateBounds(parts), 0, []));
+ }
+ let shapeBytes = 0;
+ for (const batch of batches.values()) for (const leaf of splitCells(centres, weights, batch, PAGE_TRIANGLES)) {
+ const parts = [...leaf].map((id) => records[id]);
+ const record = parts[0];
+ let shape = shared.get(record.shape);
+ if (shape === undefined) {
+ const part = partFromRecord(input, record, true);
+ const mesh = { ...part, color: new Uint8Array(part.color.length).fill(255) };
+ const { buffer, vertices, indices, uv } = pack(mesh, part.index, []);
+ shapeFile ??= createFile('shapes.bin');
+ shapeFile.write(new Uint8Array(buffer));
+ shape = shapes.length;
+ shapes.push({ vertices, indices, uv, offset: shapeBytes });
+ shapeBytes += buffer.byteLength;
+ shared.set(record.shape, shape);
+ }
+ const { vertices, indices, uv } = shapes[shape];
+ const buffer = new ArrayBuffer(parts.length * INSTANCE_BYTES), data = new DataView(buffer);
+ for (const [i, part] of parts.entries()) {
+ const at = i * INSTANCE_BYTES;
+ for (let axis = 0; axis < 3; axis++) data.setFloat32(at + 4 * axis, part.shift[axis], true);
+ data.setUint32(at + 12, part.element ?? 0, true);
+ new Uint8Array(buffer, at + 16, 4).set(linearColor(part.rgba));
+ }
+ const pick = elements.length > 0 ? true : undefined;
+ const members = pick ? [...new Set(parts.map((part) => part.element))].sort((a, b) => a - b) : undefined;
+ const texture = includeBim && record.texture >= 0 ? record.texture : undefined;
+ const opaque = record.rgba >>> 24 === 255 ? indices : 0;
+ const id = write({ buffer, vertices, indices, uv, opaque, pick, members, shape, count: parts.length,
+ groups: [{ count: indices, closed: record.solid || undefined, texture }] }, aggregateBounds(parts), 0, []);
+ roots.push(id);
+ instances.set(id, parts);
+ }
+ if (instances.size && roots.length > 1) {
+ const pageCentres = Float64Array.from(pages.flatMap(({ min, max }) => min.map((n, i) => (n + max[i]) / 2)));
+ roots = splitCells(pageCentres, new Uint32Array(pages.length).fill(1), roots, 1).map((ids) => ids[0]);
+ }
+ console.log(`${roots.length} full-resolution mesh pages`);
+ let level = 0;
+ while (roots.length > 48 || roots.reduce((sum, id) => sum + residentBytes(pages[id], shapes), 0) > ROOT_BYTES / 2) {
+ const next = [];
+ // Separate instance batches can push a level just over the root count limit.
+ const fanout = instances.size && roots.length > 48 ? Math.min(4, Math.ceil(roots.length / 48)) : 4;
+ const total = Math.ceil(roots.length / fanout);
+ level++;
+ for (let i = 0; i < roots.length; i += fanout) {
+ onProgress?.({ phase: 'overview', completed: next.length, total, level });
+ const children = roots.slice(i, i + fanout);
+ if (children.length === 1) { next.push(children[0]); continue; }
+ const group = children.map((id) => pages[id]);
+ const bounds = aggregateBounds(group);
+ const mesh = assemble(children.flatMap((id) => {
+ const page = pages[id];
+ const copies = instances.get(id);
+ return copies ? copies.map((record) => partFromRecord(input, record))
+ : [{ ...viewsOfPage(read(output, sizeOfPage(page), page.offset), page), opaque: page.opaque }];
+ }));
+ const limit = Math.min(PAGE_TRIANGLES * 3 - 3, Math.max(6, (mesh.opaque.length + mesh.blended.length) / 5));
+ const { opaque, blended, error } = reducedIndices(mesh, limit, bounds);
+ next.push(write(pack(mesh, opaque, blended), bounds, error + Math.max(...group.map((p) => p.error)), children));
+ }
+ onProgress?.({ phase: 'overview', completed: next.length, total, level });
+ roots = next;
+ console.log(`${roots.length} pages at the next level`);
+ }
+ const bounds = aggregateBounds(records);
+ let propertyBytes = 0;
+ const props = metadata.size ? createFile('elements.bin') : null;
+ try {
+ if (elements.length) onProgress?.({ phase: 'properties', completed: 0, total: elements.length });
+ for (const [index, element] of elements.entries()) {
+ if (!element.min) Object.assign(element, { min: [0, 0, 0], max: [0, 0, 0], noGeometry: true });
+ const record = metadata.get(element.id);
+ element.offset = propertyBytes;
+ element.size = record?.length ?? 0;
+ if (record) {
+ const encoded = new Uint8Array(read(input, record.length, record.at));
+ const meta = JSON.parse(utf8.decode(encoded));
+ if (meta?.id !== element.id) throw new Error('Mismatched element ID in properties.');
+ for (const field of ELEMENT_FIELDS) if (typeof meta[field] === 'string' && meta[field]) element[field] = meta[field];
+ props.write(encoded);
+ }
+ propertyBytes += element.size;
+ onProgress?.({ phase: 'properties', completed: index + 1, total: elements.length });
+ }
+ } finally { props?.close(); }
+ const manifest = validateMeshPages({ format: MESH_FORMAT, origin, ...bounds, focus: focusBounds(records, bounds), pages, roots, bytes, triangles,
+ ...(shapes.length ? { shapes, shapeBytes } : {}),
+ ...((elements.length || review) ? { elements, propertyBytes } : {}), ...(review ? { review } : {}) });
+ const manifestFile = createFile('manifest.json');
+ try { manifestFile.write(new TextEncoder().encode(JSON.stringify(manifest))); }
+ finally { manifestFile.close(); }
+ console.log(`${triangles} triangles, ${pages.length} total pages, ${bytes} bytes`);
+ return manifest;
+ } finally {
+ shapeFile?.close();
+ output?.close();
+ }
+}
diff --git a/src/IOViewer/Viewer/src/stream/meshLod.js b/src/IOViewer/Viewer/src/stream/meshLod.js
index 3f0d406..d5c868b 100644
--- a/src/IOViewer/Viewer/src/stream/meshLod.js
+++ b/src/IOViewer/Viewer/src/stream/meshLod.js
@@ -7,6 +7,7 @@ import { MESH_BUDGET, MIB } from './manifest.js';
import { readPlacements, residentBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './meshPages.js';
import { mountMeshTools } from './meshTools.js';
import { meshScene } from './meshScene.js';
+import { fetchMeshResource } from './meshSource.js';
import { SectionCaps } from '../tools/sectionCaps.js';
const canvas = document.querySelector('canvas');
@@ -27,7 +28,7 @@ function show(text) {
async function fetchRange(path, bytes, signal) {
const start = profile && performance.now();
- const response = await fetch(path, { cache: 'no-store', signal });
+ const response = await fetchMeshResource(path, { cache: 'no-store', signal });
if (!response.ok || Number(response.headers.get('content-length')) !== bytes) throw new Error(`${path} failed (${response.status}).`);
const data = await response.arrayBuffer();
if (profile) profile.fetch(performance.now() - start, data.byteLength);
@@ -45,7 +46,7 @@ const box = ({ min, max }) => new THREE.Box3(new THREE.Vector3(...min), new THRE
const BASE_ERROR = 1.5, MERGE_ERROR = 1, MOVE_SETTLE = 180;
try {
- const response = await fetch('/manifest.json');
+ const response = await fetchMeshResource('/manifest.json');
if (!response.ok) throw new Error(`Manifest: HTTP ${response.status}.`);
const manifest = validateMeshPages(await response.json());
if (manifest.review?.title) document.title = manifest.review.title;
@@ -85,7 +86,7 @@ async function start(manifest, context) {
let rasterScale = 1, lastScaleChange = -Infinity;
let drawn = new Set();
if (manifest.overview) {
- const response = await fetch('/overview.bin', { cache: 'no-store' });
+ const response = await fetchMeshResource('/overview.bin', { cache: 'no-store' });
if (!response.ok || Number(response.headers.get('content-length')) !== manifest.overview) throw new Error('Invalid overview size.');
const overview = await response.arrayBuffer();
if (overview.byteLength !== manifest.overview) throw new Error('Truncated overview.');
diff --git a/src/IOViewer/Viewer/src/stream/meshSource.js b/src/IOViewer/Viewer/src/stream/meshSource.js
new file mode 100644
index 0000000..3866445
--- /dev/null
+++ b/src/IOViewer/Viewer/src/stream/meshSource.js
@@ -0,0 +1,51 @@
+import { MESH_MANIFEST_BYTES, sizeOfPage, validateMeshPages } from './meshPages.js';
+
+export function fetchMeshResource(path, options) {
+ const local = globalThis.IOVIEWER_MESH_SOURCE;
+ return local ? local.fetch(path, options) : fetch(path, options);
+}
+
+// openFile returns a File or Blob from private storage. Page payloads stay in storage until requested.
+export async function openMeshPackage(openFile) {
+ const manifestFile = await openFile('manifest.json');
+ if (manifestFile.size > MESH_MANIFEST_BYTES) throw new Error('Manifest exceeds its size limit.');
+ const manifest = validateMeshPages(JSON.parse(await manifestFile.text()));
+ const files = new Map();
+
+ async function slice(name, length, offset, size, signal) {
+ if (!files.has(name)) files.set(name, Promise.resolve().then(() => openFile(name)).catch((error) => {
+ files.delete(name);
+ throw error;
+ }));
+ const file = await files.get(name);
+ signal?.throwIfAborted();
+ if (file.size !== length || offset + size > file.size) throw new Error('Invalid mesh data file size.');
+ return new Response(file.slice(offset, offset + size), { headers: { 'Content-Length': String(size) } });
+ }
+
+ return {
+ async fetch(path, { signal } = {}) {
+ signal?.throwIfAborted();
+ if (path === '/manifest.json') return new Response(manifestFile);
+ if (path === '/overview.bin' && manifest.overview)
+ return slice('overview.bin', manifest.overview, 0, manifest.overview, signal);
+ const match = /^\/(pages|shapes|elements)\/(0|[1-9]\d*)$/.exec(path);
+ if (match) {
+ const id = Number(match[2]);
+ if (match[1] === 'pages' && manifest.pages[id]) {
+ const page = manifest.pages[id];
+ return slice('meshes.bin', manifest.bytes, page.offset, sizeOfPage(page), signal);
+ }
+ if (match[1] === 'shapes' && manifest.shapes?.[id]) {
+ const shape = manifest.shapes[id];
+ return slice('shapes.bin', manifest.shapeBytes, shape.offset, sizeOfPage(shape), signal);
+ }
+ if (match[1] === 'elements' && manifest.elements?.[id]?.size) {
+ const element = manifest.elements[id];
+ return slice('elements.bin', manifest.propertyBytes, element.offset, element.size, signal);
+ }
+ }
+ return new Response(null, { status: 404 });
+ },
+ };
+}
diff --git a/src/IOViewer/Viewer/src/stream/meshStorage.js b/src/IOViewer/Viewer/src/stream/meshStorage.js
new file mode 100644
index 0000000..b9cbd84
--- /dev/null
+++ b/src/IOViewer/Viewer/src/stream/meshStorage.js
@@ -0,0 +1,57 @@
+import { buildMeshPagesFromSource } from './meshBuilder.js';
+
+const WINDOW_BYTES = 64 * 1024;
+
+// Called in a dedicated worker. The caller owns the empty temporary output directory.
+export async function buildLocalMeshPackage(file, directory, includeBim = true, onProgress) {
+ const reader = new FileReaderSync();
+ let windowStart = -1, bytes;
+ const source = {
+ length: file.size,
+ read(target, offset) {
+ if (offset >= file.size || target.length === 0) return 0;
+ const start = Math.floor(offset / WINDOW_BYTES) * WINDOW_BYTES;
+ if (start !== windowStart) {
+ bytes = new Uint8Array(reader.readAsArrayBuffer(file.slice(start, start + WINDOW_BYTES)));
+ windowStart = start;
+ }
+ const inside = offset - start;
+ const part = bytes.subarray(inside, inside + target.length);
+ target.set(part);
+ return part.length;
+ },
+ };
+
+ // OPFS acquisition is asynchronous. The mesh builder only uses synchronous reads and writes.
+ const handles = new Map();
+ try {
+ for (const name of ['meshes.bin', 'shapes.bin', 'elements.bin', 'manifest.json']) {
+ const file = await directory.getFileHandle(name, { create: true });
+ const handle = await file.createSyncAccessHandle();
+ handles.set(name, handle);
+ if (handle.getSize() !== 0) throw new Error('Mesh output must be empty.');
+ }
+ return await buildMeshPagesFromSource(source, (name) => {
+ const handle = handles.get(name);
+ let end = 0;
+ return {
+ read: (target, offset) => handle.read(target, { at: offset }),
+ write(data) {
+ let written = 0;
+ while (written < data.length) {
+ const count = handle.write(data.subarray(written), { at: end + written });
+ if (count <= 0) throw new Error('Could not write the local mesh package.');
+ written += count;
+ }
+ end += written;
+ },
+ close() {
+ handle.close();
+ handles.delete(name);
+ },
+ };
+ }, includeBim, onProgress);
+ } finally {
+ for (const handle of handles.values()) handle.close();
+ }
+}
diff --git a/src/IOViewer/Viewer/src/stream/meshTools.js b/src/IOViewer/Viewer/src/stream/meshTools.js
index a6046db..85292a7 100644
--- a/src/IOViewer/Viewer/src/stream/meshTools.js
+++ b/src/IOViewer/Viewer/src/stream/meshTools.js
@@ -16,6 +16,7 @@ import { mountViews } from '../ui/viewsPanel.js';
import { mountClashes } from '../ui/clashesPanel.js';
import { mountLinks } from '../ui/linksPanel.js';
import { mountTimeliner } from '../ui/timeliner.js';
+import { fetchMeshResource } from './meshSource.js';
import { meshSnapCandidates } from './meshSnap.js';
// Trace the original leaves independently of the cut on screen. The nearest hit gives the same element at every LOD.
@@ -101,7 +102,7 @@ export function mountMeshTools({ manifest, roots, nodes, bounds, world, controls
const data = { meta, async loadProperties(index, signal) {
const entry = elements[index];
if (!entry.size) return null;
- const response = await fetch(`/elements/${index}`, { signal });
+ const response = await fetchMeshResource(`/elements/${index}`, { signal });
if (!response.ok || Number(response.headers.get('content-length')) !== entry.size) throw new Error('Invalid element response.');
const loaded = await response.json();
if (loaded?.id !== entry.id || !loaded.properties || typeof loaded.properties !== 'object' || Array.isArray(loaded.properties)
diff --git a/src/IOViewer/Viewer/test/unit/meshPages.test.js b/src/IOViewer/Viewer/test/unit/meshPages.test.js
index 25504c4..8e0ced3 100644
--- a/src/IOViewer/Viewer/test/unit/meshPages.test.js
+++ b/src/IOViewer/Viewer/test/unit/meshPages.test.js
@@ -1,12 +1,21 @@
import assert from 'node:assert/strict';
-import { mkdtemp, readFile, rm, rmdir, writeFile } from 'node:fs/promises';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { basename, dirname, join, resolve } from 'node:path';
import test from 'node:test';
import { buildMeshPages, focusBounds } from '../../build-mesh-pages.js';
+import { buildMeshPagesFromSource } from '../../src/stream/meshBuilder.js';
import { INSTANCE_BYTES, MESH_FORMAT, pageBytes, readPlacements, validateMeshPages, viewsOfPage } from '../../src/stream/meshPages.js';
+import { openMeshPackage } from '../../src/stream/meshSource.js';
const bounds = { min: [0, 0, 0], max: [1, 1, 0] };
+const fixtureRoot = resolve(tmpdir());
+
+async function removeFixture(folder) {
+ assert.equal(dirname(resolve(folder)), fixtureRoot);
+ assert.match(basename(folder), /^ioviewer-(mesh|bim)-pages-/);
+ await rm(folder, { recursive: true, force: true, maxRetries: 3 });
+}
test('a shared shape has one byte range and instance batches validate their own placement data', () => {
const shape = { vertices: 3, indices: 3, offset: 0 };
@@ -49,7 +58,7 @@ test('the initial focus ignores a remote record with less than one percent of th
});
test('a native geometry record produces the same indexed triangle and preserves alpha', async () => {
- const folder = await mkdtemp(join(tmpdir(), 'ioviewer-mesh-pages-'));
+ const folder = await mkdtemp(join(fixtureRoot, 'ioviewer-mesh-pages-'));
const output = join(folder, 'output'), source = join(folder, 'one.ivmesh');
try {
const bytes = Buffer.alloc(116);
@@ -73,14 +82,12 @@ test('a native geometry record produces the same indexed triangle and preserves
assert.deepEqual([...mesh.normal], [0, 0, 32767, 0, 0, 32767, 0, 0, 32767]);
assert.deepEqual([...mesh.color], [255, 0, 0, 128, 255, 0, 0, 128, 255, 0, 0, 128]);
} finally {
- await Promise.all([source, join(output, 'manifest.json'), join(output, 'meshes.bin')].map((file) => rm(file, { force: true })));
- await rmdir(output).catch((error) => { if (error.code !== 'ENOENT') throw error; });
- await rmdir(folder);
+ await removeFixture(folder);
}
});
test('IMS2 preserves exact IDs and property ranges and also packs geometry alone', async () => {
- const folder = await mkdtemp(join(tmpdir(), 'ioviewer-bim-pages-'));
+ const folder = await mkdtemp(join(fixtureRoot, 'ioviewer-bim-pages-'));
const source = join(folder, 'one.ivmesh'), review = join(folder, 'review'), geometry = join(folder, 'geometry');
const property = Buffer.from('{"id":"9007199254740993","name":"Slab","category":"Floors","properties":{"Identity":{"Type":"Slab"}}}');
try {
@@ -103,6 +110,41 @@ test('IMS2 preserves exact IDs and property ranges and also packs geometry alone
const annotated = await buildMeshPages(source, review);
assert.deepEqual(annotated.elements, [{ ...bounds, id: '9007199254740993', name: 'Slab', category: 'Floors', offset: 0, size: property.length }]);
assert.deepEqual(await readFile(join(review, 'elements.bin')), property);
+ const browserFiles = new Map(), progress = [];
+ function copy(bytes, target, offset, size = target.length) {
+ const part = bytes.subarray(offset, offset + Math.min(size, target.length));
+ target.set(part);
+ return part.length;
+ }
+ const fromRanges = await buildMeshPagesFromSource({
+ length: input.length,
+ read: (target, offset) => copy(input, target, offset, 7),
+ }, (name) => {
+ let bytes = Buffer.alloc(0);
+ return {
+ read: (target, offset) => copy(bytes, target, offset),
+ write: (part) => { bytes = Buffer.concat([bytes, part]); },
+ close: () => { browserFiles.set(name, bytes); },
+ };
+ }, true, update => progress.push(update));
+ assert.deepEqual(fromRanges, annotated);
+ assert.deepEqual(progress, [
+ { phase: 'triangles', completed: 0, total: 1 },
+ { phase: 'triangles', completed: 1, total: 1 },
+ { phase: 'properties', completed: 0, total: 1 },
+ { phase: 'properties', completed: 1, total: 1 },
+ ]);
+ for (const [name, data] of browserFiles) assert.deepEqual(data, await readFile(join(review, name)));
+
+ const local = await openMeshPackage(async (name) => new Blob([browserFiles.get(name)]));
+ const response = await local.fetch('/pages/0');
+ assert.equal(Number(response.headers.get('Content-Length')), browserFiles.get('meshes.bin').length);
+ assert.deepEqual(Buffer.from(await response.arrayBuffer()), browserFiles.get('meshes.bin'));
+ assert.deepEqual(await (await local.fetch('/elements/0')).json(), JSON.parse(property));
+ assert.equal((await local.fetch('/pages/01')).status, 404);
+ const abort = new AbortController();
+ abort.abort();
+ await assert.rejects(local.fetch('/pages/0', { signal: abort.signal }), { name: 'AbortError' });
const shape = await buildMeshPages(source, geometry, false);
assert.equal(shape.elements, undefined);
const detailed = viewsOfPage(Uint8Array.from(await readFile(join(review, 'meshes.bin'))).buffer, annotated.pages[0]);
@@ -111,10 +153,6 @@ test('IMS2 preserves exact IDs and property ranges and also packs geometry alone
assert.deepEqual(detailed.position, bare.position);
assert.deepEqual(detailed.index, bare.index);
} finally {
- await Promise.all([source, join(review, 'elements.bin'), ...[review, geometry].flatMap((dir) => [
- join(dir, 'manifest.json'), join(dir, 'meshes.bin'),
- ])].map((file) => rm(file, { force: true })));
- for (const dir of [review, geometry]) await rmdir(dir).catch((error) => { if (error.code !== 'ENOENT') throw error; });
- await rmdir(folder);
+ await removeFixture(folder);
}
});
diff --git a/tests/IOViewer.Tests/ClusterSourceTests.cs b/tests/IOViewer.Tests/ClusterSourceTests.cs
index 4bbe82d..f7eefd7 100644
--- a/tests/IOViewer.Tests/ClusterSourceTests.cs
+++ b/tests/IOViewer.Tests/ClusterSourceTests.cs
@@ -27,6 +27,11 @@ public void KeepsWorldCoordinatesWhenAReusableTemplateWouldLoseDetail()
try
{
Assert.Equal(3, ClusterSourceWriter.Save(new ViewerDocument(scene), path, new HtmlViewerOptions()));
+ using var stream = new MemoryStream();
+ Assert.Equal(3, ClusterSourceWriter.Export(new ViewerDocument(scene), stream));
+ Assert.True(stream.CanWrite);
+ Assert.Equal(File.ReadAllBytes(path), stream.ToArray());
+ Assert.Throws(() => ClusterSourceWriter.Export(new ViewerDocument(scene), stream));
using var reader = new BinaryReader(File.OpenRead(path));
Assert.Equal("IMS4"u8.ToArray(), reader.ReadBytes(4));
Assert.Equal(0, reader.ReadDouble());