import assert from 'node:assert/strict'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { pathToFileURL } from 'node:url'; import { loadWasmProbe } from './wasm-probe-runtime.mjs'; import { playwright } from './part-primitive-business-cases.mjs'; export const projectionId = 'Part:desktop:Part_ProjectionOnSurface'; export { runLinkedProjectionCases as runProjectionCases } from './part-linked-projection-business-cases.mjs'; export async function runLegacyProjectionCases(ids) { if (!ids.includes(projectionId)) return []; const directory = path.resolve('docs/current/part-projection-business', new Date().toISOString().replace(/[:.]/g, '-')); const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'part-projection-business-')); fs.mkdirSync(directory, { recursive: true }); const result = { capabilityId: projectionId, status: 'failed', cases: [], stages: [], evidenceFiles: {} }; const stage = name => { result.stages.push({ name, at: new Date().toISOString() }); process.stderr.write(`Projection: ${name}\n`); }; const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] }); const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`); let kernel, browser; try { for (const file of ['tools/part-projection-business-cases.mjs', 'web/src/part-projection-task.tsx', 'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts', 'web/src/workbench-shell.tsx', 'web/src/scene-viewport.tsx', 'freecad-source/src/WebAssembly/FreeCADCoreProbe/PartProjectionDocument.h', 'freecad-source/src/Mod/Part/App/FeatureProjectOnSurface.cpp', 'freecad-source/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp', ...['js', 'wasm', 'worker.js'].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)]) result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex'); stage('adapter-compile-enter'); execFileSync(path.resolve('web/node_modules/.bin/tsc'), ['--target', 'ES2022', '--module', 'ESNext', '--moduleResolution', 'Bundler', '--strict', '--skipLibCheck', '--jsx', 'preserve', '--outDir', temporary, 'web/node_modules/vite/client.d.ts', 'web/src/part-desktop-adapter.ts', 'web/src/part-view-facade.ts'], { stdio: 'pipe' }); const facade = await import(pathToFileURL(path.join(temporary, 'part-document-facade.js'))); const adapter = await import(pathToFileURL(path.join(temporary, 'part-desktop-adapter.js'))); const { FacadeSerialQueue } = await import(pathToFileURL(path.join(temporary, 'facade-envelope.js'))); stage('native-load-enter'); ({ kernel } = await loadWasmProbe(process.env.FREECAD_PART_DOCUMENT_BUSINESS_BUILD ?? 'web/public/kernel', 'FreeCADWebDocumentProbe')); stage('native-load-complete'); const queue = new FacadeSerialQueue(); let sequence = 0; const router = { request: (_module, command, payload) => { assert.equal(command, facade.PART_DOCUMENT_COMMAND); return facade.dispatchPartDocument(queue, facade.createPartDocumentRequest(`projection-${++sequence}`, payload), kernel); } }; const document = 'ProjectionBusiness'; const request = (action, args = {}, owner = document) => router.request('Part', facade.PART_DOCUMENT_COMMAND, { schema: facade.PART_DOCUMENT_SCHEMA, module: 'Part', document: owner, action, builderInfo: true, includeMesh: true, ...args }); const call = async (action, args = {}, owner = document) => { const reply = await request(action, args, owner); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; }; const python = source => { const reply = JSON.parse(kernel.ccall('fc_web_dispatch_json', 'string', ['string'], [JSON.stringify({ cmd: 'part.documentViewCommand', args: { owner: 'DocumentProbe', document, command: 'Std_CommandLine', parameters: { operation: 'submit', source: `exec(${JSON.stringify(source)})` }, } })])); assert.equal(reply.ok, true, JSON.stringify(reply)); assert.equal(reply.result.stderr, '', JSON.stringify(reply)); }; const link = (object, subelement) => ({ documentId: document, object, subelements: [subelement] }); let selected; const execute = args => adapter.executePartFixedBoxDesktop(router, 'Part_ProjectionOnSurface', args, document, (owner, selection) => { assert.equal(owner, document); selected = selection; }); const accepted = async args => { const reply = await execute(args); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; }; const feature = (state, name = state.createdObject) => { const item = state.objects.find(o => o.name === name); assert.ok(item, `Missing ${name}`); return item; }; await call('create'); python(`import FreeCAD as App, Part\nd=App.getDocument('${document}')\ndef add(name,shape):\n obj=d.addObject('Part::Feature',name)\n obj.Shape=shape\n return obj\nadd('Support',Part.makePlane(20,20))\nadd('Source',Part.makePlane(4,3,App.Vector(2,2,5)))\nadd('Edge',Part.makeLine(App.Vector(2,2,5),App.Vector(6,2,5)))\nd.recompute()`); const fixture = await call('save', { path: '/tmp/ProjectionFixture.FCStd' }); await call('create', {}, 'ProjectionOther'); const other = await call('snapshot', {}, 'ProjectionOther'); const base = { support: link('Support', 'Face1'), selection: [link('Source', 'Face1')], direction: [0, 0, -1], mode: 'Faces', height: 0, offset: 0 }; stage('native-projection-enter'); const before = await call('readProjection'); const created = await accepted(base); const item = feature(created); const name = item.name; assert.equal(item.type, 'Part::ProjectOnSurface'); assert.equal(item.topology.valid, true); near(item.topology.area, 12); near(item.volume, 0); assert.deepEqual(item.projection, base); assert.ok(item.dependencies.includes('Support')); assert.ok(item.dependencies.includes('Source')); assert.deepEqual(selected, [{ documentId: document, object: name }]); assert.equal(created.undoCount, before.undoCount + 1); assert.deepEqual((await call('undo')).objects, before.objects); assert.deepEqual((await call('redo')).objects, created.objects); assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); record(base, { type: item.type, topology: item.topology, links: item.projection }, 'Native face projection has analytic area, source/support dependencies, selection and atomic undo/redo without changing another document'); const solidArgs = { ...base, action: 'edit', object: name, mode: 'All', height: 2 }; const solid = feature(await accepted(solidArgs)); near(solid.volume, 24); assert.equal(solid.topology.valid, true); const zRange = item => { const z = item.mesh.positions.filter((_value, index) => index % 3 === 2); return [Math.min(...z), Math.max(...z)]; }; const unshifted = zRange(solid); for (const offset of [-1, 1.5]) { const shifted = feature(await accepted({ ...solidArgs, offset })); near(shifted.volume, 24); assert.equal(shifted.projection.offset, offset); zRange(shifted).forEach((z, index) => near(z, unshifted[index] - offset)); record({ offset, direction: base.direction }, { boundsZ: zRange(shifted), volume: shifted.volume }, 'Signed offset translates the native solid along the normalized projection direction while retaining volume'); } const multiple = feature(await accepted({ ...solidArgs, selection: [...base.selection, link('Edge', 'Edge1')] })); near(multiple.volume, 24); assert.equal(multiple.projection.selection.length, 2); assert.ok(multiple.dependencies.includes('Edge')); assert.ok(multiple.topology.Edge > solid.topology.Edge); await accepted(solidArgs); record({ mode: 'All', sources: ['Source.Face1', 'Edge.Edge1'] }, { topology: multiple.topology, links: multiple.projection }, 'All mode retains both the extruded face and separately projected edge with native source links'); const moved = await call('setPosition', { object: 'Source', position: [1, 0, 0] }); near(feature(moved, name).volume, 24); assert.notDeepEqual(feature(moved, name).mesh.positions, solid.mesh.positions); const stable = await call('readProjection'); for (const args of [{ direction: [0, 0, 0] }, { height: -1 }, { mode: 'Unknown' }, { selection: [] }, { support: link('Support', 'Face99') }, { selection: [link('Missing', 'Edge1')] }, { selection: [{ ...link('Source', 'Face1'), documentId: 'ProjectionOther' }] }, { activeTask: true }, { action: 'edit', object: 'Support' }, { document: 'ProjectionOther' }, { action: 'edit', object: name, selection: [link(name, 'Face1')] }]) { const reply = await execute({ ...base, ...args }); assert.equal(reply.kind, 'error', JSON.stringify(reply)); assert.deepEqual(await call('readProjection'), stable); assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); record(args, reply.error, 'Invalid projection input rejects without changing geometry, links or history'); } const edge = feature(await accepted({ ...base, mode: 'Edges', selection: [link('Edge', 'Edge1')] })); assert.equal(edge.topology.valid, true); assert.equal(edge.topology.Edge, 1); near(edge.topology.length, 4); const wireArgs = { ...base, mode: 'Edges', selection: [link('Source', 'Wire1')] }; const wire = feature(await accepted(wireArgs)); assert.equal(wire.topology.valid, true); assert.equal(wire.topology.Edge, 4); near(wire.topology.length, 14); assert.deepEqual(wire.projection.selection, wireArgs.selection); record(wireArgs, { topology: wire.topology, links: wire.projection }, 'Native wire projection retains the source wire reference and its analytic rectangular perimeter'); const nativeStable = await call('readProjection'); for (const invalid of [{ direction: [0, 0, 0] }, { direction: ['0', 0, -1] }, { height: -1 }, { offset: '1' }, { mode: 'Unknown' }, { selection: [] }, { support: link('Support', 'Face99') }, { selection: [link('Missing', 'Edge1')] }, { selection: [link('Source', 'Face1'), link('Source', 'Face1')] }, { selection: [{ ...link('Source', 'Face1'), documentId: 'ProjectionOther' }] }, { selection: [link(name, 'Face1')] }]) { const args = { document, action: 'editProjection', object: name, ...base, ...invalid }; const reply = JSON.parse(kernel.ccall('fc_web_dispatch_json', 'string', ['string'], [JSON.stringify({ cmd: 'part.document', args })])); assert.equal(reply.ok, false, JSON.stringify(reply)); assert.deepEqual(await call('readProjection'), nativeStable); assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); record(args, { code: reply.code, error: reply.error }, 'Direct native malformed projection rejects and rolls back geometry, dependency links and history in both documents'); } python(`dependent=d.addObject('Part::Compound','ProjectionDependent')\ndependent.Links=[d.getObject('${name}')]\nindirect=d.addObject('Part::Compound','ProjectionIndirect')\nindirect.Links=[dependent]\nd.recompute()`); const cycleBefore = await call('readProjection'); for (const invalid of [{ selection: [link('ProjectionIndirect', 'Face1')] }, { support: link('ProjectionIndirect', 'Face1') }]) { const args = { ...solidArgs, ...invalid }; const rejected = await execute(args); assert.equal(rejected.kind, 'error', JSON.stringify(rejected)); assert.match(rejected.error.message, /cycle/i); assert.deepEqual(await call('readProjection'), cycleBefore); assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); record(args, rejected.error, 'Indirect source and support cycles reject without changing geometry, dependencies or undo history'); } const savedState = await call('readProjection'); const saved = await call('save', { path: '/tmp/ProjectionBusiness.FCStd' }); await call('close'); const opened = await call('open', { path: '/tmp/ProjectionBusiness.FCStd', bytes: saved.bytes }); assert.deepEqual(opened.objects, savedState.objects); near(feature(await accepted({ ...solidArgs, height: 3 })).volume, 36); const cancelBefore = await call('readProjection'); assert.equal((await accepted({ action: 'cancel' })).cancelled, true); assert.deepEqual((await call('readProjection')).objects, cancelBefore.objects); record({ height: [2, 3], edgeLength: 4, actions: ['source-move', 'save', 'close', 'open', 'edit', 'cancel'] }, { volume: 36, bytes: saved.bytes.byteLength }, 'Projection extrusion, edge geometry, source recompute, FCStd links and subsequent edits retain native semantics'); stage('native-curved-support-enter'); python(`d=App.getDocument('${document}')\ncurved=d.addObject('Part::Cylinder','CurvedSupport')\ncurved.Radius=5\ncurved.Height=10\ncurved.Angle=90\nadd('CurvedSource',Part.makeLine(App.Vector(10,3,2),App.Vector(10,3,5)))\nd.recompute()`); const curvedArgs = { support: link('CurvedSupport', 'Face1'), selection: [link('CurvedSource', 'Edge1')], direction: [-1, 0, 0], mode: 'Edges', height: 0, offset: 0 }; const curved = feature(await accepted(curvedArgs)); const checkCurved = (item, radius) => { assert.equal(item.topology.valid, true); assert.equal(item.topology.Edge, 1); near(item.topology.length, 3); assert.deepEqual(item.projection, curvedArgs); assert.ok(item.dependencies.includes('CurvedSupport')); assert.ok(item.dependencies.includes('CurvedSource')); const points = item.lines.flat(); assert.ok(points.length >= 2); for (const point of points) { near(point[0], Math.sqrt(radius ** 2 - 9)); near(point[1], 3); } near(Math.min(...points.map(p => p[2])), 2); near(Math.max(...points.map(p => p[2])), 5); }; checkCurved(curved, 5); python('curved.Radius=6\nd.recompute()'); checkCurved(feature(await call('readProjection'), curved.name), 6); const curvedSaved = await call('save', { path: '/tmp/CurvedProjection.FCStd' }); await call('close'); checkCurved(feature(await call('open', { path: '/tmp/CurvedProjection.FCStd', bytes: curvedSaved.bytes }), curved.name), 6); python(`d=App.getDocument('${document}')\nd.getObject('CurvedSupport').Radius=7\nd.recompute()`); checkCurved(feature(await call('readProjection'), curved.name), 7); record(curvedArgs, { topology: curved.topology, lines: curved.lines, editedRadii: [6, 7], savedBytes: curvedSaved.bytes.byteLength }, 'Curved native support produces the analytic cylindrical intersection, preserves links through FCStd and recomputes radius edits after reopen'); stage('native-complete'); kernel.PThread?.terminateAllThreads(); kernel = undefined; stage('native-cleanup-complete'); browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? '/usr/bin/google-chrome', headless: process.env.HEADLESS !== "0", args: ['--no-sandbox', '--disable-dev-shm-usage'] }); const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); const errors = []; page.on('pageerror', error => errors.push(String(error))); stage('browser-enter'); await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? 'http://127.0.0.1:5180'}/workbench.html?module=Part&command=Part_ProjectionOnSurface&document=${document}`); const panel = page.getByRole('region', { name: 'Projection on surface task', exact: true }); const upload = bytes => panel.getByLabel('Projection FCStd file', { exact: true }).setInputFiles({ name: 'Projection.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) }); await upload(fixture.bytes); for (const [title, object, element] of [['Support', 'Support', 'Face1'], ['Source 1', 'Source', 'Face1']]) { await panel.getByLabel(`${title} object`, { exact: true }).selectOption(object); await panel.getByLabel(`${title} element`, { exact: true }).selectOption(element); } for (const [axis, index] of [['X', 0], ['Y', 1], ['Z', 2]]) { for (const sign of [1, -1]) { await panel.getByRole('button', { name: `Toggle projection ${axis} direction`, exact: true }).click(); const direction = await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Projection direction ${axis}`, { exact: true }).inputValue())); assert.deepEqual(direction.map(Number), [0, 1, 2].map(i => i === index ? sign : 0)); } } await panel.getByLabel('Projection mode', { exact: true }).selectOption('Faces'); await panel.getByRole('button', { name: 'Create projection', exact: true }).click(); await panel.getByRole('button', { name: 'Apply changes', exact: true }).waitFor(); const browserResult = async height => { await page.waitForFunction(expected => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => o.projection?.height === expected) && !document.querySelector('button.run')?.disabled, height); const state = await page.evaluate(() => window.__freecadWorkbenchState.response.result); const item = feature(state); near(item.volume, 12 * height); assert.equal(item.topology.valid, true); return item; }; await browserResult(0); const cameraButton = panel.getByRole('button', { name: 'Use projection camera direction', exact: true }); const readDirection = async () => Promise.all(['X', 'Y', 'Z'].map(async axis => Number(await panel.getByLabel(`Projection direction ${axis}`, { exact: true }).inputValue()))); await cameraButton.click(); const initialCamera = await readDirection(); const norm = Math.hypot(1, -1, 0.8); initialCamera.forEach((value, index) => near(value, [-1 / norm, 1 / norm, -0.8 / norm][index])); const canvas = panel.getByLabel('Projection geometry', { exact: true }).locator('canvas'); await canvas.scrollIntoViewIfNeeded(); const bounds = await canvas.boundingBox(); assert.ok(bounds); await page.mouse.move(bounds.x + bounds.width * 0.5, bounds.y + bounds.height * 0.5); await page.mouse.down(); await page.mouse.move(bounds.x + bounds.width * 0.65, bounds.y + bounds.height * 0.55, { steps: 12 }); await page.mouse.up(); await cameraButton.click(); const orbitedCamera = await readDirection(); near(Math.hypot(...orbitedCamera), 1); assert.ok(orbitedCamera.some((value, index) => Math.abs(value - initialCamera[index]) > 0.01)); record({ action: 'camera-direction', orbit: [0.15, 0.05] }, { initialCamera, orbitedCamera }, 'Projection direction follows the initial and interactively orbited viewport camera'); // Restore the vertical projection used by the analytic extrusion checks below. for (const [axis, value] of [['X', 0], ['Y', 0], ['Z', -1]]) await panel.getByLabel(`Projection direction ${axis}`, { exact: true }).fill(String(value)); await panel.getByLabel('Projection mode', { exact: true }).selectOption('All'); await panel.getByLabel('Projection height', { exact: true }).fill('2'); await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await browserResult(2); await panel.getByRole('button', { name: 'Projection undo', exact: true }).click(); await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '0'); await panel.getByRole('button', { name: 'Projection redo', exact: true }).click(); await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '2'); const single = await browserResult(2); await panel.getByRole('button', { name: 'Add projection source', exact: true }).click(); await panel.getByLabel('Source 2 object', { exact: true }).selectOption('Edge'); await panel.getByLabel('Source 2 element', { exact: true }).selectOption('Edge1'); await panel.getByLabel('Projection offset', { exact: true }).fill('1.5'); await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => o.projection?.selection.length === 2 && o.projection.offset === 1.5)); const combined = await browserResult(2); assert.ok(combined.dependencies.includes('Edge')); assert.ok(combined.topology.Edge > single.topology.Edge); zRange(combined).forEach((z, index) => near(z, zRange(single)[index] - 1.5)); record({ route: 'mounted projection task', source: 'Edge.Edge1', offset: 1.5 }, { topology: combined.topology, projection: combined.projection, boundsZ: zRange(combined) }, 'Browser source addition and signed offset update native topology, dependencies and geometric bounds'); await panel.getByRole('button', { name: 'Remove source 2', exact: true }).click(); await panel.getByLabel('Projection offset', { exact: true }).fill('0'); await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => o.projection?.selection.length === 1 && o.projection.offset === 0)); const restored = await browserResult(2); assert.deepEqual(restored.projection, single.projection); assert.deepEqual(restored.topology, single.topology); assert.ok(!restored.dependencies.includes('Edge')); await panel.getByRole('button', { name: 'Save projection document', exact: true }).click(); await panel.getByRole('status').filter({ hasText: `Projection-${document}.FCStd` }).waitFor(); const bytes = await page.evaluate(async name => { const { readDocumentFile } = await import('/src/storage.ts'); return [...new Uint8Array(await readDocumentFile(`Projection-${name}.FCStd`))]; }, document); assert.ok(bytes.length > 0); for (const [width, height] of [[1440, 900], [390, 844]]) { await page.setViewportSize({ width, height }); const file = path.join(directory, `projection-${width}.png`); const png = await panel.locator('canvas').screenshot({ path: file }); const colors = await page.evaluate(async base64 => { const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode(); const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data; const colors = new Set(); for (let i = 0; i < pixels.length; i += 4) colors.add(`${pixels[i]},${pixels[i + 1]},${pixels[i + 2]}`); return colors.size; }, png.toString('base64')); assert.ok(colors > 8); assert.ok(await panel.evaluate(e => e.scrollWidth <= e.clientWidth + 1)); result.evidenceFiles[path.relative(process.cwd(), file)] = createHash('sha256').update(png).digest('hex'); } await panel.getByRole('button', { name: 'Close projection task', exact: true }).click(); await panel.getByRole('button', { name: 'Apply changes', exact: true }).waitFor({ state: 'detached' }); await page.reload(); await upload(bytes); await panel.getByLabel('Projection feature', { exact: true }).selectOption(name); await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '2'); await panel.getByLabel('Projection height', { exact: true }).fill('3'); await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await browserResult(3); assert.deepEqual(errors, []); record({ command: 'Part_ProjectionOnSurface', viewports: [1440, 390], actions: ['create', 'edit', 'undo', 'redo', 'OPFS-save', 'reload', 'FCStd-open', 'edit'] }, { volume: 36, bytes: bytes.length }, 'Mounted projection task dispatches linked geometry, persists editable FCStd through OPFS and renders desktop/mobile geometry without overflow'); stage('browser-complete'); result.status = 'not_implemented'; result.remaining = [ 'Desktop preview transaction: create on task activation, recompute live edits, commit on accept and abort all task edits on reject', 'Viewport subelement selection gates', 'Linked-object projection coverage', ]; } catch (error) { result.error = String(error.stack ?? error); process.stderr.write(result.error + '\n'); } finally { kernel?.PThread?.terminateAllThreads(); await browser?.close(); fs.rmSync(temporary, { recursive: true, force: true }); stage('cleanup-complete'); } fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n'); return [result]; }