diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f45322a..ee6cad09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ All notable changes to Kromacut are documented in this file. - **Pull request CI and `test:e2e:all`** - Pull requests into `develop` and `main`, and pushes to them, now run lint, the build, unit tests, the desktop app's Rust tests (`cargo test` on Linux, macOS, and Windows), and every Playwright e2e suite in parallel jobs, with cached npm packages, Chromium, and cargo builds. The other Linux jobs run on Ubuntu 24.04 rather than `ubuntu-latest` (Ubuntu 26.04), where Playwright cannot install Chromium, and the Chromium cache is keyed by runner image. One `CI passed` check summarizes the result. Fork pull requests get a read-only token and no secrets. `npm run test:e2e:all` runs the same suites locally one after another: the `@smoke` tests, then the docs, landing, privacy, terms, 404, i18n, and i18n build suites, each on a fresh server. It fails if any suite fails, if a Playwright config isn't in the suite list, or if a test isn't run by any suite; the long `@full` export matrix stays on demand. Area specs now refuse to run under the wrong Playwright config and name the script to use. Palette Proof, the Settings legal links, and the adaptive Stack Matrix round trip were not in any suite and now run with `@smoke`. - **Cats Exact benchmark reproducibility** - Audited the stale replay fingerprint against historical prediction changes while preserving captured observations and artifact hashes. Calibrated benchmarks capture provenance before optimization, pin archived source and provenance to one resolved commit, and save full results before golden assertions. CLI validation rejects invalid case/head/grouping selections and report paths that alias saved inputs, and checks replay results against preparation checksums; cached preparation requires an uncached Exact result and rejects mismatched physical/separation settings, repeat budgets, profiles, palettes, and model contexts. Fresh-stack multi-head measurements support warmed repeated samples, deterministic result checks, and separate fitting, optimization, analysis, and build-validation timing. The cats fixtures record the profile hash of the committed LF file instead of its Windows CRLF form, and `.kfil` and performance fixture JSON files are checked out byte-for-byte on every platform, so the immutability check passes on macOS and Linux; cached multi-head preparation still accepts results captured from CRLF checkouts of the same profile. - **Multi-head printing guide** - New in-app documentation page explaining Multi-head printing: prerequisites, how layers become color runs and windows, the Head Schedule, the combination search space, Color grouping, and what Fast, Balanced, and Thorough search depth change, with four explanatory diagrams. The guide, navigation metadata, and diagrams are available in all 12 languages, with measured translated labels and reciprocal Auto-paint links. Covers routed preview colors, 3MF head assignments and M600 checkpoints, single-head fallback, and cancellation when the image changes. Regression checks require matching guide metadata and complete diagram catalogs and label bounds; browser coverage loads the guide and all four illustrations in every language. -- **Multi-head printing** - Auto-paint can analyze per-pixel filament orders across 2–8 heads in a background worker. Successful builds route every color region through its per-layer filament path and scheduled physical head; the preview shows each region’s predicted blend, corrected by the same calibration evidence as single-head builds, and can display its physical filament instead. All smoothing strengths share conforming region boundaries and closed layer geometry, with chunked generation to keep builds responsive. Multi-head 3MFs retain that geometry and physical filament colors, use the selected head count and head assignments, and insert M600 pause markers at exactly the Head Schedule’s swap checkpoints. The download menu offers only 3MF for multi-head builds, as it does for Flat Paint, because STL can't carry head routing. Single-head fallback builds still offer STL. Selected heads beyond the filament count remain EMPTY, and Center/Edge priorities use the same weighted targets as normal Auto-paint; colors with zero regional weight retain printable surfaces through palette matching and finite routing groups without changing weighted centroids. Fast/Balanced/Thorough controls search effort with bounded deterministic sampling. A **Color grouping** control chooses the search targets: Layer-based merges colors sharing a printer layer; Color-based keeps hues separate within a bounded group budget while preserving every member’s original print layer. At least one group is retained per occupied layer, including visible regions with zero regional weight, so capped palettes keep every printable color assigned without changing scoring weights. Color-based can produce more printed colors, but does not guarantee lower color error. Fast fitted-optics simulation nominates a bounded shortlist; windows and final region paths are scored with the full appearance model and usage-weighted CIEDE2000 on the original grouped colors. Fully scored assignments are reused when their physical context is unchanged, avoiding repeated broad searches during reconciliation. The current order remains available during reconciliation, and calibrated preview colors and the 0.25 minimum predicted gain gate are retained. Head count, search depth, color grouping, and the mode toggle persist through fallback builds and retain edits made during analysis; Multi-head and Flat Paint are mutually exclusive. Worker errors, unusable or non-improving plans, and plans whose predicted usage-weighted mean CIEDE2000 gain over the normal stack is below 0.25 retain the normal single-head model, with a notice and its original start color and swaps. Instructions follow the built snapshot, and before the first multi-head build **Copy** gives the same build prompt the panel shows, not single-head swaps; fallback builds copy their single-head plan. Image changes cancel pending analysis and discard obsolete builds. Controls, notices, schedules, copied text, and usage guides are localized into all 12 languages. Added region/filament routing, head/extruder, pause, smoothing/topology, fallback, predicted gain, async lifecycle, worker failure, browser settings-persistence, and 3MF-only download menu regression coverage. Color-group regressions cover capped palettes crossing physical layer boundaries, and calibrated image measurements use final-stack surfaces with CIEDE2000. Added full-model shortlist, proof-anchor, weighted reconciliation, seeded corrected multi-window routing, and bounded-evaluation regressions plus reproducible measured-profile cats/Rocco benchmarks; removed unused LUT analyzers and test-only assignment bookkeeping. +- **Multi-head printing** - Auto-paint can analyze per-pixel filament orders across 2–8 heads in a background worker. Successful builds route every color region through its per-layer filament path and scheduled physical head; the preview shows each region’s predicted blend, corrected by the same calibration evidence as single-head builds, and can display its physical filament instead. All smoothing strengths share conforming region boundaries and closed layer geometry, with chunked generation to keep builds responsive. Multi-head 3MFs retain that geometry and physical filament colors, use the selected head count and head assignments, and insert M600 pause markers at exactly the Head Schedule’s swap checkpoints. The download menu offers only 3MF for multi-head builds, as it does for Flat Paint, because STL can't carry head routing. Single-head fallback builds still offer STL. Selected heads beyond the filament count remain EMPTY, and Center/Edge priorities use the same weighted targets as normal Auto-paint; colors with zero regional weight retain printable surfaces through palette matching and finite routing groups without changing weighted centroids. Fast/Balanced/Thorough controls search effort with bounded deterministic sampling. A **Color grouping** control chooses the search targets: Layer-based merges colors sharing a printer layer; Color-based keeps hues separate within a bounded group budget while preserving every member’s original print layer. At least one group is retained per occupied layer, including visible regions with zero regional weight, so capped palettes keep every printable color assigned without changing scoring weights. Color-based can produce more printed colors, but does not guarantee lower color error. Fast fitted-optics simulation nominates a bounded shortlist; windows and final region paths are scored with the full appearance model and usage-weighted CIEDE2000 on the original grouped colors. Fully scored assignments are reused when their physical context is unchanged, avoiding repeated broad searches during reconciliation. The current order remains available during reconciliation, and calibrated preview colors and the 0.25 minimum predicted gain gate are retained. Head count, search depth, color grouping, and the mode toggle persist through fallback builds and retain edits made during analysis; Multi-head and Flat Paint are mutually exclusive. Worker errors, unusable or non-improving plans, and plans whose predicted usage-weighted mean CIEDE2000 gain over the normal stack is below 0.25 retain the normal single-head model, with a notice and its original start color and swaps. Instructions follow the built snapshot, and before the first multi-head build **Copy** gives the same build prompt the panel shows, not single-head swaps; fallback builds copy their single-head plan. Image changes cancel pending analysis and discard obsolete builds. Controls, notices, schedules, copied text, and usage guides are localized into all 12 languages. Added region/filament routing, head/extruder, pause, smoothing/topology, fallback, predicted gain, async lifecycle, worker failure, browser settings-persistence, and 3MF-only download menu regression coverage. Color-group regressions cover capped palettes crossing physical layer boundaries, and calibrated image measurements use final-stack surfaces with CIEDE2000. Added full-model shortlist, proof-anchor, weighted reconciliation, seeded corrected multi-window routing, and bounded-evaluation regressions plus reproducible measured-profile cats/Rocco benchmarks; removed unused LUT analyzers, test-only assignment bookkeeping, and an unreachable per-nozzle voxel export path, so multi-head export progress no longer reserves an idle span. - **Multi-head filament requirements** - Head schedules use final per-color paths only on layers those regions can print, avoiding reloads for abandoned filaments and unprinted suffixes while retaining zero-weight visible regions, useful preloads, and idle-head carryover. Height dithering resolves the actual filtered pixels on the preview's cropped block grid in the analysis worker; routing validation retains those printed surface limits. Added deterministic unused-load, active-layer head coverage, shared-block dithering, cropped-pixel scheduling, swap-count, copied-instruction, and physical 3MF regression coverage. - **Awards page and Snapmaker Innovation Fund winner badge** - A new Awards page shows Kromacut's Snapmaker Innovation Fund Winner medal, linked to the Snapmaker Innovation Fund page. It is available in all 12 languages, prerendered for search engines, and listed in the sitemap. The website footer and the Settings links open it; the desktop app opens it in the system browser. The website and the README each gain an Awards section near the bottom. The badges embed Snapmaker's official logo files unaltered. A maintenance script regenerates the badge SVGs and the PNGs rendered from them; pages show the PNGs because Safari and other WebKit views draw the SVG lettering at the wrong font weight. Added route, static-page, Settings-link, and landing browser coverage. Privacy and Terms browser tests now account for all eight footer links, with the Privacy suite checking keyboard focus from Support through Awards to Privacy, restoring both suites after the Awards link was added. @@ -53,7 +53,7 @@ All notable changes to Kromacut are documented in this file. - **Smooth Meshing strengths** - Choose None, Minimal, Medium, or Aggressive for preview and exported geometry. Medium preserves the previous enabled result; saved on/off settings migrate to Medium/None. Aggressive smooths remaining diagonal stair steps with a stable finishing pass inside the existing movement limit, while avoiding redundant boundary-map copies between passes. Print instructions and 3MF metadata record the built strength. Added topology and export regression coverage for every preset, strength-ordering checks across diagonal orientations, and a repeatable comparison benchmark. - **Desktop file associations** - Desktop packages register `.kfil` and legacy `.kapp` filament profiles and `.kpal` palettes with Kromacut file icons. Opening a file launches Kromacut or delivers it to the existing window, imports through the normal validation/migration and calibration-preservation rules, and selects the resulting saved item, including existing content duplicates. External imports wait until an open palette editor, calibration dialog, profile Rename/Save New form, or filament-row edit is finished or cancelled, preserving drafts and the profile being edited. Name/HD inputs, color and TD-conversion popovers, and pending debounced color updates hold both profile and palette imports; committed changes then use the normal unsaved-edit confirmation. Overlapping manual and desktop imports merge with the latest saved list, preserving files imported while a manual read is pending. Late Palette Proof saves merge into the original profile's latest data without removing newer imports, and cannot recreate a deleted profile or attach old evidence after its filaments change. Multi-profile batches load the final saved version after duplicate handling and later updates. Profile opening protects unsaved filament edits, including newly applied calibration measurements, with a confirmation dialog; unreadable, invalid, oversized, or unpersistable imports report an error. Linux packages include MIME definitions, file-forwarding launchers, document icons, and cache refresh scripts; portable AppImages require desktop integration. Added native queue, import, packaging, and browser regression coverage, including overlapping manual/desktop imports, late proof saves after closing or changing their owner, batch selection, imports queued during editing, saving/cancelling profile forms, and retrying after a profile save failure. - **README video guides** - Linked the Kromacut tutorial and project introduction in side-by-side video cards with thumbnail previews. -- **Multi-extruder 3MF export** - The 3MF exporter can now write a multi-extruder project: an extruder count, pause (`M600`) markers at chosen layers for head swaps, and per-nozzle voxel meshes so each head's material is its own object. Diagonal voxel contacts preserve independently closed surface fans through export, physical Z gaps stay capped, and representative nozzle colors retain physical filament overrides. Smoothed or transformed meshes and scenes without compatible voxel metadata retain their original geometry. Per-nozzle reconstruction yields during mask merging, face generation, edge pairing, and triangulation, with progress updates. The smooth mesher also accepts an optional combined mask with shared cap/wall subdivisions so adjacent color groups remain joined at seam junctions; skipping corner repair keeps diagonal surface fans separate in both meshers. Not reachable from the app yet. Added occupancy, indexed topology, smoothing preservation, responsiveness, transform, physical-color, and combined-mask meshing regression tests. +- **Multi-extruder 3MF export** - The 3MF exporter can now write a multi-extruder project: an extruder count and pause (`M600`) markers at chosen layers for head swaps. Each nozzle-tagged mesh keeps its original geometry, transforms, and smoothing. Added transform and smoothing preservation regression tests. ### Changed diff --git a/src/lib/export3mf.ts b/src/lib/export3mf.ts index 5a8dc56e..62fdc7a7 100644 --- a/src/lib/export3mf.ts +++ b/src/lib/export3mf.ts @@ -4,7 +4,6 @@ import { MINIMAL_PROJECT_SETTINGS, KROMACUT_CONFIG } from './slicerDefaults'; import { clampProgress, exportMeshProgress, exportZipProgress, progressInSpan } from './progress'; import { normalizeHexColor } from './colorUtils'; import type { SmoothMeshingStrength } from '../types'; -import { buildNozzleVoxelMeshAsync, type NozzleLayerRecord } from './voxelMesh'; export interface Export3MFOptions { layerHeight?: number; @@ -46,8 +45,6 @@ type ExportGeometrySource = { positions: ArrayLike; indices?: ArrayLike; itemSize?: number; - /** Keep coincident vertices belonging to separate voxel surface fans distinct. */ - preserveVertexIndices?: boolean; }; function utf8ByteLength(value: string): number { @@ -117,7 +114,6 @@ function getKromacutExportGeometry(geometry: THREE.BufferGeometry): ExportGeomet positions: source.positions, indices: source.indices, itemSize: source.itemSize ?? 3, - preserveVertexIndices: source.preserveVertexIndices === true, }; } @@ -134,183 +130,6 @@ function generateUUID() { }); } -/** - * Build one manifold THREE.Mesh per nozzle from scene meshes tagged with - * userData.nozzleIndex. Each nozzle's per-layer pixel masks are OR-ed and - * fed to buildNozzleVoxelMesh, which preserves closed surface fans at diagonal - * contacts and removes internal faces at layer or color boundaries. Fall back - * to the original meshes when smoothing is enabled or the scene cannot share an - * untransformed voxel grid. - */ -async function buildNozzleManifoldMeshes( - meshes: THREE.Mesh[], - layerFilamentColors?: string[], - onProgress?: (progress: number) => void -): Promise { - type LayerData = { - baseZ_mm: number; - topZ_world: number; - mask: Uint8Array; - width: number; - height: number; - pixelSize: number; - }; - - const nozzleLayerMap = new Map>(); - const nozzleHex = new Map(); - let heightScale = 1; - let heightScaleComputed = false; - const identityMatrix = new THREE.Matrix4(); - let grid: { width: number; height: number; pixelSize: number } | undefined; - let lastYield = performance.now(); - const maybeYield = async (progress: number) => { - onProgress?.(progress); - if (performance.now() - lastYield >= 8) { - await new Promise((resolve) => setTimeout(resolve, 0)); - lastYield = performance.now(); - } - }; - - for (const [meshIndex, mesh] of meshes.entries()) { - const nozzleIndex = mesh.userData?.nozzleIndex; - if (typeof nozzleIndex !== 'number' || !mesh.matrixWorld.equals(identityMatrix)) return []; - - const rawGeom = mesh.geometry?.userData?.kromacutExportGeometry as - Record | undefined; - // This existing source flag disables pixel-based reconstruction for - // smoothed geometry, even when export strength metadata is omitted. - if (rawGeom?.compactHeightfield === false) return []; - const activePixels = rawGeom?.activePixels as Uint8Array | undefined; - const width = rawGeom?.width as number | undefined; - const height = rawGeom?.height as number | undefined; - const pixelSize = rawGeom?.pixelSize as number | undefined; - const topZ_world = rawGeom?.topZ as number | undefined; - if (!activePixels || !width || !height || !pixelSize || topZ_world === undefined) return []; - if (activePixels.length !== width * height) return []; - if (grid && (grid.width !== width || grid.height !== height || grid.pixelSize !== pixelSize)) { - return []; - } - grid ??= { width, height, pixelSize }; - - const baseZ_mm = (mesh.userData.baseZ as number) ?? 0; - const topZ_mm = mesh.userData.topZ as number; - if ( - !Number.isFinite(baseZ_mm) || !Number.isFinite(topZ_mm) || - topZ_mm <= baseZ_mm || topZ_mm <= 0 - ) return []; - - const meshHeightScale = topZ_world / topZ_mm; - if (!Number.isFinite(meshHeightScale) || meshHeightScale <= 0) return []; - if (!heightScaleComputed) { - heightScale = meshHeightScale; - heightScaleComputed = true; - } else if (Math.abs(meshHeightScale - heightScale) > 1e-9) return []; - - if (!nozzleHex.has(nozzleIndex)) { - const mat = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material; - const overrideHex = readMeshUserDataString(mesh, 'kromacutFilamentHex') - ?? layerFilamentColors?.[meshIndex]; - let hex = normalizeHexColor(overrideHex, '#FFFFFF').slice(1); - if (!overrideHex && 'color' in mat) { - hex = (mat as THREE.MeshStandardMaterial).color.getHexString().toUpperCase(); - } - nozzleHex.set(nozzleIndex, hex); - } - - let nozzleMap = nozzleLayerMap.get(nozzleIndex); - if (!nozzleMap) { - nozzleMap = new Map(); - nozzleLayerMap.set(nozzleIndex, nozzleMap); - } - - const layerKey = baseZ_mm.toFixed(8); - let layerData = nozzleMap.get(layerKey); - if (!layerData) { - layerData = { - baseZ_mm, - topZ_world, - mask: new Uint8Array(width * height), - width, - height, - pixelSize, - }; - nozzleMap.set(layerKey, layerData); - } else if (layerData.topZ_world !== topZ_world) return []; - for (let mi = 0; mi < activePixels.length; mi++) { - if (activePixels[mi]) layerData.mask[mi] = 1; - if ((mi + 1) % 4096 === 0) { - await maybeYield(0.25 * (meshIndex + (mi + 1) / activePixels.length) / meshes.length); - } - } - await maybeYield(0.25 * (meshIndex + 1) / meshes.length); - } - - if (nozzleLayerMap.size === 0) return []; - - // Build a global sorted layer list so each nozzle's layer records are - // aligned to the same indices (null where a nozzle is absent), enabling - // correct Z-adjacency checks for cap insertion in buildNozzleVoxelMesh. - type GlobalLayer = { - key: string; - baseZ_mm: number; - topZ_world: number; - baseZ_world: number; - }; - const globalLayerMap = new Map(); - for (const [, nozzleMap] of nozzleLayerMap) { - for (const [key, data] of nozzleMap) { - if (!globalLayerMap.has(key)) { - globalLayerMap.set(key, { - key, - baseZ_mm: data.baseZ_mm, - topZ_world: data.topZ_world, - baseZ_world: data.baseZ_mm * heightScale, - }); - } - } - } - const globalLayers = [...globalLayerMap.values()].sort((a, b) => a.baseZ_mm - b.baseZ_mm); - - const syntheticMeshes: THREE.Mesh[] = []; - let nozzleOffset = 0; - - for (const [nozzleIndex, nozzleMap] of nozzleLayerMap) { - const firstData = nozzleMap.values().next().value as LayerData; - const { width, height, pixelSize } = firstData; - - const layerRecords: (NozzleLayerRecord | null)[] = globalLayers.map((gl) => { - const data = nozzleMap.get(gl.key); - if (!data) return null; - return { mask: data.mask, baseZ: gl.baseZ_world, topZ: data.topZ_world }; - }); - - const { positions, indices } = await buildNozzleVoxelMeshAsync( - layerRecords, width, height, pixelSize, { - onProgress: (progress) => onProgress?.( - 0.25 + 0.75 * (nozzleOffset + progress) / nozzleLayerMap.size - ), - } - ); - nozzleOffset++; - - const hex = nozzleHex.get(nozzleIndex) ?? 'FFFFFF'; - const geom = new THREE.BufferGeometry(); - geom.userData.kromacutExportGeometry = { - positions, indices, itemSize: 3, preserveVertexIndices: true, - }; - const mat = new THREE.MeshStandardMaterial({ color: '#' + hex }); - const syntheticMesh = new THREE.Mesh(geom, mat); - syntheticMesh.userData.nozzleIndex = nozzleIndex; - syntheticMesh.userData.kromacutFilamentHex = '#' + hex; - syntheticMeshes.push(syntheticMesh); - } - - syntheticMeshes.sort( - (a, b) => (a.userData.nozzleIndex ?? 0) - (b.userData.nozzleIndex ?? 0) - ); - return syntheticMeshes; -} - export async function exportObjectTo3MFBlob( root: THREE.Object3D, options?: Export3MFOptions @@ -379,23 +198,6 @@ ${metadataContentTypes}${metadataContentTypes ? '\n' : ''}`; const reportProgress = (value: number) => { onProgress?.(clampProgress(value)); }; - const reconstructionSpan = (options?.extruderCount ?? 0) >= 2 ? 0.2 : 0; - - // For multi-head mode: replace the fragmented per-layer-per-color mesh list - // with one manifold voxel solid per nozzle before group building. This - // eliminates coincident faces at color- and layer-boundaries that cause - // non-manifold geometry in slicers. - if (reconstructionSpan > 0 && (options?.smoothMeshingStrength ?? 'none') === 'none') { - const manifoldMeshes = await buildNozzleManifoldMeshes( - meshes, options?.layerFilamentColors, - (progress) => reportProgress(reconstructionSpan * progress) - ); - if (manifoldMeshes.length > 0) { - meshes.length = 0; - for (const m of manifoldMeshes) meshes.push(m); - } - } - if (reconstructionSpan > 0) reportProgress(reconstructionSpan); // Group meshes into exported objects (see ExportMeshGroup). const groups: ExportMeshGroup[] = []; @@ -718,13 +520,10 @@ ${metadataContentTypes}${metadataContentTypes ? '\n' : ''}`; // Progress tracking const totalGroups = groups.length; - // Reconstruction and mesh serialization share the first 80%; ZIP owns the final 20%. + // Mesh serialization owns the first 80%; ZIP owns the final 20%. const reportMeshProgress = (groupIdx: number, meshFrac: number) => { if (!onProgress) return; - reportProgress(progressInSpan( - reconstructionSpan, 0.8 - reconstructionSpan, - exportMeshProgress(groupIdx, totalGroups, meshFrac) / 0.8 - )); + reportProgress(exportMeshProgress(groupIdx, totalGroups, meshFrac)); }; for (let i = 0; i < groups.length; i++) { @@ -871,10 +670,9 @@ ${metadataContentTypes}${metadataContentTypes ? '\n' : ''}`; if (source?.indices) { const positions = source.positions; const indices = source.indices; - // Nozzle-tagged source meshes also carry separate fans when - // reconstruction falls back for smoothing or transforms. - const preserveVertexIndices = source.preserveVertexIndices - || typeof mesh.userData.nozzleIndex === 'number'; + // Keep the multi-head mesher's vertex indexing instead of + // re-welding by coordinate. + const preserveVertexIndices = typeof mesh.userData.nozzleIndex === 'number'; const itemSize = source.itemSize ?? 3; const matrixElements = mesh.matrixWorld.elements; const sourceVertexCount = Math.floor(positions.length / itemSize); diff --git a/src/lib/meshing.ts b/src/lib/meshing.ts index b8d88876..2977d0e3 100644 --- a/src/lib/meshing.ts +++ b/src/lib/meshing.ts @@ -32,33 +32,12 @@ export interface MeshYieldOptions { yieldIntervalMs?: number; onYield?: () => Promise; onProgress?: (progress: MeshProgress) => void; - /** - * Skip the downward-facing bottom cap. Used by the multi-head / per-colour-group - * meshing path when stacking sub-meshes on top of a lower layer so interior faces - * don't z-fight the layer beneath. - */ - skipBottomCap?: boolean; - /** - * Skip the binary corner-contact repair pass. Used when a layer is split into - * multiple colour groups so adjacent groups aren't independently "repaired" into - * overlapping geometry. - */ - skipRepair?: boolean; - /** - * Union of all colour-group masks on this layer. When provided, boundary smoothing - * runs on this combined solid instead of the group's own mask: internal seams - * between adjacent groups are never smoothed, and vertices on the true exterior - * are moved identically by every group's mesher. Without this, each group smooths - * its own outline independently and adjacent colours peel apart at shared edges. - */ - combinedMask?: PixelMask; } interface GridMeshOptions extends MeshYieldOptions { mesher: 'greedy' | 'smooth'; smoothBoundary: boolean; strength?: SmoothMeshingStrength; - combinedMask?: PixelMask; } interface SmoothMeshOptions extends MeshYieldOptions { @@ -414,24 +393,15 @@ function createGridVertexMapper( width: number, height: number, smoothBoundary: boolean, - strength: SmoothMeshingStrength = 'medium', - combinedMask?: PixelMask + strength: SmoothMeshingStrength = 'medium' ) { if (!smoothBoundary) { return (x: number, y: number): [number, number] => [x, y]; } const stride = width + 1; - // Build the smoothing graph from the union of all colour groups on the layer - // (falling back to this group's own pixels for single-group layers). Every group - // is a subset of the combined mask, so all groups derive the identical boundary - // graph and therefore identical smoothed positions — vertices shared between - // adjacent groups stay welded instead of each group smoothing them differently. - // Seam vertices interior to the combined solid never enter the graph and map to - // their original grid position in every group. - const solidPixels = combinedMask ?? meshingPixels; const getCell = (x: number, y: number) => - x >= 0 && y >= 0 && x < width && y < height && solidPixels[y * width + x] ? 1 : 0; + x >= 0 && y >= 0 && x < width && y < height && meshingPixels[y * width + x] ? 1 : 0; const boundaryNeighbors = new Map>(); const addBoundaryEdge = (ax: number, ay: number, bx: number, by: number) => { @@ -629,10 +599,7 @@ async function generateGridMesh( options: GridMeshOptions ): Promise { const startedAt = performance.now(); - const skipBottomCap = options.skipBottomCap ?? false; - const meshingPixels = options.skipRepair - ? activePixels - : repairBinaryCornerContacts(activePixels, width, height); + const meshingPixels = repairBinaryCornerContacts(activePixels, width, height); const positions: number[] = []; const indices: number[] = []; let vertCount = 0; @@ -665,8 +632,7 @@ async function generateGridMesh( } }; - // Weld within each surface fan. At an unrepaired diagonal contact the two - // occupied quadrants need distinct indices, even at identical coordinates. + // Vertex welding maps: key = y * (width + 1) + x const topMap = new Map(); const bottomMap = new Map(); const stride = width + 1; @@ -680,22 +646,11 @@ async function generateGridMesh( width, height, options.smoothBoundary, - options.strength, - options.combinedMask + options.strength ); - const getOrAddVertex = (x: number, y: number, isTop: boolean, interiorY: number): number => { - let fan = 0; - if (options.skipRepair && x > 0 && x < width && y > 0 && y < height) { - const topLeft = !!meshingPixels[(y - 1) * width + x - 1]; - const topRight = !!meshingPixels[(y - 1) * width + x]; - const bottomLeft = !!meshingPixels[y * width + x - 1]; - const bottomRight = !!meshingPixels[y * width + x]; - if (topLeft === bottomRight && topRight === bottomLeft && topLeft !== topRight) { - fan = interiorY < y ? 0 : 1; - } - } - const key = (y * stride + x) * 2 + fan; + const getOrAddVertex = (x: number, y: number, isTop: boolean): number => { + const key = y * stride + x; const map = isTop ? topMap : bottomMap; let idx = map.get(key); if (idx !== undefined) return idx; @@ -781,20 +736,6 @@ async function generateGridMesh( verticesAtX.get(xCoord)!.add(y + h); } - if (options.smoothBoundary && options.combinedMask) { - // Other colour groups can end a seam anywhere along this rectangle. - // Use the shared unit grid on every cap/wall boundary so all groups - // include those junctions before applying the common smoothing map. - for (let dx = 1; dx < w; dx++) { - verticesAtY.get(y)!.add(x + dx); - verticesAtY.get(y + h)!.add(x + dx); - } - for (let dy = 1; dy < h; dy++) { - verticesAtX.get(x)!.add(y + dy); - verticesAtX.get(x + w)!.add(y + dy); - } - } - await maybeYield(); } @@ -882,8 +823,8 @@ async function generateGridMesh( for (let i = 0; i < boundary.length; i++) { const [vx, vy] = boundary[i]; - topLoop[i] = getOrAddVertex(vx, vy, true, y); - bottomLoop[i] = getOrAddVertex(vx, vy, false, y); + topLoop[i] = getOrAddVertex(vx, vy, true); + bottomLoop[i] = getOrAddVertex(vx, vy, false); } const facePoints = boundary.map(([vx, vy]) => { @@ -918,9 +859,7 @@ async function generateGridMesh( for (const [a, b, c] of faces) { indices.push(topLoop[a], topLoop[b], topLoop[c]); - if (!skipBottomCap) { - indices.push(bottomLoop[a], bottomLoop[c], bottomLoop[b]); - } + indices.push(bottomLoop[a], bottomLoop[c], bottomLoop[b]); } await maybeYield(); @@ -994,11 +933,10 @@ async function generateGridMesh( const mustSplit = requiredVertices.has(runEnd) && isContiguous; if (!isContiguous || mustSplit || i === xCoords.length) { - const interiorY = isSouth ? yCoord - 1 : yCoord; - const wTL = getOrAddVertex(runStart, yCoord, true, interiorY); - const wTR = getOrAddVertex(runEnd, yCoord, true, interiorY); - const wBR = getOrAddVertex(runEnd, yCoord, false, interiorY); - const wBL = getOrAddVertex(runStart, yCoord, false, interiorY); + const wTL = getOrAddVertex(runStart, yCoord, true); + const wTR = getOrAddVertex(runEnd, yCoord, true); + const wBR = getOrAddVertex(runEnd, yCoord, false); + const wBL = getOrAddVertex(runStart, yCoord, false); if (isSouth) { addQuadCCW(wBL, wTL, wTR, wBR); @@ -1040,10 +978,10 @@ async function generateGridMesh( const mustSplit = requiredVertices.has(runEnd) && isContiguous; if (!isContiguous || mustSplit || i === yCoords.length) { - const wTL = getOrAddVertex(xCoord, runStart, true, runStart); - const wTR = getOrAddVertex(xCoord, runEnd, true, runStart); - const wBR = getOrAddVertex(xCoord, runEnd, false, runStart); - const wBL = getOrAddVertex(xCoord, runStart, false, runStart); + const wTL = getOrAddVertex(xCoord, runStart, true); + const wTR = getOrAddVertex(xCoord, runEnd, true); + const wBR = getOrAddVertex(xCoord, runEnd, false); + const wBL = getOrAddVertex(xCoord, runStart, false); if (isEast) { addQuadCCW(wBR, wTR, wTL, wBL); diff --git a/src/lib/multiHeadGeometry.ts b/src/lib/multiHeadGeometry.ts index c80e9b59..fc625d80 100644 --- a/src/lib/multiHeadGeometry.ts +++ b/src/lib/multiHeadGeometry.ts @@ -171,9 +171,8 @@ export async function* generateMultiHeadMeshes( const geometry = new THREE.BufferGeometry(); geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); geometry.setIndex(indices); - // Retain the actual shared tessellation. Supplying voxel occupancy - // here would make export replace smoothing and collapse different - // physical filaments used by one head across swap checkpoints. + // Export writes this shared tessellation as-is, so the 3MF keeps + // the preview's smoothing and each region's physical filament. geometry.userData.kromacutExportGeometry = { positions, indices }; const material = new THREE.MeshStandardMaterial({ color: previewHex, diff --git a/src/lib/voxelMesh.ts b/src/lib/voxelMesh.ts deleted file mode 100644 index 2d65ebe8..00000000 --- a/src/lib/voxelMesh.ts +++ /dev/null @@ -1,276 +0,0 @@ -/** - * 3D voxel mesher for multi-head 3MF export. - * - * Produces a closed surface per nozzle from per-layer pixel-occupancy masks. - * Exposed faces stay unit-sized to avoid T-junctions. Edge/vertex-only contacts - * retain separate surface fans at identical coordinates; consumers must preserve - * these indices instead of welding vertices by position. - * - * Winding convention matches meshing.ts (THREE.js FrontSide, Z-up): - * top caps → CCW from above (+Z) bottom caps → CCW from below (-Z) - * east walls → CCW from east (+X) west walls → CCW from west (-X) - * south walls→ CCW from south (+Y) north walls → CCW from north (-Y) - */ - -export interface NozzleLayerRecord { - /** Per-pixel occupancy (width × height Uint8Array, 1 = this nozzle). */ - mask: Uint8Array; - /** World-space Z of the bottom of this layer (already height-scaled). */ - baseZ: number; - /** World-space Z of the top of this layer (already height-scaled). */ - topZ: number; -} - -/** - * Build a manifold voxel surface (possibly multiple touching shells) for one nozzle. - * - * `layers` must be sorted by ascending baseZ. Null entries represent global - * print layers where this nozzle is absent; they are used to determine - * Z-continuity so correct top/bottom caps are inserted at Z-gaps. - */ -export function buildNozzleVoxelMesh( - layers: (NozzleLayerRecord | null)[], - width: number, - height: number, - pixelSize: number, -): { positions: Float32Array; indices: number[] } { - const work = generateNozzleVoxelMesh(layers, width, height, pixelSize); - let step = work.next(); - while (!step.done) step = work.next(); - return step.value; -} - -/** Use the same deterministic mesher while allowing the exporter to update the UI. */ -export async function buildNozzleVoxelMeshAsync( - layers: (NozzleLayerRecord | null)[], - width: number, - height: number, - pixelSize: number, - options: { - yieldIntervalMs?: number; - onYield?: () => Promise; - onProgress?: (progress: number) => void; - } = {}, -): Promise<{ positions: Float32Array; indices: number[] }> { - const work = generateNozzleVoxelMesh(layers, width, height, pixelSize); - const yieldIntervalMs = options.yieldIntervalMs ?? 8; - const yieldControl = options.onYield ?? (() => new Promise((resolve) => setTimeout(resolve, 0))); - let lastYield = performance.now(); - let step = work.next(); - while (!step.done) { - options.onProgress?.(step.value); - if (performance.now() - lastYield >= yieldIntervalMs) { - await yieldControl(); - lastYield = performance.now(); - } - step = work.next(); - } - options.onProgress?.(1); - return step.value; -} - -function* generateNozzleVoxelMesh( - layers: (NozzleLayerRecord | null)[], - width: number, - height: number, - pixelSize: number, -): Generator { - const pos: number[] = []; - const idx: number[] = []; - const vmap = new Map(); - const corners: number[] = []; - const parents: number[] = []; - const faceVoxels: number[] = []; - const edgeUses = new Map(); - let voxel = 0; - - const addV = (x: number, y: number, z: number): number => { - const key = `${x},${y},${z}`; - let i = vmap.get(key); - if (i === undefined) { - i = pos.length / 3; - vmap.set(key, i); - pos.push(x, y, z); - } - return i; - }; - - const nextCorner = (corner: number) => corner - corner % 4 + (corner + 1) % 4; - - // Keep face-local corners until exposed edges have been paired. A coordinate - // alone cannot distinguish the two sheets at a diagonal voxel contact. - const quad = ( - ax: number, ay: number, az: number, - bx: number, by: number, bz: number, - cx: number, cy: number, cz: number, - dx: number, dy: number, dz: number, - ) => { - const a = addV(ax, ay, az), b = addV(bx, by, bz); - const c = addV(cx, cy, cz), d = addV(dx, dy, dz); - const start = corners.length; - corners.push(a, b, c, d); - faceVoxels.push(voxel); - for (let offset = 0; offset < 4; offset++) { - const corner = start + offset; - parents.push(corner); - const from = corners[corner], to = corners[nextCorner(corner)]; - const key = from < to ? `${from},${to}` : `${to},${from}`; - const uses = edgeUses.get(key); - if (uses) uses.push(corner); - else edgeUses.set(key, [corner]); - } - }; - - const numLayers = layers.length; - const EPS = 1e-9; - - for (let li = 0; li < numLayers; li++) { - const layer = layers[li]; - if (!layer) continue; - - const { mask, baseZ, topZ: z1 } = layer; - const prev = li > 0 ? layers[li - 1] : null; - const next = li < numLayers - 1 ? layers[li + 1] : null; - - // Z-continuity: whether the adjacent layer abuts this one without a gap. - const prevAdj = prev !== null && Math.abs(prev.topZ - baseZ) < EPS; - const nextAdj = next !== null && Math.abs(z1 - next.baseZ) < EPS; - // Canonicalize only genuinely abutting planes, without snapping real gaps. - const z0 = prevAdj ? prev!.topZ : baseZ; - - for (let r = 0; r < height; r++) { - for (let c = 0; c < width; c++) { - const mi = r * width + c; - if (mi % 256 === 0) { - yield 0.6 * (li + mi / (width * height)) / Math.max(1, numLayers); - } - if (!mask[mi]) continue; - voxel = li * width * height + mi; - - const x0 = c * pixelSize, x1 = (c + 1) * pixelSize; - const y0 = r * pixelSize, y1 = (r + 1) * pixelSize; - - // ── TOP CAP (normal +Z) ───────────────────────────────────── - // Generate when this nozzle does NOT continue into the next - // Z-adjacent layer at this pixel. - if (!nextAdj || !next!.mask[mi]) { - // CCW from above: (x0,y0)→(x1,y0)→(x1,y1)→(x0,y1) - quad(x0, y0, z1, x1, y0, z1, x1, y1, z1, x0, y1, z1); - } - - // ── BOTTOM CAP (normal -Z) ────────────────────────────────── - if (!prevAdj || !prev!.mask[mi]) { - // CW from above = CCW from below - quad(x0, y0, z0, x0, y1, z0, x1, y1, z0, x1, y0, z0); - } - - // ── EAST WALL (normal +X) at x = x1 ──────────────────────── - if (c === width - 1 || !mask[mi + 1]) { - // CCW(wBR,wTR,wTL,wBL) = (x1,y1,z0)→(x1,y1,z1)→(x1,y0,z1)→(x1,y0,z0) - quad(x1, y1, z0, x1, y1, z1, x1, y0, z1, x1, y0, z0); - } - - // ── WEST WALL (normal -X) at x = x0 ──────────────────────── - if (c === 0 || !mask[mi - 1]) { - // CCW(wBL,wTL,wTR,wBR) = (x0,y0,z0)→(x0,y0,z1)→(x0,y1,z1)→(x0,y1,z0) - quad(x0, y0, z0, x0, y0, z1, x0, y1, z1, x0, y1, z0); - } - - // ── SOUTH WALL (normal +Y) at y = y1 ─────────────────────── - if (r === height - 1 || !mask[mi + width]) { - // CCW(wBL,wTL,wTR,wBR) = (x0,y1,z0)→(x0,y1,z1)→(x1,y1,z1)→(x1,y1,z0) - quad(x0, y1, z0, x0, y1, z1, x1, y1, z1, x1, y1, z0); - } - - // ── NORTH WALL (normal -Y) at y = y0 ─────────────────────── - if (r === 0 || !mask[mi - width]) { - // CCW(wBR,wTR,wTL,wBL) = (x1,y0,z0)→(x1,y0,z1)→(x0,y0,z1)→(x0,y0,z0) - quad(x1, y0, z0, x1, y0, z1, x0, y0, z1, x0, y0, z0); - } - } - } - } - - yield 0.6; - const find = (corner: number): number => { - while (parents[corner] !== corner) { - parents[corner] = parents[parents[corner]]; - corner = parents[corner]; - } - return corner; - }; - const join = (a: number, b: number) => { parents[find(a)] = find(b); }; - const output: number[] = []; - const midpoints = new Map(); - const addOutput = (x: number, y: number, z: number) => { - const index = output.length / 3; - output.push(x, y, z); - return index; - }; - const pair = (a: number, b: number, splitEdge: boolean) => { - join(a, nextCorner(b)); - join(nextCorner(a), b); - if (splitEdge) { - const from = corners[a] * 3, to = corners[nextCorner(a)] * 3; - const midpoint = addOutput( - (pos[from] + pos[to]) / 2, - (pos[from + 1] + pos[to + 1]) / 2, - (pos[from + 2] + pos[to + 2]) / 2 - ); - midpoints.set(a, midpoint); - midpoints.set(b, midpoint); - } - }; - let processedEdges = 0; - for (const uses of edgeUses.values()) { - if (uses.length === 2) { - pair(uses[0], uses[1], false); - } else { - // Four exposed faces mean two diagonal occupied voxels. Pair the two - // faces of each voxel, never the faces across the empty quadrants. - // Separate midpoints also distinguish the sheets when their endpoint - // fans happen to reconnect elsewhere around the vertex. - for (let i = 0; i < uses.length; i++) { - for (let j = i + 1; j < uses.length; j++) { - if (faceVoxels[Math.floor(uses[i] / 4)] === faceVoxels[Math.floor(uses[j] / 4)]) { - pair(uses[i], uses[j], true); - } - } - } - } - if (++processedEdges % 256 === 0) yield 0.6 + 0.2 * processedEdges / edgeUses.size; - } - yield 0.8; - const vertexMap = new Map(); - const getCorner = (corner: number) => { - const root = find(corner); - let vertex = vertexMap.get(root); - if (vertex === undefined) { - const offset = corners[root] * 3; - vertex = addOutput(pos[offset], pos[offset + 1], pos[offset + 2]); - vertexMap.set(root, vertex); - } - return vertex; - }; - for (let start = 0; start < corners.length; start += 4) { - if (start % 256 === 0) yield 0.8 + 0.2 * start / corners.length; - const boundary: number[] = []; - for (let corner = start; corner < start + 4; corner++) { - boundary.push(getCorner(corner)); - const midpoint = midpoints.get(corner); - if (midpoint !== undefined) boundary.push(midpoint); - } - if (boundary.length === 4) { - idx.push(boundary[0], boundary[1], boundary[2], boundary[0], boundary[2], boundary[3]); - } else { - const a = corners[start] * 3, c = corners[start + 2] * 3; - const center = addOutput( - (pos[a] + pos[c]) / 2, (pos[a + 1] + pos[c + 1]) / 2, (pos[a + 2] + pos[c + 2]) / 2 - ); - for (let i = 0; i < boundary.length; i++) { - idx.push(center, boundary[i], boundary[(i + 1) % boundary.length]); - } - } - } - return { positions: new Float32Array(output), indices: idx }; -} diff --git a/tests/export3mf.test.ts b/tests/export3mf.test.ts index 94aaad8d..fcafd51a 100644 --- a/tests/export3mf.test.ts +++ b/tests/export3mf.test.ts @@ -2157,56 +2157,23 @@ interface MultiHeadArchive { contentTypesXml: string; } -async function createNozzleOccupancyLayer( - rows: string[], nozzle: number, baseZ = 0, topZ = 1, heightScale = 1 -) { +async function createNozzleLayer(rows: string[], nozzle: number, baseZ = 0, topZ = 1) { const mask = maskFromRows(rows); const data = await generateGreedyMesh( - mask.activePixels, mask.width, mask.height, topZ - baseZ, baseZ, 1, heightScale, - { yieldIntervalMs: Infinity, onYield: async () => undefined, skipRepair: true } + mask.activePixels, mask.width, mask.height, topZ - baseZ, baseZ, 1, 1, + { yieldIntervalMs: Infinity, onYield: async () => undefined } ); - const mesh = createCompactExportLayer(data, mask, 1, topZ * heightScale, 0x0000ff); + // Match multi-head preview meshes, which carry only their tessellation. + const mesh = createMeshDataLayer(data, 0x0000ff); + mesh.geometry.userData.kromacutExportGeometry = { positions: data.positions, indices: data.indices }; mesh.userData = { nozzleIndex: nozzle, baseZ, topZ }; return mesh; } -test('multi-head occupancy export preserves diagonal shells within and across layers', async () => { - for (const masks of [ - [['#.', '.#']], - [['#.'], ['.#']], - [['#.', '..'], ['..', '.#']], - [['##', '#.'], ['#.', '.#']], - ]) { - const root = new THREE.Group(); - for (const [z, rows] of masks.entries()) { - root.add(await createNozzleOccupancyLayer(rows, 1, z, z + 1, 2)); - } - const objects = await exportMeshObjects(root, { extruderCount: 2 }); - assert.equal(objects.length, 1, 'all occupied layers should be merged per nozzle'); - assertRawExportObjectIsManifold(objects[0], `diagonal occupancy ${JSON.stringify(masks)}`); - const volume = masks.flat().join('').split('#').length - 1; - assert.ok(Math.abs(inspectMeshIntegrity(objects[0].mesh).signedVolume - volume * 2) < 1e-5); - } -}); - -test('multi-head occupancy export keeps complementary diagonal materials separate', async () => { - const root = new THREE.Group(); - root.add(await createNozzleOccupancyLayer(['#.', '.#'], 1)); - root.add(await createNozzleOccupancyLayer(['.#', '#.'], 2)); - const archive = await exportArchiveXml(root, { extruderCount: 2 }); - const objects = parseMeshObjects(archive.modelXml); - assert.equal(objects.length, 2); - assert.deepEqual([...parseModelSettingsPartExtruders(archive.modelSettingsXml).values()], [1, 2]); - for (const object of objects) { - assertRawExportObjectIsManifold(object, 'diagonal material shells'); - assert.ok(Math.abs(inspectMeshIntegrity(object.mesh).signedVolume - 2) < 1e-6); - } -}); - -test('multi-head occupancy export preserves mesh and parent transforms', async () => { +test('multi-head export preserves mesh and parent transforms', async () => { for (const transform of ['translate', 'rotate', 'scale', 'parent'] as const) { const root = new THREE.Group(); - const mesh = await createNozzleOccupancyLayer(['#'], 1); + const mesh = await createNozzleLayer(['#'], 1); if (transform === 'translate') mesh.position.set(7, 8, 0); if (transform === 'rotate') mesh.rotation.set(0.3, 0.5, 0.7); if (transform === 'scale') mesh.scale.set(2, 3, 4); @@ -2245,80 +2212,20 @@ test('multi-head export preserves every source smoothing strength', async () => } }); -test('smoothed multi-head fallback preserves separate indexed diagonal fans', async () => { - for (const strength of ['minimal', 'medium', 'aggressive'] as const) { - const root = new THREE.Group(); - for (const [nozzle, rows] of [[1, ['#.', '.#']], [2, ['.#', '#.']]] as const) { - const mask = maskFromRows([...rows]); - const data = await generateSmoothMesh(mask.activePixels, 2, 2, 1, 0, 1, 1, { - strength, skipRepair: true, combinedMask: new Uint8Array(4).fill(1), - yieldIntervalMs: Infinity, onYield: async () => undefined, - }); - const mesh = createCompactExportLayer(data, mask, 1, 1, 0x0000ff, false); - mesh.userData = { nozzleIndex: nozzle, baseZ: 0, topZ: 1 }; - root.add(mesh); - } - const objects = await exportMeshObjects(root, { extruderCount: 2, smoothMeshingStrength: strength }); - assert.equal(objects.length, 2); - for (const object of objects) assertRawExportObjectIsManifold(object, `${strength} diagonal fans`); - } -}); - -test('multi-head reconstruction yields to timers while reporting progress', async () => { +test('multi-head export reports the same progress as single-head export', async () => { const { exportObjectTo3MFBlob } = await loadExport3mfModule(); const root = new THREE.Group(); - root.add(await createNozzleOccupancyLayer(Array(128).fill('#'.repeat(128)), 1)); - const samples: number[] = []; - const timerProgress: number[] = []; - let progress = 0; - const timer = setInterval(() => timerProgress.push(progress), 0); - try { - await exportObjectTo3MFBlob(root, { - extruderCount: 2, - onProgress: (value) => { progress = value; samples.push(value); }, - }); - } finally { - clearInterval(timer); - } - assertMonotonicProgress(samples, 'multi-head reconstruction and export'); - assert.ok(timerProgress.some((value) => value > 0 && value < 0.2), - 'timers must run during reconstruction, before mesh serialization'); - assert.equal(samples.at(-1), 1); -}); - -test('multi-head occupancy export retains meshes without compatible voxel metadata', async () => { - for (const incompatible of ['untagged', 'different grid'] as const) { - const root = new THREE.Group(); - root.add(await createNozzleOccupancyLayer(['#'], 1)); - if (incompatible === 'untagged') { - root.add(createLayerMesh(new THREE.BoxGeometry(1, 1, 1), 0xff0000)); - } else { - root.add(await createNozzleOccupancyLayer(['##'], 1, 1, 2)); - } - const normal = await exportMeshObjects(root); - const multiHead = await exportMeshObjects(root, { extruderCount: 2 }); - assert.equal(multiHead.length, normal.length, incompatible); - assert.deepEqual(multiHead.map((object) => object.mesh), normal.map((object) => object.mesh)); - } -}); - -test('multi-head occupancy export resolves physical colors before nozzle sorting and collapse', async () => { - const root = new THREE.Group(); - const first = await createNozzleOccupancyLayer(['#'], 2, 0, 1); - const second = await createNozzleOccupancyLayer(['#'], 1, 1, 2); - const third = await createNozzleOccupancyLayer(['#'], 2, 2, 3); - first.userData.kromacutFilamentHex = '#FF0000'; - root.add(first, second, third); - const archive = await exportArchiveXml(root, { - extruderCount: 2, layerFilamentColors: ['#FFFF00', '#00FF00', '#00FFFF'], - }); - assert.deepEqual(archive.projectSettings.filament_colour, ['#00FF00', '#FF0000']); - const colors = parseBaseMaterialColors(archive.modelXml); - const objects = parseMeshObjects(archive.modelXml); - assert.equal(objects.length, 2); - assert.deepEqual(objects.map((object) => colors[object.materialIndex]), ['00FF00', 'FF0000']); - assert.equal(first.userData.kromacutFilamentHex, '#FF0000', 'source metadata must stay unchanged'); - assert.equal(second.userData.kromacutFilamentHex, undefined); + root.add(await createNozzleLayer(['##', '#.'], 1), await createNozzleLayer(['#.'], 2, 1, 2)); + const progressFor = async (extruderCount?: number) => { + const samples: number[] = []; + await exportObjectTo3MFBlob(root, { extruderCount, onProgress: (value) => samples.push(value) }); + return samples; + }; + const meshPhase = (samples: number[]) => samples.filter((value) => value < 0.8); + const multiHead = await progressFor(2); + assertMonotonicProgress(multiHead, 'multi-head export'); + assert.equal(multiHead.at(-1), 1); + assert.deepEqual(meshPhase(multiHead), meshPhase(await progressFor())); }); async function exportMultiHead( diff --git a/tests/meshingOptions.test.ts b/tests/meshingOptions.test.ts deleted file mode 100644 index 7ca50657..00000000 --- a/tests/meshingOptions.test.ts +++ /dev/null @@ -1,251 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { generateGreedyMesh, generateSmoothMesh, type MeshData } from '../src/lib/meshing.ts'; -import { assertClosedIndexedSurface } from './helpers/meshAssertions.ts'; -import { inspectMeshIntegrity } from './meshDiagnostics.ts'; - -// Re-applied during the develop rebase: the multi-head / per-colour-group build -// path passes skipBottomCap (stacked sub-meshes) and skipRepair (independent -// colour groups). These guard that wiring against future mesher refactors. - -const noYield = { yieldIntervalMs: Infinity, onYield: async () => undefined }; - -function maskFromRows(rows: string[]): { activePixels: Uint8Array; width: number; height: number } { - const width = rows[0].length; - const height = rows.length; - const activePixels = new Uint8Array(width * height); - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - if (rows[y][x] === '#') activePixels[y * width + x] = 1; - } - } - return { activePixels, width, height }; -} - -// Count triangles whose geometric normal points downward (-Z) — i.e. bottom-cap faces. -function countDownwardFacingTriangles(mesh: MeshData): number { - const { positions, indices } = mesh; - let count = 0; - for (let i = 0; i < indices.length; i += 3) { - const a = indices[i] * 3; - const b = indices[i + 1] * 3; - const c = indices[i + 2] * 3; - const abx = positions[b] - positions[a]; - const aby = positions[b + 1] - positions[a + 1]; - const acx = positions[c] - positions[a]; - const acy = positions[c + 1] - positions[a + 1]; - const nz = abx * acy - aby * acx; // z-component of (B-A) x (C-A) - if (nz < -1e-6) count++; - } - return count; -} - -const meshers = [ - { name: 'greedy', generate: generateGreedyMesh }, - { name: 'smooth', generate: generateSmoothMesh }, -]; - -for (const { name, generate } of meshers) { - test(`${name}: skipBottomCap omits the downward-facing bottom cap`, async () => { - const mask = maskFromRows(['###', '###', '###']); - - const withCap = await generate(mask.activePixels, mask.width, mask.height, 1, 0, 1, 1, { - ...noYield, - }); - const withoutCap = await generate(mask.activePixels, mask.width, mask.height, 1, 0, 1, 1, { - ...noYield, - skipBottomCap: true, - }); - - assert.ok( - countDownwardFacingTriangles(withCap) > 0, - 'default build should emit bottom-cap (downward) faces' - ); - assert.equal( - countDownwardFacingTriangles(withoutCap), - 0, - 'skipBottomCap should emit no downward-facing faces' - ); - assert.ok( - withoutCap.indices.length < withCap.indices.length, - 'skipBottomCap should produce fewer triangles' - ); - }); -} - -test('smooth: combinedMask prevents smoothing at shared internal edges between colour groups', async () => { - // Two adjacent colour groups in a 2×2 grid: group A = left column, group B = right column. - // The shared edge (x=1) is internal to the layer. With combinedMask, it should not be - // treated as an exterior boundary by group A's mesher — so those vertices stay at x=1. - // Without combinedMask each group smooths the shared edge inward independently, which - // would create a visible gap. - const maskA = maskFromRows(['#.', '#.']); // left column - const combined = maskFromRows(['##', '##']); // full 2×2 grid - - const withoutCombined = await generateSmoothMesh( - maskA.activePixels, maskA.width, maskA.height, 1, 0, 1, 1, - { ...noYield } - ); - const withCombined = await generateSmoothMesh( - maskA.activePixels, maskA.width, maskA.height, 1, 0, 1, 1, - { ...noYield, combinedMask: combined.activePixels } - ); - - const maxX = (mesh: MeshData) => { - let m = -Infinity; - for (let i = 0; i < mesh.positions.length; i += 3) m = Math.max(m, mesh.positions[i]); - return m; - }; - - assert.ok( - maxX(withoutCombined) < 1.0, - 'without combinedMask, the right edge of group A is treated as exterior and smoothed inward' - ); - assert.equal( - maxX(withCombined), - 1.0, - 'with combinedMask, the shared right edge of group A is interior and stays unsmoothed at x=1' - ); -}); - -test('smooth: combinedMask only suppresses smoothing at shared edges, not the true exterior', async () => { - // Group A = left column of a 2×2 grid. Even with combinedMask, the left exterior edge - // (x=0) and the top/bottom exterior edges should still be smoothed inward. - const maskA = maskFromRows(['#.', '#.']); - const combined = maskFromRows(['##', '##']); - - const withCombined = await generateSmoothMesh( - maskA.activePixels, maskA.width, maskA.height, 1, 0, 1, 1, - { ...noYield, combinedMask: combined.activePixels } - ); - const noSmooth = await generateGreedyMesh( - maskA.activePixels, maskA.width, maskA.height, 1, 0, 1, 1, - { ...noYield } - ); - - const minX = (mesh: MeshData) => { - let m = Infinity; - for (let i = 0; i < mesh.positions.length; i += 3) m = Math.min(m, mesh.positions[i]); - return m; - }; - - assert.ok( - minX(withCombined) > minX(noSmooth), - 'combinedMask still allows the true exterior (left edge) to be smoothed inward' - ); -}); - -test('smooth: adjacent colour groups place shared exterior vertices identically (no peeling)', async () => { - // Group A = left column, group B = right column of a 2×2 layer. The grid vertices - // where the seam meets the exterior — (1,0) and (1,2) — are used by both meshes. - // Each group's mesher must smooth them to the exact same position, otherwise the - // colours visibly peel apart at the seam. This requires the smoothing graph to be - // built from the combined solid, not just each group's own outline. - const maskA = maskFromRows(['#.', '#.']); - const maskB = maskFromRows(['.#', '.#']); - const combined = maskFromRows(['##', '##']); - - const meshA = await generateSmoothMesh(maskA.activePixels, 2, 2, 1, 0, 1, 1, { - ...noYield, - skipRepair: true, - combinedMask: combined.activePixels, - }); - const meshB = await generateSmoothMesh(maskB.activePixels, 2, 2, 1, 0, 1, 1, { - ...noYield, - skipRepair: true, - combinedMask: combined.activePixels, - }); - - const vertexSet = (mesh: MeshData) => { - const set = new Set(); - for (let i = 0; i < mesh.positions.length; i += 3) { - set.add( - `${mesh.positions[i]},${mesh.positions[i + 1]},${mesh.positions[i + 2]}` - ); - } - return set; - }; - - // Every vertex of A near the seam plane (x = 1) must exist bitwise-identically in B. - const bVertices = vertexSet(meshB); - let seamVertices = 0; - for (let i = 0; i < meshA.positions.length; i += 3) { - const x = meshA.positions[i]; - if (Math.abs(x - 1) > 0.4) continue; - seamVertices++; - const key = `${x},${meshA.positions[i + 1]},${meshA.positions[i + 2]}`; - assert.ok( - bVertices.has(key), - `seam vertex ${key} from group A has no identical counterpart in group B` - ); - } - assert.ok(seamVertices > 0, 'expected group A to have vertices near the seam'); -}); - -for (const strength of ['none', 'minimal', 'medium', 'aggressive'] as const) { - test(`skipRepair: ${strength} preserves indexed fans at diagonal colour contacts`, async () => { - for (const rows of [ - ['AB', 'BA'], ['BA', 'AB'], ['A.A', '.A.', 'A.A'], - // Diagonal quadrants can reconnect elsewhere in the same component. - ['AAA', 'A.A', 'AA.'], - ]) { - const width = rows[0].length, height = rows.length; - const mask = Uint8Array.from(rows.join(''), (cell) => Number(cell === 'A')); - const combined = Uint8Array.from(rows.join(''), (cell) => Number(cell !== '.')); - for (const combinedMask of [undefined, combined]) { - const mesh = await generateSmoothMesh(mask, width, height, 1, 0, 1, 1, { - ...noYield, strength, skipRepair: true, combinedMask, - }); - assertClosedIndexedSurface(mesh); - if (strength === 'none') { - const count = mask.reduce((sum, cell) => sum + cell, 0); - assert.ok(Math.abs(inspectMeshIntegrity(mesh).signedVolume - count) < 1e-6); - } - } - } - }); -} - -for (const strength of ['minimal', 'medium', 'aggressive'] as const) { - test(`smooth: ${strength} shares cap and wall subdivisions at seam junctions`, async () => { - for (const rows of [ - ['AB', 'AB', 'A.'], - ['AAA', 'BB.'], - ['AAB', 'ACB', 'ACC'], - ]) { - const width = rows[0].length; - const height = rows.length; - const combined = Uint8Array.from(rows.join(''), (color) => Number(color !== '.')); - const meshes = new Map(); - for (const color of new Set(rows.join('').replaceAll('.', ''))) { - const mask = Uint8Array.from(rows.join(''), (cell) => Number(cell === color)); - const mesh = await generateSmoothMesh(mask, width, height, 1, 0, 1, 1, { - ...noYield, strength, skipRepair: true, combinedMask: combined, - }); - assert.ok(inspectMeshIntegrity(mesh).isValid, `${color} must remain closed and oriented`); - meshes.set(color, mesh); - } - const key = (mesh: MeshData, i: number) => - Array.from(mesh.positions.slice(i * 3, i * 3 + 3)).join(','); - for (const [color, mesh] of meshes) { - const others = [...meshes].filter(([other]) => other !== color); - for (let i = 0; i < mesh.positions.length / 3; i++) { - const [x, y] = mesh.positions.slice(i * 3, i * 3 + 2); - const gx = Math.round(x), gy = Math.round(y); - const touchingColors = new Set(); - for (const dy of [-1, 0]) for (const dx of [-1, 0]) { - const cell = rows[gy + dy]?.[gx + dx]; - if (cell && cell !== '.') touchingColors.add(cell); - } - for (const [other, otherMesh] of others) { - if (!touchingColors.has(other)) continue; - const vertices = new Set(Array.from( - { length: otherMesh.positions.length / 3 }, (_, j) => key(otherMesh, j) - )); - assert.ok(vertices.has(key(mesh, i)), `${rows}: ${color}/${other} seam vertex ${key(mesh, i)}`); - } - } - } - } - }); -} diff --git a/tests/voxelMesh.test.ts b/tests/voxelMesh.test.ts deleted file mode 100644 index 41f4dc99..00000000 --- a/tests/voxelMesh.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { Vector3 } from 'three'; -import { buildNozzleVoxelMesh, buildNozzleVoxelMeshAsync, type NozzleLayerRecord } from '../src/lib/voxelMesh.ts'; -import { assertClosedIndexedSurface } from './helpers/meshAssertions.ts'; - -test('voxel mesh preserves closed shells for every 2x2x2 occupancy', () => { - for (let occupancy = 1; occupancy < 256; occupancy++) { - const layers: NozzleLayerRecord[] = [0, 1].map((z) => ({ - mask: Uint8Array.from({ length: 4 }, (_, i) => (occupancy >> (z * 4 + i)) & 1), - baseZ: z, - topZ: z + 1, - })); - const count = layers.reduce((total, layer) => total + layer.mask.reduce((a, b) => a + b, 0), 0); - const mesh = buildNozzleVoxelMesh(layers, 2, 2, 1); - assertClosedIndexedSurface(mesh, { volume: count, label: `occupancy ${occupancy.toString(2)}` }); - - // Surface area must equal the exposed voxel faces, with internal faces removed. - let expectedArea = count * 6; - for (let z = 0; z < 2; z++) { - for (let y = 0; y < 2; y++) { - for (let x = 0; x < 2; x++) { - const i = y * 2 + x; - if (!layers[z].mask[i]) continue; - if (x === 0 && layers[z].mask[i + 1]) expectedArea -= 2; - if (y === 0 && layers[z].mask[i + 2]) expectedArea -= 2; - if (z === 0 && layers[1].mask[i]) expectedArea -= 2; - } - } - } - let area = 0; - const vertex = (i: number) => new Vector3().fromArray(mesh.positions, i * 3); - for (let i = 0; i < mesh.indices.length; i += 3) { - const [a, b, c] = mesh.indices.slice(i, i + 3).map(vertex); - area += b.sub(a).cross(c.sub(a)).length() / 2; - } - assert.equal(area, expectedArea, `occupancy ${occupancy}: exposed surface area`); - } -}); - -test('voxel mesh caps missing layers and physical Z gaps independently', () => { - for (const layers of [ - [{ mask: new Uint8Array([1]), baseZ: 0, topZ: 1 }, null, - { mask: new Uint8Array([1]), baseZ: 2, topZ: 3 }], - [{ mask: new Uint8Array([1]), baseZ: 0, topZ: 1 }, - { mask: new Uint8Array([1]), baseZ: 1.0001, topZ: 2.0001 }], - ]) { - assertClosedIndexedSurface(buildNozzleVoxelMesh(layers, 1, 1, 1), { volume: 2, label: 'Z gap' }); - } -}); - -test('async voxel reconstruction yields during face generation, pairing, and triangulation', async () => { - const layers = [0, 1].map((z) => ({ - mask: Uint8Array.from({ length: 144 }, (_, i) => Number((i % 12 + Math.floor(i / 12) + z) % 2 === 0)), - baseZ: z, - topZ: z + 1, - })); - let progress = 0; - const yieldedAt: number[] = []; - const mesh = await buildNozzleVoxelMeshAsync(layers, 12, 12, 1, { - yieldIntervalMs: 0, - onProgress: (value) => { - assert.ok(value >= progress && value <= 1, 'voxel progress must be monotonic'); - progress = value; - }, - onYield: async () => { - await new Promise((resolve) => setTimeout(resolve, 0)); - yieldedAt.push(progress); - }, - }); - for (const [start, end] of [[0, 0.6], [0.6, 0.8], [0.8, 1]]) { - assert.ok(yieldedAt.some((value) => value >= start && value < end), - `must yield during voxel phase ${start}-${end}`); - } - assert.equal(progress, 1); - assert.deepEqual(mesh, buildNozzleVoxelMesh(layers, 12, 12, 1), 'chunking must preserve geometry'); - assertClosedIndexedSurface(mesh, { volume: 144, label: 'async checkerboard' }); -});