diff --git a/README.md b/README.md index 9c4e426..61ac46f 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,7 @@ The documentation site with API references and guides is at geometry.Id); var materials = scene.Materials.ToDictionary(material => material.Id); var textures = scene.Textures.Select((texture, index) => (texture.Id, index)).ToDictionary(texture => texture.Id, texture => texture.index); + var canonical = FindEqualMeshes(geometries, scene.Instances); + ShapeKey Key(SceneInstance instance, Transform3d t) => new(canonical[instance.GeometryId], t.XAxis, t.YAxis, t.ZAxis); + var uses = new Dictionary(); + foreach (var instance in scene.Instances) + { + if (!canonical.ContainsKey(instance.GeometryId)) continue; + var key = Key(instance, instance.Transform ?? Transform3d.Identity); + uses[key] = uses.GetValueOrDefault(key) + 1; + } + var templates = uses.Where(entry => entry.Value > 1).ToDictionary(entry => entry.Key, _ => new List()); + bool sharedFormat = templates.Count > 0; var closed = new Dictionary(); var bounds = scene.ComputeBounds(); var origin = bounds.IsEmpty ? Vector3d.Zero : bounds.Center; if (!double.IsFinite(origin.X) || !double.IsFinite(origin.Y) || !double.IsFinite(origin.Z)) throw new InvalidDataException("Non-finite scene origin."); - writer.Write(Signature); + writer.Write(sharedFormat ? SharedSignature : Signature); writer.Write(origin.X); writer.Write(origin.Y); writer.Write(origin.Z); @@ -65,12 +81,30 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt ? textures.GetValueOrDefault(textureId, -1) : -1; var transform = instance.Transform ?? Transform3d.Identity; var rebased = transform with { Translation = transform.Translation - origin }; + var template = canonical.ContainsKey(geometry.Id) ? templates.GetValueOrDefault(Key(instance, transform)) : null; + bool hasNormals = geometry.Normals?.Count == geometry.Vertices.Count; + bool hasUvs = geometry.UVs?.Count == geometry.Vertices.Count; + var shift = Vector3d.Zero; + if (template is not null && SharedTranslation(geometry, rebased) is { } translation) + { + shift = translation; + if (template.Count > 0) + { + foreach (var record in template) + { + WriteHeader(record.Bounds, record.Vertices, record.Indices, record.Closed, record.Offset); + triangles += record.Indices / 3; + } + continue; + } + rebased = transform with { Translation = Vector3d.Zero }; + } + else template = null; var nx = Vector3d.Cross(transform.YAxis, transform.ZAxis); var ny = Vector3d.Cross(transform.ZAxis, transform.XAxis); var nz = Vector3d.Cross(transform.XAxis, transform.YAxis); bool mirrored = Vector3d.Dot(transform.XAxis, nx) < 0; bool hasIndices = geometry.Indices.Count != 0; - bool hasNormals = geometry.Normals?.Count == geometry.Vertices.Count; int count = hasIndices ? geometry.Indices.Count : geometry.Vertices.Count / 3 * 3; if (count % 3 != 0) throw new InvalidDataException($"Invalid triangle indices in geometry {geometry.Id}."); if (!closed.TryGetValue(geometry.Id, out bool solid)) @@ -94,10 +128,8 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt { slot = vertices.Count; remap.Add(index, slot); - var p = rebased.Apply(geometry.Vertices[index]); - var point = new Vector3d((float)p.X, (float)p.Y, (float)p.Z); - if (!float.IsFinite((float)point.X) || !float.IsFinite((float)point.Y) || !float.IsFinite((float)point.Z)) - throw new InvalidDataException($"Non-finite vertex in geometry {geometry.Id}."); + var p = template is null ? geometry.Vertices[index] : geometry.Vertices[index] - geometry.Vertices[0]; + var point = RoundPoint(rebased.Apply(p)); vertices.Add(point); box = box.Encapsulate(point); if (hasNormals) @@ -105,22 +137,13 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt var n = geometry.Normals![index]; normals.Add(((nx * n.X + ny * n.Y + nz * n.Z) * (mirrored ? -1 : 1)).Normalized()); } - if (texture >= 0) uvs.Add(geometry.UVs![index]); + if (texture >= 0 || (template is not null && hasUvs)) uvs.Add(geometry.UVs![index]); } indices.Add(slot); } - WriteVector(writer, box.Min); - WriteVector(writer, box.Max); - writer.Write(vertices.Count); - writer.Write(length); - writer.Write(color.R); - writer.Write(color.G); - writer.Write(color.B); - writer.Write(color.A); - writer.Write(hasNormals ? 1 : 0); - writer.Write(instance.ElementId); - writer.Write(texture); - writer.Write(solid ? 1 : 0); + long offset = template is null ? -1 : writer.BaseStream.Position; + template?.Add(new ShapeRecord(offset, box, vertices.Count, length, solid)); + WriteHeader(box, vertices.Count, length, solid, offset); foreach (var p in vertices) WriteVector(writer, p); foreach (var n in normals) WriteVector(writer, n); foreach (int i in indices) writer.Write(i); @@ -134,6 +157,27 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt triangles += length / 3; start += length; } + + void WriteHeader(BoundingBox3d box, int vertexCount, int indexCount, bool isClosed, long shapeOffset) + { + WriteVector(writer, template is null ? box.Min : RoundBounds(box.Min + shift, false)); + WriteVector(writer, template is null ? box.Max : RoundBounds(box.Max + shift, true)); + writer.Write(vertexCount); + writer.Write(indexCount); + writer.Write(color.R); + writer.Write(color.G); + writer.Write(color.B); + writer.Write(color.A); + writer.Write(hasNormals ? 1 : 0); + writer.Write(instance.ElementId); + writer.Write(texture); + writer.Write((isClosed ? 1 : 0) | (sharedFormat && (texture >= 0 || (template is not null && hasUvs)) ? 2 : 0)); + if (sharedFormat) + { + writer.Write(shapeOffset); + WriteVector(writer, shift); + } + } } if (triangles == 0) throw new InvalidDataException("The source contains no triangle geometry."); long geometryEnd = writer.BaseStream.Position; @@ -150,6 +194,81 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt return triangles; } + private static Vector3d? SharedTranslation(SceneGeometry geometry, Transform3d rebased) + { + // Two float32 values can cancel and erase detail that the original world-space vertex retains. + const double tolerance = GeometryQuantizer.Step / 2; + static bool Preserved(double world, double local, double shift) => + Math.Abs((double)(float)world - (float)((float)local + shift)) <= tolerance; + + var anchor = geometry.Vertices[0]; + var position = rebased.Apply(anchor); + var shift = new Vector3d((float)position.X, (float)position.Y, (float)position.Z); + var linear = rebased with { Translation = Vector3d.Zero }; + foreach (var vertex in geometry.Vertices) + { + var world = rebased.Apply(vertex); + var local = linear.Apply(vertex - anchor); + if (!Preserved(world.X, local.X, shift.X) || !Preserved(world.Y, local.Y, shift.Y) + || !Preserved(world.Z, local.Z, shift.Z)) return null; + } + return shift; + } + + private static Vector3d RoundPoint(Vector3d p) + { + var point = new Vector3d((float)p.X, (float)p.Y, (float)p.Z); + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z)) + throw new InvalidDataException("Non-finite vertex or placement in clustered geometry."); + return point; + } + + private static Vector3d RoundBounds(Vector3d p, bool upper) + { + static float Outward(double value, bool upper) + { + var rounded = (float)value; + return upper && rounded < value ? MathF.BitIncrement(rounded) + : !upper && rounded > value ? MathF.BitDecrement(rounded) : rounded; + } + RoundPoint(p); + return new(Outward(p.X, upper), Outward(p.Y, upper), Outward(p.Z, upper)); + } + + private static Dictionary FindEqualMeshes(Dictionary geometries, IEnumerable instances) + { + var used = instances.Select(instance => instance.GeometryId).Distinct().Select(id => geometries.GetValueOrDefault(id)) + .Where(mesh => mesh is { Topology: SceneTopology.Triangles } && mesh.Vertices.Count >= 3).Select(mesh => mesh!); + var canonical = new Dictionary(); + foreach (var group in used.GroupBy(mesh => (mesh.Vertices.Count, mesh.Indices.Count, mesh.Normals?.Count, mesh.UVs?.Count))) + { + if (!group.Skip(1).Any()) + { + var mesh = group.First(); + canonical.Add(mesh.Id, mesh.Id); + continue; + } + var candidates = new Dictionary>(); + foreach (var mesh in group) + { + var hash = new HashCode(); + foreach (var vertex in mesh.Vertices) hash.Add(vertex); + foreach (var index in mesh.Indices) hash.Add(index); + if (mesh.Normals is { } normals) foreach (var normal in normals) hash.Add(normal); + if (mesh.UVs is { } uvs) foreach (var uv in uvs) hash.Add(uv); + var key = hash.ToHashCode(); + if (!candidates.TryGetValue(key, out var matches)) candidates.Add(key, matches = []); + var equal = matches.Find(candidate => candidate.Vertices.SequenceEqual(mesh.Vertices) + && candidate.Indices.SequenceEqual(mesh.Indices) && Same(candidate.Normals, mesh.Normals) && Same(candidate.UVs, mesh.UVs)); + if (equal is null) matches.Add(mesh); + canonical.Add(mesh.Id, equal?.Id ?? mesh.Id); + } + } + return canonical; + + static bool Same(IReadOnlyList? a, IReadOnlyList? b) => a is null ? b is null : b is not null && a.SequenceEqual(b); + } + // Tessellation can duplicate vertices at normal and UV seams. private static bool IsClosed(SceneGeometry geometry, int count) { diff --git a/src/IOViewer/Viewer/build-mesh-pages.js b/src/IOViewer/Viewer/build-mesh-pages.js index 3f2a85e..8ee17b6 100644 --- a/src/IOViewer/Viewer/build-mesh-pages.js +++ b/src/IOViewer/Viewer/build-mesh-pages.js @@ -2,7 +2,7 @@ import { closeSync, fstatSync, mkdirSync, openSync, readSync, writeFileSync } fr import { join } from 'node:path'; import { MeshoptSimplifier } from 'meshoptimizer/simplifier'; import { splitCells, unitNormals } from './src/engine/chunks.js'; -import { ELEMENT_FIELDS, isBounds, isPoint, MAX_ELEMENT_BYTES, MESH_FORMAT, MESH_MANIFEST_BYTES, PAGE_TRIANGLES, ROOT_BYTES, pageBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './src/stream/meshPages.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'; const HEADER = 28, RECORD = 40; @@ -10,6 +10,7 @@ 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); @@ -24,19 +25,20 @@ function read(fd, bytes, offset) { function recordsOf(fd, includeBim) { const header = new DataView(read(fd, HEADER, 0)); const version = header.getUint32(0, true); - const reviewFormat = version === 0x33534d49; + 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 + (reviewFormat ? 16 : annotated ? 8 : 0); + 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 = []; + 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); @@ -56,15 +58,26 @@ function recordsOf(fd, includeBim) { } } 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 solid = reviewFormat ? recordView.getUint32(RECORD + 12, true) : 0; - const bytes = vertices * (12 * (1 + normals) + (texture >= 0 ? 8 : 0)) + indices * 4; + 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 || solid > 1 || texture < -1 || (includeBim && texture >= textureCount) || bytes > end - offset) throw new Error('Invalid mesh record.'); + || 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(); @@ -83,8 +96,9 @@ function recordsOf(fd, includeBim) { } } } - records.push({ min, max, vertices, indices, rgba, normals, offset, bytes, element, texture, solid: !!solid, includeBim }); - offset += bytes; + 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(); @@ -161,7 +175,7 @@ function assemble(parts, tagged = false, leaf = false) { tags: tagged ? Uint32Array.from([...opaqueTags, ...blendedTags]) : null }; } -function partFromRecord(fd, record) { +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); @@ -170,11 +184,13 @@ function partFromRecord(fd, record) { 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 = [channel[record.rgba & 255], channel[(record.rgba >>> 8) & 255], channel[(record.rgba >>> 16) & 255], a]; + 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 = texture === undefined ? null : new Float32Array(buffer, index.byteOffset + index.byteLength, record.vertices * 2); + 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 }; } @@ -256,12 +272,13 @@ function pack(mesh, opaque, blended, tags = null) { export async function buildMeshPages(source, destination, includeBim = true) { await MeshoptSimplifier.ready; const input = openSync(source, 'r'); - let output; + let output, shapeFile; 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; @@ -271,23 +288,74 @@ export async function buildMeshPages(source, destination, includeBim = true) { bytes += buffer.byteLength; return pages.length - 1; } - const leaves = splitCells(centres, weights, records.keys(), PAGE_TRIANGLES); + 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 + sizeOfPage(pages[id]), 0) > ROOT_BYTES / 2) { + while (roots.length > 48 || roots.reduce((sum, id) => sum + residentBytes(pages[id], shapes), 0) > ROOT_BYTES / 2) { const next = []; - for (let i = 0; i < roots.length; i += 4) { - const children = roots.slice(i, i + 4); + // 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(group.map((page) => ({ ...viewsOfPage(read(output, sizeOfPage(page), page.offset), page), opaque: page.opaque }))); + 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)); @@ -315,11 +383,13 @@ export async function buildMeshPages(source, destination, includeBim = 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; } finally { + if (shapeFile !== undefined) closeSync(shapeFile); if (output !== undefined) closeSync(output); closeSync(input); } diff --git a/src/IOViewer/Viewer/federate-mesh-pages.js b/src/IOViewer/Viewer/federate-mesh-pages.js index 4a4b8cf..c32f537 100644 --- a/src/IOViewer/Viewer/federate-mesh-pages.js +++ b/src/IOViewer/Viewer/federate-mesh-pages.js @@ -12,12 +12,21 @@ if (!destination || !Number.isSafeInteger(target) || target <= 0 || folders.leng const sources = await Promise.all(folders.map(async (folder) => { const manifest = validateMeshPages(JSON.parse(await readFile(join(folder, 'manifest.json')))); const file = join(folder, 'meshes.bin'); + const shapesFile = manifest.shapes ? join(folder, 'shapes.bin') : null; // shortcut: benchmark placements carry geometry only, add namespaced element IDs if federated BIM review is needed. - if ((await stat(file)).size !== manifest.bytes || manifest.elements || manifest.pages.some((page) => page.shift)) { + if ((await stat(file)).size !== manifest.bytes || (shapesFile && (await stat(shapesFile)).size !== manifest.shapeBytes) + || manifest.elements || manifest.pages.some((page) => page.shift)) { throw new Error('Expected a geometry-only package made directly from an input model.'); } - return { manifest, file }; + return { manifest, file, shapesFile }; })); +const shapes = []; +let shapeBytes = 0; +for (const source of sources) { + source.firstShape = shapes.length; + for (const shape of source.manifest.shapes ?? []) shapes.push({ ...shape, offset: shape.offset + shapeBytes }); + shapeBytes += source.manifest.shapeBytes ?? 0; +} const plan = []; for (let bytes = 0; bytes < target;) { const source = sources[plan.length % sources.length]; @@ -29,12 +38,13 @@ const pitch = [0, 1].map((axis) => 20 + Math.max(...sources.map(({ manifest }) = const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity]; const pages = [], roots = [], placements = []; let bytes = 0, overview = 0, triangles = 0; -for (const [i, { manifest }] of plan.entries()) { +for (const [i, { manifest, firstShape }] of plan.entries()) { const shift = [i % columns * pitch[0] - manifest.min[0], Math.floor(i / columns) * pitch[1] - manifest.min[1], -manifest.min[2]]; const point = (p) => p.map((n, axis) => n + shift[axis]); const transformed = (bounds) => ({ min: point(bounds.min), max: point(bounds.max) }); const first = pages.length; for (const page of manifest.pages) pages.push({ ...page, ...transformed(page), shift, + ...(page.shape === undefined ? {} : { shape: firstShape + page.shape }), offset: bytes + page.offset, children: page.children.map((id) => first + id) }); for (const id of manifest.roots) { roots.push(first + id); @@ -49,7 +59,8 @@ for (const [i, { manifest }] of plan.entries()) { bytes += manifest.bytes; triangles += manifest.triangles; } -const manifest = validateMeshPages({ format: MESH_FORMAT, origin: [0, 0, 0], min, max, pages, roots, placements, bytes, triangles, overview }); +const manifest = validateMeshPages({ format: MESH_FORMAT, origin: [0, 0, 0], min, max, pages, roots, placements, bytes, triangles, + ...(shapes.length ? { shapes, shapeBytes } : { overview }) }); await mkdir(destination); const packed = join(destination, 'meshes.bin'); await (await open(packed, 'wx')).close(); @@ -58,19 +69,28 @@ for (const [i, { file }] of plan.entries()) { console.log(`Copied ${i + 1}/${plan.length} placements`); } if ((await stat(join(destination, 'meshes.bin'))).size !== bytes) throw new Error('Incomplete federation archive.'); -const rootFile = await open(join(destination, 'overview.bin'), 'wx'); -try { - for (const { manifest: source, file } of plan) { - const handle = await open(file, 'r'); - try { - for (const id of source.roots) { - const page = source.pages[id], length = sizeOfPage(page), buffer = Buffer.alloc(length); - const { bytesRead } = await handle.read(buffer, 0, length, page.offset); - if (bytesRead !== length) throw new Error('Truncated overview page.'); - await rootFile.writeFile(buffer); - } - } finally { await handle.close(); } +if (shapes.length) { + const packedShapes = join(destination, 'shapes.bin'); + await (await open(packedShapes, 'wx')).close(); + for (const { shapesFile } of sources) if (shapesFile) { + await pipeline(createReadStream(shapesFile), createWriteStream(packedShapes, { flags: 'a' })); } -} finally { await rootFile.close(); } + if ((await stat(packedShapes)).size !== shapeBytes) throw new Error('Incomplete federation shapes.'); +} else { + const rootFile = await open(join(destination, 'overview.bin'), 'wx'); + try { + for (const { manifest: source, file } of plan) { + const handle = await open(file, 'r'); + try { + for (const id of source.roots) { + const page = source.pages[id], length = sizeOfPage(page), buffer = Buffer.alloc(length); + const { bytesRead } = await handle.read(buffer, 0, length, page.offset); + if (bytesRead !== length) throw new Error('Truncated overview page.'); + await rootFile.writeFile(buffer); + } + } finally { await handle.close(); } + } + } finally { await rootFile.close(); } +} await writeFile(join(destination, 'manifest.json'), JSON.stringify(manifest), { flag: 'wx' }); console.log(`${plan.length} placements, ${pages.length} pages, ${triangles} triangles, ${bytes} bytes`); diff --git a/src/IOViewer/Viewer/serve-stream.js b/src/IOViewer/Viewer/serve-stream.js index 098ada1..c2a7aa3 100644 --- a/src/IOViewer/Viewer/serve-stream.js +++ b/src/IOViewer/Viewer/serve-stream.js @@ -33,6 +33,12 @@ export async function startStreamServer(folder, port = 0) { for (const [id, page] of manifest.pages.entries()) { files.set(`/pages/${id}`, { ...info, start: page.offset, size: sizeOfPage(page) }); } + if (manifest.shapes) { + const shapes = await fileInfo('shapes.bin', manifest.shapeBytes); + for (const [id, shape] of manifest.shapes.entries()) { + files.set(`/shapes/${id}`, { ...shapes, start: shape.offset, size: sizeOfPage(shape) }); + } + } if (manifest.overview) { files.set('/overview.bin', { ...await fileInfo('overview.bin', manifest.overview), start: 0, size: manifest.overview }); } diff --git a/src/IOViewer/Viewer/src/stream/meshLod.js b/src/IOViewer/Viewer/src/stream/meshLod.js index af1889d..3f0d406 100644 --- a/src/IOViewer/Viewer/src/stream/meshLod.js +++ b/src/IOViewer/Viewer/src/stream/meshLod.js @@ -4,7 +4,7 @@ import { NavigationControls } from '../nav/controls.js'; import { ViewCube } from '../nav/viewCube.js'; import { el } from '../ui/dom.js'; import { MESH_BUDGET, MIB } from './manifest.js'; -import { sizeOfPage, validateMeshPages, viewsOfPage } from './meshPages.js'; +import { readPlacements, residentBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './meshPages.js'; import { mountMeshTools } from './meshTools.js'; import { meshScene } from './meshScene.js'; import { SectionCaps } from '../tools/sectionCaps.js'; @@ -25,13 +25,20 @@ function show(text) { message.hidden = false; } -async function fetchPage(node, signal) { +async function fetchRange(path, bytes, signal) { const start = profile && performance.now(); - const response = await fetch(`/pages/${node.id}`, { cache: 'no-store', signal }); - if (!response.ok || Number(response.headers.get('content-length')) !== node.bytes) throw new Error(`Page ${node.id} failed (${response.status}).`); + const response = await fetch(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); - return viewsOfPage(data, node); + return data; +} + +async function fetchPage(node, signal) { + const page = fetchRange(`/pages/${node.id}`, node.bytes, signal); + if (!node.template) return viewsOfPage(await page, node); + const [placements, shape] = await Promise.all([page, fetchRange(`/shapes/${node.shape}`, node.templateBytes, signal)]); + return { ...viewsOfPage(shape, node.template), placements: readPlacements(placements, node) }; } const box = ({ min, max }) => new THREE.Box3(new THREE.Vector3(...min), new THREE.Vector3(...max)); @@ -53,7 +60,10 @@ async function start(manifest, context) { const bounds = box(manifest); const nodes = manifest.pages.map((page, id) => { const bytes = sizeOfPage(page); - return { ...page, id, box: box(page), bytes, memory: bytes + page.indices * 2 + (page.pick ? page.vertices * 4 : 0) }; + const template = manifest.shapes?.[page.shape]; + const memory = residentBytes(page, manifest.shapes) + page.indices * 2 + + (template ? bytes : page.pick ? page.vertices * 4 : 0); + return { ...page, id, box: box(page), bytes, template, templateBytes: template ? sizeOfPage(template) : 0, memory }; }); const roots = manifest.roots.map((id) => nodes[id]); const pinned = new Set(roots); @@ -68,7 +78,7 @@ async function start(manifest, context) { let bytes = roots.reduce((n, node) => n + node.memory, 0), peak = bytes; let wireBudget = false; const pageMemory = (node) => node.memory + (wireBudget ? node.indices * 8 : 0); - let requested = 0, downloaded = 0, evictions = 0, fallback = 0, exact = 0, visible = 0; + let requested = 0, downloaded = 0, evictions = 0, fallback = 0, exact = 0, visible = 0, instanced = 0; let coarsePixels = 0, nearbyCoarsePixels = 0; let frame = 0, lost = false; let lastMove = -Infinity, settleTimer = 0, lastFrame = 0, fastFrames = 0, movingError = BASE_ERROR, threshold = BASE_ERROR; @@ -144,8 +154,8 @@ async function start(manifest, context) { for (const material of appearances.values()) configureMaterial(material); requestFrame(); } - function materialFor(tagged, blended, textureId) { - const key = `${scene.mode}-${tagged}-${blended}-${textureId}`; + function materialFor(tagged, blended, textureId, placed) { + const key = `${scene.mode}-${tagged}-${blended}-${textureId}-${placed}`; let material = appearances.get(key); if (material) return material; const white = scene.mode === 'white'; @@ -162,10 +172,10 @@ async function start(manifest, context) { } map = textures.get(textureId); } - material = new THREE.MeshLambertMaterial({ vertexColors: tagged || !white, color: white && !tagged ? 0xfafafa : 0xffffff, + material = new THREE.MeshLambertMaterial({ vertexColors: placed || tagged || !white, color: white && !tagged && !placed ? 0xfafafa : 0xffffff, wireframe: scene.mode === 'wireframe', map }); material.userData.blended = blended; - if (tagged) scene.patchMaterial(material, { white }); + if (placed || tagged) scene.patchMaterial(material, { white, placed, tagged }); configureMaterial(material); appearances.set(key, material); return material; @@ -176,7 +186,7 @@ async function start(manifest, context) { item.mesh.material = item.groups.map((group) => { const blended = start >= node.opaque; start += group.count; - return materialFor(!!node.pick, blended, group.texture); + return materialFor(!!node.pick, blended, group.texture, !!node.template); }); item.mode = scene.mode; } @@ -206,12 +216,12 @@ async function start(manifest, context) { function renderStencils(renderer, camera, plane) { if (!capWorld) { capWorld = new THREE.Scene(); - capMaterials = [false, true].map((tagged) => [ + capMaterials = [0, 1, 2, 3].map((flags) => [ [THREE.BackSide, THREE.IncrementWrapStencilOp], [THREE.FrontSide, THREE.DecrementWrapStencilOp], ].map(([side, stencilZPass]) => { const material = new THREE.MeshBasicMaterial({ side, stencilZPass, stencilWrite: true, clippingPlanes: [plane], colorWrite: false, depthWrite: false, depthTest: false }); - if (tagged) scene.patchMaterial(material, { stencil: true }); + if (flags) scene.patchMaterial(material, { stencil: true, tagged: Boolean(flags & 1), placed: Boolean(flags & 2) }); return material; })); } @@ -224,7 +234,7 @@ async function start(manifest, context) { const invisible = new THREE.MeshBasicMaterial({ visible: false }); item.stencil = new THREE.Mesh(item.mesh.geometry); item.stencil.position.copy(item.mesh.position); - item.stencilMaterials = capMaterials[Number(!!node.pick)].map((material) => + item.stencilMaterials = capMaterials[Number(!!node.pick) + 2 * Number(!!node.template)].map((material) => item.groups.map(({ closed }) => closed ? material : invisible)); } item.stencil.material = item.stencilMaterials[pass]; @@ -240,20 +250,27 @@ async function start(manifest, context) { window.__ioviewerMeshLod = { controls, manifest, ready, ...tools, stats: () => ({ bytes, peak, budget: MESH_BUDGET, requested, evictions, downloaded, visible, exact, fallback, coarsePixels, nearbyCoarsePixels, threshold, rasterScale, pending: pending.size, - resident: resident.size, triangles: renderer.info.render.triangles, draws: renderer.info.render.calls, failures: [...failed.values()] }) }; + resident: resident.size, instanced, + triangles: renderer.info.render.triangles, draws: renderer.info.render.calls, failures: [...failed.values()] }) }; function stage(node, view, ready = false) { if (view.index.some((i) => i >= node.vertices) || view.position.some((value) => !Number.isFinite(value))) { throw new Error(`Invalid geometry in page ${node.id}.`); } - const geometry = new THREE.BufferGeometry(); + const geometry = node.template ? new THREE.InstancedBufferGeometry() : new THREE.BufferGeometry(); const attribute = (array, size, normalized = false) => new THREE.BufferAttribute(array, size, normalized) .onUpload(function () { this.array = null; }); geometry.setAttribute('position', attribute(view.position, 3)); geometry.setAttribute('normal', attribute(view.normal, 3, true)); geometry.setAttribute('color', attribute(view.color, 4, true)); if (view.uv) geometry.setAttribute('uv', attribute(view.uv, 2)); - if (view.tags) { + if (view.placements) { + const { offset, rgba, elements } = view.placements; + geometry.instanceCount = node.count; + geometry.setAttribute('placementOffset', new THREE.InstancedBufferAttribute(offset, 3)); + geometry.setAttribute('placementColor', new THREE.InstancedBufferAttribute(rgba, 4, true)); + if (elements) geometry.setAttribute('elementIndex', new THREE.InstancedBufferAttribute(Float32Array.from(elements), 1)); + } else if (view.tags) { const elements = new Float32Array(node.vertices); for (let i = 0; i < view.index.length; i++) { const element = view.tags[Math.floor(i / 3)]; @@ -319,7 +336,7 @@ async function start(manifest, context) { pending.add(node); requested++; fetchPage(node).then((view) => { - downloaded += node.bytes; + downloaded += node.bytes + node.templateBytes; transferred.push({ node, view }); requestFrame(); }, (error) => { fail(node, error); requestFrame(); }); @@ -379,6 +396,7 @@ async function start(manifest, context) { item.mesh.frustumCulled = false; // Three uploads the full vertex and index buffers on the first draw. item.mesh.geometry.setDrawRange(0, 3); + if (node.template) item.mesh.geometry.instanceCount = 1; world.add(item.mesh); warm.push(node); } catch (error) { fail(node, error); } @@ -409,9 +427,10 @@ async function start(manifest, context) { const projected = projectedError(node); if (projected > BASE_ERROR / 2) queue(childrenIn(node, moving ? guard : frustum), projected); } - fallback = exact = coarsePixels = nearbyCoarsePixels = 0; + fallback = exact = instanced = coarsePixels = nearbyCoarsePixels = 0; function draw(node) { cut.add(node); + instanced += node.count ?? 0; style(node, resident.get(node)); if (!node.children.length) exact++; if (profile?.coarseMetrics && node.children.length) { @@ -477,6 +496,7 @@ async function start(manifest, context) { item.mode = undefined; item.mesh.frustumCulled = true; item.mesh.geometry.setDrawRange(0, Infinity); + if (node.template) item.mesh.geometry.instanceCount = node.count; item.ready = true; pending.delete(node); } diff --git a/src/IOViewer/Viewer/src/stream/meshPages.js b/src/IOViewer/Viewer/src/stream/meshPages.js index 568826f..59ff98a 100644 --- a/src/IOViewer/Viewer/src/stream/meshPages.js +++ b/src/IOViewer/Viewer/src/stream/meshPages.js @@ -3,6 +3,7 @@ import { validateReviewMeta } from '../data.js'; export const MESH_FORMAT = 'ioviewer-mesh-clusters-1'; export const PAGE_TRIANGLES = 8192; +export const INSTANCE_BYTES = 20; // xyz, element slot, RGBA export const ROOT_BYTES = 48 * MIB; export const MESH_MANIFEST_BYTES = 64 * MIB; export const align4 = (bytes) => (bytes + 3) & ~3; @@ -11,7 +12,8 @@ export const pageBytes = (vertices, indices, pick = false, uv = false) => { const end = pick ? align4(mesh) + (indices / 3) * 4 : mesh; return uv ? align4(end) + vertices * 8 : end; }; -export const sizeOfPage = ({ vertices, indices, pick, uv }) => pageBytes(vertices, indices, pick, uv); +export const sizeOfPage = ({ vertices, indices, pick, uv, count }) => count === undefined ? pageBytes(vertices, indices, pick, uv) : count * INSTANCE_BYTES; +export const residentBytes = (page, shapes) => sizeOfPage(page) + (page.shape === undefined ? 0 : sizeOfPage(shapes[page.shape])); export const MAX_PAGE_BYTES = pageBytes(PAGE_TRIANGLES * 3, PAGE_TRIANGLES * 3); export const isPoint = (p) => Array.isArray(p) && p.length === 3 && p.every(Number.isFinite); export const isBounds = (value) => isPoint(value?.min) && isPoint(value?.max) && value.min.every((v, i) => v <= value.max[i]); @@ -30,6 +32,19 @@ export function validateMeshPages(manifest) { throw new Error('Invalid mesh cluster manifest.'); } const parent = new Uint8Array(manifest.pages.length); + let shapeBytes = 0; + if (manifest.shapes !== undefined) { + if (!Array.isArray(manifest.shapes) || !manifest.shapes.length) throw new Error('Invalid mesh shapes.'); + for (const shape of manifest.shapes) { + if (!shape || !count(shape.vertices) || !count(shape.indices) || shape.indices > PAGE_TRIANGLES * 3 + || shape.indices % 3 || shape.vertices > shape.indices || shape.offset !== shapeBytes + || (shape.uv !== undefined && typeof shape.uv !== 'boolean') || shape.pick !== undefined || shape.count !== undefined) { + throw new Error('Invalid mesh shape.'); + } + shapeBytes += sizeOfPage(shape); + } + } + if ((manifest.shapeBytes ?? 0) !== shapeBytes) throw new Error('Invalid mesh shape byte total.'); if (manifest.review !== undefined) { if (!manifest.review || typeof manifest.review !== 'object' || Array.isArray(manifest.review)) throw new Error('Invalid mesh review.'); validateReviewMeta({ ...manifest.review, elements: manifest.elements ?? [] }); @@ -49,6 +64,13 @@ export function validateMeshPages(manifest) { || page.members.some((member, i) => !Number.isInteger(member) || member < 0 || member >= manifest.elements.length || (i > 0 && member <= page.members[i - 1])))) || (page.children.length === 0 && page.error !== 0)) throw new Error(`Invalid mesh cluster page ${id}.`); + if (page.shape !== undefined || page.count !== undefined) { + const shape = Number.isSafeInteger(page.shape) && manifest.shapes?.[page.shape]; + if (!shape || !count(page.count) || page.indices * page.count > PAGE_TRIANGLES * 3 || page.children.length + || page.vertices !== shape.vertices || page.indices !== shape.indices || page.uv !== shape.uv + || (page.opaque !== 0 && page.opaque !== page.indices) || page.groups?.length !== 1 + || (page.pick && !page.members)) throw new Error(`Invalid mesh instance batch ${id}.`); + } if (page.groups !== undefined) { let at = 0; if (page.children.length || !Array.isArray(page.groups) || !page.groups.length || page.groups.some((group) => { @@ -61,7 +83,7 @@ export function validateMeshPages(manifest) { }) || at !== page.indices) throw new Error(`Invalid mesh groups at page ${id}.`); } length += sizeOfPage(page); - if (!page.children.length) triangles += page.indices / 3; + if (!page.children.length) triangles += page.indices / 3 * (page.count ?? 1); for (const child of page.children) { if (!Number.isSafeInteger(child) || child < 0 || child >= id || parent[child] || manifest.pages[child].error > page.error) { throw new Error(`Invalid cluster hierarchy at page ${id}.`); @@ -70,12 +92,13 @@ export function validateMeshPages(manifest) { parent[child] = 1; } } - let pinned = 0; + let pinned = 0, overview = 0; for (const root of manifest.roots) { if (!Number.isSafeInteger(root) || root < 0 || root >= parent.length || parent[root]) throw new Error('Invalid mesh cluster root.'); if (!contains(manifest, manifest.pages[root])) throw new Error('A root exceeds the scene bounds.'); parent[root] = 1; - pinned += sizeOfPage(manifest.pages[root]); + overview += sizeOfPage(manifest.pages[root]); + pinned += residentBytes(manifest.pages[root], manifest.shapes); } let propertyBytes = 0; for (const element of manifest.elements ?? []) { @@ -87,7 +110,7 @@ export function validateMeshPages(manifest) { propertyBytes += element.size; } if (!parent.every(Boolean) || !count(length) || length !== manifest.bytes || triangles !== manifest.triangles || pinned > ROOT_BYTES - || (manifest.overview !== undefined && manifest.overview !== pinned) || propertyBytes !== (manifest.propertyBytes ?? 0)) { + || (manifest.overview !== undefined && (manifest.overview !== overview || shapeBytes > 0)) || propertyBytes !== (manifest.propertyBytes ?? 0)) { throw new Error('Invalid cluster coverage or byte totals.'); } return manifest; @@ -104,3 +127,21 @@ export function viewsOfPage(buffer, { vertices, indices, pick, uv }) { uv: uv ? new Float32Array(buffer, align4(pageBytes(vertices, indices, pick)), vertices * 2) : null, }; } + +export function readPlacements(buffer, page) { + if (buffer.byteLength !== sizeOfPage(page)) throw new Error('Truncated mesh instance batch.'); + const data = new DataView(buffer), offset = new Float32Array(page.count * 3); + const rgba = new Uint8Array(page.count * 4), elements = page.pick ? new Uint32Array(page.count) : null; + for (let i = 0; i < page.count; i++) { + const at = i * INSTANCE_BYTES; + for (let axis = 0; axis < 3; axis++) offset[i * 3 + axis] = data.getFloat32(at + 4 * axis, true); + rgba.set(new Uint8Array(buffer, at + 16, 4), i * 4); + if (elements) elements[i] = data.getUint32(at + 12, true); + if ((rgba[i * 4 + 3] === 255) !== Boolean(page.opaque)) throw new Error('Invalid instance alpha.'); + } + const members = new Set(elements ?? []); + if (!offset.every(Number.isFinite) || (elements && (members.size !== page.members.length || page.members.some((i) => !members.has(i))))) { + throw new Error('Invalid mesh instance data.'); + } + return { offset, rgba, elements }; +} diff --git a/src/IOViewer/Viewer/src/stream/meshScene.js b/src/IOViewer/Viewer/src/stream/meshScene.js index 3a43d92..8290326 100644 --- a/src/IOViewer/Viewer/src/stream/meshScene.js +++ b/src/IOViewer/Viewer/src/stream/meshScene.js @@ -20,7 +20,7 @@ export function meshScene(elements, nodes, bounds, context, setClipping, render) for (const node of nodes) { node.affected = node.hidden = 0; node.total = node.members?.length ?? 0; - node.hasTexture = !!node.uv; + node.hasTexture = node.groups?.some(({ texture }) => texture !== undefined) ?? !!node.uv; node.hasClosed = node.groups?.some((group) => group.closed) ?? false; for (const child of node.children) { parents[child] = node.id; @@ -124,22 +124,32 @@ export function meshScene(elements, nodes, bounds, context, setClipping, render) affected(node) { return indexed ? node.affected > 0 : changedElements > 0; }, visibilityAffects(node) { return indexed ? node.hidden > 0 : hiddenElements > 0; }, fullyHidden(node) { return node.total > 0 && node.total === node.hidden; }, - patchMaterial(material, { stencil = false, white = false } = {}) { + patchMaterial(material, { stencil = false, white = false, placed = false, tagged = true } = {}) { const key = material.customProgramCacheKey(); - material.customProgramCacheKey = () => `${key}-element-${stencil}-${white}`; + material.customProgramCacheKey = () => `${key}-element-${stencil}-${white}-${placed}-${tagged}`; material.onBeforeCompile = (shader) => { - shader.uniforms.elementState = { value: texture }; - shader.uniforms.elementWidth = { value: width }; - shader.vertexShader = shader.vertexShader.replace('#include ', `#include - attribute float elementIndex; - uniform highp sampler2D elementState; - uniform int elementWidth;`); - shader.vertexShader = shader.vertexShader.replace('#include ', ` - int iovElement = int(elementIndex); - vec4 iovState = texelFetch(elementState, ivec2(iovElement % elementWidth, iovElement / elementWidth), 0); - #include - if (iovState.a > 0.9) gl_Position = vec4(0.0, 0.0, 2.0, 1.0); - ${stencil ? '' : `${white ? 'vColor.rgb = vec3(0.95);' : ''} if (iovState.a > 0.25) vColor.rgb = iovState.rgb;`}`); + if (placed) { + shader.vertexShader = shader.vertexShader.replace('#include ', `#include + attribute vec3 placementOffset; + attribute vec4 placementColor;`); + shader.vertexShader = shader.vertexShader.replace('#include ', '#include \ntransformed += placementOffset;'); + if (!stencil) shader.vertexShader = shader.vertexShader.replace('#include ', + `#include \nvColor = placementColor; ${white ? 'vColor.rgb = vec3(0.95);' : ''}`); + } + if (tagged) { + shader.uniforms.elementState = { value: texture }; + shader.uniforms.elementWidth = { value: width }; + shader.vertexShader = shader.vertexShader.replace('#include ', `#include + attribute float elementIndex; + uniform highp sampler2D elementState; + uniform int elementWidth;`); + shader.vertexShader = shader.vertexShader.replace('#include ', ` + int iovElement = int(elementIndex); + vec4 iovState = texelFetch(elementState, ivec2(iovElement % elementWidth, iovElement / elementWidth), 0); + #include + if (iovState.a > 0.9) gl_Position = vec4(0.0, 0.0, 2.0, 1.0); + ${stencil ? '' : `${white && !placed ? 'vColor.rgb = vec3(0.95);' : ''} if (iovState.a > 0.25) vColor.rgb = iovState.rgb;`}`); + } }; }, }; diff --git a/src/IOViewer/Viewer/src/stream/meshSnap.js b/src/IOViewer/Viewer/src/stream/meshSnap.js index 16a07b8..d69f9b3 100644 --- a/src/IOViewer/Viewer/src/stream/meshSnap.js +++ b/src/IOViewer/Viewer/src/stream/meshSnap.js @@ -3,12 +3,11 @@ import { edgeParameter, featureEdges, SNAP_RADIUS, visibleEdgeRanges } from '../ import { isClipped } from '../tools/sectionMath.js'; export function meshSnapCandidates(hit, camera, rect, clientX, clientY, sections) { - const { view, node, element } = hit; + const { view, shift, element } = hit; const { position, index, tags } = view; const triangles = tags ? index.filter((_, i) => tags[Math.floor(i / 3)] === element) : index; const { vertices, edges } = featureEdges(position, triangles); const matrix = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); - const shift = new THREE.Vector3().fromArray(node.shift ?? [0, 0, 0]); const { planes, intersection } = sections.clipping(); const x = clientX - rect.left, y = clientY - rect.top; const points = new Map(); diff --git a/src/IOViewer/Viewer/src/stream/meshTools.js b/src/IOViewer/Viewer/src/stream/meshTools.js index 623a73b..a6046db 100644 --- a/src/IOViewer/Viewer/src/stream/meshTools.js +++ b/src/IOViewer/Viewer/src/stream/meshTools.js @@ -21,7 +21,7 @@ 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. export async function pickMeshSurface(ray, roots, nodes, getPage, sections, signal, visible = () => true) { const queue = [], p = new THREE.Vector3(), a = p.clone(), b = p.clone(), c = p.clone(); - const localRay = ray.clone(), shift = new THREE.Vector3(); + const localRay = ray.clone(), shift = new THREE.Vector3(), base = new THREE.Vector3(); const clip = sections.clipping(); const enqueue = (node) => { if (sections.isCut(node.box, clip)) return; @@ -40,26 +40,42 @@ export async function pickMeshSurface(ray, roots, nodes, getPage, sections, sign continue; } const view = await getPage(node, signal); - const { position, index, color, tags } = view; + const { position, index, color, tags, placements } = view; if (index.some((i) => i >= position.length / 3) || position.some((value) => !Number.isFinite(value))) { throw new Error('Invalid pick page geometry.'); } - shift.fromArray(node.shift ?? [0, 0, 0]); - localRay.origin.copy(ray.origin).sub(shift); - for (let i = 0; i < index.length; i += 3) { - const element = tags?.[i / 3] ?? null; - if (element !== null && !visible(element)) continue; - const x = index[i], y = index[i + 1], z = index[i + 2]; - if (!color[x * 4 + 3] && !color[y * 4 + 3] && !color[z * 4 + 3]) continue; - a.fromArray(position, x * 3); - b.fromArray(position, y * 3); - c.fromArray(position, z * 3); - if (!localRay.intersectTriangle(a, b, c, true, p)) continue; - p.add(shift); - const d = p.distanceToSquared(ray.origin); - if (d >= best || isClipped(p, clip.planes, clip.intersection)) continue; - best = d; - hit = { element, point: p.clone(), view, node }; + base.fromArray(node.shift ?? [0, 0, 0]); + if (placements) { + const bounds = new THREE.Box3().setFromArray(position); + for (let slot = 0; slot < node.count; slot++) { + signal?.throwIfAborted(); + const element = placements.elements?.[slot] ?? null; + if (!placements.rgba[slot * 4 + 3] || (element !== null && !visible(element))) continue; + shift.fromArray(placements.offset, slot * 3).add(base); + localRay.origin.copy(ray.origin).sub(shift); + if (localRay.intersectsBox(bounds)) trace(element); + } + } else { + shift.copy(base); + localRay.origin.copy(ray.origin).sub(shift); + trace(null); + } + function trace(placementElement) { + for (let i = 0; i < index.length; i += 3) { + const element = placements ? placementElement : tags?.[i / 3] ?? null; + if (!placements && element !== null && !visible(element)) continue; + const x = index[i], y = index[i + 1], z = index[i + 2]; + if (!placements && !color[x * 4 + 3] && !color[y * 4 + 3] && !color[z * 4 + 3]) continue; + a.fromArray(position, x * 3); + b.fromArray(position, y * 3); + c.fromArray(position, z * 3); + if (!localRay.intersectTriangle(a, b, c, true, p)) continue; + p.add(shift); + const d = p.distanceToSquared(ray.origin); + if (d >= best || isClipped(p, clip.planes, clip.intersection)) continue; + best = d; + hit = { element, point: p.clone(), shift: shift.clone(), view, node }; + } } } return hit; diff --git a/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js b/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js index f2d384a..84f903a 100644 --- a/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js +++ b/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js @@ -1,6 +1,6 @@ import { expect, test } from '@playwright/test'; import { execFileSync } from 'node:child_process'; -import { mkdtemp, rm, rmdir } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, rmdir, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { buildMeshPages } from '../../build-mesh-pages.js'; @@ -17,10 +17,16 @@ let folder; test.beforeAll(async () => { folder = await mkdtemp(join(tmpdir(), 'ioviewer-mesh-review-')); + const measure = JSON.parse(await readFile(join(generated, 'measure-snap.json'))); + measure.Meshes[0].Color = { R: 230, G: 20, B: 20, A: 255 }; + measure.Meshes[1].Color = { R: 20, G: 230, B: 20, A: 255 }; + measure.Meshes[1].Transform = { ...measure.Meshes[0].Transform, Translation: { X: 5, Y: 0, Z: 0 } }; + const repeated = join(folder, 'repeated.json'); + await writeFile(repeated, JSON.stringify(measure)); for (const [name, input, ...args] of [ ['review', join(generated, 'bcf-model.json'), '--bcf', join(fixturesDir, '../bcf/review.bcfzip')], ['textures', join(fixturesDir, 'textured.json')], - ['measure', join(generated, 'measure-snap.json')], + ['measure', repeated], ]) { const source = join(folder, `${name}.ivmesh`); execFileSync('dotnet', [cli, input, '-o', source, ...args], { stdio: 'pipe' }); @@ -30,9 +36,10 @@ test.beforeAll(async () => { test.afterAll(async () => { if (!folder) return; + await rm(join(folder, 'repeated.json'), { force: true }); for (const name of ['review', 'textures', 'measure']) { await rm(join(folder, `${name}.ivmesh`), { force: true }); - for (const file of ['meshes.bin', 'manifest.json', 'elements.bin']) await rm(join(folder, name, file), { force: true }); + for (const file of ['meshes.bin', 'shapes.bin', 'manifest.json', 'elements.bin']) await rm(join(folder, name, file), { force: true }); await rmdir(join(folder, name)).catch((error) => { if (error.code !== 'ENOENT') throw error; }); } await rmdir(folder); @@ -206,8 +213,36 @@ test('stream textures retain UVs and the standard display toolbar controls their }); }); -test('stream measurement snaps to a vertex, midpoint and edge on a fetched mesh', async ({ page }) => { +test('stream instances keep their own colors, picking and visibility and support snapping', async ({ page }) => { await withViewer(page, 'measure', async () => { + const instances = await page.evaluate(() => { + const { controls, scene, manifest, stats } = window.__ioviewerMeshLod; + const box = scene.visibleBox(), center = box.getCenter(box.max.clone()); + controls.setProjection('orthographic'); + controls.restoreViewCamera({ position: [center.x, center.y, center.z + 16], target: center.toArray(), up: [0, 1, 0] }); + controls.camera.updateMatrixWorld(); + const points = [0, 1].map((i) => { + const box = scene.elementBox(i); + const p = box.getCenter(box.max.clone()).project(controls.camera); + return [(p.x + 1) * innerWidth / 2, (1 - p.y) * innerHeight / 2]; + }); + return { points, copies: stats().instanced, shapes: manifest.shapes.length }; + }); + expect(instances.copies).toBe(2); + expect(instances.shapes).toBe(1); + await frame(page); + const red = await sample(page, instances.points[0]); + const green = await sample(page, instances.points[1]); + expect(red[0]).toBeGreaterThan(red[1] + 60); + expect(green[1]).toBeGreaterThan(green[0] + 60); + await page.mouse.click(...instances.points[1]); + await expect(page.locator('#ioviewer-properties')).toContainText('Pipe 1'); + await page.keyboard.press('h'); + await expect.poll(() => shown(page, 'Pipe 1')).toBe(false); + await frame(page); + const hidden = await sample(page, instances.points[1]); + expect(hidden[1]).toBeLessThan(green[1] - 60); + expect(await shown(page, 'Pipe 0')).toBe(true); const coords = await page.evaluate(() => { const { controls, scene } = window.__ioviewerMeshLod; scene.setVisible([1], false); diff --git a/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js b/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js index a921447..53b13ae 100644 --- a/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js +++ b/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Vector3 } from 'three'; import { startStreamServer } from '../../serve-stream.js'; -import { MESH_FORMAT, sizeOfPage, viewsOfPage } from '../../src/stream/meshPages.js'; +import { MESH_FORMAT, readPlacements, sizeOfPage, viewsOfPage } from '../../src/stream/meshPages.js'; test('the section plane cuts both sides of a rendered cluster seam', async ({ page }) => { const folder = await mkdtemp(join(tmpdir(), 'ioviewer-section-')); @@ -105,19 +105,31 @@ test('select a real original element and keep its properties while changing deta const folder = process.env.PERF_MESH_TOOLS_MODEL; test.skip(!folder, 'Set PERF_MESH_TOOLS_MODEL to an annotated IFC or RVT package.'); const manifest = JSON.parse(await readFile(join(folder, 'manifest.json'))); - const leaves = manifest.pages.filter((node) => node.pick); - expect(leaves.length).toBeGreaterThan(1); + const leaves = manifest.pages.filter((node) => node.pick && (!manifest.shapes || node.shape !== undefined)); + expect(leaves.length).toBeGreaterThan(0); const candidates = []; const file = await open(join(folder, 'meshes.bin')); + let shapeFile; + const readPage = async (handle, node) => { + const size = sizeOfPage(node); + const buffer = new ArrayBuffer(size); + expect((await handle.read(new Uint8Array(buffer), 0, size, node.offset)).bytesRead).toBe(size); + return buffer; + }; try { + if (manifest.shapes) shapeFile = await open(join(folder, 'shapes.bin')); for (let sample = 1; sample <= 12; sample++) { const node = leaves[Math.floor(leaves.length * sample / 13)]; - const size = sizeOfPage(node); - const buffer = new ArrayBuffer(size); - expect((await file.read(new Uint8Array(buffer), 0, size, node.offset)).bytesRead).toBe(size); - const { position, index, color, tags } = viewsOfPage(buffer, node); + const buffer = await readPage(file, node); + const template = manifest.shapes?.[node.shape]; + const copies = template ? readPlacements(buffer, node) : null; + const slot = copies?.elements.findIndex((i, k) => manifest.elements[i].size && copies.rgba[k * 4 + 3] === 255); + if (slot === -1) continue; + const { position, index, color, tags } = template + ? viewsOfPage(await readPage(shapeFile, template), template) : viewsOfPage(buffer, node); for (let i = 0; i < index.length; i += 3) { - const element = manifest.elements[tags[i / 3]]; + const elementIndex = copies ? copies.elements[slot] : tags[i / 3]; + const element = manifest.elements[elementIndex]; const [x, y, z] = index.slice(i, i + 3); if (!element.size || [x, y, z].some((v) => color[v * 4 + 3] !== 255)) continue; const a = new Vector3().fromArray(position, x * 3); @@ -127,14 +139,16 @@ test('select a real original element and keep its properties while changing deta if (normal.lengthSq() < 1e-5) continue; normal.normalize(); const target = a.add(b).add(c).divideScalar(3); + if (copies) target.add(new Vector3().fromArray(copies.offset, slot * 3)); if (target.z <= (manifest.focus ?? manifest).min[2]) continue; const camera = { target: target.toArray(), position: target.addScaledVector(normal, 0.2).toArray(), up: Math.abs(normal.z) > 0.9 ? [0, 1, 0] : [0, 0, 1] }; - candidates.push({ camera, id: element.id, index: tags[i / 3] }); + candidates.push({ camera, id: element.id, index: elementIndex }); break; } } } finally { + await shapeFile?.close(); await file.close(); } expect(candidates.length).toBeGreaterThan(0); diff --git a/src/IOViewer/Viewer/test/unit/meshPages.test.js b/src/IOViewer/Viewer/test/unit/meshPages.test.js index eac8c95..25504c4 100644 --- a/src/IOViewer/Viewer/test/unit/meshPages.test.js +++ b/src/IOViewer/Viewer/test/unit/meshPages.test.js @@ -4,10 +4,31 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; import { buildMeshPages, focusBounds } from '../../build-mesh-pages.js'; -import { MESH_FORMAT, pageBytes, validateMeshPages, viewsOfPage } from '../../src/stream/meshPages.js'; +import { INSTANCE_BYTES, MESH_FORMAT, pageBytes, readPlacements, validateMeshPages, viewsOfPage } from '../../src/stream/meshPages.js'; const bounds = { min: [0, 0, 0], max: [1, 1, 0] }; +test('a shared shape has one byte range and instance batches validate their own placement data', () => { + const shape = { vertices: 3, indices: 3, offset: 0 }; + const node = { ...bounds, ...shape, shape: 0, count: 2, pick: true, members: [0, 1], + children: [], error: 0, opaque: 3, groups: [{ count: 3 }] }; + const manifest = { ...bounds, format: MESH_FORMAT, origin: [0, 0, 0], pages: [node], roots: [0], + elements: ['1', '2'].map((id) => ({ ...bounds, id, offset: 0, size: 0 })), + bytes: 2 * INSTANCE_BYTES, shapes: [shape], shapeBytes: pageBytes(3, 3), triangles: 2 }; + assert.equal(validateMeshPages(manifest), manifest); + assert.throws(() => validateMeshPages({ ...manifest, pages: [{ ...node, shape: 1 }] }), /instance batch/); + assert.throws(() => validateMeshPages({ ...manifest, triangles: 1 }), /totals/); + const data = new DataView(new ArrayBuffer(manifest.bytes)); + data.setUint8(19, 255); + data.setUint8(INSTANCE_BYTES + 19, 255); + data.setFloat32(INSTANCE_BYTES, 2, true); + data.setUint32(INSTANCE_BYTES + 12, 1, true); + assert.deepEqual([...readPlacements(data.buffer, node).offset], [0, 0, 0, 2, 0, 0]); + assert.deepEqual([...readPlacements(data.buffer, node).elements], [0, 1]); + data.setUint32(INSTANCE_BYTES + 12, 2, true); + assert.throws(() => readPlacements(data.buffer, node), /instance data/); +}); + test('a cluster tree covers every leaf exactly once and bounds its error and byte ranges', () => { const page = { ...bounds, offset: 0, vertices: 3, indices: 3, opaque: 3, error: 0, children: [] }; const step = pageBytes(3, 3); diff --git a/tests/IOViewer.Tests/ClusterSourceTests.cs b/tests/IOViewer.Tests/ClusterSourceTests.cs index 0f1c5c8..4bbe82d 100644 --- a/tests/IOViewer.Tests/ClusterSourceTests.cs +++ b/tests/IOViewer.Tests/ClusterSourceTests.cs @@ -8,6 +8,114 @@ namespace IOViewer.Tests; public class ClusterSourceTests { + [Fact] + public void KeepsWorldCoordinatesWhenAReusableTemplateWouldLoseDetail() + { + var scene = new SceneDocument(); + scene.Geometries.Add(new SceneGeometry { Id = 1, + Vertices = [new(1_000_000, 0, 0), Vector3d.Zero, new(0.01, 1, 0)], Indices = [0, 1, 2] }); + scene.Geometries.Add(new SceneGeometry { Id = 2, + Vertices = [new(-1_000_000, 0, 0), new(-1_000_000, 1, 0), new(-1_000_000, 0, 1)], Indices = [0, 1, 2] }); + for (int i = 1; i <= 3; i++) + { + scene.Elements.Add(new SceneElement { Id = i, ModelId = 1 }); + scene.Instances.Add(new SceneInstance { ElementId = i, GeometryId = i < 3 ? 1 : 2, + Transform = Transform3d.Identity with { Translation = new Vector3d(0, i * 10, 0) } }); + } + var directory = Directory.CreateTempSubdirectory(); + var path = Path.Combine(directory.FullName, "world-precision.ivmesh"); + try + { + Assert.Equal(3, ClusterSourceWriter.Save(new ViewerDocument(scene), path, new HtmlViewerOptions())); + using var reader = new BinaryReader(File.OpenRead(path)); + Assert.Equal("IMS4"u8.ToArray(), reader.ReadBytes(4)); + Assert.Equal(0, reader.ReadDouble()); + reader.BaseStream.Position = 36 + 56; + Assert.Equal(-1, reader.ReadInt64()); + reader.BaseStream.Position = 36 + 76 + 24; + Assert.Equal(0.01f, reader.ReadSingle()); + } + finally + { + File.Delete(path); + directory.Delete(); + } + } + + [Fact] + public void SharesOnlyIdenticalSourceMeshesAndKeepsPlacementsIndependent() + { + var mesh = new SceneGeometry + { + Id = 1, Vertices = [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], Indices = [0, 1, 2], + Normals = [Vector3d.UnitZ, Vector3d.UnitZ, Vector3d.UnitZ], UVs = [new(0, 0), new(1, 0), new(0, 1)], + }; + var scene = new SceneDocument(); + SceneGeometry Copy(int id, Vector3d[]? points = null, int[]? indices = null, Vector3d[]? normals = null, Vector2d[]? uvs = null) => new() + { + Id = id, Vertices = points is null ? [.. mesh.Vertices] : [.. points], + Indices = indices is null ? [.. mesh.Indices] : [.. indices], + Normals = normals is null ? [.. mesh.Normals!] : [.. normals], + UVs = uvs is null ? [.. mesh.UVs!] : [.. uvs], + }; + scene.Geometries.AddRange([ + mesh, Copy(2), Copy(3, points: [Vector3d.Zero, new(Math.BitIncrement(1d), 0, 0), Vector3d.UnitY]), + Copy(4, indices: [0, 2, 1]), Copy(5, normals: [Vector3d.UnitX, Vector3d.UnitZ, Vector3d.UnitZ]), + Copy(6, uvs: [new(0, 0), new(Math.BitIncrement(1d), 0), new(0, 1)]), + ]); + int[] geometryIds = [1, 1, 2, 3, 4, 5, 6, 1]; + for (int i = 0; i < geometryIds.Length; i++) + { + long id = 100 + i; + scene.Elements.Add(new SceneElement { Id = id, ModelId = 1, Name = $"Part {i}" }); + var t = Transform3d.Identity with { Translation = new Vector3d(i * 10, 0, 0) }; + if (i == geometryIds.Length - 1) t = t with { XAxis = -Vector3d.UnitX }; + scene.Instances.Add(new SceneInstance { GeometryId = geometryIds[i], ElementId = id, Transform = t, + Color = new RgbaColor((byte)i, 30, 80) }); + } + var directory = Directory.CreateTempSubdirectory(); + var path = Path.Combine(directory.FullName, "shared.ivmesh"); + try + { + Assert.Equal(geometryIds.Length, ClusterSourceWriter.Save(new ViewerDocument(scene), path, new HtmlViewerOptions())); + using var reader = new BinaryReader(File.OpenRead(path)); + Assert.Equal("IMS4"u8.ToArray(), reader.ReadBytes(4)); + reader.BaseStream.Position = 28; + long end = reader.ReadInt64(); + long first = reader.BaseStream.Position; + float? x = null; + for (int i = 0; i < geometryIds.Length; i++) + { + long start = reader.BaseStream.Position; + reader.BaseStream.Position += 24; + int vertices = reader.ReadInt32(), indices = reader.ReadInt32(); + Assert.Equal(i, reader.ReadByte()); + reader.BaseStream.Position += 3; + int normals = reader.ReadInt32(); + Assert.Equal(100 + i, reader.ReadInt64()); + reader.ReadInt32(); + int flags = reader.ReadInt32(); + long shape = reader.ReadInt64(); + float shiftX = reader.ReadSingle(); + reader.BaseStream.Position += 8; + Assert.Equal(i < 3 ? first : -1L, shape); + if (i < 3) + { + x ??= shiftX; + Assert.Equal(i * 10, shiftX - x.Value); + } + if (shape == -1 || shape == start) + reader.BaseStream.Position += vertices * (12 * (1 + normals) + ((flags & 2) != 0 ? 8 : 0)) + indices * 4; + } + Assert.Equal(end, reader.BaseStream.Position); + } + finally + { + File.Delete(path); + directory.Delete(); + } + } + [Fact] public void WritesRebasedMirroredGeometryAndPreservesMaterialAlpha() {