From 5f0e82a86e6bb0d1c95e4f78c1b58ba7f87f6eb0 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:38:00 +0300 Subject: [PATCH] Cover viewer and exporter regressions --- docs/public-api.md | 2 +- src/IOViewer/Importers/GlbViewerImporter.cs | 16 +- src/IOViewer/Viewer/test/e2e/panels.spec.js | 115 +++++++++++-- src/IOViewer/Viewer/test/e2e/smoke.spec.js | 152 ++++++++++++++---- src/IOViewer/Viewer/test/e2e/ui.spec.js | 3 + .../Viewer/test/unit/modelScene.test.js | 9 +- .../IOViewer.Tests/GlbSharedGeometryTests.cs | 43 ++++- .../IOViewer.Tests/HtmlViewerExporterTests.cs | 2 +- .../ModelAndCliIntegrationTests.cs | 49 ++++++ 9 files changed, 332 insertions(+), 59 deletions(-) diff --git a/docs/public-api.md b/docs/public-api.md index 8287805..16b36de 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -94,6 +94,6 @@ HtmlViewerExporter.Save(scene, "clashes.html"); ### Importers (`IOViewer.Importers`) -- `GlbViewerImporter`: Reads binary glTF 2.0 (`.glb`) files into a `ViewerDocument` with one model. Each glTF mesh primitive becomes one `SceneGeometry`, and each node that uses it a `SceneInstance` per primitive with the node's world transform, converted from glTF's Y-up to the viewer's Z-up. Each such node also becomes a `SceneElement` (category `GLB`, named after the node, else the mesh) that all its instances belong to. A material's base colour factor is linear in glTF and becomes an sRGB colour with the same alpha. A node hierarchy that is not a tree (a node referenced twice or a cycle) is rejected with `InvalidDataException`. +- `GlbViewerImporter`: Reads binary glTF 2.0 (`.glb`) files into a `ViewerDocument` with one model. Each glTF mesh primitive becomes one `SceneGeometry`, and each node that uses it a `SceneInstance` per primitive with the node's world transform, converted from glTF's Y-up to the viewer's Z-up. Each such node also becomes a `SceneElement` (category `GLB`, named after the node, else the mesh) that all its instances belong to. A material's base colour factor is linear in glTF and becomes an sRGB colour with the same alpha. A node hierarchy that is not a tree (a node referenced twice or a cycle) is rejected with `InvalidDataException`. The importer also throws `InvalidDataException` when an explicit default scene index does not refer to a scene. - `ObjViewerImporter`: Reads Wavefront OBJ geometry into a `ViewerDocument` as is, without changing the up axis. Each object or group (`o`/`g`) becomes one `SceneGeometry` holding only the vertices its faces use, one `SceneInstance` and one `SceneElement` (category `OBJ`) with its name. Material (`.mtl`) files are not read. - `JsonViewerImporter`: Reads viewer JSON (format 2), IOScene scene files and IOViewer 0.1/0.2 snapshots (files without `Kind`) into a `ViewerDocument`. A 0.1/0.2 mesh without an element gets an element of its own. A newer format or an unknown kind is rejected with `InvalidDataException`. diff --git a/src/IOViewer/Importers/GlbViewerImporter.cs b/src/IOViewer/Importers/GlbViewerImporter.cs index 0d4fd59..7a09861 100644 --- a/src/IOViewer/Importers/GlbViewerImporter.cs +++ b/src/IOViewer/Importers/GlbViewerImporter.cs @@ -78,6 +78,15 @@ private static ViewerDocument Load(Stream stream, string documentTitle, string m using var jsonDoc = JsonDocument.Parse(jsonText); var root = jsonDoc.RootElement; + bool hasScenes = root.TryGetProperty("scenes", out var scenes); + int sceneIndex = 0; + if (root.TryGetProperty("scene", out var defaultScene)) + { + if (defaultScene.ValueKind != JsonValueKind.Number || !defaultScene.TryGetInt32(out sceneIndex)) + throw new InvalidDataException("glTF default scene index must be a 32-bit integer."); + if (sceneIndex < 0 || !hasScenes || scenes.ValueKind != JsonValueKind.Array || sceneIndex >= scenes.GetArrayLength()) + throw new InvalidDataException($"glTF default scene index {sceneIndex} does not reference a scene."); + } // Parse accessors & bufferViews if (!root.TryGetProperty("accessors", out var accessorsEl) || @@ -212,13 +221,10 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName) } } - if (root.TryGetProperty("scenes", out var scenesEl) && root.TryGetProperty("nodes", out var nodesEl)) + if (hasScenes && root.TryGetProperty("nodes", out var nodesEl)) { var nodes = nodesEl.EnumerateArray().ToArray(); - var scenes = scenesEl.EnumerateArray().ToArray(); - int sceneIndex = root.TryGetProperty("scene", out var sceneProp) ? sceneProp.GetInt32() : 0; - if (sceneIndex >= 0 && sceneIndex < scenes.Length && - scenes[sceneIndex].TryGetProperty("nodes", out var rootNodes)) + if (scenes.GetArrayLength() > 0 && scenes[sceneIndex].TryGetProperty("nodes", out var rootNodes)) { // glTF node hierarchy is a strict tree: reaching a node twice (shared child, repeated root, cycle) is invalid. var visited = new HashSet(); diff --git a/src/IOViewer/Viewer/test/e2e/panels.spec.js b/src/IOViewer/Viewer/test/e2e/panels.spec.js index 735e063..07a5eb7 100644 --- a/src/IOViewer/Viewer/test/e2e/panels.spec.js +++ b/src/IOViewer/Viewer/test/e2e/panels.spec.js @@ -36,6 +36,17 @@ const colorOf = (page, i) => }, i); const css = (page, color) => page.evaluate((c) => window.__ioviewer.scene.instance(0).mesh.material.color.clone().set(c).toArray(), color); +function buildingVariant(name, edit) { + const html = readFileSync(path.join(viewerDir, 'test-results', 'building.html'), 'utf8'); + const tag = /(', start); - const data = JSON.parse(html.slice(start, end)); const bad = (id, name, dates) => ({ id, name, type: 'construct', progress: 0, attachedElements: [300002], ...dates }); - data.timeliner.start = '0001-01-01T00:00:00Z'; - data.timeliner.tasks.unshift( - bad('B1', 'No dates', {}), - bad('B2', 'Default year', { start: '0001-01-01T00:00:00Z', end: '2026-03-03T00:00:00Z' }), - bad('B3', 'Reversed', { start: '2026-03-10T00:00:00Z', end: '2026-03-05T00:00:00Z' }), - bad('B4', 'Invalid', { start: 'soon', end: '2026-03-05T00:00:00Z' }), - { ...bad('B5', 'Unknown ids', { start: '2026-03-02T08:00:00Z', end: '2026-03-05T00:00:00Z' }), attachedElements: [999999] }, - ); - writeFileSync(path.join(viewerDir, 'test-results', 'bad-4d.html'), html.slice(0, start) + JSON.stringify(data) + html.slice(end)); + buildingVariant('bad-4d', (data) => { + data.timeliner.start = '0001-01-01T00:00:00Z'; + data.timeliner.tasks.unshift( + bad('B1', 'No dates', {}), + bad('B2', 'Default year', { start: '0001-01-01T00:00:00Z', end: '2026-03-03T00:00:00Z' }), + bad('B3', 'Reversed', { start: '2026-03-10T00:00:00Z', end: '2026-03-05T00:00:00Z' }), + bad('B4', 'Invalid', { start: 'soon', end: '2026-03-05T00:00:00Z' }), + { ...bad('B5', 'Unknown ids', { start: '2026-03-02T08:00:00Z', end: '2026-03-05T00:00:00Z' }), attachedElements: [999999] }, + ); + }); const errors = await open(page, 'bad-4d'); await rail(page, 'timeliner').click(); @@ -491,6 +550,32 @@ test.describe('malformed 4D', () => { }); test.describe('links', () => { + test('legacy files resolve members by file name and path', async ({ page }) => { + buildingVariant('legacy-links', (data) => { + const file = data.linkedFiles.find((f) => f.name === 'Structure'); + delete file.members; + const byName = data.elements.find((e) => e.name === 'Column Twin'); + const byPath = data.elements.find((e) => e.name === 'Column Twin Mirrored'); + byName.link = file.name; + byPath.link = file.path; + for (const element of data.elements) if (element !== byName && element !== byPath) delete element.link; + }); + const errors = await open(page, 'legacy-links'); + const twins = [await indexOf(page, 'Column Twin'), await indexOf(page, 'Column Twin Mirrored')]; + const slab = await indexOf(page, 'Ground Slab'); + await rail(page, 'links').click(); + const row = sidePanel(page, 'links').locator('.ioviewer-link').filter({ hasText: 'Structure' }); + await expect(row.locator('.ioviewer-row-count')).toHaveText('2'); + const checkbox = row.getByRole('checkbox'); + await expect(checkbox).toBeChecked(); + await checkbox.uncheck(); + for (const index of twins) expect(await visible(page, index)).toBe(false); + expect(await visible(page, slab)).toBe(true); + await checkbox.check(); + for (const index of twins) expect(await visible(page, index)).toBe(true); + expect(errors).toEqual([]); + }); + test('unchecking a link hides its elements; checking shows them again but not those the user hid', async ({ page }) => { const errors = await open(page); const duct = await indexOf(page, 'Supply Duct SA-1'); diff --git a/src/IOViewer/Viewer/test/e2e/smoke.spec.js b/src/IOViewer/Viewer/test/e2e/smoke.spec.js index 02a991e..125a700 100644 --- a/src/IOViewer/Viewer/test/e2e/smoke.spec.js +++ b/src/IOViewer/Viewer/test/e2e/smoke.spec.js @@ -133,18 +133,46 @@ test('adaptive orbit compacts a cell on the GPU and full detail and picking stil expect(result.compact.stats).toEqual({ drawn: 24, inView: 48, draws: 1 }); expect(result.far).toBe(0); expect(result.restored).toEqual(result.full); - expect(errors).toEqual([]); -}); - -test('empty document shows "no geometry"', async ({ page }) => { - const { errors, requests } = await open(page, 'empty'); - await expect(page.getByText('Нет геометрии')).toBeVisible(); - await expect(page.locator('#ioviewer-status')).toHaveText('Выбрано: 0 · Элементов: 0'); + await nextFrame(page); + await page.evaluate(() => { + const { scene, motionDetail } = window.__ioviewer; + // Exercise the render loop after the controller has budgeted for per-instance detail in a single cell. + motionDetail.budget = 34; + motionDetail._refine = true; + window.orbitFrames = []; + const end = motionDetail.end.bind(motionDetail); + motionDetail.end = (now) => { + window.orbitFrames.push({ threshold: motionDetail.minPixels, ...scene.drawStats() }); + end(now); + }; + }); + const { width, height } = page.viewportSize(); + await page.mouse.move(width / 2, height / 2); + await page.mouse.down(); + await page.mouse.move(width / 2 + 14, height / 2); + await page.mouse.up(); + await expect.poll(() => page.evaluate(() => window.orbitFrames.some((frame) => frame.threshold > 0 && frame.drawn < frame.inView))).toBe(true); + await expect.poll(() => page.evaluate(() => window.orbitFrames.at(-1))).toEqual({ threshold: 0, ...result.full.stats }); expect(errors).toEqual([]); - expect(requests).toEqual([]); }); +for (const [locale, message, status] of [ + ['ru-RU', 'Нет геометрии', 'Выбрано: 0 · Элементов: 0'], + ['en-US', 'No geometry', 'Selected: 0 · Elements: 0'], +]) { + test.describe(locale, () => { + test.use({ locale }); + test('empty document shows the localized message and zero counts', async ({ page }) => { + const { errors, requests } = await open(page, 'empty'); + await expect(page.getByText(message)).toBeVisible(); + await expect(page.locator('#ioviewer-status')).toHaveText(status); + expect(errors).toEqual([]); + expect(requests).toEqual([]); + }); + }); +} + test('startup profiling samples load and first render once', async ({ page }) => { await page.addInitScript(() => { window.startupSamples = []; @@ -192,6 +220,33 @@ test('ModelScene addresses elements by index across meshes and materials', async expect(errors).toEqual([]); }); +test('one material bucket draws and picks elements in several merged chunks and instanced cells', async ({ page }) => { + await page.addInitScript(() => { window.IOVIEWER_TEST = { mergedCap: 0, chunkVertices: 24 }; }); + const { errors } = await open(page, 'building'); + const indices = ['Ground Slab', 'Floor Slab Level 2', 'Column A1 Level 1', 'Column D2 Level 1'] + .map((name) => building.Elements.findIndex((element) => element.Name === name)); + const result = await page.evaluate((indices) => { + const { scene, controls, picker, camera } = window.__ioviewer; + const meshes = indices.map((i) => scene.instance(scene.instancesOf(i)[0]).mesh); + const rect = picker.renderer.domElement.getBoundingClientRect(); + const hits = indices.map((i) => { + scene.isolate([i]); + controls.fitBox(scene.elementBox(i), false); + return picker.pick(rect.left + rect.width / 2, rect.top + rect.height / 2)?.element; + }); + scene.showAll(); + return { + sameMaterial: meshes.every((mesh) => mesh.material === meshes[0].material), + instanced: meshes.map((mesh) => mesh.isInstancedMesh === true), + meshCount: new Set(meshes).size, + hits, + }; + }, indices); + expect(result).toEqual({ sameMaterial: true, instanced: [false, false, true, true], meshCount: 4, hits: indices }); + await renderedCenter(page); + expect(errors).toEqual([]); +}); + // Mean grey level (0..255) of the 4x4 screen pixels around (x, y); the PNG is decoded by the page itself. async function brightness(page, x, y) { const png = await page.screenshot({ clip: { x: x - 2, y: y - 2, width: 4, height: 4 } }); @@ -208,6 +263,39 @@ async function brightness(page, x, y) { }, png.toString('base64')); } +for (const instanced of [false, true]) { + test(`textures sample the expected checker squares (${instanced ? 'instanced' : 'merged'})`, async ({ page }) => { + if (instanced) await page.addInitScript(() => { window.IOVIEWER_TEST = { mergedCap: 0, minRepeats: 1 }; }); + const { errors } = await open(page, 'textured'); + expect(await page.evaluate(() => window.__ioviewer.scene.instance(0).mesh.isInstancedMesh === true)).toBe(instanced); + const coords = await page.evaluate(() => { + const { scene, controls, camera } = window.__ioviewer; + const { rtcOffset } = JSON.parse(document.getElementById('ioviewer-meta').textContent); + const rtc = camera.position.clone().fromArray(rtcOffset); + const center = camera.position.clone().set(0, -2, 1.5).sub(rtc); + controls._set(center.clone().addScaledVector(camera.position.clone().set(0, -1, 0), 3), center); + camera.updateMatrixWorld(); + scene.setDisplayMode('textures'); + const rect = document.getElementById('ioviewer-canvas').getBoundingClientRect(); + // The 48-sided cylinder has radius 2 and UVs (arc length, height) in metres. Sample the centres of + // checker squares 1/16 m wide on the first facet after -Y, interpolating between its endpoints. + const a = 3 * Math.PI / 2, b = a + Math.PI / 24; + const first = center.clone().set(2 * Math.cos(a), 2 * Math.sin(a), 0); + const last = center.clone().set(2 * Math.cos(b), 2 * Math.sin(b), 0); + return [[9.53125, 1.53125], [9.59375, 1.53125], [9.65625, 1.53125], [9.53125, 1.59375]] + .map(([u, z]) => { + const p = first.clone().lerp(last, (u / 2 - a) / (b - a)).setZ(z).sub(rtc).project(camera); + return [Math.round(rect.left + (p.x + 1) * rect.width / 2), Math.round(rect.top + (1 - p.y) * rect.height / 2)]; + }); + }); + await expect.poll(async () => { + const [light, darkU, repeatU, darkV] = await Promise.all(coords.map(([x, y]) => brightness(page, x, y))); + return Math.min(light, repeatU) - Math.max(darkU, darkV); + }).toBeGreaterThan(35); + expect(errors).toEqual([]); + }); +} + test('a mirrored instance is shaded like its unmirrored twin', async ({ page }) => { const { errors } = await open(page, 'building'); const twins = ['Column Twin', 'Column Twin Mirrored'].map((n) => building.Elements.findIndex((e) => e.Name === n)); @@ -376,27 +464,33 @@ test('context lost shows the reload message', async ({ page }) => { await expect(page.locator('#ioviewer-message')).toBeVisible(); }); -test('pick element with index > 4096 (large fixture)', async ({ page }) => { - const { errors } = await open(page, 'large'); - for (const element of [4097, 15123, 19999]) { - // Zoomed onto the element (it is 0.3 m among 20000), the centre of its top face. - const hit = await page.evaluate((element) => { - const { scene, controls, picker, camera } = window.__ioviewer; - const box = scene.elementBox(element); - controls.fitBox(box, false); - camera.updateMatrixWorld(); - const top = box.getCenter(box.min.clone()); - top.z = box.max.z; - const p = top.clone().project(camera); - const rect = document.getElementById('ioviewer-canvas').getBoundingClientRect(); - const found = picker.pick(rect.left + ((p.x + 1) / 2) * rect.width, rect.top + ((1 - p.y) / 2) * rect.height); - return found && { element: found.element, distance: found.point.distanceTo(top), slot: scene.instance(scene.instancesOf(element)[0]).slot }; - }, element); - expect(hit.element).toBe(element); - expect(hit.distance).toBeLessThan(0.01); - } - expect(errors).toEqual([]); -}); +for (const pickFloat of [true, false]) { + test(`picking round-trips high slots and surface points (pickFloat: ${pickFloat})`, async ({ page }) => { + await page.addInitScript((value) => { window.IOVIEWER_TEST = { pickFloat: value }; }, pickFloat); + const { errors } = await open(page, 'large'); + if (!pickFloat) expect(await page.evaluate(() => window.__ioviewer.picker._float)).toBe(false); + for (const element of [4097, 15123, 19999]) { + // Zoomed onto the element (it is 0.3 m among 20000), the centre of its top face. + const hit = await page.evaluate((element) => { + const { scene, controls, picker, camera } = window.__ioviewer; + const box = scene.elementBox(element); + controls.fitBox(box, false); + camera.updateMatrixWorld(); + const top = box.getCenter(box.min.clone()); + top.z = box.max.z; + const p = top.clone().project(camera); + const rect = document.getElementById('ioviewer-canvas').getBoundingClientRect(); + const found = picker.pick(rect.left + ((p.x + 1) / 2) * rect.width, rect.top + ((1 - p.y) / 2) * rect.height); + return found && { element: found.element, distance: found.point.distanceTo(top), slot: scene.instance(scene.instancesOf(element)[0]).slot }; + }, element); + expect(hit).not.toBeNull(); + expect(hit.slot).toBeGreaterThanOrEqual(256); + expect(hit.element).toBe(element); + expect(hit.distance).toBeLessThan(0.01); + } + expect(errors).toEqual([]); + }); +} test('a restored context keeps the reload message and nothing throws: no render, no pick', async ({ page }) => { const { errors } = await open(page, 'building'); diff --git a/src/IOViewer/Viewer/test/e2e/ui.spec.js b/src/IOViewer/Viewer/test/e2e/ui.spec.js index d87947f..2dec448 100644 --- a/src/IOViewer/Viewer/test/e2e/ui.spec.js +++ b/src/IOViewer/Viewer/test/e2e/ui.spec.js @@ -162,6 +162,9 @@ test('hotkeys: I isolates, H hides, Shift+H shows all, F zooms to the selection; await sidePanel(page, 'model').locator('input').fill(''); await sidePanel(page, 'model').locator('input').press('KeyH'); expect(await visible(page, d2)).toBe(true); + await sidePanel(page, 'model').locator('input').press('Escape'); + await expect(sidePanel(page, 'model').locator('input')).toBeFocused(); + expect(await selected(page)).toEqual([d2]); await page.mouse.click(...blank); // leaves the field; H now hides await page.mouse.click(...(await screenAt(page, d2))); await page.keyboard.press('KeyH'); diff --git a/src/IOViewer/Viewer/test/unit/modelScene.test.js b/src/IOViewer/Viewer/test/unit/modelScene.test.js index e89eb56..13fd91d 100644 --- a/src/IOViewer/Viewer/test/unit/modelScene.test.js +++ b/src/IOViewer/Viewer/test/unit/modelScene.test.js @@ -139,8 +139,13 @@ test('<=256 changed slots -> updateRanges, >256 -> full upload', () => { }; uploaded(); const version = texture.version; - scene.setHighlighted([3, 4, 5]); - assert.equal(texture.updateRanges.length, 3); + const highlighted = [3, 9, 257]; + const unchanged = [2, 4, 8, 10, 256, 258]; + const original = unchanged.map((i) => bytes(scene, i)); + scene.setHighlighted(highlighted); + assert.deepEqual(texture.updateRanges, highlighted.map((i) => ({ start: scene.instance(i).slot * 4, count: 4 }))); + assert.deepEqual(highlighted.map((i) => bytes(scene, i)), highlighted.map(() => [245, 158, 11, 255])); + assert.deepEqual(unchanged.map((i) => bytes(scene, i)), original); assert.equal(texture.version, version + 1); uploaded(); scene.setHighlighted(Array.from({ length: 300 }, (_, i) => i)); diff --git a/tests/IOViewer.Tests/GlbSharedGeometryTests.cs b/tests/IOViewer.Tests/GlbSharedGeometryTests.cs index 5268459..3efa979 100644 --- a/tests/IOViewer.Tests/GlbSharedGeometryTests.cs +++ b/tests/IOViewer.Tests/GlbSharedGeometryTests.cs @@ -11,6 +11,12 @@ public class GlbSharedGeometryTests { // One triangle mesh (first vertex configurable, others (1,0,0), (0,1,0)) plus the given nodes and scene roots. internal static ViewerDocument Import(string nodesJson, string rootNodes, float[]? vertex0 = null) + { + using var glb = BuildGlb(nodesJson, $$""" "scenes": [{ "nodes": [{{rootNodes}}] }] """, vertex0); + return GlbViewerImporter.Load(glb, "Test"); + } + + internal static MemoryStream BuildGlb(string nodesJson, string sceneProperties, float[]? vertex0 = null) { var bin = new byte[44]; float[] pos = [vertex0?[0] ?? 0, vertex0?[1] ?? 0, vertex0?[2] ?? 0, 1, 0, 0, 0, 1, 0]; @@ -31,7 +37,7 @@ internal static ViewerDocument Import(string nodesJson, string rootNodes, float[ ], "meshes": [{ "name": "Tri", "primitives": [{ "attributes": { "POSITION": 0 }, "indices": 1 }] }], "nodes": [{{nodesJson}}], - "scenes": [{ "nodes": [{{rootNodes}}] }] + {{sceneProperties}} } """; @@ -40,8 +46,8 @@ internal static ViewerDocument Import(string nodesJson, string rootNodes, float[ Array.Fill(paddedJson, (byte)0x20); jsonBytes.CopyTo(paddedJson, 0); - using var ms = new MemoryStream(); - using var bw = new BinaryWriter(ms); + var ms = new MemoryStream(); + using var bw = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true); bw.Write(0x46546C67u); bw.Write(2u); bw.Write((uint)(12 + 8 + paddedJson.Length + 8 + bin.Length)); @@ -53,7 +59,7 @@ internal static ViewerDocument Import(string nodesJson, string rootNodes, float[ bw.Write(bin); bw.Flush(); ms.Position = 0; - return GlbViewerImporter.Load(ms, "Test"); + return ms; } private static void AssertNear(Vector3d expected, Vector3d actual) @@ -99,9 +105,34 @@ public void NodeRotationQuaternion_IsApplied() [Fact] public void NestedNodes_ComposeParentThenChild() { - var doc = Import("""{ "translation": [0,5,0], "children": [1] }, { "mesh": 0, "translation": [1,0,0] }""", "0"); + var doc = Import(""" + { "translation": [5,7,11], "rotation": [0,0,0.7071068,0.7071068], "scale": [2,3,4], "children": [1] }, + { "mesh": 0, "translation": [1,2,3], "rotation": [0,0.7071068,0,0.7071068], "scale": [2,3,4] } + """, "0", [1, 1, 1]); + + // Child takes (1,1,1) to (5,5,1), then parent to (-10,17,15) before Y-up to Z-up. + AssertNear(new Vector3d(-10, -15, 17), World(doc, 0)); + } + + [Fact] + public void DefaultScene_SelectsTheReferencedScene() + { + using var glb = BuildGlb("""{ "mesh": 0 }""", """ "scene": 1, "scenes": [{}, { "nodes": [0] }] """); + Assert.Single(GlbViewerImporter.Load(glb).Scene.Instances); + } - AssertNear(new Vector3d(1, 0, 5), World(doc, 0)); + [Theory] + [InlineData("\"scene\": -1, \"scenes\": [{ \"nodes\": [0] }]")] + [InlineData("\"scene\": 1, \"scenes\": [{ \"nodes\": [0] }]")] + [InlineData("\"scene\": 0, \"scenes\": []")] + [InlineData("\"scene\": 0")] + [InlineData("\"scene\": 2147483648, \"scenes\": [{}]")] + [InlineData("\"scene\": \"0\", \"scenes\": [{}]")] + public void DefaultScene_RejectsInvalidReference(string sceneProperties) + { + using var glb = BuildGlb("""{ "mesh": 0 }""", sceneProperties); + var error = Assert.Throws(() => GlbViewerImporter.Load(glb)); + Assert.Contains("glTF default scene index", error.Message); } [Fact] diff --git a/tests/IOViewer.Tests/HtmlViewerExporterTests.cs b/tests/IOViewer.Tests/HtmlViewerExporterTests.cs index 4457f63..03a71b4 100644 --- a/tests/IOViewer.Tests/HtmlViewerExporterTests.cs +++ b/tests/IOViewer.Tests/HtmlViewerExporterTests.cs @@ -1071,7 +1071,7 @@ public void Viewpoints_RejectInvalidStateBeforeWriting(string invalid, string me } [Fact] - public void Export_200kElements_DoesNotBuildWholeString() + public void Export_200kElements_WritesCompletePayloadWithSharedGeometry() { const int count = 200_000; var scene = TestScenes.Empty(); diff --git a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs index f206e81..0bc1edd 100644 --- a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs +++ b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs @@ -60,6 +60,29 @@ v 0 1 0 f 1 2 3 """; + [Fact] + public void Cli_MissingInputAndUnknownOption_ReportTheCorrectExitCodes() + { + string input = Path.Combine(Path.GetTempPath(), $"missing_{Guid.NewGuid():N}.obj"); + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + Console.SetError(errors); + Assert.Equal(1, Program.Main(["--unknown-option"])); + Assert.Contains("--unknown-option", errors.ToString()); + errors.GetStringBuilder().Clear(); + + Assert.Equal(2, Program.Main([input])); + Assert.Contains($"File not found: '{input}'", errors.ToString()); + Assert.False(File.Exists(Path.ChangeExtension(input, ".html"))); + } + finally + { + Console.SetError(origErr); + } + } + [Fact] public void Cli_AnOutputThatCannotBeWritten_GivesExitCode3() { @@ -200,6 +223,32 @@ f 1 2 9 } } + [Fact] + public void Cli_InvalidGlbDefaultScene_FailsAtLoadAndKeepsExistingOutput() + { + string input = Path.Combine(Path.GetTempPath(), $"test_model_{Guid.NewGuid():N}.glb"); + string output = Path.ChangeExtension(input, ".html"); + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + using var glb = GlbSharedGeometryTests.BuildGlb("""{ "mesh": 0 }""", """ "scene": 1, "scenes": [{ "nodes": [0] }] """); + File.WriteAllBytes(input, glb.ToArray()); + File.WriteAllText(output, "previous export"); + Console.SetError(errors); + + Assert.Equal(3, Program.Main([input, "-o", output])); + Assert.Contains($"Failed to load '{input}': glTF default scene index 1", errors.ToString()); + Assert.Equal("previous export", File.ReadAllText(output)); + } + finally + { + Console.SetError(origErr); + File.Delete(input); + File.Delete(output); + } + } + [Fact] public void Cli_InvalidGeometryInJson_FailsAtExportAndKeepsExistingOutput() {