From f03a9172baf68ff2e6e4be2815ebf3e56131bf4b Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:36:43 -0700 Subject: [PATCH 001/116] Parametric: elastic properties for materials (modulus, Poisson's ratio, yield and tensile strength) --- src/parametric/src/app/dialogs.ts | 56 ++++++++++++----- src/parametric/src/model/document.ts | 3 + src/parametric/src/model/materials.ts | 87 +++++++++++++++++++++------ src/parametric/src/model/types.ts | 8 +++ 4 files changed, 123 insertions(+), 31 deletions(-) diff --git a/src/parametric/src/app/dialogs.ts b/src/parametric/src/app/dialogs.ts index 1462210c12..79319ae35e 100644 --- a/src/parametric/src/app/dialogs.ts +++ b/src/parametric/src/app/dialogs.ts @@ -10,7 +10,7 @@ import { changeUnits, mapExpressions } from '../model/document'; import type { MaterialRef, SkCurve, SkDimension, UnitSystem, Variable } from '../model/types'; import { UNIT_SYSTEMS, formatNumber } from '../model/units'; import { BASE_FRAMES } from '../model/planes'; -import { MATERIALS } from '../model/materials'; +import { type ElasticProps, MATERIALS, MATERIAL_NOTES, elasticOf, validElastic } from '../model/materials'; import { uniqueId } from '../model/ids'; import { idFactory, mirrorAxisDirection, mirrorEntities, offsetCurves, pickMirrorAxis } from '../sketch/ops'; import { SketchIndex, tessellate } from '../sketch/geom'; @@ -204,7 +204,7 @@ function fieldLabel(text: string, field: HTMLElement): HTMLElement { export async function materialDialog(app: App) { const signal = app.documentSignal; const cur = app.store.doc.material; - const preset = cur && MATERIALS.find((m) => m.name === cur.name && m.density === cur.density); + const preset = cur && MATERIALS.find((m) => m.name === cur.name && m.density === cur.density && (cur.E === undefined || (cur.E === m.E && cur.nu === m.nu && cur.yield === m.yield && cur.uts === m.uts))); const select = h('select', { class: 'input', 'aria-label': 'Material' }) as HTMLSelectElement; select.append(h('option', { value: '' }, 'Not specified')); for (const m of MATERIALS) { @@ -213,41 +213,69 @@ export async function materialDialog(app: App) { select.append(o); } select.append(h('option', { value: '__custom' }, 'Custom...')); + const own = cur && !preset ? elasticOf(cur) : null; + const num = (v: number | undefined, label: string, step = 'any') => h('input', { class: 'input', type: 'number', min: '0', step, value: v === undefined ? '' : String(v), 'aria-label': label }) as HTMLInputElement; const customName = h('input', { class: 'input', value: cur && !preset ? cur.name : 'Custom material', 'aria-label': 'Custom material name' }) as HTMLInputElement; - const customDensity = h('input', { class: 'input', type: 'number', min: '0', step: 'any', value: String(cur?.density ?? 1000), 'aria-label': 'Density in kg per cubic metre' }) as HTMLInputElement; - const custom = h('div', { class: 'grid-form' }, fieldLabel('Name', customName), customName, fieldLabel('Density (kg/m³)', customDensity), customDensity); + const customDensity = num(cur?.density ?? 1000, 'Density in kg per cubic metre'); + // Elastic properties: optional, for stress analysis (GPa reads better than MPa for the modulus). + const customE = num(own ? own.E / 1000 : undefined, 'Elastic modulus in GPa'); + const customNu = num(own?.nu, 'Poisson\'s ratio'); + const customYield = num(own?.yield, 'Yield strength in MPa'); + const customUts = num(own?.uts, 'Tensile strength in MPa'); + const custom = h('div', { class: 'grid-form' }, fieldLabel('Name', customName), customName, fieldLabel('Density (kg/m³)', customDensity), customDensity, + fieldLabel('Elastic modulus (GPa)', customE), customE, fieldLabel('Poisson\'s ratio', customNu), customNu, + fieldLabel('Yield strength (MPa)', customYield), customYield, fieldLabel('Tensile strength (MPa)', customUts), customUts); + const customHint = h('p', { class: 'field-label' }, 'The elastic properties are needed for stress analysis; leave them all empty if the part will not be analyzed.'); if (cur && !preset) select.value = '__custom'; + // A preset's analysis properties, and what to keep in mind about them. + const props = h('div', { class: 'field-label fea-material-props', 'aria-live': 'polite' }); const error = h('div', { id: nextDomId('density-error'), class: 'field-label', role: 'alert', style: { color: 'var(--danger)' } }); customDensity.setAttribute('aria-describedby', error.id); + const elasticFields = [customE, customNu, customYield, customUts]; + const customElastic = (): ElasticProps | null | 'invalid' => { + if (elasticFields.every((f) => !f.value.trim())) return null; + const e = { E: Number(customE.value) * 1000, nu: Number(customNu.value), yield: Number(customYield.value), uts: Number(customUts.value) }; + return elasticFields.some((f) => !f.value.trim()) || !validElastic(e) ? 'invalid' : e; + }; const validate = () => { const density = Number(customDensity.value); - const valid = select.value !== '__custom' || (Number.isFinite(density) && density > 0); - error.textContent = valid ? '' : 'Enter a finite, positive density.'; - if (valid) customDensity.removeAttribute('aria-invalid'); + const densityOk = select.value !== '__custom' || (Number.isFinite(density) && density > 0); + const elasticOk = select.value !== '__custom' || customElastic() !== 'invalid'; + error.textContent = !densityOk ? 'Enter a finite, positive density.' : !elasticOk ? 'Enter all four elastic properties as positive numbers, with a Poisson\'s ratio from 0 to below 0.5 (or leave them all empty).' : ''; + if (densityOk) customDensity.removeAttribute('aria-invalid'); else customDensity.setAttribute('aria-invalid', 'true'); - return valid; + for (const f of elasticFields) { if (elasticOk) f.removeAttribute('aria-invalid'); else f.setAttribute('aria-invalid', 'true'); } + return densityOk && elasticOk; }; - customDensity.addEventListener('input', () => { if (error.textContent) validate(); }); + for (const f of [customDensity, ...elasticFields]) f.addEventListener('input', () => { if (error.textContent) validate(); }); const sync = () => { - custom.hidden = select.value !== '__custom'; + custom.hidden = customHint.hidden = select.value !== '__custom'; + const m = MATERIALS.find((x) => x.name === select.value); + const e = m ? elasticOf(m) : null; + props.hidden = !m; + props.textContent = !m ? '' : (e ? `Elastic modulus ${formatGroup([e.E / 1000], 1)[0]} GPa, Poisson's ratio ${e.nu}, yield strength ${e.yield} MPa, tensile strength ${e.uts} MPa. ` : '') + (MATERIAL_NOTES[m.name] ?? (e ? 'Typical values.' : '')); if (custom.hidden) validate(); }; select.addEventListener('change', sync); sync(); const v = await showDialog({ title: 'Material', signal, - body: [h('p', {}, 'The material sets the density used for mass properties.'), select, custom, error], + body: [h('p', {}, 'The material sets the density used for mass properties, and the elastic properties used for stress analysis.'), select, props, custom, customHint, error], buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Apply', value: 'ok', primary: true }], onAction: (action) => { - if (action === 'ok' && !validate()) { customDensity.focus(); return false; } + if (action === 'ok' && !validate()) { (customDensity.getAttribute('aria-invalid') ? customDensity : customE).focus(); return false; } }, }); if (v !== 'ok' || signal.aborted) return; let m: MaterialRef | null = null; if (select.value === '__custom') { const d = Number(customDensity.value); - m = { name: customName.value.trim() || 'Custom material', density: d }; - } else if (select.value) m = MATERIALS.find((x) => x.name === select.value) ?? null; + const e = customElastic(); + m = { name: customName.value.trim() || 'Custom material', density: d, ...(e && e !== 'invalid' ? e : {}) }; + } else if (select.value) { + const p = MATERIALS.find((x) => x.name === select.value); + m = p ? { ...p } : null; + } app.store.change('Edit material', (doc) => { doc.material = m; }); } diff --git a/src/parametric/src/model/document.ts b/src/parametric/src/model/document.ts index a1df14d3bf..559c25aaf1 100644 --- a/src/parametric/src/model/document.ts +++ b/src/parametric/src/model/document.ts @@ -12,6 +12,7 @@ import { validFeature } from './validate-feature'; import { validSketch } from './validate-sketch'; import { validDrawing } from './validate-drawing'; import { camIds, normalizeCam } from './cam'; +import { normalizeMaterial } from './materials'; import { solveSketch } from '../sketch/solver'; import { hasExternal } from '../sketch/external'; @@ -81,6 +82,8 @@ export function parseDocument(text: string): PartDocument { // Times a Date can hold (the drawing's title block shows the modified day). for (const k of ['created', 'modified'] as const) if (!Number.isFinite(doc[k]) || Math.abs(doc[k]) > 8.64e15) doc[k] = base[k]; if (doc.material != null && !(isObj(doc.material) && typeof doc.material.name === 'string' && Number.isFinite(doc.material.density) && doc.material.density > 0)) doc.material = null; + // Elastic properties that are not a complete, valid set are dropped (the material stays). + if (doc.material) doc.material = normalizeMaterial(doc.material); if (doc.drawing != null && !validDrawing(doc.drawing)) throw new Error('The part file is damaged (invalid drawing).'); // Machining data that cannot be read is dropped rather than refusing the part. if (doc.cam != null) doc.cam = normalizeCam(doc.cam); diff --git a/src/parametric/src/model/materials.ts b/src/parametric/src/model/materials.ts index 76565d983f..50c4e3505b 100644 --- a/src/parametric/src/model/materials.ts +++ b/src/parametric/src/model/materials.ts @@ -1,24 +1,77 @@ -// Material presets: name and density (kg/m^3) used for mass properties. +// Material presets: density (kg/m^3) for mass properties, and the elastic +// properties a static stress analysis needs: elastic modulus and yield and +// tensile strength in MPa, Poisson's ratio. Values are typical published +// figures for the grade named (room temperature); real parts vary with +// temper, heat treatment and, for plastics, with moisture and print settings. import type { MaterialRef } from './types'; export const MATERIALS: MaterialRef[] = [ - { name: 'Plain Carbon Steel', density: 7800 }, - { name: 'Stainless Steel (304)', density: 8000 }, - { name: 'Alloy Steel', density: 7700 }, - { name: 'Cast Iron', density: 7200 }, - { name: 'Aluminum 6061', density: 2700 }, - { name: 'Aluminum 7075', density: 2810 }, - { name: 'Brass', density: 8500 }, - { name: 'Copper', density: 8900 }, - { name: 'Titanium (Ti-6Al-4V)', density: 4430 }, - { name: 'ABS', density: 1040 }, - { name: 'PLA', density: 1240 }, - { name: 'PETG', density: 1270 }, - { name: 'Nylon 6/6', density: 1140 }, - { name: 'Acrylic (PMMA)', density: 1190 }, - { name: 'Polycarbonate', density: 1200 }, + { name: 'Plain Carbon Steel', density: 7800, E: 200000, nu: 0.29, yield: 250, uts: 400 }, + { name: 'Stainless Steel (304)', density: 8000, E: 193000, nu: 0.29, yield: 215, uts: 505 }, + { name: 'Alloy Steel', density: 7700, E: 205000, nu: 0.29, yield: 415, uts: 655 }, + { name: 'Cast Iron', density: 7200, E: 110000, nu: 0.26, yield: 200, uts: 200 }, + { name: 'Aluminum 6061', density: 2700, E: 68900, nu: 0.33, yield: 276, uts: 310 }, + { name: 'Aluminum 7075', density: 2810, E: 71700, nu: 0.33, yield: 503, uts: 572 }, + { name: 'Brass', density: 8500, E: 100000, nu: 0.33, yield: 240, uts: 370 }, + { name: 'Copper', density: 8900, E: 117000, nu: 0.34, yield: 70, uts: 220 }, + { name: 'Titanium (Ti-6Al-4V)', density: 4430, E: 113800, nu: 0.34, yield: 880, uts: 950 }, + { name: 'ABS', density: 1040, E: 2200, nu: 0.35, yield: 40, uts: 44 }, + { name: 'PLA', density: 1240, E: 3500, nu: 0.36, yield: 50, uts: 60 }, + { name: 'PETG', density: 1270, E: 2100, nu: 0.38, yield: 50, uts: 53 }, + { name: 'Nylon 6/6', density: 1140, E: 2800, nu: 0.39, yield: 70, uts: 80 }, + { name: 'Acrylic (PMMA)', density: 1190, E: 3200, nu: 0.37, yield: 70, uts: 70 }, + { name: 'Polycarbonate', density: 1200, E: 2400, nu: 0.37, yield: 62, uts: 66 }, + // Wood is anisotropic (stiffer and stronger along the grain several times over): + // an isotropic analysis would mislead, so it has no elastic properties. { name: 'Oak', density: 750 }, { name: 'Pine', density: 510 }, - { name: 'Glass', density: 2500 }, + { name: 'Glass', density: 2500, E: 70000, nu: 0.22, yield: 40, uts: 40 }, ]; + +/** Notes shown with a preset's analysis properties. */ +export const MATERIAL_NOTES: Record = { + 'Cast Iron': 'Brittle (gray iron): no yield point, so its tensile strength stands in for yield.', + ABS: 'Typical values: plastics vary with grade, temperature and moisture.', + PLA: 'Typical values for molded plastic: 3D printed parts are weaker and stiffer along the layers than across them.', + PETG: 'Typical values for molded plastic: 3D printed parts are weaker and stiffer along the layers than across them.', + 'Nylon 6/6': 'Typical dry values: nylon absorbs moisture and becomes softer and weaker.', + 'Acrylic (PMMA)': 'Brittle: its tensile strength stands in for yield. Typical values.', + Polycarbonate: 'Typical values: plastics vary with grade, temperature and moisture.', + Oak: 'Wood is anisotropic: it cannot be analyzed as an isotropic material.', + Pine: 'Wood is anisotropic: it cannot be analyzed as an isotropic material.', + Glass: 'Brittle: its design tensile strength stands in for yield.', +}; + +/** Elastic properties of a material in MPa (E, yield, ultimate) and Poisson's ratio. */ +export interface ElasticProps { + E: number; + nu: number; + yield: number; + uts: number; +} + +/** Whether a value is a usable elastic property set (Poisson's ratio below 0.5: incompressible solids cannot be analyzed this way). */ +export function validElastic(m: Partial): m is ElasticProps { + const pos = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v > 0; + return pos(m.E) && typeof m.nu === 'number' && Number.isFinite(m.nu) && m.nu >= 0 && m.nu < 0.5 && pos(m.yield) && pos(m.uts); +} + +/** + * The elastic properties of the part's material: its own, else those of the + * preset of that name and density (parts saved before materials had them). + * Null when it has none (wood, a custom material without them, no material). + */ +export function elasticOf(m: MaterialRef | null | undefined): ElasticProps | null { + if (!m) return null; + if (validElastic(m)) return { E: m.E, nu: m.nu, yield: m.yield, uts: m.uts }; + if (m.E !== undefined) return null; + const preset = MATERIALS.find((p) => p.name === m.name && p.density === m.density); + return preset && validElastic(preset) ? { E: preset.E, nu: preset.nu, yield: preset.yield, uts: preset.uts } : null; +} + +/** A material read from a file: the elastic properties are kept only as a complete, valid set. */ +export function normalizeMaterial(m: MaterialRef): MaterialRef { + const { E, nu, yield: sy, uts, ...rest } = m; + return validElastic({ E, nu, yield: sy, uts }) ? { ...rest, E, nu, yield: sy, uts } : rest; +} diff --git a/src/parametric/src/model/types.ts b/src/parametric/src/model/types.ts index ce29b8a86e..7fc30e5aa0 100644 --- a/src/parametric/src/model/types.ts +++ b/src/parametric/src/model/types.ts @@ -599,6 +599,14 @@ export interface MaterialRef { name: string; /** kg/m^3 */ density: number; + /** + * Elastic properties for stress analysis (all four, or none): elastic modulus, + * yield and ultimate tensile strength in MPa, and Poisson's ratio. + */ + E?: number; + nu?: number; + yield?: number; + uts?: number; } export interface PartDocument { From 5c5430741cc0ea0fdddcfe38687945d165fabf43 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:43:10 -0700 Subject: [PATCH 002/116] Parametric: limit and mechanical mates and motion studies in the mate solver and assembly files Distance and angle mates can be kept between limits; hinge, gear, rack and pinion, screw, width and slot mates. Coupling mates measure motion from where each solve starts, so turns add up past a full turn. Motion studies step the solver frame by frame with rotary, linear and mate-driving motors, stop at limits or lock-ups, and give paths, turns and mate values with derivatives. --- src/parametric/src/assembly/motion.ts | 285 ++++++++++++++ src/parametric/src/assembly/solver.ts | 364 ++++++++++++++++-- src/parametric/src/model/assembly.ts | 149 ++++++- .../tests/assembly-kinematics.test.ts | 355 +++++++++++++++++ src/parametric/tests/assembly-model.test.ts | 69 ++++ 5 files changed, 1189 insertions(+), 33 deletions(-) create mode 100644 src/parametric/src/assembly/motion.ts create mode 100644 src/parametric/tests/assembly-kinematics.test.ts diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts new file mode 100644 index 0000000000..fa05c833c5 --- /dev/null +++ b/src/parametric/src/assembly/motion.ts @@ -0,0 +1,285 @@ +// Motion studies: an assembly's mechanism driven by motors over time. +// +// Each frame is a solve of the mates from the frame before (a warm start), +// with the motors as hard goals: a rotary motor turns its component by what +// its profile turns it in that frame, a linear motor moves it, a mate driver +// sets its mate's value. Coupling mates (gears, racks, screws) measure motion +// from the frame before, so their turns add up over the study. A frame that +// cannot be solved stops the study: a limit is reached, or the mechanism +// locks up (the motors ask for a motion the mates do not allow). +// +// Results come from the frames: positions of a point of a component, its +// turn, or what a mate measures, with velocities and accelerations by finite +// differences. + +import type { Quat, Vec3 } from '../math/vec'; +import { add, dot, len, normalize, qMul } from '../math/vec'; +import type { MotionMotor, Placement } from '../model/assembly'; +import type { Id } from '../model/types'; +import { + CONFLICT_TOL, type Drive, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, mateMeasure, placeGeo, quatRotVec, +} from './solver'; + +/** A motor ready to run: what it moves and its motion over time. */ +export interface MotorInput { + id: Id; + name: string; + kind: MotionMotor['kind']; + /** Rotary and linear: the component moved, and the axis or direction entity (on it, or on another component). */ + body?: Id; + entity?: SolverEntity; + /** Mate driver: the mate whose value it sets. */ + mate?: Id; + /** Rotary: the turn (radians); linear: the travel (mm), from the start of the study. Mate driver: the mate's value (mm or degrees). */ + at: (t: number) => number; +} + +/** Numbers of a motor's profile, evaluated (degrees, mm, seconds, Hz). */ +export interface ProfileValues { + profile: MotionMotor['profile']; + speed?: number; + rpm?: boolean; + amplitude?: number; + frequency?: number; + from?: number; + to?: number; + reverse?: boolean; +} + +/** + * A motor's motion over time. Rotary motors give radians, linear ones mm; + * a mate driver gives its mate's value, starting from `base` (the value the + * mate has) unless it ramps between two values. + */ +export function profileOf(kind: MotionMotor['kind'], p: ProfileValues, duration: number, base = 0): (t: number) => number { + const sign = p.reverse ? -1 : 1; + // Rotary values are in degrees (rpm for speeds when asked), turned into radians. + const k = kind === 'rotary' ? Math.PI / 180 : 1; + const speed = (p.speed ?? 0) * (kind === 'rotary' && p.rpm ? 6 : 1); + if (p.profile === 'constant') return (t) => base + sign * k * speed * t; + if (p.profile === 'oscillate') { + const a = p.amplitude ?? 0, f = p.frequency ?? 0; + return (t) => base + sign * k * a * Math.sin(2 * Math.PI * f * t); + } + const from = p.from ?? 0, to = p.to ?? 0; + return (t) => from + ((to - from) * Math.min(1, Math.max(0, t / Math.max(duration, 1e-9)))); +} + +export interface MotionSetup { + bodies: SolverBody[]; + /** The mates that hold (conflicting and broken ones left out). */ + mates: SolverMate[]; + motors: MotorInput[]; + duration: number; + fps: number; + /** The assembly's size (see SolveOptions.scale). */ + scale: number; + /** Names of mates and motors, for the messages. */ + names?: Map; +} + +export interface MotionStop { + /** Seconds. */ + time: number; + kind: 'limit' | 'locked'; + message: string; + /** The mate whose limit was reached, or that could not hold. */ + mate?: Id; +} + +export interface MotionResult { + /** Seconds, one per frame computed. */ + times: number[]; + /** Placements of every component in each frame. */ + frames: Map[]; + /** Why the study stopped before its end, or null. */ + stop: MotionStop | null; + /** The study's length (seconds), even when it stopped early. */ + duration: number; +} + +/** + * Steps a study frame by frame (so the caller can share the time: see + * runMotion). The first frame is the assembly as it is. + */ +export class MotionRun { + readonly count: number; + readonly dt: number; + readonly result: MotionResult; + private k = 0; + private solverMates: SolverMate[]; + + constructor(private setup: MotionSetup) { + this.count = Math.max(1, Math.round(setup.duration * setup.fps)); + this.dt = setup.duration / this.count; + // Only what the motors move is solved: the mates of the components they drive and those linked to them. + const moving = new Set(); + for (const m of setup.motors) { + const ids = m.body ? [m.body] : setup.mates.filter((x) => x.id === m.mate).flatMap(mateBodies); + for (const id of ids) for (const x of matesMoving(id, setup.bodies, setup.mates)) moving.add(x); + } + this.solverMates = setup.mates.filter((x) => moving.has(x)); + const first = new Map(setup.bodies.map((b) => [b.id, b.placement])); + this.result = { times: [0], frames: [first], stop: null, duration: setup.duration }; + } + + get done(): boolean { + return this.k >= this.count || !!this.result.stop; + } + + /** Frames computed so far, out of count + 1. */ + get progress(): number { + return this.k / this.count; + } + + /** Computes the next frame; false once the study is over (or stopped). */ + step(): boolean { + if (this.done) return false; + const s = this.setup; + const t0 = this.k * this.dt, t1 = (this.k + 1) * this.dt; + const prev = this.result.frames[this.result.frames.length - 1]; + const drives: Drive[] = []; + let mates = this.solverMates; + for (const m of s.motors) { + if (m.kind === 'mate') { + const v = m.at(t1); + mates = mates.map((x) => (x.id === m.mate ? { ...x, value: v } : x)); + continue; + } + if (!m.body || !m.entity) continue; + const g = placeGeo(m.entity.geo, m.entity.body ? prev.get(m.entity.body) ?? null : null); + const dir = directionOf(g); + if (!dir) continue; + const amount = m.at(t1) - m.at(t0); + if (m.kind === 'rotary') drives.push({ kind: 'rotate', body: m.body, axis: dir, amount }); + else { + // A point of the moved component: the entity's, when it is on it. + const local: Vec3 = m.entity.body === m.body ? pointOfGeo(m.entity.geo) ?? [0, 0, 0] : s.bodies.find((b) => b.id === m.body)?.center ?? [0, 0, 0]; + drives.push({ kind: 'translate', body: m.body, local, dir, amount }); + } + } + const bodies = s.bodies.map((b) => ({ ...b, placement: prev.get(b.id) ?? b.placement })); + const solver = new MateSolver(bodies, mates); + const r = solver.solve({ scale: s.scale, drives, maxIter: 80 }); + this.k++; + if (!r.ok) { + this.result.stop = this.whyStopped(solver, r.placements, prev, mates, r.residuals, t1); + return false; + } + this.result.times.push(t1); + this.result.frames.push(r.placements); + return !this.done; + } + + private whyStopped(solver: MateSolver, pl: Map, prev: Map, mates: SolverMate[], residuals: Map, t: number): MotionStop { + const name = (id: Id) => this.setup.names?.get(id) ?? id; + const time = Math.round(t * 1e4) / 1e4; + // A limit reached: its one-sided row is what does not hold. + for (const m of mates) { + if (!(m.limit || m.type === 'slot')) continue; + const all = solver.mateResidual(m, pl, this.setup.scale, prev, true) ?? []; + const eq = solver.mateResidual(m, pl, this.setup.scale, prev, false) ?? []; + if (Math.abs(all[all.length - 1] ?? 0) > CONFLICT_TOL && all.length > eq.length) { + return { time, kind: 'limit', mate: m.id, message: `${name(m.id)} reached its limit at ${time} s: the motion stops there.` }; + } + } + let worst: Id | undefined, w = 0; + for (const [id, v] of residuals) if (v > w) { w = v; worst = id; } + const which = worst && w > CONFLICT_TOL ? ` (${name(worst)} cannot hold)` : ''; + return { time, kind: 'locked', mate: worst && w > CONFLICT_TOL ? worst : undefined, message: `The mechanism locks up at ${time} s${which}: the motors ask for a motion the mates do not allow.` }; + } +} + +const directionOf = (g: Geo): Vec3 | null => (g.kind === 'plane' ? normalize(g.n) : g.kind === 'axis' || g.kind === 'line' ? normalize(g.d) : null); +const pointOfGeo = (g: Geo): Vec3 | null => (g.kind === 'plane' ? g.o : g.kind === 'axis' || g.kind === 'line' || g.kind === 'point' ? g.p : g.kind === 'sphere' ? g.c : null); + +/** Runs a whole study at once (tests; the app runs it in slices, see AssemblyMode). */ +export function computeMotion(setup: MotionSetup): MotionResult { + const run = new MotionRun(setup); + while (run.step()); + return run.result; +} + +// ---------- results ---------- + +/** Where a point of a component (its local coordinates) is in each frame. */ +export function pointPath(res: MotionResult, body: Id, local: Vec3): Vec3[] { + return res.frames.map((f) => applyPlacement(f.get(body) ?? { p: [0, 0, 0], q: [0, 0, 0, 1] }, local)); +} + +/** + * A component's turn in each frame as a rotation vector (radians) added up + * frame by frame: about a fixed axis it is the axis times the whole angle, + * past a full turn. + */ +export function turnPath(res: MotionResult, body: Id): Vec3[] { + const out: Vec3[] = []; + let acc: Vec3 = [0, 0, 0]; + let prev: Quat | null = null; + for (const f of res.frames) { + const q = f.get(body)?.q ?? [0, 0, 0, 1]; + if (prev) acc = add(acc, quatRotVec(qMul(q, [-prev[0], -prev[1], -prev[2], prev[3]]))); + out.push(acc); + prev = q; + } + return out; +} + +/** What a mate measures in each frame (degrees unwrapped past ±180°), or null when it measures nothing. */ +export function mateSeries(res: MotionResult, mate: SolverMate, L = 100): { values: number[]; kind: 'length' | 'angle' } | null { + const first = mateMeasure(mate, res.frames[0], L); + if (!first) return null; + const values: number[] = []; + let last = first.value, acc = first.value; + for (const f of res.frames) { + const v = mateMeasure(mate, f, L)?.value ?? last; + if (first.kind === 'angle' && mate.type === 'hinge') { + let d = v - last; + d -= 360 * Math.round(d / 360); + acc += d; + } else acc = v; + last = v; + values.push(acc); + } + return { values, kind: first.kind }; +} + +/** First and second derivatives of samples at times t (central differences; one-sided at the ends). */ +export function derivatives(t: number[], v: number[]): { d1: number[]; d2: number[] } { + const n = v.length; + const d1 = new Array(n).fill(0), d2 = new Array(n).fill(0); + if (n < 2) return { d1, d2 }; + for (let i = 0; i < n; i++) { + const a = Math.max(0, i - 1), b = Math.min(n - 1, i + 1); + d1[i] = (v[b] - v[a]) / (t[b] - t[a] || 1); + } + if (n < 3) return { d1, d2 }; + for (let i = 0; i < n; i++) { + const j = Math.min(n - 2, Math.max(1, i)); + const h1 = t[j] - t[j - 1], h2 = t[j + 1] - t[j]; + // Second difference on uneven steps (the last frame of a study can be shorter). + d2[i] = (2 * ((v[j + 1] - v[j]) / h2 - (v[j] - v[j - 1]) / h1)) / (h1 + h2); + } + return { d1, d2 }; +} + +/** The magnitude of each vector. */ +export const magnitudes = (vs: Vec3[]): number[] => vs.map(len); + +/** Components and magnitude of vectors differentiated: the velocity or acceleration of a path. */ +export function vectorDerivatives(t: number[], vs: Vec3[]): { d1: Vec3[]; d2: Vec3[] } { + const axes = [0, 1, 2].map((k) => derivatives(t, vs.map((v) => v[k]))); + return { d1: vs.map((_, i) => [axes[0].d1[i], axes[1].d1[i], axes[2].d1[i]]), d2: vs.map((_, i) => [axes[0].d2[i], axes[1].d2[i], axes[2].d2[i]]) }; +} + +/** CSV of named columns (the first is the time). */ +export function resultsCsv(columns: { name: string; values: number[] }[]): string { + const n = Math.max(0, ...columns.map((c) => c.values.length)); + const cell = (s: string) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s); + const rows = [columns.map((c) => cell(c.name)).join(',')]; + for (let i = 0; i < n; i++) rows.push(columns.map((c) => (Number.isFinite(c.values[i]) ? String(Math.round(c.values[i] * 1e9) / 1e9) : '')).join(',')); + return rows.join('\n'); +} + +/** The angle (degrees) a turn path turns about a direction. */ +export const degreesAbout = (path: Vec3[], axis: Vec3): number[] => path.map((v) => (dot(v, normalize(axis)) * 180) / Math.PI); diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index cc4e84990f..01f281370d 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -13,11 +13,22 @@ // Dragging adds soft goals (the grabbed point follows the cursor, or the // component turns toward an orientation) that the mates override: a lid on a // hinge pin turns about the pin as its edge is dragged. +// +// Limits (distance and angle mates kept between two values, a hinge's angle +// range, a slot's ends) are one-sided residuals: zero inside the range, the +// overshoot outside it. They take no degree of freedom away (the rank +// analysis leaves them out) but stop a drag at the limit. +// +// Gear, rack and pinion and screw mates relate motions, not positions: how +// far a component turned or slid since the start of the solve (the +// placements it started from). Every solve starts where the last one ended +// (a drag step, a motion study frame, the document after a commit), so the +// turns add up: a gear driven round and round keeps its ratio past ±180°. import type { Quat, Vec3 } from '../math/vec'; import { add, cross, dot, len, normalize, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; import type { Id } from '../model/types'; -import type { MateType, Placement } from '../model/assembly'; +import { type MateType, type Placement, isMechanical } from '../model/assembly'; /** Geometry of a mate entity, in the coordinates of its component (or the assembly for ground). */ export type Geo = @@ -45,10 +56,32 @@ export interface SolverMate { /** Distance in mm, angle in degrees. */ value: number; flip: boolean; - /** Lock: b's placement in a's frame. */ + /** Lock: b's placement in a's frame. Hinge: where b was in a's frame at 0° (for its limits). */ rel?: Placement; + /** Second entities: a hinge's coincident faces, a width mate's second groove and tab faces, a slot's second end. */ + a2?: SolverEntity; + b2?: SolverEntity; + /** Hinge: alignment of the coincident faces. */ + aligned2?: boolean; + /** Distance (mm) or angle (degrees) range; a hinge's turn range (degrees). */ + limit?: { min: number; max: number }; + /** Gear: b's pitch diameter or part of the ratio (value is a's). */ + value2?: number; + /** Rack and pinion: value is the travel per turn (not the pitch diameter). */ + by?: 'ratio' | 'revolution'; + /** Gear, rack and pinion: the other way round; screw: left-hand. */ + reverse?: boolean; } +/** + * A motor's motion over one solve (a motion study frame), from where the + * component starts: a turn (radians) about a direction in the assembly, or a + * move (mm) of a point of it along one. + */ +export type Drive = + | { kind: 'rotate'; body: Id; axis: Vec3; amount: number } + | { kind: 'translate'; body: Id; local: Vec3; dir: Vec3; amount: number }; + export interface SolverBody { id: Id; fixed: boolean; @@ -68,6 +101,8 @@ export interface SolveOptions { drag?: DragGoal | null; /** Relative resistance of a body to moving (higher moves less). */ weight?: (id: Id) => number; + /** Motors: hard goals, held like mates. */ + drives?: Drive[]; } export interface SolveResult { @@ -77,6 +112,8 @@ export interface SolveResult { /** Largest residual of each mate (normalised), after solving. */ residuals: Map; iterations: number; + /** Largest residual of the drives (normalised). */ + driveResidual?: number; } /** 'error': a mate cannot be formed (its face is gone, or the entities do not fit its type); none conflict. */ @@ -116,6 +153,22 @@ export function rotVecQuat(w: Vec3): Quat { const qConj = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]]; +/** How far (radians, in (-π, π]) orientation q is turned from q0 about the unit direction d (both in the same frame). */ +export function turnAbout(q: Quat, q0: Quat, d: Vec3): number { + const dq = qMul(q, qConj(q0)); + const s = dq[3] < 0 ? -1 : 1; + return 2 * Math.atan2(s * (dq[0] * d[0] + dq[1] * d[1] + dq[2] * d[2]), s * dq[3]); +} + +const IDENT: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + +/** The components a mate's entities belong to (each once). */ +export function mateBodies(m: SolverMate): Id[] { + const out: Id[] = []; + for (const e of [m.a, m.b, m.a2, m.b2]) if (e?.body && !out.includes(e.body)) out.push(e.body); + return out; +} + /** Rotation vector (axis times angle) of a quaternion. */ export function quatRotVec(q: Quat): Vec3 { const s = q[3] < 0 ? -1 : 1; @@ -322,6 +375,221 @@ export function initialMateSettings(type: MateType, a: Geo, b: Geo): { aligned: return { aligned, flip, value }; } +// ---------- limits ---------- + +/** + * A distance mate's conditions apart from the distance (parallel faces...) + * and the distance it measures (signed for a plane: on the flipped side it + * is the distance below), or null when the entities cannot take one. + */ +export function distanceParts(a: Geo, b: Geo, o: { aligned: boolean; flip: boolean; scale: number }, swapped = false): { eq: number[]; d: number } | null { + const s = o.flip ? -1 : 1; + const match = (da: Vec3, db: Vec3) => (o.aligned ? sub(da, db) : add(da, db)); + const sw = () => (swapped ? null : distanceParts(b, a, o, true)); + if (a.kind === 'body' || b.kind === 'body') return null; + if (a.kind === 'plane' && b.kind === 'plane') return { eq: match(a.n, b.n), d: s * dot(sub(b.o, a.o), a.n) }; + if (b.kind === 'plane') return sw(); + if (a.kind === 'plane') { + const p = pointOf(b); + if (!p) return null; + const eq = isAxisLike(b) && !(b.kind === 'axis' && b.surface === 'circle') ? [dot(dirOf(b)!, a.n)] : []; + return { eq, d: s * dot(sub(p, a.o), a.n) }; + } + if (isPointLike(a) && isPointLike(b)) return { eq: [], d: len(sub(pointOf(a)!, pointOf(b)!)) }; + if (isAxisLike(a) && isAxisLike(b) && !isPointLike(a) && !isPointLike(b)) return { eq: match(dirOf(a)!, dirOf(b)!), d: len(cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!)) }; + if (isAxisLike(a) && isPointLike(b)) return { eq: [], d: len(cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!)) }; + if (isAxisLike(b) && isPointLike(a)) return sw(); + return null; +} + +/** The angle (degrees, 0 to 180) between two entities' directions, measured as an angle mate with that alignment does. */ +export function angleOf(a: Geo, b: Geo, aligned: boolean): number | null { + const da = dirOf(a), db = dirOf(b); + if (!da || !db) return null; + return (Math.acos(Math.max(-1, Math.min(1, (aligned ? 1 : -1) * dot(da, db)))) * 180) / Math.PI; +} + +/** The overshoot of v past [min, max] (zero inside). */ +const outside = (v: number, min: number, max: number) => (v > max ? v - max : v < min ? v - min : 0); + +/** A distance or angle mate kept between limits: its other conditions, and the overshoot (when `ineq`). */ +function limitEquations(type: 'distance' | 'angle', a: Geo, b: Geo, o: EqOpts, lim: { min: number; max: number }, ineq: boolean): number[] | null { + if (type === 'angle') { + const da = dirOf(a), db = dirOf(b); + if (!da || !db || a.kind === 'body' || b.kind === 'body') return null; + // On the cosine (smooth where the angle is 0° or 180°): cos falls as the angle grows. + const c = (o.aligned ? 1 : -1) * dot(da, db); + return ineq ? [outside(c, Math.cos((lim.max * Math.PI) / 180), Math.cos((lim.min * Math.PI) / 180))] : []; + } + const d = distanceParts(a, b, o); + if (!d) return null; + return [...d.eq, ...(ineq ? [outside(d.d, lim.min, lim.max) / o.scale] : [])]; +} + +// ---------- mechanical mates ---------- + +/** The entities of a mechanical mate placed in the assembly, with the placements of their components now and at the start of the solve. */ +interface MechContext { + m: SolverMate; + ga: Geo; gb: Geo; ga2: Geo | null; gb2: Geo | null; + pa: Placement; pb: Placement; ra: Placement; rb: Placement; + /** Placement of an entity's component, now and at the start. */ + now: (e: SolverEntity) => Placement; + start: (e: SolverEntity) => Placement; + L: number; + ineq: boolean; +} + +/** A hinge's turn (radians) from where it was at 0° (rel), about a's axis. */ +function hingeTurn(m: SolverMate, pa: Placement, pb: Placement): number | null { + if (!m.rel || m.a.geo.kind !== 'axis') return null; + const rel = relativePlacement(pa, pb); + return turnAbout(rel.q, m.rel.q, normalize(m.a.geo.d)); +} + +/** + * Rack and pinion: which way the rack moves as the pinion turns forward, + * from where the rack is beside the pinion (its teeth move with the pinion's + * near side). + */ +function rackSense(dp: Vec3, cp: Vec3, u: Vec3, pr: Vec3): number { + const w = sub(pr, cp); + const n = sub(sub(w, scale(dp, dot(w, dp))), scale(u, dot(w, u))); + const s = dot(cross(dp, n), u); + return s < 0 ? -1 : 1; +} + +function mechanicalEquations(c: MechContext): number[] | null { + const { m, ga, gb, ga2, gb2, L } = c; + const o = { aligned: m.aligned, value: m.value, flip: m.flip, scale: L }; + switch (m.type) { + case 'hinge': { + if (!ga2 || !gb2) return null; + const conc = equations('concentric', ga, gb, o, null, null), plane = equations('coincident', ga2, gb2, { ...o, aligned: !!m.aligned2 }, null, null); + if (!conc || !plane || ga.kind !== 'axis' || gb.kind !== 'axis' || ga2.kind !== 'plane' || gb2.kind !== 'plane') return null; + if (!m.limit) return [...conc, ...plane]; + const t = hingeTurn(m, c.pa, c.pb); + if (t === null) return null; + return [...conc, ...plane, ...(c.ineq ? [outside(t, (m.limit.min * Math.PI) / 180, (m.limit.max * Math.PI) / 180)] : [])]; + } + case 'gear': { + if (!isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; + const da = normalize(dirOf(ga)!), db0 = normalize(dirOf(gb)!); + // Parallel axes turn about the same direction: external gears turn opposite ways. + const db = dot(da, db0) < 0 ? scale(db0, -1) : db0; + const ta = turnAbout(c.pa.q, c.ra.q, da), tb = turnAbout(c.pb.q, c.rb.q, db); + const va = m.value, vb = m.value2 ?? 0; + if (!(va > 0) || !(vb > 0)) return null; + return [(va * ta + (m.reverse ? -1 : 1) * vb * tb) / Math.max(va, vb)]; + } + case 'rackPinion': { + // a: the pinion (an axis), b: the rack (a straight edge, along which it moves). + if (!isAxisLike(ga) || gb.kind !== 'line' || m.b.geo.kind !== 'line' || !(m.value > 0)) return null; + const dp = normalize(dirOf(ga)!), u = normalize(gb.d); + const turn = m.a.body ? turnAbout(c.pa.q, c.ra.q, dp) : 0; + const local = m.b.geo.p; + const moved = dot(sub(applyPlacement(c.pb, local), applyPlacement(c.rb, local)), u); + const sense = rackSense(placeGeoDir(m.a.geo, c.ra), pointOf(placeGeo(m.a.geo, c.ra))!, normalize(qRotate(c.rb.q, m.b.geo.d)), applyPlacement(c.rb, local)); + const perRadian = m.by === 'revolution' ? m.value / (2 * Math.PI) : m.value / 2; + return [(moved - (m.reverse ? -1 : 1) * sense * perRadian * turn) / L]; + } + case 'screw': { + const conc = equations('concentric', ga, gb, o, null, null); + if (!conc || ga.kind !== 'axis' || gb.kind !== 'axis' || m.a.geo.kind !== 'axis' || m.b.geo.kind !== 'axis' || !m.value) return null; + // b's turn and travel along a's axis, in a's frame (a nut on a screw that itself moves). + const dl = normalize(m.a.geo.d); + const rel = relativePlacement(c.pa, c.pb), rel0 = relativePlacement(c.ra, c.rb); + const turn = turnAbout(rel.q, rel0.q, dl); + const travel = dot(sub(applyPlacement(rel, m.b.geo.p), applyPlacement(rel0, m.b.geo.p)), dl); + return [...conc, (travel - ((m.reverse ? -1 : 1) * m.value * turn) / (2 * Math.PI)) / L]; + } + case 'width': { + if (!ga2 || !gb2 || ga.kind !== 'plane' || gb.kind !== 'plane' || ga2.kind !== 'plane' || gb2.kind !== 'plane') return null; + // The tab's mid plane on the groove's: parallel, and centred. + const mid = (p: Vec3, q: Vec3) => scale(add(p, q), 0.5); + return [...cross(ga.n, gb.n), dot(sub(mid(gb.o, gb2.o), mid(ga.o, ga2.o)), ga.n) / L]; + } + case 'slot': { + if (!ga2 || !isAxisLike(ga) || !isAxisLike(ga2)) return null; + const da = normalize(dirOf(ga)!), p1 = pointOf(ga)!, w = sub(pointOf(ga2)!, p1); + const along = sub(w, scale(da, dot(w, da))); + const length = len(along); + const pb = pointOf(gb); + if (length < 1e-9 || !pb) return null; + const u = scale(along, 1 / length), ns = cross(da, u); + const off = sub(pb, p1); + // An axis (a pin) stays parallel to the slot's ends; it, or a point, stays on the plane through them, between the ends. + const par = gb.kind === 'axis' || gb.kind === 'line' ? cross(da, normalize(dirOf(gb)!)) : []; + return [...par, dot(off, ns) / L, ...(c.ineq ? [outside(dot(off, u), 0, length) / L] : [])]; + } + } + return null; +} + +const placeGeoDir = (g: Geo, pl: Placement): Vec3 => normalize(qRotate(pl.q, dirOf(g) ?? [0, 0, 1])); + +/** Why the entities (and values) of a mechanical mate do not make one, or null when they do. */ +export function mechanicalProblem(m: Pick): string | null { + const { a, b, a2, b2 } = m; + const axis = (e?: SolverEntity) => !!e && (e.geo.kind === 'axis' || e.geo.kind === 'line'); + const round = (e?: SolverEntity) => !!e && e.geo.kind === 'axis'; + const plane = (e?: SolverEntity) => !!e && e.geo.kind === 'plane'; + const parallel = (x: SolverEntity, y: SolverEntity) => x.body === y.body && Math.abs(dot(normalize(dirOf(x.geo)!), normalize(dirOf(y.geo)!))) > 0.9999; + switch (m.type) { + case 'hinge': + if (!round(a) || !round(b) || !plane(a2) || !plane(b2)) return 'A hinge needs two round faces or edges (the pin and its hole) and two planar faces that touch'; + if (a2!.body !== a.body || b2!.body !== b.body) return 'Each planar face of a hinge must be on the component of the round entity selected with it'; + if (m.limit && !(m.limit.min <= m.limit.max)) return 'The smallest angle must not be more than the largest'; + return null; + case 'gear': + if (!axis(a) || !axis(b) || !a.body || !b.body) return 'A gear mate needs a round face or edge (or an axis) on each of two components'; + return m.value > 0 && (m.value2 ?? 0) > 0 ? null : 'The gear values must be more than zero'; + case 'rackPinion': + if (!round(a) || b.geo.kind !== 'line' || !b.body) return 'A rack and pinion mate needs a straight edge of the rack and a round face or edge of the pinion'; + return m.value > 0 ? null : 'The pitch diameter (or travel per turn) must be more than zero'; + case 'screw': + if (!round(a) || !round(b) || !a.body || !b.body) return 'A screw mate needs a round face or edge on each of two components'; + return m.value ? null : 'The pitch must not be zero'; + case 'width': + if (!plane(a) || !plane(a2) || !plane(b) || !plane(b2)) return 'A width mate needs two planar faces of the groove and two of the tab'; + if (!parallel(a, a2!) || !parallel(b, b2!)) return 'The two groove faces (and the two tab faces) must be parallel faces of one component'; + return a.body === b.body ? 'The groove and the tab must be on different components' : null; + case 'slot': + if (!round(a) || !round(a2)) return 'A slot mate needs the two round ends of the slot and a pin (a round face or edge, an axis or a point)'; + if (!parallel(a, a2!)) return 'The two ends must be on the same component, and parallel'; + if (len(cross(sub(pointOf(a2!.geo)!, pointOf(a.geo)!), normalize(dirOf(a.geo)!))) < 1e-6) return 'Select the two ends of the slot (they are the same axis)'; + if (b.geo.kind === 'plane' || b.geo.kind === 'body') return 'The pin must be a round face or edge, a straight edge or a point'; + return a.body === b.body ? 'The pin and the slot must be on different components' : null; + } + return null; +} + +/** + * What a mate measures where the components are (a result of a motion + * study): the distance or angle between its entities, a hinge's turn, a + * pin's travel along its slot; null for the others. + */ +export function mateMeasure(m: SolverMate, pl: Map, L = 100): { value: number; kind: 'length' | 'angle' } | null { + const at = (e?: SolverEntity) => (e?.body ? pl.get(e.body) ?? null : null); + const ga = placeGeo(m.a.geo, at(m.a)), gb = placeGeo(m.b.geo, at(m.b)); + if (m.type === 'distance') { const d = distanceParts(ga, gb, { aligned: m.aligned, flip: m.flip, scale: L }); return d ? { value: d.d, kind: 'length' } : null; } + if (m.type === 'angle') { const a = angleOf(ga, gb, m.aligned); return a === null ? null : { value: a, kind: 'angle' }; } + if (m.type === 'hinge') { + const pa = at(m.a) ?? IDENT, pb = at(m.b) ?? IDENT; + const rel = m.rel ?? null; + if (!rel || m.a.geo.kind !== 'axis') return null; + return { value: (turnAbout(relativePlacement(pa, pb).q, rel.q, normalize(m.a.geo.d)) * 180) / Math.PI, kind: 'angle' }; + } + if (m.type === 'slot' && m.a2) { + const ga2 = placeGeo(m.a2.geo, at(m.a2)); + const da = dirOf(ga), p1 = pointOf(ga), p2 = pointOf(ga2), pb = pointOf(gb); + if (!da || !p1 || !p2 || !pb) return null; + const d = normalize(da), w = sub(p2, p1), along = sub(w, scale(d, dot(w, d))); + return len(along) > 1e-9 ? { value: dot(sub(pb, p1), normalize(along)), kind: 'length' } : null; + } + return null; +} + // ---------- the solver ---------- interface System { @@ -348,11 +616,15 @@ export class MateSolver { const L = opts.scale && opts.scale > 0 ? opts.scale : 100; const bodies = new Map(this.bodies.map((b) => [b.id, { ...b, placement: start?.get(b.id) ?? b.placement }])); const involved = new Set(); - for (const m of mates) for (const e of [m.a, m.b]) if (e.body) involved.add(e.body); + for (const m of mates) for (const id of mateBodies(m)) involved.add(id); if (opts.drag) involved.add(opts.drag.body); + const drives = opts.drives ?? []; + for (const d of drives) involved.add(d.body); const vars = [...involved].filter((id) => bodies.has(id) && !bodies.get(id)!.fixed); const sys: System = { vars, index: new Map(vars.map((id, i) => [id, i])), bodies, centers: new Map(vars.map((id) => [id, bodies.get(id)!.center ?? [0, 0, 0]])) }; const placements = new Map([...bodies].map(([id, b]) => [id, b.placement])); + // Where the components start: what gear, rack and pinion and screw mates, and motors, measure motion from. + const ref = placements; const weights = vars.map((id) => Math.sqrt(Math.max(1e-6, opts.weight?.(id) ?? 1))); const n = vars.length * 6; const residuals = new Map(); @@ -360,7 +632,7 @@ export class MateSolver { residuals.clear(); let worst = 0; for (const m of mates) { - const r = this.mateResidual(m, pl, L); + const r = this.mateResidual(m, pl, L, ref); const v = r ? Math.max(0, ...r.map(Math.abs)) : Infinity; residuals.set(m.id, v); worst = Math.max(worst, v); @@ -369,14 +641,15 @@ export class MateSolver { }; // A component no mate holds is carried by a move drag without turning, as if picked up. const drag = opts.drag; - if (drag?.kind === 'move' && sys.index.has(drag.body) && !mates.some((m) => m.a.body === drag.body || m.b.body === drag.body)) { + if (drag?.kind === 'move' && sys.index.has(drag.body) && !drives.length && !mates.some((m) => mateBodies(m).includes(drag.body))) { const pl = placements.get(drag.body)!; const moved = new Map(placements).set(drag.body, { p: add(pl.p, sub(drag.target, applyPlacement(pl, drag.local))), q: pl.q }); return this.solve({ ...opts, drag: null }, mates, moved); } + const driveWorst = (pl: Map) => Math.max(0, ...driveResidual(drives, pl, ref, L).map(Math.abs)); if (!n) { - const worst = evalMates(placements); - return { placements, ok: worst < CONFLICT_TOL, residuals, iterations: 0 }; + const worst = evalMates(placements), dw = driveWorst(placements); + return { placements, ok: worst < CONFLICT_TOL && dw < CONFLICT_TOL, residuals, iterations: 0, driveResidual: dw }; } // While a move drag pulls, turning costs more than sliding: a component // its mates let slide follows the cursor without spinning, and one they @@ -391,7 +664,8 @@ export class MateSolver { const dragWeight = 0.05; const rows = (pl: Map, withDrag: boolean): number[] => { const out: number[] = []; - for (const m of mates) out.push(...(this.mateResidual(m, pl, L) ?? [])); + for (const m of mates) out.push(...(this.mateResidual(m, pl, L, ref) ?? [])); + if (drives.length) out.push(...driveResidual(drives, pl, ref, L)); if (withDrag && opts.drag) out.push(...dragResidual(opts.drag, pl, L).map((v) => v * dragWeight)); return out; }; @@ -407,7 +681,7 @@ export class MateSolver { iterations++; const mateCost = withDrag ? sumSq(rows(at(x), false)) : cost; if (!withDrag && Math.sqrt(mateCost) < TOL) break; - const J = this.jacobian(x, sys, placements, mates, withDrag ? opts.drag ?? null : null, dragWeight, r.length, n, vw, L); + const J = this.jacobian(x, sys, placements, mates, withDrag ? opts.drag ?? null : null, dragWeight, r.length, n, vw, L, drives); const g = new Array(n).fill(0); const A = Array.from({ length: n }, () => new Array(n).fill(0)); for (let i = 0; i < r.length; i++) { @@ -462,8 +736,8 @@ export class MateSolver { run(false, maxIter); } else run(false, maxIter); const final = at(x); - const worst = evalMates(final); - return { placements: final, ok: worst < CONFLICT_TOL, residuals, iterations }; + const worst = evalMates(final), dw = driveWorst(final); + return { placements: final, ok: worst < CONFLICT_TOL && dw < CONFLICT_TOL, residuals, iterations, driveResidual: dw }; } /** @@ -471,7 +745,7 @@ export class MateSolver { * differences: each mate depends on the variables of its two components only. * Columns are divided by the variables' weights (`vw`, one per variable). */ - private jacobian(x: number[], sys: System, base: Map, mates: SolverMate[], drag: DragGoal | null, dragWeight: number, m: number, n: number, vw: number[], L: number): number[][] { + private jacobian(x: number[], sys: System, base: Map, mates: SolverMate[], drag: DragGoal | null, dragWeight: number, m: number, n: number, vw: number[], L: number, drives: Drive[] = []): number[][] { const J = Array.from({ length: m }, () => new Array(n).fill(0)); const h = 1e-6; const current = new Map(base); @@ -499,21 +773,39 @@ export class MateSolver { }; let row = 0; for (const mt of mates) { - const f = (pl: Map) => this.mateResidual(mt, pl, L) ?? []; + const f = (pl: Map) => this.mateResidual(mt, pl, L, base) ?? []; const len0 = f(current).length; - block(row, [mt.a.body, mt.b.body], f); + block(row, mateBodies(mt), f); row += len0; } + for (const d of drives) { block(row, [d.body], (pl) => driveResidual([d], pl, base, L)); row++; } if (drag) block(row, [drag.body], (pl) => dragResidual(drag, pl, L).map((v) => v * dragWeight)); return J; } - /** A mate's residuals with the components where `pl` puts them; null when it cannot be formed. */ - mateResidual(m: SolverMate, pl: Map, L: number): number[] | null { + /** + * A mate's residuals with the components where `pl` puts them; null when + * it cannot be formed. `ref`: where the components started (what coupling + * mates measure motion from). `ineq`: with the rows of limits (left out of + * the rank analysis: a limit takes no freedom away). + */ + mateResidual(m: SolverMate, pl: Map, L: number, ref: Map = pl, ineq = true): number[] | null { const pa = m.a.body ? pl.get(m.a.body) ?? null : null; const pb = m.b.body ? pl.get(m.b.body) ?? null : null; if ((m.a.body && !pa) || (m.b.body && !pb)) return null; - return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), { aligned: m.aligned, value: m.value, flip: m.flip, scale: L, rel: m.rel }, pa, pb); + const o = { aligned: m.aligned, value: m.value, flip: m.flip, scale: L, rel: m.rel }; + if (!isMechanical(m.type)) { + const ga = placeGeo(m.a.geo, pa), gb = placeGeo(m.b.geo, pb); + if (m.limit && (m.type === 'distance' || m.type === 'angle')) return limitEquations(m.type, ga, gb, o, m.limit, ineq); + return equations(m.type, ga, gb, o, pa, pb); + } + const now = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? IDENT : IDENT); + const start = (e: SolverEntity) => (e.body ? ref.get(e.body) ?? now(e) : IDENT); + for (const e of [m.a2, m.b2]) if (e?.body && !pl.get(e.body)) return null; + return mechanicalEquations({ + m, ga: placeGeo(m.a.geo, pa), gb: placeGeo(m.b.geo, pb), ga2: m.a2 ? placeGeo(m.a2.geo, m.a2.body ? now(m.a2) : null) : null, gb2: m.b2 ? placeGeo(m.b2.geo, m.b2.body ? now(m.b2) : null) : null, + pa: now(m.a), pb: now(m.b), ra: start(m.a), rb: start(m.b), now, start, L, ineq, + }); } /** @@ -557,8 +849,8 @@ export class MateSolver { return r; }; for (const m of active) { - const a = m.a.body, b = m.b.body; - if (a && b && parent.has(a) && parent.has(b)) parent.set(root(a), root(b)); + const ids = mateBodies(m).filter((id) => parent.has(id)); + for (let i = 1; i < ids.length; i++) parent.set(root(ids[i]), root(ids[0])); } const groups = new Map(); for (const b of floating) { @@ -567,7 +859,7 @@ export class MateSolver { groups.get(r)!.bodies.push(b); } for (const m of active) { - const id = [m.a.body, m.b.body].find((x): x is Id => !!x && parent.has(x)); + const id = mateBodies(m).find((x) => parent.has(x)); if (id) groups.get(root(id))!.mates.push(m); } let dof = 0; @@ -579,10 +871,10 @@ export class MateSolver { const index = new Map(g.bodies.map((b, i) => [b.id, i])); const J: number[][] = []; for (const m of g.mates) { - const base = this.mateResidual(m, pl, L); + const base = this.mateResidual(m, pl, L, pl, false); if (!base) continue; const block = base.map(() => new Array(n).fill(0)); - for (const id of new Set([m.a.body, m.b.body])) { + for (const id of mateBodies(m)) { if (!id || !index.has(id)) continue; const i = index.get(id)!; const center = g.bodies[i].center ?? [0, 0, 0]; @@ -590,10 +882,10 @@ export class MateSolver { const x = [0, 0, 0, 0, 0, 0]; x[j] = 1e-6; work.set(id, placementWith(pl.get(id)!, center, x, 0, L)); - const rp = this.mateResidual(m, work, L)!; + const rp = this.mateResidual(m, work, L, pl, false)!; x[j] = -1e-6; work.set(id, placementWith(pl.get(id)!, center, x, 0, L)); - const rm = this.mateResidual(m, work, L)!; + const rm = this.mateResidual(m, work, L, pl, false)!; for (let r = 0; r < base.length; r++) block[r][i * 6 + j] = (rp[r] - rm[r]) / 2e-6; } work.set(id, pl.get(id)!); @@ -620,8 +912,14 @@ export class MateSolver { private validity(m: SolverMate): string | null { if (m.a.body && m.a.body === m.b.body) return 'Both entities are on the same component'; - if (!m.a.body && !m.b.body) return 'A mate needs at least one component'; + if (!mateBodies(m).length) return 'A mate needs at least one component'; if (m.type === 'lock' && !m.rel) return 'The lock mate has no stored position'; + if (m.limit) { + if (!(m.limit.min <= m.limit.max)) return 'The smallest value must not be more than the largest'; + if (m.type === 'angle' && (m.limit.min < 0 || m.limit.max > 180)) return 'Angle limits are between 0° and 180°'; + if (m.type === 'hinge' && !m.rel) return 'The hinge has no stored position to measure its angle from'; + } + if (isMechanical(m.type)) return mechanicalProblem(m); return m.type === 'lock' ? null : mateProblem(m.type, m.a.geo, m.b.geo); } } @@ -638,11 +936,21 @@ export function matesMoving(body: Id, bodies: SolverBody[], mates: SolverMate[]) for (let grew = true; grew;) { grew = false; for (const m of mates) { - const a = m.a.body, b = m.b.body; - if (a && b && floating.has(a) && floating.has(b) && linked.has(a) !== linked.has(b)) { linked.add(a); linked.add(b); grew = true; } + const ids = mateBodies(m).filter((id) => floating.has(id)); + if (ids.length > 1 && ids.some((id) => linked.has(id)) && ids.some((id) => !linked.has(id))) { for (const id of ids) linked.add(id); grew = true; } } } - return mates.filter((m) => (m.a.body && linked.has(m.a.body)) || (m.b.body && linked.has(m.b.body))); + return mates.filter((m) => mateBodies(m).some((id) => linked.has(id))); +} + +/** How far each drive is from its motion: radians for turns, lengths over L for moves. */ +function driveResidual(drives: Drive[], pl: Map, ref: Map, L: number): number[] { + return drives.map((d) => { + const p = pl.get(d.body), p0 = ref.get(d.body); + if (!p || !p0) return 0; + if (d.kind === 'rotate') return turnAbout(p.q, p0.q, d.axis) - d.amount; + return (dot(sub(applyPlacement(p, d.local), applyPlacement(p0, d.local)), d.dir) - d.amount) / L; + }); } function dragResidual(goal: DragGoal, pl: Map, L: number): number[] { diff --git a/src/parametric/src/model/assembly.ts b/src/parametric/src/model/assembly.ts index b13edd53d9..dcfe9ddaf6 100644 --- a/src/parametric/src/model/assembly.ts +++ b/src/parametric/src/model/assembly.ts @@ -58,7 +58,18 @@ export interface AsmComponent { suppressed?: boolean; } -export type MateType = 'coincident' | 'parallel' | 'perpendicular' | 'distance' | 'angle' | 'concentric' | 'tangent' | 'lock'; +export type MateType = 'coincident' | 'parallel' | 'perpendicular' | 'distance' | 'angle' | 'concentric' | 'tangent' | 'lock' | MechanicalMateType; + +/** + * Mechanical mates. A hinge is concentric and coincident in one; width and + * slot take two entities on a side. Gear, rack and pinion and screw couple + * how far one component turns to how far another turns or slides: they + * relate motions, not positions, so they hold from wherever the components + * are when they are added (see the solver). + */ +export type MechanicalMateType = 'hinge' | 'gear' | 'rackPinion' | 'screw' | 'width' | 'slot'; +export const MECHANICAL_MATES: readonly MechanicalMateType[] = ['hinge', 'gear', 'rackPinion', 'screw', 'width', 'slot']; +export const isMechanical = (t: MateType): t is MechanicalMateType => (MECHANICAL_MATES as readonly string[]).includes(t); /** What a mate references: a face or edge of a component (by name, as features reference faces), an assembly plane, or a whole component (lock). */ export type MateRef = @@ -80,8 +91,74 @@ export interface Mate { /** Distance and tangent mates: the second entity lies on the other side of the first. */ flip?: boolean; suppressed?: boolean; - /** Lock mates: where b sits in a's frame. */ + /** Lock mates: where b sits in a's frame. Hinges with angle limits: where b sat in a's frame at 0°. */ rel?: Placement; + /** + * The second pair of entities: a hinge's coincident faces (a2 on a's + * component, b2 on b's), a width mate's groove (a, a2) and tab (b, b2) + * faces, a slot's two end faces (a, a2; b is the pin). + */ + a2?: MateRef; + b2?: MateRef; + /** Hinge: alignment of the coincident faces (aligned is that of the axes). */ + aligned2?: boolean; + /** + * Distance and angle mates: the entities move freely between these values + * (value is where they were set up). Hinges: the turn from where the hinge + * was added (rel), in degrees. + */ + limit?: { min: Param; max: Param }; + /** Gear: b's pitch diameter (value is a's), or b's part of the ratio. */ + value2?: Param; + /** + * Gear: 'ratio' when the values are a ratio rather than pitch diameters. + * Rack and pinion: 'revolution' when value is the rack's travel per turn + * rather than the pinion's pitch diameter. + */ + by?: 'ratio' | 'revolution'; + /** Gear, rack and pinion: the other way round. Screw: a left-hand thread. */ + reverse?: boolean; +} + +/** What a motor does over time: a constant speed, a back and forth (sine), or a ramp between two values. */ +export type MotionProfile = 'constant' | 'oscillate' | 'ramp'; + +/** + * A motor of a motion study. Rotary motors turn a component about an axis, + * linear motors move it along a direction (both taken from a face or edge; + * the component is that of the entity); a mate driver changes the value of + * a distance or angle mate. Values are in mm, degrees and seconds. + */ +export interface MotionMotor { + id: Id; + name: string; + kind: 'rotary' | 'linear' | 'mate'; + /** Rotary and linear: the axis or direction, on the component it moves. */ + ref?: MateRef; + /** Mate driver: the distance or angle mate. */ + mate?: Id; + profile: MotionProfile; + /** Constant: speed (mm/s, deg/s, or rpm when `rpm`). */ + speed?: Param; + rpm?: boolean; + /** Oscillate: amplitude (mm or degrees) and frequency (Hz). */ + amplitude?: Param; + frequency?: Param; + /** Ramp (mate drivers): the value at the start and at the end of the study. */ + from?: Param; + to?: Param; + reverse?: boolean; + suppressed?: boolean; +} + +export interface MotionStudy { + id: Id; + name: string; + /** Seconds. */ + duration: number; + /** Frames computed per second. */ + fps: number; + motors: MotionMotor[]; } export interface ExplodeStep { @@ -103,11 +180,14 @@ export interface AssemblyDocument extends Omit = { coincident: 'Coincident', parallel: 'Parallel', perpendicular: 'Perpendicular', distance: 'Distance', angle: 'Angle', concentric: 'Concentric', tangent: 'Tangent', lock: 'Lock', + hinge: 'Hinge', gear: 'Gear', rackPinion: 'Rack Pinion', screw: 'Screw', width: 'Width', slot: 'Slot', }; /** Distinct component colours, picked in turn for each new part. */ @@ -156,6 +236,8 @@ const BASE_PLANES = ['front', 'top', 'right']; const MATE_TYPES = Object.keys(MATE_LABELS); /** The most components (and parts), mates and explode steps an assembly file may have. */ export const MAX_COMPONENTS = 2000, MAX_MATES = 10000, MAX_EXPLODE_STEPS = 1000; +/** The most motion studies, motors per study, and frames a study may compute. */ +export const MAX_STUDIES = 100, MAX_MOTORS = 50, MAX_FRAMES = 20000; function validPlacement(v: unknown): v is Placement { return isObj(v) && isVec(v.p) && Array.isArray(v.q) && v.q.length === 4 && v.q.every(isNum) && Math.hypot(...(v.q as number[])) > 1e-9; @@ -178,6 +260,35 @@ function validMateRef(v: unknown, comps: Set): boolean { return true; } +/** The new fields of a mate (limits, second entities, mechanical settings), each only where its type has it. */ +function validMateExtras(m: Record, comps: Set): boolean { + const t = m.type as MateType; + const has = (k: string) => m[k] !== undefined; + const isBool = (k: string) => !has(k) || typeof m[k] === 'boolean'; + if (has('a2') && (!['hinge', 'width', 'slot'].includes(t) || !validMateRef(m.a2, comps))) return false; + if (has('b2') && (!['hinge', 'width'].includes(t) || !validMateRef(m.b2, comps))) return false; + if (!isBool('aligned2') || !isBool('reverse')) return false; + if (has('value2') && (t !== 'gear' || !isParam(m.value2))) return false; + if (has('limit') && (!['distance', 'angle', 'hinge'].includes(t) || !isObj(m.limit) || !isParam(m.limit.min) || !isParam(m.limit.max))) return false; + if (has('by') && !((t === 'gear' && m.by === 'ratio') || (t === 'rackPinion' && m.by === 'revolution'))) return false; + if (!isMechanical(t)) return !has('aligned2') && !has('reverse'); + // What each mechanical mate needs; its entities are faces, edges or planes (not whole components). + const needs: Record = { hinge: ['a2', 'b2'], width: ['a2', 'b2'], slot: ['a2'], gear: ['value', 'value2'], rackPinion: ['value'], screw: ['value'] }; + if (needs[t].some((k) => !has(k))) return false; + return [m.a, m.b, m.a2, m.b2].every((r) => r === undefined || (isObj(r) && ('plane' in r || 'face' in r || 'edge' in r))); +} + +function validMotor(v: unknown, comps: Set, mates: Set): boolean { + if (!isObj(v) || !isStr(v.id) || typeof v.name !== 'string' || !['rotary', 'linear', 'mate'].includes(v.kind as string) || !['constant', 'oscillate', 'ramp'].includes(v.profile as string)) return false; + for (const k of ['speed', 'amplitude', 'frequency', 'from', 'to']) if (v[k] !== undefined && !isParam(v[k])) return false; + for (const k of ['rpm', 'reverse', 'suppressed']) if (v[k] !== undefined && typeof v[k] !== 'boolean') return false; + const need = v.profile === 'constant' ? ['speed'] : v.profile === 'oscillate' ? ['amplitude', 'frequency'] : ['from', 'to']; + if (need.some((k) => v[k] === undefined)) return false; + if (v.kind === 'mate') return isStr(v.mate) && mates.has(v.mate) && v.ref === undefined && v.rpm === undefined; + // Rotary and linear motors move the component of a face or edge, at a constant speed or back and forth. + return v.mate === undefined && v.profile !== 'ramp' && (v.rpm === undefined || v.kind === 'rotary') && isObj(v.ref) && isStr(v.ref.comp) && ('face' in v.ref || 'edge' in v.ref) && validMateRef(v.ref, comps); +} + function validSource(v: unknown): v is PartSource | null { return v === null || (isObj(v) && ((v.type === 'cloud' && isStr(v.path)) || (v.type === 'local' && isStr(v.id)))); } @@ -227,13 +338,28 @@ export function validateAssembly(raw: unknown): AssemblyDocument { if (!isObj(m) || !isStr(m.id) || ids.has(m.id) || !MATE_TYPES.includes(m.type as string) || !validMateRef(m.a, compIds) || !validMateRef(m.b, compIds)) throw damaged('invalid mate'); if (m.value !== undefined && !isParam(m.value)) throw damaged('invalid mate value'); if (m.rel !== undefined && !validPlacement(m.rel)) throw damaged('invalid mate'); + if (!validMateExtras(m, compIds)) throw damaged('invalid mate'); ids.add(m.id); } + const mateIds = new Set(mates.map((m) => (m as Mate).id)); const explode = Array.isArray(d.explode) ? d.explode : []; for (const s of explode) { if (!isObj(s) || !isStr(s.id) || ids.has(s.id) || !Array.isArray(s.comps) || !s.comps.every((c) => compIds.has(c as string)) || !isVec(s.dir) || !isParam(s.distance)) throw damaged('invalid explode step'); ids.add(s.id); } + // Motion studies (files from before them have none). + if (d.studies !== undefined && !Array.isArray(d.studies)) throw damaged('invalid motion study'); + const studies = (d.studies ?? []) as unknown[]; + if (studies.length > MAX_STUDIES) throw new Error(`This assembly has ${studies.length} motion studies, more than Parametric can open (at most ${MAX_STUDIES}).`); + for (const s of studies) { + if (!isObj(s) || !isStr(s.id) || ids.has(s.id) || typeof s.name !== 'string' || !isNum(s.duration) || s.duration <= 0 || s.duration > 3600 || !isNum(s.fps) || s.fps < 1 || s.fps > 240 + || s.duration * s.fps > MAX_FRAMES || !Array.isArray(s.motors) || s.motors.length > MAX_MOTORS) throw damaged('invalid motion study'); + ids.add(s.id); + for (const mo of s.motors) { + if (!validMotor(mo, compIds, mateIds) || ids.has((mo as MotionMotor).id)) throw damaged('invalid motor'); + ids.add((mo as MotionMotor).id); + } + } if (d.drawing != null && !validDrawing(d.drawing)) throw damaged('invalid drawing'); const units = typeof d.units === 'string' && Object.hasOwn(UNIT_SYSTEMS, d.units) ? d.units : 'MMGS'; const base = newAssembly(typeof d.name === 'string' && d.name ? d.name : undefined, units); @@ -268,6 +394,7 @@ export function validateAssembly(raw: unknown): AssemblyDocument { })).map((m) => JSON.parse(JSON.stringify(m)) as Mate), explode: explode.map((s) => ({ id: s.id, name: typeof s.name === 'string' && s.name ? s.name : s.id, comps: [...new Set(s.comps as Id[])], dir: [...s.dir] as Vec3, distance: s.distance })), exploded: d.exploded === true && explode.length > 0, + ...(studies.length ? { studies: (studies as MotionStudy[]).map((s) => ({ id: s.id, name: s.name || s.id, duration: s.duration, fps: s.fps, motors: s.motors.map(motorCopy) })) } : {}), ...(d.drawing != null ? { drawing: d.drawing } : {}), created: isNum(d.created) && Math.abs(d.created) < 8.64e15 ? d.created : base.created, modified: isNum(d.modified) && Math.abs(d.modified) < 8.64e15 ? d.modified : base.modified, @@ -302,9 +429,18 @@ export function parseAnyDocument(text: string): PartDocument | AssemblyDocument } } -/** Allocates a new id in an assembly (components, parts, mates, explode steps). */ +/** A motor with only the fields it may have (a file's other fields are dropped). */ +function motorCopy(m: MotionMotor): MotionMotor { + const out: MotionMotor = { id: m.id, name: m.name || m.id, kind: m.kind, profile: m.profile }; + for (const k of ['ref', 'mate', 'speed', 'amplitude', 'frequency', 'from', 'to'] as const) if (m[k] !== undefined) (out as unknown as Record)[k] = structuredClone(m[k]); + for (const k of ['rpm', 'reverse', 'suppressed'] as const) if (m[k] === true) out[k] = true; + return out; +} + +/** Allocates a new id in an assembly (components, parts, mates, explode steps, motion studies and motors). */ export function nextAsmId(doc: AssemblyDocument, prefix: string): Id { - const used = new Set([...doc.parts.map((p) => p.id), ...doc.components.map((c) => c.id), ...doc.mates.map((m) => m.id), ...doc.explode.map((s) => s.id)]); + const studies = doc.studies ?? []; + const used = new Set([...doc.parts.map((p) => p.id), ...doc.components.map((c) => c.id), ...doc.mates.map((m) => m.id), ...doc.explode.map((s) => s.id), ...studies.flatMap((s) => [s.id, ...s.motors.map((m) => m.id)])]); let id: string; do id = `${prefix}${doc.nextId++}`; while (used.has(id)); return id; @@ -331,10 +467,13 @@ export function nextPartColor(doc: AssemblyDocument): string { return PART_COLORS.find((c) => !used.has(c)) ?? PART_COLORS[doc.parts.length % PART_COLORS.length]; } +/** The entities a mate references (its second pair too). */ +export const mateRefs = (m: Mate): MateRef[] => [m.a, m.b, ...(m.a2 ? [m.a2] : []), ...(m.b2 ? [m.b2] : [])]; + /** The components a mate references. */ export function mateComps(m: Mate): Id[] { const out: Id[] = []; - for (const r of [m.a, m.b]) if ('comp' in r) out.push(r.comp); + for (const r of mateRefs(m)) if ('comp' in r && !out.includes(r.comp)) out.push(r.comp); return out; } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts new file mode 100644 index 0000000000..8c526a4497 --- /dev/null +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -0,0 +1,355 @@ +import { describe, expect, it } from 'vitest'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, mateBodies, mateMeasure, matesMoving, placeGeo, relativePlacement, turnAbout } from '../src/assembly/solver'; +import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, mateSeries, pointPath, profileOf, resultsCsv, turnPath, vectorDerivatives } from '../src/assembly/motion'; +import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; +import type { MateType, Placement } from '../src/model/assembly'; + +const Z: Vec3 = [0, 0, 1]; +const plane = (o: Vec3, n: Vec3): Geo => ({ kind: 'plane', o, n }); +const axis = (p: Vec3, d: Vec3 = Z, r = 2): Geo => ({ kind: 'axis', p, d, r, surface: 'cylinder' }); +const body = (id: string, fixed: boolean, p: Vec3 = [0, 0, 0], q: Quat = [0, 0, 0, 1]): SolverBody => ({ id, fixed, placement: { p, q }, center: [0, 0, 0] }); +let n = 0; +const mate = (type: MateType, a: [string | null, Geo], b: [string | null, Geo], extra: Partial = {}): SolverMate => ({ + id: `m${++n}`, type, a: { body: a[0], geo: a[1] }, b: { body: b[0], geo: b[1] }, aligned: true, value: 0, flip: false, ...extra, +}); +/** A hinge between a's axis at pa and b's at pb (both along z), their z = 0 faces touching. */ +const hinge = (a: string, pa: Vec3, b: string, pb: Vec3, extra: Partial = {}) => mate('hinge', [a, axis(pa)], [b, axis(pb)], { + a2: { body: a, geo: plane([0, 0, 0], Z) }, b2: { body: b, geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: false, ...extra, +}); +const deg = (r: number) => (r * 180) / Math.PI; +const angleZ = (q: Quat) => Math.atan2(qRotate(q, [1, 0, 0])[1], qRotate(q, [1, 0, 0])[0]); +const rotary = (bodyId: string, entity: Geo, speed: number, extra: Partial = {}): MotorInput => ({ + id: 'motor', name: 'RotaryMotor1', kind: 'rotary', body: bodyId, entity: { body: bodyId, geo: entity }, at: profileOf('rotary', { profile: 'constant', speed }, 1), ...extra, +}); + +describe('limit mates', () => { + const TOP = plane([0, 5, 0], [0, 1, 0]), BOTTOM = plane([0, -5, 0], [0, -1, 0]); + const blockOnSlide = (limit: { min: number; max: number }, y = 40) => { + const bodies = [body('base', true), body('blk', false, [3, y, 1])]; + // Kept upright and sliding along y only (two faces), with the distance between the limits. + const mates = [ + mate('coincident', ['base', plane([5, 0, 0], [1, 0, 0])], ['blk', plane([5, 0, 0], [1, 0, 0])]), + mate('coincident', ['base', plane([0, 0, 5], Z)], ['blk', plane([0, 0, 5], Z)]), + mate('distance', ['base', TOP], ['blk', BOTTOM], { aligned: false, limit, value: 10 }), + ]; + return new MateSolver(bodies, mates); + }; + const gap = (pl: Map) => (placeGeo(BOTTOM, pl.get('blk')!) as { o: Vec3 }).o[1] - 5; + + it('a distance limit lets the component move between its values, and stops a drag at them', () => { + const s = blockOnSlide({ min: 5, max: 20 }); + const r = s.analyze(); + // Moved in to the largest distance, still free to slide: one degree of freedom. + expect(gap(r.placements)).toBeCloseTo(20, 4); + expect(r.status).toBe('under'); + expect(r.dof).toBe(1); + expect(r.defined.size).toBe(0); + // Inside the range it stays where it is put. + const inside = blockOnSlide({ min: 5, max: 20 }, 22).solve(); + expect(gap(inside.placements)).toBeCloseTo(12, 9); + // Dragged far down, it stops at the smallest distance. + const down = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [0, -100, 0] } }, s.mates, r.placements); + expect(down.ok).toBe(true); + expect(gap(down.placements)).toBeCloseTo(5, 4); + const up = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [0, 300, 0] } }, s.mates, r.placements); + expect(gap(up.placements)).toBeCloseTo(20, 4); + }); + + it('a limit that cannot be met with the other mates conflicts; one upside down is a mate error', () => { + const base = blockOnSlide({ min: 5, max: 20 }); + const over = new MateSolver(base.bodies, [...base.mates, mate('distance', ['base', TOP], ['blk', BOTTOM], { aligned: false, value: 30 })]).analyze(); + expect(over.status).toBe('over'); + expect(over.conflicts.size).toBe(1); + const bad = blockOnSlide({ min: 20, max: 5 }).analyze(); + expect(bad.status).toBe('error'); + expect([...bad.invalid.values()][0]).toMatch(/smallest/); + }); + + it('an angle limit stops a lid turning on its hinge', () => { + const lidTop = plane([20, 1, 0], [0, 1, 0]); + const mates = [ + mate('concentric', ['base', axis([0, 0, 0])], ['lid', axis([0, 0, 0])]), + mate('coincident', ['base', plane([0, 0, 0], Z)], ['lid', plane([0, 0, 0], Z)]), + mate('angle', ['base', plane([0, 0, 0], [0, 1, 0])], ['lid', lidTop], { limit: { min: 0, max: 60 }, value: 0 }), + ]; + const s = new MateSolver([body('base', true), body('lid', false)], mates); + const r = s.analyze(); + expect(r.dof).toBe(1); + // Dragging the lid's end straight up: it turns until 60°, then stops. + let pl = r.placements; + for (let k = 1; k <= 8; k++) pl = s.solve({ drag: { kind: 'move', body: 'lid', local: [40, 0, 0], target: [0, 10 * k, 0] } }, s.mates, pl).placements; + expect(deg(angleZ(pl.get('lid')!.q))).toBeCloseTo(60, 3); + }); +}); + +describe('mechanical mates', () => { + it('a hinge is concentric and coincident in one, with angle limits from where it was added', () => { + const lid = body('lid', false, [5, 3, 7], qAxisAngle(normalize([1, 2, 0]), 0.3)); + const free = new MateSolver([body('base', true), lid], [hinge('base', [0, 0, 0], 'lid', [0, 0, 0])]).analyze(); + expect(free.dof).toBe(1); + const p = free.placements.get('lid')!; + expect(len(applyPlacement(p, [0, 0, 0]))).toBeLessThan(1e-6); + expect(dot(qRotate(p.q, Z), Z)).toBeCloseTo(1, 8); + // With limits of -30° to 45° measured from the lid where it is now. + const start: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const limited = hinge('base', [0, 0, 0], 'lid', [0, 0, 0], { rel: relativePlacement(start, start), limit: { min: -30, max: 45 } }); + const s = new MateSolver([body('base', true), body('lid', false)], [limited]); + expect(s.analyze().dof).toBe(1); + let pl = new Map([['base', start], ['lid', start]]); + for (let k = 1; k <= 12; k++) pl = s.solve({ drag: { kind: 'rotate', body: 'lid', q: qAxisAngle(Z, (k * 10 * Math.PI) / 180) } }, s.mates, pl).placements; + expect(deg(angleZ(pl.get('lid')!.q))).toBeCloseTo(45, 3); + expect(mateMeasure(limited, pl)!.value).toBeCloseTo(45, 3); + for (let k = 1; k <= 12; k++) pl = s.solve({ drag: { kind: 'rotate', body: 'lid', q: qAxisAngle(Z, ((45 - k * 10) * Math.PI) / 180) } }, s.mates, pl).placements; + expect(deg(angleZ(pl.get('lid')!.q))).toBeCloseTo(-30, 3); + // Faces on the wrong components are refused. + const crossed = { ...limited, a2: limited.b2, b2: limited.a2 }; + expect(new MateSolver([body('base', true), body('lid', false)], [crossed]).analyze().invalid.get(crossed.id)).toMatch(/component of the round entity/); + }); + + /** Two gears on hinges, 30 mm apart: A (pitch Ø20) at the origin, B (Ø40) beside it. */ + const gears = (extra: Partial = {}) => { + const bodies = [body('g', true), body('A', false), body('B', false, [30, 0, 0])]; + const mates = [hinge('g', [0, 0, 0], 'A', [0, 0, 0]), hinge('g', [30, 0, 0], 'B', [0, 0, 0]), mate('gear', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0], [0, 0, -1])], { value: 20, value2: 40, ...extra })]; + return new MateSolver(bodies, mates); + }; + + it('a gear mate couples two turns by the ratio, the other way round, past ±180°', () => { + const s = gears(); + const r = s.analyze(); + expect(r.status).toBe('under'); + expect(r.dof).toBe(1); + // Turning A by 30° steps to 390° (dragged round): B turns half as far the other way, also past 180°. + let pl = r.placements; + let a = 0, b = 0; + for (let k = 1; k <= 13; k++) { + const next = s.solve({ drag: { kind: 'rotate', body: 'A', q: qAxisAngle(Z, (k * 30 * Math.PI) / 180) } }, s.mates, pl); + expect(next.ok).toBe(true); + a += turnAbout(next.placements.get('A')!.q, pl.get('A')!.q, Z); + b += turnAbout(next.placements.get('B')!.q, pl.get('B')!.q, Z); + pl = next.placements; + } + expect(deg(a)).toBeCloseTo(390, 2); + expect(deg(b)).toBeCloseTo(-195, 2); + // B's orientation is that turn, not one wrapped to ±180°. + expect(dot(qRotate(pl.get('B')!.q, [1, 0, 0]), [Math.cos(b), Math.sin(b), 0])).toBeCloseTo(1, 6); + // Reversed (an internal gear): the same way round. + const rev = gears({ reverse: true }); + const turned = rev.solve({ drag: { kind: 'rotate', body: 'A', q: qAxisAngle(Z, 0.5) } }, rev.mates); + expect(turnAbout(turned.placements.get('B')!.q, [0, 0, 0, 1], Z)).toBeCloseTo(0.25, 5); + }); + + it('dragging one gear by a tooth turns the other', () => { + const s = gears(); + let pl = s.analyze().placements; + // Grab A's rim at (10, 0) and pull it up: A turns, and B with it. + for (let k = 1; k <= 6; k++) pl = s.solve({ drag: { kind: 'move', body: 'A', local: [10, 0, 0], target: [10, 3 * k, 0] } }, s.mates, pl).placements; + const ta = angleZ(pl.get('A')!.q), tb = angleZ(pl.get('B')!.q); + expect(ta).toBeGreaterThan(0.5); + expect(tb).toBeCloseTo(-ta / 2, 5); + }); + + it('a gear pair keeps its ratio over a full turn of a motor', () => { + const s = gears(); + const res = computeMotion({ bodies: s.bodies, mates: s.mates, motors: [rotary('A', axis([0, 0, 0]), 360)], duration: 1.5, fps: 40, scale: 100 }); + expect(res.stop).toBeNull(); + expect(res.frames).toHaveLength(61); + const a = degreesAbout(turnPath(res, 'A'), Z), b = degreesAbout(turnPath(res, 'B'), Z); + expect(a[60]).toBeCloseTo(540, 4); + for (let i = 0; i < a.length; i++) expect(b[i]).toBeCloseTo(-a[i] / 2, 4); + // Angular velocity from the frames: 360°/s and −180°/s. + const w = derivatives(res.times, b).d1; + expect(w[30]).toBeCloseTo(-180, 3); + }); + + /** A pinion (Ø20) on a hinge at the origin, its rack below it sliding along x. */ + const rackAndPinion = (extra: Partial = {}) => { + const bodies = [body('g', true), body('P', false), body('R', false, [0, -10, 0])]; + const mates = [ + hinge('g', [0, 0, 0], 'P', [0, 0, 0]), + mate('coincident', ['g', plane([0, -10, 0], [0, 1, 0])], ['R', plane([0, 0, 0], [0, 1, 0])]), + mate('coincident', ['g', plane([0, 0, 0], Z)], ['R', plane([0, 0, 0], Z)]), + mate('rackPinion', ['P', axis([0, 0, 0])], ['R', { kind: 'line', p: [0, 0, 0], d: [1, 0, 0] }], { value: 20, ...extra }), + ]; + return new MateSolver(bodies, mates); + }; + + it('rack and pinion: turning the pinion moves the rack, and dragging the rack turns the pinion', () => { + const s = rackAndPinion(); + expect(s.analyze().dof).toBe(1); + const res = computeMotion({ bodies: s.bodies, mates: s.mates, motors: [rotary('P', axis([0, 0, 0]), 90)], duration: 1, fps: 20, scale: 100 }); + expect(res.stop).toBeNull(); + // A quarter turn moves the rack by a quarter of the pitch circle, the way the pinion's bottom moves. + expect(res.frames[20].get('R')!.p[0]).toBeCloseTo((Math.PI / 2) * 10, 5); + // Dragged 10π mm along: the pinion turns half a turn (past 90°, in steps as a pointer moves). + let pl = s.analyze().placements; + for (let k = 1; k <= 10; k++) pl = s.solve({ drag: { kind: 'move', body: 'R', local: [0, 0, 0], target: [k * Math.PI, -10, 0] } }, s.mates, pl).placements; + expect(pl.get('R')!.p[0]).toBeCloseTo(10 * Math.PI, 3); + expect(Math.abs(deg(angleZ(pl.get('P')!.q)))).toBeCloseTo(180, 2); + // By travel per turn, and reversed. + const per = rackAndPinion({ by: 'revolution', value: 50, reverse: true }); + const r2 = computeMotion({ bodies: per.bodies, mates: per.mates, motors: [rotary('P', axis([0, 0, 0]), 360)], duration: 1, fps: 30, scale: 100 }); + expect(r2.frames[30].get('R')!.p[0]).toBeCloseTo(-50, 4); + }); + + it('a screw turns a nut along its axis by the pitch per turn, right or left hand', () => { + const run = (reverse: boolean) => { + const mates = [mate('screw', ['g', axis([0, 0, 0])], ['N', axis([0, 0, 0])], { value: 2, reverse })]; + const s = new MateSolver([body('g', true), body('N', false, [0, 0, 5])], mates); + expect(s.analyze().dof).toBe(1); + return computeMotion({ bodies: s.bodies, mates, motors: [rotary('N', axis([0, 0, 0]), 360)], duration: 3, fps: 24, scale: 50 }); + }; + const right = run(false); + expect(right.stop).toBeNull(); + expect(right.frames[72].get('N')!.p[2]).toBeCloseTo(11, 4); + expect(run(true).frames[72].get('N')!.p[2]).toBeCloseTo(-1, 4); + }); + + it('a width mate centres a tab in a groove', () => { + const groove: [Geo, Geo] = [plane([-10, 0, 0], [1, 0, 0]), plane([10, 0, 0], [-1, 0, 0])]; + const tab: [Geo, Geo] = [plane([-3, 0, 0], [-1, 0, 0]), plane([3, 0, 0], [1, 0, 0])]; + const m = mate('width', ['g', groove[0]], ['T', tab[0]], { a2: { body: 'g', geo: groove[1] }, b2: { body: 'T', geo: tab[1] } }); + const s = new MateSolver([body('g', true), body('T', false, [6, 2, 1], qAxisAngle([0, 1, 0], 0.2))], [m]); + const r = s.analyze(); + expect(r.dof).toBe(3); + const t = r.placements.get('T')!; + expect(t.p[0]).toBeCloseTo(0, 6); + expect(Math.abs(qRotate(t.q, [1, 0, 0])[0])).toBeCloseTo(1, 8); + const skew = { ...m, a2: { body: 'g', geo: plane([10, 0, 0], normalize([-1, 1, 0])) } }; + expect(new MateSolver(s.bodies, [skew]).analyze().invalid.get(skew.id)).toMatch(/parallel/); + }); + + it('a slot mate keeps a pin on the slot, between its ends', () => { + const m = mate('slot', ['g', axis([0, 0, 0], Z, 3)], ['pin', axis([0, 0, 0], Z, 3)], { a2: { body: 'g', geo: axis([30, 0, 0], Z, 3) } }); + const s = new MateSolver([body('g', true), body('pin', false, [10, 5, 3], qAxisAngle([1, 0, 0], 0.2))], [m]); + const r = s.analyze(); + expect(r.dof).toBe(3); + const p = r.placements.get('pin')!; + expect(p.p[1]).toBeCloseTo(0, 6); + expect(dot(qRotate(p.q, Z), Z)).toBeCloseTo(1, 8); + expect(mateMeasure(m, r.placements)!.value).toBeCloseTo(p.p[0], 6); + // Dragged past the end, it stops there. + let pl = r.placements; + for (let k = 1; k <= 5; k++) pl = s.solve({ drag: { kind: 'move', body: 'pin', local: [0, 0, 0], target: [10 + 10 * k, 0, p.p[2]] } }, s.mates, pl).placements; + expect(pl.get('pin')!.p[0]).toBeCloseTo(30, 4); + const same = { ...m, a2: { body: 'g', geo: axis([0, 0, 9], Z, 3) } }; + expect(new MateSolver(s.bodies, [same]).analyze().invalid.get(same.id)).toMatch(/same axis/); + }); + + it('mates of more than two components link them for dragging', () => { + const m = mate('width', ['a', plane([0, 0, 0], [1, 0, 0])], ['b', plane([0, 0, 0], [1, 0, 0])], { a2: { body: 'c', geo: plane([1, 0, 0], [1, 0, 0]) }, b2: { body: 'b', geo: plane([1, 0, 0], [1, 0, 0]) } }); + expect(mateBodies(m)).toEqual(['a', 'b', 'c']); + const bodies = [body('a', false), body('b', false), body('c', false), body('d', false)]; + expect(matesMoving('c', bodies, [m]).map((x) => x.id)).toEqual([m.id]); + }); +}); + +describe('motion studies', () => { + const r = 20, l = 60; + /** A crank (r), rod (l) and slider on x, the crank at θ0 (degrees). */ + const crankSlider = (theta0: number, extraMates: SolverMate[] = []) => { + const th = (theta0 * Math.PI) / 180; + const pin: Vec3 = [r * Math.cos(th), r * Math.sin(th), 0]; + const phi = Math.asin((-r * Math.sin(th)) / l); + const x = pin[0] + l * Math.cos(phi); + const bodies = [body('g', true), body('crank', false, [0, 0, 0], qAxisAngle(Z, th)), body('rod', false, pin, qAxisAngle(Z, phi)), body('slider', false, [x, 0, 0])]; + const mates = [ + hinge('g', [0, 0, 0], 'crank', [0, 0, 0]), + hinge('crank', [r, 0, 0], 'rod', [0, 0, 0]), + hinge('rod', [l, 0, 0], 'slider', [0, 0, 0]), + mate('coincident', ['g', plane([0, 0, 0], [0, 1, 0])], ['slider', plane([0, 0, 0], [0, 1, 0])]), + ...extraMates, + ]; + return { bodies, mates }; + }; + const slide = (theta: number) => { + const t = (theta * Math.PI) / 180; + return r * Math.cos(t) + Math.sqrt(l * l - r * r * Math.sin(t) ** 2); + }; + + it('a crank-slider has one degree of freedom and its slider follows the closed-form position', () => { + const cs = crankSlider(30); + expect(new MateSolver(cs.bodies, cs.mates).analyze().dof).toBe(1); + const res = computeMotion({ ...cs, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 4, fps: 25, scale: 200 }); + expect(res.stop).toBeNull(); + expect(res.times).toHaveLength(101); + res.frames.forEach((f, i) => expect(f.get('slider')!.p[0]).toBeCloseTo(slide(30 + 90 * res.times[i]), 4)); + // Velocity and acceleration of the slider from the frames, against the derivatives of the formula. + const path = pointPath(res, 'slider', [0, 0, 0]); + const { d1, d2 } = vectorDerivatives(res.times, path); + const h = 1e-4, x = (t: number) => slide(30 + 90 * t); + const v = (t: number) => (x(t + h) - x(t - h)) / (2 * h), a = (t: number) => (x(t + h) - 2 * x(t) + x(t - h)) / (h * h); + expect(d1[50][0]).toBeCloseTo(v(2), 0); + expect(d2[50][0] / a(2)).toBeCloseTo(1, 1); + // A crank angle reading past a full turn: 30° + 360°. + expect(degreesAbout(turnPath(res, 'crank'), Z)[100]).toBeCloseTo(360, 3); + }); + + it('stops at a limit and says which', () => { + // The slider kept beyond 45 mm from the crank's axis: the crank turning down toward 180° pushes it there. + const limit = mate('distance', ['g', plane([0, 0, 0], [1, 0, 0])], ['slider', plane([0, 0, 0], [1, 0, 0])], { limit: { min: 45, max: 100 }, value: 60 }); + const cs = crankSlider(30, [limit]); + const res = computeMotion({ ...cs, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 4, fps: 25, scale: 200, names: new Map([[limit.id, 'LimitDistance1']]) }); + expect(res.stop?.kind).toBe('limit'); + expect(res.stop?.mate).toBe(limit.id); + expect(res.stop?.message).toMatch(/LimitDistance1 reached its limit/); + const last = res.frames[res.frames.length - 1].get('slider')!.p[0]; + expect(last).toBeGreaterThan(45 - 1e-6); + expect(last).toBeLessThan(47); + }); + + it('reports a mechanism that locks up', () => { + // The crank also held at its angle by an angle mate: the motor cannot turn it. + const held = mate('angle', ['g', plane([0, 0, 0], [0, 1, 0])], ['crank', plane([0, 0, 0], [0, 1, 0])], { value: 30 }); + const cs = crankSlider(30, [held]); + const res = computeMotion({ ...cs, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 1, fps: 10, scale: 200 }); + expect(res.stop?.kind).toBe('locked'); + expect(res.stop?.time).toBeCloseTo(0.1, 6); + expect(res.frames).toHaveLength(1); + }); + + it('drives a distance mate by a ramp, and the crank follows', () => { + const drive = mate('distance', ['g', plane([0, 0, 0], [1, 0, 0])], ['slider', plane([0, 0, 0], [1, 0, 0])], { value: slide(30) }); + const cs = crankSlider(30, [drive]); + expect(new MateSolver(cs.bodies, cs.mates).analyze().dof).toBe(0); + const motor: MotorInput = { id: 'mo', name: 'MateDriver1', kind: 'mate', mate: drive.id, at: profileOf('mate', { profile: 'ramp', from: slide(30), to: 50 }, 2) }; + const run = new MotionRun({ ...cs, motors: [motor], duration: 2, fps: 10, scale: 200 }); + let steps = 0; + while (run.step()) steps++; + expect(steps).toBe(19); + expect(run.done).toBe(true); + const res = run.result; + expect(res.stop).toBeNull(); + res.frames.forEach((f, i) => expect(f.get('slider')!.p[0]).toBeCloseTo(slide(30) + ((50 - slide(30)) * res.times[i]) / 2, 5)); + // The crank's angle where the slider is at 50 mm: r cos θ + √(l² − r² sin² θ) = 50. + const th = angleZ(res.frames[20].get('crank')!.q); + expect(slide(deg(th))).toBeCloseTo(50, 4); + // The mate's measure as a result: its distance. + expect(mateSeries(res, drive)!.values[20]).toBeCloseTo(50, 5); + }); + + it('profiles: constant speed (deg/s or rpm), oscillation, ramp, reversed', () => { + expect(profileOf('rotary', { profile: 'constant', speed: 90 }, 1)(2)).toBeCloseTo(Math.PI, 12); + expect(profileOf('rotary', { profile: 'constant', speed: 60, rpm: true }, 1)(0.5)).toBeCloseTo(Math.PI, 9); + expect(profileOf('linear', { profile: 'oscillate', amplitude: 10, frequency: 0.25, reverse: true }, 1)(1)).toBeCloseTo(-10, 12); + expect(profileOf('mate', { profile: 'constant', speed: 5 }, 1, 20)(2)).toBe(30); + expect(profileOf('mate', { profile: 'ramp', from: 10, to: 30 }, 4)(1)).toBe(15); + expect(profileOf('mate', { profile: 'ramp', from: 10, to: 30 }, 4)(9)).toBe(30); + }); + + it('a linear motor moves a component along a direction', () => { + const mates = [mate('coincident', ['g', plane([0, 0, 0], [0, 1, 0])], ['s', plane([0, 0, 0], [0, 1, 0])]), mate('coincident', ['g', plane([0, 0, 0], Z)], ['s', plane([0, 0, 0], Z)])]; + const motor: MotorInput = { id: 'mo', name: 'LinearMotor1', kind: 'linear', body: 's', entity: { body: 's', geo: { kind: 'line', p: [0, 0, 0], d: [1, 0, 0] } }, at: profileOf('linear', { profile: 'oscillate', amplitude: 10, frequency: 0.5 }, 2) }; + const res = computeMotion({ bodies: [body('g', true), body('s', false)], mates, motors: [motor], duration: 2, fps: 20, scale: 100 }); + res.frames.forEach((f, i) => expect(f.get('s')!.p[0]).toBeCloseTo(10 * Math.sin(Math.PI * res.times[i]), 6)); + }); + + it('differentiates samples and writes CSV', () => { + const t = [0, 0.1, 0.2, 0.3, 0.4]; + const { d1, d2 } = derivatives(t, t.map((x) => x * x)); + expect(d1[2]).toBeCloseTo(0.4, 12); + expect(d2[2]).toBeCloseTo(2, 9); + expect(d2[0]).toBeCloseTo(2, 9); + expect(resultsCsv([{ name: 'Time (s)', values: [0, 0.5] }, { name: 'X, mm', values: [1, 2.25] }])).toBe('Time (s),"X, mm"\n0,1\n0.5,2.25'); + expect(len(sub(pointPath({ times: [0], frames: [new Map([['a', { p: [1, 2, 3], q: [0, 0, 0, 1] }]])], stop: null, duration: 1 }, 'a', [1, 0, 0])[0], [2, 2, 3]))).toBe(0); + }); +}); diff --git a/src/parametric/tests/assembly-model.test.ts b/src/parametric/tests/assembly-model.test.ts index 5d1c48356a..0ddea582b3 100644 --- a/src/parametric/tests/assembly-model.test.ts +++ b/src/parametric/tests/assembly-model.test.ts @@ -164,3 +164,72 @@ describe('combined model', () => { expect(placementMatrix({ p: [1, 2, 3], q: [0, 0, 0, 1] })).toEqual([1, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 3]); }); }); + +describe('mechanical mates and motion studies in files', () => { + const face = (name: string) => ({ name, sig: { type: 'plane', c: [0, 0, 0] as [number, number, number], area: 10, n: [0, 0, 1] as [number, number, number] } }); + const cyl = (name: string) => ({ name, sig: { type: 'cylinder', c: [0, 0, 0] as [number, number, number], area: 10 } }); + function kinematic(): AssemblyDocument { + const doc = sample(); + doc.mates.push( + { id: 'm20', name: 'Hinge1', type: 'hinge', a: { comp: 'c3', face: cyl('h') }, b: { comp: 'c4', face: cyl('k') }, a2: { comp: 'c3', face: face('f1') }, b2: { comp: 'c4', face: face('f2') }, aligned: true, aligned2: false, limit: { min: -30, max: '=Gap*20' }, rel: { p: [0, 0, 0], q: [0, 0, 0, 1] } }, + { id: 'm21', name: 'Gear1', type: 'gear', a: { comp: 'c4', face: cyl('k') }, b: { comp: 'c5', face: cyl('k') }, aligned: true, value: 20, value2: 40, reverse: true }, + { id: 'm22', name: 'Gear2', type: 'gear', a: { comp: 'c4', face: cyl('k') }, b: { comp: 'c5', face: cyl('k') }, aligned: true, value: 1, value2: 3, by: 'ratio' }, + { id: 'm23', name: 'Rack Pinion1', type: 'rackPinion', a: { comp: 'c4', face: cyl('k') }, b: { comp: 'c5', edge: { name: 'e', sig: { type: 'line', m: [0, 0, 0], len: 5 } } }, aligned: true, value: 50, by: 'revolution' }, + { id: 'm24', name: 'Screw1', type: 'screw', a: { comp: 'c3', face: cyl('h') }, b: { comp: 'c4', face: cyl('k') }, aligned: true, value: 1.5, reverse: true }, + { id: 'm25', name: 'Width1', type: 'width', a: { comp: 'c3', face: face('g1') }, a2: { comp: 'c3', face: face('g2') }, b: { comp: 'c4', face: face('t1') }, b2: { comp: 'c4', face: face('t2') }, aligned: true }, + { id: 'm26', name: 'Slot1', type: 'slot', a: { comp: 'c3', face: cyl('s1') }, a2: { comp: 'c3', face: cyl('s2') }, b: { comp: 'c4', face: cyl('k') }, aligned: true }, + { id: 'm27', name: 'LimitDistance1', type: 'distance', a: { plane: 'top' }, b: { comp: 'c4', face: face('t1') }, aligned: true, value: 10, limit: { min: 5, max: 20 } }, + ); + doc.studies = [{ + id: 's30', name: 'Motion Study1', duration: 2, fps: 30, motors: [ + { id: 'o31', name: 'RotaryMotor1', kind: 'rotary', ref: { comp: 'c4', face: cyl('k') }, profile: 'constant', speed: 60, rpm: true }, + { id: 'o32', name: 'LinearMotor1', kind: 'linear', ref: { comp: 'c5', edge: { name: 'e', sig: { type: 'line', m: [0, 0, 0], len: 5 } } }, profile: 'oscillate', amplitude: 5, frequency: '=Gap', reverse: true }, + { id: 'o33', name: 'MateDriver1', kind: 'mate', mate: 'm27', profile: 'ramp', from: 5, to: 20, suppressed: true }, + ], + }]; + return doc; + } + + it('round-trips mechanical mates, limits and motion studies, and allocates ids past them', () => { + const doc = kinematic(); + const back = parseAssembly(serializeDocument(doc as never)); + expect(back).toEqual({ ...doc, nextId: 34 }); + expect(nextAsmId(back, 'm')).toBe('m34'); + // Files from before studies have none, and say nothing about them. + expect('studies' in parseAssembly(serializeDocument(sample() as never))).toBe(false); + }); + + it('refuses mechanical mates and studies with bad or misplaced fields', () => { + const text = serializeDocument(kinematic() as never); + const edit = (patch: (d: Record) => void) => { const raw = JSON.parse(text); patch(raw); return () => parseAssembly(JSON.stringify(raw)); }; + const mate = (id: string) => (d: Record) => d.mates.find((m: { id: string }) => m.id === id); + expect(edit((d) => { delete mate('m20')(d).b2; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).a2 = { comp: 'c99', face: face('x') }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).a2 = { comp: 'c3' }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).limit = { min: 1 }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).aligned2 = 'yes'; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m21')(d).value2; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).reverse = 1; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).by = 'revolution'; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m24')(d).value; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].a2 = d.mates[0].a; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].limit = { min: 0, max: 1 }; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].reverse = true; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].value2 = 3; })).toThrow(/invalid mate/); + expect(edit((d) => { d.studies = {}; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].fps = 0; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].duration = 3000; d.studies[0].fps = 100; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].id = 'c3'; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].motors[0].ref = { comp: 'c99', face: face('x') }; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[0].profile = 'ramp'; d.studies[0].motors[0].from = 0; d.studies[0].motors[0].to = 1; })).toThrow(/invalid motor/); + expect(edit((d) => { delete d.studies[0].motors[0].speed; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[1].rpm = true; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[2].mate = 'm99'; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[2].ref = d.studies[0].motors[0].ref; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[1].id = d.studies[0].motors[0].id; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[0].kind = 'jet'; })).toThrow(/invalid motor/); + // Unknown fields of a motor are dropped. + const back = parseAssembly(JSON.stringify({ ...JSON.parse(text), studies: [{ ...JSON.parse(text).studies[0], motors: [{ ...JSON.parse(text).studies[0].motors[0], extra: 1 }] }] })); + expect('extra' in back.studies![0].motors[0]).toBe(false); + }); +}); From e5a636f1a4d07fc9b135c21dca7f04538a2bde40 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:55:50 -0700 Subject: [PATCH 003/116] Parametric: limit and mechanical mates in the Mate panel, and motion studies The Mate panel limits distance and angle mates and makes hinge, gear, rack and pinion, screw, width and slot mates, each with its own selection boxes and values. Motion studies have rotary, linear and mate-driving motors, are calculated in slices with progress and cancel, play back with loop and scrub, and plot a component's or mate's motion with velocity and acceleration, with CSV download. Studies are listed in the design tree and saved with the assembly; editing the assembly puts their results out of date. --- src/parametric/src/app/assembly/index.ts | 39 +- src/parametric/src/app/assembly/mode.ts | 157 ++++- .../src/app/assembly/motion-panel.ts | 557 ++++++++++++++++++ src/parametric/src/app/assembly/panels.ts | 346 +++++++++-- src/parametric/src/app/assembly/tree.ts | 18 +- src/parametric/src/styles/app.css | 13 + .../tests/e2e/assembly-kinematics.spec.ts | 358 +++++++++++ 7 files changed, 1410 insertions(+), 78 deletions(-) create mode 100644 src/parametric/src/app/assembly/motion-panel.ts create mode 100644 src/parametric/tests/e2e/assembly-kinematics.spec.ts diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts index 0c9a4d3895..cbcf4797ab 100644 --- a/src/parametric/src/app/assembly/index.ts +++ b/src/parametric/src/app/assembly/index.ts @@ -2,7 +2,7 @@ // ribbon tab and commands, switching the interface between part and // assembly documents, and the context menus of components and mates. -import { Boxes, Expand, ListOrdered, Magnet, Move3d, PackagePlus, RefreshCw, SquaresIntersect, SquareArrowOutUpRight } from 'lucide'; +import { Bolt, Boxes, Clapperboard, Cog, Expand, ListOrdered, Magnet, Move3d, PackagePlus, RefreshCw, SquaresIntersect, SquareArrowOutUpRight } from 'lucide'; import { type AssemblyDocument, MATE_LABELS, asAssembly, mateComps } from '../../model/assembly'; import type { Id } from '../../model/types'; import { type Location, sameLocation } from '../../platform/files'; @@ -16,6 +16,7 @@ import type { RibbonTab } from '../shell'; import { AssemblyMode } from './mode'; import { ASSEMBLY_SOURCE, EXPLODED_SOURCE, assemblySource } from '../drawing-sources'; import { ExplodePanel, InterferencePanel, MatePanel, MovePanel, assemblyMassDialog, bomDialog, insertComponent, pickPart, updateParts } from './panels'; +import { MotionStudyPanel } from './motion-panel'; addIcons({ assembly: Boxes as unknown as IconNode, @@ -37,6 +38,15 @@ addIcons({ 'mate:distance': 'smartDimension', 'mate:angle': [['path', { d: 'M4 20h16M4 20L15 5' }], ['path', { d: 'M11 20a7 7 0 0 0-2.4-5.3' }]], 'mate:lock': 'lock', + 'mate:hinge': [['path', { d: 'M4 6h7v12H4z', class: 'a' }], ['path', { d: 'M13 6h7v12h-7z' }], ['circle', { cx: 12, cy: 12, r: 2.2 }]], + 'mate:gear': Cog as unknown as IconNode, + 'mate:rackPinion': [['circle', { cx: 12, cy: 9, r: 5, class: 'a' }], ['path', { d: 'M3 18h18M5 18v-2.5M9 18v-2.5M13 18v-2.5M17 18v-2.5M21 18v-2.5' }]], + 'mate:screw': Bolt as unknown as IconNode, + 'mate:width': [['path', { d: 'M4 4v16M20 4v16' }], ['rect', { x: 9, y: 7, width: 6, height: 10, rx: 0.5, class: 'a' }], ['path', { d: 'M5.5 12h2M16.5 12h2' }]], + 'mate:slot': [['path', { d: 'M7 8h10a4 4 0 0 1 0 8H7a4 4 0 0 1 0-8z' }], ['circle', { cx: 9, cy: 12, r: 2, class: 'a' }]], + motionStudy: Clapperboard as unknown as IconNode, + play: [['path', { d: 'M7 4l13 8-13 8z', class: 'a' }]], + pause: [['path', { d: 'M7 4h3v16H7zM14 4h3v16h-3z', class: 'a' }]], }); /** The tabs an assembly shows; part tabs (sketch, features...) are hidden. */ @@ -47,7 +57,7 @@ export const ASSEMBLY_TAB: RibbonTab = { groups: [ [{ cmd: 'insertComponent' }, { cmd: 'mate' }], [{ stack: [{ cmd: 'moveComponent' }, { cmd: 'rotateComponent' }] }, { stack: [{ cmd: 'explodedView' }, { cmd: 'toggleExplode' }] }], - [{ cmd: 'interference' }, { cmd: 'billOfMaterials' }], + [{ cmd: 'interference' }, { cmd: 'billOfMaterials' }, { cmd: 'motionStudy' }], [{ stack: [{ cmd: 'updateParts' }, { cmd: 'openPart' }] }], ], }; @@ -112,7 +122,7 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { }, }, { - id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly', description: 'Position components relative to each other with mates.', + id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly limit hinge gear rack pinion screw width slot mechanical', description: 'Position components relative to each other with mates.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MatePanel(mode()!)), }, @@ -124,6 +134,10 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { enabled: () => !!doc()?.explode.length, checked: () => !!doc()?.exploded, run: () => { const m = mode(); if (m) m.commit(m.doc.exploded ? 'Collapse' : 'Explode', (d) => { d.exploded = !d.exploded; }, false); }, }, + { + id: 'motionStudy', label: 'Motion Study', icon: 'motionStudy', keywords: 'animation motor kinematics mechanism simulate plot velocity', description: 'Drive the mechanism with motors over time, play it back and plot positions, velocities and accelerations.', + enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MotionStudyPanel(mode()!)), + }, { id: 'interference', label: 'Interference Detection', icon: 'interference', keywords: 'clash overlap collision check', description: 'Find components that overlap, and by how much.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new InterferencePanel(mode()!)) }, { id: 'billOfMaterials', label: 'Bill of Materials', icon: 'bom', keywords: 'bom parts list quantity', description: 'The parts of the assembly with their quantities and materials.', enabled: asm, run: () => { const m = mode(); if (m) void bomDialog(m); } }, { @@ -205,7 +219,9 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { const mt = m.doc.mates.find((x) => x.id === id); if (mt) { openPanelWhenBuilt(() => new MatePanel(m, mt)); return; } const st = m.doc.explode.find((x) => x.id === id); - if (st) openPanelWhenBuilt(() => new ExplodePanel(m, st)); + if (st) { openPanelWhenBuilt(() => new ExplodePanel(m, st)); return; } + const study = m.study(id); + if (study) openPanelWhenBuilt(() => new MotionStudyPanel(m, study)); }; if (!app.assembly) { partTree = app.tree; partFlyout = app.flyout; } app.assembly = m; @@ -277,15 +293,28 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { const mate = id ? d.mates.find((x) => x.id === id) : undefined; if (mate) { const ids = app.tree.targets(mate.id).filter((x) => d.mates.some((y) => y.id === x)); + // Gears and racks turn the other way round; mates of directions flip their alignment. + const reverses = mate.type === 'gear' || mate.type === 'rackPinion'; + const aligns = !['perpendicular', 'lock', 'tangent', 'width', 'slot'].includes(mate.type) && !reverses; return [ { label: 'Edit Mate', icon: 'edit', run: () => m.edit(mate.id) }, { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(mate.id) }, - ...(mate.type !== 'perpendicular' && mate.type !== 'lock' && mate.type !== 'tangent' ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.commit('Flip alignment', (x) => { for (const y of x.mates) if (y.id === mate.id) y.aligned = !y.aligned; }) } as MenuItem] : []), + ...(aligns ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.commit('Flip alignment', (x) => { for (const y of x.mates) if (y.id === mate.id) y.aligned = !y.aligned; }) } as MenuItem] : []), + ...(reverses ? [{ label: 'Reverse Direction', icon: 'reset', run: () => m.commit('Reverse direction', (x) => { for (const y of x.mates) if (y.id === mate.id) y.reverse = y.reverse ? undefined : true; }) } as MenuItem] : []), { label: mate.suppressed ? 'Unsuppress' : 'Suppress', icon: mate.suppressed ? 'eye' : 'eyeOff', run: () => m.commit(mate.suppressed ? 'Unsuppress' : 'Suppress', (x) => { for (const y of x.mates) if (ids.includes(y.id)) y.suppressed = mate.suppressed ? undefined : true; }) }, sep, { label: 'Delete', icon: 'trash', shortcut: 'Delete', run: () => void m.deleteItems(ids) }, ]; } + const study = id ? m.study(id) : undefined; + if (study) { + return [ + { label: 'Edit Motion Study', icon: 'edit', run: () => m.edit(study.id) }, + { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(study.id) }, + sep, + { label: 'Delete', icon: 'trash', shortcut: 'Delete', run: () => void m.deleteItems([study.id]) }, + ]; + } const step = id ? d.explode.find((x) => x.id === id) : undefined; if (step) { return [ diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index 26b16a9e5f..39dbff62a6 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -13,10 +13,11 @@ import { BASE_FRAMES, BASE_PLANE_NAMES } from '../../model/planes'; import type { Id, PartDocument } from '../../model/types'; import { UNIT_SYSTEMS } from '../../model/units'; import { - type AsmComponent, type AsmPart, type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type Placement, MATE_LABELS, PartCache, asAssembly, mateComps, + type AsmComponent, type AsmPart, type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MotionStudy, type Placement, MATE_LABELS, PartCache, asAssembly, mateComps, mateRefs, } from '../../model/assembly'; import { type ComposedModel, type PartGeometry, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; import { type AnalysisResult, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, matesMoving } from '../../assembly/solver'; +import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, profileOf } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; import { confirmDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; @@ -111,7 +112,7 @@ export class AssemblyMode { if (app.kernel.generation !== this.generation) { this.geoms.clear(); this.generation = app.kernel.generation; } const used = doc.parts.filter((p) => doc.components.some((c) => c.part === p.id && !c.suppressed)); // Only the drawing changed (a view dragged on the sheet): the components are shown as they are. - const shownKey = JSON.stringify([app.kernel.generation, app.settings.quality, { ...doc, drawing: undefined, modified: undefined, blobs: undefined }]); + const shownKey = JSON.stringify([app.kernel.generation, app.settings.quality, { ...doc, drawing: undefined, modified: undefined, blobs: undefined, studies: undefined }]); if (this.model && shownKey === this.shownKey && used.every((p) => this.geoms.has(this.key(p)))) return; this.shownKey = ''; const builds: AsmPartBuild[] = []; @@ -206,10 +207,15 @@ export class AssemblyMode { return { body: c.id, geo: { kind: 'body' } }; } - /** Mate value in mm or degrees. */ - mateValue(m: Mate): number { - if (m.value === undefined) return 0; - return this.app.store.evalParam(m.value, m.type === 'angle' ? 'angle' : 'length'); + /** Mate value in mm or degrees (a gear's teeth when its ratio is by teeth). */ + mateValue(m: Mate, v = m.value): number { + if (v === undefined) return 0; + return this.app.store.evalParam(v, m.type === 'angle' || m.type === 'hinge' ? 'angle' : m.by === 'ratio' ? 'count' : 'length'); + } + + /** What the value of a mate is called (for messages). */ + private valueName(m: Mate): string { + return m.type === 'angle' || m.type === 'hinge' ? 'Angle' : m.type === 'gear' ? (m.by === 'ratio' ? 'Teeth' : 'Pitch diameter') : m.type === 'screw' ? 'Pitch' : m.type === 'rackPinion' ? (m.by === 'revolution' ? 'Travel per turn' : 'Pitch diameter') : 'Distance'; } /** @@ -227,16 +233,25 @@ export class AssemblyMode { const inactive = new Set(); for (const m of doc.mates) { if (m.suppressed || mateComps(m).some((id) => doc.components.find((c) => c.id === id)?.suppressed)) { inactive.add(m.id); continue; } - const a = this.entity(m.a, doc), b = this.entity(m.b, doc); - if (typeof a === 'string' || typeof b === 'string') { problems.set(m.id, typeof a === 'string' ? a : b as string); continue; } - let value = 0; + const ents = mateRefs(m).map((r) => this.entity(r, doc)); + const bad = ents.find((e): e is string => typeof e === 'string'); + if (bad) { problems.set(m.id, bad); continue; } + const [a, b] = ents as SolverEntity[]; + const a2 = m.a2 ? (ents[2] as SolverEntity) : undefined, b2 = m.b2 ? (ents[ents.length - 1] as SolverEntity) : undefined; + let value = 0, value2: number | undefined, limit: { min: number; max: number } | undefined; try { value = this.mateValue(m); + if (m.value2 !== undefined) value2 = this.mateValue(m, m.value2); + if (m.limit) limit = { min: this.mateValue(m, m.limit.min), max: this.mateValue(m, m.limit.max) }; } catch (e) { - problems.set(m.id, `${m.type === 'angle' ? 'Angle' : 'Distance'}: ${(e as Error).message}`); + problems.set(m.id, `${this.valueName(m)}: ${(e as Error).message}`); continue; } - mates.push({ id: m.id, type: m.type, a, b, aligned: m.aligned, value, flip: !!m.flip, rel: m.rel }); + mates.push({ + id: m.id, type: m.type, a, b, aligned: m.aligned, value, flip: !!m.flip, rel: m.rel, + ...(a2 ? { a2 } : {}), ...(b2 ? { b2 } : {}), ...(m.aligned2 !== undefined ? { aligned2: m.aligned2 } : {}), + ...(value2 !== undefined ? { value2 } : {}), ...(limit ? { limit } : {}), ...(m.by ? { by: m.by } : {}), ...(m.reverse ? { reverse: true } : {}), + }); } return { bodies, mates, problems, inactive }; } @@ -249,7 +264,7 @@ export class AssemblyMode { while (grew) { grew = false; for (const m of mates) { - const ids = [m.a.body, m.b.body]; + const ids = [m.a, m.b, m.a2, m.b2].flatMap((e) => (e ? [e.body] : [])); const touches = ids.some((id) => (id ? out.has(id) : ground)); if (!touches) continue; for (const id of ids) if (id && !out.has(id)) { out.add(id); grew = true; } @@ -458,7 +473,7 @@ export class AssemblyMode { const out: SelItem[] = []; for (const it of this.app.selection.ofKind('feature')) { const m = this.doc.mates.find((x) => x.id === it.id); - if (m) for (const r of [m.a, m.b]) { const x = this.itemOf(r); if (x) out.push(x); } + if (m) for (const r of mateRefs(m)) { const x = this.itemOf(r); if (x) out.push(x); } const s = this.doc.explode.find((x) => x.id === it.id); if (s) for (const id of s.comps) out.push({ kind: 'feature', id }); } @@ -487,6 +502,8 @@ export class AssemblyMode { if (m) return `${MATE_LABELS[m.type]} mate: ${this.mateLabel(m)}`; const s = this.doc.explode.find((x) => x.id === it.id); if (s) return s.name; + const st = this.study(it.id); + if (st) return `Motion study ${st.name}: ${st.duration} s, ${st.motors.length} ${st.motors.length === 1 ? 'motor' : 'motors'}`; } return null; } @@ -513,22 +530,26 @@ export class AssemblyMode { itemName(id: Id): string | null { const d = this.doc; - return d.components.find((x) => x.id === id)?.name ?? d.mates.find((x) => x.id === id)?.name ?? d.explode.find((x) => x.id === id)?.name ?? null; + return d.components.find((x) => x.id === id)?.name ?? d.mates.find((x) => x.id === id)?.name ?? d.explode.find((x) => x.id === id)?.name ?? this.study(id)?.name ?? null; } nameRefusal(id: Id, name: string): string | null { const low = name.toLowerCase(); const d = this.doc; - const other = [...d.components, ...d.mates, ...d.explode].find((x) => x.id !== id && x.name.toLowerCase() === low); + const other = [...d.components, ...d.mates, ...d.explode, ...d.studies ?? []].find((x) => x.id !== id && x.name.toLowerCase() === low); return other ? `"${name}" is already the name of another item. Choose another name.` : null; } rename(id: Id, name: string) { this.commit('Rename', (d) => { - for (const x of [...d.components, ...d.mates, ...d.explode]) if (x.id === id) x.name = name; + for (const x of [...d.components, ...d.mates, ...d.explode, ...d.studies ?? []]) if (x.id === id) x.name = name; }, false); } + study(id: Id): MotionStudy | undefined { + return this.doc.studies?.find((s) => s.id === id); + } + /** Double click or Enter on a tree row. */ edit(id: Id) { if (this.component(id)) this.app.selection.set([{ kind: 'feature', id }]); @@ -541,16 +562,22 @@ export class AssemblyMode { const comps = doc.components.filter((c) => ids.includes(c.id)); const mates = doc.mates.filter((m) => ids.includes(m.id) || mateComps(m).some((c) => comps.some((x) => x.id === c))); const steps = doc.explode.filter((s) => ids.includes(s.id)); - const names = [...comps, ...doc.mates.filter((m) => ids.includes(m.id)), ...steps].map((x) => x.name); + const studies = (doc.studies ?? []).filter((s) => ids.includes(s.id)); + const names = [...comps, ...doc.mates.filter((m) => ids.includes(m.id)), ...steps, ...studies].map((x) => x.name); if (!names.length) return; const dependent = mates.filter((m) => !ids.includes(m.id)); const msg = dependent.length ? `Delete ${names.join(', ')}? These mates reference ${comps.length === 1 ? 'it' : 'them'} and are deleted too: ${dependent.map((m) => m.name).join(', ')}.` : `Delete ${names.join(', ')}?`; if (!(await confirmDialog('Delete', msg, 'Delete', true, signal)) || signal.aborted) return; if (this.app.panel) await this.app.closePanel(false); - const gone = new Set([...comps.map((c) => c.id), ...mates.map((m) => m.id), ...steps.map((s) => s.id)]); + const gone = new Set([...comps.map((c) => c.id), ...mates.map((m) => m.id), ...steps.map((s) => s.id), ...studies.map((s) => s.id)]); this.commit('Delete', (d) => { d.components = d.components.filter((c) => !gone.has(c.id)); d.mates = d.mates.filter((m) => !gone.has(m.id)); + // Motors of deleted components and mates go with them (a file keeps none that point nowhere). + if (d.studies) { + d.studies = d.studies.filter((s) => !gone.has(s.id)).map((s) => ({ ...s, motors: s.motors.filter((mo) => !(mo.mate && gone.has(mo.mate)) && !(mo.ref && 'comp' in mo.ref && gone.has(mo.ref.comp))) })); + if (!d.studies.length) delete d.studies; + } d.explode = d.explode.filter((s) => !gone.has(s.id)).map((s) => ({ ...s, comps: s.comps.filter((c) => !gone.has(c)) })).filter((s) => s.comps.length); if (!d.explode.length) d.exploded = false; d.parts = d.parts.filter((p) => d.components.some((c) => c.part === p.id)); @@ -593,12 +620,106 @@ export class AssemblyMode { }); } + // ---------- motion studies ---------- + + /** Computed motion studies, with what they were computed from (see studyKey). */ + private motions = new Map(); + + /** What a study's results depend on: the study and everything the mates are solved from. */ + studyKey(st: MotionStudy): string { + return JSON.stringify([this.solveKey(this.doc), { ...st, id: undefined, name: undefined }]); + } + + /** A study's results, and whether they are those of the assembly (and study) as they are now. */ + motionOf(id: Id, st = this.study(id)): { result: MotionResult; current: boolean } | null { + const r = this.motions.get(id); + return r && st ? { result: r.result, current: r.key === this.studyKey(st) } : null; + } + + /** A study added to the document keeps the results computed while it was set up. */ + keepMotion(from: Id, to: Id) { + const r = this.motions.get(from); + if (r) this.motions.set(to, r); + } + + /** The solver input of a study, or why it cannot run. Components start where the mates put them now. */ + motionSetup(st: MotionStudy): MotionSetup | string { + const motors = st.motors.filter((m) => !m.suppressed); + if (!motors.length) return 'Add a motor to drive the mechanism.'; + const { bodies, mates } = this.solverInput(); + const a = this.analysis; + const held = mates.filter((m) => !a?.conflicts.has(m.id) && !a?.invalid.has(m.id)); + const start = bodies.map((b) => ({ ...b, placement: this.solved.get(b.id) ?? b.placement })); + const names = new Map([...this.doc.mates.map((m) => [m.id, m.name] as [Id, string]), ...motors.map((m) => [m.id, m.name] as [Id, string])]); + const store = this.app.store; + const inputs: MotorInput[] = []; + for (const mo of motors) { + // Frequencies and rpm are plain numbers: evaluated as angles are (no length unit is applied). + const values = (kind: 'length' | 'angle') => ({ + profile: mo.profile, rpm: mo.rpm, reverse: mo.reverse, + ...Object.fromEntries((['speed', 'amplitude', 'from', 'to'] as const).filter((k) => mo[k] !== undefined).map((k) => [k, store.evalParam(mo[k]!, mo.rpm && k === 'speed' ? 'angle' : kind)])), + ...(mo.frequency !== undefined ? { frequency: store.evalParam(mo.frequency, 'angle') } : {}), + }); + try { + if (mo.kind === 'mate') { + const mt = this.doc.mates.find((x) => x.id === mo.mate); + const sm = held.find((x) => x.id === mo.mate); + if (!mt || (mt.type !== 'distance' && mt.type !== 'angle') || mt.limit) return `${mo.name}: the mate it drives must be a distance or angle mate without limits.`; + if (!sm) return `${mo.name}: ${mt.name} does not hold (suppressed, or with an error). Fix it to drive it.`; + inputs.push({ id: mo.id, name: mo.name, kind: 'mate', mate: mt.id, at: profileOf('mate', values(mt.type === 'angle' ? 'angle' : 'length'), st.duration, sm.value) }); + continue; + } + const e = mo.ref ? this.entity(mo.ref) : 'It has no axis or direction'; + if (typeof e === 'string') return `${mo.name}: ${e}.`; + const comp = e.body ? this.component(e.body) : undefined; + if (!comp || comp.suppressed) return `${mo.name}: its component is suppressed.`; + if (comp.fixed) return `${mo.name}: ${comp.name} is fixed. Float it, or pick a face or edge of the component to move.`; + if (e.geo.kind !== 'axis' && e.geo.kind !== 'line' && e.geo.kind !== 'plane') return `${mo.name}: pick a round face or edge, a straight edge or a planar face for its ${mo.kind === 'rotary' ? 'axis' : 'direction'}.`; + inputs.push({ id: mo.id, name: mo.name, kind: mo.kind, body: comp.id, entity: e, at: profileOf(mo.kind, values(mo.kind === 'rotary' ? 'angle' : 'length'), st.duration) }); + } catch (err) { + return `${mo.name}: ${(err as Error).message}`; + } + } + return { bodies: start, mates: held, motors: inputs, duration: st.duration, fps: st.fps, scale: this.scale(), names }; + } + + /** + * Computes a study in slices of a few milliseconds, yielding to the + * interface between them (it stays responsive, and the progress shows). + * Null when cancelled; a message when it cannot run. + */ + async computeMotion(st: MotionStudy, id: Id, onProgress: (f: number) => void, cancelled: () => boolean): Promise { + const setup = this.motionSetup(st); + if (typeof setup === 'string') return setup; + const key = this.studyKey(st); + const run = new MotionRun(setup); + onProgress(0); + while (!run.done) { + const t0 = performance.now(); + while (!run.done && performance.now() - t0 < 12) run.step(); + onProgress(run.progress); + await yieldToUI(); + if (cancelled() || this.app.assembly !== this) return null; + } + this.motions.set(id, { key, result: run.result }); + return run.result; + } + dispose() { this.preview = null; this.explodePreview = null; } } +/** Lets the browser handle input and paint before going on (a message, not a timer: timers are slowed in background tabs). */ +function yieldToUI(): Promise { + return new Promise((resolve) => { + const ch = new MessageChannel(); + ch.port1.onmessage = () => { ch.port1.close(); resolve(); }; + ch.port2.postMessage(0); + }); +} + /** * Dragging components in the graphics area: the grabbed point follows the * cursor (Alt, or Rotate Component: the component turns), within what the diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts new file mode 100644 index 0000000000..614f5b1da2 --- /dev/null +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -0,0 +1,557 @@ +// The Motion Study panel: a study's length and frame rate, its motors, +// computing its frames (in slices, cancelable, with progress), playing them +// back (play, pause, loop, scrub) and plotting results (a point of a +// component, its turn, or what a mate measures, with velocities and +// accelerations) that can be downloaded as CSV. + +import { type MotionResult, derivatives, mateSeries, pointPath, resultsCsv, turnPath, vectorDerivatives } from '../../assembly/motion'; +import { type SolverMate, relativePlacement } from '../../assembly/solver'; +import { type Vec3, len } from '../../math/vec'; +import { type MotionMotor, type MotionProfile, type MotionStudy, MATE_LABELS, nextAsmId } from '../../model/assembly'; +import type { Id, Param } from '../../model/types'; +import { UNIT_SYSTEMS } from '../../model/units'; +import { download, safeName } from '../../platform/files'; +import { h } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import { type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm'; +import type { SelItem } from '../selection'; +import type { AssemblyMode } from './mode'; + +type Quantity = 0 | 1 | 2; +type Axis = 'mag' | 'x' | 'y' | 'z'; + +const KIND_LABELS: Record = { rotary: 'Rotary motor', linear: 'Linear motor', mate: 'Mate driver' }; +const KIND_NAMES: Record = { rotary: 'RotaryMotor', linear: 'LinearMotor', mate: 'MateDriver' }; + +/** A new study's settings: 5 s at 30 frames a second. */ +const newStudy = (): MotionStudy => ({ id: '', name: '', duration: 5, fps: 30, motors: [] }); + +export class MotionStudyPanel extends PropertyPanel { + title = 'Motion Study'; + icon = 'motionStudy'; + private study: MotionStudy; + private readonly original: string; + /** Results are kept under the study's id ('' while a new study is set up). */ + private readonly key: Id; + /** A motor being added or changed, and where it goes in the list (-1: at the end). */ + private motor: MotionMotor | null = null; + private motorIndex = -1; + private computing = false; + private progress = 0; + private runs = 0; + private error: string | null = null; + private t = 0; + private playing = false; + private loop = false; + private speed = 1; + private raf = 0; + private last = 0; + private disposed = false; + private target = ''; + private point: { comp: Id; local: Vec3; label: string } | null = null; + private quantity: Quantity = 0; + private angular = false; + private axis: Axis = 'mag'; + private slider: HTMLInputElement | null = null; + private clock: HTMLElement | null = null; + private plotCursor: SVGLineElement | null = null; + private playBtn: HTMLButtonElement | null = null; + private bar: HTMLProgressElement | null = null; + + constructor(private mode: AssemblyMode, private existing: MotionStudy | null = null) { + super(); + this.study = structuredClone(existing ?? newStudy()); + this.original = JSON.stringify(this.study); + this.key = existing?.id ?? ''; + if (existing) { this.editingId = existing.id; this.title = `Motion Study: ${existing.name}`; } + this.helpText = 'Add motors that turn or move components (or drive a distance or angle mate), then Calculate. Play the motion back and plot how a component or mate moves. The study starts from where the components are now.'; + mode.app.selection.clear(); + } + + private get app(): App { + return this.mode.app; + } + + /** The results of this study as it is set up now (null when not computed, or out of date). */ + private result(): MotionResult | null { + const r = this.mode.motionOf(this.key, this.study); + return r?.current ? r.result : null; + } + + // ---------- panel ---------- + + render(): HTMLElement[] { + if (this.motor) return this.renderMotor(); + const res = this.result(); + const out = [this.studySection(), this.motorsSection(), this.calcSection(res)]; + if (res && res.frames.length > 1) out.push(this.playSection(res), this.resultsSection(res)); + return out; + } + + private studySection(): HTMLElement { + const num = (label: string, value: number, min: number, max: number, step: string, set: (v: number) => void) => { + const input = h('input', { class: 'input', type: 'number', min: String(min), max: String(max), step, value: String(value), 'aria-label': label }) as HTMLInputElement; + input.addEventListener('change', () => { + const v = Number(input.value); + const ok = Number.isFinite(v) && v >= min && v <= max; + input.setAttribute('aria-invalid', String(!ok)); + input.title = ok ? '' : `Between ${min} and ${max}`; + if (ok) { set(v); this.stale(); } + }); + return h('div', {}, h('div', { class: 'field-label', 'aria-hidden': 'true' }, label), input); + }; + return section('Study', [ + num('Duration (s)', this.study.duration, 0.1, 3600, '0.1', (v) => { this.study.duration = v; }), + num('Frames per second', this.study.fps, 1, 240, '1', (v) => { this.study.fps = Math.round(v); }), + ], { icon: 'motionStudy' }); + } + + private motorsSection(): HTMLElement { + const list = h('div', { class: 'file-list', role: 'list', 'aria-label': 'Motors' }); + this.study.motors.forEach((m, i) => { + const edit = h('button', { class: 'file-item', type: 'button' }, + h('span', { 'aria-hidden': 'true' }, icon(m.kind === 'mate' ? 'smartDimension' : m.kind === 'rotary' ? 'rotateComponent' : 'moveComponent', 16)), + h('span', { class: 'txt' }, h('span', { class: 'n' }, `${m.name}${m.suppressed ? ' (suppressed)' : ''}`), h('span', { class: 'meta' }, this.describeMotor(m)))); + edit.addEventListener('click', () => { this.motor = structuredClone(m); this.motorIndex = i; this.app.refreshPanel(); }); + const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': `Delete ${m.name}` }, icon('trash', 14)); + del.addEventListener('click', () => { this.study.motors.splice(i, 1); this.stale(); this.app.refreshPanel(); }); + list.append(h('div', { class: 'file-row kin-motor', role: 'listitem' }, edit, del)); + }); + const add = h('button', { class: 'btn small', type: 'button' }, icon('add', 14), 'Add Motor'); + add.addEventListener('click', () => { + this.motor = { id: '', name: '', kind: 'rotary', profile: 'constant', speed: 60 }; + this.motorIndex = -1; + this.app.refreshPanel(); + }); + return section('Motors', [...(this.study.motors.length ? [list] : [h('p', { class: 'field-label' }, 'No motors yet: add one to drive the mechanism.')]), add]); + } + + private describeMotor(m: MotionMotor): string { + const v = (p: Param | undefined) => (p === undefined ? '?' : typeof p === 'string' ? p : String(Math.round(p * 1000) / 1000)); + const unit = m.kind === 'rotary' ? (m.rpm ? ' rpm' : '°/s') : m.kind === 'linear' ? ' mm/s' : '/s'; + const what = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate)?.name ?? '?' : m.ref && 'comp' in m.ref ? this.mode.component(m.ref.comp)?.name ?? '?' : '?'; + const how = m.profile === 'constant' ? `${v(m.speed)}${unit}` : m.profile === 'oscillate' ? `±${v(m.amplitude)} at ${v(m.frequency)} Hz` : `${v(m.from)} to ${v(m.to)}`; + return `${KIND_LABELS[m.kind]}, ${what}: ${how}${m.reverse ? ', reversed' : ''}`; + } + + private calcSection(res: MotionResult | null): HTMLElement { + const items: HTMLElement[] = []; + const old = this.mode.motionOf(this.key, this.study); + if (this.computing) { + this.bar = h('progress', { max: '1', value: String(this.progress), 'aria-label': 'Calculation progress' }) as HTMLProgressElement; + const cancel = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); + cancel.addEventListener('click', () => { this.runs++; this.computing = false; this.app.refreshPanel(); }); + items.push(h('p', { class: 'field-label', role: 'status' }, 'Calculating the motion...'), this.bar, cancel); + } else { + const calc = h('button', { class: 'btn small primary', type: 'button', disabled: !this.study.motors.length }, icon('rebuild', 14), res ? 'Calculate again' : 'Calculate'); + calc.addEventListener('click', () => void this.calculate()); + items.push(calc); + if (this.error) items.push(h('p', { class: 'pm-msg error', role: 'alert' }, this.error)); + else if (old && !old.current) items.push(h('p', { class: 'pm-msg warn', role: 'status' }, 'The results are out of date: the assembly or the study changed since they were calculated. Calculate again.')); + else if (res?.stop) items.push(h('p', { class: `pm-msg ${res.stop.kind === 'limit' ? 'warn' : 'error'}`, role: 'alert' }, res.stop.message)); + else if (res) items.push(h('p', { class: 'pm-msg info', role: 'status' }, `Calculated ${res.frames.length} frames.`)); + } + return section('Calculation', items); + } + + /** The study changed: results no longer match it (they stay cached for an undo of the change). */ + private stale() { + this.play(false); + this.error = null; + this.mode.previewPlacements(null); + this.app.refreshPanel(); + } + + private async calculate() { + const run = ++this.runs; + this.play(false); + this.computing = true; + this.progress = 0; + this.error = null; + this.app.refreshPanel(); + const st = structuredClone(this.study); + const r = await this.mode.computeMotion(st, this.key, (f) => { this.progress = f; if (this.bar) this.bar.value = f; }, () => run !== this.runs || this.disposed); + if (run !== this.runs || this.disposed) return; + this.computing = false; + if (typeof r === 'string') this.error = r; + this.t = 0; + this.app.refreshPanel(); + if (r && typeof r !== 'string') { this.showAt(0); if (r.frames.length > 1 && !r.stop) this.play(true); } + } + + // ---------- playback ---------- + + private playSection(res: MotionResult): HTMLElement { + const end = res.times[res.times.length - 1]; + const slider = h('input', { type: 'range', min: '0', max: '1000', step: '1', value: String(Math.round((this.t / Math.max(end, 1e-9)) * 1000)), 'aria-label': 'Study time', class: 'kin-slider' }) as HTMLInputElement; + slider.addEventListener('input', () => { this.play(false); this.t = (Number(slider.value) / 1000) * end; this.showAt(this.t); }); + this.slider = slider; + this.clock = h('div', { class: 'field-label kin-clock', 'aria-live': 'off' }); + const play = h('button', { class: 'btn small', type: 'button' }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; + play.addEventListener('click', () => this.play(!this.playing)); + this.playBtn = play; + const toStart = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the start', onclick: () => { this.play(false); this.t = 0; this.showAt(0); } }, icon('upToLine', 16)); + const toEnd = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the end', onclick: () => { this.play(false); this.t = end; this.showAt(end); } }, icon('downToLine', 16)); + const speed = selectField('Playback speed', String(this.speed), [{ value: '0.25', label: '¼ speed' }, { value: '0.5', label: '½ speed' }, { value: '1', label: 'Real time' }, { value: '2', label: '2× speed' }, { value: '5', label: '5× speed' }], (v) => { this.speed = Number(v); }); + queueMicrotask(() => this.showAt(this.t)); + return section('Playback', [h('div', { class: 'row kin-play' }, toStart, play, toEnd), slider, this.clock, checkbox('Loop', this.loop, (v) => { this.loop = v; }), speed]); + } + + private play(on: boolean) { + const res = this.result(); + this.playing = on && !!res; + cancelAnimationFrame(this.raf); + if (this.playBtn) this.playBtn.replaceChildren(icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play'); + if (!this.playing || !res) return; + const end = res.times[res.times.length - 1]; + if (this.t >= end - 1e-9) this.t = 0; + this.last = performance.now(); + const tick = (now: number) => { + if (!this.playing || this.disposed) return; + const r = this.result(); + if (!r) { this.play(false); return; } + this.t += ((now - this.last) / 1000) * this.speed; + this.last = now; + if (this.t >= end) { + if (this.loop) this.t %= Math.max(end, 1e-9); + else { this.t = end; this.showAt(end); this.play(false); return; } + } + this.showAt(this.t); + this.raf = requestAnimationFrame(tick); + }; + this.raf = requestAnimationFrame(tick); + } + + /** Shows the frame at time t (the nearest computed one). */ + private showAt(t: number) { + const res = this.result(); + if (!res || this.disposed) return; + const i = frameAt(res, t); + this.mode.previewPlacements(res.frames[i]); + const end = res.times[res.times.length - 1]; + if (this.slider && document.activeElement !== this.slider) this.slider.value = String(Math.round((t / Math.max(end, 1e-9)) * 1000)); + if (this.clock) this.clock.textContent = `${t.toFixed(2)} s / ${end.toFixed(2)} s`; + if (this.plotCursor) { + const x = plotX(res.times[i], end); + this.plotCursor.setAttribute('x1', String(x)); + this.plotCursor.setAttribute('x2', String(x)); + } + } + + // ---------- results ---------- + + /** The mates a result can be plotted for (those that measure something). */ + private measurable(): SolverMate[] { + const { mates } = this.mode.solverInput(); + return mates.filter((m) => m.type === 'distance' || m.type === 'angle' || (m.type === 'hinge' && m.rel) || m.type === 'slot'); + } + + private resultsSection(res: MotionResult): HTMLElement { + const doc = this.mode.doc; + const comps = doc.components.filter((c) => !c.suppressed && !c.fixed); + const mates = this.measurable(); + const options = [ + ...comps.map((c) => ({ value: `comp:${c.id}`, label: `Component: ${c.name}` })), + ...mates.map((m) => ({ value: `mate:${m.id}`, label: `Mate: ${doc.mates.find((x) => x.id === m.id)?.name ?? m.id}` })), + ]; + if (!options.some((o) => o.value === this.target)) { + // The component the first motor drives, else the first one that moves. + const first = this.study.motors.find((m) => m.ref && 'comp' in m.ref)?.ref; + this.target = first && 'comp' in first && comps.some((c) => c.id === first.comp) ? `comp:${first.comp}` : options[0]?.value ?? ''; + } + if (!options.length) return section('Results', [h('p', { class: 'field-label' }, 'No component moves.')]); + const items: HTMLElement[] = [selectField('Result of', this.target, options, (v) => { this.target = v; this.point = null; this.app.refreshPanel(); }, 'part')]; + const isComp = this.target.startsWith('comp:'); + if (isComp) { + const comp = this.target.slice(5); + const box = new SelectionBox(this, 'Point (optional)', { vertex: true, face: true, edge: true }, (it) => this.pointOf(it, comp), (sel) => { + const p = sel[0]?.data as { comp: Id; local: Vec3; label: string } | undefined; + this.point = p ?? null; + this.app.refreshPanel(); + }, { single: true, placeholder: 'The component\'s origin; or select a vertex, edge or face of it', icon: 'point' }); + if (this.point) box.setItems([{ item: null, data: this.point, label: this.point.label }]); + items.push(box.el, + selectField('Quantity', `${this.angular ? 'a' : 'l'}${this.quantity}`, [ + { value: 'l0', label: 'Linear displacement' }, { value: 'l1', label: 'Linear velocity' }, { value: 'l2', label: 'Linear acceleration' }, + { value: 'a0', label: 'Angular displacement' }, { value: 'a1', label: 'Angular velocity' }, { value: 'a2', label: 'Angular acceleration' }, + ], (v) => { this.angular = v[0] === 'a'; this.quantity = Number(v[1]) as Quantity; this.app.refreshPanel(); }), + selectField('Vector component', this.axis, [{ value: 'mag', label: 'Magnitude' }, { value: 'x', label: 'X' }, { value: 'y', label: 'Y' }, { value: 'z', label: 'Z' }], (v) => { this.axis = v; this.app.refreshPanel(); })); + } else { + items.push(selectField('Quantity', String(this.quantity), [{ value: '0', label: 'Value' }, { value: '1', label: 'Rate of change' }, { value: '2', label: 'Second derivative' }], (v) => { this.quantity = Number(v) as Quantity; this.app.refreshPanel(); })); + } + const series = this.series(res); + if (series) items.push(this.plot(res, series)); + const csv = h('button', { class: 'btn small', type: 'button', disabled: !series }, icon('download', 14), 'Download CSV'); + csv.addEventListener('click', () => this.downloadCsv(res)); + items.push(csv); + return section('Results', items); + } + + /** A picked vertex, edge or face as a point of the component (its coordinates in the component). */ + private pointOf(it: SelItem, comp: Id): SelBoxItem | null { + const mode = this.mode; + let world: Vec3 | null = null, owner: Id | undefined, label = ''; + if (it.kind === 'vertex') { world = it.p; label = 'Vertex'; owner = this.nearestComp(it.p); } + if (it.kind === 'face') { const f = this.app.faces[it.index]; owner = mode.faceComponent(it.index)?.id; world = f?.center ?? null; label = `Face (${f?.type}) centre`; } + if (it.kind === 'edge') { const e = this.app.edges[it.index]; owner = mode.edgeComponent(it.index)?.id; world = e ? e.center ?? e.mid : null; label = `Edge (${e?.type}) ${e?.center ? 'centre' : 'midpoint'}`; } + const pl = mode.shownPlacement(comp); + if (!world || !pl || owner !== comp) return null; + const local = relativePlacement(pl, { p: world, q: [0, 0, 0, 1] }).p; + return { item: it, data: { comp, local, label }, label }; + } + + private nearestComp(p: Vec3): Id | undefined { + let best: Id | undefined, d = Infinity; + this.app.faces.forEach((f, i) => { + const x = len([f.center[0] - p[0], f.center[1] - p[1], f.center[2] - p[2]]); + if (x < d) { d = x; best = this.mode.faceComponent(i)?.id; } + }); + return best; + } + + /** The plotted series: values per frame, with its name and unit. */ + private series(res: MotionResult): { values: number[]; name: string; unit: string } | null { + const u = UNIT_SYSTEMS[this.mode.doc.units]; + const per = ['', '/s', '/s²'][this.quantity]; + if (this.target.startsWith('mate:')) { + const m = this.measurable().find((x) => x.id === this.target.slice(5)); + const s = m && mateSeries(res, m, 100); + if (!m || !s) return null; + const vals = this.quantity === 0 ? s.values : derivatives(res.times, s.values)[this.quantity === 1 ? 'd1' : 'd2']; + const lengthy = s.kind === 'length'; + const name = `${this.mode.doc.mates.find((x) => x.id === m.id)?.name ?? ''} ${['value', 'rate of change', 'second derivative'][this.quantity]}`; + return { values: lengthy ? vals.map((v) => v / u.scale) : vals, name, unit: `${lengthy ? u.length : '°'}${per}` }; + } + const comp = this.target.slice(5); + const vecs = this.vectors(res, comp); + const pick = (v: Vec3) => (this.axis === 'mag' ? len(v) : v['xyz'.indexOf(this.axis)]); + const list = vecs[this.angular ? 'angular' : 'linear'][this.quantity]; + const name = `${this.mode.component(comp)?.name ?? ''} ${this.angular ? 'angular' : 'linear'} ${['displacement', 'velocity', 'acceleration'][this.quantity]}${this.axis === 'mag' ? '' : ` ${this.axis.toUpperCase()}`}`; + return { values: list.map((v) => (this.angular ? pick(v) : pick(v) / u.scale)), name, unit: `${this.angular ? '°' : u.length}${per}` }; + } + + /** Displacement, velocity and acceleration vectors of the chosen point (mm) and of the component's turn (degrees). */ + private vectors(res: MotionResult, comp: Id): { linear: Vec3[][]; angular: Vec3[][] } { + const local = this.point?.comp === comp ? this.point.local : [0, 0, 0] as Vec3; + const path = pointPath(res, comp, local); + const disp = path.map((p) => [p[0] - path[0][0], p[1] - path[0][1], p[2] - path[0][2]] as Vec3); + const lin = vectorDerivatives(res.times, path); + const turn = turnPath(res, comp).map((v) => v.map((x) => (x * 180) / Math.PI) as Vec3); + const ang = vectorDerivatives(res.times, turn); + return { linear: [disp, lin.d1, lin.d2], angular: [turn, ang.d1, ang.d2] }; + } + + private plot(res: MotionResult, s: { values: number[]; name: string; unit: string }): HTMLElement { + const end = res.times[res.times.length - 1]; + const min = Math.min(...s.values), max = Math.max(...s.values); + // A constant is drawn across the middle. + const flat = !(max - min > 1e-9 * Math.max(1, Math.abs(max))); + const lo = flat ? min - 1 : min, hi = flat ? max + 1 : max; + const y = (v: number) => PLOT.top + (1 - (v - lo) / (hi - lo)) * (PLOT.h - PLOT.top - PLOT.bottom); + const pts = s.values.map((v, i) => `${plotX(res.times[i], end).toFixed(1)},${y(v).toFixed(1)}`).join(' '); + const ns = 'http://www.w3.org/2000/svg'; + const el = (tag: K, attrs: Record, text?: string): SVGElementTagNameMap[K] => { + const e = document.createElementNS(ns, tag); + for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, String(v)); + if (text !== undefined) e.textContent = text; + return e; + }; + const fmtN = (v: number) => (Math.abs(v) >= 1000 || (Math.abs(v) < 0.01 && v !== 0) ? v.toExponential(2) : String(Math.round(v * 100) / 100)); + const svg = el('svg', { viewBox: `0 0 ${PLOT.w} ${PLOT.h}`, class: 'kin-plot', role: 'img', 'aria-label': `Plot of ${s.name} (${s.unit}) against time, from ${fmtN(min)} to ${fmtN(max)}` }); + const x0 = PLOT.left, x1 = PLOT.w - PLOT.right, yb = PLOT.h - PLOT.bottom; + svg.append( + el('rect', { x: x0, y: PLOT.top, width: x1 - x0, height: yb - PLOT.top, class: 'kin-plot-frame' }), + ...(lo < 0 && hi > 0 ? [el('line', { x1: x0, x2: x1, y1: y(0), y2: y(0), class: 'kin-plot-zero' })] : []), + el('polyline', { points: pts, class: 'kin-plot-line' }), + el('text', { x: x0 - 4, y: flat ? y(max) + 3 : PLOT.top + 4, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtN(flat ? max : hi)), + ...(flat ? [] : [el('text', { x: x0 - 4, y: yb, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtN(lo))]), + el('text', { x: x0, y: PLOT.h - 4, class: 'kin-plot-text' }, '0 s'), + el('text', { x: x1, y: PLOT.h - 4, 'text-anchor': 'end', class: 'kin-plot-text' }, `${fmtN(end)} s`), + ); + const t = res.times[frameAt(res, this.t)]; + this.plotCursor = el('line', { x1: plotX(t, end), x2: plotX(t, end), y1: PLOT.top, y2: yb, class: 'kin-plot-cursor' }); + svg.append(this.plotCursor); + // Clicking the plot goes to that time. + svg.addEventListener('click', (e) => { + const r = svg.getBoundingClientRect(); + const fx = ((e.clientX - r.left) / r.width) * PLOT.w; + this.play(false); + this.t = Math.max(0, Math.min(end, ((fx - x0) / (x1 - x0)) * end)); + this.showAt(this.t); + }); + return h('div', { class: 'kin-plot-box' }, h('div', { class: 'field-label' }, `${s.name} (${s.unit})`), svg as unknown as HTMLElement); + } + + private downloadCsv(res: MotionResult) { + const u = UNIT_SYSTEMS[this.mode.doc.units]; + const cols: { name: string; values: number[] }[] = [{ name: 'Time (s)', values: res.times }]; + if (this.target.startsWith('mate:')) { + const m = this.measurable().find((x) => x.id === this.target.slice(5)); + const s = m && mateSeries(res, m, 100); + if (!s) return; + const k = s.kind === 'length' ? 1 / u.scale : 1, unit = s.kind === 'length' ? u.length : 'deg'; + const d = derivatives(res.times, s.values); + cols.push({ name: `Value (${unit})`, values: s.values.map((v) => v * k) }, { name: `Rate (${unit}/s)`, values: d.d1.map((v) => v * k) }, { name: `Second derivative (${unit}/s^2)`, values: d.d2.map((v) => v * k) }); + } else { + const v = this.vectors(res, this.target.slice(5)); + const add = (name: string, list: Vec3[], unit: string, k: number) => { + for (const [i, a] of ['X', 'Y', 'Z'].entries()) cols.push({ name: `${name} ${a} (${unit})`, values: list.map((x) => x[i] * k) }); + cols.push({ name: `${name} magnitude (${unit})`, values: list.map((x) => len(x) * k) }); + }; + ['Displacement', 'Velocity', 'Acceleration'].forEach((n, i) => add(n, v.linear[i], `${u.length}${['', '/s', '/s^2'][i]}`, 1 / u.scale)); + ['Angle', 'Angular velocity', 'Angular acceleration'].forEach((n, i) => add(n, v.angular[i], `deg${['', '/s', '/s^2'][i]}`, 1)); + } + const label = this.target.startsWith('mate:') ? this.mode.doc.mates.find((x) => x.id === this.target.slice(5))?.name : this.mode.component(this.target.slice(5))?.name; + download(resultsCsv(cols), `${safeName(this.study.name || 'Motion Study')} ${safeName(label ?? '')}.csv`, 'text/csv'); + } + + // ---------- a motor ---------- + + private renderMotor(): HTMLElement[] { + const m = this.motor!; + const ctx = this.app.unitContext(); + const set = (patch: Partial) => { Object.assign(this.motor!, patch); this.app.refreshPanel(); }; + const items: HTMLElement[] = [ + h('div', { class: 'field-label' }, 'Motor type'), + segmented('Motor type', m.kind, [{ value: 'rotary', label: 'Rotary' }, { value: 'linear', label: 'Linear' }, { value: 'mate', label: 'Mate' }], (v) => { + const p: MotionProfile = v !== 'mate' && m.profile === 'ramp' ? 'constant' : m.profile; + Object.assign(this.motor!, { kind: v, profile: p, ref: v === 'mate' ? undefined : m.ref, mate: v === 'mate' ? m.mate : undefined, rpm: v === 'rotary' ? m.rpm : undefined }); + if (p === 'constant' && m.speed === undefined) this.motor!.speed = 10; + this.app.refreshPanel(); + }), + ]; + if (m.kind === 'mate') { + const mates = this.mode.doc.mates.filter((x) => (x.type === 'distance' || x.type === 'angle') && !x.limit); + if (!mates.length) items.push(h('p', { class: 'pm-msg warn' }, 'The assembly has no distance or angle mate (without limits) to drive.')); + else { + if (!mates.some((x) => x.id === m.mate)) m.mate = mates[0].id; + items.push(selectField('Mate to drive', m.mate!, mates.map((x) => ({ value: x.id, label: `${x.name} (${MATE_LABELS[x.type]})` })), (v) => set({ mate: v }), 'mate')); + } + } else { + const box = new SelectionBox(this, m.kind === 'rotary' ? 'Motor axis' : 'Motor direction', { face: true, edge: true }, (it) => { + const r = this.mode.refOf(it); + if (!r || !('comp' in r) || !('face' in r || 'edge' in r)) return null; + return { item: it, data: r, label: `${'face' in r ? `Face (${r.face.sig.type})` : `Edge (${r.edge.sig.type})`} of ${this.mode.component(r.comp)?.name ?? '?'}` }; + }, (sel) => { this.motor!.ref = sel[0]?.data as MotionMotor['ref']; }, { + single: true, icon: 'axis', + placeholder: m.kind === 'rotary' ? 'Select a round face or edge of the component to turn (or a straight edge or face along its axis)' : 'Select a straight edge or face of the component to move, along it (or across a face)', + }); + if (m.ref && 'comp' in m.ref) box.setItems([{ item: this.mode.itemOf(m.ref), data: m.ref, label: `${'face' in m.ref ? `Face (${m.ref.face.sig.type})` : 'edge' in m.ref ? `Edge (${m.ref.edge.sig.type})` : 'Component'} of ${this.mode.component(m.ref.comp)?.name ?? '?'}` }]); + items.push(box.el); + } + const profiles: { value: MotionProfile; label: string }[] = m.kind === 'mate' + ? [{ value: 'constant', label: 'Constant speed' }, { value: 'oscillate', label: 'Harmonic' }, { value: 'ramp', label: 'Linear ramp between values' }] + : [{ value: 'constant', label: 'Constant speed' }, { value: 'oscillate', label: 'Oscillating' }]; + items.push(selectField('Motion', m.profile, profiles, (v) => { + const defaults: Partial = v === 'constant' ? { speed: m.speed ?? 10 } : v === 'oscillate' ? { amplitude: m.amplitude ?? 10, frequency: m.frequency ?? 1 } : { from: m.from ?? 0, to: m.to ?? 10 }; + set({ profile: v, ...defaults }); + })); + const mate = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate) : undefined; + const kind = m.kind === 'rotary' || mate?.type === 'angle' ? 'angle' : 'length'; + const unit = kind === 'angle' ? '°' : UNIT_SYSTEMS[ctx.units].length; + // Number fields with the unit of what they hold (a speed's is per second). + const field = (label: string, key: 'speed' | 'amplitude' | 'frequency' | 'from' | 'to', k: 'length' | 'angle', shown: string) => { + const f = numberField({ label, value: m[key] ?? 0, kind: k, ctx, onChange: (v) => { this.motor![key] = v; } }); + const lab = f.querySelector('.field-label'); + if (lab) lab.textContent = `${label} (${shown})`; + return f; + }; + if (m.profile === 'constant') { + if (m.kind === 'rotary') { + items.push(field('Speed', 'speed', 'angle', m.rpm ? 'rpm' : '°/s'), + segmented('Speed unit', m.rpm ? 'rpm' : 'deg', [{ value: 'deg', label: '°/s' }, { value: 'rpm', label: 'rpm' }], (v) => set({ rpm: v === 'rpm' ? true : undefined }))); + } else items.push(field('Speed', 'speed', kind, `${unit}/s`)); + } else if (m.profile === 'oscillate') items.push(field('Amplitude', 'amplitude', kind, unit), field('Frequency', 'frequency', 'angle', 'Hz')); + else items.push(field('Start value', 'from', kind, unit), field('End value', 'to', kind, unit)); + if (m.profile !== 'ramp') items.push(checkbox('Reverse direction', !!m.reverse, (v) => { this.motor!.reverse = v || undefined; })); + items.push(checkbox('Suppressed', !!m.suppressed, (v) => { this.motor!.suppressed = v || undefined; })); + const done = h('button', { class: 'btn small primary', type: 'button' }, this.motorIndex < 0 ? 'Add' : 'Apply'); + done.addEventListener('click', () => this.finishMotor(true)); + const back = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); + back.addEventListener('click', () => this.finishMotor(false)); + items.push(h('div', { class: 'row kin-motor-buttons' }, done, back)); + return [section(this.motorIndex < 0 ? 'Add Motor' : `Motor: ${m.name}`, items, { icon: 'motionStudy' })]; + } + + private finishMotor(save: boolean) { + const m = this.motor; + if (!m) return; + if (save) { + if (!this.checkFields()) return; + if (m.kind !== 'mate' && !m.ref) { this.setMessage('error', m.kind === 'rotary' ? 'Select the motor\'s axis: a round face or edge of the component to turn.' : 'Select the motor\'s direction: a straight edge or face of the component to move.'); return; } + if (m.kind === 'mate' && !m.mate) { this.setMessage('error', 'Select the mate to drive.'); return; } + // Only the fields of its kind and profile are kept. + const keep: (keyof MotionMotor)[] = m.profile === 'constant' ? ['speed'] : m.profile === 'oscillate' ? ['amplitude', 'frequency'] : ['from', 'to']; + for (const k of ['speed', 'amplitude', 'frequency', 'from', 'to'] as const) if (!keep.includes(k)) delete m[k]; + if (m.kind !== 'rotary') delete m.rpm; + if (m.profile === 'ramp') delete m.reverse; + if (m.kind === 'mate') delete m.ref; else delete m.mate; + if (this.motorIndex < 0) { + // Ids and names are allocated as the document's would be (the study's own motors counted too). + const draft = { ...this.mode.doc, studies: [...(this.mode.doc.studies ?? []).filter((s) => s.id !== this.key), this.study] }; + m.id = nextAsmId(structuredClone({ ...draft, blobs: {} }), 'o'); + const all = draft.studies.flatMap((s) => s.motors); + let k = all.filter((x) => x.kind === m.kind).length + 1; + while (all.some((x) => x.name === `${KIND_NAMES[m.kind]}${k}`)) k++; + m.name = `${KIND_NAMES[m.kind]}${k}`; + this.study.motors.push(m); + } else this.study.motors[this.motorIndex] = m; + } + this.motor = null; + this.setMessage(null); + this.stale(); + } + + onPick(item: SelItem, additive: boolean): boolean { + if (!this.activeBox) return false; + return this.activeBox.toggle(item, additive); + } + + ok(): boolean { + if (this.motor) { this.finishMotor(true); if (this.motor) return false; } + this.play(false); + this.runs++; + this.mode.previewPlacements(null); + const st = structuredClone(this.study); + if (this.existing) this.mode.commit(`Edit ${st.name}`, (d) => { d.studies = (d.studies ?? []).map((s) => (s.id === st.id ? st : s)); }, false); + else { + this.mode.commit('Add motion study', (d) => { + st.id = nextAsmId(d, 's'); + let k = (d.studies?.length ?? 0) + 1; + while (d.studies?.some((s) => s.name.toLowerCase() === `motion study${k}`)) k++; + st.name = `Motion Study${k}`; + d.studies = [...d.studies ?? [], st]; + }, false); + this.mode.keepMotion('', st.id); + } + return true; + } + + cancel() { + this.play(false); + this.runs++; + this.mode.previewPlacements(null); + } + + get edited(): boolean { + return JSON.stringify(this.study) !== this.original || !!this.motor; + } + + dispose() { + this.disposed = true; + this.playing = false; + cancelAnimationFrame(this.raf); + this.mode.previewPlacements(null); + } +} + +const PLOT = { w: 280, h: 150, left: 44, right: 8, top: 8, bottom: 18 }; +const plotX = (t: number, end: number) => PLOT.left + (t / Math.max(end, 1e-9)) * (PLOT.w - PLOT.left - PLOT.right); + +/** The frame nearest time t. */ +function frameAt(res: MotionResult, t: number): number { + let lo = 0, hi = res.times.length - 1; + while (lo < hi) { const m = (lo + hi + 1) >> 1; if (res.times[m] <= t + 1e-9) lo = m; else hi = m - 1; } + return lo + 1 < res.times.length && res.times[lo + 1] - t < t - res.times[lo] ? lo + 1 : lo; +} diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts index 58e2702b5c..1d68316c2c 100644 --- a/src/parametric/src/app/assembly/panels.ts +++ b/src/parametric/src/app/assembly/panels.ts @@ -11,8 +11,8 @@ import { BASE_PLANE_NAMES } from '../../model/planes'; import type { Id, Param, PartDocument } from '../../model/types'; import { UNIT_SYSTEMS } from '../../model/units'; import { - type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MateType, type PartSource, MATE_LABELS, assemblyBom, bomCsv, instanceName, - isAssembly, newPartBlobId, nextAsmId, nextPartColor, parseAnyDocument, + type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MateType, type MechanicalMateType, type PartSource, type Placement, MATE_LABELS, MECHANICAL_MATES, assemblyBom, bomCsv, instanceName, + isAssembly, isMechanical, newPartBlobId, nextAsmId, nextPartColor, parseAnyDocument, } from '../../model/assembly'; import { type Geo, fittingMates, initialMateSettings, mateProblem, placeGeo, relativePlacement } from '../../assembly/solver'; import { @@ -25,7 +25,7 @@ import { icon } from '../../ui/icons'; import { showDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; import { formatGroup } from '../dialogs'; -import { type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm'; +import { type PickFilter, type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm'; import type { SelItem } from '../selection'; import type { AssemblyMode } from './mode'; @@ -184,32 +184,69 @@ export function insertComponent(mode: AssemblyMode, picked: PickedPart) { // ---------- Mate ---------- -const MATE_TYPES: MateType[] = ['coincident', 'parallel', 'perpendicular', 'distance', 'angle', 'concentric', 'tangent', 'lock']; +const STANDARD_MATES: MateType[] = ['coincident', 'parallel', 'perpendicular', 'distance', 'angle', 'concentric', 'tangent', 'lock']; + +/** The selection boxes of a mechanical mate: their labels, what each takes, and how many entities. */ +const MECH_BOXES: Record = { + hinge: [ + { label: 'Concentric selections', placeholder: 'Select the pin and its hole (round faces or edges)', count: 2, filter: { face: true, edge: true } }, + { label: 'Coincident selections', placeholder: 'Select two planar faces that touch', count: 2, filter: { face: true, plane: true } }, + ], + gear: [{ label: 'Gears', placeholder: 'Select a round face or edge of each gear', count: 2, filter: { face: true, edge: true } }], + rackPinion: [{ label: 'Rack and pinion', placeholder: 'Select a straight edge of the rack and a round face or edge of the pinion', count: 2, filter: { face: true, edge: true } }], + screw: [{ label: 'Screw selections', placeholder: 'Select a round face or edge of the screw and of the nut', count: 2, filter: { face: true, edge: true } }], + width: [ + { label: 'Width selections', placeholder: 'Select the two faces of the groove', count: 2, filter: { face: true, plane: true } }, + { label: 'Tab selections', placeholder: 'Select the two faces of the tab', count: 2, filter: { face: true } }, + ], + slot: [ + { label: 'Slot ends', placeholder: 'Select the two round ends of the slot', count: 2, filter: { face: true, edge: true } }, + { label: 'Pin', placeholder: 'Select the pin (a round face or edge)', count: 1, filter: { face: true, edge: true } }, + ], +}; export class MatePanel extends PropertyPanel { title = 'Mate'; icon = 'mate'; private box!: SelectionBox; private refs: MateRef[] = []; + /** The second selection box of hinge, width and slot mates. */ + private refs2: MateRef[] = []; private type: MateType | null = null; private aligned = true; + private aligned2 = false; private flip = false; private value: Param = 10; + private value2: Param = 20; + private limitOn = false; + private min: Param = 0; + private max: Param = 10; + private by: 'ratio' | 'revolution' | null = null; + private reverse = false; private auto = true; private result = h('div', { class: 'pm-msg', role: 'status' }); constructor(private mode: AssemblyMode, private existing: Mate | null = null) { super(); - this.helpText = 'Select two faces, edges or planes of different components (or of a component and the assembly). Mates keep them together as you move things.'; + this.helpText = 'Select two faces, edges or planes of different components (or of a component and the assembly). Mates keep them together as you move things. Mechanical mates (hinge, gear, rack and pinion, screw, width, slot) are in the list of mate types.'; if (existing) { this.editingId = existing.id; - this.refs = [existing.a, existing.b]; this.type = existing.type; this.aligned = existing.aligned; + this.aligned2 = !!existing.aligned2; this.flip = !!existing.flip; this.value = existing.value ?? (existing.type === 'angle' ? 90 : 10); + this.value2 = existing.value2 ?? 20; + this.limitOn = !!existing.limit; + if (existing.limit) { this.min = existing.limit.min; this.max = existing.limit.max; } + this.by = existing.by ?? null; + this.reverse = !!existing.reverse; this.auto = false; this.title = `Mate: ${existing.name}`; + const t = existing.type; + if (t === 'width' || t === 'slot') { this.refs = [existing.a, existing.a2!]; this.refs2 = [existing.b, ...(existing.b2 ? [existing.b2] : [])]; } + else if (t === 'hinge') { this.refs = [existing.a, existing.b]; this.refs2 = [existing.a2!, existing.b2!]; } + else this.refs = [existing.a, existing.b]; } else { const pre = mode.app.selection.items.map((it) => mode.refOf(it)).filter((r): r is MateRef => !!r).slice(0, 2); if (pre.length) { this.refs = pre; this.pickDefaults(); } @@ -231,8 +268,14 @@ export class MatePanel extends PropertyPanel { return c; } - /** The type, alignment, side and value that fit the two entities where they are. */ + private get mech(): MechanicalMateType | null { + return this.type && isMechanical(this.type) ? this.type : null; + } + + /** The type, alignment, side and values that fit the entities where they are. */ private pickDefaults() { + const mech = this.mech; + if (mech) { this.mechDefaults(mech); return; } if (this.refs.length < 2) return; const [a, b] = this.refs.map((r) => this.geo(r)); if (!a || !b) return; @@ -243,90 +286,283 @@ export class MatePanel extends PropertyPanel { this.flip = st.flip; if (this.type === 'distance') this.value = Math.round(st.value * 1000) / 1000; if (this.type === 'angle') this.value = Math.round(st.value * 100) / 100; + if (this.limitOn && typeof this.value === 'number') this.limitAround(this.value); + } + + /** Limits around the value a mate has where its entities are. */ + private limitAround(v: number) { + if (this.type === 'angle') { this.min = Math.max(0, Math.round(v - 30)); this.max = Math.min(180, Math.round(v + 30)); } + else if (this.type === 'hinge') { this.min = -45; this.max = 45; } + else { this.min = Math.max(0, Math.round((v - 10) * 1000) / 1000); this.max = Math.round((v + 10) * 1000) / 1000; } + } + + private mechDefaults(t: MechanicalMateType) { + const g = this.refs.map((r) => this.geo(r)); + const round = (x: Geo | null | undefined) => (x && x.kind === 'axis' && x.r > 0 ? Math.round(2 * x.r * 1000) / 1000 : null); + if (g.length === 2 && g[0] && g[1]) { + if (t === 'hinge' || t === 'screw') this.aligned = initialMateSettings('concentric', g[0], g[1]).aligned; + if (t === 'gear' && this.by !== 'ratio') { this.value = round(g[0]) ?? 20; this.value2 = round(g[1]) ?? 20; } + if (t === 'rackPinion') { + // The pinion first: the round one. + if (g[0].kind === 'line' && g[1].kind === 'axis') this.refs = [this.refs[1], this.refs[0]]; + if (this.by !== 'revolution') this.value = round(this.geo(this.refs[0])) ?? 20; + } + } + if (t === 'hinge' && this.refs2.length === 2) { + const [a2, b2] = this.hingeFaces(); + const ga = a2 && this.geo(a2), gb = b2 && this.geo(b2); + if (ga && gb) this.aligned2 = initialMateSettings('coincident', ga, gb).aligned; + } + if (t === 'screw' && typeof this.value === 'number' && this.value === 10 && !this.existing) this.value = 1; + } + + /** A hinge's two faces, the one on the first round entity's component first. */ + private hingeFaces(): [MateRef | undefined, MateRef | undefined] { + const [f, g] = this.refs2; + const comp = this.refs[0] && 'comp' in this.refs[0] ? this.refs[0].comp : null; + return f && g && 'comp' in g && g.comp === comp ? [g, f] : [f, g]; } render(): HTMLElement[] { const app = this.mode.app; const ctx = app.unitContext(); - this.box = new SelectionBox(this, 'Entities to mate', { face: true, edge: true, plane: true, feature: true }, (it) => this.convert(it), (items) => { - if (items.length > 2) { this.box.setItems(items.slice(-2)); return; } - this.refs = items.map((x) => x.data as MateRef); - if (!this.existing) this.pickDefaults(); - this.mode.app.refreshPanel(); - this.update(); - }, { placeholder: 'Select two faces, edges or planes', icon: 'mate' }); - this.box.setItems(this.refs.map((r) => ({ item: this.mode.itemOf(r), data: r, label: this.label(r) }))); - const geos = this.refs.length === 2 ? this.refs.map((r) => this.geo(r)) : null; - const fits = geos && geos[0] && geos[1] ? MATE_TYPES.filter((t) => t === 'lock' || !mateProblem(t, geos[0]!, geos[1]!)) : MATE_TYPES; + const mech = this.mech; + const sections: HTMLElement[] = []; + if (mech) { + const boxes = MECH_BOXES[mech]; + const made: SelectionBox[] = []; + boxes.forEach((spec, i) => { + const box = new SelectionBox(this, spec.label, spec.filter, (it) => this.convert(it), (items) => { + if (items.length > spec.count) { box.setItems(items.slice(-spec.count)); return; } + const refs = items.map((x) => x.data as MateRef); + if (i === 0) this.refs = refs; else this.refs2 = refs; + this.mechDefaults(mech); + // A full box hands the picks on to the next one. + const next = made[i + 1]; + if (refs.length === spec.count && next && next.items.length < boxes[i + 1].count) this.activate(next); + this.mode.app.refreshPanel(); + this.update(); + }, { placeholder: spec.placeholder, icon: 'mate', single: spec.count === 1 }); + box.setItems((i === 0 ? this.refs : this.refs2).map((r) => ({ item: this.mode.itemOf(r), data: r, label: this.label(r) }))); + made.push(box); + }); + this.box = made[0]; + sections.push(section('Mate Selections', made.map((b) => b.el))); + } else { + this.box = new SelectionBox(this, 'Entities to mate', { face: true, edge: true, plane: true, feature: true }, (it) => this.convert(it), (items) => { + if (items.length > 2) { this.box.setItems(items.slice(-2)); return; } + this.refs = items.map((x) => x.data as MateRef); + if (!this.existing) this.pickDefaults(); + this.mode.app.refreshPanel(); + this.update(); + }, { placeholder: 'Select two faces, edges or planes', icon: 'mate' }); + this.box.setItems(this.refs.map((r) => ({ item: this.mode.itemOf(r), data: r, label: this.label(r) }))); + sections.push(section('Mate Selections', [this.box.el])); + } + const geos = !mech && this.refs.length === 2 ? this.refs.map((r) => this.geo(r)) : null; + const fits = geos && geos[0] && geos[1] ? STANDARD_MATES.filter((t) => t === 'lock' || !mateProblem(t, geos[0]!, geos[1]!)) : STANDARD_MATES; const type = this.type ?? 'coincident'; - const typeSel = selectField('Mate type', type, fits.map((t) => ({ value: t, label: MATE_LABELS[t] })), (v) => { - this.type = v; - this.auto = false; - this.pickDefaults(); - this.mode.app.refreshPanel(); - this.update(); - }, `mate:${type}`); - const out: HTMLElement[] = [section('Mate Selections', [this.box.el]), section('Standard Mates', [typeSel])]; + const typeSel = selectField('Mate type', type, [...fits, ...MECHANICAL_MATES].map((t) => ({ value: t, label: MATE_LABELS[t] })), (v) => this.setType(v), `mate:${type}`); + // The two kinds of mates in groups of their own. + const sel = typeSel.querySelector('select')!; + const group = (label: string, types: readonly MateType[]) => { + const g = h('optgroup', { label }); + for (const o of [...sel.options]) if (types.includes(o.value as MateType)) g.append(o); + return g; + }; + sel.append(group('Standard', STANDARD_MATES), group('Mechanical', MECHANICAL_MATES)); + sel.value = type; + sections.push(section('Mate Type', [typeSel])); + const extra = mech ? this.mechOptions(mech, ctx) : this.standardOptions(type, ctx); + if (extra.length) sections.push(section('Options', extra)); + sections.push(h('section', { class: 'pm-section' }, this.result)); + queueMicrotask(() => this.update()); + return sections; + } + + private setType(v: MateType) { + const was = this.mech; + this.type = v; + this.auto = false; + const now = this.mech; + // Entities picked for one kind of mate carry over as far as they fit the other. + // Whole components (picked in the tree) make no mechanical mate. + if (!was && now) { this.refs2 = []; this.refs = this.refs.filter((r) => !('comp' in r) || 'face' in r || 'edge' in r).slice(0, 2); } + if (was && !now) this.refs = this.refs.slice(0, 2); + if (now === 'gear' && this.by === 'revolution') this.by = null; + if (now === 'rackPinion' && this.by === 'ratio') this.by = null; + if (!now && this.by) this.by = null; + if (this.limitOn && v !== 'distance' && v !== 'angle' && v !== 'hinge') this.limitOn = false; + this.pickDefaults(); + this.mode.app.refreshPanel(); + this.update(); + } + + private standardOptions(type: MateType, ctx: ReturnType): HTMLElement[] { const extra: HTMLElement[] = []; + const kind = type === 'distance' ? 'length' : 'angle'; if (type === 'distance' || type === 'angle') { - extra.push(numberField({ - label: type === 'distance' ? 'Distance' : 'Angle', icon: type === 'distance' ? 'smartDimension' : 'angle', value: this.value, kind: type === 'distance' ? 'length' : 'angle', ctx, min: type === 'distance' ? 0 : 0, max: type === 'angle' ? 180 : undefined, + extra.push(checkbox(type === 'distance' ? 'Limit the distance (between two values)' : 'Limit the angle (between two values)', this.limitOn, (v) => { + this.limitOn = v; + if (v) { + const [a, b] = this.refs.map((r) => this.geo(r)); + const now = a && b ? initialMateSettings(type, a, b).value : typeof this.value === 'number' ? this.value : 10; + this.limitAround(now); + } + this.mode.app.refreshPanel(); + this.update(); + })); + if (this.limitOn) extra.push(...this.limitFields(kind, ctx)); + else extra.push(numberField({ + label: type === 'distance' ? 'Distance' : 'Angle', icon: type === 'distance' ? 'smartDimension' : 'angle', value: this.value, kind, ctx, min: 0, max: type === 'angle' ? 180 : undefined, onChange: (v) => { this.value = v; this.update(); }, })); } if (type === 'distance' || type === 'tangent') extra.push(checkbox('Flip dimension (other side)', this.flip, (v) => { this.flip = v; this.update(); })); - if (type !== 'perpendicular' && type !== 'lock' && type !== 'tangent') { - extra.push(h('div', { class: 'field-label' }, 'Mate alignment'), segmented('Mate alignment', this.aligned ? 'aligned' : 'anti', [ - { value: 'aligned', label: 'Aligned' }, { value: 'anti', label: 'Anti-Aligned' }, - ], (v) => { this.aligned = v === 'aligned'; this.update(); })); + if (type !== 'perpendicular' && type !== 'lock' && type !== 'tangent') extra.push(...this.alignment()); + return extra; + } + + private alignment(): HTMLElement[] { + return [h('div', { class: 'field-label' }, 'Mate alignment'), segmented('Mate alignment', this.aligned ? 'aligned' : 'anti', [ + { value: 'aligned', label: 'Aligned' }, { value: 'anti', label: 'Anti-Aligned' }, + ], (v) => { this.aligned = v === 'aligned'; this.update(); })]; + } + + private limitFields(kind: 'length' | 'angle', ctx: ReturnType): HTMLElement[] { + const angle = kind === 'angle' && this.type === 'angle'; + return [ + numberField({ label: 'Maximum', icon: kind === 'length' ? 'smartDimension' : 'angle', value: this.max, kind, ctx, min: angle ? 0 : undefined, max: angle ? 180 : undefined, onChange: (v) => { this.max = v; this.update(); } }), + numberField({ label: 'Minimum', icon: kind === 'length' ? 'smartDimension' : 'angle', value: this.min, kind, ctx, min: angle ? 0 : undefined, max: angle ? 180 : undefined, onChange: (v) => { this.min = v; this.update(); } }), + ]; + } + + private mechOptions(t: MechanicalMateType, ctx: ReturnType): HTMLElement[] { + const out: HTMLElement[] = []; + const reverse = (label: string) => checkbox(label, this.reverse, (v) => { this.reverse = v; this.update(); }); + switch (t) { + case 'hinge': + out.push(...this.alignment(), checkbox('Limit the angle (from where it is now)', this.limitOn, (v) => { + this.limitOn = v; + if (v) this.limitAround(0); + this.mode.app.refreshPanel(); + this.update(); + })); + if (this.limitOn) out.push(...this.limitFields('angle', ctx)); + break; + case 'gear': { + const teeth = this.by === 'ratio'; + out.push(h('div', { class: 'field-label' }, 'Ratio from'), segmented('Ratio from', teeth ? 'ratio' : 'diameter', [{ value: 'diameter', label: 'Pitch diameters' }, { value: 'ratio', label: 'Teeth' }], (v) => { + this.by = v === 'ratio' ? 'ratio' : null; + if (v === 'ratio') { this.value = 20; this.value2 = 40; } else this.mechDefaults('gear'); + this.mode.app.refreshPanel(); + this.update(); + })); + const kind = teeth ? 'count' : 'length'; + out.push( + numberField({ label: teeth ? 'Teeth of the first gear' : 'Pitch diameter of the first gear', value: this.value, kind, ctx, min: teeth ? 1 : 0, onChange: (v) => { this.value = v; this.update(); } }), + numberField({ label: teeth ? 'Teeth of the second gear' : 'Pitch diameter of the second gear', value: this.value2, kind, ctx, min: teeth ? 1 : 0, onChange: (v) => { this.value2 = v; this.update(); } }), + reverse('Reverse (an internal gear: both turn the same way)'), + ); + break; + } + case 'rackPinion': { + const per = this.by === 'revolution'; + out.push(h('div', { class: 'field-label' }, 'Rack travel from'), segmented('Rack travel from', per ? 'revolution' : 'diameter', [{ value: 'diameter', label: 'Pitch diameter' }, { value: 'revolution', label: 'Travel per turn' }], (v) => { + this.by = v === 'revolution' ? 'revolution' : null; + if (typeof this.value === 'number') this.value = Math.round((v === 'revolution' ? this.value * Math.PI : this.value / Math.PI) * 1000) / 1000; + this.mode.app.refreshPanel(); + this.update(); + })); + out.push( + numberField({ label: per ? 'Rack travel per turn of the pinion' : 'Pinion pitch diameter', icon: 'smartDimension', value: this.value, kind: 'length', ctx, min: 0, onChange: (v) => { this.value = v; this.update(); } }), + reverse('Reverse the direction'), + ); + break; + } + case 'screw': + out.push( + numberField({ label: 'Pitch (travel per turn)', icon: 'smartDimension', value: this.value, kind: 'length', ctx, min: 0, onChange: (v) => { this.value = v; this.update(); } }), + h('div', { class: 'field-label' }, 'Thread'), segmented('Thread', this.reverse ? 'left' : 'right', [{ value: 'right', label: 'Right-hand' }, { value: 'left', label: 'Left-hand' }], (v) => { this.reverse = v === 'left'; this.update(); }), + ...this.alignment(), + ); + break; + default: + break; } - if (extra.length) out.push(section('Options', extra)); - out.push(h('section', { class: 'pm-section' }, this.result)); - queueMicrotask(() => this.update()); return out; } private convert(it: SelItem): SelBoxItem | null { const r = this.mode.refOf(it); if (!r) return null; - if ('comp' in r && !('face' in r) && !('edge' in r) && this.type !== 'lock') { + if ('comp' in r && !('face' in r) && !('edge' in r)) { // A component picked in the tree only takes a lock mate. - this.type = 'lock'; - this.auto = false; + if (this.mech) return null; + if (this.type !== 'lock') { this.type = 'lock'; this.auto = false; } } return { item: it, data: r, label: this.label(r) }; } + /** Where b sits in a's frame now (lock mates, and hinges measuring their angle). */ + private relNow(a: MateRef, b: MateRef): Placement | undefined { + const doc = this.mode.doc; + const at = (r: MateRef): Placement | undefined => ('comp' in r ? this.mode.solved.get(r.comp) ?? doc.components.find((c) => c.id === (r as { comp: Id }).comp)?.placement : { p: [0, 0, 0], q: [0, 0, 0, 1] }); + const pa = at(a), pb = at(b); + return pa && pb ? relativePlacement(pa, pb) : undefined; + } + /** The mate as it would be added. */ private mate(): Mate | null { - if (this.refs.length !== 2 || !this.type) return null; - const doc = this.mode.doc; + if (!this.type) return null; + const base = { id: this.existing?.id ?? '', name: this.existing?.name ?? '', type: this.type, aligned: this.aligned, ...(this.existing?.suppressed ? { suppressed: true } : {}) }; + const mech = this.mech; + if (mech) return this.mechMate(mech, base); + if (this.refs.length !== 2) return null; let [a, b] = this.refs; if (this.type === 'lock') { a = 'comp' in a ? { comp: a.comp } : a; b = 'comp' in b ? { comp: b.comp } : b; } + const limited = this.limitOn && (this.type === 'distance' || this.type === 'angle'); const m: Mate = { - id: this.existing?.id ?? '', name: this.existing?.name ?? '', type: this.type, a, b, aligned: this.aligned, + ...base, a, b, ...(this.type === 'distance' || this.type === 'angle' ? { value: this.value } : {}), + ...(limited ? { limit: { min: this.min, max: this.max } } : {}), ...(this.flip && (this.type === 'distance' || this.type === 'tangent') ? { flip: true } : {}), - ...(this.existing?.suppressed ? { suppressed: true } : {}), }; - if (this.type === 'lock') { - const pa = 'comp' in a ? this.mode.solved.get(a.comp) ?? doc.components.find((c) => c.id === (a as { comp: Id }).comp)?.placement : { p: [0, 0, 0] as Vec3, q: [0, 0, 0, 1] as [number, number, number, number] }; - const pb = 'comp' in b ? this.mode.solved.get(b.comp) ?? doc.components.find((c) => c.id === (b as { comp: Id }).comp)?.placement : { p: [0, 0, 0] as Vec3, q: [0, 0, 0, 1] as [number, number, number, number] }; - if (pa && pb) m.rel = relativePlacement(pa, pb); - } + if (this.type === 'lock') m.rel = this.relNow(a, b); return m; } + private mechMate(t: MechanicalMateType, base: Omit): Mate | null { + const counts = MECH_BOXES[t].map((x) => x.count); + if (this.refs.length !== counts[0] || (counts[1] && this.refs2.length !== counts[1])) return null; + const [r0, r1] = this.refs; + switch (t) { + case 'hinge': { + const [a2, b2] = this.hingeFaces(); + const keep = this.existing?.type === 'hinge' && this.existing.rel && JSON.stringify([this.existing.a, this.existing.b]) === JSON.stringify([r0, r1]); + const rel = this.limitOn ? (keep ? this.existing!.rel : this.relNow(r0, r1)) : undefined; + return { ...base, a: r0, b: r1, a2, b2, aligned2: this.aligned2, ...(this.limitOn ? { limit: { min: this.min, max: this.max } } : {}), ...(rel ? { rel } : {}) }; + } + case 'gear': return { ...base, a: r0, b: r1, value: this.value, value2: this.value2, ...(this.by === 'ratio' ? { by: 'ratio' } : {}), ...(this.reverse ? { reverse: true } : {}) }; + case 'rackPinion': return { ...base, a: r0, b: r1, value: this.value, ...(this.by === 'revolution' ? { by: 'revolution' } : {}), ...(this.reverse ? { reverse: true } : {}) }; + case 'screw': return { ...base, a: r0, b: r1, value: this.value, ...(this.reverse ? { reverse: true } : {}) }; + case 'width': return { ...base, a: r0, a2: r1, b: this.refs2[0], b2: this.refs2[1] }; + case 'slot': return { ...base, a: r0, a2: r1, b: this.refs2[0] }; + } + } + private withMate(d: AssemblyDocument, m: Mate) { if (this.existing) d.mates = d.mates.map((x) => (x.id === m.id ? m : x)); else { m.id = nextAsmId(d, 'm'); - const n = d.mates.filter((x) => x.type === m.type).length + 1; - let name = `${MATE_LABELS[m.type]}${n}`; - for (let k = n + 1; d.mates.some((x) => x.name === name); k++) name = `${MATE_LABELS[m.type]}${k}`; + // Limit mates are named for what they limit, as in "LimitDistance1". + const kind = m.limit && m.type !== 'hinge' ? `Limit${MATE_LABELS[m.type]}` : MATE_LABELS[m.type]; + const n = d.mates.filter((x) => x.type === m.type && !!x.limit === !!m.limit).length + 1; + let name = `${kind}${n}`; + for (let k = n + 1; d.mates.some((x) => x.name === name); k++) name = `${kind}${k}`; m.name = name; d.mates.push(m); } @@ -336,7 +572,13 @@ export class MatePanel extends PropertyPanel { private update() { const m = this.mate(); const mode = this.mode; - if (!m) { this.result.textContent = this.refs.length < 2 ? 'Select two entities to mate.' : ''; this.result.className = 'pm-msg'; mode.previewPlacements(null); return; } + if (!m) { + const mech = this.mech; + this.result.textContent = mech ? `Select ${MECH_BOXES[mech].map((b) => b.label.toLowerCase()).join(' and ')}.` : this.refs.length < 2 ? 'Select two entities to mate.' : ''; + this.result.className = 'pm-msg'; + mode.previewPlacements(null); + return; + } const d = structuredClone({ ...mode.doc, blobs: {} }) as AssemblyDocument; this.withMate(d, m); const r = mode.solveDoc(d); @@ -354,7 +596,7 @@ export class MatePanel extends PropertyPanel { ok(): boolean { const m = this.mate(); - if (!m) { this.setMessage('error', 'Select two entities to mate.'); return false; } + if (!m) { this.setMessage('error', this.mech ? `Select ${MECH_BOXES[this.mech].map((b) => b.label.toLowerCase()).join(' and ')}.` : 'Select two entities to mate.'); return false; } const d = structuredClone({ ...this.mode.doc, blobs: {} }) as AssemblyDocument; this.withMate(d, m); const r = this.mode.solveDoc(d); @@ -371,7 +613,7 @@ export class MatePanel extends PropertyPanel { } get edited(): boolean { - return this.refs.length === 2 && !this.existing; + return (this.refs.length > 0 || this.refs2.length > 0) && !this.existing; } } diff --git a/src/parametric/src/app/assembly/tree.ts b/src/parametric/src/app/assembly/tree.ts index 51ca59fc59..a8ddb0b540 100644 --- a/src/parametric/src/app/assembly/tree.ts +++ b/src/parametric/src/app/assembly/tree.ts @@ -1,7 +1,7 @@ // The design tree of an assembly: the assembly, its planes and origin, the // components (with (f) for fixed and (-) for under-defined ones, as in other -// CAD systems), the Mates folder and the exploded view steps. Same rows, -// keys and menus as the part tree. +// CAD systems), the Mates folder, the exploded view steps and the motion +// studies. Same rows, keys and menus as the part tree. import type { Id } from '../../model/types'; import { BASE_PLANE_NAMES } from '../../model/planes'; @@ -19,7 +19,7 @@ interface Row { label: string; icon: string; depth: number; - kind: 'root' | 'plane' | 'origin' | 'component' | 'folder' | 'mate' | 'step'; + kind: 'root' | 'plane' | 'origin' | 'component' | 'folder' | 'mate' | 'step' | 'study'; children?: boolean; expanded?: boolean; muted?: string; @@ -82,6 +82,17 @@ export class AssemblyTree { rows.push({ key: 'explode', item: null, label: 'Exploded View', icon: 'explode', depth: 1, kind: 'folder', children: true, expanded: open, muted: doc.exploded ? ' (exploded)' : ' (collapsed)' }); if (open || this.filter) for (const s of doc.explode) rows.push({ key: s.id, id: s.id, item: { kind: 'feature', id: s.id }, label: s.name, icon: 'explode', depth: 2, kind: 'step', muted: ` (${s.comps.length} ${s.comps.length === 1 ? 'component' : 'components'})` }); } + const studies = doc.studies ?? []; + if (studies.length) { + const open = !this.collapsed.has('studies'); + rows.push({ key: 'studies', item: null, label: 'Motion Studies', icon: 'motionStudy', depth: 1, kind: 'folder', children: true, expanded: open }); + if (open || this.filter) for (const s of studies) { + // Results computed for the assembly as it was before an edit are out of date. + const res = mode.motionOf(s.id, s); + const state = res ? (res.current ? (res.result.stop ? ', stopped early' : ', calculated') : ', out of date') : ''; + rows.push({ key: s.id, id: s.id, item: { kind: 'feature', id: s.id }, label: s.name, icon: 'motionStudy', depth: 2, kind: 'study', muted: ` (${s.motors.length} ${s.motors.length === 1 ? 'motor' : 'motors'}${state})` }); + } + } if (!this.filter) return rows; return rows.filter((r) => r.depth === 0 || r.label.toLowerCase().includes(this.filter)); } @@ -141,6 +152,7 @@ export class AssemblyTree { else if (r.key === 'part') app.openCommandMenu(['properties', 'rename', 'equations', 'insertComponent', 'billOfMaterials'], e.clientX, e.clientY, 'Assembly menu'); else if (r.key === 'mates') app.openCommandMenu(['mate'], e.clientX, e.clientY, 'Mates menu'); else if (r.key === 'explode') app.openCommandMenu(['explodedView', 'toggleExplode'], e.clientX, e.clientY, 'Exploded view menu'); + else if (r.key === 'studies') app.openCommandMenu(['motionStudy'], e.clientX, e.clientY, 'Motion studies menu'); }); el.addEventListener('pointerenter', () => { if (r.item) sel.setHover(r.item); }); el.addEventListener('pointerleave', () => { if (r.item) sel.setHover(null); }); diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 0f324e1811..5f601a40f4 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -741,3 +741,16 @@ a.icon-btn { text-decoration: none; } .cam-tools, .cam-post { grid-template-columns: minmax(0, 1fr); } .cam-gcode { height: 220px; } } + +/* Motion studies (assemblies) */ +.kin-play { gap: 6px; align-items: center; } +.kin-slider { width: 100%; accent-color: var(--accent); } +.kin-clock { font-family: var(--font-mono); } +.kin-motor-buttons { gap: 6px; justify-content: flex-end; margin-top: 6px; } +.kin-plot-box { margin: 6px 0; } +.kin-plot { display: block; width: 100%; height: auto; background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: crosshair; } +.kin-plot-frame { fill: none; stroke: var(--border); } +.kin-plot-zero { stroke: var(--border-strong); stroke-dasharray: 3 3; } +.kin-plot-line { fill: none; stroke: var(--accent); stroke-width: 1.5; stroke-linejoin: round; } +.kin-plot-cursor { stroke: var(--danger); stroke-width: 1; } +.kin-plot-text { fill: var(--text-2); font-size: 9px; font-family: var(--font-mono); } diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts new file mode 100644 index 0000000000..c43e9fa36b --- /dev/null +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -0,0 +1,358 @@ +import { type Page, expect, test } from '@playwright/test'; +import { openApp } from './helpers'; + +type A = import('../../src/app/app').App; + +const pts = (prefix: string, p: [number, number][]) => [ + ...p.map(([x, y], i) => ({ id: `${prefix}p${i}`, t: 'point', x, y })), + ...p.map((_, i) => ({ id: `${prefix}l${i}`, t: 'line', a: `${prefix}p${i}`, b: `${prefix}p${(i + 1) % p.length}` })), +]; +const extrude = (id: string, sketch: string, depth: number) => ({ id, name: id, type: 'extrude', sketch, cut: false, end: 'blind', depth, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }); +const circle = (id: string, x: number, y: number, r: number) => [{ id: `${id}c`, t: 'point', x, y }, { id, t: 'circle', c: `${id}c`, r }]; +/** A 100 × 40 × 10 plate with Ø20 holes 30 mm apart (for gears of Ø20 and Ø40 pitch). */ +const PLATE = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [...pts('r', [[0, 0], [100, 0], [100, 40], [0, 40]]), ...circle('h1', 20, 20, 10), ...circle('h2', 50, 20, 10)], constraints: [] }, + extrude('E1', 'S1', 10), +]; +const disc = (r: number) => [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: circle('k', 0, 0, r), constraints: [] }, + extrude('E1', 'S1', 5), +]; +/** A 100 × 10 × 10 bar (a rack, or a tab). */ +const BAR = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: pts('r', [[0, 0], [100, 0], [100, 10], [0, 10]]), constraints: [] }, + extrude('E1', 'S1', 10), +]; + +async function makePart(page: Page, name: string, features: unknown[]) { + await page.evaluate(async ({ name, features }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + await a.commands.get('new')!.run(); + a.store.change('Make part', (d) => { d.name = name; d.features = features as never; d.nextId = 100; }); + a.commands.run('save'); + }, { name, features }); + await expect(page).toHaveTitle(`${name} - Parametric`); +} + +async function insert(page: Page, name: string) { + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('insertComponent'); }); + const dlg = page.getByRole('dialog', { name: 'Insert Components' }); + await dlg.getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(dlg).toHaveCount(0); +} + +/** Waits until every listed component's faces are shown. */ +async function built(page: Page, names: string[]) { + await page.waitForFunction((names) => { + const a = (window as unknown as { __parametric: A }).__parametric; + return names.every((n) => { + const id = a.assembly?.doc.components.find((c) => c.name === n)?.id; + return !!id && a.faces.some((f) => f.feature === id); + }); + }, names); +} + +/** A face (by its name in the part) or edge of a component, as the graphics area picks it. */ +type Pick = { comp: string; face?: string; edge?: 'x' }; +async function picked(page: Page, p: Pick) { + return page.evaluate(({ comp, face, edge }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + const id = a.assembly!.doc.components.find((c) => c.name === comp)!.id; + if (edge) { + // A straight edge along x. + const index = a.edges.findIndex((e) => e.name.startsWith(`${id}#`) && e.type === 'line' && Math.abs(e.dir?.[0] ?? 0) > 0.99); + return { kind: 'edge' as const, index, name: a.edges[index].name }; + } + const index = a.faces.findIndex((f) => f.name === `${id}#${face}`); + return { kind: 'face' as const, index, name: a.faces[index].name }; + }, p); +} + +/** Selects in the graphics area before a command opens (as clicking faces does). */ +async function select(page: Page, picks: Pick[]) { + const items = await Promise.all(picks.map((p) => picked(page, p))); + await page.evaluate((items) => { (window as unknown as { __parametric: A }).__parametric.selection.set(items); }, items); +} + +/** A pick in the graphics area while a panel is open (what a click on the face does). */ +async function pick(page: Page, p: Pick) { + const item = await picked(page, p); + await page.evaluate((item) => { const a = (window as unknown as { __parametric: A }).__parametric; a.panel!.onPick(item, false); }, item); +} + +async function openMate(page: Page, type: string) { + await page.locator('.cm [data-cmd="mate"]').click(); + const pm = page.locator('.pm'); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption(type); + return pm; +} + +async function newAssemblyWith(page: Page, parts: [string, unknown[]][], comps: string[]) { + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + for (const [name, f] of parts) await makePart(page, name, f); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await expect(page.getByRole('tab', { name: 'Assembly' })).toBeVisible(); + for (const c of comps) await insert(page, c); +} + +test('hinges and a gear through the Mate panel, a motion study that plays and plots, saved and opened again', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + + // Hinges: the gear's round face in the plate's hole, its back face on the plate's front. + for (const [gear, hole] of [['Small<1>', 'E1:side:h1'], ['Large<1>', 'E1:side:h2']]) { + await select(page, [{ comp: gear, face: 'E1:side:k' }, { comp: 'Plate<1>', face: hole }]); + const pm = await openMate(page, 'hinge'); + await expect(pm.getByRole('group', { name: 'Concentric selections' })).toContainText(gear); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: gear, face: 'E1:cap0' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + } + await expect(tree.getByRole('treeitem', { name: /^Hinge2/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (2 DOF)'); + + // Gear: pitch diameters from the round faces (20 and 40). + await select(page, [{ comp: 'Small<1>', face: 'E1:side:k' }, { comp: 'Large<1>', face: 'E1:side:k' }]); + const pm = await openMate(page, 'gear'); + await expect(pm.getByRole('textbox', { name: 'Pitch diameter of the first gear' })).toHaveValue('20'); + await expect(pm.getByRole('textbox', { name: 'Pitch diameter of the second gear' })).toHaveValue('40'); + await expect(pm.getByRole('status').filter({ hasText: '1 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Gear1/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + + // Rotate the small gear by dragging: the large one turns half as far, the other way. + const turns = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const z = (n: string) => { const q = m.solved.get(m.doc.components.find((c) => c.name === n)!.id)!.q; return (2 * Math.atan2(q[2], q[3]) * 180) / Math.PI; }; + return { small: z('Small<1>'), large: z('Large<1>') }; + }); + const before = await turns(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const id = m.doc.components.find((c) => c.name === 'Small<1>')!.id; + let pl = new Map(m.solved); + for (let k = 1; k <= 4; k++) pl = m.dragSolve({ kind: 'rotate', body: id, q: [0, 0, Math.sin((k * 10 * Math.PI) / 360), Math.cos((k * 10 * Math.PI) / 360)] }, pl); + m.commitPlacements('Rotate component', pl); + }); + const after = await turns(); + expect(after.small - before.small).toBeGreaterThan(20); + expect(after.large - before.large).toBeCloseTo(-(after.small - before.small) / 2, 3); + + // A motion study: a rotary motor on the small gear at 90°/s for 4 s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await expect(pm.getByRole('button', { name: 'Calculate' })).toBeDisabled(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor axis' }).click(); + await pick(page, { comp: 'Small<1>', face: 'E1:side:k' }); + await expect(pm.getByRole('group', { name: 'Motor axis' })).toContainText('Small<1>'); + await pm.getByRole('textbox', { name: 'Speed' }).fill('90'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await expect(pm.getByRole('listitem').filter({ hasText: 'RotaryMotor1' })).toContainText('Small<1>: 90°/s'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('4'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 121 frames' })).toBeVisible(); + // It plays: the time moves on and the large gear turns. + const clock = pm.locator('.kin-clock'); + await expect(clock).toContainText('/ 4.00 s'); + await expect.poll(async () => Number((await clock.innerText()).split(' ')[0]), { timeout: 10_000 }).toBeGreaterThan(0.3); + await pm.getByRole('button', { name: 'Pause' }).click(); + await expect(pm.getByRole('button', { name: 'Play', exact: true })).toBeVisible(); + // Scrubbed to the end: the small gear turned 360°, the large one 180° back. + await pm.getByRole('button', { name: 'To the end' }).click(); + await expect(clock).toContainText('4.00 s / 4.00 s'); + const shown = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const z = (n: string) => { const q = m.shownPlacement(m.doc.components.find((c) => c.name === n)!.id)!.q; return (2 * Math.atan2(q[2], q[3]) * 180) / Math.PI; }; + // Both read in (-180°, 180°]: compared a full turn apart. + const d = z('Large<1>') - z('Small<1>') / -2; + return d - 360 * Math.round(d / 360); + }); + expect(Math.abs(shown)).toBeLessThan(1e-3); + // Plot the large gear's turn about Z. + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Component: Large<1>' }); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular displacement' }); + await pm.getByRole('combobox', { name: 'Vector component' }).selectOption({ label: 'Z' }); + const plot = pm.getByRole('img', { name: /Plot of Large<1> angular displacement Z/ }); + await expect(plot).toHaveAttribute('aria-label', /from -180 to 0/); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular velocity' }); + await expect(pm.getByRole('img', { name: /angular velocity Z \(°\/s\)/ })).toHaveAttribute('aria-label', /from -45 to -45/); + const download = page.waitForEvent('download'); + await pm.getByRole('button', { name: 'Download CSV' }).click(); + const { readFileSync } = await import('node:fs'); + const csv = new TextDecoder().decode(readFileSync(await (await download).path())).split('\n'); + expect(csv[0]).toContain('Time (s),Displacement X (mm)'); + expect(csv[0]).toContain('Angle Z (deg)'); + expect(csv).toHaveLength(122); + const col = csv[0].split(',').indexOf('Angle Z (deg)'); + expect(Number(csv[121].split(',')[col])).toBeCloseTo(-180, 3); + await pm.getByRole('button', { name: 'OK' }).click(); + const study = tree.getByRole('treeitem', { name: /^Motion Study1/ }); + await expect(study).toContainText('(1 motor, calculated)'); + + // Editing the assembly puts the results out of date; undo brings them back. + await tree.getByRole('treeitem', { name: /^Gear1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Reverse Direction' }).click(); + await expect(study).toContainText('out of date'); + await page.keyboard.press('Meta+z'); + await expect(study).toContainText('calculated'); + + // Saved and opened again: mates and study are kept. + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const name = (await page.title()).replace(' - Parametric', ''); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('new'); }); + await expect(page).toHaveTitle(/^Part\d+ - Parametric$/); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('open'); }); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(page).toHaveTitle(`${name} - Parametric`); + await expect(tree.getByRole('treeitem', { name: /^Gear1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /^Hinge1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /^Motion Study1 \(1 motor\)/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + // Opened from the tree, it calculates again. + await tree.getByRole('treeitem', { name: /^Motion Study1/ }).dblclick(); + await expect(pm.getByRole('listitem').filter({ hasText: 'RotaryMotor1' })).toBeVisible(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 121 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + + // The small gear's hinge limited to ±45° from where it is: the study stops there. + await tree.getByRole('treeitem', { name: /^Hinge1/ }).dblclick(); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('hinge'); + await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('45'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Hinge1'))).toMatchObject({ limit: { min: -45, max: 45 }, rel: { q: expect.any(Array) } }); + await expect(tree.getByRole('treeitem', { name: /^Motion Study1/ })).toBeVisible(); + await tree.getByRole('treeitem', { name: /^Motion Study1/ }).dblclick(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert').filter({ hasText: /Hinge1 reached its limit at 0\.5\d* s/ })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('limit, width, slot, screw and rack and pinion mates through the Mate panel; a study stops at a limit', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Small', disc(10)]], ['Plate', 'Bar', 'Small']); + await built(page, ['Plate<1>', 'Bar<1>', 'Small<1>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + const pm = page.locator('.pm'); + const suppress = async (name: RegExp) => { + await tree.getByRole('treeitem', { name }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect(tree.getByRole('treeitem', { name })).toHaveAttribute('aria-description', /Suppressed/); + }; + const noError = async (name: RegExp) => { + await expect(tree.getByRole('treeitem', { name })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name })).not.toHaveAttribute('aria-description', /Error/); + }; + + // Width: the bar centred between the plate's two ends. + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('width'); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl3' }); + await expect(pm.getByRole('group', { name: 'Tab selections' })).toHaveClass(/active/); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl3' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Width1/); + const barX = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + return m.solved.get(m.doc.components.find((c) => c.name === 'Bar<1>')!.id)!.p[0]; + }); + // The bar is as long as the plate: centred, it lines up with it. + expect(await barX()).toBeCloseTo(0, 4); + await suppress(/^Width1/); + + // A limit distance: the bar kept 5 to 15 mm in front of the plate. + await select(page, [{ comp: 'Plate<1>', face: 'E1:cap1' }, { comp: 'Bar<1>', face: 'E1:cap0' }]); + await openMate(page, 'distance'); + await pm.getByRole('checkbox', { name: /Limit the distance/ }).check(); + await pm.getByRole('textbox', { name: 'Maximum' }).fill('15'); + await pm.getByRole('textbox', { name: 'Maximum' }).press('Enter'); + await pm.getByRole('textbox', { name: 'Minimum' }).fill('5'); + await pm.getByRole('textbox', { name: 'Minimum' }).press('Enter'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds. 10 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^LimitDistance1/); + const gapZ = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + // The bar starts behind the plate's front face: the distance is on that side. + return Math.abs(m.solved.get(m.doc.components.find((c) => c.name === 'Bar<1>')!.id)!.p[2] - 10); + }); + const gap = await gapZ(); + expect(gap).toBeGreaterThan(5 - 1e-4); + expect(gap).toBeLessThan(15 + 1e-4); + // A linear motor pushing the bar away: the study stops at the limit. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('group', { name: 'Motor direction' }).click(); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap1' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert').filter({ hasText: 'LimitDistance1 reached its limit' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + await suppress(/^LimitDistance1/); + + // Slot: the small disc's round face between the plate's two holes (the slot's ends). + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slot'); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:h1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:h2' }); + await pick(page, { comp: 'Small<1>', face: 'E1:side:k' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds. 9 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Slot1/); + await suppress(/^Slot1/); + + // Screw: the disc in the first hole, 2 mm a turn, left-hand. + await select(page, [{ comp: 'Plate<1>', face: 'E1:side:h1' }, { comp: 'Small<1>', face: 'E1:side:k' }]); + await openMate(page, 'screw'); + await pm.getByRole('textbox', { name: 'Pitch (travel per turn)' }).fill('2'); + await pm.getByRole('textbox', { name: 'Pitch (travel per turn)' }).press('Enter'); + await pm.getByRole('group', { name: 'Thread' }).getByRole('button', { name: 'Left-hand' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Screw1/); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Screw1'))).toMatchObject({ type: 'screw', value: 2, reverse: true }); + await suppress(/^Screw1/); + + // Rack and pinion: the bar's straight edge and the disc's round face (picked the other way round). + await select(page, [{ comp: 'Bar<1>', edge: 'x' }, { comp: 'Small<1>', face: 'E1:side:k' }]); + await openMate(page, 'rackPinion'); + await expect(pm.getByRole('textbox', { name: 'Pinion pitch diameter' })).toHaveValue('20'); + await pm.getByRole('group', { name: 'Rack travel from' }).getByRole('button', { name: 'Travel per turn' }).click(); + await expect(pm.getByRole('textbox', { name: 'Rack travel per turn of the pinion' })).toHaveValue('62.832'); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Rack Pinion1/); + const rp = () => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Rack Pinion1')!); + // The pinion first, whichever was picked first. + expect((await rp()).a).toMatchObject({ face: { name: 'E1:side:k' } }); + expect(await rp()).toMatchObject({ by: 'revolution', value: 62.832 }); + await tree.getByRole('treeitem', { name: /^Rack Pinion1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Reverse Direction' }).click(); + expect((await rp()).reverse).toBe(true); + + // Edited from the tree: the panel shows what it has. + await tree.getByRole('treeitem', { name: /^Rack Pinion1/ }).dblclick(); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('rackPinion'); + await expect(pm.getByRole('checkbox', { name: 'Reverse the direction' })).toBeChecked(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From fd1963f34367f84421ca01761238617a37c1c700 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:57:08 -0700 Subject: [PATCH 004/116] Parametric: interference check over a motion study's frames Checks up to 40 frames spread over the motion with the worker's interference detection, lists the times where components overlap (a click goes to that frame), and puts the shown scene back afterwards. --- src/parametric/src/app/assembly/mode.ts | 43 ++++++++++--- .../src/app/assembly/motion-panel.ts | 62 +++++++++++++++++-- .../tests/e2e/assembly-kinematics.spec.ts | 7 +++ 3 files changed, 101 insertions(+), 11 deletions(-) diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index 39dbff62a6..153f4221a0 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -5,7 +5,7 @@ // allow. The design tree, ribbon and panels of assemblies are set up here. import type { FaceInfo, FeatureStatus } from '../../kernel/protocol'; -import type { AsmPartBuild, AsmPartResult } from '../../kernel/assembly'; +import type { AsmPartBuild, AsmPartResult, InterferencePair } from '../../kernel/assembly'; import { KernelRestartError } from '../../kernel/client'; import { type Quat, type Vec3, add, cross, dot, normalize, qAxisAngle, qMul, scale, sub } from '../../math/vec'; import { DocStore, parseDocument } from '../../model/document'; @@ -380,12 +380,7 @@ export class AssemblyMode { // The worker places the same components, in the same order, for measure, export and // interference, and the hidden ones too for mass properties (they are still in the assembly). this.sceneComps = all.map((it) => it.comp.id); - void app.kernel.assembly({ - op: 'scene', items: all.map((it) => { - const part = doc.parts.find((p) => p.id === it.comp.part)!; - return { part: this.key(part), m: placementMatrix(it.placement), name: it.comp.name, color: part.color, ...(it.comp.hidden ? { hidden: true } : {}) }; - }), - }).catch(() => undefined); + void app.kernel.assembly({ op: 'scene', items: this.sceneItems(all) }).catch(() => undefined); if (this.fitPending && model.bbox) { this.fitPending = false; app.viewport.zoomToFit(false, false); @@ -395,6 +390,15 @@ export class AssemblyMode { this.onShow(); } + /** The worker's scene of components placed as given. */ + private sceneItems(all: { comp: AsmComponent; placement: Placement }[]) { + const doc = this.doc; + return all.map((it) => { + const part = doc.parts.find((p) => p.id === it.comp.part)!; + return { part: this.key(part), m: placementMatrix(it.placement), name: it.comp.name, color: part.color, ...(it.comp.hidden ? { hidden: true } : {}) }; + }); + } + updateStatus() { const btn = this.app.shell.statusSketch; const a = this.analysis; @@ -705,6 +709,31 @@ export class AssemblyMode { return run.result; } + /** + * Interference over a study's motion: the worker's interference check on + * frames spread over it (at most `most`). The components the graphics area + * shows are put back in the worker's scene afterwards. Null when cancelled. + */ + async motionInterference(res: MotionResult, most: number, onProgress: (f: number) => void, cancelled: () => boolean): Promise<{ time: number; pairs: [Id, Id][] }[] | null> { + const n = res.frames.length; + const picks = [...new Set(Array.from({ length: Math.min(n, most) }, (_, k) => Math.round((k * (n - 1)) / Math.max(1, Math.min(n, most) - 1))))]; + const out: { time: number; pairs: [Id, Id][] }[] = []; + try { + for (const [k, i] of picks.entries()) { + const all = this.doc.components.filter((c) => !c.suppressed && this.geometryOf(c.part)).map((comp) => ({ comp, placement: res.frames[i].get(comp.id) ?? this.solved.get(comp.id) ?? comp.placement })); + await this.app.kernel.assembly({ op: 'scene', items: this.sceneItems(all) }); + const pairs = await this.app.kernel.assembly({ op: 'interference' }); + if (cancelled() || this.app.assembly !== this) return null; + const hit = pairs.filter((p) => !p.failed && p.volume > 1e-6).map((p) => [all[p.a].comp.id, all[p.b].comp.id] as [Id, Id]); + if (hit.length) out.push({ time: res.times[i], pairs: hit }); + onProgress((k + 1) / picks.length); + } + } finally { + if (this.app.assembly === this) this.show(); + } + return out; + } + dispose() { this.preview = null; this.explodePreview = null; diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index 614f5b1da2..c304d5a2fc 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -85,10 +85,60 @@ export class MotionStudyPanel extends PropertyPanel { if (this.motor) return this.renderMotor(); const res = this.result(); const out = [this.studySection(), this.motorsSection(), this.calcSection(res)]; - if (res && res.frames.length > 1) out.push(this.playSection(res), this.resultsSection(res)); + if (res && res.frames.length > 1) out.push(this.playSection(res), this.resultsSection(res), this.interferenceSection(res)); return out; } + // ---------- interference over the motion ---------- + + /** Frames checked for interference, for the results they were checked on. */ + private clashes: { result: MotionResult; list: { time: number; pairs: [Id, Id][] }[] } | null = null; + private checking = false; + + private interferenceSection(res: MotionResult): HTMLElement { + const items: HTMLElement[] = []; + if (this.checking) { + this.bar = h('progress', { max: '1', value: '0', 'aria-label': 'Interference check progress' }) as HTMLProgressElement; + items.push(h('p', { class: 'field-label', role: 'status' }, 'Checking frames for interference...'), this.bar); + } else { + const run = h('button', { class: 'btn small', type: 'button' }, icon('interference', 14), 'Check Interference'); + run.addEventListener('click', () => void this.checkInterference(res)); + items.push(h('p', { class: 'field-label' }, `Finds components that overlap in ${Math.min(INTERFERENCE_FRAMES, res.frames.length)} frames spread over the motion.`), run); + const c = this.clashes?.result === res ? this.clashes.list : null; + if (c && !c.length) items.push(h('p', { class: 'pm-msg info', role: 'status' }, 'No interference in the frames checked.')); + if (c?.length) { + const name = (id: Id) => this.mode.component(id)?.name ?? '?'; + const list = h('div', { class: 'file-list', role: 'list', 'aria-label': 'Interference over the motion' }); + for (const f of c) { + const b = h('button', { class: 'file-item', type: 'button' }, h('span', { 'aria-hidden': 'true', style: { color: 'var(--danger)' } }, icon('interference', 16)), + h('span', { class: 'txt' }, h('span', { class: 'n' }, `${f.time.toFixed(2)} s`), h('span', { class: 'meta' }, f.pairs.map(([a, b]) => `${name(a)} and ${name(b)}`).join('; ')))); + b.addEventListener('click', () => { this.play(false); this.t = f.time; this.showAt(f.time); }); + list.append(h('div', { class: 'file-row', role: 'listitem' }, b)); + } + items.push(h('p', { class: 'pm-msg warn', role: 'status' }, `Components overlap in ${c.length} of the frames checked.`), list); + } + } + return section('Interference', items, { collapsed: false }); + } + + private async checkInterference(res: MotionResult) { + const run = ++this.runs; + this.play(false); + this.checking = true; + this.app.refreshPanel(); + let list: { time: number; pairs: [Id, Id][] }[] | null = null; + try { + list = await this.mode.motionInterference(res, INTERFERENCE_FRAMES, (f) => { if (this.bar) this.bar.value = f; }, () => run !== this.runs || this.disposed); + } catch (e) { + if (!this.disposed) this.error = (e as Error).message; + } + this.checking = false; + if (this.disposed || run !== this.runs) return; + if (list) this.clashes = { result: res, list }; + this.app.refreshPanel(); + this.showAt(this.t); + } + private studySection(): HTMLElement { const num = (label: string, value: number, min: number, max: number, step: string, set: (v: number) => void) => { const input = h('input', { class: 'input', type: 'number', min: String(min), max: String(max), step, value: String(value), 'aria-label': label }) as HTMLInputElement; @@ -188,7 +238,7 @@ export class MotionStudyPanel extends PropertyPanel { slider.addEventListener('input', () => { this.play(false); this.t = (Number(slider.value) / 1000) * end; this.showAt(this.t); }); this.slider = slider; this.clock = h('div', { class: 'field-label kin-clock', 'aria-live': 'off' }); - const play = h('button', { class: 'btn small', type: 'button' }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; + const play = h('button', { class: 'btn small', type: 'button', disabled: this.checking }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; play.addEventListener('click', () => this.play(!this.playing)); this.playBtn = play; const toStart = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the start', onclick: () => { this.play(false); this.t = 0; this.showAt(0); } }, icon('upToLine', 16)); @@ -200,7 +250,8 @@ export class MotionStudyPanel extends PropertyPanel { private play(on: boolean) { const res = this.result(); - this.playing = on && !!res; + // Not while the worker's scene is moved frame by frame for the interference check. + this.playing = on && !!res && !this.checking; cancelAnimationFrame(this.raf); if (this.playBtn) this.playBtn.replaceChildren(icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play'); if (!this.playing || !res) return; @@ -226,7 +277,7 @@ export class MotionStudyPanel extends PropertyPanel { /** Shows the frame at time t (the nearest computed one). */ private showAt(t: number) { const res = this.result(); - if (!res || this.disposed) return; + if (!res || this.disposed || this.checking) return; const i = frameAt(res, t); this.mode.previewPlacements(res.frames[i]); const end = res.times[res.times.length - 1]; @@ -546,6 +597,9 @@ export class MotionStudyPanel extends PropertyPanel { } } +/** The most frames checked for interference (each is a boolean check of every pair in the worker). */ +const INTERFERENCE_FRAMES = 40; + const PLOT = { w: 280, h: 150, left: 44, right: 8, top: 8, bottom: 18 }; const plotX = (t: number, end: number) => PLOT.left + (t / Math.max(end, 1e-9)) * (PLOT.w - PLOT.left - PLOT.right); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index c43e9fa36b..a988e1fa2f 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -307,6 +307,13 @@ test('limit, width, slot, screw and rack and pinion mates through the Mate panel await pm.getByRole('button', { name: 'Add', exact: true }).click(); await pm.getByRole('button', { name: 'Calculate' }).click(); await expect(pm.getByRole('alert').filter({ hasText: 'LimitDistance1 reached its limit' })).toBeVisible(); + // The bar moves through the plate (where the width mate left it): interference over the motion lists the frames. + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(pm.getByRole('status').filter({ hasText: /Components overlap in \d+ of the frames checked/ })).toBeVisible({ timeout: 60_000 }); + const clashes = pm.getByRole('list', { name: 'Interference over the motion' }).getByRole('listitem'); + await expect(clashes.first()).toContainText(/Plate<1> and Bar<1>|Bar<1> and Plate<1>/); + await clashes.last().getByRole('button').click(); + await expect(pm.locator('.kin-clock')).toContainText(/^0\.\d\d s \//); await pm.getByRole('button', { name: 'Cancel' }).click(); await suppress(/^LimitDistance1/); From f3d6081c7c5b0101f1747de80ac430d6aba97460 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:57:35 -0700 Subject: [PATCH 005/116] Parametric: README for limit and mechanical mates and motion studies --- src/parametric/README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/parametric/README.md b/src/parametric/README.md index 7521feb18b..f1a2d5f696 100644 --- a/src/parametric/README.md +++ b/src/parametric/README.md @@ -53,8 +53,10 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to **Assemblies** - File > New Assembly. Insert Components places parts from your cloud, this browser or your device (a part file or a STEP model); insert a part several times for several instances (bracket<1>, bracket<2>). The first component is fixed; the others float. -- Mates: coincident, parallel, perpendicular, distance, angle, concentric, tangent and lock, between faces, edges and the assembly planes, with aligned or anti-aligned alignment and values that take equations. The Mates folder in the design tree edits, flips, suppresses and deletes them. The status bar shows whether the assembly is under, fully or over defined; conflicting mates are marked. -- Drag a component (Alt+drag, or Rotate Component, turns it): it moves only as its mates allow, so a lid on a hinge pin turns about the pin. Fixed components do not move. +- Mates: coincident, parallel, perpendicular, distance, angle, concentric, tangent and lock, between faces, edges and the assembly planes, with aligned or anti-aligned alignment and values that take equations. Distance and angle mates can be limited to a range instead of a value (the component moves freely between a minimum and a maximum). The Mates folder in the design tree edits, flips, suppresses and deletes them. The status bar shows whether the assembly is under, fully or over defined; conflicting mates are marked. +- Mechanical mates: hinge (concentric and coincident in one, with optional angle limits from where it was added), gear (two axes turning by a ratio of pitch diameters or teeth, reversible for internal gears), rack and pinion (the rack's travel by the pinion's pitch diameter or a distance per turn), screw (a nut travelling a pitch per turn, right- or left-hand), width (a tab centred in a groove) and slot (a pin travelling along a slot between its ends). Gear, rack and screw mates hold from wherever the components are when they are added, and their turns add up past a full turn. +- Drag a component (Alt+drag, or Rotate Component, turns it): it moves only as its mates allow, so a lid on a hinge pin turns about the pin, turning one gear turns the other, dragging a rack turns its pinion, and a drag stops at a mate's limits. Fixed components do not move. +- Motion studies (Motion Study): rotary motors (a constant speed in °/s or rpm, or oscillating), linear motors (constant speed or oscillating) and mate drivers (a distance or angle mate's value at a constant speed, harmonic, or ramped between two values) drive the mechanism for a duration at a frame rate. Frames are calculated without freezing the interface (with progress, and a Cancel); the study stops and says why when a limit is reached or the mechanism locks up. Play, pause, loop and scrub through the motion; plot a point of a component (its displacement, velocity, acceleration, or its turn, angular velocity and acceleration) or what a mate measures against time, download the results as CSV, and check the frames for interference. Studies are listed in the design tree and saved with the assembly; editing the assembly puts their results out of date. - Exploded view steps, interference detection with the overlapping volumes, a bill of materials (item, part, quantity, material; copy or download as CSV), mass properties with each part's material, measure, section view, and STEP (components as named solids) and STL export of the whole assembly. - An assembly references its part files and keeps a copy of each, so it opens even when a part file is moved, shared or downloaded. Open Part edits a component's part; save it and go back, and the assembly takes the change (Update Parts reads the part files again). @@ -118,7 +120,7 @@ npm run build # type check, license check, production build in dist/ | Area | Where | Notes | |---|---|---| | Document model | `src/model` | Plain JSON parts: features, sketches, variables. Undo/redo by snapshots. Parameters may be expressions. | -| Assemblies | `src/model/assembly.ts`, `src/assembly`, `src/app/assembly`, `src/kernel/assembly.ts` | Assembly documents embed their parts as blobs. Rigid-body mate solver: damped least squares over mate residuals, six degrees of freedom per floating component, rank analysis for the definition, conflicts found by adding mates one at a time. Components' meshes are placed on the main thread (dragging needs no kernel call); the worker keeps the placed solids for measure, interference, mass, projection and export. | +| Assemblies | `src/model/assembly.ts`, `src/assembly`, `src/app/assembly`, `src/kernel/assembly.ts` | Assembly documents embed their parts as blobs. Rigid-body mate solver: damped least squares over mate residuals, six degrees of freedom per floating component, rank analysis for the definition, conflicts found by adding mates one at a time. Limits are one-sided residuals, left out of the rank analysis. Gear, rack and pinion and screw mates relate the motion since the start of each solve, and every solve starts where the last ended, so turns accumulate. Motion studies (`src/assembly/motion.ts`) solve frame by frame from the frame before with the motors as hard goals; results are finite differences of the frames. Components' meshes are placed on the main thread (dragging needs no kernel call); the worker keeps the placed solids for measure, interference, mass, projection and export. | | Sketch solver | `src/sketch/solver.ts` | Minimum-norm damped Gauss-Newton per independent cluster, with a rank analysis for degrees of freedom and redundant or conflicting constraints. | | Profiles | `src/sketch/profiles.ts` | Planar face finding on the sketch graph; nested loops alternate material and holes. | | Geometry kernel | `src/kernel` | OpenCascade (WebAssembly) in a Web Worker. Each feature is cached under a hash of everything before it, so edits rebuild only what changed. Faces are named after the feature and sketch entity that created them. | From 0895afa5d29b0120332b07ccae9603cdd3b56888 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:58:53 -0700 Subject: [PATCH 006/116] Parametric: motion study styles beside the CAM playback rules; accessibility checks of the new panels --- src/parametric/src/styles/app.css | 25 +++++++++---------- .../tests/e2e/assembly-kinematics.spec.ts | 14 +++++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 5f601a40f4..06014eca19 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -716,6 +716,18 @@ a.icon-btn { text-decoration: none; } .cam-play { gap: 6px; align-items: center; } .cam-slider { width: 100%; accent-color: var(--accent); } .cam-clock { font-family: var(--font-mono); } +/* Motion studies (assemblies) */ +.kin-play { gap: 6px; align-items: center; } +.kin-slider { width: 100%; accent-color: var(--accent); } +.kin-clock { font-family: var(--font-mono); } +.kin-motor-buttons { gap: 6px; justify-content: flex-end; margin-top: 6px; } +.kin-plot-box { margin: 6px 0; } +.kin-plot { display: block; width: 100%; height: auto; background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: crosshair; } +.kin-plot-frame { fill: none; stroke: var(--border); } +.kin-plot-zero { stroke: var(--border-strong); stroke-dasharray: 3 3; } +.kin-plot-line { fill: none; stroke: var(--accent); stroke-width: 1.5; stroke-linejoin: round; } +.kin-plot-cursor { stroke: var(--danger); stroke-width: 1; } +.kin-plot-text { fill: var(--text-2); font-size: 9px; font-family: var(--font-mono); } .cam-legend { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: var(--fs-sm); color: var(--text-2); } .cam-legend span { display: inline-flex; align-items: center; gap: 5px; } .cam-legend i { width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-strong); } @@ -741,16 +753,3 @@ a.icon-btn { text-decoration: none; } .cam-tools, .cam-post { grid-template-columns: minmax(0, 1fr); } .cam-gcode { height: 220px; } } - -/* Motion studies (assemblies) */ -.kin-play { gap: 6px; align-items: center; } -.kin-slider { width: 100%; accent-color: var(--accent); } -.kin-clock { font-family: var(--font-mono); } -.kin-motor-buttons { gap: 6px; justify-content: flex-end; margin-top: 6px; } -.kin-plot-box { margin: 6px 0; } -.kin-plot { display: block; width: 100%; height: auto; background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: crosshair; } -.kin-plot-frame { fill: none; stroke: var(--border); } -.kin-plot-zero { stroke: var(--border-strong); stroke-dasharray: 3 3; } -.kin-plot-line { fill: none; stroke: var(--accent); stroke-width: 1.5; stroke-linejoin: round; } -.kin-plot-cursor { stroke: var(--danger); stroke-width: 1; } -.kin-plot-text { fill: var(--text-2); font-size: 9px; font-family: var(--font-mono); } diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index a988e1fa2f..467b6da8d4 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -87,6 +87,18 @@ async function openMate(page: Page, type: string) { return pm; } +/** Serious and critical accessibility violations on the page (axe). */ +async function axeViolations(page: Page): Promise { + await page.addScriptTag({ path: 'node_modules/axe-core/axe.min.js' }); + return page.evaluate(async () => { + // @ts-expect-error axe is injected above + const r = await window.axe.run(document, { resultTypes: ['violations'] }); + return r.violations + .filter((v: { impact: string }) => v.impact === 'serious' || v.impact === 'critical') + .map((v: { id: string; nodes: { target: string[] }[] }) => `${v.id}: ${v.nodes.slice(0, 3).map((n) => n.target.join(' ')).join(', ')}`); + }); +} + async function newAssemblyWith(page: Page, parts: [string, unknown[]][], comps: string[]) { await page.getByRole('button', { name: /New part/ }).click(); await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); @@ -112,6 +124,7 @@ test('hinges and a gear through the Mate panel, a motion study that plays and pl await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); await pick(page, { comp: gear, face: 'E1:cap0' }); await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + if (gear === 'Small<1>') expect(await axeViolations(page)).toEqual([]); await pm.getByRole('button', { name: 'OK' }).click(); } await expect(tree.getByRole('treeitem', { name: /^Hinge2/ })).toBeVisible(); @@ -185,6 +198,7 @@ test('hinges and a gear through the Mate panel, a motion study that plays and pl await expect(plot).toHaveAttribute('aria-label', /from -180 to 0/); await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular velocity' }); await expect(pm.getByRole('img', { name: /angular velocity Z \(°\/s\)/ })).toHaveAttribute('aria-label', /from -45 to -45/); + expect(await axeViolations(page)).toEqual([]); const download = page.waitForEvent('download'); await pm.getByRole('button', { name: 'Download CSV' }).click(); const { readFileSync } = await import('node:fs'); From f80a3a4b675ff9a8c8d25cd08baa67dfb05dc984 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:59:32 -0700 Subject: [PATCH 007/116] Parametric: motion studies solve only what the motors move; motor summaries in the document's units --- src/parametric/src/app/assembly/motion-panel.ts | 15 +++++++-------- src/parametric/src/assembly/motion.ts | 4 +++- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index c304d5a2fc..c9ece22aa4 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -178,10 +178,14 @@ export class MotionStudyPanel extends PropertyPanel { } private describeMotor(m: MotionMotor): string { - const v = (p: Param | undefined) => (p === undefined ? '?' : typeof p === 'string' ? p : String(Math.round(p * 1000) / 1000)); - const unit = m.kind === 'rotary' ? (m.rpm ? ' rpm' : '°/s') : m.kind === 'linear' ? ' mm/s' : '/s'; + // Lengths in the document's units (linear motors, and mate drivers of distance mates). + const u = UNIT_SYSTEMS[this.mode.doc.units]; + const mt = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate) : undefined; + const lengthy = m.kind === 'linear' || mt?.type === 'distance'; + const v = (p: Param | undefined, len = lengthy) => (p === undefined ? '?' : typeof p === 'string' ? p : String(Math.round((len ? p / u.scale : p) * 1000) / 1000)); + const unit = m.kind === 'rotary' ? (m.rpm ? ' rpm' : '°/s') : lengthy ? ` ${u.length}/s` : '°/s'; const what = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate)?.name ?? '?' : m.ref && 'comp' in m.ref ? this.mode.component(m.ref.comp)?.name ?? '?' : '?'; - const how = m.profile === 'constant' ? `${v(m.speed)}${unit}` : m.profile === 'oscillate' ? `±${v(m.amplitude)} at ${v(m.frequency)} Hz` : `${v(m.from)} to ${v(m.to)}`; + const how = m.profile === 'constant' ? `${v(m.speed)}${unit}` : m.profile === 'oscillate' ? `±${v(m.amplitude)} at ${v(m.frequency, false)} Hz` : `${v(m.from)} to ${v(m.to)}`; return `${KIND_LABELS[m.kind]}, ${what}: ${how}${m.reverse ? ', reversed' : ''}`; } @@ -554,11 +558,6 @@ export class MotionStudyPanel extends PropertyPanel { this.stale(); } - onPick(item: SelItem, additive: boolean): boolean { - if (!this.activeBox) return false; - return this.activeBox.toggle(item, additive); - } - ok(): boolean { if (this.motor) { this.finishMotor(true); if (this.motor) return false; } this.play(false); diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index fa05c833c5..626c5b8d73 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -114,8 +114,10 @@ export class MotionRun { this.dt = setup.duration / this.count; // Only what the motors move is solved: the mates of the components they drive and those linked to them. const moving = new Set(); + const floating = new Set(setup.bodies.filter((b) => !b.fixed).map((b) => b.id)); for (const m of setup.motors) { - const ids = m.body ? [m.body] : setup.mates.filter((x) => x.id === m.mate).flatMap(mateBodies); + // (A fixed component links nothing: from it, every mate to the ground would be solved.) + const ids = (m.body ? [m.body] : setup.mates.filter((x) => x.id === m.mate).flatMap(mateBodies)).filter((id) => floating.has(id)); for (const id of ids) for (const x of matesMoving(id, setup.bodies, setup.mates)) moving.add(x); } this.solverMates = setup.mates.filter((x) => moving.has(x)); From 3fa50ce244cedc4c87a80d915f7108fe9258bd6c Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:03:39 -0700 Subject: [PATCH 008/116] Parametric: static study model (fixtures, loads, mesh setting) saved with the part --- src/parametric/src/model/document.ts | 4 +- src/parametric/src/model/fea.ts | 203 +++++++++++++++++++++++++++ src/parametric/src/model/types.ts | 3 + 3 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 src/parametric/src/model/fea.ts diff --git a/src/parametric/src/model/document.ts b/src/parametric/src/model/document.ts index 559c25aaf1..df138a6a9d 100644 --- a/src/parametric/src/model/document.ts +++ b/src/parametric/src/model/document.ts @@ -13,6 +13,7 @@ import { validSketch } from './validate-sketch'; import { validDrawing } from './validate-drawing'; import { camIds, normalizeCam } from './cam'; import { normalizeMaterial } from './materials'; +import { parseStudy, studyIds } from './fea'; import { solveSketch } from '../sketch/solver'; import { hasExternal } from '../sketch/external'; @@ -87,11 +88,12 @@ export function parseDocument(text: string): PartDocument { if (doc.drawing != null && !validDrawing(doc.drawing)) throw new Error('The part file is damaged (invalid drawing).'); // Machining data that cannot be read is dropped rather than refusing the part. if (doc.cam != null) doc.cam = normalizeCam(doc.cam); + if (doc.study != null) doc.study = parseStudy(doc.study); for (const f of doc.features) if (typeof f.name !== 'string' || !f.name) f.name = f.id; // New feature ids must not collide with existing ones, even when the file's // counter is missing or stale. let maxId = 0; - for (const f of [...doc.features, ...doc.variables, ...camIds(doc.cam).map((id) => ({ id }))]) { + for (const f of [...doc.features, ...doc.variables, ...camIds(doc.cam).map((id) => ({ id })), ...studyIds(doc.study).map((id) => ({ id }))]) { const m = /^[a-z]+(\d+)$/i.exec(String(f?.id ?? '')); const suffix = m ? Number(m[1]) : NaN; // Unsafe suffixes cannot be emitted by the numeric allocator. diff --git a/src/parametric/src/model/fea.ts b/src/parametric/src/model/fea.ts new file mode 100644 index 0000000000..b042dd4fe8 --- /dev/null +++ b/src/parametric/src/model/fea.ts @@ -0,0 +1,203 @@ +// Static stress analysis study kept with the part: fixtures and loads on +// faces (by reference, so they follow the part through dimension changes) +// and the mesh setting. Values are stored in millimetres, newtons, +// megapascals (N/mm^2) and mm/s^2, whatever the display units. Results are +// not stored: they are computed again from the part and the study. + +import type { AxisRef, FaceRef, Id, PartDocument, UnitSystem } from './types'; +import { UNIT_SYSTEMS } from './units'; + +/** A direction: a base axis, a straight edge (or the axis of a circular one), or a face (its normal, or a cylinder's axis). */ +export type FeaDir = Exclude; + +export type FixtureType = 'fixed' | 'roller' | 'hinge'; + +export interface FeaFixture { + id: Id; + name: string; + type: FixtureType; + faces: FaceRef[]; + suppressed?: boolean; +} + +/** A total force spread over the faces: normal to them (dir null, pressing on them) or along a direction. */ +export interface FeaForce { + id: Id; + name: string; + type: 'force'; + faces: FaceRef[]; + /** Newtons. */ + value: number; + dir: FeaDir | null; + flip: boolean; + suppressed?: boolean; +} + +/** A pressure on the faces, pushing into them (flip: pulling). */ +export interface FeaPressure { + id: Id; + name: string; + type: 'pressure'; + faces: FaceRef[]; + /** MPa (N/mm^2). */ + value: number; + flip: boolean; + suppressed?: boolean; +} + +/** The part's own weight: the acceleration of gravity along a direction. */ +export interface FeaGravity { + id: Id; + name: string; + type: 'gravity'; + /** mm/s^2. */ + value: number; + dir: FeaDir; + flip: boolean; + suppressed?: boolean; +} + +export type FeaLoad = FeaForce | FeaPressure | FeaGravity; +export type FeaLoadType = FeaLoad['type']; + +export interface StaticStudy { + id: Id; + name: string; + fixtures: FeaFixture[]; + loads: FeaLoad[]; + /** Mesh fineness from 0 (coarse: twice the automatic element size) to 1 (fine: half of it). */ + mesh: { fineness: number }; +} + +export const FIXTURE_LABELS: Record = { fixed: 'Fixed', roller: 'Roller/Slider', hinge: 'Fixed Hinge' }; +export const LOAD_LABELS: Record = { force: 'Force', pressure: 'Pressure', gravity: 'Gravity' }; +export const FIXTURE_ICONS: Record = { fixed: 'feaFixed', roller: 'feaRoller', hinge: 'feaHinge' }; +export const LOAD_ICONS: Record = { force: 'feaForce', pressure: 'feaPressure', gravity: 'feaGravity' }; + +/** Standard gravity, mm/s^2. */ +export const GRAVITY = 9806.65; + +export function newStudy(id: Id): StaticStudy { + return { id, name: 'Static Study', fixtures: [], loads: [], mesh: { fineness: 0.5 } }; +} + +/** Element size for a fineness, from the automatic size (no larger than the part's walls allow). */ +export function elementSizeFor(auto: number, max: number, fineness: number): number { + return Math.min(max, auto * 2 ** (1 - 2 * Math.max(0, Math.min(1, fineness)))); +} + +// ---------- units ---------- + +export interface FeaUnits { + force: string; + /** Newtons per display force unit. */ + forceScale: number; + stress: string; + /** MPa per display stress unit. */ + stressScale: number; + accel: string; + /** mm/s^2 per display acceleration unit. */ + accelScale: number; + length: string; + /** mm per display length unit. */ + lengthScale: number; +} + +export function feaUnits(units: UnitSystem): FeaUnits { + const u = UNIT_SYSTEMS[units]; + if (units === 'IPS') return { force: 'lbf', forceScale: 4.4482216152605, stress: 'psi', stressScale: 0.00689475729316836, accel: 'in/s²', accelScale: 25.4, length: u.length, lengthScale: u.scale }; + return { force: 'N', forceScale: 1, stress: 'MPa', stressScale: 1, accel: 'm/s²', accelScale: 1000, length: u.length, lengthScale: u.scale }; +} + +// ---------- reading files ---------- + +const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const vec3 = (v: unknown) => Array.isArray(v) && v.length === 3 && v.every(finite); +const str = (v: unknown): v is string => typeof v === 'string'; + +function faceRefOf(v: unknown): FaceRef | null { + if (!isObj(v) || !str(v.name) || !isObj(v.sig)) return null; + const s = v.sig; + if (!str(s.type) || !vec3(s.c) || !finite(s.area) || (s.n != null && !vec3(s.n))) return null; + return { name: v.name, sig: { type: s.type, c: s.c as FaceRef['sig']['c'], area: s.area, ...(s.n != null ? { n: s.n as FaceRef['sig']['c'] } : {}) } }; +} + +function dirOf(v: unknown): FeaDir | null { + if (!isObj(v)) return null; + if (v.kind === 'base') return v.axis === 'x' || v.axis === 'y' || v.axis === 'z' ? { kind: 'base', axis: v.axis } : null; + if (v.kind === 'face') { const face = faceRefOf(v.face); return face ? { kind: 'face', face } : null; } + if (v.kind === 'edge' && isObj(v.edge) && str(v.edge.name) && isObj(v.edge.sig)) { + const s = v.edge.sig; + if (!str(s.type) || !vec3(s.m) || !finite(s.len)) return null; + return { kind: 'edge', edge: { name: v.edge.name, sig: { type: s.type, m: s.m as [number, number, number], len: s.len } } }; + } + return null; +} + +function facesOf(v: unknown): FaceRef[] | null { + if (!Array.isArray(v)) return null; + const out = v.map(faceRefOf); + return out.every((f): f is FaceRef => !!f) ? out : null; +} + +const bad = (what: string): never => { throw new Error(`The part file is damaged (invalid study: ${what}).`); }; + +/** + * Checks a study read from a file, strictly: anything that is not a study + * as this version writes it is refused with a message (a damaged study is + * not silently changed into another one). + */ +export function parseStudy(raw: unknown): StaticStudy { + if (!isObj(raw) || !str(raw.id) || !raw.id || !str(raw.name)) bad('identity'); + const r = raw as Record; + if (!Array.isArray(r.fixtures) || !Array.isArray(r.loads) || !isObj(r.mesh)) bad('lists'); + const ids = new Set([r.id as string]); + const ident = (o: Record, what: string) => { + if (!str(o.id) || !o.id || ids.has(o.id) || !str(o.name)) bad(`${what} identity`); + ids.add(o.id as string); + if (o.suppressed !== undefined && typeof o.suppressed !== 'boolean') bad(`${what} suppression`); + return { id: o.id as string, name: o.name as string, ...(o.suppressed ? { suppressed: true } : {}) }; + }; + const fixtures = (r.fixtures as unknown[]).map((f): FeaFixture => { + if (!isObj(f)) return bad('fixture'); + const base = ident(f, 'fixture'); + if (f.type !== 'fixed' && f.type !== 'roller' && f.type !== 'hinge') bad('fixture type'); + const faces = facesOf(f.faces) ?? bad('fixture faces'); + return { ...base, type: f.type as FixtureType, faces }; + }); + const loads = (r.loads as unknown[]).map((l): FeaLoad => { + if (!isObj(l)) return bad('load'); + const base = ident(l, 'load'); + if (!finite(l.value)) bad('load value'); + if (typeof l.flip !== 'boolean') bad('load direction'); + const value = l.value as number, flip = l.flip as boolean; + if (l.type === 'force') { + const faces = facesOf(l.faces) ?? bad('force faces'); + const dir = l.dir == null ? null : (dirOf(l.dir) ?? bad('force direction')); + return { ...base, type: 'force', faces, value, dir, flip }; + } + if (l.type === 'pressure') return { ...base, type: 'pressure', faces: facesOf(l.faces) ?? bad('pressure faces'), value, flip }; + if (l.type === 'gravity') return { ...base, type: 'gravity', value, dir: dirOf(l.dir) ?? bad('gravity direction'), flip }; + return bad('load type'); + }); + const m = r.mesh as Record; + if (!finite(m.fineness) || m.fineness < 0 || m.fineness > 1) bad('mesh'); + return { id: r.id as string, name: r.name as string, fixtures, loads, mesh: { fineness: m.fineness as number } }; +} + +/** Ids used by a study (so new ids never collide with them). */ +export function studyIds(s: StaticStudy | null | undefined): string[] { + return s ? [s.id, ...s.fixtures.map((f) => f.id), ...s.loads.map((l) => l.id)] : []; +} + +export function studyOf(doc: PartDocument): StaticStudy | null { + return doc.study ?? null; +} + +/** Name for a new fixture or load: the label followed by the first number not taken. */ +export function nextStudyName(s: StaticStudy, label: string): string { + const used = new Set([...s.fixtures, ...s.loads].map((x) => x.name.toLowerCase())); + const base = label.replace(/[^A-Za-z]/g, ''); + for (let i = 1; ; i++) if (!used.has(`${base}-${i}`.toLowerCase())) return `${base}-${i}`; +} diff --git a/src/parametric/src/model/types.ts b/src/parametric/src/model/types.ts index 7fc30e5aa0..1a97919273 100644 --- a/src/parametric/src/model/types.ts +++ b/src/parametric/src/model/types.ts @@ -6,6 +6,7 @@ import type { Vec2, Vec3, Frame } from '../math/vec'; import type { BaseFlangeFeature, EdgeFlangeFeature, HemFeature, SketchedBendFeature } from './sheetmetal'; import type { CamDoc } from './cam'; +import type { StaticStudy } from './fea'; export type Id = string; @@ -628,6 +629,8 @@ export interface PartDocument { drawing?: DrawingDoc | null; /** Machining: tools, setups and operations (see model/cam.ts), if any. */ cam?: CamDoc | null; + /** Static stress analysis: fixtures, loads and mesh setting (see model/fea.ts), if any. */ + study?: StaticStudy | null; nextId: number; created: number; modified: number; From 255baf9ba056674977d323c009955a00e7dd6dc0 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:03:39 -0700 Subject: [PATCH 009/116] Parametric: tetrahedral mesher for stress analysis (lattice stuffing, edge recovery, quadratic nodes) --- src/parametric/src/fea/mesher.ts | 888 ++++++++++++++++++++++++ src/parametric/src/fea/surface.ts | 378 ++++++++++ src/parametric/src/kernel/build.ts | 26 +- src/parametric/src/kernel/client.ts | 7 +- src/parametric/src/kernel/protocol.ts | 13 + src/parametric/src/kernel/worker.ts | 6 + src/parametric/tests/fea-mesher.test.ts | 91 +++ 7 files changed, 1407 insertions(+), 2 deletions(-) create mode 100644 src/parametric/src/fea/mesher.ts create mode 100644 src/parametric/src/fea/surface.ts create mode 100644 src/parametric/tests/fea-mesher.test.ts diff --git a/src/parametric/src/fea/mesher.ts b/src/parametric/src/fea/mesher.ts new file mode 100644 index 0000000000..f2b6eccfe2 --- /dev/null +++ b/src/parametric/src/fea/mesher.ts @@ -0,0 +1,888 @@ +// Volume mesher: 10-node tetrahedra filling the part. +// +// 1. Isosurface stuffing (after Labelle and Shewchuk, 2007): a body-centred +// cubic lattice is laid over the part; lattice points are classified inside +// or outside by exact ray crossing counts, lattice edges that cross the +// boundary are cut where they cross it, lattice points close to a cut are +// moved onto it ("warped"), and every lattice tetrahedron is clipped to the +// part with fixed stencils. Quadrilaterals shared by neighbours are split +// through their lowest numbered corner, so neighbours always agree. +// 2. Feature recovery: the stuffed boundary passes through the part's +// surface but cuts across its edges and corners. Mesh vertices are moved +// onto the corners and then onto the edges between faces, so that every +// boundary triangle lies on one B-rep face (faces carrying loads and +// fixtures are covered exactly). Moves that would spoil a tetrahedron are +// refused. +// 3. Interior vertices are smoothed where that improves the worst element +// around them. +// 4. Quadratic nodes are added at edge midpoints; those on the boundary are +// put on the curved surface (or on the edge between two faces). +// +// The lattice is uniform: features thinner than about the element size are +// meshed coarsely or missed, which the volume check reports. + +import { SurfaceIndex } from './surface'; + +export interface MeshOptions { + /** Target element size (lattice spacing), mm. */ + size: number; + progress?: (stage: string, fraction: number) => void; + /** Development: logs statistics after each stage. */ + debug?: (msg: string) => void; +} + +export interface TetMesh { + /** xyz of every node: corner nodes first, then midside nodes. */ + nodes: Float64Array; + /** Number of corner nodes. */ + corners: number; + /** 10 nodes per element: corners 0-3, then midside nodes of edges 01, 12, 20, 03, 13, 23. */ + tets: Int32Array; + /** 6 nodes per boundary triangle: corners, then midside nodes of edges 01, 12, 20 (outward normal by the right hand rule). */ + tris: Int32Array; + /** B-rep face of each boundary triangle. */ + triFace: Int32Array; + stats: MeshStats; +} + +export interface MeshStats { + size: number; + nodes: number; + elements: number; + /** Volume of the mesh and of the boundary it was made from (mm^3). */ + volume: number; + surfaceVolume: number; + /** Mean ratio quality (1 regular, 0 flat): worst and average. */ + minQuality: number; + meanQuality: number; + /** Smallest and largest dihedral angle of the corner tetrahedra (degrees). */ + minDihedral: number; + maxDihedral: number; + /** Elements whose quadratic shape had to be straightened (their surface stays flat). */ + straightened: number; + /** Boundary triangles whose face could not be told from their corners. */ + unassigned: number; + /** Separate pieces of mesh. */ + pieces: number; +} + +const ALPHA_LONG = 0.24917; +const ALPHA_SHORT = 0.41189; + +/** Edges of a 10-node tetrahedron (corner pairs), in midside node order. */ +export const TET_EDGES: [number, number][] = [[0, 1], [1, 2], [2, 0], [0, 3], [1, 3], [2, 3]]; + +export class MeshError extends Error {} + +export function tetVolume(P: ArrayLike, a: number, b: number, c: number, d: number): number { + const ax = P[a * 3], ay = P[a * 3 + 1], az = P[a * 3 + 2]; + const bx = P[b * 3] - ax, by = P[b * 3 + 1] - ay, bz = P[b * 3 + 2] - az; + const cx = P[c * 3] - ax, cy = P[c * 3 + 1] - ay, cz = P[c * 3 + 2] - az; + const dx = P[d * 3] - ax, dy = P[d * 3 + 1] - ay, dz = P[d * 3 + 2] - az; + return (bx * (cy * dz - cz * dy) - by * (cx * dz - cz * dx) + bz * (cx * dy - cy * dx)) / 6; +} + +/** Mean ratio quality of a tetrahedron: 1 for a regular one, 0 (or negative) for flat (inverted) ones. */ +export function tetQuality(P: ArrayLike, a: number, b: number, c: number, d: number): number { + const v = tetVolume(P, a, b, c, d); + const l2 = (i: number, j: number) => (P[i * 3] - P[j * 3]) ** 2 + (P[i * 3 + 1] - P[j * 3 + 1]) ** 2 + (P[i * 3 + 2] - P[j * 3 + 2]) ** 2; + const s = l2(a, b) + l2(a, c) + l2(a, d) + l2(b, c) + l2(b, d) + l2(c, d); + if (!(s > 0)) return 0; + return (12 * Math.sign(v) * Math.cbrt(9 * v * v)) / s; +} + +function dihedrals(P: ArrayLike, n: number[]): number[] { + const p = (i: number) => [P[n[i] * 3], P[n[i] * 3 + 1], P[n[i] * 3 + 2]]; + const sub = (a: number[], b: number[]) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + const cr = (a: number[], b: number[]) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + const out: number[] = []; + for (const [i, j] of TET_EDGES) { + const [k, l] = [0, 1, 2, 3].filter((q) => q !== i && q !== j); + const e = sub(p(j), p(i)); + const n1 = cr(e, sub(p(k), p(i))), n2 = cr(e, sub(p(l), p(i))); + const c = (n1[0] * n2[0] + n1[1] * n2[1] + n1[2] * n2[2]) / (Math.hypot(...n1) * Math.hypot(...n2) || 1); + out.push((Math.acos(Math.max(-1, Math.min(1, c))) * 180) / Math.PI); + } + return out; +} + +/** Default element size for a part: fine enough for its walls, bounded so the problem stays solvable in a browser. */ +export function defaultElementSize(volume: number, area: number, diag: number): number { + // 2V/A is the thickness of a plate (and a third of a cube's side). + const wall = area > 0 ? (2 * volume) / area : diag / 10; + const h = Math.min(diag / 25, wall / 1.5); + // About 48 degrees of freedom per h^3 of a quadratic BCC mesh; keep the default near 150k. + const floor = Math.cbrt(Math.max(volume, 1e-9) / 3000); + return Math.max(h, floor, diag / 400); +} + +/** Largest element size that still meshes the part's walls (about their thickness). */ +export function maxElementSize(volume: number, area: number, diag: number): number { + const wall = area > 0 ? (2 * volume) / area : diag / 10; + return Math.max(wall, defaultElementSize(volume, area, diag)); +} + +/** Estimated degrees of freedom of a mesh of the given element size. */ +export function estimateDofs(volume: number, size: number): number { + return Math.round((48 * volume) / size ** 3); +} + +export function meshSolid(surf: SurfaceIndex, opts: MeshOptions): TetMesh { + const h = opts.size; + const progress = opts.progress ?? (() => {}); + if (!(h > 0) || !surf.nt) throw new MeshError('The part has no solid to mesh.'); + const ext = [0, 1, 2].map((d) => surf.max[d] - surf.min[d]); + // Lattice origin a cell and an odd fraction outside the part: no lattice point lands exactly on a flat face. + const frac = [0.1374, 0.2653, 0.3917]; + const o = [0, 1, 2].map((d) => surf.min[d] - h * (1 + frac[d])); + const n = [0, 1, 2].map((d) => Math.ceil((ext[d] + 2 * h) / h) + 1); + const [nx, ny, nz] = n; + const NB = (nx + 1) * (ny + 1) * (nz + 1); + const NR = nx * ny * nz; + const NV = NB + NR; + if (NV > 60e6) throw new MeshError('The elements are too small for this part. Choose a coarser mesh.'); + const bId = (i: number, j: number, k: number) => i + (nx + 1) * (j + (ny + 1) * k); + const rId = (i: number, j: number, k: number) => NB + i + nx * (j + ny * k); + const latticePos = (v: number, out: number[]) => { + if (v < NB) { + const i = v % (nx + 1), r = (v - i) / (nx + 1), j = r % (ny + 1), k = (r - j) / (ny + 1); + out[0] = o[0] + i * h; out[1] = o[1] + j * h; out[2] = o[2] + k * h; + } else { + const w = v - NB, i = w % nx, r = (w - i) / nx, j = r % ny, k = (r - j) / ny; + out[0] = o[0] + (i + 0.5) * h; out[1] = o[1] + (j + 0.5) * h; out[2] = o[2] + (k + 0.5) * h; + } + return out; + }; + + // ---- classify lattice points ---- + progress('Classifying lattice points', 0); + const sign = new Int8Array(NV).fill(-1); + const scan = (yz: (j: number, k: number) => [number, number], count: number, xAt: (i: number) => number, id: (i: number, j: number, k: number) => number, nj: number, nk: number) => { + for (let k = 0; k < nk; k++) { + for (let j = 0; j < nj; j++) { + const [y, z] = yz(j, k); + const { x } = surf.xCrossings(y, z); + if (!x.length) continue; + // Points before the first crossing are outside; each crossing flips. + let c = 0; + for (let i = 0; i < count; i++) { + const xi = xAt(i); + while (c < x.length && x[c] <= xi) c++; + if (c & 1) sign[id(i, j, k)] = 1; + } + } + } + }; + scan((j, k) => [o[1] + j * h, o[2] + k * h], nx + 1, (i) => o[0] + i * h, bId, ny + 1, nz + 1); + scan((j, k) => [o[1] + (j + 0.5) * h, o[2] + (k + 0.5) * h], nx, (i) => o[0] + (i + 0.5) * h, rId, ny, nz); + + // ---- neighbours of a lattice point: [vertex, long edge?] ---- + const neighbours = (v: number, out: number[]): number => { + let m = 0; + if (v < NB) { + const i = v % (nx + 1), r = (v - i) / (nx + 1), j = r % (ny + 1), k = (r - j) / (ny + 1); + if (i > 0) out[m++] = bId(i - 1, j, k); + if (i < nx) out[m++] = bId(i + 1, j, k); + if (j > 0) out[m++] = bId(i, j - 1, k); + if (j < ny) out[m++] = bId(i, j + 1, k); + if (k > 0) out[m++] = bId(i, j, k - 1); + if (k < nz) out[m++] = bId(i, j, k + 1); + const long = m; + for (let c = 0; c < 8; c++) { + const a = i - 1 + (c & 1), b = j - 1 + ((c >> 1) & 1), d = k - 1 + ((c >> 2) & 1); + if (a >= 0 && b >= 0 && d >= 0 && a < nx && b < ny && d < nz) out[m++] = rId(a, b, d); + } + return m * 16 + long; + } + const w = v - NB, i = w % nx, r = (w - i) / nx, j = r % ny, k = (r - j) / ny; + if (i > 0) out[m++] = rId(i - 1, j, k); + if (i < nx - 1) out[m++] = rId(i + 1, j, k); + if (j > 0) out[m++] = rId(i, j - 1, k); + if (j < ny - 1) out[m++] = rId(i, j + 1, k); + if (k > 0) out[m++] = rId(i, j, k - 1); + if (k < nz - 1) out[m++] = rId(i, j, k + 1); + const long = m; + for (let c = 0; c < 8; c++) out[m++] = bId(i + (c & 1), j + ((c >> 1) & 1), k + ((c >> 2) & 1)); + return m * 16 + long; + }; + + // ---- cut points ---- + progress('Cutting the lattice', 0.15); + const ekey = (a: number, b: number) => (a < b ? a * NV + b : b * NV + a); + const cutIndex = new Map(); + const cutPos: number[] = []; + const cutTri: number[] = []; + const nb: number[] = new Array(14); + const pa = [0, 0, 0], pb = [0, 0, 0]; + for (let v = 0; v < NV; v++) { + if (sign[v] !== 1) continue; + const m = neighbours(v, nb) >> 4; + latticePos(v, pa); + for (let q = 0; q < m; q++) { + const w = nb[q]; + if (sign[w] !== -1) continue; + latticePos(w, pb); + const hit = surf.segmentHit(pa, pb); + let p: number[], tri: number; + if (hit) { + p = [pa[0] + (pb[0] - pa[0]) * hit.t, pa[1] + (pb[1] - pa[1]) * hit.t, pa[2] + (pb[2] - pa[2]) * hit.t]; + tri = hit.tri; + } else { + // A crossing too close to a triangle edge for the segment test: the nearest boundary point to the edge's middle. + const mid = [(pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2, (pa[2] + pb[2]) / 2]; + const c = surf.closest(mid, h * 2); + if (!c) { p = mid; tri = -1; } else { + const dx = pb[0] - pa[0], dy = pb[1] - pa[1], dz = pb[2] - pa[2]; + const t = Math.max(0.05, Math.min(0.95, ((c.p[0] - pa[0]) * dx + (c.p[1] - pa[1]) * dy + (c.p[2] - pa[2]) * dz) / (dx * dx + dy * dy + dz * dz))); + p = [pa[0] + dx * t, pa[1] + dy * t, pa[2] + dz * t]; + tri = c.tri; + } + } + cutIndex.set(ekey(v, w), cutTri.length); + cutPos.push(p[0], p[1], p[2]); + cutTri.push(tri); + } + } + + // ---- warp lattice points onto cuts close to them ---- + progress('Warping', 0.3); + const warped = new Map(); + const candidates = new Set(); + for (const k of cutIndex.keys()) { const a = Math.floor(k / NV); candidates.add(a); candidates.add(k - a * NV); } + for (const v of [...candidates].sort((a, b) => a - b)) { + const meta = neighbours(v, nb); + const m = meta >> 4, long = meta & 15; + latticePos(v, pa); + let best = -1, bd = Infinity; + for (let q = 0; q < m; q++) { + const ci = cutIndex.get(ekey(v, nb[q])); + if (ci === undefined) continue; + latticePos(nb[q], pb); + const L = Math.hypot(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]); + const d = Math.hypot(cutPos[ci * 3] - pa[0], cutPos[ci * 3 + 1] - pa[1], cutPos[ci * 3 + 2] - pa[2]); + if (d < (q < long ? ALPHA_LONG : ALPHA_SHORT) * L && d < bd) { bd = d; best = ci; } + } + if (best < 0) continue; + warped.set(v, { p: [cutPos[best * 3], cutPos[best * 3 + 1], cutPos[best * 3 + 2]], tri: cutTri[best] }); + sign[v] = 0; + for (let q = 0; q < m; q++) cutIndex.delete(ekey(v, nb[q])); + } + + // ---- stuff the lattice tetrahedra ---- + progress('Filling', 0.4); + // Node references: lattice points (< NV), cut points (NV + cut), Steiner points (NV + cuts + s). + const NC = cutTri.length; + const steiner: number[] = []; + const out: number[] = []; + let coned = 0; + const refPos = (r: number, dst: number[], at: number) => { + if (r < NV) { + const w = warped.get(r); + if (w) { dst[at] = w.p[0]; dst[at + 1] = w.p[1]; dst[at + 2] = w.p[2]; return; } + latticePos(r, pa); + dst[at] = pa[0]; dst[at + 1] = pa[1]; dst[at + 2] = pa[2]; + } else if (r < NV + NC) { + const c = r - NV; + dst[at] = cutPos[c * 3]; dst[at + 1] = cutPos[c * 3 + 1]; dst[at + 2] = cutPos[c * 3 + 2]; + } else { + const s = r - NV - NC; + dst[at] = steiner[s * 3]; dst[at + 1] = steiner[s * 3 + 1]; dst[at + 2] = steiner[s * 3 + 2]; + } + }; + const tmp = new Array(12).fill(0); + const vol4 = (a: number, b: number, c: number, d: number) => { + refPos(a, tmp, 0); refPos(b, tmp, 3); refPos(c, tmp, 6); refPos(d, tmp, 9); + return tetVolume(tmp, 0, 1, 2, 3); + }; + const cut = (p: number, m: number) => { + const c = cutIndex.get(ekey(p, m)); + if (c === undefined) throw new MeshError('The mesher lost a boundary crossing.'); + return NV + c; + }; + /** Emits sub-tetrahedra of one convex piece; they must all have one orientation, else the piece is coned from its centroid. */ + const emit = (tets: number[][], faces: number[][] | null) => { + const vols = tets.map((t) => vol4(t[0], t[1], t[2], t[3])); + const scale = Math.max(...vols.map(Math.abs)); + const pos = vols.every((v) => v > 1e-9 * scale), neg = vols.every((v) => v < -1e-9 * scale); + if (pos || neg || !faces) { + tets.forEach((t, i) => { if (vols[i] < 0) out.push(t[0], t[2], t[1], t[3]); else if (vols[i] > 0) out.push(t[0], t[1], t[2], t[3]); }); + return; + } + // Cone the faces from the centroid of the piece's corners. + const corners = [...new Set(faces.flat())]; + const c = [0, 0, 0]; + for (const r of corners) { refPos(r, tmp, 0); c[0] += tmp[0]; c[1] += tmp[1]; c[2] += tmp[2]; } + const s = NV + NC + steiner.length / 3; + steiner.push(c[0] / corners.length, c[1] / corners.length, c[2] / corners.length); + const cone = faces.map((f) => [f[0], f[1], f[2], s]); + const cv = cone.map((t) => vol4(t[0], t[1], t[2], t[3])); + coned++; + cone.forEach((t, i) => { if (cv[i] < 0) out.push(t[0], t[2], t[1], t[3]); else if (cv[i] > 0) out.push(t[0], t[1], t[2], t[3]); }); + }; + /** A quadrilateral (cyclic) as two triangles split through its lowest reference. */ + const quad = (q: number[]): number[][] => { + const m = q.indexOf(Math.min(...q)); + return m % 2 === 0 ? [[q[0], q[1], q[2]], [q[0], q[2], q[3]]] : [[q[1], q[2], q[3]], [q[1], q[3], q[0]]]; + }; + const prism = (a: number, b: number, c: number, d: number, e: number, f: number) => { + // Rotate and turn over until the lowest reference is a (Dompierre et al. 1999). + let P = [a, b, c, d, e, f]; + const m = P.indexOf(Math.min(...P)); + if (m >= 3) P = [P[3], P[4], P[5], P[0], P[1], P[2]]; + const r = m % 3; + P = [P[r], P[(r + 1) % 3], P[(r + 2) % 3], P[3 + r], P[3 + (r + 1) % 3], P[3 + (r + 2) % 3]]; + const [A, B, C, D, E, F] = P; + const tets = Math.min(B, F) < Math.min(C, E) ? [[A, B, C, F], [A, B, F, E], [A, E, F, D]] : [[A, B, C, E], [A, E, C, F], [A, E, F, D]]; + const faces = [[A, B, C], [D, E, F], ...quad([A, B, E, D]), ...quad([B, C, F, E]), ...quad([C, A, D, F])]; + emit(tets, faces); + }; + const pyramid = (q: number[], apex: number) => { + const base = quad(q); + emit(base.map((t) => [t[0], t[1], t[2], apex]), [...base, [q[0], q[1], apex], [q[1], q[2], apex], [q[2], q[3], apex], [q[3], q[0], apex]]); + }; + const centroid = [0, 0, 0]; + const stuff = (t: number[]) => { + const P: number[] = [], Z: number[] = [], M: number[] = []; + for (const v of t) (sign[v] > 0 ? P : sign[v] < 0 ? M : Z).push(v); + if (!P.length) { + if (Z.length !== 4) return; + // Four boundary points: inside if its middle is. + centroid[0] = centroid[1] = centroid[2] = 0; + for (const v of t) { refPos(v, tmp, 0); centroid[0] += tmp[0] / 4; centroid[1] += tmp[1] / 4; centroid[2] += tmp[2] / 4; } + if (surf.inside(centroid)) emit([t], null); + return; + } + if (!M.length) { emit([t], null); return; } + if (P.length === 1) { + const p = P[0]; + if (M.length === 3) emit([[p, cut(p, M[0]), cut(p, M[1]), cut(p, M[2])]], null); + else if (M.length === 2) emit([[p, Z[0], cut(p, M[0]), cut(p, M[1])]], null); + else emit([[p, Z[0], Z[1], cut(p, M[0])]], null); + } else if (P.length === 2) { + const [p0, p1] = P; + if (M.length === 2) prism(p0, cut(p0, M[0]), cut(p0, M[1]), p1, cut(p1, M[0]), cut(p1, M[1])); + else pyramid([p0, p1, cut(p1, M[0]), cut(p0, M[0])], Z[0]); + } else { + const m = M[0]; + prism(P[0], P[1], P[2], cut(P[0], m), cut(P[1], m), cut(P[2], m)); + } + }; + const four = [0, 0, 0, 0]; + const cells = [[0, 0], [-1, 0], [-1, -1], [0, -1]]; + for (let d = 0; d < 3; d++) { + const d1 = (d + 1) % 3, d2 = (d + 2) % 3; + const lim = [nx, ny, nz]; + for (let k = 0; k <= nz; k++) for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) { + const idx = [i, j, k]; + if (idx[d] >= lim[d]) continue; + const b0 = bId(i, j, k); + const e = [i, j, k]; e[d]++; + const b1 = bId(e[0], e[1], e[2]); + const r: number[] = []; + for (const [a, b] of cells) { + const c = [i, j, k]; c[d1] += a; c[d2] += b; + if (c[0] < 0 || c[1] < 0 || c[2] < 0 || c[0] >= nx || c[1] >= ny || c[2] >= nz) break; + r.push(rId(c[0], c[1], c[2])); + } + if (r.length < 4) continue; + if (sign[b0] < 0 && sign[b1] < 0 && r.every((v) => sign[v] < 0)) continue; + for (let q = 0; q < 4; q++) { + four[0] = b0; four[1] = b1; four[2] = r[q]; four[3] = r[(q + 1) % 4]; + stuff(four); + } + } + } + if (!out.length) throw new MeshError('The mesh is empty: the elements are too large for this part. Choose a finer mesh.'); + + // ---- compact the nodes ---- + progress('Recovering edges', 0.55); + const refMap = new Map(); + const tets = new Int32Array(out.length); + const posList: number[] = []; + const triOf: number[] = []; + for (let q = 0; q < out.length; q++) { + const r = out[q]; + let id = refMap.get(r); + if (id === undefined) { + id = triOf.length; + refMap.set(r, id); + refPos(r, tmp, 0); + posList.push(tmp[0], tmp[1], tmp[2]); + triOf.push(r < NV ? (warped.get(r)?.tri ?? -1) : r < NV + NC ? cutTri[r - NV] : -1); + } + tets[q] = id; + } + const W = new WorkMesh(posList, Array.from(tets), h); + const qstat = (label: string) => { + if (!opts.debug) return; + let mq = Infinity, bad = 0; + for (let t = 0; t < W.nt; t++) { const q = W.quality(t); mq = Math.min(mq, q); if (q < 0.2) bad++; } + opts.debug(`${label}: min quality ${mq.toFixed(3)}, below 0.2: ${bad} of ${W.nt}, coned ${coned}, nodes ${W.nn}`); + }; + qstat('stuffed'); + { + const bt = boundaryOf(W.typed()); + for (const v of bt.tris) W.onB[v] = 1; + } + // Labels: the faces a boundary vertex is on. + for (let v = 0; v < W.nn; v++) { + if (!W.onB[v]) continue; + if (triOf[v] >= 0) { W.labels[v] = [surf.face[triOf[v]]]; continue; } + const c = surf.closest(W.pos(v), h); + W.labels[v] = c ? [surf.face[c.tri]] : []; + } + + // ---- corners ---- + const bverts: number[] = []; + for (let v = 0; v < W.nn; v++) if (W.onB[v]) bverts.push(v); + const vgrid = new PointGrid(W.P, bverts, h); + for (const c of surf.corners) { + const cp = surf.vertex(c.v); + const near = vgrid.near(cp, h * 0.9).filter((v) => !W.locked[v] && W.labels[v].some((f) => c.faces.includes(f))); + near.sort((a, b) => dist2(W.P, a, cp) - dist2(W.P, b, cp)); + for (const v of near.slice(0, 4)) { + if (W.move(v, cp, 0.1)) { W.locked[v] = 1; W.labels[v] = [...c.faces]; break; } + } + } + + // ---- edges between faces ---- + const disjoint = (a: number[], b: number[]) => !a.some((x) => b.includes(x)); + /** Faces a, b of two vertices' labels that meet along an edge of the part. */ + const seamOf = (u: number, w: number): [number, number] | null => { + for (const fa of W.labels[u]) for (const fb of W.labels[w]) if (fa >= 0 && fb >= 0 && fa !== fb && surf.adjacent(fa, fb)) return [fa, fb]; + return null; + }; + for (let pass = 0; pass < 6; pass++) { + const edges: { u: number; w: number; a: number; b: number; d2: number }[] = []; + forBoundaryEdges(boundaryOf(W.typed()).tris, (u, w) => { + if (!disjoint(W.labels[u], W.labels[w])) return; + const s = seamOf(u, w); + if (!s) return; + const m = [(W.P[u * 3] + W.P[w * 3]) / 2, (W.P[u * 3 + 1] + W.P[w * 3 + 1]) / 2, (W.P[u * 3 + 2] + W.P[w * 3 + 2]) / 2]; + const q = surf.closestOnSeam(s[0], s[1], m); + if (q && q.d2 < h * h) edges.push({ u, w, a: s[0], b: s[1], d2: q.d2 }); + }); + if (!edges.length) break; + edges.sort((p, q) => p.d2 - q.d2); + let moved = 0, split = 0, refused = 0; + for (const e of edges) { + const { u, w, a, b } = e; + // Still a crossing edge (an earlier move may have settled it)? + if (!disjoint(W.labels[u], W.labels[w]) || !W.hasEdge(u, w)) continue; + // Move the end nearer the seam onto it, else the other end. + const ends = [u, w].filter((v) => !W.locked[v]).map((v) => ({ v, q: surf.closestOnSeam(a, b, W.pos(v))! })).filter((x) => x.q && x.q.d2 < h * h).sort((p, q) => p.q.d2 - q.q.d2); + let done = false; + for (const x of ends) { + if (W.move(x.v, x.q.p, 0.12)) { W.locked[x.v] = 1; W.labels[x.v] = [a, b]; moved++; done = true; break; } + } + if (done) continue; + // Neither end can go: split the edge and put the new vertex on the seam. + const m = [(W.P[u * 3] + W.P[w * 3]) / 2, (W.P[u * 3 + 1] + W.P[w * 3 + 1]) / 2, (W.P[u * 3 + 2] + W.P[w * 3 + 2]) / 2]; + const q = surf.closestOnSeam(a, b, m); + if (!q) continue; + const x = W.split(u, w); + W.onB[x] = 1; + if (W.move(x, q.p, 0.05)) { W.locked[x] = 1; W.labels[x] = [a, b]; split++; continue; } + // Partly there is still better than across the corner. + const half = [(m[0] + q.p[0]) / 2, (m[1] + q.p[1]) / 2, (m[2] + q.p[2]) / 2]; + W.move(x, half, 0.05); + const c = surf.closest(W.pos(x), h, new Set([a, b])); + W.labels[x] = c ? [surf.face[c.tri]] : [a]; + refused++; + } + opts.debug?.(`pass ${pass}: ${edges.length} crossing edges, ${moved} moved, ${split} split, ${refused} left`); + if (!moved && !split) break; + } + + qstat('snapped'); + if (opts.debug) { + let open = 0; + forBoundaryEdges(boundaryOf(W.typed()).tris, (u, w) => { if (disjoint(W.labels[u], W.labels[w])) open++; }); + opts.debug(`crossing edges left: ${open}`); + } + // ---- smooth interior vertices ---- + progress('Improving elements', 0.65); + W.smooth(4); + qstat('smoothed'); + + // Elements that ended up flat are dropped. + const ideal = (h ** 3) / 12; + const lin = W.typed(); + const P = lin.P, nn = lin.nn, labels = W.labels; + const keep: number[] = []; + for (let t = 0; t < lin.nt; t++) if (tetVolume(P, lin.tets[t * 4], lin.tets[t * 4 + 1], lin.tets[t * 4 + 2], lin.tets[t * 4 + 3]) > 1e-9 * ideal) keep.push(t); + let T4 = lin.tets; + if (keep.length < lin.nt) { + T4 = new Int32Array(keep.length * 4); + keep.forEach((t, i) => T4.set(lin.tets.subarray(t * 4, t * 4 + 4), i * 4)); + } + const bnd = boundaryOf({ P, tets: T4, nn, nt: T4.length / 4 }); + const NT = T4.length / 4; + + // ---- faces of boundary triangles ---- + const B = bnd.tris; + const nb3 = B.length / 3; + const triFace = new Int32Array(nb3).fill(-1); + let unassigned = 0; + for (let f = 0; f < nb3; f++) { + const a = B[f * 3], b = B[f * 3 + 1], c = B[f * 3 + 2]; + for (const v of [a, b, c]) if (!labels[v].length) { const q = surf.closest([P[v * 3], P[v * 3 + 1], P[v * 3 + 2]], h * 2); labels[v] = q ? [surf.face[q.tri]] : [-1]; } + const common = labels[a].filter((x) => x >= 0 && labels[b].includes(x) && labels[c].includes(x)); + if (common.length === 1) { triFace[f] = common[0]; continue; } + const cen = [(P[a * 3] + P[b * 3] + P[c * 3]) / 3, (P[a * 3 + 1] + P[b * 3 + 1] + P[c * 3 + 1]) / 3, (P[a * 3 + 2] + P[b * 3 + 2] + P[c * 3 + 2]) / 3]; + const q = surf.closest(cen, h * 2, common.length ? new Set(common) : null) ?? surf.closest(cen, h * 4); + triFace[f] = q ? surf.face[q.tri] : -1; + if (!common.length) unassigned++; + } + + // ---- quadratic nodes ---- + progress('Adding midside nodes', 0.75); + const edgeMap = new Map(); + const mid: number[] = []; + const T10 = new Int32Array(NT * 10); + const eKey = (a: number, b: number) => (a < b ? a * nn + b : b * nn + a); + for (let t = 0; t < NT; t++) { + for (let k = 0; k < 4; k++) T10[t * 10 + k] = T4[t * 4 + k]; + TET_EDGES.forEach(([i, j], e) => { + const a = T4[t * 4 + i], b = T4[t * 4 + j]; + const key = eKey(a, b); + let m = edgeMap.get(key); + if (m === undefined) { + m = nn + mid.length / 3; + edgeMap.set(key, m); + mid.push((P[a * 3] + P[b * 3]) / 2, (P[a * 3 + 1] + P[b * 3 + 1]) / 2, (P[a * 3 + 2] + P[b * 3 + 2]) / 2); + } + T10[t * 10 + 4 + e] = m; + }); + } + const N = new Float64Array(P.length + mid.length); + N.set(P); + N.set(mid, P.length); + const straight = new Float64Array(mid); + // Boundary midside nodes onto the curved surface: the faces of the triangles beside the edge. + const edgeFaces = new Map(); + for (let f = 0; f < nb3; f++) { + for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) { + const key = eKey(B[f * 3 + i], B[f * 3 + j]); + let l = edgeFaces.get(key); + if (!l) edgeFaces.set(key, (l = [])); + if (triFace[f] >= 0 && !l.includes(triFace[f])) l.push(triFace[f]); + } + } + const movedMid: number[] = []; + for (const [key, faces] of edgeFaces) { + const m = edgeMap.get(key); + if (m === undefined || !faces.length) continue; + const a = Math.floor(key / nn), b = key - a * nn; + const p = [N[m * 3], N[m * 3 + 1], N[m * 3 + 2]]; + const len = Math.sqrt(dist2(N, a, [N[b * 3], N[b * 3 + 1], N[b * 3 + 2]])); + let q: number[] | null = null; + // An edge along the seam of two faces stays on the seam (both its ends are on it). + const seam = faces.length === 2 ? faces : []; + if (seam.length === 2 && labels[a].includes(seam[0]) && labels[a].includes(seam[1]) && labels[b].includes(seam[0]) && labels[b].includes(seam[1])) { + const s = surf.closestOnSeam(seam[0], seam[1], p); + if (s && s.d2 < (len * 0.5) ** 2) q = s.p; + } + if (!q && faces.length === 1) { + const c = surf.closest(p, len * 0.5, new Set(faces)); + if (c) q = c.p; + } + if (!q) continue; + N[m * 3] = q[0]; N[m * 3 + 1] = q[1]; N[m * 3 + 2] = q[2]; + movedMid.push(m); + } + // Curved elements must stay valid: straighten those with a non-positive Jacobian anywhere. + progress('Checking elements', 0.85); + let straightened = 0; + for (let pass = 0; pass < 4; pass++) { + let bad = 0; + for (let t = 0; t < NT; t++) { + if (quadraticValid(N, T10, t)) continue; + bad++; + for (let k = 4; k < 10; k++) { + const m = T10[t * 10 + k], s = (m - nn) * 3; + N[m * 3] = straight[s]; N[m * 3 + 1] = straight[s + 1]; N[m * 3 + 2] = straight[s + 2]; + } + } + straightened += bad; + if (!bad) break; + } + + // Boundary triangles with their midside nodes. + const tris = new Int32Array(nb3 * 6); + for (let f = 0; f < nb3; f++) { + const a = B[f * 3], b = B[f * 3 + 1], c = B[f * 3 + 2]; + tris.set([a, b, c, edgeMap.get(eKey(a, b))!, edgeMap.get(eKey(b, c))!, edgeMap.get(eKey(c, a))!], f * 6); + } + + // ---- statistics ---- + progress('Statistics', 0.95); + let minQ = Infinity, sumQ = 0, minD = 180, maxD = 0; + for (let t = 0; t < NT; t++) { + const n4 = [T4[t * 4], T4[t * 4 + 1], T4[t * 4 + 2], T4[t * 4 + 3]]; + const q = tetQuality(P, n4[0], n4[1], n4[2], n4[3]); + minQ = Math.min(minQ, q); sumQ += q; + for (const d of dihedrals(P, n4)) { minD = Math.min(minD, d); maxD = Math.max(maxD, d); } + } + let volume = 0; + for (let t = 0; t < NT; t++) volume += quadraticVolume(N, T10, t); + return { + nodes: N, corners: nn, tets: T10, tris, triFace, + stats: { + size: h, nodes: N.length / 3, elements: NT, volume, surfaceVolume: surf.volume(), minQuality: minQ, meanQuality: sumQ / NT, + minDihedral: minD, maxDihedral: maxD, straightened, unassigned, pieces: countPieces(T4, nn), + }, + }; +} + +// ---------- helpers ---------- + +function dist2(P: ArrayLike, v: number, p: ArrayLike): number { + return (P[v * 3] - p[0]) ** 2 + (P[v * 3 + 1] - p[1]) ** 2 + (P[v * 3 + 2] - p[2]) ** 2; +} + +interface LinearMesh { P: Float64Array; tets: Int32Array; nn: number; nt: number } + +/** Boundary triangles (faces of one tetrahedron only), oriented outward. */ +function boundaryOf(m: LinearMesh): { tris: Int32Array } { + const { tets, nn } = m; + const nt = tets.length / 4; + const faces = new Map(); + // Faces opposite each corner, ordered so their normal points out of a positive tetrahedron. + const F = [[1, 2, 3], [0, 3, 2], [0, 1, 3], [0, 2, 1]]; + const out: number[] = []; + const seen = new Map(); + void faces; + for (let t = 0; t < nt; t++) { + for (const f of F) { + const a = tets[t * 4 + f[0]], b = tets[t * 4 + f[1]], c = tets[t * 4 + f[2]]; + const s = [a, b, c].sort((x, y) => x - y); + const key = `${s[0]},${s[1]},${s[2]}`; + const prev = seen.get(key); + if (prev === undefined) seen.set(key, out.length / 3); + else seen.set(key, -1); + out.push(a, b, c); + } + } + void nn; + const tris: number[] = []; + for (const idx of seen.values()) if (idx >= 0) tris.push(out[idx * 3], out[idx * 3 + 1], out[idx * 3 + 2]); + return { tris: Int32Array.from(tris) }; +} + +function forBoundaryEdges(tris: Int32Array, fn: (a: number, b: number) => void) { + const seen = new Set(); + for (let f = 0; f < tris.length; f += 3) { + for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) { + const a = tris[f + i], b = tris[f + j]; + const key = a < b ? `${a},${b}` : `${b},${a}`; + if (seen.has(key)) continue; + seen.add(key); + fn(a, b); + } + } +} + +export function vertexTets(m: LinearMesh): { start: Int32Array; items: Int32Array } { + const { tets, nn } = m; + const nt = tets.length / 4; + const start = new Int32Array(nn + 1); + for (let q = 0; q < tets.length; q++) start[tets[q] + 1]++; + for (let i = 0; i < nn; i++) start[i + 1] += start[i]; + const fill = start.slice(); + const items = new Int32Array(tets.length); + for (let t = 0; t < nt; t++) for (let k = 0; k < 4; k++) items[fill[tets[t * 4 + k]]++] = t; + return { start, items }; +} + +function countPieces(tets: Int32Array, nn: number): number { + const parent = new Int32Array(nn).map((_, i) => i); + const find = (x: number): number => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }; + const used = new Uint8Array(nn); + for (let t = 0; t < tets.length; t += 4) { + for (let k = 0; k < 4; k++) used[tets[t + k]] = 1; + const a = find(tets[t]); + for (let k = 1; k < 4; k++) { const b = find(tets[t + k]); if (a !== b) parent[b] = a; } + } + let n = 0; + for (let i = 0; i < nn; i++) if (used[i] && find(i) === i) n++; + return n; +} + +/** Derivatives of the 10-node shape functions in volume coordinates (L1, L2, L3; L0 = 1 - L1 - L2 - L3) at a point. */ +export function quadDerivs(l1: number, l2: number, l3: number, out: Float64Array) { + const l0 = 1 - l1 - l2 - l3; + // dN/dL1, dN/dL2, dN/dL3 for each node (3 per node). + // Corners: N0 = L0(2L0-1), Ni = Li(2Li-1). + const d0 = 1 - 4 * l0; + out.fill(0); + out[0] = d0; out[1] = d0; out[2] = d0; + out[3] = 4 * l1 - 1; + out[7] = 4 * l2 - 1; + out[11] = 4 * l3 - 1; + // Edges 01, 12, 20, 03, 13, 23: N = 4 La Lb. + // 01: 4 L0 L1 + out[12] = 4 * (l0 - l1); out[13] = -4 * l1; out[14] = -4 * l1; + // 12: 4 L1 L2 + out[15] = 4 * l2; out[16] = 4 * l1; out[17] = 0; + // 20: 4 L2 L0 + out[18] = -4 * l2; out[19] = 4 * (l0 - l2); out[20] = -4 * l2; + // 03: 4 L0 L3 + out[21] = -4 * l3; out[22] = -4 * l3; out[23] = 4 * (l0 - l3); + // 13: 4 L1 L3 + out[24] = 4 * l3; out[25] = 0; out[26] = 4 * l1; + // 23: 4 L2 L3 + out[27] = 0; out[28] = 4 * l3; out[29] = 4 * l2; +} + +/** 4-point Gauss rule on the tetrahedron (degree 2): volume coordinates (L1, L2, L3) and weight (of the unit tetrahedron, volume 1/6). */ +const GA = 0.5854101966249685, GB = 0.1381966011250105; +export const GAUSS4: [number, number, number, number][] = [[GB, GB, GB, 1 / 24], [GA, GB, GB, 1 / 24], [GB, GA, GB, 1 / 24], [GB, GB, GA, 1 / 24]]; + +const dN = new Float64Array(30); + +/** Jacobian determinant of element t at volume coordinates (l1, l2, l3). */ +export function quadJacobian(N: ArrayLike, T: ArrayLike, t: number, l1: number, l2: number, l3: number): number { + quadDerivs(l1, l2, l3, dN); + let j00 = 0, j01 = 0, j02 = 0, j10 = 0, j11 = 0, j12 = 0, j20 = 0, j21 = 0, j22 = 0; + for (let a = 0; a < 10; a++) { + const n = T[t * 10 + a] * 3; + const x = N[n], y = N[n + 1], z = N[n + 2]; + const g0 = dN[a * 3], g1 = dN[a * 3 + 1], g2 = dN[a * 3 + 2]; + j00 += g0 * x; j01 += g0 * y; j02 += g0 * z; + j10 += g1 * x; j11 += g1 * y; j12 += g1 * z; + j20 += g2 * x; j21 += g2 * y; j22 += g2 * z; + } + return j00 * (j11 * j22 - j12 * j21) - j01 * (j10 * j22 - j12 * j20) + j02 * (j10 * j21 - j11 * j20); +} + +const CHECK_POINTS: [number, number, number][] = [ + [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0], [0, 0, 0.5], [0.5, 0, 0.5], [0, 0.5, 0.5], + ...GAUSS4.map(([a, b, c]) => [a, b, c] as [number, number, number]), +]; + +/** Whether a curved element's Jacobian is positive at its nodes and quadrature points (and not much smaller than its straight value). */ +function quadraticValid(N: ArrayLike, T: ArrayLike, t: number): boolean { + const lin = 6 * tetVolume(N, T[t * 10], T[t * 10 + 1], T[t * 10 + 2], T[t * 10 + 3]); + for (const [a, b, c] of CHECK_POINTS) if (!(quadJacobian(N, T, t, a, b, c) > 0.1 * lin)) return false; + return true; +} + +export function quadraticVolume(N: ArrayLike, T: ArrayLike, t: number): number { + let v = 0; + for (const [a, b, c, w] of GAUSS4) v += quadJacobian(N, T, t, a, b, c) * w; + return v; +} + +/** Points near a point, by bins. */ +class PointGrid { + private bins = new Map(); + constructor(private P: ArrayLike, ids: number[], private c: number) { + for (const v of ids) { + const k = this.key(P[v * 3], P[v * 3 + 1], P[v * 3 + 2]); + let l = this.bins.get(k); + if (!l) this.bins.set(k, (l = [])); + l.push(v); + } + } + private key(x: number, y: number, z: number) { + return `${Math.floor(x / this.c)},${Math.floor(y / this.c)},${Math.floor(z / this.c)}`; + } + near(p: ArrayLike, r: number): number[] { + const out: number[] = []; + const lo = [0, 1, 2].map((d) => Math.floor((p[d] - r) / this.c)), hi = [0, 1, 2].map((d) => Math.floor((p[d] + r) / this.c)); + for (let x = lo[0]; x <= hi[0]; x++) for (let y = lo[1]; y <= hi[1]; y++) for (let z = lo[2]; z <= hi[2]; z++) { + for (const v of this.bins.get(`${x},${y},${z}`) ?? []) if (dist2(this.P, v, p) <= r * r) out.push(v); + } + return out; + } +} + +/** A tetrahedral mesh being edited: vertices move, edges split. */ +class WorkMesh { + P: number[]; + T: number[]; + vt: number[][]; + onB: number[] = []; + labels: number[][] = []; + locked: number[] = []; + constructor(P: number[], T: number[], private h: number) { + this.P = P; + this.T = T; + this.vt = Array.from({ length: P.length / 3 }, () => []); + for (let t = 0; t < T.length / 4; t++) for (let k = 0; k < 4; k++) this.vt[T[t * 4 + k]].push(t); + const n = P.length / 3; + this.onB = new Array(n).fill(0); + this.locked = new Array(n).fill(0); + this.labels = Array.from({ length: n }, () => []); + } + get nn() { return this.P.length / 3; } + get nt() { return this.T.length / 4; } + pos(v: number): number[] { return [this.P[v * 3], this.P[v * 3 + 1], this.P[v * 3 + 2]]; } + quality(t: number) { const T = this.T; return tetQuality(this.P, T[t * 4], T[t * 4 + 1], T[t * 4 + 2], T[t * 4 + 3]); } + worst(v: number) { let w = Infinity; for (const t of this.vt[v]) w = Math.min(w, this.quality(t)); return w; } + hasEdge(u: number, w: number) { return this.vt[u].some((t) => this.vt[w].includes(t)); } + /** Moves v to p unless an element around it would get worse than minQ (or than the worst it had). */ + move(v: number, p: ArrayLike, minQ: number): boolean { + const old = this.pos(v); + const before = this.worst(v); + this.P[v * 3] = p[0]; this.P[v * 3 + 1] = p[1]; this.P[v * 3 + 2] = p[2]; + if (this.worst(v) >= Math.min(minQ, before)) return true; + this.P[v * 3] = old[0]; this.P[v * 3 + 1] = old[1]; this.P[v * 3 + 2] = old[2]; + return false; + } + /** Splits edge u-w at its middle; returns the new vertex. */ + split(u: number, w: number): number { + const x = this.nn; + this.P.push((this.P[u * 3] + this.P[w * 3]) / 2, (this.P[u * 3 + 1] + this.P[w * 3 + 1]) / 2, (this.P[u * 3 + 2] + this.P[w * 3 + 2]) / 2); + this.vt.push([]); + this.onB.push(0); + this.locked.push(0); + this.labels.push([]); + const shared = this.vt[u].filter((t) => this.vt[w].includes(t)); + for (const t of shared) { + // t keeps u (w becomes x); the copy keeps w (u becomes x): both keep the orientation. + const nt = this.nt; + const copy = this.T.slice(t * 4, t * 4 + 4); + for (let k = 0; k < 4; k++) { + if (this.T[t * 4 + k] === w) this.T[t * 4 + k] = x; + if (copy[k] === u) copy[k] = x; + } + this.T.push(...copy); + this.vt[w] = this.vt[w].filter((q) => q !== t); + this.vt[w].push(nt); + this.vt[x].push(t, nt); + for (const c of copy) if (c !== x && c !== w) this.vt[c].push(nt); + } + return x; + } + /** Moves interior vertices where that raises the worst element around them. */ + smooth(passes: number) { + for (let pass = 0; pass < passes; pass++) { + for (let v = 0; v < this.nn; v++) { + if (this.onB[v]) continue; + const worst = this.worst(v); + if (worst > 0.45) continue; + const nb = new Set(); + for (const t of this.vt[v]) for (let k = 0; k < 4; k++) if (this.T[t * 4 + k] !== v) nb.add(this.T[t * 4 + k]); + const c = [0, 0, 0]; + for (const w of nb) { c[0] += this.P[w * 3] / nb.size; c[1] += this.P[w * 3 + 1] / nb.size; c[2] += this.P[w * 3 + 2] / nb.size; } + const old = this.pos(v); + let best = worst, bestP = old; + // The middle of the neighbours, part way there, and small steps along the axes. + const step = this.h * 0.08; + const tries = [c, [0, 1, 2].map((d) => old[d] + (c[d] - old[d]) * 0.5)]; + for (let d = 0; d < 3; d++) for (const sgn of [-1, 1]) { const p = old.slice(); p[d] += sgn * step; tries.push(p); } + for (const p of tries) { + this.P[v * 3] = p[0]; this.P[v * 3 + 1] = p[1]; this.P[v * 3 + 2] = p[2]; + const q = this.worst(v); + if (q > best) { best = q; bestP = p; } + } + this.P[v * 3] = bestP[0]; this.P[v * 3 + 1] = bestP[1]; this.P[v * 3 + 2] = bestP[2]; + } + } + } + typed(): LinearMesh { + return { P: Float64Array.from(this.P), tets: Int32Array.from(this.T), nn: this.nn, nt: this.nt }; + } +} diff --git a/src/parametric/src/fea/surface.ts b/src/parametric/src/fea/surface.ts new file mode 100644 index 0000000000..2655beb2a0 --- /dev/null +++ b/src/parametric/src/fea/surface.ts @@ -0,0 +1,378 @@ +// The part's boundary as the kernel triangulates it (a closed triangle mesh +// whose triangles know their B-rep face), indexed for the queries the mesher +// needs: which side of the boundary a point is on, where a segment crosses +// it, and the nearest point on it (on any face, on given faces, or on the +// edges between two faces). +// +// Inside tests count crossings of a ray along +x. They are exact in the sense +// that matters: a ray through a shared edge or vertex is counted once, +// because every edge function is evaluated with its end points in one +// canonical order (both triangles get the same number) and zeros are broken +// by a fixed rule (as if the ray were moved by an infinitesimal amount). + +export interface FeaSurfaceData { + /** xyz per vertex (a vertex may repeat, once per face it is on). */ + positions: Float32Array | Float64Array; + /** Three vertex indices per triangle. */ + indices: Uint32Array | Int32Array; + /** B-rep face index of each triangle. */ + triFace: Int32Array; +} + +export interface ClosestHit { + p: [number, number, number]; + tri: number; + d2: number; +} + +const EPS_AREA = 0; + +export class SurfaceIndex { + /** Welded vertices (exact coordinates), xyz. */ + readonly v: Float64Array; + /** Triangles over welded vertices. */ + readonly t: Int32Array; + readonly face: Int32Array; + readonly nt: number; + readonly min: [number, number, number] = [Infinity, Infinity, Infinity]; + readonly max: [number, number, number] = [-Infinity, -Infinity, -Infinity]; + /** Bins of triangles over (y, z) for rays along x. */ + private yz: { y0: number; z0: number; c: number; ny: number; nz: number; start: Int32Array; items: Int32Array }; + /** 3D bins of triangles for segment and nearest point queries. */ + private g: { o: [number, number, number]; c: number; n: [number, number, number]; start: Int32Array; items: Int32Array }; + /** Edges between faces: per face pair key, segments (welded vertex pairs). */ + private seams = new Map(); + /** Welded vertices where three or more faces meet, with their faces. */ + readonly corners: { v: number; faces: number[] }[] = []; + + constructor(data: FeaSurfaceData) { + const P = data.positions, I = data.indices; + const key = new Map(); + const remap = new Int32Array(P.length / 3); + const vs: number[] = []; + for (let i = 0; i < remap.length; i++) { + const x = P[i * 3], y = P[i * 3 + 1], z = P[i * 3 + 2]; + const k = `${x},${y},${z}`; + let id = key.get(k); + if (id === undefined) { id = vs.length / 3; key.set(k, id); vs.push(x, y, z); } + remap[i] = id; + } + this.v = Float64Array.from(vs); + // Triangles that collapse after welding have no area and carry nothing. + const tris: number[] = [], faces: number[] = []; + for (let k = 0; k < I.length / 3; k++) { + const a = remap[I[k * 3]], b = remap[I[k * 3 + 1]], c = remap[I[k * 3 + 2]]; + if (a === b || b === c || a === c) continue; + tris.push(a, b, c); + faces.push(data.triFace[k]); + } + this.t = Int32Array.from(tris); + this.face = Int32Array.from(faces); + this.nt = faces.length; + const V = this.v; + for (let i = 0; i < V.length; i += 3) for (let k = 0; k < 3; k++) { this.min[k] = Math.min(this.min[k], V[i + k]); this.max[k] = Math.max(this.max[k], V[i + k]); } + this.yz = this.buildYz(); + this.g = this.buildGrid(); + this.buildSeams(); + } + + get diag(): number { + return Math.hypot(this.max[0] - this.min[0], this.max[1] - this.min[1], this.max[2] - this.min[2]); + } + + /** Area of each face (by index, up to the largest index present). */ + faceAreas(): number[] { + const out: number[] = []; + for (let k = 0; k < this.nt; k++) { + const f = this.face[k]; + while (out.length <= f) out.push(0); + out[f] += this.triArea(k); + } + return out; + } + + triArea(k: number): number { + const V = this.v, a = this.t[k * 3] * 3, b = this.t[k * 3 + 1] * 3, c = this.t[k * 3 + 2] * 3; + const ux = V[b] - V[a], uy = V[b + 1] - V[a + 1], uz = V[b + 2] - V[a + 2]; + const wx = V[c] - V[a], wy = V[c + 1] - V[a + 1], wz = V[c + 2] - V[a + 2]; + return 0.5 * Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx); + } + + /** Volume enclosed (divergence theorem; positive when the triangles face outward). */ + volume(): number { + const V = this.v, T = this.t; + let s = 0; + for (let k = 0; k < this.nt; k++) { + const a = T[k * 3] * 3, b = T[k * 3 + 1] * 3, c = T[k * 3 + 2] * 3; + s += V[a] * (V[b + 1] * V[c + 2] - V[b + 2] * V[c + 1]) - V[a + 1] * (V[b] * V[c + 2] - V[b + 2] * V[c]) + V[a + 2] * (V[b] * V[c + 1] - V[b + 1] * V[c]); + } + return s / 6; + } + + // ---------- rays along x ---------- + + private buildYz() { + const V = this.v, T = this.t; + const area = (this.max[1] - this.min[1]) * (this.max[2] - this.min[2]); + const c = Math.max(Math.sqrt(Math.max(area, 1e-12) / Math.max(1, this.nt)) * 2, 1e-9); + const ny = Math.max(1, Math.min(2048, Math.ceil((this.max[1] - this.min[1]) / c) + 1)); + const nz = Math.max(1, Math.min(2048, Math.ceil((this.max[2] - this.min[2]) / c) + 1)); + const cy = Math.max((this.max[1] - this.min[1]) / ny, 1e-12), cz = Math.max((this.max[2] - this.min[2]) / nz, 1e-12); + const cc = Math.max(cy, cz); + const y0 = this.min[1], z0 = this.min[2]; + const nY = Math.max(1, Math.ceil((this.max[1] - y0) / cc) + 1), nZ = Math.max(1, Math.ceil((this.max[2] - z0) / cc) + 1); + const count = new Int32Array(nY * nZ + 1); + const range = (k: number) => { + let ya = Infinity, yb = -Infinity, za = Infinity, zb = -Infinity; + for (let q = 0; q < 3; q++) { const i = T[k * 3 + q] * 3; ya = Math.min(ya, V[i + 1]); yb = Math.max(yb, V[i + 1]); za = Math.min(za, V[i + 2]); zb = Math.max(zb, V[i + 2]); } + return [Math.max(0, Math.floor((ya - y0) / cc)), Math.min(nY - 1, Math.floor((yb - y0) / cc)), Math.max(0, Math.floor((za - z0) / cc)), Math.min(nZ - 1, Math.floor((zb - z0) / cc))]; + }; + for (let k = 0; k < this.nt; k++) { + const [a, b, e, f] = range(k); + for (let j = e; j <= f; j++) for (let i = a; i <= b; i++) count[j * nY + i + 1]++; + } + for (let i = 1; i < count.length; i++) count[i] += count[i - 1]; + const fill = count.slice(); + const items = new Int32Array(count[count.length - 1]); + for (let k = 0; k < this.nt; k++) { + const [a, b, e, f] = range(k); + for (let j = e; j <= f; j++) for (let i = a; i <= b; i++) items[fill[j * nY + i]++] = k; + } + return { y0, z0, c: cc, ny: nY, nz: nZ, start: count, items }; + } + + /** + * Edge function of welded vertices a, b at point (y, z) in the (y, z) projection, + * evaluated with the end points in a fixed order so that both triangles on an edge agree. + */ + private edgeFn(a: number, b: number, y: number, z: number): number { + const V = this.v; + if (a > b) return -this.edgeFn(b, a, y, z); + const ay = V[a * 3 + 1], az = V[a * 3 + 2], by = V[b * 3 + 1], bz = V[b * 3 + 2]; + return (by - ay) * (z - az) - (bz - az) * (y - ay); + } + + /** Whether an edge (a to b, the triangle on its left in (y, z)) owns points exactly on it. */ + private owns(a: number, b: number): boolean { + const V = this.v; + const dy = V[b * 3 + 1] - V[a * 3 + 1], dz = V[b * 3 + 2] - V[a * 3 + 2]; + return dz > 0 || (dz === 0 && dy < 0); + } + + /** + * Where the line {(t, y, z)} crosses the boundary: x values in increasing + * order, with the triangle crossed. Triangles seen edge-on are not crossed. + */ + xCrossings(y: number, z: number): { x: number[]; tri: number[] } { + const g = this.yz; + const i = Math.floor((y - g.y0) / g.c), j = Math.floor((z - g.z0) / g.c); + const xs: number[] = [], ts: number[] = []; + if (i < 0 || j < 0 || i >= g.ny || j >= g.nz) return { x: xs, tri: ts }; + const cell = j * g.ny + i; + const T = this.t, V = this.v; + for (let q = g.start[cell]; q < g.start[cell + 1]; q++) { + const k = g.items[q]; + let a = T[k * 3], b = T[k * 3 + 1], c = T[k * 3 + 2]; + let o = this.edgeFn(a, b, V[c * 3 + 1], V[c * 3 + 2]); + if (o === EPS_AREA) continue; + if (o < 0) { const s = b; b = c; c = s; o = -o; } + const w0 = this.edgeFn(b, c, y, z), w1 = this.edgeFn(c, a, y, z), w2 = this.edgeFn(a, b, y, z); + if (w0 < 0 || w1 < 0 || w2 < 0) continue; + if ((w0 === 0 && !this.owns(b, c)) || (w1 === 0 && !this.owns(c, a)) || (w2 === 0 && !this.owns(a, b))) continue; + const s = w0 + w1 + w2; + if (!(s > 0)) continue; + xs.push((w0 * V[a * 3] + w1 * V[b * 3] + w2 * V[c * 3]) / s); + ts.push(k); + } + const order = xs.map((_, n) => n).sort((p, q) => xs[p] - xs[q]); + return { x: order.map((n) => xs[n]), tri: order.map((n) => ts[n]) }; + } + + /** Whether a point is inside the closed boundary. */ + inside(p: ArrayLike): boolean { + const { x } = this.xCrossings(p[1], p[2]); + let n = 0; + for (const v of x) if (v > p[0]) n++; + return (n & 1) === 1; + } + + // ---------- 3D bins ---------- + + private buildGrid() { + const V = this.v, T = this.t; + const ext = [this.max[0] - this.min[0], this.max[1] - this.min[1], this.max[2] - this.min[2]]; + // About two triangles per occupied cell, bounded in total. + const avgEdge = Math.sqrt((this.faceAreas().reduce((a, b) => a + b, 0) / Math.max(1, this.nt)) * 2); + let c = Math.max(avgEdge * 1.5, this.diag / 400, 1e-9); + while ((ext[0] / c + 1) * (ext[1] / c + 1) * (ext[2] / c + 1) > 8e6) c *= 1.5; + const o: [number, number, number] = [this.min[0] - c * 0.5, this.min[1] - c * 0.5, this.min[2] - c * 0.5]; + const n: [number, number, number] = [Math.ceil(ext[0] / c) + 2, Math.ceil(ext[1] / c) + 2, Math.ceil(ext[2] / c) + 2]; + const range = (k: number) => { + const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; + for (let q = 0; q < 3; q++) for (let d = 0; d < 3; d++) { const v = V[T[k * 3 + q] * 3 + d]; lo[d] = Math.min(lo[d], v); hi[d] = Math.max(hi[d], v); } + return [0, 1, 2].flatMap((d) => [Math.max(0, Math.floor((lo[d] - o[d]) / c)), Math.min(n[d] - 1, Math.floor((hi[d] - o[d]) / c))]); + }; + const count = new Int32Array(n[0] * n[1] * n[2] + 1); + for (let k = 0; k < this.nt; k++) { + const r = range(k); + for (let z = r[4]; z <= r[5]; z++) for (let y = r[2]; y <= r[3]; y++) for (let x = r[0]; x <= r[1]; x++) count[(z * n[1] + y) * n[0] + x + 1]++; + } + for (let i = 1; i < count.length; i++) count[i] += count[i - 1]; + const fill = count.slice(); + const items = new Int32Array(count[count.length - 1]); + for (let k = 0; k < this.nt; k++) { + const r = range(k); + for (let z = r[4]; z <= r[5]; z++) for (let y = r[2]; y <= r[3]; y++) for (let x = r[0]; x <= r[1]; x++) items[fill[(z * n[1] + y) * n[0] + x]++] = k; + } + return { o, c, n, start: count, items }; + } + + /** Calls fn with each triangle whose bins meet the box (a triangle may come more than once). */ + private eachNear(lo: ArrayLike, hi: ArrayLike, fn: (k: number) => void) { + const g = this.g; + const r = [0, 1, 2].flatMap((d) => [Math.max(0, Math.floor((lo[d] - g.o[d]) / g.c)), Math.min(g.n[d] - 1, Math.floor((hi[d] - g.o[d]) / g.c))]); + for (let z = r[4]; z <= r[5]; z++) for (let y = r[2]; y <= r[3]; y++) for (let x = r[0]; x <= r[1]; x++) { + const cell = (z * g.n[1] + y) * g.n[0] + x; + for (let q = g.start[cell]; q < g.start[cell + 1]; q++) fn(g.items[q]); + } + } + + /** + * Where the segment p-q crosses the boundary: the parameter t in (0, 1) and + * the triangle, the crossing nearest to p; null when none is found. + */ + segmentHit(p: ArrayLike, q: ArrayLike): { t: number; tri: number } | null { + const lo = [Math.min(p[0], q[0]), Math.min(p[1], q[1]), Math.min(p[2], q[2])]; + const hi = [Math.max(p[0], q[0]), Math.max(p[1], q[1]), Math.max(p[2], q[2])]; + const dx = q[0] - p[0], dy = q[1] - p[1], dz = q[2] - p[2]; + const V = this.v, T = this.t; + let best: { t: number; tri: number } | null = null; + this.eachNear(lo, hi, (k) => { + const a = T[k * 3] * 3, b = T[k * 3 + 1] * 3, c = T[k * 3 + 2] * 3; + const e1x = V[b] - V[a], e1y = V[b + 1] - V[a + 1], e1z = V[b + 2] - V[a + 2]; + const e2x = V[c] - V[a], e2y = V[c + 1] - V[a + 1], e2z = V[c + 2] - V[a + 2]; + const px = dy * e2z - dz * e2y, py = dz * e2x - dx * e2z, pz = dx * e2y - dy * e2x; + const det = e1x * px + e1y * py + e1z * pz; + if (det === 0) return; + const inv = 1 / det; + const sx = p[0] - V[a], sy = p[1] - V[a + 1], sz = p[2] - V[a + 2]; + const u = (sx * px + sy * py + sz * pz) * inv; + if (u < -1e-12 || u > 1 + 1e-12) return; + const qx = sy * e1z - sz * e1y, qy = sz * e1x - sx * e1z, qz = sx * e1y - sy * e1x; + const v = (dx * qx + dy * qy + dz * qz) * inv; + if (v < -1e-12 || u + v > 1 + 1e-12) return; + const t = (e2x * qx + e2y * qy + e2z * qz) * inv; + if (t < 0 || t > 1) return; + if (!best || t < best.t) best = { t, tri: k }; + }); + return best; + } + + /** Nearest point of triangle k to p. */ + closestOnTri(k: number, p: ArrayLike): [number, number, number] { + const V = this.v, T = this.t; + const a = T[k * 3] * 3, b = T[k * 3 + 1] * 3, c = T[k * 3 + 2] * 3; + return closestOnTriangle(p, V[a], V[a + 1], V[a + 2], V[b], V[b + 1], V[b + 2], V[c], V[c + 1], V[c + 2]); + } + + /** + * Nearest point on the boundary within radius r of p (on the given faces + * only, if any), or null when there is none that close. + */ + closest(p: ArrayLike, r: number, faces?: ReadonlySet | null): ClosestHit | null { + let best: ClosestHit | null = null; + let lim = r * r; + this.eachNear([p[0] - r, p[1] - r, p[2] - r], [p[0] + r, p[1] + r, p[2] + r], (k) => { + if (faces && !faces.has(this.face[k])) return; + const c = this.closestOnTri(k, p); + const d2 = (c[0] - p[0]) ** 2 + (c[1] - p[1]) ** 2 + (c[2] - p[2]) ** 2; + if (d2 <= lim && (!best || d2 < best.d2)) { best = { p: c, tri: k, d2 }; lim = d2; } + }); + return best; + } + + // ---------- face boundaries ---------- + + private buildSeams() { + const T = this.t; + const edgeFaces = new Map(); + const nv = this.v.length / 3; + const vertFaces: Set[] = []; + for (let k = 0; k < this.nt; k++) { + for (let q = 0; q < 3; q++) { + const a = T[k * 3 + q], b = T[k * 3 + (q + 1) % 3]; + const key = Math.min(a, b) * nv + Math.max(a, b); + let l = edgeFaces.get(key); + if (!l) edgeFaces.set(key, (l = [])); + l.push(this.face[k]); + (vertFaces[a] ??= new Set()).add(this.face[k]); + } + } + for (const [key, fs] of edgeFaces) { + const uniq = [...new Set(fs)]; + if (uniq.length < 2) continue; + const a = Math.floor(key / nv), b = key - a * nv; + for (let i = 0; i < uniq.length; i++) for (let j = i + 1; j < uniq.length; j++) { + const pk = pairKey(uniq[i], uniq[j]); + let l = this.seams.get(pk); + if (!l) this.seams.set(pk, (l = [])); + l.push(a, b); + } + } + vertFaces.forEach((s, v) => { if (s && s.size >= 3) this.corners.push({ v, faces: [...s] }); }); + } + + /** Whether faces a and b share an edge. */ + adjacent(a: number, b: number): boolean { + return this.seams.has(pairKey(a, b)); + } + + /** Nearest point on the edge between faces a and b (squared distance), or null if they do not meet. */ + closestOnSeam(a: number, b: number, p: ArrayLike): { p: [number, number, number]; d2: number } | null { + const segs = this.seams.get(pairKey(a, b)); + if (!segs) return null; + const V = this.v; + let best: [number, number, number] | null = null, bd = Infinity; + for (let i = 0; i < segs.length; i += 2) { + const s = segs[i] * 3, e = segs[i + 1] * 3; + const dx = V[e] - V[s], dy = V[e + 1] - V[s + 1], dz = V[e + 2] - V[s + 2]; + const l2 = dx * dx + dy * dy + dz * dz; + let t = l2 > 0 ? ((p[0] - V[s]) * dx + (p[1] - V[s + 1]) * dy + (p[2] - V[s + 2]) * dz) / l2 : 0; + t = Math.max(0, Math.min(1, t)); + const c: [number, number, number] = [V[s] + dx * t, V[s + 1] + dy * t, V[s + 2] + dz * t]; + const d2 = (c[0] - p[0]) ** 2 + (c[1] - p[1]) ** 2 + (c[2] - p[2]) ** 2; + if (d2 < bd) { bd = d2; best = c; } + } + return best ? { p: best, d2: bd } : null; + } + + vertex(i: number): [number, number, number] { + return [this.v[i * 3], this.v[i * 3 + 1], this.v[i * 3 + 2]]; + } +} + +const pairKey = (a: number, b: number) => (a < b ? `${a}|${b}` : `${b}|${a}`); + +/** Nearest point of triangle abc to p (Ericson, Real-Time Collision Detection 5.1.5). */ +export function closestOnTriangle(p: ArrayLike, ax: number, ay: number, az: number, bx: number, by: number, bz: number, cx: number, cy: number, cz: number): [number, number, number] { + const abx = bx - ax, aby = by - ay, abz = bz - az; + const acx = cx - ax, acy = cy - ay, acz = cz - az; + const apx = p[0] - ax, apy = p[1] - ay, apz = p[2] - az; + const d1 = abx * apx + aby * apy + abz * apz, d2 = acx * apx + acy * apy + acz * apz; + if (d1 <= 0 && d2 <= 0) return [ax, ay, az]; + const bpx = p[0] - bx, bpy = p[1] - by, bpz = p[2] - bz; + const d3 = abx * bpx + aby * bpy + abz * bpz, d4 = acx * bpx + acy * bpy + acz * bpz; + if (d3 >= 0 && d4 <= d3) return [bx, by, bz]; + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { const v = d1 / (d1 - d3); return [ax + abx * v, ay + aby * v, az + abz * v]; } + const cpx = p[0] - cx, cpy = p[1] - cy, cpz = p[2] - cz; + const d5 = abx * cpx + aby * cpy + abz * cpz, d6 = acx * cpx + acy * cpy + acz * cpz; + if (d6 >= 0 && d5 <= d6) return [cx, cy, cz]; + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { const w = d2 / (d2 - d6); return [ax + acx * w, ay + acy * w, az + acz * w]; } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { const w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); return [bx + (cx - bx) * w, by + (cy - by) * w, bz + (cz - bz) * w]; } + const denom = 1 / (va + vb + vc); + const v = vb * denom, w = vc * denom; + return [ax + abx * v + acx * w, ay + aby * v + acy * w, az + abz * v + acz * w]; +} diff --git a/src/parametric/src/kernel/build.ts b/src/parametric/src/kernel/build.ts index 7282147cd8..bcfd65ed43 100644 --- a/src/parametric/src/kernel/build.ts +++ b/src/parametric/src/kernel/build.ts @@ -28,7 +28,7 @@ import { hasExternal, resolveExternal } from '../sketch/external'; import { solveSketch } from '../sketch/solver'; import { measureDimension } from '../sketch/ops'; import type { - BuildRequest, BuildResult, EdgeInfo, FaceInfo, FeatureStatus, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, + BuildRequest, BuildResult, EdgeInfo, FaceInfo, FeaSurface, FeatureStatus, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, } from './protocol'; import { type WeldCtx, type WeldState, applyEndCap, applyGusset, applyStructuralMember, applyTrimExtend, applyWeldBead } from './weldments'; @@ -1808,6 +1808,30 @@ export class ModelBuilder { } } + /** + * The solid's boundary triangulated for the stress analysis mesher: each + * triangle with the index of its face (as in the build result's faces), + * at a chordal tolerance (mm), with the solid's exact volume. + */ + feaSurface(tolerance: number): FeaSurface { + const st = this.current; + if (!st.body) throw new FeatureError('The part has no solid body to analyze.'); + const b = boxOf(st.body); + const tol = Math.max(tolerance, (b ? dist(b.min, b.max) : 1) * 2e-5); + const m = meshShape(st.body, tol, 0.15); + const faceIndex = new ShapeIndex(st.faces.map((f) => f.shape)); + const triFace = new Int32Array(m.indices.length / 3); + const claimed = new Set(); + for (let g = 0; g + 2 < m.faceGroups.length; g += 3) { + const start = m.faceGroups[g], count = m.faceGroups[g + 1], hash = m.faceGroups[g + 2]; + const cands = faceIndex.findHash(hash); + const fi = cands.find((c) => !claimed.has(c)) ?? cands[0] ?? -1; + claimed.add(fi); + for (let t = start; t < start + count; t += 3) triFace[t / 3] = fi; + } + return { positions: m.positions, indices: m.indices, triFace, volume: volumeOf(st.body), faceNames: st.faces.map((f) => f.name) }; + } + exportBrep(): string { const body = this.current.body; if (!body) throw new FeatureError('There is no geometry to export'); diff --git a/src/parametric/src/kernel/client.ts b/src/parametric/src/kernel/client.ts index 5c25eea656..60b1c6b505 100644 --- a/src/parametric/src/kernel/client.ts +++ b/src/parametric/src/kernel/client.ts @@ -10,7 +10,7 @@ import type { SolidWorksImport } from '../formats/sldprt'; import type { Id } from '../model/types'; import type { AsmPartBuild, AsmRequest, AsmSceneItem } from './assembly'; -import type { BuildRequest, BuildResult, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, WorkerRequest, WorkerResponse } from './protocol'; +import type { BuildRequest, BuildResult, FeaSurface, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, WorkerRequest, WorkerResponse } from './protocol'; type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void }; type Call = Pending & { at: number; type: WorkerRequest['type'] }; @@ -291,6 +291,11 @@ export class KernelClient { return this.call({ type: 'export', format, quality, name }); } + /** The solid's boundary for the stress analysis mesher (see ModelBuilder.feaSurface). */ + feaSurface(tolerance: number): Promise { + return this.call({ type: 'feaSurface', tolerance }); + } + exportBrep(): Promise { return this.call({ type: 'export', format: 'brep', quality: 1 }); } diff --git a/src/parametric/src/kernel/protocol.ts b/src/parametric/src/kernel/protocol.ts index 077a4e4af3..55c0aa89e2 100644 --- a/src/parametric/src/kernel/protocol.ts +++ b/src/parametric/src/kernel/protocol.ts @@ -184,6 +184,17 @@ export interface ProjectionResult { cutGroups?: number[]; } +/** The solid's boundary triangulated for the stress analysis mesher (see ModelBuilder.feaSurface). */ +export interface FeaSurface { + positions: Float32Array; + indices: Uint32Array; + /** Face of each triangle: an index into the build result's faces. */ + triFace: Int32Array; + /** Exact volume of the solid (mm^3). */ + volume: number; + faceNames: string[]; +} + export type WorkerRequest = | { id: number; type: 'init' } | { id: number; type: 'reset' } @@ -200,6 +211,8 @@ export type WorkerRequest = | { id: number; type: 'measure'; a: MeasureTarget; b: MeasureTarget } | { id: number; type: 'export'; format: 'step' | 'stl' | 'brep'; quality: number; name?: string } | { id: number; type: 'checkImport'; format: 'step'; text: string } + /** The solid's boundary for the stress analysis mesher, at a chordal tolerance (mm). */ + | { id: number; type: 'feaSurface'; tolerance: number } | { id: number; type: 'convertSolidWorks'; data: Uint8Array; name: string } /** Assemblies: building their parts and the placed components (see assembly.ts). */ | { id: number; type: 'asm'; req: AsmRequest } diff --git a/src/parametric/src/kernel/worker.ts b/src/parametric/src/kernel/worker.ts index c8698f52c3..6fa6a0b190 100644 --- a/src/parametric/src/kernel/worker.ts +++ b/src/parametric/src/kernel/worker.ts @@ -136,6 +136,12 @@ async function handle(ev: MessageEvent) { reply({ id: msg.id, ok: true, result, heap: memory?.buffer.byteLength }, r.op === 'build' || r.op === 'interference' ? asmTransfers(result) : []); return; } + case 'feaSurface': { + if (assembly.active) throw new Error('Stress analysis works on parts.'); + const res = builder.feaSurface(msg.tolerance); + reply({ id: msg.id, ok: true, result: res }, [res.positions.buffer, res.indices.buffer, res.triFace.buffer] as ArrayBuffer[]); + return; + } case 'checkImport': reply({ id: msg.id, ok: true, result: await checkStep(msg.text) }); return; diff --git a/src/parametric/tests/fea-mesher.test.ts b/src/parametric/tests/fea-mesher.test.ts new file mode 100644 index 0000000000..51ffe42663 --- /dev/null +++ b/src/parametric/tests/fea-mesher.test.ts @@ -0,0 +1,91 @@ +// Volume meshing for stress analysis on parts built by the real kernel: +// positive elements, the mesh's volume against the solid's, faces covered by +// boundary triangles of their own, and every example part meshed. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import { EXAMPLES } from '../src/app/examples'; +import { SurfaceIndex } from '../src/fea/surface'; +import { type TetMesh, defaultElementSize, maxElementSize, meshSolid, quadJacobian, tetVolume } from '../src/fea/mesher'; +import { elementSizeFor } from '../src/model/fea'; +import { integrateTriangle } from '../src/fea/elements'; +import type { Feature } from '../src/model/types'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +async function surfaceOf(features: Feature[], tol = 0.01) { + const b = new ModelBuilder(); + const res = await b.build(req(features, { quality: 1 })); + expect(res.status.every((s) => s.ok)).toBe(true); + const fs = b.feaSurface(tol); + return { surf: new SurfaceIndex(fs), fs, faces: res.faces }; +} + +/** Every element positive, at its corners and at its quadrature points. */ +function expectValid(m: TetMesh) { + const ne = m.tets.length / 10; + for (let e = 0; e < ne; e++) { + const t = m.tets; + expect(tetVolume(m.nodes, t[e * 10], t[e * 10 + 1], t[e * 10 + 2], t[e * 10 + 3])).toBeGreaterThan(0); + for (const [a, b, c] of [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0.25, 0.25, 0.25]]) expect(quadJacobian(m.nodes, t, e, a, b, c)).toBeGreaterThan(0); + } +} + +/** Area of the mesh's boundary triangles on each face. */ +function meshFaceAreas(m: TetMesh): Map { + const out = new Map(); + for (let f = 0; f < m.triFace.length; f++) out.set(m.triFace[f], (out.get(m.triFace[f]) ?? 0) + integrateTriangle(m.nodes, m.tris, f)); + return out; +} + +describe('volume mesher', () => { + it('meshes a box exactly: volume, faces, edges and corners', async () => { + const { surf, faces } = await surfaceOf([sketch('s1', rect(0, 0, 200, 20)), extrude('f1', 's1', 10)]); + expect(surf.volume()).toBeCloseTo(40000, 3); + const m = meshSolid(surf, { size: 4 }); + expectValid(m); + expect(m.stats.volume / 40000).toBeCloseTo(1, 6); + expect(m.stats.unassigned).toBe(0); + expect(m.stats.pieces).toBe(1); + const areas = meshFaceAreas(m); + faces.forEach((f, i) => expect(areas.get(i)! / f.area).toBeCloseTo(1, 4)); + expect(m.stats.minQuality).toBeGreaterThan(0.15); + }, 60000); + + it('meshes a plate with a hole: curved boundary on the cylinder', async () => { + const { surf, fs, faces } = await surfaceOf([sketch('s1', [...rect(-50, -25, 50, 25), ...circle(0, 0, 5)]), extrude('f1', 's1', 4)]); + const m = meshSolid(surf, { size: 1.5 }); + expectValid(m); + // Quadratic elements follow the hole: the volume is within a few parts in ten thousand of the exact one. + expect(Math.abs(m.stats.volume / fs.volume - 1)).toBeLessThan(5e-4); + const areas = meshFaceAreas(m); + const hole = faces.findIndex((f) => f.type === 'cylinder'); + expect(areas.get(hole)! / faces[hole].area).toBeCloseTo(1, 2); + faces.forEach((f, i) => expect(Math.abs(areas.get(i)! / f.area - 1)).toBeLessThan(0.01)); + }, 60000); + + for (const ex of EXAMPLES) { + it(`meshes the ${ex.name} example at its automatic size, coarse and fine`, async () => { + const { surf, fs, faces } = await surfaceOf(ex.make().features); + const area = surf.faceAreas().reduce((a, b) => a + b, 0); + const auto = defaultElementSize(fs.volume, area, surf.diag); + const max = maxElementSize(fs.volume, area, surf.diag); + for (const size of [elementSizeFor(auto, max, 0), elementSizeFor(auto, max, 0.5), elementSizeFor(auto, max, 1)]) { + const m = meshSolid(surf, { size }); + expectValid(m); + expect(m.stats.pieces).toBe(1); + expect(Math.abs(m.stats.volume / fs.volume - 1)).toBeLessThan(size > auto ? 0.015 : 0.004); + // Every face of the part is meshed, the large ones to within a few percent of their area. + const areas = meshFaceAreas(m); + faces.forEach((f, i) => { + expect(areas.get(i) ?? 0, `${f.name} (${f.type}) at ${size}`).toBeGreaterThan(0); + if (f.area > 40 * size * size) expect(Math.abs((areas.get(i) ?? 0) / f.area - 1), `${f.name} at ${size}`).toBeLessThan(size > auto ? 0.1 : 0.03); + }); + } + }, 120000); + } +}); From e810d7c85fefa93814c801c9fc0af4c98e87e50b Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:03:39 -0700 Subject: [PATCH 010/116] Parametric: linear static solver (10-node tetrahedra, multigrid preconditioned conjugate gradients) --- src/parametric/src/fea/amg.ts | 631 ++++++++++++++++++++++++ src/parametric/src/fea/elements.ts | 192 +++++++ src/parametric/src/fea/static.ts | 442 +++++++++++++++++ src/parametric/tests/fea-solver.test.ts | 134 +++++ 4 files changed, 1399 insertions(+) create mode 100644 src/parametric/src/fea/amg.ts create mode 100644 src/parametric/src/fea/elements.ts create mode 100644 src/parametric/src/fea/static.ts create mode 100644 src/parametric/tests/fea-solver.test.ts diff --git a/src/parametric/src/fea/amg.ts b/src/parametric/src/fea/amg.ts new file mode 100644 index 0000000000..19ccf45f26 --- /dev/null +++ b/src/parametric/src/fea/amg.ts @@ -0,0 +1,631 @@ +// Sparse block matrices and the linear solver: preconditioned conjugate +// gradients with a smoothed aggregation algebraic multigrid preconditioner +// (Vanek, Mandel and Brezina 1996) built for elasticity: nodes are grouped +// into aggregates, each aggregate's six rigid body motions (three +// translations, three rotations) span its coarse degrees of freedom, and the +// tentative prolongator is smoothed with one damped block Jacobi step. A +// V-cycle with block Gauss-Seidel smoothing (forward before, backward after: +// symmetric, so conjugate gradients may use it) and a dense Cholesky solve on +// the coarsest level. Block Jacobi is kept as a fallback preconditioner. +// +// Matrices are stored in block rows: the fine level in 3 x 3 node blocks, +// coarse levels in 6 x 6 aggregate blocks. + +export interface BlockMatrix { + /** Block rows (= block columns). */ + n: number; + /** Block size. */ + b: number; + rowPtr: Int32Array; + col: Int32Array; + /** b * b values per block, row-major. */ + val: Float64Array; +} + +/** Prolongator: n fine block rows of size b, m coarse block columns of size c. */ +interface Prolongator { + n: number; + m: number; + b: number; + c: number; + rowPtr: Int32Array; + col: Int32Array; + val: Float64Array; +} + +/** y = A x */ +export function matvec(A: BlockMatrix, x: Float64Array, y: Float64Array) { + const { n, b, rowPtr, col, val } = A; + if (b === 3) { + for (let i = 0; i < n; i++) { + let y0 = 0, y1 = 0, y2 = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q] * 3, v = q * 9; + const x0 = x[j], x1 = x[j + 1], x2 = x[j + 2]; + y0 += val[v] * x0 + val[v + 1] * x1 + val[v + 2] * x2; + y1 += val[v + 3] * x0 + val[v + 4] * x1 + val[v + 5] * x2; + y2 += val[v + 6] * x0 + val[v + 7] * x1 + val[v + 8] * x2; + } + y[i * 3] = y0; y[i * 3 + 1] = y1; y[i * 3 + 2] = y2; + } + return; + } + const bb = b * b; + for (let i = 0; i < n; i++) { + for (let r = 0; r < b; r++) y[i * b + r] = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q] * b, v = q * bb; + for (let r = 0; r < b; r++) { + let s = 0; + for (let c = 0; c < b; c++) s += val[v + r * b + c] * x[j + c]; + y[i * b + r] += s; + } + } + } +} + +/** Sparsity pattern of the node blocks of a mesh (nodes sharing an element), columns sorted. */ +export function meshPattern(nNodes: number, elems: Int32Array, perElem: number): BlockMatrix { + const ne = elems.length / perElem; + const start = new Int32Array(nNodes + 1); + for (let q = 0; q < elems.length; q++) start[elems[q] + 1]++; + for (let i = 0; i < nNodes; i++) start[i + 1] += start[i]; + const fill = start.slice(); + const items = new Int32Array(elems.length); + for (let e = 0; e < ne; e++) for (let k = 0; k < perElem; k++) items[fill[elems[e * perElem + k]]++] = e; + const stamp = new Int32Array(nNodes).fill(-1); + const rowPtr = new Int32Array(nNodes + 1); + const cols: number[] = []; + const row: number[] = []; + for (let i = 0; i < nNodes; i++) { + row.length = 0; + for (let q = start[i]; q < start[i + 1]; q++) { + const e = items[q]; + for (let k = 0; k < perElem; k++) { + const j = elems[e * perElem + k]; + if (stamp[j] !== i) { stamp[j] = i; row.push(j); } + } + } + row.sort((a, b) => a - b); + for (const j of row) cols.push(j); + rowPtr[i + 1] = cols.length; + } + const col = Int32Array.from(cols); + return { n: nNodes, b: 3, rowPtr, col, val: new Float64Array(col.length * 9) }; +} + +/** Position of block (i, j) in A, or -1. */ +export function blockAt(A: BlockMatrix, i: number, j: number): number { + let lo = A.rowPtr[i], hi = A.rowPtr[i + 1] - 1; + const col = A.col; + while (lo <= hi) { + const m = (lo + hi) >> 1; + const c = col[m]; + if (c === j) return m; + if (c < j) lo = m + 1; + else hi = m - 1; + } + return -1; +} + +// ---------- small dense helpers ---------- + +/** Inverse of a symmetric positive b x b block (Gauss-Jordan); a singular one gives the inverse of its diagonal part where possible. */ +function invertBlock(src: Float64Array, off: number, b: number, out: Float64Array, oOff: number) { + const a = new Float64Array(b * b * 2); + for (let r = 0; r < b; r++) { for (let c = 0; c < b; c++) a[r * 2 * b + c] = src[off + r * b + c]; a[r * 2 * b + b + r] = 1; } + let scale = 0; + for (let r = 0; r < b; r++) scale = Math.max(scale, Math.abs(src[off + r * b + r])); + for (let c = 0; c < b; c++) { + let p = c, pv = Math.abs(a[c * 2 * b + c]); + for (let r = c + 1; r < b; r++) { const v = Math.abs(a[r * 2 * b + c]); if (v > pv) { pv = v; p = r; } } + if (!(pv > 1e-12 * scale) || !(pv > 0)) { + // A degree of freedom with no stiffness (a dummy coarse one): leave it alone. + for (let r = 0; r < b; r++) a[r * 2 * b + c] = r === c ? 1 : 0; + for (let k = 0; k < 2 * b; k++) a[c * 2 * b + k] = k === c || k === b + c ? 1 : 0; + for (let r = 0; r < b; r++) if (r !== c) a[r * 2 * b + b + c] = 0; + continue; + } + if (p !== c) for (let k = 0; k < 2 * b; k++) { const t = a[c * 2 * b + k]; a[c * 2 * b + k] = a[p * 2 * b + k]; a[p * 2 * b + k] = t; } + const d = a[c * 2 * b + c]; + for (let k = 0; k < 2 * b; k++) a[c * 2 * b + k] /= d; + for (let r = 0; r < b; r++) { + if (r === c) continue; + const f = a[r * 2 * b + c]; + if (f === 0) continue; + for (let k = 0; k < 2 * b; k++) a[r * 2 * b + k] -= f * a[c * 2 * b + k]; + } + } + for (let r = 0; r < b; r++) for (let c = 0; c < b; c++) out[oOff + r * b + c] = a[r * 2 * b + b + c]; +} + +function blockDiagInverse(A: BlockMatrix): Float64Array { + const { n, b } = A; + const bb = b * b; + const out = new Float64Array(n * bb); + for (let i = 0; i < n; i++) { + const q = blockAt(A, i, i); + if (q < 0) { for (let r = 0; r < b; r++) out[i * bb + r * b + r] = 1; continue; } + invertBlock(A.val, q * bb, b, out, i * bb); + } + return out; +} + +// ---------- multigrid ---------- + +/** Strength of connection for aggregation (relative block norm). */ +const THETA = 0.08; + +interface Level { + A: BlockMatrix; + Dinv: Float64Array; + P: Prolongator | null; + /** Work vectors. */ + x: Float64Array; + r: Float64Array; + t: Float64Array; +} + +export interface Preconditioner { + apply(r: Float64Array, z: Float64Array): void; + levels: number; + description: string; +} + +/** Block Jacobi preconditioner. */ +export function blockJacobi(A: BlockMatrix): Preconditioner { + const D = blockDiagInverse(A); + const b = A.b, bb = b * b; + return { + levels: 1, description: 'block Jacobi', + apply(r, z) { + for (let i = 0; i < A.n; i++) for (let p = 0; p < b; p++) { + let s = 0; + for (let c = 0; c < b; c++) s += D[i * bb + p * b + c] * r[i * b + c]; + z[i * b + p] = s; + } + }, + }; +} + +/** + * Smoothed aggregation multigrid for a 3D elasticity matrix in node blocks, + * with the nodes' coordinates for the rigid body motions. + */ +export function smoothedAggregation(A: BlockMatrix, coords: Float64Array, opts: { + coarsest?: number; progress?: (f: number) => void; debug?: (m: string) => void; + /** Nodes whose unknowns are in their own frame: 3 x 3 rotation per node (columns: local axes in global coordinates), row-major. */ + frames?: Float64Array; + /** Number of leading local unknowns of each node that are held (removed from the problem). */ + held?: Int8Array; +} = {}): Preconditioner { + const coarsest = opts.coarsest ?? 900; + // Rigid body motions of each node, about the centroid and scaled to the part's size (well conditioned). + const n0 = A.n; + const c0 = [0, 0, 0]; + for (let i = 0; i < n0; i++) for (let d = 0; d < 3; d++) c0[d] += coords[i * 3 + d] / n0; + let L = 0; + for (let i = 0; i < n0; i++) L = Math.max(L, Math.hypot(coords[i * 3] - c0[0], coords[i * 3 + 1] - c0[1], coords[i * 3 + 2] - c0[2])); + L = L || 1; + // B: per node b x 6 (row-major). + let B: Float64Array = new Float64Array(n0 * 18); + for (let i = 0; i < n0; i++) { + const x = (coords[i * 3] - c0[0]) / L, y = (coords[i * 3 + 1] - c0[1]) / L, z = (coords[i * 3 + 2] - c0[2]) / L; + // u = t + w x r: rows ux, uy, uz; columns tx, ty, tz, wx, wy, wz. + B.set([1, 0, 0, 0, z, -y, 0, 1, 0, -z, 0, x, 0, 0, 1, y, -x, 0], i * 18); + // The motions in the node's own frame (R^T B), none in the held directions. + const R = opts.frames, k = opts.held?.[i] ?? 0; + if (R && (k || R[i * 9] !== 1 || R[i * 9 + 4] !== 1 || R[i * 9 + 8] !== 1)) { + const g = B.slice(i * 18, i * 18 + 18); + for (let r = 0; r < 3; r++) for (let j = 0; j < 6; j++) B[i * 18 + r * 6 + j] = r < k ? 0 : R[i * 9 + r] * g[j] + R[i * 9 + 3 + r] * g[6 + j] + R[i * 9 + 6 + r] * g[12 + j]; + } + } + const levels: Level[] = []; + let cur = A; + for (let depth = 0; depth < 12; depth++) { + const Dinv = blockDiagInverse(cur); + const N = cur.n * cur.b; + const lvl: Level = { A: cur, Dinv, P: null, x: new Float64Array(N), r: new Float64Array(N), t: new Float64Array(N) }; + levels.push(lvl); + if (N <= coarsest) break; + let t = performance.now(); + const lap = (what: string) => { const n = performance.now(); opts.debug?.(`level ${depth} ${what}: ${(n - t).toFixed(0)} ms`); t = n; }; + const agg = aggregate(cur, depth === 0 ? THETA : THETA * 0.5 ** depth); + lap(`aggregate (${agg.count} of ${cur.n})`); + if (agg.count * 6 >= N * 0.8 || agg.count < 2) break; + const { P, Bc } = tentative(cur.b, agg, B); + lap('tentative'); + const Ps = smoothProlongator(cur, Dinv, P); + lap(`smooth (${Ps.col.length} blocks)`); + const Ac = galerkin(cur, Ps); + lap(`galerkin (${Ac.col.length} blocks)`); + lvl.P = Ps; + B = Bc; + cur = Ac; + opts.progress?.(Math.min(0.9, (depth + 1) / 4)); + } + // Coarsest level: dense Cholesky (with a tiny shift if the level has dummy degrees of freedom). + const last = levels[levels.length - 1]; + const dense = denseCholesky(last.A); + const vcycle = (k: number, b: Float64Array, x: Float64Array) => { + const lv = levels[k]; + if (k === levels.length - 1) { dense(b, x); return; } + x.fill(0); + gaussSeidel(lv.A, lv.Dinv, b, x, true); + matvec(lv.A, x, lv.t); + for (let i = 0; i < b.length; i++) lv.r[i] = b[i] - lv.t[i]; + const nx = levels[k + 1]; + const rc = new Float64Array(nx.A.n * nx.A.b); + restrict(lv.P!, lv.r, rc); + const xc = new Float64Array(rc.length); + vcycle(k + 1, rc, xc); + prolongAdd(lv.P!, xc, x); + gaussSeidel(lv.A, lv.Dinv, b, x, false); + }; + return { + levels: levels.length, + description: `smoothed aggregation multigrid, ${levels.length} levels (${levels.map((l) => l.A.n * l.A.b).join(', ')} unknowns)`, + apply(r, z) { vcycle(0, r, z); }, + }; +} + +/** Groups nodes into aggregates: a node and its strongly connected neighbours, then the rest joined to a neighbour's. */ +function aggregate(A: BlockMatrix, theta: number): { of: Int32Array; count: number } { + const { n, b, rowPtr, col, val } = A; + const bb = b * b; + const norm = (q: number) => { let s = 0; for (let k = 0; k < bb; k++) s += val[q * bb + k] ** 2; return Math.sqrt(s); }; + const diag = new Float64Array(n); + for (let i = 0; i < n; i++) { const q = blockAt(A, i, i); diag[i] = q >= 0 ? norm(q) : 0; } + const strong = (i: number, q: number) => { const j = col[q]; return j !== i && norm(q) > theta * Math.sqrt(diag[i] * diag[j]); }; + const of = new Int32Array(n).fill(-1); + let count = 0; + // Pass 1: whole neighbourhoods. + for (let i = 0; i < n; i++) { + if (of[i] >= 0) continue; + let free = true, any = false; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) if (strong(i, q)) { any = true; if (of[col[q]] >= 0) { free = false; break; } } + if (!free || !any) continue; + of[i] = count; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) if (strong(i, q)) of[col[q]] = count; + count++; + } + // Pass 2: the rest join the neighbouring aggregate they are most strongly connected to. + const pass1 = of.slice(); + for (let i = 0; i < n; i++) { + if (of[i] >= 0) continue; + let best = -1, bv = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + if (j === i || pass1[j] < 0) continue; + const v = norm(q) / Math.sqrt(diag[i] * diag[j] || 1); + if (v > bv) { bv = v; best = pass1[j]; } + } + if (best >= 0) of[i] = best; + } + // Pass 3: whatever is left (isolated groups) makes aggregates of its own. + for (let i = 0; i < n; i++) { + if (of[i] >= 0) continue; + of[i] = count; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) if (of[col[q]] < 0) of[col[q]] = count; + count++; + } + return { of, count }; +} + +/** + * Tentative prolongator: per aggregate, the rigid body motions of its nodes + * orthonormalised (QR); R becomes the coarse level's rigid body motions. + */ +function tentative(b: number, agg: { of: Int32Array; count: number }, B: Float64Array): { P: Prolongator; Bc: Float64Array } { + const n = agg.of.length; + const members: number[][] = Array.from({ length: agg.count }, () => []); + for (let i = 0; i < n; i++) members[agg.of[i]].push(i); + const c = 6; + const val = new Float64Array(n * b * c); + const Bc = new Float64Array(agg.count * c * c); + for (let a = 0; a < agg.count; a++) { + const nodes = members[a]; + const rows = nodes.length * b; + // Q: rows x 6, column-major for Gram-Schmidt. + const Q = new Float64Array(rows * c); + nodes.forEach((i, k) => { for (let r = 0; r < b; r++) for (let j = 0; j < c; j++) Q[j * rows + k * b + r] = B[i * b * c + r * c + j]; }); + const R = new Float64Array(c * c); + let ref = 0; + for (let j = 0; j < c; j++) { let s = 0; for (let r = 0; r < rows; r++) s += Q[j * rows + r] ** 2; ref = Math.max(ref, Math.sqrt(s)); } + for (let j = 0; j < c; j++) { + // Twice, for orthogonality to machine precision. + for (let pass = 0; pass < 2; pass++) { + for (let k = 0; k < j; k++) { + let d = 0; + for (let r = 0; r < rows; r++) d += Q[k * rows + r] * Q[j * rows + r]; + R[k * c + j] += d; + for (let r = 0; r < rows; r++) Q[j * rows + r] -= d * Q[k * rows + r]; + } + } + let s = 0; + for (let r = 0; r < rows; r++) s += Q[j * rows + r] ** 2; + s = Math.sqrt(s); + if (s > 1e-10 * ref) { + R[j * c + j] = s; + for (let r = 0; r < rows; r++) Q[j * rows + r] /= s; + } else { + // Dependent motion (too few nodes to tell it apart): a dummy coarse unknown. + for (let r = 0; r < rows; r++) Q[j * rows + r] = 0; + } + } + nodes.forEach((i, k) => { for (let r = 0; r < b; r++) for (let j = 0; j < c; j++) val[i * b * c + r * c + j] = Q[j * rows + k * b + r]; }); + Bc.set(R, a * c * c); + } + const rowPtr = new Int32Array(n + 1); + for (let i = 0; i < n; i++) rowPtr[i + 1] = i + 1; + return { P: { n, m: agg.count, b, c, rowPtr, col: Int32Array.from(agg.of), val }, Bc }; +} + +/** Largest eigenvalue of D^-1 A, by power iteration. */ +function spectralRadius(A: BlockMatrix, Dinv: Float64Array): number { + const N = A.n * A.b, b = A.b, bb = b * b; + let x = new Float64Array(N); + for (let i = 0; i < N; i++) x[i] = Math.sin(i * 12.9898 + 1) + 1.1; + const y = new Float64Array(N); + let lam = 1; + for (let it = 0; it < 15; it++) { + let nx = 0; + for (let i = 0; i < N; i++) nx += x[i] * x[i]; + nx = Math.sqrt(nx); + for (let i = 0; i < N; i++) x[i] /= nx; + matvec(A, x, y); + const z = new Float64Array(N); + for (let i = 0; i < A.n; i++) for (let p = 0; p < b; p++) { let s = 0; for (let c = 0; c < b; c++) s += Dinv[i * bb + p * b + c] * y[i * b + c]; z[i * b + p] = s; } + let nz = 0; + for (let i = 0; i < N; i++) nz += z[i] * z[i]; + lam = Math.sqrt(nz); + x = z; + } + return lam; +} + +/** P = (I - w D^-1 A) P0, with w = 4 / (3 rho(D^-1 A)). */ +function smoothProlongator(A: BlockMatrix, Dinv: Float64Array, P0: Prolongator): Prolongator { + const w = 4 / 3 / spectralRadius(A, Dinv); + const { n, b, rowPtr, col, val } = A; + const c = P0.c, bb = b * b, bc = b * c; + const rows: number[] = []; + const outPtr = new Int32Array(n + 1); + const outCol: number[] = []; + const outVal: number[] = []; + const acc = new Map(); + const tmp = new Float64Array(bc); + for (let i = 0; i < n; i++) { + acc.clear(); + // (A P0) row block i: sum over j of A_ij P0_j (P0 has one block per row). + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + const J = P0.col[j]; + let blk = acc.get(J); + if (!blk) { blk = new Float64Array(bc); acc.set(J, blk); } + for (let r = 0; r < b; r++) for (let k = 0; k < c; k++) { + let s = 0; + for (let m = 0; m < b; m++) s += val[q * bb + r * b + m] * P0.val[j * bc + m * c + k]; + blk[r * c + k] += s; + } + } + const own = P0.col[i]; + rows.length = 0; + for (const J of acc.keys()) rows.push(J); + if (!acc.has(own)) rows.push(own); + rows.sort((x, y) => x - y); + for (const J of rows) { + const blk = acc.get(J); + // -w D^-1 (A P0) + tmp.fill(0); + if (blk) for (let r = 0; r < b; r++) for (let k = 0; k < c; k++) { let s = 0; for (let m = 0; m < b; m++) s += Dinv[i * bb + r * b + m] * blk[m * c + k]; tmp[r * c + k] = -w * s; } + if (J === own) for (let r = 0; r < bc; r++) tmp[r] += P0.val[i * bc + r]; + outCol.push(J); + for (let r = 0; r < bc; r++) outVal.push(tmp[r]); + } + outPtr[i + 1] = outCol.length; + } + return { n, m: P0.m, b, c, rowPtr: outPtr, col: Int32Array.from(outCol), val: Float64Array.from(outVal) }; +} + +/** Coarse matrix P^T A P. */ +function galerkin(A: BlockMatrix, P: Prolongator): BlockMatrix { + const { n, b, rowPtr, col, val } = A; + const c = P.c, bb = b * b, bc = b * c, cc = c * c; + const rowsC: Map[] = Array.from({ length: P.m }, () => new Map()); + const ap = new Map(); + for (let i = 0; i < n; i++) { + ap.clear(); + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + for (let p = P.rowPtr[j]; p < P.rowPtr[j + 1]; p++) { + const J = P.col[p]; + let blk = ap.get(J); + if (!blk) { blk = new Float64Array(bc); ap.set(J, blk); } + for (let r = 0; r < b; r++) { + const a0 = q * bb + r * b; + for (let k = 0; k < c; k++) { + let s = 0; + for (let m = 0; m < b; m++) s += val[a0 + m] * P.val[p * bc + m * c + k]; + blk[r * c + k] += s; + } + } + } + } + for (let p = P.rowPtr[i]; p < P.rowPtr[i + 1]; p++) { + const I = P.col[p]; + const row = rowsC[I]; + for (const [J, blk] of ap) { + let dst = row.get(J); + if (!dst) { dst = new Float64Array(cc); row.set(J, dst); } + // P_iI^T (b x c)^T * blk (b x c) + for (let r = 0; r < c; r++) for (let k = 0; k < c; k++) { + let s = 0; + for (let m = 0; m < b; m++) s += P.val[p * bc + m * c + r] * blk[m * c + k]; + dst[r * c + k] += s; + } + } + } + } + const rp = new Int32Array(P.m + 1); + let nnz = 0; + for (let I = 0; I < P.m; I++) { nnz += rowsC[I].size; rp[I + 1] = nnz; } + const cl = new Int32Array(nnz); + const vl = new Float64Array(nnz * cc); + for (let I = 0; I < P.m; I++) { + const keys = [...rowsC[I].keys()].sort((x, y) => x - y); + keys.forEach((J, k) => { cl[rp[I] + k] = J; vl.set(rowsC[I].get(J)!, (rp[I] + k) * cc); }); + // A dummy coarse unknown (no stiffness) gets a unit diagonal so the level stays solvable. + const q = keys.indexOf(I); + if (q >= 0) { + const d = (rp[I] + q) * cc; + let scale = 0; + for (let r = 0; r < c; r++) scale = Math.max(scale, vl[d + r * c + r]); + for (let r = 0; r < c; r++) if (!(vl[d + r * c + r] > 1e-12 * scale)) { + let off = 0; + for (let k = 0; k < c; k++) off += Math.abs(vl[d + r * c + k]); + if (off <= 1e-12 * scale) vl[d + r * c + r] = scale || 1; + } + } + } + return { n: P.m, b: c, rowPtr: rp, col: cl, val: vl }; +} + +function restrict(P: Prolongator, r: Float64Array, out: Float64Array) { + out.fill(0); + const { n, b, c, rowPtr, col, val } = P; + const bc = b * c; + for (let i = 0; i < n; i++) { + for (let p = rowPtr[i]; p < rowPtr[i + 1]; p++) { + const J = col[p] * c; + for (let k = 0; k < c; k++) { + let s = 0; + for (let m = 0; m < b; m++) s += val[p * bc + m * c + k] * r[i * b + m]; + out[J + k] += s; + } + } + } +} + +function prolongAdd(P: Prolongator, xc: Float64Array, x: Float64Array) { + const { n, b, c, rowPtr, col, val } = P; + const bc = b * c; + for (let i = 0; i < n; i++) { + for (let p = rowPtr[i]; p < rowPtr[i + 1]; p++) { + const J = col[p] * c; + for (let m = 0; m < b; m++) { + let s = 0; + for (let k = 0; k < c; k++) s += val[p * bc + m * c + k] * xc[J + k]; + x[i * b + m] += s; + } + } + } +} + +/** One block Gauss-Seidel sweep, forward or backward. */ +function gaussSeidel(A: BlockMatrix, Dinv: Float64Array, rhs: Float64Array, x: Float64Array, forward: boolean) { + const { n, b, rowPtr, col, val } = A; + const bb = b * b; + const s = new Float64Array(b); + for (let k = 0; k < n; k++) { + const i = forward ? k : n - 1 - k; + for (let r = 0; r < b; r++) s[r] = rhs[i * b + r]; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + if (j === i) continue; + for (let r = 0; r < b; r++) { + let t = 0; + for (let m = 0; m < b; m++) t += val[q * bb + r * b + m] * x[j * b + m]; + s[r] -= t; + } + } + for (let r = 0; r < b; r++) { + let t = 0; + for (let m = 0; m < b; m++) t += Dinv[i * bb + r * b + m] * s[m]; + x[i * b + r] = t; + } + } +} + +/** Dense Cholesky solve of a (small) block matrix; a zero pivot (a free motion) is skipped. */ +function denseCholesky(A: BlockMatrix): (b: Float64Array, x: Float64Array) => void { + const N = A.n * A.b, bs = A.b, bb = bs * bs; + const M = new Float64Array(N * N); + for (let i = 0; i < A.n; i++) for (let q = A.rowPtr[i]; q < A.rowPtr[i + 1]; q++) { + const j = A.col[q]; + for (let r = 0; r < bs; r++) for (let c = 0; c < bs; c++) M[(i * bs + r) * N + j * bs + c] = A.val[q * bb + r * bs + c]; + } + let scale = 0; + for (let i = 0; i < N; i++) scale = Math.max(scale, M[i * N + i]); + const skip = new Uint8Array(N); + for (let k = 0; k < N; k++) { + let d = M[k * N + k]; + for (let p = 0; p < k; p++) d -= M[k * N + p] ** 2; + if (!(d > 1e-13 * scale)) { skip[k] = 1; M[k * N + k] = 1; for (let i = k + 1; i < N; i++) M[i * N + k] = 0; continue; } + const l = Math.sqrt(d); + M[k * N + k] = l; + for (let i = k + 1; i < N; i++) { + let s = M[i * N + k]; + for (let p = 0; p < k; p++) s -= M[i * N + p] * M[k * N + p]; + M[i * N + k] = s / l; + } + } + return (b, x) => { + for (let i = 0; i < N; i++) { + if (skip[i]) { x[i] = 0; continue; } + let s = b[i]; + for (let p = 0; p < i; p++) s -= M[i * N + p] * x[p]; + x[i] = s / M[i * N + i]; + } + for (let i = N - 1; i >= 0; i--) { + if (skip[i]) { x[i] = 0; continue; } + let s = x[i]; + for (let p = i + 1; p < N; p++) s -= M[p * N + i] * x[p]; + x[i] = s / M[i * N + i]; + } + }; +} + +export interface CgResult { + iterations: number; + residual: number; + converged: boolean; +} + +/** Preconditioned conjugate gradients from x = 0; tol is relative to |b|. */ +export function pcg(A: BlockMatrix, b: Float64Array, x: Float64Array, M: Preconditioner, opts: { tol?: number; maxIter?: number; progress?: (it: number, rel: number) => void } = {}): CgResult { + const N = b.length; + const tol = opts.tol ?? 1e-8; + const maxIter = opts.maxIter ?? 2000; + const r = new Float64Array(N), z = new Float64Array(N), p = new Float64Array(N), q = new Float64Array(N); + x.fill(0); + r.set(b); + let bn = 0; + for (let i = 0; i < N; i++) bn += b[i] * b[i]; + bn = Math.sqrt(bn); + if (!(bn > 0)) return { iterations: 0, residual: 0, converged: true }; + M.apply(r, z); + p.set(z); + let rz = 0; + for (let i = 0; i < N; i++) rz += r[i] * z[i]; + let rel = 1; + for (let it = 1; it <= maxIter; it++) { + matvec(A, p, q); + let pq = 0; + for (let i = 0; i < N; i++) pq += p[i] * q[i]; + if (!(pq > 0)) return { iterations: it, residual: rel, converged: false }; + const alpha = rz / pq; + let rn = 0; + for (let i = 0; i < N; i++) { x[i] += alpha * p[i]; r[i] -= alpha * q[i]; rn += r[i] * r[i]; } + rel = Math.sqrt(rn) / bn; + opts.progress?.(it, rel); + if (rel <= tol) return { iterations: it, residual: rel, converged: true }; + M.apply(r, z); + let rz2 = 0; + for (let i = 0; i < N; i++) rz2 += r[i] * z[i]; + const beta = rz2 / rz; + rz = rz2; + for (let i = 0; i < N; i++) p[i] = z[i] + beta * p[i]; + } + return { iterations: maxIter, residual: rel, converged: false }; +} diff --git a/src/parametric/src/fea/elements.ts b/src/parametric/src/fea/elements.ts new file mode 100644 index 0000000000..d7338fc3b2 --- /dev/null +++ b/src/parametric/src/fea/elements.ts @@ -0,0 +1,192 @@ +// 10-node (quadratic) tetrahedra and 6-node boundary triangles for linear +// isotropic elasticity: stiffness by 4-point Gauss quadrature (exact for +// straight-sided elements), consistent nodal loads for body forces and for +// tractions and pressures on curved faces, and stresses at the nodes. + +import { GAUSS4, quadDerivs } from './mesher'; + +/** Lame constants of an isotropic material. */ +export function lame(E: number, nu: number): { lambda: number; mu: number } { + return { lambda: (E * nu) / ((1 + nu) * (1 - 2 * nu)), mu: E / (2 * (1 + nu)) }; +} + +/** Shape functions of the 10-node tetrahedron at volume coordinates (L1, L2, L3). */ +export function quadShape(l1: number, l2: number, l3: number, out: Float64Array) { + const l0 = 1 - l1 - l2 - l3; + out[0] = l0 * (2 * l0 - 1); out[1] = l1 * (2 * l1 - 1); out[2] = l2 * (2 * l2 - 1); out[3] = l3 * (2 * l3 - 1); + out[4] = 4 * l0 * l1; out[5] = 4 * l1 * l2; out[6] = 4 * l2 * l0; out[7] = 4 * l0 * l3; out[8] = 4 * l1 * l3; out[9] = 4 * l2 * l3; +} + +const dN = new Float64Array(30); + +/** + * Gradients of the shape functions (x, y, z per node, 30 values) at volume + * coordinates; returns the Jacobian determinant (6 times the volume for a straight element). + */ +export function shapeGradients(X: ArrayLike, nodes: ArrayLike, off: number, l1: number, l2: number, l3: number, g: Float64Array): number { + quadDerivs(l1, l2, l3, dN); + let j00 = 0, j01 = 0, j02 = 0, j10 = 0, j11 = 0, j12 = 0, j20 = 0, j21 = 0, j22 = 0; + for (let a = 0; a < 10; a++) { + const n = nodes[off + a] * 3; + const x = X[n], y = X[n + 1], z = X[n + 2]; + const d0 = dN[a * 3], d1 = dN[a * 3 + 1], d2 = dN[a * 3 + 2]; + j00 += d0 * x; j01 += d0 * y; j02 += d0 * z; + j10 += d1 * x; j11 += d1 * y; j12 += d1 * z; + j20 += d2 * x; j21 += d2 * y; j22 += d2 * z; + } + const c00 = j11 * j22 - j12 * j21, c01 = j02 * j21 - j01 * j22, c02 = j01 * j12 - j02 * j11; + const c10 = j12 * j20 - j10 * j22, c11 = j00 * j22 - j02 * j20, c12 = j02 * j10 - j00 * j12; + const c20 = j10 * j21 - j11 * j20, c21 = j01 * j20 - j00 * j21, c22 = j00 * j11 - j01 * j10; + const det = j00 * c00 + j01 * c10 + j02 * c20; + const inv = 1 / det; + // dN/dx = J^-1 dN/dxi, with J[i][j] = dx_j/dxi_i. + for (let a = 0; a < 10; a++) { + const d0 = dN[a * 3], d1 = dN[a * 3 + 1], d2 = dN[a * 3 + 2]; + g[a * 3] = (c00 * d0 + c01 * d1 + c02 * d2) * inv; + g[a * 3 + 1] = (c10 * d0 + c11 * d1 + c12 * d2) * inv; + g[a * 3 + 2] = (c20 * d0 + c21 * d1 + c22 * d2) * inv; + } + return det; +} + +const grad = new Float64Array(30); + +/** + * Element stiffness (30 x 30, row-major, node-major degrees of freedom) of + * element e: K_ab^ij = int lambda a_i b_j + mu a_j b_i + mu delta_ij (a . b) dV. + * Returns false if the element is inverted. + */ +export function elementStiffness(X: ArrayLike, tets: ArrayLike, e: number, lambda: number, mu: number, K: Float64Array): boolean { + K.fill(0); + for (const [l1, l2, l3, w] of GAUSS4) { + const det = shapeGradients(X, tets, e * 10, l1, l2, l3, grad); + if (!(det > 0)) return false; + const f = det * w; + for (let a = 0; a < 10; a++) { + const ax = grad[a * 3], ay = grad[a * 3 + 1], az = grad[a * 3 + 2]; + for (let b = a; b < 10; b++) { + const bx = grad[b * 3], by = grad[b * 3 + 1], bz = grad[b * 3 + 2]; + const dot = mu * (ax * bx + ay * by + az * bz); + const r = a * 3, c = b * 3; + K[r * 30 + c] += f * (lambda * ax * bx + mu * ax * bx + dot); + K[r * 30 + c + 1] += f * (lambda * ax * by + mu * ay * bx); + K[r * 30 + c + 2] += f * (lambda * ax * bz + mu * az * bx); + K[(r + 1) * 30 + c] += f * (lambda * ay * bx + mu * ax * by); + K[(r + 1) * 30 + c + 1] += f * (lambda * ay * by + mu * ay * by + dot); + K[(r + 1) * 30 + c + 2] += f * (lambda * ay * bz + mu * az * by); + K[(r + 2) * 30 + c] += f * (lambda * az * bx + mu * ax * bz); + K[(r + 2) * 30 + c + 1] += f * (lambda * az * by + mu * ay * bz); + K[(r + 2) * 30 + c + 2] += f * (lambda * az * bz + mu * az * bz + dot); + } + } + } + // Mirror the upper node blocks. + for (let a = 0; a < 10; a++) for (let b = a + 1; b < 10; b++) { + for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) K[(b * 3 + j) * 30 + a * 3 + i] = K[(a * 3 + i) * 30 + b * 3 + j]; + } + return true; +} + +const Nv = new Float64Array(10); + +/** Adds the consistent nodal loads of a body force b (force per volume) on element e to F. Returns the element's volume. */ +export function addBodyForce(X: ArrayLike, tets: ArrayLike, e: number, b: ArrayLike, F: Float64Array): number { + let vol = 0; + for (const [l1, l2, l3, w] of GAUSS4) { + const det = shapeGradients(X, tets, e * 10, l1, l2, l3, grad); + quadShape(l1, l2, l3, Nv); + const f = det * w; + vol += f; + for (let a = 0; a < 10; a++) { + const n = tets[e * 10 + a] * 3; + F[n] += Nv[a] * f * b[0]; F[n + 1] += Nv[a] * f * b[1]; F[n + 2] += Nv[a] * f * b[2]; + } + } + return vol; +} + +// 6-point Gauss rule on the triangle (degree 4): (s, t, weight of the unit triangle, area 1/2). +const TA = 0.445948490915965, TB = 0.091576213509771, WA = 0.223381589678011 / 2, WB = 0.109951743655322 / 2; +const TRI6: [number, number, number][] = [ + [TA, TA, WA], [1 - 2 * TA, TA, WA], [TA, 1 - 2 * TA, WA], + [TB, TB, WB], [1 - 2 * TB, TB, WB], [TB, 1 - 2 * TB, WB], +]; + +/** Shape functions and their s, t derivatives of the 6-node triangle (corners 0-2, then edges 01, 12, 20). */ +function triShape(s: number, t: number, N: Float64Array, Ns: Float64Array, Nt: Float64Array) { + const r = 1 - s - t; + N[0] = r * (2 * r - 1); N[1] = s * (2 * s - 1); N[2] = t * (2 * t - 1); N[3] = 4 * r * s; N[4] = 4 * s * t; N[5] = 4 * t * r; + Ns[0] = 1 - 4 * r; Ns[1] = 4 * s - 1; Ns[2] = 0; Ns[3] = 4 * (r - s); Ns[4] = 4 * t; Ns[5] = -4 * t; + Nt[0] = 1 - 4 * r; Nt[1] = 0; Nt[2] = 4 * t - 1; Nt[3] = -4 * s; Nt[4] = 4 * s; Nt[5] = 4 * (r - t); +} + +const tN = new Float64Array(6), tNs = new Float64Array(6), tNt = new Float64Array(6); + +/** + * Integrates over boundary triangle f (6 nodes): calls fn(node slot, weight N_a dA, n dA) per + * quadrature point and node, with n dA the area-weighted outward normal. Returns its area. + */ +export function integrateTriangle(X: ArrayLike, tris: ArrayLike, f: number, fn?: (a: number, w: number, nx: number, ny: number, nz: number) => void): number { + let area = 0; + for (const [s, t, w] of TRI6) { + triShape(s, t, tN, tNs, tNt); + let sx = 0, sy = 0, sz = 0, tx = 0, ty = 0, tz = 0; + for (let a = 0; a < 6; a++) { + const n = tris[f * 6 + a] * 3; + sx += tNs[a] * X[n]; sy += tNs[a] * X[n + 1]; sz += tNs[a] * X[n + 2]; + tx += tNt[a] * X[n]; ty += tNt[a] * X[n + 1]; tz += tNt[a] * X[n + 2]; + } + const nx = (sy * tz - sz * ty) * w, ny = (sz * tx - sx * tz) * w, nz = (sx * ty - sy * tx) * w; + const dA = Math.hypot(nx, ny, nz); + area += dA; + if (fn) for (let a = 0; a < 6; a++) fn(a, tN[a] * dA, tN[a] * nx, tN[a] * ny, tN[a] * nz); + } + return area; +} + +/** Natural coordinates of the 10 nodes of the tetrahedron (L1, L2, L3). */ +export const TET_NODES: [number, number, number][] = [ + [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0], [0, 0, 0.5], [0.5, 0, 0.5], [0, 0.5, 0.5], +]; + +/** + * Strain (xx, yy, zz, xy, yz, zx as tensor components) at each node of element e from + * the displacements U; 60 values (6 per node). + */ +export function elementNodeStrains(X: ArrayLike, tets: ArrayLike, e: number, U: ArrayLike, out: Float64Array) { + for (let k = 0; k < 10; k++) { + const [l1, l2, l3] = TET_NODES[k]; + shapeGradients(X, tets, e * 10, l1, l2, l3, grad); + let uxx = 0, uxy = 0, uxz = 0, uyx = 0, uyy = 0, uyz = 0, uzx = 0, uzy = 0, uzz = 0; + for (let a = 0; a < 10; a++) { + const n = tets[e * 10 + a] * 3; + const gx = grad[a * 3], gy = grad[a * 3 + 1], gz = grad[a * 3 + 2]; + const ux = U[n], uy = U[n + 1], uz = U[n + 2]; + uxx += ux * gx; uxy += ux * gy; uxz += ux * gz; + uyx += uy * gx; uyy += uy * gy; uyz += uy * gz; + uzx += uz * gx; uzy += uz * gy; uzz += uz * gz; + } + const o = k * 6; + out[o] = uxx; out[o + 1] = uyy; out[o + 2] = uzz; + out[o + 3] = (uxy + uyx) / 2; out[o + 4] = (uyz + uzy) / 2; out[o + 5] = (uzx + uxz) / 2; + } +} + +/** Eigenvalues of a symmetric 3 x 3 tensor (xx, yy, zz, xy, yz, zx), largest first. */ +export function principal(xx: number, yy: number, zz: number, xy: number, yz: number, zx: number): [number, number, number] { + const p1 = xy * xy + yz * yz + zx * zx; + const q = (xx + yy + zz) / 3; + if (p1 <= 1e-30 * (xx * xx + yy * yy + zz * zz + 1e-300)) { + const v = [xx, yy, zz].sort((a, b) => b - a); + return [v[0], v[1], v[2]]; + } + const p2 = (xx - q) ** 2 + (yy - q) ** 2 + (zz - q) ** 2 + 2 * p1; + const p = Math.sqrt(p2 / 6); + const bxx = (xx - q) / p, byy = (yy - q) / p, bzz = (zz - q) / p, bxy = xy / p, byz = yz / p, bzx = zx / p; + const detB = bxx * (byy * bzz - byz * byz) - bxy * (bxy * bzz - byz * bzx) + bzx * (bxy * byz - byy * bzx); + const r = Math.max(-1, Math.min(1, detB / 2)); + const phi = Math.acos(r) / 3; + const e1 = q + 2 * p * Math.cos(phi); + const e3 = q + 2 * p * Math.cos(phi + (2 * Math.PI) / 3); + return [e1, 3 * q - e1 - e3, e3]; +} diff --git a/src/parametric/src/fea/static.ts b/src/parametric/src/fea/static.ts new file mode 100644 index 0000000000..7b94e1eae4 --- /dev/null +++ b/src/parametric/src/fea/static.ts @@ -0,0 +1,442 @@ +// Linear static analysis on a quadratic tetrahedral mesh: assembly of the +// stiffness matrix, loads, fixtures (as constraints in each node's own +// directions), the check that the fixtures hold the part, the solve, and the +// stresses, strains and reactions that come out of it. +// +// Units: millimetres, newtons, megapascals (N/mm^2), tonnes per cubic +// millimetre for density (so density times mm/s^2 is N/mm^3). + +import { type BlockMatrix, type Preconditioner, blockAt, blockJacobi, matvec, meshPattern, pcg, smoothedAggregation } from './amg'; +import { addBodyForce, elementNodeStrains, elementStiffness, integrateTriangle, lame, principal } from './elements'; +import type { TetMesh } from './mesher'; + +export type Vec3 = [number, number, number]; + +export type FixtureInput = + | { kind: 'fixed'; faces: number[] } + /** No motion normal to the faces (each node: the mesh normal there). */ + | { kind: 'roller'; faces: number[] } + /** A cylindrical face that may only turn about its axis (no radial or axial motion). */ + | { kind: 'hinge'; faces: number[]; axis: { p: Vec3; d: Vec3 } }; + +export type LoadInput = + /** Total force spread evenly over the faces' area: along dir, or (dir null) pressing on the faces as a pressure would. */ + | { kind: 'force'; faces: number[]; total: number; dir: Vec3 | null } + /** Pressure (MPa), pushing into the faces. */ + | { kind: 'pressure'; faces: number[]; value: number } + /** Acceleration of gravity (mm/s^2): the part's weight acts along it. */ + | { kind: 'gravity'; accel: Vec3 }; + +export interface StaticInput { + /** Elastic modulus (MPa), Poisson's ratio, density (t/mm^3). */ + E: number; + nu: number; + density: number; + fixtures: FixtureInput[]; + loads: LoadInput[]; +} + +export interface StaticResult { + /** Displacement per node (x, y, z). */ + U: Float64Array; + /** Per node: von Mises stress, principal stresses (largest first), equivalent strain. */ + vonMises: Float64Array; + p1: Float64Array; + p2: Float64Array; + p3: Float64Array; + strain: Float64Array; + /** Stress components per node (xx, yy, zz, xy, yz, zx). */ + stress: Float64Array; + /** Reaction force of each fixture, and the sum of the applied loads (N). */ + reactions: Vec3[]; + applied: Vec3; + /** Area each load acts on, as meshed (mm^2): 0 for gravity. */ + loadAreas: number[]; + dofs: number; + iterations: number; + residual: number; + solver: string; + ms: { assemble: number; setup: number; solve: number; stress: number }; +} + +/** A study the solver cannot run, with a message for the user. */ +export class StudyError extends Error {} + +const AXES = ['X', 'Y', 'Z']; + +/** + * Whether the fixtures hold every piece of the mesh: rigid motions they do + * not stop are described ('free to move along X', 'free to turn about ...'). + */ +export function rigidMotions(mesh: TetMesh, constrained: Map): string[] { + const X = mesh.nodes, nn = mesh.nodes.length / 3; + // Pieces of the mesh (connected through elements). + const parent = new Int32Array(nn).map((_, i) => i); + const find = (x: number): number => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }; + const T = mesh.tets; + for (let e = 0; e < T.length; e += 10) { const a = find(T[e]); for (let k = 1; k < 10; k++) { const b = find(T[e + k]); if (a !== b) parent[b] = a; } } + const pieces = new Map(); + for (let e = 0; e < T.length; e += 10) { + for (let k = 0; k < 10; k++) { + const v = T[e + k], r = find(v); + let p = pieces.get(r); + if (!p) pieces.set(r, (p = { c: [0, 0, 0], n: 0, M: new Array(36).fill(0) })); + } + } + const seen = new Uint8Array(nn); + for (let e = 0; e < T.length; e++) { + const v = T[e]; + if (seen[v]) continue; + seen[v] = 1; + const p = pieces.get(find(v))!; + p.c[0] += X[v * 3]; p.c[1] += X[v * 3 + 1]; p.c[2] += X[v * 3 + 2]; p.n++; + } + let L = 0; + for (const p of pieces.values()) { p.c = [p.c[0] / p.n, p.c[1] / p.n, p.c[2] / p.n]; } + for (let v = 0; v < nn; v++) if (seen[v]) { const p = pieces.get(find(v))!; L = Math.max(L, Math.hypot(X[v * 3] - p.c[0], X[v * 3 + 1] - p.c[1], X[v * 3 + 2] - p.c[2])); } + L = L || 1; + // Each constrained direction d at x stops the rigid motions (t, w) with d.t + ((x - c) x d).w != 0. + for (const [v, dirs] of constrained) { + const p = pieces.get(find(v)); + if (!p) continue; + const r = [(X[v * 3] - p.c[0]) / L, (X[v * 3 + 1] - p.c[1]) / L, (X[v * 3 + 2] - p.c[2]) / L]; + for (const d of dirs) { + const row = [d[0], d[1], d[2], r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]]; + for (let i = 0; i < 6; i++) for (let j = 0; j < 6; j++) p.M[i * 6 + j] += row[i] * row[j]; + } + } + const free: string[] = []; + const several = pieces.size > 1; + let k = 0; + for (const p of pieces.values()) { + k++; + const { values, vectors } = jacobiEigen(p.M, 6); + const top = Math.max(...values, 0); + // The free motions: eigenvectors of (nearly) zero eigenvalues. + const nul: number[][] = []; + values.forEach((lam, i) => { if (!(top > 0) || lam <= 1e-9 * top) nul.push(vectors.slice(i * 6, i * 6 + 6)); }); + if (!nul.length) continue; + const where = several ? ` (piece ${k} of ${pieces.size})` : ''; + // Name them along the axes where they are: a motion along X is free if its projection on the free motions is whole. + const inNull = (v: number[]) => { let s = 0; for (const n of nul) { let d = 0; for (let q = 0; q < 6; q++) d += n[q] * v[q]; s += d * d; } return s; }; + const named: string[] = []; + for (let a = 0; a < 3; a++) { const v = [0, 0, 0, 0, 0, 0]; v[a] = 1; if (inNull(v) > 0.98) named.push(`free to move along ${AXES[a]}`); } + // Turning about an axis along X (through any point): some free motion has a rotation part along X alone. + for (let a = 0; a < 3; a++) { + // Largest |w_a| / |w| over the free motions' span: the rotation parts' Gram matrix. + const W = nul.map((n) => [n[3], n[4], n[5]]); + const G = W.map((x) => W.map((y) => x[0] * y[0] + x[1] * y[1] + x[2] * y[2])); + const g = W.map((x) => x[a]); + // Best combination c maximising (g.c)^2 / (c.G.c): solve G c = g (least squares by Jacobi eigen). + const m = W.length; + const { values: gv, vectors: gV } = jacobiEigen(G.flat(), m); + let ratio = 0; + const gmax = Math.max(...gv, 0); + gv.forEach((lam, i) => { if (lam > 1e-9 * gmax && gmax > 0) { let d = 0; for (let q = 0; q < m; q++) d += gV[i * m + q] * g[q]; ratio += (d * d) / lam; } }); + if (ratio > 0.98) named.push(`free to turn about ${AXES[a]}`); + } + if (named.length >= nul.length) { for (const n of named) free.push(n + where); continue; } + // Otherwise the eigenvectors as they are. + for (const v of nul) { + const t = Math.hypot(v[0], v[1], v[2]), w = Math.hypot(v[3], v[4], v[5]); + if (w < 0.05 * t) free.push(`free to move ${describeDir([v[0], v[1], v[2]])}${where}`); + else free.push(`free to turn ${describeDir([v[3] / w, v[4] / w, v[5] / w], 'about')}${where}`); + } + } + return free; +} + +function describeDir(d: number[], prep = 'along'): string { + const n = Math.hypot(d[0], d[1], d[2]) || 1; + const u = d.map((x) => x / n); + const i = [0, 1, 2].reduce((b, k) => (Math.abs(u[k]) > Math.abs(u[b]) ? k : b), 0); + if (Math.abs(u[i]) > 0.999) return `${prep} ${AXES[i]}`; + return `${prep} (${u.map((x) => x.toFixed(2)).join(', ')})`; +} + +/** Eigenvalues and vectors (rows of `vectors`) of a symmetric n x n matrix (cyclic Jacobi). */ +export function jacobiEigen(Ain: number[], n: number): { values: number[]; vectors: number[] } { + const A = Ain.slice(); + const V = new Array(n * n).fill(0); + for (let i = 0; i < n; i++) V[i * n + i] = 1; + for (let sweep = 0; sweep < 60; sweep++) { + let off = 0; + for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) off += A[i * n + j] ** 2; + if (off < 1e-30) break; + for (let p = 0; p < n; p++) for (let q = p + 1; q < n; q++) { + const apq = A[p * n + q]; + if (Math.abs(apq) < 1e-300) continue; + const theta = (A[q * n + q] - A[p * n + p]) / (2 * apq); + const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1)); + const c = 1 / Math.sqrt(t * t + 1), s = t * c; + for (let k = 0; k < n; k++) { + const akp = A[k * n + p], akq = A[k * n + q]; + A[k * n + p] = c * akp - s * akq; A[k * n + q] = s * akp + c * akq; + } + for (let k = 0; k < n; k++) { + const apk = A[p * n + k], aqk = A[q * n + k]; + A[p * n + k] = c * apk - s * aqk; A[q * n + k] = s * apk + c * aqk; + } + for (let k = 0; k < n; k++) { + const vkp = V[k * n + p], vkq = V[k * n + q]; + V[k * n + p] = c * vkp - s * vkq; V[k * n + q] = s * vkp + c * vkq; + } + } + } + const values = Array.from({ length: n }, (_, i) => A[i * n + i]); + const vectors: number[] = []; + for (let i = 0; i < n; i++) for (let k = 0; k < n; k++) vectors.push(V[k * n + i]); + return { values, vectors }; +} + +/** Nodes of the boundary triangles on the given faces. */ +function faceNodes(mesh: TetMesh, faces: Set): number[] { + const out = new Set(); + for (let f = 0; f < mesh.triFace.length; f++) if (faces.has(mesh.triFace[f])) for (let a = 0; a < 6; a++) out.add(mesh.tris[f * 6 + a]); + return [...out]; +} + +/** The constrained directions of each node (global unit vectors). */ +export function constraintsOf(mesh: TetMesh, fixtures: FixtureInput[]): Map { + const X = mesh.nodes; + const out = new Map(); + const add = (v: number, d: Vec3) => { let l = out.get(v); if (!l) out.set(v, (l = [])); l.push(d); }; + fixtures.forEach((fx, i) => { + const faces = new Set(fx.faces); + const nodes = faceNodes(mesh, faces); + if (!nodes.length) throw new StudyError(`Fixture ${i + 1}: its faces are not in the mesh.`); + if (fx.kind === 'fixed') { for (const v of nodes) { add(v, [1, 0, 0]); add(v, [0, 1, 0]); add(v, [0, 0, 1]); } return; } + if (fx.kind === 'roller') { + // The surface normal at each node: the (area weighted) normals of the triangles on the faces around it. + const nrm = new Map(); + for (let f = 0; f < mesh.triFace.length; f++) { + if (!faces.has(mesh.triFace[f])) continue; + const a = mesh.tris[f * 6] * 3, b = mesh.tris[f * 6 + 1] * 3, c = mesh.tris[f * 6 + 2] * 3; + const ux = X[b] - X[a], uy = X[b + 1] - X[a + 1], uz = X[b + 2] - X[a + 2], wx = X[c] - X[a], wy = X[c + 1] - X[a + 1], wz = X[c + 2] - X[a + 2]; + const fn: Vec3 = [uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx]; + for (let q = 0; q < 6; q++) { + const v = mesh.tris[f * 6 + q]; + let n = nrm.get(v); + if (!n) nrm.set(v, (n = [0, 0, 0])); + n[0] += fn[0]; n[1] += fn[1]; n[2] += fn[2]; + } + } + for (const [v, n] of nrm) { const l = Math.hypot(n[0], n[1], n[2]); if (l > 0) add(v, [n[0] / l, n[1] / l, n[2] / l]); } + return; + } + const { p, d } = fx.axis; + const dl = Math.hypot(d[0], d[1], d[2]) || 1; + const ax: Vec3 = [d[0] / dl, d[1] / dl, d[2] / dl]; + for (const v of nodes) { + const r = [X[v * 3] - p[0], X[v * 3 + 1] - p[1], X[v * 3 + 2] - p[2]]; + const t = r[0] * ax[0] + r[1] * ax[1] + r[2] * ax[2]; + const rad: Vec3 = [r[0] - t * ax[0], r[1] - t * ax[1], r[2] - t * ax[2]]; + const rl = Math.hypot(rad[0], rad[1], rad[2]); + add(v, ax); + if (rl > 1e-9) add(v, [rad[0] / rl, rad[1] / rl, rad[2] / rl]); + else { add(v, [1, 0, 0]); add(v, [0, 1, 0]); add(v, [0, 0, 1]); } + } + }); + return out; +} + +/** Orthonormal basis (columns of a 3 x 3 rotation, row-major) whose first k columns span the directions; returns k. */ +function constraintBasis(dirs: Vec3[], R: Float64Array, off: number): number { + const basis: Vec3[] = []; + for (const d of dirs) { + const v: Vec3 = [d[0], d[1], d[2]]; + for (const b of basis) { const s = v[0] * b[0] + v[1] * b[1] + v[2] * b[2]; v[0] -= s * b[0]; v[1] -= s * b[1]; v[2] -= s * b[2]; } + const l = Math.hypot(v[0], v[1], v[2]); + if (l > 1e-3) basis.push([v[0] / l, v[1] / l, v[2] / l]); + if (basis.length === 3) break; + } + const k = basis.length; + // Complete to a right-handed frame. + for (const e of [[1, 0, 0], [0, 1, 0], [0, 0, 1]] as Vec3[]) { + if (basis.length === 3) break; + const v: Vec3 = [e[0], e[1], e[2]]; + for (const b of basis) { const s = v[0] * b[0] + v[1] * b[1] + v[2] * b[2]; v[0] -= s * b[0]; v[1] -= s * b[1]; v[2] -= s * b[2]; } + const l = Math.hypot(v[0], v[1], v[2]); + if (l > 0.3) basis.push([v[0] / l, v[1] / l, v[2] / l]); + } + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) R[off + r * 3 + c] = basis[c][r]; + return k; +} + +/** The loads as nodal forces; also the total applied force and each load's meshed area. */ +export function loadVector(mesh: TetMesh, input: StaticInput): { F: Float64Array; applied: Vec3; areas: number[] } { + const X = mesh.nodes, N = X.length / 3; + const F = new Float64Array(N * 3); + const areas: number[] = []; + input.loads.forEach((ld, i) => { + if (ld.kind === 'gravity') { + const b = [input.density * ld.accel[0], input.density * ld.accel[1], input.density * ld.accel[2]]; + for (let e = 0; e < mesh.tets.length / 10; e++) addBodyForce(X, mesh.tets, e, b, F); + areas.push(0); + return; + } + const faces = new Set(ld.faces); + const tris: number[] = []; + for (let f = 0; f < mesh.triFace.length; f++) if (faces.has(mesh.triFace[f])) tris.push(f); + if (!tris.length) throw new StudyError(`Load ${i + 1}: its faces are not in the mesh.`); + let area = 0; + for (const f of tris) area += integrateTriangle(X, mesh.tris, f); + areas.push(area); + if (ld.kind === 'force' && ld.dir) { + const l = Math.hypot(ld.dir[0], ld.dir[1], ld.dir[2]) || 1; + const t = [(ld.total * ld.dir[0]) / l / area, (ld.total * ld.dir[1]) / l / area, (ld.total * ld.dir[2]) / l / area]; + for (const f of tris) integrateTriangle(X, mesh.tris, f, (a, w) => { const n = mesh.tris[f * 6 + a] * 3; F[n] += t[0] * w; F[n + 1] += t[1] * w; F[n + 2] += t[2] * w; }); + return; + } + // Pressure (or a normal force as the pressure that adds up to it on a flat face): along the inward normal. + const p = ld.kind === 'pressure' ? ld.value : ld.total / area; + for (const f of tris) integrateTriangle(X, mesh.tris, f, (a, _w, nx, ny, nz) => { const n = mesh.tris[f * 6 + a] * 3; F[n] -= p * nx; F[n + 1] -= p * ny; F[n + 2] -= p * nz; }); + }); + const applied: Vec3 = [0, 0, 0]; + for (let v = 0; v < N; v++) { applied[0] += F[v * 3]; applied[1] += F[v * 3 + 1]; applied[2] += F[v * 3 + 2]; } + return { F, applied, areas }; +} + +export function solveStatic(mesh: TetMesh, input: StaticInput, progress: (stage: string, f: number) => void = () => {}, debug?: (m: string) => void): StaticResult { + const t0 = performance.now(); + const X = mesh.nodes, N = X.length / 3; + if (!(input.E > 0) || !(input.nu >= 0 && input.nu < 0.5)) throw new StudyError('The material\'s elastic properties are not valid.'); + if (!input.fixtures.length) throw new StudyError('The study has no fixtures: the part is free to move. Add a fixture to hold it.'); + if (!input.loads.length) throw new StudyError('The study has no loads. Add a force, pressure or gravity.'); + const constrained = constraintsOf(mesh, input.fixtures); + const free = rigidMotions(mesh, constrained); + if (free.length) throw new StudyError(`The fixtures do not hold the part: it is ${free.join(', ')}. Add fixtures (or change them) so that it cannot move or turn as a rigid body.`); + const { F, applied, areas } = loadVector(mesh, input); + + // ---- assembly ---- + progress('Assembling', 0); + const A = meshPattern(N, mesh.tets, 10); + const { lambda, mu } = lame(input.E, input.nu); + const Ke = new Float64Array(900); + const ne = mesh.tets.length / 10; + const slot = new Int32Array(100); + for (let e = 0; e < ne; e++) { + if (!elementStiffness(X, mesh.tets, e, lambda, mu, Ke)) throw new StudyError('The mesh has an inverted element. Try another mesh size.'); + for (let a = 0; a < 10; a++) for (let b = 0; b < 10; b++) slot[a * 10 + b] = blockAt(A, mesh.tets[e * 10 + a], mesh.tets[e * 10 + b]); + for (let a = 0; a < 10; a++) for (let b = 0; b < 10; b++) { + const q = slot[a * 10 + b] * 9; + for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) A.val[q + i * 3 + j] += Ke[(a * 3 + i) * 30 + b * 3 + j]; + } + if ((e & 4095) === 0) progress('Assembling', e / ne); + } + // Rows of the constrained nodes as assembled, for the reactions. + const reactionRows = new Map(); + for (const v of constrained.keys()) reactionRows.set(v, { cols: A.col.slice(A.rowPtr[v], A.rowPtr[v + 1]), vals: A.val.slice(A.rowPtr[v] * 9, A.rowPtr[v + 1] * 9) }); + const Forig = F.slice(); + + // ---- constraints: each constrained node in its own frame, the constrained directions removed ---- + const R = new Float64Array(N * 9); + const k = new Int8Array(N); + for (let v = 0; v < N; v++) { R[v * 9] = R[v * 9 + 4] = R[v * 9 + 8] = 1; } + for (const [v, dirs] of constrained) k[v] = constraintBasis(dirs, R, v * 9); + const rotated = new Uint8Array(N); + for (const v of constrained.keys()) rotated[v] = k[v] < 3 ? 1 : 0; + const tmp = new Float64Array(9); + for (let i = 0; i < N; i++) { + for (let q = A.rowPtr[i]; q < A.rowPtr[i + 1]; q++) { + const j = A.col[q]; + if (!rotated[i] && !rotated[j] && !k[i] && !k[j]) continue; + const o = q * 9; + if (rotated[i] || rotated[j]) { + // R_i^T A_ij R_j + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) { + let s = 0; + for (let m = 0; m < 3; m++) for (let l = 0; l < 3; l++) s += R[i * 9 + m * 3 + r] * A.val[o + m * 3 + l] * R[j * 9 + l * 3 + c]; + tmp[r * 3 + c] = s; + } + A.val.set(tmp, o); + } + for (let r = 0; r < k[i]; r++) for (let c = 0; c < 3; c++) A.val[o + r * 3 + c] = 0; + for (let c = 0; c < k[j]; c++) for (let r = 0; r < 3; r++) A.val[o + r * 3 + c] = 0; + } + } + const diagScale = (() => { let s = 0; for (let i = 0; i < N; i++) { const q = blockAt(A, i, i) * 9; s = Math.max(s, A.val[q], A.val[q + 4], A.val[q + 8]); } return s; })(); + for (let i = 0; i < N; i++) { + if (!k[i]) continue; + const q = blockAt(A, i, i) * 9; + for (let r = 0; r < k[i]; r++) A.val[q + r * 4] = diagScale; + const f = [F[i * 3], F[i * 3 + 1], F[i * 3 + 2]]; + for (let r = 0; r < 3; r++) F[i * 3 + r] = r < k[i] ? 0 : R[i * 9 + r] * f[0] + R[i * 9 + 3 + r] * f[1] + R[i * 9 + 6 + r] * f[2]; + } + const tAsm = performance.now(); + + // ---- solve ---- + progress('Preparing the solver', 0); + let M: Preconditioner; + try { + M = smoothedAggregation(A, X, { progress: (f) => progress('Preparing the solver', f), debug, frames: R, held: k }); + } catch { + M = blockJacobi(A); + } + const tSetup = performance.now(); + const Ul = new Float64Array(N * 3); + let res = pcg(A, F, Ul, M, { tol: 1e-9, maxIter: 800, progress: (it, rel) => { if (it % 5 === 0) progress('Solving', Math.min(0.99, Math.log10(1 / Math.max(rel, 1e-12)) / 9)); } }); + if (!res.converged && M.levels > 1) { + // Fall back on the simple preconditioner (slow, but it does not depend on the aggregation). + M = blockJacobi(A); + res = pcg(A, F, Ul, M, { tol: 1e-9, maxIter: 20000, progress: (it, rel) => { if (it % 25 === 0) progress('Solving', Math.min(0.99, Math.log10(1 / Math.max(rel, 1e-12)) / 9)); } }); + } + if (!res.converged && !(res.residual < 1e-5)) throw new StudyError('The solver did not converge. The study may be poorly constrained, or the mesh may have very poor elements: try another mesh size.'); + const tSolve = performance.now(); + // Back to global directions. + const U = new Float64Array(N * 3); + for (let v = 0; v < N; v++) { + for (let r = 0; r < 3; r++) U[v * 3 + r] = R[v * 9 + r * 3] * Ul[v * 3] + R[v * 9 + r * 3 + 1] * Ul[v * 3 + 1] + R[v * 9 + r * 3 + 2] * Ul[v * 3 + 2]; + } + + // ---- reactions ---- + const reactions: Vec3[] = input.fixtures.map(() => [0, 0, 0]); + const owner = new Map(); + input.fixtures.forEach((fx, i) => { for (const v of faceNodes(mesh, new Set(fx.faces))) if (!owner.has(v)) owner.set(v, i); }); + for (const [v, row] of reactionRows) { + const r = [-Forig[v * 3], -Forig[v * 3 + 1], -Forig[v * 3 + 2]]; + for (let q = 0; q < row.cols.length; q++) { + const j = row.cols[q] * 3, o = q * 9; + for (let a = 0; a < 3; a++) r[a] += row.vals[o + a * 3] * U[j] + row.vals[o + a * 3 + 1] * U[j + 1] + row.vals[o + a * 3 + 2] * U[j + 2]; + } + const i = owner.get(v) ?? 0; + for (let a = 0; a < 3; a++) reactions[i][a] += r[a]; + } + + // ---- stresses ---- + progress('Computing stresses', 0); + const S = new Float64Array(N * 6), Eps = new Float64Array(N * 6), count = new Float64Array(N); + const strains = new Float64Array(60); + for (let e = 0; e < ne; e++) { + elementNodeStrains(X, mesh.tets, e, U, strains); + for (let a = 0; a < 10; a++) { + const v = mesh.tets[e * 10 + a]; + count[v]++; + for (let c = 0; c < 6; c++) Eps[v * 6 + c] += strains[a * 6 + c]; + } + } + const vonMises = new Float64Array(N), p1 = new Float64Array(N), p2 = new Float64Array(N), p3 = new Float64Array(N), strain = new Float64Array(N); + for (let v = 0; v < N; v++) { + const n = count[v] || 1; + const exx = Eps[v * 6] / n, eyy = Eps[v * 6 + 1] / n, ezz = Eps[v * 6 + 2] / n, exy = Eps[v * 6 + 3] / n, eyz = Eps[v * 6 + 4] / n, ezx = Eps[v * 6 + 5] / n; + const tr = exx + eyy + ezz; + const sxx = lambda * tr + 2 * mu * exx, syy = lambda * tr + 2 * mu * eyy, szz = lambda * tr + 2 * mu * ezz; + const sxy = 2 * mu * exy, syz = 2 * mu * eyz, szx = 2 * mu * ezx; + S.set([sxx, syy, szz, sxy, syz, szx], v * 6); + vonMises[v] = Math.sqrt(0.5 * ((sxx - syy) ** 2 + (syy - szz) ** 2 + (szz - sxx) ** 2) + 3 * (sxy * sxy + syz * syz + szx * szx)); + const pr = principal(sxx, syy, szz, sxy, syz, szx); + p1[v] = pr[0]; p2[v] = pr[1]; p3[v] = pr[2]; + const m = tr / 3; + const dev = (exx - m) ** 2 + (eyy - m) ** 2 + (ezz - m) ** 2 + 2 * (exy * exy + eyz * eyz + ezx * ezx); + strain[v] = Math.sqrt((2 / 3) * dev); + } + const tEnd = performance.now(); + return { + U, vonMises, p1, p2, p3, strain, stress: S, reactions, applied, loadAreas: areas, dofs: N * 3, + iterations: res.iterations, residual: res.residual, solver: M.description, + ms: { assemble: tAsm - t0, setup: tSetup - tAsm, solve: tSolve - tSetup, stress: tEnd - tSolve }, + }; +} + +export type { BlockMatrix }; +void matvec; diff --git a/src/parametric/tests/fea-solver.test.ts b/src/parametric/tests/fea-solver.test.ts new file mode 100644 index 0000000000..7e07ebbdc2 --- /dev/null +++ b/src/parametric/tests/fea-solver.test.ts @@ -0,0 +1,134 @@ +// Accuracy of the static stress analysis against closed-form results, on +// parts built and triangulated by the real kernel and meshed with 10-node +// tetrahedra: a cantilever (Euler-Bernoulli deflection and bending stress), +// a bar in tension (F/A, FL/AE), a plate with a hole (stress concentration), +// equilibrium of reactions and loads, gravity, and an under-constrained study. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import type { FaceInfo } from '../src/kernel/protocol'; +import { SurfaceIndex } from '../src/fea/surface'; +import { meshSolid } from '../src/fea/mesher'; +import { type LoadInput, type StaticInput, StudyError, solveStatic } from '../src/fea/static'; +import type { Feature } from '../src/model/types'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +const STEEL = { E: 200000, nu: 0.3, density: 7.85e-9 }; + +async function meshOf(features: Feature[], size: number) { + const b = new ModelBuilder(); + const res = await b.build(req(features, { quality: 1 })); + expect(res.status.every((s) => s.ok)).toBe(true); + const surf = new SurfaceIndex(b.feaSurface(size / 50)); + return { mesh: meshSolid(surf, { size }), faces: res.faces }; +} + +/** Index of the planar face whose outward normal is n and centre has coordinate k equal to v. */ +function planar(faces: FaceInfo[], n: [number, number, number], k?: number, v?: number): number { + const i = faces.findIndex((f) => f.type === 'plane' && f.normal && Math.abs(f.normal[0] - n[0]) + Math.abs(f.normal[1] - n[1]) + Math.abs(f.normal[2] - n[2]) < 1e-6 && (k === undefined || Math.abs(f.center[k] - v!) < 1e-6)); + expect(i).toBeGreaterThanOrEqual(0); + return i; +} + +/** Value of a nodal field at the node nearest to p. */ +function at(nodes: Float64Array, field: ArrayLike, p: number[], stride = 1, comp = 0): number { + let best = 0, bd = Infinity; + for (let v = 0; v < nodes.length / 3; v++) { + const d = (nodes[v * 3] - p[0]) ** 2 + (nodes[v * 3 + 1] - p[1]) ** 2 + (nodes[v * 3 + 2] - p[2]) ** 2; + if (d < bd) { bd = d; best = v; } + } + return field[best * stride + comp]; +} + +describe('static analysis accuracy', () => { + it('cantilever: tip deflection and bending stress (Euler-Bernoulli)', async () => { + // 200 long (x), 20 deep (y), 10 wide (z); fixed at x = 0, 500 N down at the free end. + const { mesh, faces } = await meshOf([sketch('s1', rect(0, 0, 200, 20)), extrude('f1', 's1', 10)], 2.5); + const fixed = planar(faces, [-1, 0, 0]), tip = planar(faces, [1, 0, 0]); + const F = 500, L = 200, I = (10 * 20 ** 3) / 12; + const input: StaticInput = { ...STEEL, fixtures: [{ kind: 'fixed', faces: [fixed] }], loads: [{ kind: 'force', faces: [tip], total: F, dir: [0, -1, 0] }] }; + const r = solveStatic(mesh, input, undefined, console.log); + const theory = (F * L ** 3) / (3 * STEEL.E * I); + const tipDy = at(mesh.nodes, r.U, [200, 10, 5], 3, 1); + console.log(`cantilever: ${r.dofs} dof, ${r.iterations} iterations, ${r.solver}, ms ${JSON.stringify(r.ms)}; tip ${tipDy} vs ${-theory}`); + expect(-tipDy / theory).toBeGreaterThan(0.99); + expect(-tipDy / theory).toBeLessThan(1.03); + // Bending stress at mid span on the top and bottom fibres: M c / I. + const sigma = (F * (L / 2) * 10) / I; + const top = at(mesh.nodes, r.stress, [100, 20, 5], 6, 0), bottom = at(mesh.nodes, r.stress, [100, 0, 5], 6, 0); + console.log(`bending stress ${top}, ${bottom} vs ${sigma}`); + expect(top / sigma).toBeCloseTo(1, 1); + expect(-bottom / sigma).toBeCloseTo(1, 1); + // Equilibrium: the reaction balances the load. + const sum = r.reactions[0].map((x, k) => x + r.applied[k]); + expect(Math.hypot(...sum)).toBeLessThan(1e-5 * F); + expect(r.applied[1]).toBeCloseTo(-F, 6); + }, 120000); + + it('bar in tension: uniform stress F/A and elongation FL/AE', async () => { + // 100 x 10 x 10, held by rollers on three faces (free to contract sideways). + const { mesh, faces } = await meshOf([sketch('s1', rect(0, 0, 100, 10)), extrude('f1', 's1', 10)], 2.5); + const F = 1000, A = 100, L = 100; + const input: StaticInput = { + ...STEEL, + fixtures: [{ kind: 'roller', faces: [planar(faces, [-1, 0, 0])] }, { kind: 'roller', faces: [planar(faces, [0, -1, 0])] }, { kind: 'roller', faces: [planar(faces, [0, 0, -1])] }], + loads: [{ kind: 'force', faces: [planar(faces, [1, 0, 0])], total: F, dir: null }], + }; + // A normal force presses on the face: flipped (pulling) here by a negative value. + input.loads[0] = { kind: 'force', faces: [planar(faces, [1, 0, 0])], total: -F, dir: null }; + const r = solveStatic(mesh, input); + const ux = at(mesh.nodes, r.U, [100, 5, 5], 3, 0); + expect(ux / ((F * L) / (A * STEEL.E))).toBeCloseTo(1, 2); + let lo = Infinity, hi = -Infinity; + for (let v = 0; v < mesh.nodes.length / 3; v++) { lo = Math.min(lo, r.stress[v * 6]); hi = Math.max(hi, r.stress[v * 6]); } + console.log(`bar: stress ${lo}..${hi} vs ${F / A}; elongation ${ux}`); + expect(Math.abs(lo / (F / A) - 1)).toBeLessThan(0.01); + expect(Math.abs(hi / (F / A) - 1)).toBeLessThan(0.01); + const total = r.reactions.reduce((s, x) => [s[0] + x[0], s[1] + x[1], s[2] + x[2]], [0, 0, 0]); + expect(total[0]).toBeCloseTo(-F, 3); + }, 120000); + + it('plate with a hole in tension: stress concentration about 3', async () => { + // 120 x 60 x 4 plate with a 10 mm hole (d / W = 1/6); Peterson: Kt (gross) about 3.1. + const { mesh, faces } = await meshOf([sketch('s1', [...rect(-60, -30, 60, 30), ...circle(0, 0, 5)]), extrude('f1', 's1', 4)], 2.5); + const sNom = 10; + const input: StaticInput = { + ...STEEL, + fixtures: [{ kind: 'roller', faces: [planar(faces, [-1, 0, 0])] }, { kind: 'roller', faces: [planar(faces, [0, 0, -1])] }, { kind: 'roller', faces: [planar(faces, [0, -1, 0])] }], + loads: [{ kind: 'pressure', faces: [planar(faces, [1, 0, 0])], value: -sNom }], + }; + // Symmetry would need a roller at y = 0; a roller on the bottom edge face holds y instead (it carries no load in x). + const r = solveStatic(mesh, input, undefined, console.log); + let peak = 0; + for (let v = 0; v < mesh.nodes.length / 3; v++) if (Math.hypot(mesh.nodes[v * 3], mesh.nodes[v * 3 + 1]) < 5.5) peak = Math.max(peak, r.stress[v * 6]); + console.log(`plate with hole: peak ${peak}, Kt ${peak / sNom}, ${r.dofs} dof, ${r.iterations} iterations, ms ${JSON.stringify(r.ms)}`); + expect(peak / sNom).toBeGreaterThan(2.7); + expect(peak / sNom).toBeLessThan(3.4); + }, 120000); + + it('gravity: the reactions carry the weight', async () => { + const { mesh, faces } = await meshOf([sketch('s1', rect(0, 0, 100, 20)), extrude('f1', 's1', 10)], 3); + const g = 9810; + const r = solveStatic(mesh, { ...STEEL, fixtures: [{ kind: 'fixed', faces: [planar(faces, [-1, 0, 0])] }], loads: [{ kind: 'gravity', accel: [0, -g, 0] }] }); + const weight = STEEL.density * 100 * 20 * 10 * g; + expect(r.applied[1] / -weight).toBeCloseTo(1, 6); + expect(r.reactions[0][1] / weight).toBeCloseTo(1, 6); + }, 120000); + + it('explains an under-constrained study', async () => { + const { mesh, faces } = await meshOf([sketch('s1', rect(0, 0, 100, 20)), extrude('f1', 's1', 10)], 4); + const load: LoadInput = { kind: 'force', faces: [planar(faces, [1, 0, 0])], total: 100, dir: [0, -1, 0] }; + expect(() => solveStatic(mesh, { ...STEEL, fixtures: [], loads: [load] })).toThrow(StudyError); + // A roller on one face leaves the part free to slide and turn in its plane. + const err = (() => { try { solveStatic(mesh, { ...STEEL, fixtures: [{ kind: 'roller', faces: [planar(faces, [-1, 0, 0])] }], loads: [load] }); } catch (e) { return e as Error; } return null; })(); + expect(err).toBeInstanceOf(StudyError); + expect(err!.message).toMatch(/free to move along Y/); + expect(err!.message).toMatch(/free to move along Z/); + expect(err!.message).toMatch(/free to turn about X/); + }, 120000); +}); From 80c65a55f262a1e50ed9d17f8acac75f8b73d035 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:15:16 -0700 Subject: [PATCH 011/116] Parametric: Analysis tab: static study setup, fixtures, loads, mesh, run in a worker, result plots with legend, probe and report --- src/parametric/src/app/fea/index.ts | 164 +++++++ src/parametric/src/app/fea/panels.ts | 442 +++++++++++++++++++ src/parametric/src/app/fea/plot.ts | 246 +++++++++++ src/parametric/src/app/fea/report.ts | 104 +++++ src/parametric/src/app/fea/workspace.ts | 555 ++++++++++++++++++++++++ src/parametric/src/app/tree.ts | 5 +- src/parametric/src/fea/client.ts | 102 +++++ src/parametric/src/fea/results.ts | 185 ++++++++ src/parametric/src/fea/worker.ts | 47 ++ src/parametric/src/main.ts | 2 + src/parametric/src/styles/app.css | 23 + 11 files changed, 1874 insertions(+), 1 deletion(-) create mode 100644 src/parametric/src/app/fea/index.ts create mode 100644 src/parametric/src/app/fea/panels.ts create mode 100644 src/parametric/src/app/fea/plot.ts create mode 100644 src/parametric/src/app/fea/report.ts create mode 100644 src/parametric/src/app/fea/workspace.ts create mode 100644 src/parametric/src/fea/client.ts create mode 100644 src/parametric/src/fea/results.ts create mode 100644 src/parametric/src/fea/worker.ts diff --git a/src/parametric/src/app/fea/index.ts b/src/parametric/src/app/fea/index.ts new file mode 100644 index 0000000000..7c5d34a7c7 --- /dev/null +++ b/src/parametric/src/app/fea/index.ts @@ -0,0 +1,164 @@ +// Stress analysis in the interface: the Analysis tab of the CommandManager, +// its commands and the study's rows in the design tree. This module is small +// and loaded with the app; the panels, the plots and the analysis worker are +// loaded the first time a command needs them, so a part without a study +// costs nothing more to open. + +import { FIXTURE_ICONS, FIXTURE_LABELS, LOAD_ICONS, type FixtureType, type FeaLoadType, type StaticStudy } from '../../model/fea'; +import type { FaceRef, Id } from '../../model/types'; +import { addIcons } from '../../ui/icons'; +import { toast } from '../../ui/overlay'; +import type { App, AppHooks } from '../app'; +import type { CamRow } from '../cam'; +import type { Command } from '../commands'; +import type { RibbonTab } from '../shell'; +import type { FeaWorkspace } from './workspace'; + +const P = (d: string, cls?: string): [string, Record] => (cls ? ['path', { d, class: cls }] : ['path', { d }]); +const C = (cx: number, cy: number, r: number, cls?: string): [string, Record] => (cls ? ['circle', { cx, cy, r, class: cls }] : ['circle', { cx, cy, r }]); + +addIcons({ + // A bracket with a stress gradient. + feaStudy: [P('M4 20V6h5v9h11v5z', 's'), P('M4 20V6h5v9h11v5z'), P('M6 8v2M6 12v2M11 17h2M15 17h2', 'a'), P('M14 3l3 3 3-3', 'thin')], + feaFixed: [P('M7 4h12v10H7z', 's'), P('M7 4h12v10H7z'), P('M4 3v14'), P('M1 6l3-3M1 10l3-3M1 14l3-3M1 18l3-3', 'thin')], + feaRoller: [P('M7 4h12v10H7z', 's'), P('M7 4h12v10H7z'), C(5, 7, 1.6, 'a'), C(5, 12, 1.6, 'a'), P('M2 3v14', 'thin')], + feaHinge: [C(12, 10, 6, 's'), C(12, 10, 6), C(12, 10, 2, 'a'), P('M5 21h14M12 16v5', 'thin')], + feaForce: [P('M4 15h16v5H4z', 's'), P('M4 15h16v5H4z'), P('M12 2v11', 'thick-a'), P('M9 10l3 3 3-3', 'a')], + feaPressure: [P('M4 15h16v5H4z', 's'), P('M4 15h16v5H4z'), P('M6 4v8M12 4v8M18 4v8', 'a'), P('M4.5 10l1.5 2 1.5-2M10.5 10l1.5 2 1.5-2M16.5 10l1.5 2 1.5-2', 'a')], + feaGravity: [P('M7 3h10v8H7z', 's'), P('M7 3h10v8H7z'), P('M12 12v9', 'thick-a'), P('M9 18l3 3 3-3', 'a'), P('M10 7h4', 'thin')], + feaMesh: [P('M3 20L12 4l9 16z', 's'), P('M3 20L12 4l9 16z'), P('M7.5 12h9M12 20l-4.5-8M12 20l4.5-8', 'thin')], + feaRun: [P('M6 4l14 8-14 8z', 'a'), P('M6 4l14 8-14 8z')], + feaResults: [['rect', { x: 4, y: 3, width: 6, height: 18, rx: 1, class: 's' }], P('M4 7h6M4 11h6M4 15h6', 'thin'), P('M13 5h7M13 12h7M13 19h7')], + feaReport: [P('M6 2h9l4 4v16H6z'), P('M15 2v4h4'), P('M9 18v-4M12 18v-7M15 18v-5', 'a')], + feaProbe: [P('M3 21l6-6'), C(13, 11, 6, 's'), C(13, 11, 6), P('M11 11h4M13 9v4', 'thin')], +}); + +let loading: Promise | null = null; +let workspace: FeaWorkspace | null = null; + +/** The analysis workspace, loaded (with the panels and the worker) the first time it is needed. */ +export async function feaWorkspace(app: App): Promise { + loading ??= import('./workspace'); + const m = await loading; + workspace ??= new m.FeaWorkspace(app); + return workspace; +} + +/** The workspace if it has been loaded (the design tree shows results only then). */ +export function loadedFeaWorkspace(): FeaWorkspace | null { + return workspace; +} + +/** Index of a referenced face in the current part (by name, else the nearest face of the same kind and size), or -1. */ +export function faceIndexOf(app: App, ref: FaceRef): number { + const faces = app.faces; + const i = faces.findIndex((f) => f.name === ref.name && !f.body); + if (i >= 0) return i; + let best = -1, bd = Infinity; + faces.forEach((f, k) => { + if (f.body || f.type !== ref.sig.type) return; + const d = Math.hypot(f.center[0] - ref.sig.c[0], f.center[1] - ref.sig.c[1], f.center[2] - ref.sig.c[2]) + Math.abs(f.area - ref.sig.area) * 1e-3; + if (d < bd) { bd = d; best = k; } + }); + return bd < 1e-3 ? best : -1; +} + +export function installFea(app: App, hooks: AppHooks) { + const partOnly = () => !app.assembly && !app.inDrawing; + const withWs = (fn: (ws: FeaWorkspace) => void | Promise) => () => { + if (!partOnly()) return; + void feaWorkspace(app).then(fn).catch((e) => toast({ kind: 'error', message: `The analysis could not start: ${(e as Error).message}` })); + }; + const hasStudy = () => partOnly() && !!app.store.doc.study; + const fixture = (type: FixtureType, desc: string, keywords: string): Command => ({ + id: `fea:${type}`, label: FIXTURE_LABELS[type], icon: FIXTURE_ICONS[type], description: desc, keywords: `fea analysis simulation fixture restraint support ${keywords}`, + enabled: partOnly, run: withWs((ws) => ws.newFixture(type)), + }); + const load = (type: FeaLoadType, label: string, desc: string, keywords: string): Command => ({ + id: `fea:${type}`, label, icon: LOAD_ICONS[type], description: desc, keywords: `fea analysis simulation load ${keywords}`, + enabled: partOnly, run: withWs((ws) => ws.newLoad(type)), + }); + const commands: Command[] = [ + { + id: 'fea:study', label: 'Static Study', icon: 'feaStudy', keywords: 'fea finite element analysis stress simulation static linear', + description: 'Set up a linear static stress analysis of the part: material, fixtures, loads and mesh.', enabled: partOnly, run: withWs((ws) => ws.openStudy()), + }, + fixture('fixed', 'Hold faces so they cannot move.', 'fixed clamp encastre'), + fixture('roller', 'Let faces slide along themselves but not move off them.', 'roller slider symmetry sliding'), + fixture('hinge', 'Let a cylindrical face (a pin hole) only turn about its axis.', 'hinge pin pivot bearing'), + load('force', 'Force', 'A total force on faces, normal to them or along a direction.', 'force newton push pull'), + load('pressure', 'Pressure', 'A pressure on faces, normal to them.', 'pressure psi pascal'), + load('gravity', 'Gravity', 'The part\'s own weight, from its material\'s density.', 'gravity weight self acceleration'), + { id: 'fea:mesh', label: 'Mesh', icon: 'feaMesh', keywords: 'fea mesh element size tetrahedra coarse fine', description: 'Set the element size and mesh the part.', enabled: hasStudy, run: withWs((ws) => ws.openMesh()) }, + { id: 'fea:run', label: 'Run', icon: 'feaRun', keywords: 'fea solve run calculate analysis', description: 'Mesh the part and solve the study.', enabled: hasStudy, run: withWs((ws) => ws.run()) }, + { + id: 'fea:results', label: 'Results', icon: 'feaResults', keywords: 'fea results stress displacement strain factor of safety plot von mises', description: 'Show the stress, displacement, strain and factor of safety plots.', + enabled: hasStudy, run: withWs((ws) => ws.showResults()), + }, + { id: 'fea:report', label: 'Report', icon: 'feaReport', keywords: 'fea report export csv print summary', description: 'Export the results summary as a CSV file or a printable report.', enabled: hasStudy, run: withWs((ws) => ws.report()) }, + ]; + app.commands.register(...commands); + + const tab: RibbonTab = { + id: 'analysis', label: 'Analysis', + groups: [ + [{ cmd: 'fea:study' }, { cmd: 'material' }], + [{ cmd: 'fea:fixed' }, { stack: [{ cmd: 'fea:roller' }, { cmd: 'fea:hinge' }] }], + [{ cmd: 'fea:force' }, { stack: [{ cmd: 'fea:pressure' }, { cmd: 'fea:gravity' }] }], + [{ cmd: 'fea:mesh' }, { cmd: 'fea:run' }], + [{ cmd: 'fea:results' }, { cmd: 'fea:report' }], + ], + labels: ['Study', 'Fixtures', 'Loads', 'Solve', 'Results'], + }; + // After CAM, before Drafting. + const at = hooks.ribbonTabs.findIndex((t) => t.id === 'drawing'); + hooks.ribbonTabs.splice(at < 0 ? hooks.ribbonTabs.length : at, 0, tab); + // A part opened with a study shows its symbols when the tab is chosen (the workspace loads then). + app.ribbonTabListeners.push((id) => { if (id === 'analysis' && app.store.doc.study && partOnly()) void feaWorkspace(app).then((ws) => ws.redraw()); }); +} + +// ---------- design tree ---------- + +export function feaTreeRows(app: App, expanded: (key: string) => boolean): CamRow[] { + const s: StaticStudy | null | undefined = app.store.doc.study; + if (!s || app.assembly) return []; + const ws = loadedFeaWorkspace(); + const run = (fn: (ws: FeaWorkspace) => void) => () => void feaWorkspace(app).then(fn); + const open = expanded('fea'); + const state = ws?.state() ?? 'none'; + const rows: CamRow[] = [{ + key: 'fea', label: s.name, icon: 'feaStudy', depth: 1, children: true, expanded: open, selected: false, + muted: state === 'busy' ? ` ${ws?.progressText() ?? 'running'}` : '', + action: () => { if (app.ribbonTabId !== 'analysis') app.setRibbonTab('analysis'); }, + open: run((w) => w.openStudy()), + menu: (x, y) => app.openCommandMenu(['fea:run', 'fea:mesh', 'fea:results', 'fea:report', 'material'], x, y, 'Study menu'), + }]; + if (!open) return rows; + const missing = (faces: FaceRef[]) => (app.faces.length && faces.some((f) => faceIndexOf(app, f) < 0) ? { kind: 'error' as const, text: 'A face it uses is no longer in the part. Edit it and pick the faces again.' } : !faces.length ? { kind: 'error' as const, text: 'No faces picked' } : undefined); + for (const f of s.fixtures) { + rows.push({ + key: `fea:${f.id}`, label: f.name, icon: FIXTURE_ICONS[f.type], depth: 2, selected: ws?.focus === f.id, suppressed: !!f.suppressed, badge: missing(f.faces), + action: run((w) => w.focusItem(f.id)), open: run((w) => w.editItem(f.id)), menu: (x, y) => void feaWorkspace(app).then((w) => w.itemMenu(f.id, x, y)), + }); + } + for (const l of s.loads) { + rows.push({ + key: `fea:${l.id}`, label: l.name, icon: LOAD_ICONS[l.type], depth: 2, selected: ws?.focus === l.id, suppressed: !!l.suppressed, badge: l.type === 'gravity' ? undefined : missing(l.faces), + action: run((w) => w.focusItem(l.id)), open: run((w) => w.editItem(l.id)), menu: (x, y) => void feaWorkspace(app).then((w) => w.itemMenu(l.id, x, y)), + }); + } + const mesh = ws?.meshText() ?? ''; + rows.push({ + key: 'fea:mesh', label: 'Mesh', icon: 'feaMesh', depth: 2, muted: mesh ? ` ${mesh}` : ' (not meshed)', selected: false, + action: run((w) => w.openMesh()), open: run((w) => w.openMesh()), menu: (x, y) => app.openCommandMenu(['fea:mesh', 'fea:run'], x, y, 'Mesh menu'), + }); + rows.push({ + key: 'fea:results', label: 'Results', icon: 'feaResults', depth: 2, selected: false, + muted: state === 'none' ? ' (not run)' : state === 'busy' ? ' (running)' : '', + badge: state === 'stale' ? { kind: 'warn', text: 'Out of date: the part or the study changed since it was run. Run it again.' } : state === 'error' ? { kind: 'error', text: ws?.errorText() ?? 'The study could not be solved' } : undefined, + action: run((w) => w.showResults()), open: run((w) => w.showResults()), menu: (x, y) => app.openCommandMenu(['fea:results', 'fea:run', 'fea:report'], x, y, 'Results menu'), + }); + return rows; +} + +export type { Id }; diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts new file mode 100644 index 0000000000..77dbcdd0b3 --- /dev/null +++ b/src/parametric/src/app/fea/panels.ts @@ -0,0 +1,442 @@ +// PropertyManager panels of the analysis: the study (name, material, mesh), +// fixtures, loads, and the results with their plots, probe and summary. + +import type { FieldName } from '../../fea/results'; +import type { Vec3 } from '../../fea/static'; +import { FIXTURE_ICONS, FIXTURE_LABELS, GRAVITY, LOAD_ICONS, LOAD_LABELS, feaUnits, type FeaDir, type FeaFixture, type FeaLoad, type FixtureType } from '../../model/fea'; +import { elasticOf } from '../../model/materials'; +import type { FaceRef } from '../../model/types'; +import { formatNumber } from '../../model/units'; +import { h, nextDomId } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import { PropertyPanel, type SelBoxItem, SelectionBox, checkbox, section, segmented, selectField } from '../pm'; +import { edgeRef, faceRef, type SelItem } from '../selection'; +import { faceIndexOf } from './index'; +import { FIELD_LABELS, ResultPlot, fieldKind, formatValue } from './plot'; +import type { FeaWorkspace } from './workspace'; + +/** A number in a unit of its own (force, pressure, acceleration), stored in the base unit (value times scale). */ +function valueField(label: string, value: number, unit: string, scale: number, onChange: (v: number) => void, opts: { positive?: boolean } = {}): HTMLElement { + const id = nextDomId('fea'); + const show = (v: number) => Number((v / scale).toPrecision(8)).toString(); + const input = h('input', { class: 'input', id, inputmode: 'decimal', autocomplete: 'off', spellcheck: 'false', 'aria-label': `${label} (${unit})`, value: show(value) }) as HTMLInputElement; + const commit = () => { + const t = input.value.trim(); + const v = Number(t); + const bad = !t || !Number.isFinite(v) ? 'Enter a number' : opts.positive && !(v > 0) ? 'Must be greater than 0' : ''; + input.classList.toggle('invalid', !!bad); + if (bad) { input.setAttribute('aria-invalid', 'true'); input.title = bad; return; } + input.removeAttribute('aria-invalid'); + input.title = ''; + onChange(v * scale); + }; + input.addEventListener('input', commit); + input.addEventListener('change', commit); + return h('div', {}, h('label', { class: 'field-label', for: id }, `${label} (${unit})`), input); +} + +abstract class FeaPanel extends PropertyPanel { + readonly feaPanel = true; + constructor(readonly app: App, readonly ws: FeaWorkspace) { super(); } + + protected faceItems(refs: FaceRef[]): SelBoxItem[] { + return refs.map((r) => { + const i = faceIndexOf(this.app, r); + const item: SelItem | null = i >= 0 ? { kind: 'face', index: i, name: this.app.faces[i].name } : null; + return { item, data: r, label: item ? this.app.describe(item) : `${r.name} (missing)` }; + }); + } + + protected toFace(it: SelItem, type?: string): SelBoxItem | null { + if (it.kind !== 'face') return null; + const f = this.app.faces[it.index]; + if (!f || f.body) { this.setMessage('warn', 'Pick faces of the solid.'); return null; } + if (type && f.type !== type) { this.setMessage('warn', type === 'cylinder' ? 'Pick cylindrical faces (a pin hole or a shaft).' : 'Pick flat faces.'); return null; } + this.setMessage(null); + return { item: it, data: faceRef(f), label: this.app.describe(it) }; + } + + dispose() { + this.ws.redraw(); + } +} + +// ---------- study and mesh ---------- + +export class StudyPanel extends FeaPanel { + title = 'Static Study'; + icon = 'feaStudy'; + confirm = false; + private name: string; + private fineness: number; + + constructor(app: App, ws: FeaWorkspace) { + super(app, ws); + const s = ws.study!; + this.name = s.name; + this.fineness = s.mesh.fineness; + } + + progress(_b: { stage: string; progress: number }) { + const bar = this.el.querySelector('progress'); + const label = this.el.querySelector('.fea-stage'); + if (bar) bar.value = _b.progress; + if (label) label.textContent = _b.stage; + } + + private commit() { + const name = this.name.trim(); + this.app.store.change('Edit study', (d) => { + if (!d.study) return; + if (name) d.study.name = name; + d.study.mesh.fineness = this.fineness; + }); + } + + render(): HTMLElement[] { + const app = this.app, ws = this.ws; + const s = ws.study; + if (!s) return [section('Study', [h('p', { class: 'pm-msg' }, 'The study was deleted.')])]; + const nameInput = h('input', { class: 'input', value: this.name, 'aria-label': 'Study name' }) as HTMLInputElement; + nameInput.addEventListener('change', () => { this.name = nameInput.value; this.commit(); }); + const mat = app.store.doc.material; + const el = elasticOf(mat); + const matText = !mat ? 'No material chosen.' : el ? `${mat.name}: E ${formatNumber(el.E / 1000, 1)} GPa, ν ${el.nu}, yield ${el.yield} MPa` : `${mat.name}: no elastic properties (cannot be analyzed).`; + const matBtn = h('button', { class: 'btn small', type: 'button', onclick: () => app.commands.run('material') }, icon('material', 16), 'Material...'); + // Mesh: coarse to fine. + const sizes = ws.sizes(this.fineness); + const u = feaUnits(app.store.doc.units); + const slider = h('input', { type: 'range', min: '0', max: '1', step: '0.05', value: String(this.fineness), 'aria-label': 'Mesh density, coarse to fine', class: 'fea-slider' }) as HTMLInputElement; + const sizeText = h('div', { class: 'field-label', 'aria-live': 'polite' }); + const describe = () => { + const z = ws.sizes(this.fineness); + sizeText.textContent = z ? `Element size ${formatNumber(z.size / u.lengthScale, app.store.doc.decimals)} ${u.length} (automatic ${formatNumber(z.auto / u.lengthScale, app.store.doc.decimals)}), about ${z.dofs.toLocaleString('en-US')} unknowns` : 'Element size: found when the part is first meshed.'; + }; + describe(); + slider.addEventListener('input', () => { this.fineness = Number(slider.value); describe(); }); + slider.addEventListener('change', () => this.commit()); + const meshBtn = h('button', { class: 'btn small', type: 'button', disabled: !!ws.busy, onclick: () => void ws.meshNow() }, icon('feaMesh', 16), 'Mesh'); + const runBtn = h('button', { class: 'btn small primary', type: 'button', disabled: !!ws.busy, onclick: () => void ws.run() }, icon('feaRun', 16), 'Run'); + const m = ws.mesh; + const stats: HTMLElement[] = []; + if (ws.busy) stats.push(h('p', { class: 'field-label fea-stage', role: 'status' }, ws.busy.stage), h('progress', { max: '1', value: String(ws.busy.progress), 'aria-label': 'Progress' })); + if (m) { + const st = m.info.stats; + const volErr = (st.volume / st.surfaceVolume - 1) * 100; + stats.push(h('table', { class: 'table fea-stats' }, h('tbody', {}, + ...([ + ['Elements', st.elements.toLocaleString('en-US')], ['Nodes', st.nodes.toLocaleString('en-US')], + ['Element size', `${formatNumber(st.size / u.lengthScale, app.store.doc.decimals)} ${u.length}`], + ['Quality (worst / mean)', `${st.minQuality.toFixed(2)} / ${st.meanQuality.toFixed(2)}`], + ['Dihedral angles', `${st.minDihedral.toFixed(1)}° to ${st.maxDihedral.toFixed(1)}°`], + ['Volume against the part', `${volErr >= 0 ? '+' : ''}${volErr.toFixed(2)}%`], + ] as [string, string][]).map(([k, v]) => h('tr', {}, h('th', {}, k), h('td', { class: 'num' }, v)))))); + if (Math.abs(volErr) > 2) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The mesh misses part of the volume: some walls are thinner than the elements. Use a finer mesh.')); + if (!m.key.startsWith(`${app.geometryVersion}|`)) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part changed since it was meshed.')); + } + if (ws.error?.message && !ws.busy) stats.push(h('p', { class: 'pm-msg error', role: 'alert' }, ws.error.message)); + void sizes; + return [ + section('Study', [h('label', { class: 'field-label' }, 'Name'), nameInput, h('p', { class: 'field-label' }, 'Linear static: small displacements, linear elastic isotropic material.')], { icon: 'feaStudy' }), + section('Material', [h('p', { class: 'field-label fea-material' }, matText), matBtn], { icon: 'material' }), + section('Mesh', [h('div', { class: 'row fea-slider-row' }, h('span', { class: 'field-label' }, 'Coarse'), slider, h('span', { class: 'field-label' }, 'Fine')), sizeText, h('div', { class: 'row' }, meshBtn, runBtn), ...stats], { icon: 'feaMesh' }), + section('Study', [h('button', { class: 'btn small danger', type: 'button', onclick: () => ws.deleteStudy() }, icon('trash', 16), 'Delete Study')], { collapsed: true }), + ]; + } + + ok() { return true; } + + dispose() { + super.dispose(); + this.app.renderer.setLines('feaMesh', null); + } +} + +// ---------- fixtures ---------- + +export class FixturePanel extends FeaPanel { + title: string; + icon: string; + + constructor(app: App, ws: FeaWorkspace, private f: FeaFixture, private creating: boolean) { + super(app, ws); + this.title = creating ? FIXTURE_LABELS[f.type] : f.name; + this.icon = FIXTURE_ICONS[f.type]; + } + + get present(): boolean { + return this.creating || !!this.ws.study?.fixtures.some((x) => x.id === this.f.id); + } + + get edited() { return true; } + + render(): HTMLElement[] { + const f = this.f; + const type = segmented('Fixture type', f.type, (['fixed', 'roller', 'hinge'] as FixtureType[]).map((t) => ({ value: t, label: FIXTURE_LABELS[t] })), (t) => { + f.type = t; + if (t === 'hinge') f.faces = f.faces.filter((r) => r.sig.type === 'cylinder'); + this.app.refreshPanel(); + }); + const help = f.type === 'fixed' ? 'The faces cannot move in any direction.' : f.type === 'roller' ? 'The faces can slide along themselves but not move off them (no motion normal to the face): also a symmetry plane.' : 'The cylindrical faces can only turn about their axis (a pin): no radial or axial motion.'; + const box = new SelectionBox(this, 'Faces', { face: true }, (it) => this.toFace(it, f.type === 'hinge' ? 'cylinder' : undefined), (items) => { f.faces = items.map((i) => i.data as FaceRef); }, { placeholder: 'Pick the faces to hold', icon: FIXTURE_ICONS[f.type] }); + box.setItems(this.faceItems(f.faces)); + return [section('Type', [type, h('p', { class: 'field-label' }, help)], { icon: FIXTURE_ICONS[f.type] }), section('Faces', [box.el])]; + } + + ok(): boolean { + const f = this.f; + if (!f.faces.length) { this.setMessage('error', 'Pick at least one face.'); return false; } + const label = this.creating ? `Add ${f.name}` : `Edit ${f.name}`; + this.app.store.change(label, (d) => { + if (!d.study) return; + const i = d.study.fixtures.findIndex((x) => x.id === f.id); + if (i >= 0) d.study.fixtures[i] = structuredClone(f); + else d.study.fixtures.push(structuredClone(f)); + }); + return true; + } +} + +// ---------- loads ---------- + +type DirChoice = 'normal' | 'x' | 'y' | 'z' | 'ref'; + +export class LoadPanel extends FeaPanel { + title: string; + icon: string; + private refItems: SelBoxItem[] = []; + + constructor(app: App, ws: FeaWorkspace, private l: FeaLoad, private creating: boolean) { + super(app, ws); + this.title = creating ? LOAD_LABELS[l.type] : l.name; + this.icon = LOAD_ICONS[l.type]; + if ((l.type === 'force' || l.type === 'gravity') && l.dir && l.dir.kind !== 'base') this.refItems = this.dirItems(l.dir); + } + + get present(): boolean { + return this.creating || !!this.ws.study?.loads.some((x) => x.id === this.l.id); + } + + get edited() { return true; } + + private dirItems(d: FeaDir): SelBoxItem[] { + if (d.kind === 'face') return this.faceItems([d.face]).map((x) => ({ ...x, data: d })); + if (d.kind === 'edge') { + const i = this.app.edges.findIndex((e) => e.name === d.edge.name); + const item: SelItem | null = i >= 0 ? { kind: 'edge', index: i, name: d.edge.name } : null; + return [{ item, data: d, label: item ? this.app.describe(item) : `${d.edge.name} (missing)` }]; + } + return []; + } + + private toDir(it: SelItem): SelBoxItem | null { + if (it.kind === 'face') { + const f = this.app.faces[it.index]; + if (!f || !(f.normal || f.axis)) { this.setMessage('warn', 'Pick a flat face (its normal) or a cylindrical face (its axis), or a straight edge.'); return null; } + return { item: it, data: { kind: 'face', face: faceRef(f) } satisfies FeaDir, label: this.app.describe(it) }; + } + if (it.kind === 'edge') { + const e = this.app.edges[it.index]; + if (!e || !(e.dir || e.axis)) { this.setMessage('warn', 'Pick a straight edge (its direction) or a circular edge (its axis).'); return null; } + return { item: it, data: { kind: 'edge', edge: edgeRef(e) } satisfies FeaDir, label: this.app.describe(it) }; + } + return null; + } + + render(): HTMLElement[] { + const l = this.l, app = this.app; + const u = feaUnits(app.store.doc.units); + const out: HTMLElement[] = []; + if (l.type !== 'gravity') { + const box = new SelectionBox(this, 'Faces', { face: true }, (it) => this.toFace(it), (items) => { l.faces = items.map((i) => i.data as FaceRef); }, { placeholder: 'Pick the faces it acts on', icon: LOAD_ICONS[l.type] }); + box.setItems(this.faceItems(l.faces)); + out.push(section('Faces', [box.el], { icon: LOAD_ICONS[l.type] })); + } + const value = l.type === 'force' ? valueField('Total force', l.value, u.force, u.forceScale, (v) => { l.value = v; }, { positive: true }) + : l.type === 'pressure' ? valueField('Pressure', l.value, u.stress, u.stressScale, (v) => { l.value = v; }, { positive: true }) + : valueField('Acceleration', l.value, u.accel, u.accelScale, (v) => { l.value = v; }, { positive: true }); + const items: HTMLElement[] = [value]; + if (l.type === 'force' || l.type === 'gravity') { + const choice: DirChoice = !l.dir ? 'normal' : l.dir.kind === 'base' ? l.dir.axis : 'ref'; + const options: { value: DirChoice; label: string }[] = [ + ...(l.type === 'force' ? [{ value: 'normal' as DirChoice, label: 'Normal to the faces' }] : []), + { value: 'x', label: 'Along X' }, { value: 'y', label: 'Along Y' }, { value: 'z', label: 'Along Z' }, + { value: 'ref', label: 'Along a picked edge or face' }, + ]; + items.push(selectField('Direction', choice, options, (v) => { + if (v === 'normal' && l.type === 'force') l.dir = null; + else if (v === 'x' || v === 'y' || v === 'z') l.dir = { kind: 'base', axis: v }; + else if (v === 'ref') l.dir = (this.refItems[0]?.data as FeaDir | undefined) ?? (l.type === 'force' ? null : l.dir); + if (v === 'ref' && !this.refItems.length) this.pickRef = true; + else this.pickRef = false; + app.refreshPanel(); + })); + if (choice === 'ref' || this.pickRef) { + const ref = new SelectionBox(this, 'Direction reference', { face: true, edge: true }, (it) => this.toDir(it), (sel) => { + this.refItems = sel; + if (sel[0]) l.dir = sel[0].data as FeaDir; + }, { single: true, placeholder: 'Pick an edge or a face', icon: 'axis' }); + ref.setItems(this.refItems); + items.push(ref.el); + queueMicrotask(() => this.activate(ref)); + } + } + items.push(checkbox(l.type === 'gravity' ? 'Reverse direction' : l.type === 'pressure' ? 'Reverse direction (pull on the faces)' : 'Reverse direction', l.flip, (v) => { l.flip = v; this.ws.redraw(); })); + const help = l.type === 'force' ? (l.dir ? 'The total force is spread evenly over the faces\' area.' : 'Normal to the faces, pressing on them: spread as a pressure (on a curved face the pieces point different ways).') + : l.type === 'pressure' ? 'Pushes into the faces, normal to them everywhere.' : `The part's weight from its density, along the direction (${(GRAVITY / u.accelScale).toFixed(u.accel === 'm/s²' ? 3 : 1)} ${u.accel} is standard gravity).`; + out.push(section('Value', [...items, h('p', { class: 'field-label' }, help)], { icon: LOAD_ICONS[l.type] })); + return out; + } + + private pickRef = false; + + ok(): boolean { + const l = this.l; + if (l.type !== 'gravity' && !l.faces.length) { this.setMessage('error', 'Pick at least one face.'); return false; } + if (!(l.value > 0) || !Number.isFinite(l.value)) { this.setMessage('error', 'Enter a value greater than 0.'); return false; } + if (this.pickRef && (l.type === 'force' || l.type === 'gravity') && (!l.dir || l.dir.kind === 'base')) { this.setMessage('error', 'Pick an edge or face for the direction.'); return false; } + this.app.store.change(this.creating ? `Add ${l.name}` : `Edit ${l.name}`, (d) => { + if (!d.study) return; + const i = d.study.loads.findIndex((x) => x.id === l.id); + if (i >= 0) d.study.loads[i] = structuredClone(l); + else d.study.loads.push(structuredClone(l)); + }); + return true; + } +} + +// ---------- results ---------- + +const FIELDS: FieldName[] = ['vonMises', 'p1', 'p2', 'p3', 'disp', 'ux', 'uy', 'uz', 'strain', 'fos']; + +export class ResultsPanel extends FeaPanel { + title = 'Results'; + icon = 'feaResults'; + confirm = false; + private plot: ResultPlot | null = null; + private plotted: unknown = null; + private field: FieldName = 'vonMises'; + + progress(b: { stage: string; progress: number }) { + const bar = this.el.querySelector('progress'); + const label = this.el.querySelector('.fea-stage'); + if (bar) bar.value = b.progress; + if (label) label.textContent = b.stage; + } + + render(): HTMLElement[] { + const app = this.app, ws = this.ws; + if (ws.busy) { + return [section('Running', [ + h('p', { class: 'field-label fea-stage', role: 'status' }, ws.busy.stage), + h('progress', { max: '1', value: String(ws.busy.progress), 'aria-label': 'Analysis progress' }), + h('button', { class: 'btn small', type: 'button', onclick: () => ws.cancel() }, 'Cancel'), + ], { icon: 'feaRun' })]; + } + const res = ws.result; + const err = ws.error; + const msgs: HTMLElement[] = []; + if (err) msgs.push(h('p', { class: 'pm-msg error', role: 'alert' }, err.message)); + if (!res) { + this.disposePlot(); + return [section('Results', [...msgs, h('p', { class: 'field-label' }, 'Run the study to see its results.'), h('button', { class: 'btn small primary', type: 'button', onclick: () => void ws.run() }, icon('feaRun', 16), 'Run')], { icon: 'feaResults' })]; + } + const s = res.sol.summary; + if (ws.state() === 'stale') msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'Out of date: the part, the study or the material changed since it was run.'), h('button', { class: 'btn small', type: 'button', onclick: () => void ws.run() }, icon('feaRun', 16), 'Run Again')); + if (s.maxVonMises.value > res.yield) msgs.push(h('p', { class: 'pm-msg error', role: 'alert' }, `The highest von Mises stress (${formatValue(app, s.maxVonMises.value, 'stress')}) is above the yield strength of ${res.material} (${formatValue(app, res.yield, 'stress')}): the part would yield there, and a linear analysis no longer describes it.`)); + const b = app.bbox; + const size = b ? Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]) : 0; + if (size && s.maxDisplacement.value > 0.05 * size) msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part moves by more than 5% of its size: a linear (small displacement) analysis may not describe it well.')); + // The plot. + if (!this.plot) { + this.plot = new ResultPlot(app, res.mesh, res.sol, res.yield); + this.plot.onProbe = () => this.drawProbes(); + this.plotted = res; + this.ws.plotting = true; + this.ws.redraw(); + this.plot.field = this.field; + this.plot.draw(); + } else if (this.plotted !== res) { + this.plotted = res; + this.plot.setResult(res.mesh, res.sol, res.yield); + } + const plot = this.plot; + const field = selectField('Plot', plot.field, FIELDS.map((f) => ({ value: f, label: FIELD_LABELS[f] })), (v) => { plot.field = this.field = v; plot.draw(); this.drawProbes(); }); + const deform = selectField<'auto' | 'true' | 'none'>('Deformed shape', plot.deform, [{ value: 'auto', label: 'Deformed (automatic scale)' }, { value: 'true', label: 'Deformed (true scale)' }, { value: 'none', label: 'Undeformed' }], (v) => { plot.deform = v; plot.draw(); }); + const mesh = checkbox('Show the mesh', plot.showMesh, (v) => { plot.showMesh = v; plot.draw(); }); + const probe = h('button', { class: 'btn small', type: 'button', 'aria-pressed': String(plot.probing) }, icon('feaProbe', 16), 'Probe') as HTMLButtonElement; + probe.addEventListener('click', () => { plot.setProbing(!plot.probing); probe.setAttribute('aria-pressed', String(plot.probing)); this.drawProbes(); }); + const clear = h('button', { class: 'btn small', type: 'button', onclick: () => { plot.probes = []; plot.draw(); this.drawProbes(); } }, 'Clear'); + this.probeList = h('div', { class: 'fea-probes', 'aria-live': 'polite' }); + queueMicrotask(() => this.drawProbes()); + const rows: [string, string][] = [ + ['Max von Mises stress', formatValue(app, s.maxVonMises.value, 'stress')], + [' at', this.point(s.maxVonMises.at)], + ['Yield strength', `${formatValue(app, res.yield, 'stress')} (${res.material})`], + ['Min factor of safety', s.maxVonMises.value > 0 ? (res.yield / s.maxVonMises.value).toFixed(2) : '∞'], + ['Max displacement', formatValue(app, s.maxDisplacement.value, 'length')], + [' at', this.point(s.maxDisplacement.at)], + ['Max principal stress', formatValue(app, s.maxP1.value, 'stress')], + ['Min principal stress', formatValue(app, s.minP3.value, 'stress')], + ['Max equivalent strain', s.maxStrain.value.toExponential(3)], + ]; + const u = feaUnits(app.store.doc.units); + const force = (v: Vec3) => `${v.map((x) => formatNumber(x / u.forceScale, 3)).join(', ')} ${u.force}`; + const total = s.reactions.reduce((a, r) => [a[0] + r[0], a[1] + r[1], a[2] + r[2]], [0, 0, 0]); + const imbalance = Math.hypot(total[0] + s.applied[0], total[1] + s.applied[1], total[2] + s.applied[2]) / Math.max(Math.hypot(...s.applied), 1e-30); + const forces: [string, string][] = [ + ['Applied loads (sum)', force(s.applied)], + ...res.fixtureNames.map((n, i) => [`Reaction: ${n}`, force(s.reactions[i])] as [string, string]), + ['Reactions (sum)', force(total)], + ['Equilibrium error', `${(imbalance * 100).toExponential(1)}%`], + ]; + const st = res.mesh.stats; + const solve: [string, string][] = [ + ['Mesh', `${st.elements.toLocaleString('en-US')} elements, ${st.nodes.toLocaleString('en-US')} nodes`], + ['Unknowns', s.dofs.toLocaleString('en-US')], + ['Element quality (worst)', st.minQuality.toFixed(2)], + ['Solver', `${s.iterations} iterations, ${((s.ms.assemble + s.ms.setup + s.ms.solve + s.ms.stress) / 1000).toFixed(1)} s`], + ]; + const table = (r: [string, string][], cls: string) => h('table', { class: `table ${cls}` }, h('tbody', {}, ...r.map(([k, v]) => h('tr', {}, h('th', {}, k.trim()), h('td', { class: 'num' }, v))))); + return [ + ...(msgs.length ? [section('Messages', msgs)] : []), + section('Plot', [field, deform, mesh, h('div', { class: 'row' }, probe, clear), this.probeList], { icon: 'feaResults' }), + section('Summary', [table(rows, 'fea-summary')], { icon: 'feaStudy' }), + section('Forces', [table(forces, 'fea-forces')], { collapsed: false }), + section('Mesh and solver', [table(solve, 'fea-solve')], { collapsed: true }), + section('Export', [h('div', { class: 'row' }, h('button', { class: 'btn small', type: 'button', onclick: () => ws.report() }, icon('feaReport', 16), 'Report...'))]), + ]; + } + + private probeList: HTMLElement | null = null; + + private point(p: Vec3): string { + const u = feaUnits(this.app.store.doc.units); + return `(${p.map((x) => formatNumber(x / u.lengthScale, this.app.store.doc.decimals)).join(', ')}) ${u.length}`; + } + + private drawProbes() { + const list = this.probeList, plot = this.plot; + if (!list || !plot) return; + list.textContent = ''; + if (plot.probing && !plot.probes.length) list.append(h('p', { class: 'field-label' }, 'Click the plot to read the value there.')); + const kind = fieldKind(plot.field); + plot.probes.forEach((p, i) => list.append(h('div', { class: 'fea-probe' }, h('b', {}, `${i + 1}`), h('span', {}, formatValue(this.app, p.value, kind)), h('span', { class: 'field-label' }, this.point(plot.probePoint(p)))))); + } + + private disposePlot() { + if (!this.plot) return; + this.plot.dispose(); + this.plot = null; + this.ws.plotting = false; + this.ws.redraw(); + } + + ok() { return true; } + + dispose() { + this.disposePlot(); + super.dispose(); + } +} diff --git a/src/parametric/src/app/fea/plot.ts b/src/parametric/src/app/fea/plot.ts new file mode 100644 index 0000000000..8654214465 --- /dev/null +++ b/src/parametric/src/app/fea/plot.ts @@ -0,0 +1,246 @@ +// A result plot in the graphics area: the mesh's boundary, deformed by the +// displacements times a scale, coloured by a field with a legend, the mesh +// lines on request, and probe pins that read the field where they are put. + +import { type FeaMeshInfo, type FeaSolution, type FieldName, SUB, colorAt, fieldValues, interpolate, rayHit } from '../../fea/results'; +import type { Vec3 } from '../../fea/static'; +import { feaUnits } from '../../model/fea'; +import type { SolidBatch } from '../../render/renderer'; +import { h } from '../../ui/dom'; +import type { App } from '../app'; +import type { ViewportTool } from '../viewport'; + +export const FIELD_LABELS: Record = { + vonMises: 'von Mises stress', p1: 'Principal stress 1 (largest)', p2: 'Principal stress 2', p3: 'Principal stress 3 (smallest)', + disp: 'Displacement', ux: 'Displacement X', uy: 'Displacement Y', uz: 'Displacement Z', strain: 'Equivalent strain', fos: 'Factor of safety', +}; + +export type FieldKind = 'stress' | 'length' | 'none'; +export const fieldKind = (f: FieldName): FieldKind => (f === 'vonMises' || f === 'p1' || f === 'p2' || f === 'p3' ? 'stress' : f === 'disp' || f === 'ux' || f === 'uy' || f === 'uz' ? 'length' : 'none'); + +/** Factor of safety plots stop at this value (larger ones show its colour). */ +export const FOS_CAP = 10; + +export interface Probe { + at: Vec3; + value: number; + tri: number; + s: number; + t: number; +} + +/** A value with its unit in the part's units: stress (MPa in), displacement (mm in), or a plain number. */ +export function formatValue(app: App, v: number, kind: FieldKind): string { + if (!Number.isFinite(v)) return v > 0 ? '∞' : '–'; + const u = feaUnits(app.store.doc.units); + const sig = (x: number, d = 4) => (x === 0 ? '0' : Math.abs(x) >= 1e5 || Math.abs(x) < 1e-3 ? x.toExponential(d - 1) : Number(x.toPrecision(d)).toString()); + if (kind === 'stress') return `${sig(v / u.stressScale)} ${u.stress}`; + if (kind === 'length') return `${sig(v / u.lengthScale)} ${u.length}`; + return sig(v); +} + +export class ResultPlot { + field: FieldName = 'vonMises'; + /** 'auto': the largest displacement shown as a twentieth of the part's size; 'true': as it is; 'none': undeformed. */ + deform: 'auto' | 'true' | 'none' = 'auto'; + showMesh = false; + probes: Probe[] = []; + probing = false; + private legend: HTMLElement | null = null; + private pins: HTMLElement | null = null; + private positions: Float32Array | null = null; + private values: Float32Array | null = null; + private modelHidden = false; + private prevCamera: (() => void) | null = null; + private tool: ViewportTool | null = null; + onProbe: () => void = () => {}; + + constructor(private readonly app: App, private mesh: FeaMeshInfo, private sol: FeaSolution, private yieldStrength: number) {} + + setResult(mesh: FeaMeshInfo, sol: FeaSolution, yieldStrength: number) { + this.mesh = mesh; + this.sol = sol; + this.yieldStrength = yieldStrength; + this.probes = []; + this.draw(); + } + + /** The deformation scale in use. */ + scale(): number { + if (this.deform === 'none') return 0; + if (this.deform === 'true') return 1; + const max = this.sol.summary.maxDisplacement.value; + const st = this.mesh.stats; + const b = this.bounds(); + const size = Math.hypot(b[3] - b[0], b[4] - b[1], b[5] - b[2]) || st.size * 10; + return max > 0 ? (0.05 * size) / max : 0; + } + + private bounds(): number[] { + const P = this.mesh.nodes; + const b = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity]; + for (let i = 0; i < P.length; i += 3) for (let k = 0; k < 3; k++) { b[k] = Math.min(b[k], P[i + k]); b[k + 3] = Math.max(b[k + 3], P[i + k]); } + return b; + } + + /** Range of the shown field (factor of safety: from its smallest to the cap). */ + range(): [number, number] { + const v = this.values ?? fieldValues(this.sol, this.field, this.yieldStrength); + let lo = Infinity, hi = -Infinity; + for (let i = 0; i < v.length; i++) { const x = this.field === 'fos' ? Math.min(v[i], FOS_CAP) : v[i]; if (x < lo) lo = x; if (x > hi) hi = x; } + if (this.field === 'fos') hi = Math.max(hi, lo); + return [lo, hi]; + } + + draw() { + const app = this.app, r = app.renderer; + const { nodes, tris, triFace } = this.mesh; + const values = fieldValues(this.sol, this.field, this.yieldStrength); + this.values = values; + const [lo, hi] = this.range(); + const k = this.scale(); + const U = this.sol.fields[0]; + const n = nodes.length / 3; + const pos = new Float32Array(n * 3); + for (let i = 0; i < n * 3; i++) pos[i] = nodes[i] + k * U[i]; + this.positions = pos; + // Vertices per node and face, so normals are smooth within a face and sharp between faces. + const vid = new Map(); + const vp: number[] = [], vc: number[] = [], idx: number[] = []; + const nf = 1 + Math.max(0, ...triFace); + const tcol = (x: number) => { + const t = hi > lo ? (Math.min(x, this.field === 'fos' ? FOS_CAP : Infinity) - lo) / (hi - lo) : 0.5; + // Low factors of safety are the ones to see: red. + return colorAt(this.field === 'fos' ? 1 - t : t); + }; + const vertex = (node: number, face: number) => { + const key = node * (nf + 1) + face + 1; + let v = vid.get(key); + if (v === undefined) { + v = vp.length / 3; + vid.set(key, v); + vp.push(pos[node * 3], pos[node * 3 + 1], pos[node * 3 + 2]); + vc.push(...tcol(values[node]), 255); + } + return v; + }; + const nt = tris.length / 6; + for (let f = 0; f < nt; f++) { + for (const [a, b, c] of SUB) idx.push(vertex(tris[f * 6 + a], triFace[f]), vertex(tris[f * 6 + b], triFace[f]), vertex(tris[f * 6 + c], triFace[f])); + } + const nor = new Float32Array(vp.length); + for (let q = 0; q < idx.length; q += 3) { + const a = idx[q] * 3, b = idx[q + 1] * 3, c = idx[q + 2] * 3; + const ux = vp[b] - vp[a], uy = vp[b + 1] - vp[a + 1], uz = vp[b + 2] - vp[a + 2], wx = vp[c] - vp[a], wy = vp[c + 1] - vp[a + 1], wz = vp[c + 2] - vp[a + 2]; + const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx; + for (const v of [a, b, c]) { nor[v] += nx; nor[v + 1] += ny; nor[v + 2] += nz; } + } + for (let i = 0; i < nor.length; i += 3) { const l = Math.hypot(nor[i], nor[i + 1], nor[i + 2]) || 1; nor[i] /= l; nor[i + 1] /= l; nor[i + 2] /= l; } + const batch: SolidBatch = { positions: new Float32Array(vp), normals: nor, colors: new Uint8Array(vc), indices: new Uint32Array(idx) }; + if (!this.modelHidden) { r.setModel(null, 1, 1); this.modelHidden = true; } + r.setSolid('feaPlot', batch); + if (this.showMesh) { + const L = this.mesh.lines; + // The mesh lines follow the deformed shape: move each end point by its node's displacement (nodes found by position). + const at = new Map(); + for (let i = 0; i < n; i++) at.set(`${nodes[i * 3]},${nodes[i * 3 + 1]},${nodes[i * 3 + 2]}`, i); + const lp = new Float32Array(L.length); + for (let i = 0; i < L.length; i += 3) { + const v = at.get(`${L[i]},${L[i + 1]},${L[i + 2]}`); + for (let c = 0; c < 3; c++) lp[i + c] = L[i + c] + (v === undefined ? 0 : k * U[v * 3 + c]); + } + r.setLines('feaMesh', { positions: lp, colors: new Uint8Array((L.length / 6) * 4).map((_, i) => (i % 4 === 3 ? 160 : 30)), width: 1, depth: 'test', order: 6, bias: 4e-5 }); + } else r.setLines('feaMesh', null); + // Probes follow the deformed shape and the field shown. + for (const p of this.probes) { + p.value = interpolate(values, tris, p.tri, p.s, p.t); + p.at = [0, 1, 2].map((c) => interpolate(pos, tris, p.tri, p.s, p.t, 3, c)) as Vec3; + } + this.drawLegend(lo, hi); + this.placePins(); + if (!this.prevCamera) { + const prev = r.onCamera; + this.prevCamera = prev; + r.onCamera = () => { prev(); this.placePins(); }; + } + } + + private drawLegend(lo: number, hi: number) { + const app = this.app; + this.legend?.remove(); + const kind = fieldKind(this.field); + const u = feaUnits(app.store.doc.units); + const unit = kind === 'stress' ? u.stress : kind === 'length' ? u.length : ''; + const ticks = h('div', { class: 'fea-legend-ticks' }); + const N = 6; + for (let i = 0; i < N; i++) { + const v = hi - ((hi - lo) * i) / (N - 1); + const top = this.field === 'fos' && i === 0 && hi >= FOS_CAP ? `≥ ${FOS_CAP}` : formatValue(app, v, kind).replace(` ${unit}`, ''); + ticks.append(h('span', {}, top)); + } + const stops = Array.from({ length: 9 }, (_, i) => { const c = colorAt(this.field === 'fos' ? i / 8 : 1 - i / 8); return `rgb(${c.join(',')}) ${(i / 8) * 100}%`; }); + const bar = h('div', { class: 'fea-legend-bar', style: { background: `linear-gradient(to bottom, ${stops.join(', ')})` } }); + const extra: HTMLElement[] = []; + if (kind === 'stress' && this.field === 'vonMises') extra.push(h('div', { class: 'fea-legend-note' }, `Yield strength: ${formatValue(app, this.yieldStrength, 'stress')}`)); + const k = this.scale(); + extra.push(h('div', { class: 'fea-legend-note' }, this.deform === 'none' ? 'Undeformed shape' : `Deformation scale: ${k >= 100 ? Math.round(k).toLocaleString('en-US') : Number(k.toPrecision(3))}${this.deform === 'true' ? ' (true scale)' : ''}`)); + this.legend = h('div', { class: 'fea-legend', role: 'img', 'aria-label': `Legend: ${FIELD_LABELS[this.field]} from ${formatValue(app, lo, kind)} to ${formatValue(app, hi, kind)}` }, + h('div', { class: 'fea-legend-title' }, `${FIELD_LABELS[this.field]}${unit ? ` (${unit})` : ''}`), + h('div', { class: 'fea-legend-scale' }, bar, ticks), ...extra); + app.shell.viewport.append(this.legend); + } + + private placePins() { + const app = this.app; + if (!this.pins) { this.pins = h('div', { class: 'fea-pins', 'aria-hidden': 'true' }); app.shell.viewport.append(this.pins); } + this.pins.textContent = ''; + const cam = app.renderer.camera; + const kind = fieldKind(this.field); + this.probes.forEach((p, i) => { + const [x, y, z] = cam.project(p.at); + if (z < -1 || z > 1) return; + this.pins!.append(h('div', { class: 'fea-pin', style: { left: `${x}px`, top: `${y}px` } }, h('span', {}, `${i + 1}: ${formatValue(app, p.value, kind)}`))); + }); + } + + /** Turns probing on or off: a click on the plot reads the field there. */ + setProbing(on: boolean) { + this.probing = on; + const vp = this.app.viewport; + if (on) { + this.tool = { + click: (ev) => { + const hit = this.positions && rayHit(this.positions, this.mesh.tris, ev.ray.o, ev.ray.d); + if (!hit || !this.values) return true; + const at = [0, 1, 2].map((c) => interpolate(this.positions!, this.mesh.tris, hit.tri, hit.u, hit.v, 3, c)) as Vec3; + this.probes.push({ at, value: interpolate(this.values, this.mesh.tris, hit.tri, hit.u, hit.v), tri: hit.tri, s: hit.u, t: hit.v }); + this.placePins(); + this.onProbe(); + return true; + }, + }; + vp.tool = this.tool; + } else if (vp.tool === this.tool) { + vp.tool = null; + this.tool = null; + } + } + + /** Undeformed position of a probe (for listing it in model coordinates). */ + probePoint(p: Probe): Vec3 { + const { nodes, tris } = this.mesh; + return [0, 1, 2].map((c) => interpolate(nodes, tris, p.tri, p.s, p.t, 3, c)) as Vec3; + } + + dispose() { + const app = this.app; + this.setProbing(false); + if (this.prevCamera) { app.renderer.onCamera = this.prevCamera; this.prevCamera = null; } + app.renderer.setSolid('feaPlot', null); + app.renderer.setLines('feaMesh', null); + this.legend?.remove(); + this.pins?.remove(); + this.legend = this.pins = null; + if (this.modelHidden) { app.showModelMesh(); this.modelHidden = false; } + } +} diff --git a/src/parametric/src/app/fea/report.ts b/src/parametric/src/app/fea/report.ts new file mode 100644 index 0000000000..d06c7ff0b9 --- /dev/null +++ b/src/parametric/src/app/fea/report.ts @@ -0,0 +1,104 @@ +// The results summary as a CSV file or a printable report (HTML in a new +// window, printed or saved as PDF by the browser). + +import { feaUnits } from '../../model/fea'; +import { formatNumber } from '../../model/units'; +import { download } from '../../platform/files'; +import type { Vec3 } from '../../fea/static'; +import { h } from '../../ui/dom'; +import { showDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import type { FeaResult, FeaWorkspace } from './workspace'; + +interface Line { section: string; name: string; value: string; unit: string } + +/** The summary as rows: section, quantity, value (in the part's units), unit. */ +export function summaryRows(app: App, ws: FeaWorkspace, r: FeaResult): Line[] { + const u = feaUnits(app.store.doc.units); + const s = r.sol.summary, st = r.mesh.stats; + const out: Line[] = []; + const add = (section: string, name: string, value: string | number, unit = '') => out.push({ section, name, value: typeof value === 'number' ? String(Number(value.toPrecision(6))) : value, unit }); + const L = (x: number) => x / u.lengthScale, S = (x: number) => x / u.stressScale, F = (x: number) => x / u.forceScale; + const at = (p: Vec3) => p.map((x) => formatNumber(L(x), app.store.doc.decimals)).join(' '); + add('Study', 'Part', app.store.doc.name); + add('Study', 'Study', ws.study?.name ?? ''); + add('Study', 'Type', 'Linear static (small displacements, linear elastic isotropic material)'); + add('Study', 'Solved', new Date(r.when).toISOString()); + add('Study', 'Up to date', ws.state() === 'ok' ? 'yes' : 'no (the part or the study changed since)'); + add('Material', 'Name', r.material); + add('Material', 'Elastic modulus', S(r.input.E), u.stress); + add('Material', 'Poisson\'s ratio', r.input.nu); + add('Material', 'Yield strength', S(r.yield), u.stress); + add('Material', 'Tensile strength', S(r.uts), u.stress); + add('Material', 'Density', r.input.density * 1e12, 'kg/m³'); + add('Results', 'Max von Mises stress', S(s.maxVonMises.value), u.stress); + add('Results', 'Max von Mises stress at', at(s.maxVonMises.at), u.length); + add('Results', 'Min factor of safety (yield / von Mises)', s.maxVonMises.value > 0 ? r.yield / s.maxVonMises.value : 'infinite'); + add('Results', 'Max displacement', L(s.maxDisplacement.value), u.length); + add('Results', 'Max displacement at', at(s.maxDisplacement.at), u.length); + add('Results', 'Max principal stress', S(s.maxP1.value), u.stress); + add('Results', 'Min principal stress', S(s.minP3.value), u.stress); + add('Results', 'Max equivalent strain', s.maxStrain.value); + add('Results', 'Yielding', s.maxVonMises.value > r.yield ? 'yes: stress above yield, the linear analysis no longer holds there' : 'no'); + r.loadNames.forEach((n, i) => { + const ld = r.input.loads[i]; + add('Loads', n, ld.kind === 'gravity' ? 'gravity' : ld.kind === 'pressure' ? `${Number(S(ld.value).toPrecision(6))} ${u.stress} on ${formatNumber(s.loadAreas[i] / u.lengthScale ** 2, 2)} ${u.length}²` : `${Number(F(ld.total).toPrecision(6))} ${u.force} on ${formatNumber(s.loadAreas[i] / u.lengthScale ** 2, 2)} ${u.length}²`); + }); + for (const [k, v] of [['X', 0], ['Y', 1], ['Z', 2]] as const) add('Forces', `Applied loads (sum) ${k}`, F(s.applied[v]), u.force); + r.fixtureNames.forEach((n, i) => { for (const [k, v] of [['X', 0], ['Y', 1], ['Z', 2]] as const) add('Forces', `Reaction ${n} ${k}`, F(s.reactions[i][v]), u.force); }); + const total = s.reactions.reduce((a, x) => [a[0] + x[0], a[1] + x[1], a[2] + x[2]], [0, 0, 0]); + const imbalance = Math.hypot(total[0] + s.applied[0], total[1] + s.applied[1], total[2] + s.applied[2]) / Math.max(Math.hypot(...s.applied), 1e-30); + add('Forces', 'Equilibrium error (|reactions + loads| / |loads|)', imbalance); + add('Mesh', 'Element type', '10-node quadratic tetrahedra'); + add('Mesh', 'Element size', L(st.size), u.length); + add('Mesh', 'Elements', st.elements); + add('Mesh', 'Nodes', st.nodes); + add('Mesh', 'Unknowns', s.dofs); + add('Mesh', 'Worst element quality (mean ratio)', st.minQuality); + add('Mesh', 'Mean element quality', st.meanQuality); + add('Mesh', 'Volume against the part', `${((st.volume / st.surfaceVolume - 1) * 100).toFixed(3)}%`); + add('Solver', 'Method', `Conjugate gradients, ${s.solver}`); + add('Solver', 'Iterations', s.iterations); + add('Solver', 'Relative residual', s.residual); + add('Solver', 'Time', (s.ms.assemble + s.ms.setup + s.ms.solve + s.ms.stress) / 1000, 's'); + return out; +} + +const csvCell = (v: string) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v); + +export function summaryCsv(rows: Line[]): string { + return ['Section,Quantity,Value,Unit', ...rows.map((r) => [r.section, r.name, r.value, r.unit].map(csvCell).join(','))].join('\n') + '\n'; +} + +const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!); + +export function reportHtml(title: string, rows: Line[], image: string | null): string { + const sections = [...new Set(rows.map((r) => r.section))]; + const body = sections.map((s) => `

${esc(s)}

${rows.filter((r) => r.section === s).map((r) => ``).join('')}
${esc(r.name)}${esc(r.value)}${r.unit ? ` ${esc(r.unit)}` : ''}
`).join(''); + return `${esc(title)}

${esc(title)}

${image ? `Result plot` : ''}${body} +

Linear static analysis: small displacements, linear elastic isotropic material, no contact. Stresses at sharp inner corners and at the edges of fixed faces can grow without bound as the mesh is refined (stress singularities); judge them by the stresses a little away from such spots.

`; +} + +export async function reportDialog(app: App, ws: FeaWorkspace, r: FeaResult) { + const rows = summaryRows(app, ws, r); + const name = `${app.store.doc.name || 'Part'} - ${ws.study?.name ?? 'Static Study'}`; + const v = await showDialog({ + title: 'Results Report', signal: app.documentSignal, + body: [h('p', {}, 'Export the study\'s summary: material, loads, reaction forces, the largest stress and displacement, the factor of safety and the mesh.')], + buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Download CSV', value: 'csv' }, { label: 'Printable Report', value: 'html', primary: true }], + }); + if (v === 'csv') download(summaryCsv(rows), `${name}.csv`, 'text/csv'); + if (v === 'html') { + const image = ws.plotting ? app.renderer.capture(1400) : null; + const html = reportHtml(name, rows, image); + const w = window.open('', '_blank'); + if (!w) { download(html, `${name}.html`, 'text/html'); toast({ kind: 'info', message: 'The report was downloaded (the browser blocked the new window): open it and print it.' }); return; } + w.document.write(html); + w.document.close(); + setTimeout(() => { try { w.print(); } catch { /* the user prints it */ } }, 300); + } +} diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts new file mode 100644 index 0000000000..81b16eca67 --- /dev/null +++ b/src/parametric/src/app/fea/workspace.ts @@ -0,0 +1,555 @@ +// The stress analysis of the open part: the boundary triangulation from the +// geometry kernel, the mesh and the solution from the analysis worker (kept +// until the part, the study or the material changes, then marked out of +// date), the study's symbols in the graphics area, and the result plots. +// Loaded the first time an analysis command runs. + +import { FeaCancelled, FeaClient } from '../../fea/client'; +import type { FeaMeshInfo, FeaSolution } from '../../fea/results'; +import type { FixtureInput, LoadInput, StaticInput, Vec3 } from '../../fea/static'; +import { defaultElementSize, estimateDofs, maxElementSize } from '../../fea/mesher'; +import type { FeaSurface } from '../../kernel/protocol'; +import { FIXTURE_LABELS, LOAD_LABELS, elementSizeFor, newStudy, nextStudyName, type FeaDir, type FeaFixture, type FeaLoad, type FeaLoadType, type FixtureType, type StaticStudy } from '../../model/fea'; +import { elasticOf } from '../../model/materials'; +import { allocateId } from '../../model/document'; +import type { Id } from '../../model/types'; +import { type MenuItem, openMenu } from '../../ui/menu'; +import { promptDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import { faceIndexOf } from './index'; +import { FixturePanel, LoadPanel, ResultsPanel, StudyPanel } from './panels'; +import { reportDialog } from './report'; + +export type StudyState = 'none' | 'busy' | 'ok' | 'stale' | 'error'; + +interface SurfaceState { + version: number; + data: FeaSurface; + auto: number; + max: number; + diag: number; +} + +export interface FeaResult { + key: string; + mesh: FeaMeshInfo; + sol: FeaSolution; + input: StaticInput; + /** Yield and tensile strength (MPa) and material name when it was solved. */ + yield: number; + uts: number; + material: string; + size: number; + /** Names of the fixtures and loads, in input order. */ + fixtureNames: string[]; + loadNames: string[]; + when: number; +} + +const FIX_COLOR = [40, 170, 90]; +const LOAD_COLOR = [210, 60, 150]; + +export class FeaWorkspace { + readonly client = new FeaClient(); + /** The fixture or load selected in the tree (its faces highlighted). */ + focus: Id | null = null; + private surface: SurfaceState | null = null; + private surfaceLoading: Promise | null = null; + mesh: { key: string; info: FeaMeshInfo; size: number } | null = null; + result: FeaResult | null = null; + busy: { stage: string; progress: number } | null = null; + error: { key: string; message: string } | null = null; + private generation = 0; + /** Results panel open: it draws the plot (the study's symbols are hidden). */ + plotting = false; + + constructor(readonly app: App) { + app.store.on((reason) => { + if (reason === 'load') this.reset(); + this.changed(); + }); + app.ribbonTabListeners.push(() => this.redraw()); + app.commands.onChange(() => { + // A new part shape: the surface, the mesh and the results are out of date (results stay, marked). + if (this.surface && this.surface.version !== app.geometryVersion) { this.surface = null; this.changed(); } + }); + } + + private reset() { + this.client.cancel(); + this.surface = null; + this.mesh = null; + this.result = null; + this.busy = null; + this.error = null; + this.focus = null; + this.generation++; + } + + get study(): StaticStudy | null { + return this.app.store.doc.study ?? null; + } + + /** Redraws the tree and the graphics. */ + changed() { + this.redraw(); + this.app.renderTrees(); + if (this.app.panel instanceof ResultsPanel || this.app.panel instanceof StudyPanel) this.app.refreshPanel(); + } + + // ---------- state ---------- + + /** What the results depend on: the part's shape, the mesh size, the study's fixtures and loads, the material. */ + solveKey(size?: number): string { + const s = this.study; + const strip = (x: FeaFixture | FeaLoad) => { const { name: _n, ...rest } = x; void _n; return rest; }; + return JSON.stringify([this.app.geometryVersion, size ?? this.sizeOf(), s ? [s.fixtures.map(strip), s.loads.map(strip)] : null, elasticOf(this.app.store.doc.material), this.app.store.doc.material?.density]); + } + + private sizeOf(): number { + const s = this.study, sf = this.surface; + return sf && s ? elementSizeFor(sf.auto, sf.max, s.mesh.fineness) : 0; + } + + state(): StudyState { + if (this.busy) return 'busy'; + if (this.error && !this.result) return 'error'; + if (!this.result) return 'none'; + if (!this.surface || this.surface.version !== this.app.geometryVersion || this.result.key !== this.solveKey()) return 'stale'; + return 'ok'; + } + + progressText(): string { + return this.busy ? `${this.busy.stage}${this.busy.progress > 0 ? ` ${Math.round(this.busy.progress * 100)}%` : ''}` : ''; + } + + errorText(): string { + return this.error?.message ?? ''; + } + + meshText(): string { + const m = this.mesh; + if (!m) return ''; + const st = m.info.stats; + return `(${st.elements.toLocaleString('en-US')} elements${m.key.startsWith(`${this.app.geometryVersion}|`) ? '' : ', out of date'})`; + } + + /** Can the study run now (a part with a solid, nothing being edited)? */ + ready(): string | null { + const app = this.app; + if (app.assembly) return 'Stress analysis works on parts. Open the part to analyze it.'; + if (!app.bbox) return 'The part has no solid body to analyze yet.'; + if (app.sketchEditor || (app.panel?.editingId)) return 'Finish the feature or sketch being edited first.'; + return null; + } + + // ---------- geometry ---------- + + /** The part's boundary from the kernel, with the automatic and largest element sizes. */ + async surfaceState(): Promise { + const app = this.app; + await app.whenBuilt(); + const version = app.geometryVersion; + if (this.surface && this.surface.version === version) return this.surface; + if (this.surfaceLoading) return this.surfaceLoading; + this.surfaceLoading = (async () => { + try { + const b = app.bbox; + const diag = b ? Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]) : 100; + const data = await app.kernel.feaSurface(diag * 3e-4); + let area = 0; + const P = data.positions, I = data.indices; + for (let t = 0; t < I.length; t += 3) { + const a = I[t] * 3, b2 = I[t + 1] * 3, c = I[t + 2] * 3; + const ux = P[b2] - P[a], uy = P[b2 + 1] - P[a + 1], uz = P[b2 + 2] - P[a + 2], wx = P[c] - P[a], wy = P[c + 1] - P[a + 1], wz = P[c + 2] - P[a + 2]; + area += 0.5 * Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx); + } + const st: SurfaceState = { version, data, diag, auto: defaultElementSize(data.volume, area, diag), max: maxElementSize(data.volume, area, diag) }; + if (app.geometryVersion !== version) return this.surfaceState(); + this.surface = st; + return st; + } finally { + this.surfaceLoading = null; + } + })(); + return this.surfaceLoading; + } + + /** Element size and estimated size of the problem for a fineness (null before the surface is known). */ + sizes(fineness: number): { size: number; auto: number; dofs: number } | null { + const sf = this.surface; + if (!sf) return null; + const size = elementSizeFor(sf.auto, sf.max, fineness); + return { size, auto: sf.auto, dofs: estimateDofs(sf.data.volume, size) }; + } + + private setBusy(stage: string, progress: number) { + const was = this.busy?.stage; + this.busy = { stage, progress }; + this.app.setStatus(this.progressText()); + // The tree and panel show the stage; redraw them on a new stage or every few percent. + if (was !== stage || Math.round(progress * 100) % 5 === 0) { + this.app.renderTrees(); + const p = this.app.panel; + if (p instanceof ResultsPanel || p instanceof StudyPanel) p.progress(this.busy); + } + } + + /** Meshes the part at the study's size if the mesh is not current. */ + async ensureMesh(): Promise<{ info: FeaMeshInfo; size: number } | null> { + const s = this.study; + if (!s) return null; + const gen = this.generation; + this.setBusy('Preparing the part', 0); + const sf = await this.surfaceState(); + if (gen !== this.generation) return null; + const size = elementSizeFor(sf.auto, sf.max, s.mesh.fineness); + const key = `${sf.version}|${size}`; + if (this.mesh?.key === key && this.client.meshed) return this.mesh; + this.setBusy('Meshing', 0); + // A copy: the surface stays here for the next mesh (the worker gets its own). + const surface = { positions: sf.data.positions.slice(), indices: sf.data.indices.slice(), triFace: sf.data.triFace.slice() }; + const info = await this.client.mesh(surface, size, (stage, v) => this.setBusy(`Meshing: ${stage.toLowerCase()}`, v)); + if (gen !== this.generation) return null; + this.mesh = { key, info, size }; + return this.mesh; + } + + /** Meshes the part (from the mesh panel). */ + async meshNow(): Promise { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + try { + await this.ensureMesh(); + this.error = null; + } catch (e) { + if (!(e instanceof FeaCancelled)) this.error = { key: '', message: (e as Error).message }; + } finally { + this.busy = null; + this.app.setStatus(this.mesh ? `Meshed: ${this.mesh.info.stats.elements.toLocaleString('en-US')} elements, ${this.mesh.info.stats.nodes.toLocaleString('en-US')} nodes` : this.error?.message ?? '', !this.mesh); + this.changed(); + } + } + + // ---------- the study as solver input ---------- + + /** Direction of a reference (unit vector), or null if it cannot be found in the part. */ + dirOf(d: FeaDir): Vec3 | null { + const app = this.app; + if (d.kind === 'base') return d.axis === 'x' ? [1, 0, 0] : d.axis === 'y' ? [0, 1, 0] : [0, 0, 1]; + if (d.kind === 'face') { + const i = faceIndexOf(app, d.face); + const f = app.faces[i]; + if (!f) return null; + const v = f.normal ?? f.axis?.d; + return v ? [v[0], v[1], v[2]] : null; + } + const e = app.edges.find((x) => x.name === d.edge.name) ?? null; + if (!e) return null; + const v = e.dir ?? e.axis; + if (v) return [v[0], v[1], v[2]]; + const l = Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1], e.b[2] - e.a[2]); + return l > 0 ? [(e.b[0] - e.a[0]) / l, (e.b[1] - e.a[1]) / l, (e.b[2] - e.a[2]) / l] : null; + } + + /** The study for the solver: face indices, directions, the material (throws a message for the user). */ + inputOf(s: StaticStudy): { input: StaticInput; fixtureNames: string[]; loadNames: string[] } { + const app = this.app; + const mat = app.store.doc.material; + const el = elasticOf(mat); + if (!mat) throw new Error('Choose the part\'s material first (Material on the Analysis tab).'); + if (!el) throw new Error(`${mat.name} has no elastic properties for analysis${/oak|pine|wood/i.test(mat.name) ? ' (wood is anisotropic)' : ''}. Choose another material, or give a custom one its elastic modulus, Poisson's ratio and strengths.`); + const faces = (refs: FeaFixture['faces'], what: string) => { + const out = refs.map((r) => faceIndexOf(app, r)); + if (!out.length) throw new Error(`${what}: pick the faces it acts on.`); + if (out.some((i) => i < 0)) throw new Error(`${what}: a face it uses is no longer in the part. Edit it and pick the faces again.`); + return out; + }; + const fixtures: FixtureInput[] = []; + const fixtureNames: string[] = []; + for (const f of s.fixtures) { + if (f.suppressed) continue; + const idx = faces(f.faces, f.name); + if (f.type === 'hinge') { + const cyl = app.faces[idx[0]]; + if (!idx.every((i) => app.faces[i].type === 'cylinder') || !cyl.axis) throw new Error(`${f.name}: a fixed hinge goes on cylindrical faces (a pin hole or a shaft).`); + fixtures.push({ kind: 'hinge', faces: idx, axis: { p: cyl.axis.p, d: cyl.axis.d } }); + } else fixtures.push({ kind: f.type, faces: idx }); + fixtureNames.push(f.name); + } + const loads: LoadInput[] = []; + const loadNames: string[] = []; + for (const l of s.loads) { + if (l.suppressed) continue; + const sign = l.flip ? -1 : 1; + if (l.type === 'gravity') { + const d = this.dirOf(l.dir); + if (!d) throw new Error(`${l.name}: its direction reference is no longer in the part.`); + loads.push({ kind: 'gravity', accel: [d[0] * l.value * sign, d[1] * l.value * sign, d[2] * l.value * sign] }); + } else if (l.type === 'pressure') { + loads.push({ kind: 'pressure', faces: faces(l.faces, l.name), value: l.value * sign }); + } else { + const idx = faces(l.faces, l.name); + if (!l.dir) loads.push({ kind: 'force', faces: idx, total: l.value * sign, dir: null }); + else { + const d = this.dirOf(l.dir); + if (!d) throw new Error(`${l.name}: its direction reference is no longer in the part.`); + loads.push({ kind: 'force', faces: idx, total: l.value, dir: [d[0] * sign, d[1] * sign, d[2] * sign] }); + } + } + loadNames.push(l.name); + } + if (!fixtures.length) throw new Error('Add a fixture: without one the part is free to move.'); + if (!loads.length) throw new Error('Add a load: a force, a pressure or gravity.'); + return { input: { E: el.E, nu: el.nu, density: mat.density * 1e-12, fixtures, loads }, fixtureNames, loadNames }; + } + + // ---------- running ---------- + + /** Meshes (if needed) and solves the study, then shows the results. */ + async run(): Promise { + const s = this.study; + if (!s) { this.openStudy(); return; } + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + if (this.busy) return; + const gen = ++this.generation; + let resolved: ReturnType; + try { + resolved = this.inputOf(s); + } catch (e) { + this.error = { key: this.solveKey(), message: (e as Error).message }; + this.changed(); + void this.openResults(); + return; + } + this.error = null; + void this.openResults(); + try { + const m = await this.ensureMesh(); + if (!m || gen !== this.generation) return; + const key = this.solveKey(m.size); + const t0 = performance.now(); + const sol = await this.client.solve(resolved.input, (stage, v) => this.setBusy(stage, v)); + if (gen !== this.generation) return; + const el = elasticOf(this.app.store.doc.material)!; + this.result = { + key, mesh: m.info, sol, input: resolved.input, yield: el.yield, uts: el.uts, material: this.app.store.doc.material?.name ?? '', size: m.size, + fixtureNames: resolved.fixtureNames, loadNames: resolved.loadNames, when: Date.now(), + }; + this.busy = null; + this.app.setStatus(`Solved in ${((performance.now() - t0) / 1000).toFixed(1)} s: ${sol.summary.dofs.toLocaleString('en-US')} degrees of freedom`); + } catch (e) { + if (e instanceof FeaCancelled) { this.app.setStatus('Analysis cancelled'); } + else { this.error = { key: this.solveKey(), message: (e as Error).message }; this.app.setStatus((e as Error).message, true); } + } finally { + if (gen === this.generation) this.busy = null; + this.changed(); + } + } + + cancel() { + this.generation++; + this.client.cancel(); + this.busy = null; + this.changed(); + } + + // ---------- panels ---------- + + /** Creates the study if there is none (one undo step); returns it. */ + ensureStudy(): StaticStudy { + if (!this.study) { + this.app.store.change('New static study', (d) => { d.study = newStudy(allocateId(d, 'st')); }); + this.app.setRibbonTab('analysis'); + } + return this.study!; + } + + openStudy() { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + this.ensureStudy(); + this.app.exitModes(); + void this.app.openPanel(new StudyPanel(this.app, this)); + void this.surfaceState().then(() => this.app.panel instanceof StudyPanel && this.app.refreshPanel()).catch(() => {}); + } + + openMesh() { + this.openStudy(); + } + + newFixture(type: FixtureType) { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + const s = this.ensureStudy(); + const faces = this.app.selection.ofKind('face').map((it) => this.app.faces[it.index]).filter((f) => f && !f.body && (type !== 'hinge' || f.type === 'cylinder')); + const f: FeaFixture = { id: allocateId(this.app.store.doc, 'fx'), name: nextStudyName(s, FIXTURE_LABELS[type].replace(/\/.*/, '')), type, faces: faces.map((x) => ({ name: x.name, sig: { type: x.type, c: x.center, n: x.normal, area: x.area } })) }; + this.app.exitModes(); + void this.app.openPanel(new FixturePanel(this.app, this, f, true)); + } + + newLoad(type: FeaLoadType) { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + const s = this.ensureStudy(); + const faces = this.app.selection.ofKind('face').map((it) => this.app.faces[it.index]).filter((f) => f && !f.body).map((x) => ({ name: x.name, sig: { type: x.type, c: x.center, n: x.normal, area: x.area } })); + const id = allocateId(this.app.store.doc, 'ld'); + const name = nextStudyName(s, LOAD_LABELS[type]); + const inch = this.app.store.doc.units === 'IPS'; + const l: FeaLoad = type === 'force' ? { id, name, type, faces, value: inch ? 444.8221615 : 100, dir: null, flip: false } + : type === 'pressure' ? { id, name, type, faces, value: inch ? 0.6894757 : 1, flip: false } + : { id, name, type, value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }; + this.app.exitModes(); + void this.app.openPanel(new LoadPanel(this.app, this, l, true)); + } + + editItem(id: Id) { + const s = this.study; + const fx = s?.fixtures.find((x) => x.id === id), ld = s?.loads.find((x) => x.id === id); + if (!fx && !ld) return; + this.focus = id; + this.app.exitModes(); + if (fx) void this.app.openPanel(new FixturePanel(this.app, this, structuredClone(fx), false)); + else void this.app.openPanel(new LoadPanel(this.app, this, structuredClone(ld!), false)); + } + + focusItem(id: Id) { + this.focus = this.focus === id ? null : id; + if (this.app.ribbonTabId !== 'analysis') this.app.setRibbonTab('analysis'); + this.changed(); + } + + itemMenu(id: Id, x: number, y: number) { + const s = this.study; + const item = s?.fixtures.find((f) => f.id === id) ?? s?.loads.find((l) => l.id === id); + if (!item) return; + const mutate = (label: string, fn: (it: FeaFixture | FeaLoad, st: StaticStudy) => void) => this.app.store.change(label, (d) => { + const st = d.study; + const it = st?.fixtures.find((f) => f.id === id) ?? st?.loads.find((l) => l.id === id); + if (st && it) fn(it, st); + }); + const items: MenuItem[] = [ + { label: 'Edit', icon: 'edit', run: () => this.editItem(id) }, + { label: item.suppressed ? 'Unsuppress' : 'Suppress', icon: item.suppressed ? 'eye' : 'eyeOff', run: () => mutate(item.suppressed ? 'Unsuppress' : 'Suppress', (it) => { it.suppressed = !it.suppressed || undefined; }) }, + { + label: 'Rename', icon: 'text', run: () => void promptDialog('Rename', 'Name', item.name, (v) => (v.trim() ? null : 'Enter a name'), this.app.documentSignal).then((name) => { + if (name && name.trim() !== item.name) mutate('Rename', (it) => { it.name = name.trim(); }); + }), + }, + { separator: true }, + { label: 'Delete', icon: 'trash', run: () => mutate(`Delete ${item.name}`, (_it, st) => { st.fixtures = st.fixtures.filter((f) => f.id !== id); st.loads = st.loads.filter((l) => l.id !== id); }) }, + ]; + openMenu(items, x, y, { label: `${item.name} menu` }); + } + + /** Opens the results panel (it shows progress while the study runs). */ + async openResults() { + if (this.app.panel instanceof ResultsPanel) { this.app.refreshPanel(); return; } + this.app.exitModes(); + await this.app.openPanel(new ResultsPanel(this.app, this)); + } + + /** Shows the results, running the study first if it has never run. */ + async showResults() { + if (!this.result && !this.busy && !this.error) { await this.run(); return; } + await this.openResults(); + } + + report() { + if (!this.result) { toast({ kind: 'info', message: 'Run the study first: there are no results to report yet.' }); return; } + void reportDialog(this.app, this, this.result); + } + + deleteStudy() { + if (this.app.panel instanceof ResultsPanel || this.app.panel instanceof StudyPanel) void this.app.closePanel(false); + this.app.store.change('Delete study', (d) => { d.study = null; }); + this.reset(); + this.changed(); + } + + // ---------- display ---------- + + private shown(): boolean { + const app = this.app; + if (app.inDrawing || app.assembly || app.sketchEditor || this.plotting) return false; + return app.ribbonTabId === 'analysis' || app.panel instanceof FixturePanel || app.panel instanceof LoadPanel || app.panel instanceof StudyPanel; + } + + /** Triangles of a face of the shown model. */ + private faceTris(index: number, out: number[]) { + const m = this.app.modelMesh; + if (!m) return; + const idx = m.indices, P = m.positions, vf = m.vertexFace; + for (let t = 0; t < idx.length; t += 3) { + if (Math.round(vf[idx[t]]) !== index) continue; + for (let k = 0; k < 3; k++) { const v = idx[t + k] * 3; out.push(P[v], P[v + 1], P[v + 2]); } + } + } + + /** The fixtures and loads on the model (tinted faces, arrows), and the mesh while its panel is open. */ + redraw() { + const r = this.app.renderer; + if (!r) return; + const s = this.study; + if (!s || !this.shown()) { + r.setTris('feaFix', null); r.setLines('feaArrows', null); + if (!this.plotting) r.setLines('feaMesh', null); + return; + } + const tri: number[] = [], col: number[] = []; + const arrows: number[] = [], acol: number[] = []; + const b = this.app.bbox; + const size = b ? Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]) * 0.08 : 10; + const arrow = (p: Vec3, d: Vec3, c: number[]) => { + // From the tail to the point it presses on. + const t: Vec3 = [p[0] - d[0] * size, p[1] - d[1] * size, p[2] - d[2] * size]; + const side: Vec3 = Math.abs(d[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + const n: Vec3 = [d[1] * side[2] - d[2] * side[1], d[2] * side[0] - d[0] * side[2], d[0] * side[1] - d[1] * side[0]]; + const nl = Math.hypot(...n) || 1; + const h = size * 0.25; + const back: Vec3 = [p[0] - d[0] * h, p[1] - d[1] * h, p[2] - d[2] * h]; + arrows.push(...t, ...p, ...p, back[0] + (n[0] / nl) * h * 0.5, back[1] + (n[1] / nl) * h * 0.5, back[2] + (n[2] / nl) * h * 0.5, ...p, back[0] - (n[0] / nl) * h * 0.5, back[1] - (n[1] / nl) * h * 0.5, back[2] - (n[2] / nl) * h * 0.5); + for (let k = 0; k < 3; k++) acol.push(...c, 255); + }; + const tint = (faces: FeaFixture['faces'], c: number[], focused: boolean) => { + for (const ref of faces) { + const i = faceIndexOf(this.app, ref); + if (i < 0) continue; + const before = tri.length; + this.faceTris(i, tri); + for (let k = before; k < tri.length; k += 3) col.push(...c, focused ? 150 : 95); + } + }; + for (const f of s.fixtures) if (!f.suppressed) tint(f.faces, FIX_COLOR, this.focus === f.id); + for (const l of s.loads) { + if (l.suppressed) continue; + if (l.type === 'gravity') { + const d = this.dirOf(l.dir); + if (d && b) { + const c: Vec3 = [(b.min[0] + b.max[0]) / 2, (b.min[1] + b.max[1]) / 2, (b.min[2] + b.max[2]) / 2]; + const sg = l.flip ? -1 : 1; + arrow(c, [d[0] * sg, d[1] * sg, d[2] * sg], LOAD_COLOR); + } + continue; + } + tint(l.faces, LOAD_COLOR, this.focus === l.id); + for (const ref of l.faces) { + const f = this.app.faces[faceIndexOf(this.app, ref)]; + if (!f) continue; + let d: Vec3 | null = null; + const sg = l.flip ? -1 : 1; + if (l.type === 'force' && l.dir) { const v = this.dirOf(l.dir); if (v) d = [v[0] * sg, v[1] * sg, v[2] * sg]; } + else if (f.normal) d = [-f.normal[0] * sg, -f.normal[1] * sg, -f.normal[2] * sg]; + if (d) arrow(f.center, d, LOAD_COLOR); + } + } + r.setTris('feaFix', tri.length ? { positions: new Float32Array(tri), colors: new Uint8Array(col), depth: 'test', order: 2 } : null); + r.setLines('feaArrows', arrows.length ? { positions: new Float32Array(arrows), colors: new Uint8Array(acol), width: 2.5, depth: 'always', order: 8 } : null); + // The mesh while the study panel is open. + const m = this.mesh; + if (m && this.app.panel instanceof StudyPanel && m.key.startsWith(`${this.app.geometryVersion}|`)) { + r.setLines('feaMesh', { positions: m.info.lines, colors: new Uint8Array((m.info.lines.length / 6) * 4).fill(0).map((_, i) => (i % 4 === 3 ? 200 : 40)), width: 1, depth: 'test', order: 6, bias: 4e-5 }); + } else if (!this.plotting) r.setLines('feaMesh', null); + } +} diff --git a/src/parametric/src/app/tree.ts b/src/parametric/src/app/tree.ts index 53528cddce..0f46b2fe74 100644 --- a/src/parametric/src/app/tree.ts +++ b/src/parametric/src/app/tree.ts @@ -12,6 +12,7 @@ import type { App } from './app'; import type { SelItem } from './selection'; import { sheetMetalTreeRows } from './sheetmetal-panels'; import { camTreeRows } from './cam'; +import { feaTreeRows } from './fea'; interface Row { key: string; @@ -98,6 +99,8 @@ export class FeatureTree { } // CAM: setups and their operations, open unless closed (the set holds the closed ones). rows.push(...camTreeRows(app, (k) => !this.expanded.has(k) || !!this.filter).map((r) => ({ ...r, item: null }))); + // Stress analysis: the study's fixtures, loads, mesh and results. + rows.push(...feaTreeRows(app, (k) => !this.expanded.has(k) || !!this.filter).map((r) => ({ ...r, item: null }))); if (!this.filter) return rows; return rows.filter((r) => r.depth === 0 || r.label.toLowerCase().includes(this.filter)); } @@ -123,7 +126,7 @@ export class FeatureTree { const f = r.feature; const index = f ? doc.features.indexOf(f) : -1; // Rollback bar sits after the last built top-level feature. - if (!rollbackPlaced && ((f && r.depth === 1 && index >= built) || r.key === 'cam')) { + if (!rollbackPlaced && ((f && r.depth === 1 && index >= built) || r.key === 'cam' || r.key === 'fea')) { this.list.append(this.rollbackBar()); rollbackPlaced = true; } diff --git a/src/parametric/src/fea/client.ts b/src/parametric/src/fea/client.ts new file mode 100644 index 0000000000..bb7922bf43 --- /dev/null +++ b/src/parametric/src/fea/client.ts @@ -0,0 +1,102 @@ +// The interface side of the stress analysis worker. Requests run one at a +// time; cancelling stops the worker (a computation in progress cannot be +// interrupted otherwise) and the next request starts a new one, which meshes +// again. + +import type { StaticInput } from './static'; +import type { FeaSurfaceData } from './surface'; +import type { FeaMeshInfo, FeaSolution } from './results'; +import type { FeaWorkerRequest, FeaWorkerResponse } from './worker'; + +type Payload = { type: 'mesh'; surface: FeaSurfaceData; size: number } | { type: 'solve'; input: StaticInput }; + +interface Pending { + resolve: (v: unknown) => void; + reject: (e: Error) => void; + progress?: (stage: string, v: number) => void; +} + +export class FeaCancelled extends Error { + constructor() { super('Cancelled'); } +} + +/** An error from the worker; `user`: its message is written for the user (else an internal failure). */ +export class FeaEngineError extends Error { + constructor(message: string, readonly user: boolean) { + super(user ? message : `The analysis ran into a problem (${message})`); + } +} + +export class FeaClient { + private worker: Worker | null = null; + private nextId = 1; + private pending = new Map(); + /** Whether the worker holds a mesh (a new worker has none). */ + meshed = false; + + constructor(private readonly create: () => Worker = () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module', name: 'analysis' })) {} + + private ensure(): Worker { + if (this.worker) return this.worker; + const w = this.create(); + w.onmessage = (ev: MessageEvent) => { + const r = ev.data; + const p = this.pending.get(r.id); + if (!p) return; + if (r.type === 'progress') { p.progress?.(r.stage, r.value); return; } + this.pending.delete(r.id); + if (r.type === 'done') p.resolve(r.result); + else p.reject(new FeaEngineError(r.error, r.user)); + }; + w.onerror = (ev) => { + ev.preventDefault?.(); + this.fail(new Error(`The analysis stopped${ev.message ? ` (${ev.message})` : ''}. The part may be too large for this mesh size: try a coarser mesh.`)); + }; + this.worker = w; + this.meshed = false; + return w; + } + + private send(payload: Payload, progress?: (stage: string, v: number) => void, transfer: Transferable[] = []): Promise { + const w = this.ensure(); + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, progress }); + w.postMessage({ id, ...payload } as FeaWorkerRequest, transfer); + }); + } + + async mesh(surface: FeaSurfaceData, size: number, progress?: (stage: string, v: number) => void): Promise { + this.meshed = false; + const info = await this.send({ type: 'mesh', surface, size }, progress); + this.meshed = true; + return info; + } + + solve(input: StaticInput, progress?: (stage: string, v: number) => void): Promise { + return this.send({ type: 'solve', input }, progress); + } + + /** Stops whatever is running (its promise rejects with FeaCancelled); the mesh goes with the worker. */ + cancel() { + if (!this.pending.size) return; + this.fail(new FeaCancelled()); + } + + private fail(e: Error) { + this.worker?.terminate(); + this.worker = null; + this.meshed = false; + const all = [...this.pending.values()]; + this.pending.clear(); + for (const p of all) p.reject(e); + } + + get busy(): boolean { + return this.pending.size > 0; + } + + dispose() { + this.fail(new FeaCancelled()); + } +} diff --git a/src/parametric/src/fea/results.ts b/src/parametric/src/fea/results.ts new file mode 100644 index 0000000000..6570b550fb --- /dev/null +++ b/src/parametric/src/fea/results.ts @@ -0,0 +1,185 @@ +// What the interface gets from the analysis: the mesh's boundary (the +// surface the results are drawn on, with its own node numbering), the +// fields at those nodes, and a summary over the whole mesh. Also the +// helpers that turn fields into colours and values at a point. + +import type { MeshStats, TetMesh } from './mesher'; +import type { StaticInput, StaticResult, Vec3 } from './static'; + +export interface FeaMeshInfo { + stats: MeshStats; + /** xyz of the boundary nodes (corner and midside). */ + nodes: Float32Array; + /** 6 boundary nodes per triangle: corners, then midside nodes of edges 01, 12, 20. */ + tris: Uint32Array; + /** B-rep face of each triangle. */ + triFace: Int32Array; + /** Element edges on the boundary as segments (each edge through its midside node), for showing the mesh. */ + lines: Float32Array; +} + +export type FieldName = 'vonMises' | 'p1' | 'p2' | 'p3' | 'disp' | 'ux' | 'uy' | 'uz' | 'strain' | 'fos'; + +export interface Extreme { + value: number; + at: Vec3; +} + +export interface FeaSummary { + maxVonMises: Extreme; + maxDisplacement: Extreme; + maxP1: Extreme; + minP3: Extreme; + maxStrain: Extreme; + reactions: Vec3[]; + applied: Vec3; + loadAreas: number[]; + dofs: number; + iterations: number; + residual: number; + solver: string; + ms: StaticResult['ms']; + /** Weight of the part (N) when gravity is applied, else 0. */ + mass: number; +} + +export interface FeaSolution { + /** Per boundary node: displacement (3 per node), von Mises, principal stresses 1-3, equivalent strain. */ + fields: Float32Array[]; + summary: FeaSummary; +} + +/** The boundary of a mesh with its nodes renumbered; `map` gives each boundary node's mesh node. */ +export function meshView(mesh: TetMesh): { info: FeaMeshInfo; map: Int32Array } { + const remap = new Map(); + const map: number[] = []; + const tris = new Uint32Array(mesh.tris.length); + for (let q = 0; q < mesh.tris.length; q++) { + const v = mesh.tris[q]; + let id = remap.get(v); + if (id === undefined) { id = map.length; remap.set(v, id); map.push(v); } + tris[q] = id; + } + const nodes = new Float32Array(map.length * 3); + map.forEach((v, i) => { nodes[i * 3] = mesh.nodes[v * 3]; nodes[i * 3 + 1] = mesh.nodes[v * 3 + 1]; nodes[i * 3 + 2] = mesh.nodes[v * 3 + 2]; }); + const seen = new Set(); + const lines: number[] = []; + const nt = tris.length / 6; + for (let f = 0; f < nt; f++) { + for (const [a, b, m] of [[0, 1, 3], [1, 2, 4], [2, 0, 5]]) { + const key = tris[f * 6 + m]; + if (seen.has(key)) continue; + seen.add(key); + for (const [p, q] of [[a, m], [m, b]]) { + const i = tris[f * 6 + p] * 3, j = tris[f * 6 + q] * 3; + lines.push(nodes[i], nodes[i + 1], nodes[i + 2], nodes[j], nodes[j + 1], nodes[j + 2]); + } + } + } + return { info: { stats: mesh.stats, nodes, tris, triFace: Int32Array.from(mesh.triFace), lines: Float32Array.from(lines) }, map: Int32Array.from(map) }; +} + +function extreme(mesh: TetMesh, values: ArrayLike, sign = 1): Extreme { + let best = 0, bv = -Infinity; + for (let v = 0; v < values.length; v++) if (sign * values[v] > bv) { bv = sign * values[v]; best = v; } + return { value: values[best] ?? 0, at: [mesh.nodes[best * 3], mesh.nodes[best * 3 + 1], mesh.nodes[best * 3 + 2]] }; +} + +export function solutionOf(mesh: TetMesh, map: Int32Array, r: StaticResult, input: StaticInput): FeaSolution { + const n = map.length; + const U = new Float32Array(n * 3); + const pick = (src: Float64Array) => { const out = new Float32Array(n); for (let i = 0; i < n; i++) out[i] = src[map[i]]; return out; }; + for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) U[i * 3 + k] = r.U[map[i] * 3 + k]; + const N = r.vonMises.length; + const disp = new Float64Array(N); + for (let v = 0; v < N; v++) disp[v] = Math.hypot(r.U[v * 3], r.U[v * 3 + 1], r.U[v * 3 + 2]); + const gravity = input.loads.find((l) => l.kind === 'gravity'); + const g = gravity && gravity.kind === 'gravity' ? Math.hypot(...gravity.accel) : 0; + let volume = 0; + void volume; + return { + fields: [U, pick(r.vonMises), pick(r.p1), pick(r.p2), pick(r.p3), pick(r.strain)], + summary: { + maxVonMises: extreme(mesh, r.vonMises), maxDisplacement: extreme(mesh, disp), maxP1: extreme(mesh, r.p1), minP3: extreme(mesh, r.p3, -1), maxStrain: extreme(mesh, r.strain), + reactions: r.reactions, applied: r.applied, loadAreas: r.loadAreas, dofs: r.dofs, iterations: r.iterations, residual: r.residual, solver: r.solver, ms: r.ms, + mass: g > 0 ? mesh.stats.volume * input.density * 1000 : 0, + }, + }; +} + +/** Values of a field at the boundary nodes (factor of safety needs the yield strength). */ +export function fieldValues(sol: FeaSolution, field: FieldName, yieldStrength: number): Float32Array { + const [U, vm, p1, p2, p3, strain] = sol.fields; + const n = vm.length; + if (field === 'vonMises') return vm; + if (field === 'p1') return p1; + if (field === 'p2') return p2; + if (field === 'p3') return p3; + if (field === 'strain') return strain; + const out = new Float32Array(n); + if (field === 'fos') { for (let i = 0; i < n; i++) out[i] = vm[i] > 0 ? yieldStrength / vm[i] : Infinity; return out; } + if (field === 'disp') { for (let i = 0; i < n; i++) out[i] = Math.hypot(U[i * 3], U[i * 3 + 1], U[i * 3 + 2]); return out; } + const k = field === 'ux' ? 0 : field === 'uy' ? 1 : 2; + for (let i = 0; i < n; i++) out[i] = U[i * 3 + k]; + return out; +} + +/** Rainbow colour map (blue low, red high), t in 0..1, as RGB 0..255. */ +export function colorAt(t: number): [number, number, number] { + const x = Math.max(0, Math.min(1, t)); + // Blue, cyan, green, yellow, red. + const stops: [number, number, number][] = [[20, 60, 220], [0, 190, 230], [40, 200, 80], [250, 220, 30], [225, 40, 30]]; + const s = x * (stops.length - 1); + const i = Math.min(stops.length - 2, Math.floor(s)); + const f = s - i; + return [0, 1, 2].map((k) => Math.round(stops[i][k] + (stops[i + 1][k] - stops[i][k]) * f)) as [number, number, number]; +} + +/** + * Where a ray first meets the (possibly deformed) result surface: the triangle, + * its barycentric coordinates on the flat corner triangle, and the point. + */ +export function rayHit(positions: Float32Array, tris: Uint32Array, o: Vec3, d: Vec3): { tri: number; u: number; v: number; t: number } | null { + let best: { tri: number; u: number; v: number; t: number } | null = null; + const nt = tris.length / 6; + for (let f = 0; f < nt; f++) { + // The six-node triangle as four flat ones (corners and midside nodes). + for (const [a, b, c, map] of SUB) { + const ia = tris[f * 6 + a] * 3, ib = tris[f * 6 + b] * 3, ic = tris[f * 6 + c] * 3; + const e1 = [positions[ib] - positions[ia], positions[ib + 1] - positions[ia + 1], positions[ib + 2] - positions[ia + 2]]; + const e2 = [positions[ic] - positions[ia], positions[ic + 1] - positions[ia + 1], positions[ic + 2] - positions[ia + 2]]; + const p = [d[1] * e2[2] - d[2] * e2[1], d[2] * e2[0] - d[0] * e2[2], d[0] * e2[1] - d[1] * e2[0]]; + const det = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2]; + if (Math.abs(det) < 1e-12) continue; + const s = [o[0] - positions[ia], o[1] - positions[ia + 1], o[2] - positions[ia + 2]]; + const u = (s[0] * p[0] + s[1] * p[1] + s[2] * p[2]) / det; + if (u < 0 || u > 1) continue; + const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]]; + const v = (d[0] * q[0] + d[1] * q[1] + d[2] * q[2]) / det; + if (v < 0 || u + v > 1) continue; + const t = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) / det; + if (t <= 0 || (best && t >= best.t)) continue; + // Back to the parent triangle's coordinates. + const L = map(1 - u - v, u, v); + best = { tri: f, u: L[1], v: L[2], t }; + } + } + return best; +} + +/** Sub-triangles of a six-node triangle (slots), with the map from their barycentric coordinates to the parent's (r, s, t). */ +export const SUB: [number, number, number, (a: number, b: number, c: number) => [number, number, number]][] = [ + [0, 3, 5, (a, b, c) => [a + b / 2 + c / 2, b / 2, c / 2]], + [3, 1, 4, (a, b, c) => [a / 2, a / 2 + b + c / 2, c / 2]], + [5, 4, 2, (a, b, c) => [a / 2, b / 2, a / 2 + b / 2 + c]], + [3, 4, 5, (a, b, c) => [a / 2 + c / 2, a / 2 + b / 2, b / 2 + c / 2]], +]; + +/** Value of a node field at (s, t) on six-node triangle f (quadratic interpolation). */ +export function interpolate(values: ArrayLike, tris: Uint32Array, f: number, s: number, t: number, stride = 1, comp = 0): number { + const r = 1 - s - t; + const N = [r * (2 * r - 1), s * (2 * s - 1), t * (2 * t - 1), 4 * r * s, 4 * s * t, 4 * t * r]; + let out = 0; + for (let a = 0; a < 6; a++) out += N[a] * values[tris[f * 6 + a] * stride + comp]; + return out; +} diff --git a/src/parametric/src/fea/worker.ts b/src/parametric/src/fea/worker.ts new file mode 100644 index 0000000000..6478d5d938 --- /dev/null +++ b/src/parametric/src/fea/worker.ts @@ -0,0 +1,47 @@ +/// +// Stress analysis worker: meshes the part and solves studies away from the +// interface. It keeps the last mesh, so a study changed without changing the +// part or the mesh size is solved again without meshing. + +import { MeshError, type TetMesh, meshSolid } from './mesher'; +import { type StaticInput, StudyError, solveStatic } from './static'; +import { SurfaceIndex, type FeaSurfaceData } from './surface'; +import { type FeaMeshInfo, type FeaSolution, meshView, solutionOf } from './results'; + +declare const self: DedicatedWorkerGlobalScope; + +export type FeaWorkerRequest = + | { id: number; type: 'mesh'; surface: FeaSurfaceData; size: number } + | { id: number; type: 'solve'; input: StaticInput }; + +export type FeaWorkerResponse = + | { id: number; type: 'progress'; stage: string; value: number } + | { id: number; type: 'done'; result: unknown } + | { id: number; type: 'error'; error: string; user: boolean }; + +let mesh: TetMesh | null = null; +let viewMap: Int32Array | null = null; + +self.onmessage = (ev: MessageEvent) => { + const msg = ev.data; + const progress = (stage: string, value: number) => self.postMessage({ id: msg.id, type: 'progress', stage, value } satisfies FeaWorkerResponse); + try { + if (msg.type === 'mesh') { + mesh = null; + const surf = new SurfaceIndex(msg.surface); + mesh = meshSolid(surf, { size: msg.size, progress }); + const v = meshView(mesh); + viewMap = v.map; + const info: FeaMeshInfo = v.info; + self.postMessage({ id: msg.id, type: 'done', result: info } satisfies FeaWorkerResponse, [info.nodes.buffer, info.tris.buffer, info.triFace.buffer, info.lines.buffer] as ArrayBuffer[]); + return; + } + if (!mesh || !viewMap) throw new StudyError('Mesh the part first.'); + const res = solveStatic(mesh, msg.input, progress); + const sol: FeaSolution = solutionOf(mesh, viewMap, res, msg.input); + self.postMessage({ id: msg.id, type: 'done', result: sol } satisfies FeaWorkerResponse, sol.fields.map((f) => f.buffer) as ArrayBuffer[]); + } catch (e) { + const user = e instanceof StudyError || e instanceof MeshError; + self.postMessage({ id: msg.id, type: 'error', error: (e as Error).message ?? String(e), user } satisfies FeaWorkerResponse); + } +}; diff --git a/src/parametric/src/main.ts b/src/parametric/src/main.ts index ca0356de13..779148d57d 100644 --- a/src/parametric/src/main.ts +++ b/src/parametric/src/main.ts @@ -3,6 +3,7 @@ import { App } from './app/app'; import { makeHooks, registerCommands } from './app/actions'; import { installAssembly } from './app/assembly'; import { installCam } from './app/cam'; +import { installFea } from './app/fea'; import { FileOps } from './app/fileops'; import { StartScreen, bindAccountMenu, bindUserMenu, refreshAccount } from './app/start'; import { TaskPane, recentItems } from './app/taskpane'; @@ -34,6 +35,7 @@ async function boot() { const hooks = makeHooks(app); installAssembly(app, files, hooks); installCam(app, hooks); + installFea(app, hooks); let start: StartScreen | null = null; hooks.recent = () => recentItems(app, files); hooks.gettingStarted = () => app.openTaskPane('help'); diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 0f324e1811..154b3ccfa8 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -741,3 +741,26 @@ a.icon-btn { text-decoration: none; } .cam-tools, .cam-post { grid-template-columns: minmax(0, 1fr); } .cam-gcode { height: 220px; } } + +/* Stress analysis: result legend, probe pins, panels. */ +.fea-legend { position: absolute; right: 14px; top: 64px; z-index: 2; padding: 8px 10px; background: color-mix(in srgb, var(--panel) 88%, transparent); border: 1px solid var(--border); border-radius: var(--radius); font-size: var(--fs-sm); color: var(--text); pointer-events: none; max-width: 220px; } +.fea-legend-title { font-weight: 600; margin-bottom: 6px; } +.fea-legend-scale { display: flex; gap: 8px; height: 180px; } +.fea-legend-bar { width: 16px; border-radius: 3px; border: 1px solid var(--border-strong); } +.fea-legend-ticks { display: flex; flex-direction: column; justify-content: space-between; font-variant-numeric: tabular-nums; } +.fea-legend-note { margin-top: 6px; color: var(--text-2); } +.fea-pins { position: absolute; inset: 0; pointer-events: none; z-index: 2; overflow: hidden; } +.fea-pin { position: absolute; width: 0; height: 0; } +.fea-pin::before { content: ''; position: absolute; left: -4px; top: -4px; width: 8px; height: 8px; border-radius: 50%; background: var(--text); border: 2px solid var(--panel); } +.fea-pin span { position: absolute; left: 8px; top: -22px; white-space: nowrap; padding: 2px 6px; border-radius: 4px; background: var(--panel); border: 1px solid var(--border-strong); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; } +.fea-probes { display: flex; flex-direction: column; gap: 4px; margin-top: 6px; } +.fea-probe { display: grid; grid-template-columns: 18px auto 1fr; gap: 6px; align-items: baseline; font-variant-numeric: tabular-nums; } +.fea-slider-row { align-items: center; gap: 8px; } +.fea-slider { flex: 1; min-width: 0; } +.fea-stats td.num, .fea-summary td.num, .fea-forces td.num, .fea-solve td.num { text-align: right; font-variant-numeric: tabular-nums; } +.fea-summary th, .fea-forces th, .fea-solve th, .fea-stats th { font-weight: 500; } +.fea-material-props { margin-top: 6px; } +@media (max-width: 760px) { + .fea-legend { top: auto; bottom: 12px; right: 8px; max-width: 170px; } + .fea-legend-scale { height: 120px; } +} From 050b9937c8792579d5a67d1116d481135e49880c Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:18:07 -0700 Subject: [PATCH 012/116] Parametric: fixed hinge studies: loads that do no work on a free turn are solved with weak springs, others reported as unstable --- src/parametric/src/app/fea/panels.ts | 1 + src/parametric/src/app/fea/report.ts | 1 + src/parametric/src/fea/results.ts | 7 +-- src/parametric/src/fea/static.ts | 78 ++++++++++++++++++++++--- src/parametric/tests/fea-solver.test.ts | 38 ++++++++++++ 5 files changed, 113 insertions(+), 12 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 77dbcdd0b3..12ee2a3147 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -343,6 +343,7 @@ export class ResultsPanel extends FeaPanel { return [section('Results', [...msgs, h('p', { class: 'field-label' }, 'Run the study to see its results.'), h('button', { class: 'btn small primary', type: 'button', onclick: () => void ws.run() }, icon('feaRun', 16), 'Run')], { icon: 'feaResults' })]; } const s = res.sol.summary; + for (const w of s.warnings ?? []) msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, w)); if (ws.state() === 'stale') msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'Out of date: the part, the study or the material changed since it was run.'), h('button', { class: 'btn small', type: 'button', onclick: () => void ws.run() }, icon('feaRun', 16), 'Run Again')); if (s.maxVonMises.value > res.yield) msgs.push(h('p', { class: 'pm-msg error', role: 'alert' }, `The highest von Mises stress (${formatValue(app, s.maxVonMises.value, 'stress')}) is above the yield strength of ${res.material} (${formatValue(app, res.yield, 'stress')}): the part would yield there, and a linear analysis no longer describes it.`)); const b = app.bbox; diff --git a/src/parametric/src/app/fea/report.ts b/src/parametric/src/app/fea/report.ts index d06c7ff0b9..ff78e1a77d 100644 --- a/src/parametric/src/app/fea/report.ts +++ b/src/parametric/src/app/fea/report.ts @@ -39,6 +39,7 @@ export function summaryRows(app: App, ws: FeaWorkspace, r: FeaResult): Line[] { add('Results', 'Max principal stress', S(s.maxP1.value), u.stress); add('Results', 'Min principal stress', S(s.minP3.value), u.stress); add('Results', 'Max equivalent strain', s.maxStrain.value); + for (const w of s.warnings ?? []) add('Results', 'Note', w); add('Results', 'Yielding', s.maxVonMises.value > r.yield ? 'yes: stress above yield, the linear analysis no longer holds there' : 'no'); r.loadNames.forEach((n, i) => { const ld = r.input.loads[i]; diff --git a/src/parametric/src/fea/results.ts b/src/parametric/src/fea/results.ts index 6570b550fb..c2e3f1b80b 100644 --- a/src/parametric/src/fea/results.ts +++ b/src/parametric/src/fea/results.ts @@ -39,8 +39,9 @@ export interface FeaSummary { residual: number; solver: string; ms: StaticResult['ms']; - /** Weight of the part (N) when gravity is applied, else 0. */ + /** Mass of the part (kg) when gravity is applied, else 0. */ mass: number; + warnings: string[]; } export interface FeaSolution { @@ -95,14 +96,12 @@ export function solutionOf(mesh: TetMesh, map: Int32Array, r: StaticResult, inpu for (let v = 0; v < N; v++) disp[v] = Math.hypot(r.U[v * 3], r.U[v * 3 + 1], r.U[v * 3 + 2]); const gravity = input.loads.find((l) => l.kind === 'gravity'); const g = gravity && gravity.kind === 'gravity' ? Math.hypot(...gravity.accel) : 0; - let volume = 0; - void volume; return { fields: [U, pick(r.vonMises), pick(r.p1), pick(r.p2), pick(r.p3), pick(r.strain)], summary: { maxVonMises: extreme(mesh, r.vonMises), maxDisplacement: extreme(mesh, disp), maxP1: extreme(mesh, r.p1), minP3: extreme(mesh, r.p3, -1), maxStrain: extreme(mesh, r.strain), reactions: r.reactions, applied: r.applied, loadAreas: r.loadAreas, dofs: r.dofs, iterations: r.iterations, residual: r.residual, solver: r.solver, ms: r.ms, - mass: g > 0 ? mesh.stats.volume * input.density * 1000 : 0, + mass: g > 0 ? mesh.stats.volume * input.density * 1000 : 0, warnings: r.warnings, }, }; } diff --git a/src/parametric/src/fea/static.ts b/src/parametric/src/fea/static.ts index 7b94e1eae4..653331b4da 100644 --- a/src/parametric/src/fea/static.ts +++ b/src/parametric/src/fea/static.ts @@ -53,6 +53,8 @@ export interface StaticResult { /** Area each load acts on, as meshed (mm^2): 0 for gravity. */ loadAreas: number[]; dofs: number; + /** Things the user should know about the solution (a free motion held by weak springs). */ + warnings: string[]; iterations: number; residual: number; solver: string; @@ -69,6 +71,20 @@ const AXES = ['X', 'Y', 'Z']; * not stop are described ('free to move along X', 'free to turn about ...'). */ export function rigidMotions(mesh: TetMesh, constrained: Map): string[] { + return freeMotions(mesh, constrained).map((m) => m.text); +} + +/** A rigid motion the fixtures allow: u = t + w x (x - c) / L on the nodes of one piece. */ +export interface FreeMotion { + text: string; + v: number[]; + c: Vec3; + L: number; + /** Whether a node belongs to the piece. */ + has: (node: number) => boolean; +} + +export function freeMotions(mesh: TetMesh, constrained: Map): FreeMotion[] { const X = mesh.nodes, nn = mesh.nodes.length / 3; // Pieces of the mesh (connected through elements). const parent = new Int32Array(nn).map((_, i) => i); @@ -105,11 +121,12 @@ export function rigidMotions(mesh: TetMesh, constrained: Map): s for (let i = 0; i < 6; i++) for (let j = 0; j < 6; j++) p.M[i * 6 + j] += row[i] * row[j]; } } - const free: string[] = []; + const free: FreeMotion[] = []; const several = pieces.size > 1; let k = 0; - for (const p of pieces.values()) { + for (const [root, p] of pieces) { k++; + const motion = (text: string, v: number[]): FreeMotion => ({ text, v, c: p.c, L, has: (node) => find(node) === root }); const { values, vectors } = jacobiEigen(p.M, 6); const top = Math.max(...values, 0); // The free motions: eigenvectors of (nearly) zero eigenvalues. @@ -135,12 +152,12 @@ export function rigidMotions(mesh: TetMesh, constrained: Map): s gv.forEach((lam, i) => { if (lam > 1e-9 * gmax && gmax > 0) { let d = 0; for (let q = 0; q < m; q++) d += gV[i * m + q] * g[q]; ratio += (d * d) / lam; } }); if (ratio > 0.98) named.push(`free to turn about ${AXES[a]}`); } - if (named.length >= nul.length) { for (const n of named) free.push(n + where); continue; } + if (named.length >= nul.length) { named.forEach((n, i) => free.push(motion(n + where, nul[Math.min(i, nul.length - 1)]))); for (let i = named.length; i < nul.length; i++) free.push(motion('', nul[i])); continue; } // Otherwise the eigenvectors as they are. for (const v of nul) { const t = Math.hypot(v[0], v[1], v[2]), w = Math.hypot(v[3], v[4], v[5]); - if (w < 0.05 * t) free.push(`free to move ${describeDir([v[0], v[1], v[2]])}${where}`); - else free.push(`free to turn ${describeDir([v[3] / w, v[4] / w, v[5] / w], 'about')}${where}`); + if (w < 0.05 * t) free.push(motion(`free to move ${describeDir([v[0], v[1], v[2]])}${where}`, v)); + else free.push(motion(`free to turn ${describeDir([v[3] / w, v[4] / w, v[5] / w], 'about')}${where}`, v)); } } return free; @@ -304,9 +321,42 @@ export function solveStatic(mesh: TetMesh, input: StaticInput, progress: (stage: if (!input.fixtures.length) throw new StudyError('The study has no fixtures: the part is free to move. Add a fixture to hold it.'); if (!input.loads.length) throw new StudyError('The study has no loads. Add a force, pressure or gravity.'); const constrained = constraintsOf(mesh, input.fixtures); - const free = rigidMotions(mesh, constrained); - if (free.length) throw new StudyError(`The fixtures do not hold the part: it is ${free.join(', ')}. Add fixtures (or change them) so that it cannot move or turn as a rigid body.`); + const free = freeMotions(mesh, constrained); const { F, applied, areas } = loadVector(mesh, input); + const warnings: string[] = []; + // A free rigid motion is acceptable only if the loads do no work on it (a pinned link pulled along its + // length): it is then held by springs too weak to change the result. Otherwise the part would accelerate. + const texts = () => [...new Set(free.map((m) => m.text).filter(Boolean))].join(', '); + if (free.length) { + const modeAt = (m: FreeMotion, v: number) => { + const r = [(X[v * 3] - m.c[0]) / m.L, (X[v * 3 + 1] - m.c[1]) / m.L, (X[v * 3 + 2] - m.c[2]) / m.L]; + return [m.v[0] + m.v[4] * r[2] - m.v[5] * r[1], m.v[1] + m.v[5] * r[0] - m.v[3] * r[2], m.v[2] + m.v[3] * r[1] - m.v[4] * r[0]]; + }; + // The loads' work on the motion against what they could do at most (all of them along it where they act). + const unbalanced = free.some((m) => { + let work = 0, most = 0; + for (let v = 0; v < N; v++) { + if (!m.has(v)) continue; + const f = Math.hypot(F[v * 3], F[v * 3 + 1], F[v * 3 + 2]); + if (!f) continue; + const u = modeAt(m, v); + work += F[v * 3] * u[0] + F[v * 3 + 1] * u[1] + F[v * 3 + 2] * u[2]; + most += f * Math.hypot(u[0], u[1], u[2]); + } + return Math.abs(work) > 1e-3 * most; + }); + if (unbalanced) throw new StudyError(`The fixtures do not hold the part against its loads: it is ${texts()}, and the loads would move it that way (an unstable study). Add fixtures (or change them) so that it cannot move or turn as a rigid body.`); + // What is left of that work comes from the mesh not being exactly symmetric: take it out of the loads. + for (let pass = 0; pass < 2; pass++) for (const m of free) { + let fu = 0, uu = 0; + for (let v = 0; v < N; v++) { if (!m.has(v)) continue; const u = modeAt(m, v); fu += F[v * 3] * u[0] + F[v * 3 + 1] * u[1] + F[v * 3 + 2] * u[2]; uu += u[0] ** 2 + u[1] ** 2 + u[2] ** 2; } + if (!(uu > 0)) continue; + for (let v = 0; v < N; v++) { if (!m.has(v)) continue; const u = modeAt(m, v); for (let c = 0; c < 3; c++) F[v * 3 + c] -= (fu / uu) * u[c]; } + } + applied[0] = applied[1] = applied[2] = 0; + for (let v = 0; v < N; v++) for (let c = 0; c < 3; c++) applied[c] += F[v * 3 + c]; + warnings.push(`The fixtures leave the part ${texts()}; the loads do not push it that way, so it was solved with weak springs holding that motion. Check that this is intended.`); + } // ---- assembly ---- progress('Assembling', 0); @@ -356,6 +406,18 @@ export function solveStatic(mesh: TetMesh, input: StaticInput, progress: (stage: } } const diagScale = (() => { let s = 0; for (let i = 0; i < N; i++) { const q = blockAt(A, i, i) * 9; s = Math.max(s, A.val[q], A.val[q + 4], A.val[q + 8]); } return s; })(); + if (free.length) { + // Weak springs hold the free motions: on the free directions of the held nodes (they hardly move there), + // or on every node of a piece nothing holds. + const held = (m: FreeMotion) => { for (const v of constrained.keys()) if (m.has(v)) return true; return false; }; + const onHeld = free.every(held); + const ks = diagScale * (onHeld ? 1e-6 : 1e-10); + for (let i = 0; i < N; i++) { + if (onHeld ? !k[i] : false) continue; + const q = blockAt(A, i, i) * 9; + for (let r = k[i]; r < 3; r++) A.val[q + r * 4] += ks; + } + } for (let i = 0; i < N; i++) { if (!k[i]) continue; const q = blockAt(A, i, i) * 9; @@ -432,7 +494,7 @@ export function solveStatic(mesh: TetMesh, input: StaticInput, progress: (stage: } const tEnd = performance.now(); return { - U, vonMises, p1, p2, p3, strain, stress: S, reactions, applied, loadAreas: areas, dofs: N * 3, + U, vonMises, p1, p2, p3, strain, stress: S, reactions, applied, loadAreas: areas, dofs: N * 3, warnings, iterations: res.iterations, residual: res.residual, solver: M.description, ms: { assemble: tAsm - t0, setup: tSetup - tAsm, solve: tSolve - tSetup, stress: tEnd - tSolve }, }; diff --git a/src/parametric/tests/fea-solver.test.ts b/src/parametric/tests/fea-solver.test.ts index 7e07ebbdc2..b1c72935c1 100644 --- a/src/parametric/tests/fea-solver.test.ts +++ b/src/parametric/tests/fea-solver.test.ts @@ -132,3 +132,41 @@ describe('static analysis accuracy', () => { expect(err!.message).toMatch(/free to turn about X/); }, 120000); }); + +describe('fixed hinge', () => { + // A link 100 x 20 x 5 with two 8 mm holes 80 apart, pinned (fixed hinge) at the first. + const link = () => meshOf([sketch('s1', [...rect(0, 0, 100, 20), ...circle(10, 10, 4), ...circle(90, 10, 4)]), extrude('f1', 's1', 5)], 1.5); + const holes = (faces: FaceInfo[], x: number) => faces.flatMap((f, i) => (f.type === 'cylinder' && Math.abs(f.center[0] - x) < 1e-6 ? [i] : [])); + + it('carries a pull along the link: reactions balance the load, the free turn about the pin is reported', async () => { + const { mesh, faces } = await link(); + const pin = holes(faces, 10), end = holes(faces, 90); + expect(pin.length).toBeGreaterThan(0); + const cyl = faces[pin[0]]; + const F = 2000; + const r = solveStatic(mesh, { ...STEEL, fixtures: [{ kind: 'hinge', faces: pin, axis: cyl.axis! }], loads: [{ kind: 'force', faces: end, total: F, dir: [1, 0, 0] }] }); + expect(r.reactions[0][0]).toBeCloseTo(-F, 2); + expect(Math.abs(r.reactions[0][1])).toBeLessThan(1e-3 * F); + expect(Math.hypot(r.reactions[0][0] + r.applied[0], r.reactions[0][1] + r.applied[1], r.reactions[0][2] + r.applied[2])).toBeLessThan(1e-5 * F); + expect(r.warnings.join(' ')).toMatch(/free to turn about Z/); + // The link stretches: the far hole moves along +X, the sides of the link between the holes carry about F / (2 x 6 x 5) near the holes' middle. + const ux = at(mesh.nodes, r.U, [90, 2, 2.5], 3, 0); + expect(ux).toBeGreaterThan(0); + const sx = at(mesh.nodes, r.stress, [50, 10, 2.5], 6, 0); + expect(sx / (F / (20 * 5))).toBeCloseTo(1, 1); + }, 120000); + + it('reports a load across the link as unstable (it would turn about the pin)', async () => { + const { mesh, faces } = await link(); + const pin = holes(faces, 10), end = holes(faces, 90); + const err = (() => { try { solveStatic(mesh, { ...STEEL, fixtures: [{ kind: 'hinge', faces: pin, axis: faces[pin[0]].axis! }], loads: [{ kind: 'force', faces: end, total: 100, dir: [0, 1, 0] }] }); } catch (e) { return e as Error; } return null; })(); + expect(err).toBeInstanceOf(StudyError); + expect(err!.message).toMatch(/unstable/); + expect(err!.message).toMatch(/free to turn about Z/); + // A second pin at the other hole holds it: the load goes into the pins. + const r = solveStatic(mesh, { ...STEEL, fixtures: [{ kind: 'hinge', faces: pin, axis: faces[pin[0]].axis! }, { kind: 'hinge', faces: end, axis: faces[end[0]].axis! }], loads: [{ kind: 'force', faces: [faces.findIndex((f) => f.type === 'plane' && f.normal?.[1] === 1)], total: 100, dir: [0, -1, 0] }] }); + expect(r.warnings).toEqual([]); + const total = r.reactions.reduce((a, x) => a + x[1], 0); + expect(total).toBeCloseTo(100, 4); + }, 120000); +}); From 57e095556e9badce5dd47b7602d8eae27259de37 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:20:24 -0700 Subject: [PATCH 013/116] Parametric: tests for the study file format, materials, results export and the Analysis tab in the browser --- src/parametric/tests/e2e/analysis.spec.ts | 139 ++++++++++++++++++++++ src/parametric/tests/fea-model.test.ts | 134 +++++++++++++++++++++ 2 files changed, 273 insertions(+) create mode 100644 src/parametric/tests/e2e/analysis.spec.ts create mode 100644 src/parametric/tests/fea-model.test.ts diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts new file mode 100644 index 0000000000..cd0c07ec6c --- /dev/null +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -0,0 +1,139 @@ +import { type Page, expect, test } from '@playwright/test'; +import { openApp } from './helpers'; + +type W = { __parametric: import('../../src/app/app').App }; + +/** Where the centre of a face (by name) is on the page, once the camera stopped moving. */ +async function facePoint(page: Page, name: string): Promise<{ x: number; y: number }> { + return page.evaluate(async (name) => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const f = a.faces.find((x) => x.name === name)!; + const at = () => { + const [x, y] = a.viewport.project(f.center); + const r = a.viewport.canvas.getBoundingClientRect(); + return { x: r.x + x, y: r.y + y }; + }; + let last = at(); + for (let i = 0; i < 40; i++) { + await new Promise((r) => setTimeout(r, 50)); + const n = at(); + if (Math.abs(n.x - last.x) + Math.abs(n.y - last.y) < 0.5) break; + last = n; + } + return last; + }, name); +} + +test('sets up a static study, runs it, reads the plot and saves it with the part', async ({ page }) => { + test.setTimeout(240_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.getByRole('tab', { name: 'Analysis' }).click(); + + // Material: the preset's elastic properties are shown; Alloy Steel is chosen. + await page.locator('.cm-tools [data-cmd="material"]').click(); + const mat = page.getByRole('dialog', { name: 'Material' }); + await expect(mat.locator('.fea-material-props')).toContainText('Elastic modulus 68.9 GPa'); + await mat.getByLabel('Material', { exact: true }).selectOption({ label: 'Alloy Steel (7700 kg/m³)' }); + await expect(mat.locator('.fea-material-props')).toContainText('yield strength 415 MPa'); + await mat.getByRole('button', { name: 'Apply' }).click(); + + // A fixed face, picked in the graphics area. + await page.locator('[data-cmd="fea:fixed"]').click(); + await expect(page.locator('.pm-head').getByText('Fixed', { exact: true })).toBeVisible(); + let p = await facePoint(page, 'f1:side:bl1'); + await page.mouse.click(p.x, p.y); + await expect(page.getByRole('group', { name: 'Faces' })).toContainText('Face'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.getByRole('treeitem', { name: /^Fixed-1/ })).toBeVisible(); + + // A 500 N force pressing on the top of the upright. + await page.locator('[data-cmd="fea:force"]').click(); + p = await facePoint(page, 'f1:side:bl4'); + await page.mouse.click(p.x, p.y); + await page.getByLabel('Total force (N)').fill('500'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads[0])).toMatchObject({ type: 'force', value: 500, dir: null, faces: [{ name: 'f1:side:bl4' }] }); + + // Run: the plot, its legend and the summary. + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('.fea-legend')).toContainText('von Mises stress (MPa)'); + await expect(page.locator('.fea-legend')).toContainText('Yield strength: 415 MPa'); + const summary = page.locator('.fea-summary'); + await expect(summary).toContainText('Max von Mises stress'); + await expect(summary).toContainText('Min factor of safety'); + // Equilibrium: the reaction carries the 500 N. + await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); + + // Displacement plot, then a probe on the top of the base. + await page.getByLabel('Plot', { exact: true }).selectOption('disp'); + await expect(page.locator('.fea-legend')).toContainText('Displacement (mm)'); + await page.getByLabel('Plot', { exact: true }).selectOption('vonMises'); + await page.getByRole('button', { name: 'Probe' }).click(); + p = await facePoint(page, 'f1:side:bl2'); + await page.mouse.click(p.x + 30, p.y); + await expect(page.locator('.fea-probe')).toHaveCount(1); + await expect(page.locator('.fea-probe')).toContainText('MPa'); + await expect(page.locator('.fea-pin')).toHaveCount(1); + + // Editing the study puts the results out of date. + await page.getByRole('button', { name: 'Close', exact: true }).click(); + await expect(page.locator('.fea-legend')).toHaveCount(0); + await expect(page.getByRole('treeitem', { name: /^Results/ })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: /^Results/ })).not.toHaveAttribute('aria-description', /Out of date/); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Edit', (d) => { d.study!.loads[0].value = 600; })); + await expect(page.getByRole('treeitem', { name: /^Results/ })).toHaveAttribute('aria-description', /Out of date/); + + // Saved with the part, and read back. + await page.evaluate(() => (window as unknown as W).__parametric.commands.run('save')); + const saveAs = page.getByRole('dialog', { name: 'Save As' }); + if (await saveAs.isVisible().catch(() => false)) await saveAs.getByRole('button', { name: 'Save' }).click(); + await expect(page).toHaveTitle(/Mounting Bracket - Parametric/); + const saved = await page.evaluate(async (url) => { + const { loadText } = await import(url); + const a = (window as unknown as W).__parametric; + return JSON.parse(await loadText(a.location!)); + }, '/src/platform/files.ts'); + expect(saved.study.fixtures).toHaveLength(1); + expect(saved.study.loads[0]).toMatchObject({ type: 'force', value: 600 }); + expect(saved.material).toMatchObject({ name: 'Alloy Steel', E: 205000 }); + await page.evaluate(async (text) => { + const a = (window as unknown as W).__parametric; + const { parseDocument } = await import('/src/model/document.ts'); + a.loadDocument(parseDocument(text), null); + }, JSON.stringify(saved)); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('.fea-forces')).toContainText('0.000, 600.000, 0.000 N'); + expect(errors).toEqual([]); +}); + +test('explains a study that cannot run', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.getByRole('tab', { name: 'Analysis' }).click(); + // No fixtures: the results panel says what is missing. + await page.locator('[data-cmd="fea:force"]').click(); + const p = await facePoint(page, 'f1:side:bl4'); + await page.mouse.click(p.x, p.y); + await page.locator('.confirm-corner .ok').click(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.getByRole('alert').filter({ hasText: 'Add a fixture' })).toBeVisible(); + // A roller alone leaves the part free to slide: unstable. + await page.getByRole('button', { name: 'Close', exact: true }).click(); + await page.locator('[data-cmd="fea:roller"]').click(); + const q = await facePoint(page, 'f1:side:bl1'); + await page.mouse.click(q.x, q.y); + await page.locator('.confirm-corner .ok').click(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.getByRole('alert').filter({ hasText: /unstable/ })).toBeVisible({ timeout: 60_000 }); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/fea-model.test.ts b/src/parametric/tests/fea-model.test.ts new file mode 100644 index 0000000000..2a124732ce --- /dev/null +++ b/src/parametric/tests/fea-model.test.ts @@ -0,0 +1,134 @@ +// The study saved with the part, materials' elastic properties, and the +// results summary export: round trips, old files, refused damage. +import { describe, expect, it } from 'vitest'; +import { newDocument, parseDocument, serializeDocument } from '../src/model/document'; +import { type StaticStudy, elementSizeFor, feaUnits, newStudy, parseStudy, studyIds } from '../src/model/fea'; +import { MATERIALS, elasticOf, normalizeMaterial, validElastic } from '../src/model/materials'; +import { colorAt, interpolate } from '../src/fea/results'; +import { principal } from '../src/fea/elements'; +import { summaryCsv } from '../src/app/fea/report'; + +const face = (name: string) => ({ name, sig: { type: 'plane', c: [1, 2, 3] as [number, number, number], n: [0, 0, 1] as [number, number, number], area: 12 } }); + +function study(): StaticStudy { + const s = newStudy('st3'); + s.fixtures.push({ id: 'fx4', name: 'Fixed-1', type: 'fixed', faces: [face('f1:cap0')] }); + s.fixtures.push({ id: 'fx5', name: 'Hinge-1', type: 'hinge', faces: [{ name: 'f2:h1:1', sig: { type: 'cylinder', c: [0, 0, 0], area: 50 } }], suppressed: true }); + s.loads.push({ id: 'ld6', name: 'Force-1', type: 'force', faces: [face('f1:cap1')], value: 250, dir: { kind: 'edge', edge: { name: 'e1', sig: { type: 'line', m: [0, 0, 0], len: 10 } } }, flip: true }); + s.loads.push({ id: 'ld7', name: 'Pressure-1', type: 'pressure', faces: [face('f1:side:bl2')], value: 2, flip: false }); + s.loads.push({ id: 'ld8', name: 'Gravity-1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); + s.mesh.fineness = 0.75; + return s; +} + +describe('static study in the part file', () => { + it('saves and reads a study unchanged, and new ids never collide with its ids', () => { + const doc = newDocument(); + doc.study = study(); + const back = parseDocument(serializeDocument(doc)); + expect(back.study).toEqual(doc.study); + expect(back.nextId).toBeGreaterThan(8); + expect(studyIds(back.study)).toEqual(['st3', 'fx4', 'fx5', 'ld6', 'ld7', 'ld8']); + }); + + it('opens parts without a study, and with a null one', () => { + expect(parseDocument(serializeDocument(newDocument())).study).toBeUndefined(); + expect(parseDocument(JSON.stringify({ ...newDocument(), study: null })).study).toBeNull(); + }); + + it('refuses a damaged study with a message', () => { + const bad: [string, (s: Record) => void][] = [ + ['no fixture list', (s) => { delete s.fixtures; }], + ['unknown fixture type', (s) => { (s.fixtures as Record[])[0].type = 'glued'; }], + ['face without signature', (s) => { (s.fixtures as { faces: unknown[] }[])[0].faces = [{ name: 'x' }]; }], + ['duplicate ids', (s) => { (s.loads as Record[])[0].id = 'fx4'; }], + ['value not a number', (s) => { (s.loads as Record[])[1].value = '2 MPa'; }], + ['unknown load type', (s) => { (s.loads as Record[])[1].type = 'torque'; }], + ['gravity without a direction', (s) => { delete (s.loads as Record[])[2].dir; }], + ['bad direction', (s) => { (s.loads as Record[])[0].dir = { kind: 'base', axis: 'w' }; }], + ['fineness out of range', (s) => { s.mesh = { fineness: 3 }; }], + ['not an object', (s) => { for (const k of Object.keys(s)) delete s[k]; }], + ]; + for (const [what, damage] of bad) { + const raw = JSON.parse(JSON.stringify(study())) as Record; + damage(raw); + expect(() => parseStudy(raw), what).toThrow(/invalid study/); + expect(() => parseDocument(JSON.stringify({ ...newDocument(), study: raw })), what).toThrow(/damaged \(invalid study/); + } + }); + + it('drops unknown keys and keeps only what a study holds', () => { + const raw = { ...study(), extra: 1 } as Record; + (raw.fixtures as Record[])[0].colour = 'red'; + const s = parseStudy(raw); + expect('extra' in s).toBe(false); + expect('colour' in s.fixtures[0]).toBe(false); + }); + + it('sizes elements from the automatic size, never beyond the walls', () => { + expect(elementSizeFor(4, 100, 0.5)).toBeCloseTo(4); + expect(elementSizeFor(4, 100, 1)).toBeCloseTo(2); + expect(elementSizeFor(4, 100, 0)).toBeCloseTo(8); + expect(elementSizeFor(4, 6, 0)).toBeCloseTo(6); + }); + + it('shows forces and stresses in the part\'s units', () => { + expect(feaUnits('MMGS')).toMatchObject({ force: 'N', stress: 'MPa', length: 'mm' }); + expect(feaUnits('IPS')).toMatchObject({ force: 'lbf', stress: 'psi', length: 'in' }); + expect(1 / feaUnits('IPS').stressScale).toBeCloseTo(145.04, 1); + }); +}); + +describe('materials for analysis', () => { + it('has elastic properties for every preset but wood', () => { + for (const m of MATERIALS) expect(!!elasticOf(m), m.name).toBe(!/Oak|Pine/.test(m.name)); + const steel = elasticOf(MATERIALS[0])!; + expect(steel.E).toBeGreaterThan(190000); + expect(steel.yield).toBeLessThan(steel.uts); + }); + + it('finds the properties of a preset saved before materials had them', () => { + expect(elasticOf({ name: 'Aluminum 6061', density: 2700 })?.E).toBe(68900); + expect(elasticOf({ name: 'Aluminum 6061', density: 2600 })).toBeNull(); + expect(elasticOf({ name: 'Custom', density: 1000 })).toBeNull(); + expect(elasticOf(null)).toBeNull(); + }); + + it('keeps a custom material\'s properties only as a complete, valid set', () => { + const ok = { name: 'Custom', density: 1000, E: 1000, nu: 0.3, yield: 10, uts: 12 }; + expect(normalizeMaterial(ok)).toEqual(ok); + expect(normalizeMaterial({ ...ok, nu: 0.5 })).toEqual({ name: 'Custom', density: 1000 }); + expect(normalizeMaterial({ name: 'Custom', density: 1000, E: 1000 })).toEqual({ name: 'Custom', density: 1000 }); + expect(validElastic({ E: -1, nu: 0.3, yield: 1, uts: 1 })).toBe(false); + const doc = parseDocument(JSON.stringify({ ...newDocument(), material: { ...ok, E: 'stiff' } })); + expect(doc.material).toEqual({ name: 'Custom', density: 1000 }); + expect(parseDocument(JSON.stringify({ ...newDocument(), material: ok })).material).toEqual(ok); + }); +}); + +describe('result helpers', () => { + it('finds principal stresses', () => { + const p = principal(10, 0, 0, 0, 0, 0); + expect(p[0]).toBeCloseTo(10); + const q = principal(0, 0, 0, 5, 0, 0); + expect(q[0]).toBeCloseTo(5); + expect(q[2]).toBeCloseTo(-5); + expect(q[1]).toBeCloseTo(0); + }); + + it('interpolates on six-node triangles and maps colours', () => { + const tris = new Uint32Array([0, 1, 2, 3, 4, 5]); + const v = [0, 1, 0, 0.5, 0.5, 0]; + expect(interpolate(v, tris, 0, 0.5, 0)).toBeCloseTo(0.5); + expect(interpolate(v, tris, 0, 1, 0)).toBeCloseTo(1); + expect(colorAt(0)[2]).toBeGreaterThan(colorAt(0)[0]); + expect(colorAt(1)[0]).toBeGreaterThan(colorAt(1)[2]); + }); + + it('writes the summary as CSV, quoting what needs it', () => { + const csv = summaryCsv([{ section: 'Results', name: 'Max von Mises stress', value: '12.5', unit: 'MPa' }, { section: 'Study', name: 'Part', value: 'Bracket, "A"', unit: '' }]); + expect(csv.split('\n')[0]).toBe('Section,Quantity,Value,Unit'); + expect(csv).toContain('Results,Max von Mises stress,12.5,MPa'); + expect(csv).toContain('Study,Part,"Bracket, ""A""",'); + }); +}); From e7482541bfbf90185b79b0abe7d52fcc1c8ef518 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:20:39 -0700 Subject: [PATCH 014/116] Parametric: README: the Analysis tab, its limits and its modules --- src/parametric/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/parametric/README.md b/src/parametric/README.md index 7521feb18b..63397a970a 100644 --- a/src/parametric/README.md +++ b/src/parametric/README.md @@ -83,6 +83,14 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to - Every toolpath is checked against the part; Simulate cuts the stock operation by operation and plays it back with the tool, coloured by what is finished, what is left and where the part would be cut, and reports rapid moves through the stock and material above the flutes. - Post Process writes G-code for Fanuc, Haas, LinuxCNC, Mach3/Mach4 or Grbl, in millimetres or inches, with arcs (G2/G3, helical) and drilling cycles (G81, G82, G83, G73) where the controller has them; preview it, copy it or download it. +**Analysis (static stress)** +- An Analysis tab sets up a linear static study of the part: the material (presets carry elastic modulus, Poisson's ratio, yield and tensile strength; custom materials take them too), fixtures, loads and the mesh, kept with the part in a Static Study folder of the design tree. Run meshes and solves it in a worker of its own, with progress and Cancel. +- Fixtures on faces: Fixed (no motion), Roller/Slider (no motion normal to the face; also a symmetry plane) and Fixed Hinge (a cylindrical face that may only turn about its axis). +- Loads: a total force on faces, normal to them or along a picked edge, face or axis (reversible); a pressure; gravity from the material's density. Values are in the part's units (N and MPa, or lbf and psi). Fixtures and loads refer to faces by name, so they follow dimension changes; ones whose faces are gone are marked in the tree. +- The mesh: 10-node quadratic tetrahedra whose boundary lies on the part's faces, edges and corners, with a coarse to fine setting (the automatic size follows the part's size and wall thickness) and its size, quality and volume reported. +- Results: von Mises stress, principal stresses, displacement (resultant and X, Y, Z), equivalent strain and factor of safety (yield over von Mises) plotted on the deformed shape (automatic or true scale, or undeformed) with a legend, the mesh on request and a probe that reads values where you click. The summary gives the largest stress and displacement and where, the smallest factor of safety, the reaction of each fixture against the applied loads (an equilibrium check) and the mesh and solver statistics; export it as CSV or a printable report. Stress above yield is flagged, as are fixtures that leave the part free to move (an unstable study is refused and the free motion named). Editing the part, the study or the material marks results out of date. +- Limits: linear static only (small displacements, linear elastic isotropic material: wood, being anisotropic, has no elastic properties), parts only (not assemblies), no contact, no thermal, modal or buckling analysis. The mesh is uniform: walls much thinner than the element size need a finer mesh (the volume check says so), and stresses at sharp inner corners and at the edges of fixed faces grow as the mesh is refined (singularities). + **Working with parts** - Design tree with rollback bar, suppress, rename, hide/show, edit and delete with dependency warnings. - Global variables and equations: type `=Width/2` in any dimension or feature value. @@ -126,6 +134,7 @@ npm run build # type check, license check, production build in dist/ | Interface | `src/app`, `src/ui` | No framework. CommandManager, design tree, PropertyManager panels, sketch editor, dialogs. | | SolidWorks import | `src/formats/sldprt` | Reads the SolidWorks container (2015+ chunk format and the older OLE2), decodes the embedded Parasolid transmit and writes it as exact STEP for the kernel. Runs in the geometry worker. | | CAM | `src/model/cam.ts`, `src/cam`, `src/app/cam` | Toolpaths are generated in a worker of their own from a fine mesh of the part, in the setup's work coordinates. Drop-cutter (`src/cam/dropcutter.ts`) gives the lowest height a flat, ball, bull nose or conical cutter can reach at a point (face, edge and corner contacts, exact where a closed form exists). Where the tool can be at a height is where that is lower: its boundary is traced by marching squares with each crossing refined by bisection on the drop-cutter, and the passes inside it are offsets of a distance transform, cut from the innermost out. Parallel finishing follows drop-cutter heights along lines. The simulation lowers a height map of the stock along every move. Post processors write the moves with arcs fitted to them. | +| Analysis | `src/model/fea.ts`, `src/fea`, `src/app/fea` | Static stress analysis in a worker of its own, loaded on first use. The mesher (`src/fea/mesher.ts`) fills the solid with a body-centred cubic lattice (isosurface stuffing: exact inside tests by ray crossings of the kernel's triangulation, lattice points near the boundary warped onto it, lattice tetrahedra clipped with fixed stencils), moves vertices onto the part's corners and onto the edges between faces (splitting edges where a move would spoil an element), smooths, and adds midside nodes on the curved surface. The solver assembles 10-node tetrahedra into node-block sparse rows, applies fixtures as constraints in each node's own frame, and solves with conjugate gradients preconditioned by smoothed aggregation multigrid (rigid body modes as the near null space; block Gauss-Seidel smoothing). Fixtures are checked against rigid body motions before solving. | | Assistant | `src/assistant` | Tool-calling agent on Puter AI. Tools work on the document through a host interface (the app, or the kernel in Node for tests); each change rebuilds and is checked, failing steps are reverted, and a message's changes are squashed into one undo step. | | Platform | `src/platform` | Puter.js access, files (Puter or browser storage), theme. | From 9b202a5af6b7cdf0f3de17c9a98e0787f4cb8897 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:20:52 -0700 Subject: [PATCH 015/116] Parametric: analysis spec type checks its dynamic import --- src/parametric/tests/e2e/analysis.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index cd0c07ec6c..f34b0cc50c 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -101,11 +101,11 @@ test('sets up a static study, runs it, reads the plot and saves it with the part expect(saved.study.fixtures).toHaveLength(1); expect(saved.study.loads[0]).toMatchObject({ type: 'force', value: 600 }); expect(saved.material).toMatchObject({ name: 'Alloy Steel', E: 205000 }); - await page.evaluate(async (text) => { + await page.evaluate(async ({ text, url }) => { const a = (window as unknown as W).__parametric; - const { parseDocument } = await import('/src/model/document.ts'); + const { parseDocument } = await import(url) as typeof import('../../src/model/document'); a.loadDocument(parseDocument(text), null); - }, JSON.stringify(saved)); + }, { text: JSON.stringify(saved), url: '/src/model/document.ts' }); await page.getByRole('tab', { name: 'Analysis' }).click(); await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); await page.locator('[data-cmd="fea:run"]').click(); From 2f0632e151a8cc2b09cfcec41654ad1342e87e00 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:24:17 -0700 Subject: [PATCH 016/116] Parametric: dialogs spec expects a preset material's elastic properties --- src/parametric/tests/e2e/dialogs.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parametric/tests/e2e/dialogs.spec.ts b/src/parametric/tests/e2e/dialogs.spec.ts index b6cd2e7f65..845f326dbd 100644 --- a/src/parametric/tests/e2e/dialogs.spec.ts +++ b/src/parametric/tests/e2e/dialogs.spec.ts @@ -97,7 +97,7 @@ test('a density error does not prevent selecting a preset material', async ({ pa await dialog.getByRole('button', { name: 'Apply' }).click(); await expect(dialog).toHaveCount(0); expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.material)) - .toEqual({ name: 'Aluminum 6061', density: 2700 }); + .toEqual({ name: 'Aluminum 6061', density: 2700, E: 68900, nu: 0.33, yield: 276, uts: 310 }); expect(errors).toEqual([]); }); From d2ab5c91cf42886281fde1dc5ceaeaf86466bce4 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:25:18 -0700 Subject: [PATCH 017/116] Parametric: slider, cam follower and universal joint mates; motors on hinges and sliders Slider: one straight edge or axis, or two planar faces, on each component; one move along it, no turn, optional travel limits from where it was added. Cam: a follower (vertex, roller or flat face) touching the convex outline of the cam's profile faces (an exact circle for an eccentric, exact arcs and corners otherwise); a profile with a hollow is refused with its depth. Universal joint: the cross piece holds the two yokes square, so the output turns by atan(tan phi / cos beta), with an optional joint point. Rotary motors can go on a hinge and linear motors on a slider. --- src/parametric/src/app/assembly/index.ts | 8 +- src/parametric/src/app/assembly/mode.ts | 109 +++++++- .../src/app/assembly/motion-panel.ts | 18 +- src/parametric/src/app/assembly/panels.ts | 79 +++++- src/parametric/src/assembly/motion.ts | 32 ++- src/parametric/src/assembly/solver.ts | 263 +++++++++++++++++- src/parametric/src/model/assembly.ts | 71 +++-- .../tests/assembly-kinematics.test.ts | 167 ++++++++++- src/parametric/tests/assembly-model.test.ts | 35 +++ .../tests/e2e/assembly-kinematics.spec.ts | 152 ++++++++++ 10 files changed, 877 insertions(+), 57 deletions(-) diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts index cbcf4797ab..31b96e69a2 100644 --- a/src/parametric/src/app/assembly/index.ts +++ b/src/parametric/src/app/assembly/index.ts @@ -44,6 +44,9 @@ addIcons({ 'mate:screw': Bolt as unknown as IconNode, 'mate:width': [['path', { d: 'M4 4v16M20 4v16' }], ['rect', { x: 9, y: 7, width: 6, height: 10, rx: 0.5, class: 'a' }], ['path', { d: 'M5.5 12h2M16.5 12h2' }]], 'mate:slot': [['path', { d: 'M7 8h10a4 4 0 0 1 0 8H7a4 4 0 0 1 0-8z' }], ['circle', { cx: 9, cy: 12, r: 2, class: 'a' }]], + 'mate:slider': [['path', { d: 'M3 16h18' }], ['rect', { x: 8, y: 7, width: 8, height: 7, rx: 0.5, class: 'a' }], ['path', { d: 'M4 11l-2 2 2 2M20 11l2 2-2 2' }]], + 'mate:cam': [['path', { d: 'M12 20c-5 0-7-3-7-6 0-4 3-11 7-11s7 7 7 11c0 3-2 6-7 6z', class: 'a' }], ['circle', { cx: 12, cy: 14, r: 1.5 }]], + 'mate:universal': [['path', { d: 'M3 18l6-6M21 18l-6-6' }], ['circle', { cx: 12, cy: 10, r: 3.5, class: 'a' }], ['path', { d: 'M12 6.5v7M8.5 10h7' }]], motionStudy: Clapperboard as unknown as IconNode, play: [['path', { d: 'M7 4l13 8-13 8z', class: 'a' }]], pause: [['path', { d: 'M7 4h3v16H7zM14 4h3v16h-3z', class: 'a' }]], @@ -122,7 +125,7 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { }, }, { - id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly limit hinge gear rack pinion screw width slot mechanical', description: 'Position components relative to each other with mates.', + id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly limit hinge slider prismatic gear rack pinion screw width slot cam follower universal joint mechanical', description: 'Position components relative to each other with mates.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MatePanel(mode()!)), }, @@ -295,11 +298,12 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { const ids = app.tree.targets(mate.id).filter((x) => d.mates.some((y) => y.id === x)); // Gears and racks turn the other way round; mates of directions flip their alignment. const reverses = mate.type === 'gear' || mate.type === 'rackPinion'; - const aligns = !['perpendicular', 'lock', 'tangent', 'width', 'slot'].includes(mate.type) && !reverses; + const aligns = !['perpendicular', 'lock', 'tangent', 'width', 'slot', 'cam', 'universal'].includes(mate.type) && !reverses; return [ { label: 'Edit Mate', icon: 'edit', run: () => m.edit(mate.id) }, { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(mate.id) }, ...(aligns ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.commit('Flip alignment', (x) => { for (const y of x.mates) if (y.id === mate.id) y.aligned = !y.aligned; }) } as MenuItem] : []), + ...(mate.type === 'cam' ? [{ label: 'Flip Follower Face', icon: 'reset', run: () => m.commit('Flip follower', (x) => { for (const y of x.mates) if (y.id === mate.id) y.flip = y.flip ? undefined : true; }) } as MenuItem] : []), ...(reverses ? [{ label: 'Reverse Direction', icon: 'reset', run: () => m.commit('Reverse direction', (x) => { for (const y of x.mates) if (y.id === mate.id) y.reverse = y.reverse ? undefined : true; }) } as MenuItem] : []), { label: mate.suppressed ? 'Unsuppress' : 'Suppress', icon: mate.suppressed ? 'eye' : 'eyeOff', run: () => m.commit(mate.suppressed ? 'Unsuppress' : 'Suppress', (x) => { for (const y of x.mates) if (ids.includes(y.id)) y.suppressed = mate.suppressed ? undefined : true; }) }, sep, diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index 153f4221a0..a5a178157e 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -10,13 +10,15 @@ import { KernelRestartError } from '../../kernel/client'; import { type Quat, type Vec3, add, cross, dot, normalize, qAxisAngle, qMul, scale, sub } from '../../math/vec'; import { DocStore, parseDocument } from '../../model/document'; import { BASE_FRAMES, BASE_PLANE_NAMES } from '../../model/planes'; -import type { Id, PartDocument } from '../../model/types'; +import type { FaceRef, Id, PartDocument } from '../../model/types'; import { UNIT_SYSTEMS } from '../../model/units'; import { type AsmComponent, type AsmPart, type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MotionStudy, type Placement, MATE_LABELS, PartCache, asAssembly, mateComps, mateRefs, } from '../../model/assembly'; import { type ComposedModel, type PartGeometry, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; -import { type AnalysisResult, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, matesMoving } from '../../assembly/solver'; +import { + type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type ProfileArc, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, camProfile, mateBodies, matesMoving, +} from '../../assembly/solver'; import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, profileOf } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; import { confirmDialog, toast } from '../../ui/overlay'; @@ -204,9 +206,36 @@ export class AssemblyMode { } return geo ? { body: c.id, geo } : `The ${'face' in ref ? 'face' : 'edge'} it references on ${c.name} cannot be mated`; } + if ('point' in ref) return { body: c.id, geo: { kind: 'point', p: ref.point } }; return { body: c.id, geo: { kind: 'body' } }; } + /** Cam profiles by part copy and faces (a drag step solves the mates many times). */ + private profiles = new Map(); + + /** + * A cam mate's profile: its faces swept along one direction, as arcs (round + * faces, their extent from their circular edges) and corners (the other + * faces' edges and mesh vertices), in the cam's coordinates. + */ + camEntity(m: Mate, doc = this.doc): SolverEntity | string { + if (!('face' in m.a)) return 'A cam mate needs the faces of the cam\'s profile'; + const c = doc.components.find((x) => x.id === (m.a as { comp: Id }).comp); + if (!c) return 'Its component was deleted'; + const g = this.geometryOf(c.part); + const part = doc.parts.find((p) => p.id === c.part); + if (!g || !part) return `${c.name} is not built`; + const refs = [m.a.face, ...m.chain ?? []]; + const key = `${this.key(part)}|${JSON.stringify(refs)}`; + let prof = this.profiles.get(key); + if (!prof) { + prof = camProfileOf(g, refs, c.name); + if (this.profiles.size > 50) this.profiles.clear(); + this.profiles.set(key, prof); + } + return typeof prof === 'string' ? prof : { body: c.id, geo: prof }; + } + /** Mate value in mm or degrees (a gear's teeth when its ratio is by teeth). */ mateValue(m: Mate, v = m.value): number { if (v === undefined) return 0; @@ -233,11 +262,10 @@ export class AssemblyMode { const inactive = new Set(); for (const m of doc.mates) { if (m.suppressed || mateComps(m).some((id) => doc.components.find((c) => c.id === id)?.suppressed)) { inactive.add(m.id); continue; } - const ents = mateRefs(m).map((r) => this.entity(r, doc)); + const ents = [m.type === 'cam' ? this.camEntity(m, doc) : this.entity(m.a, doc), this.entity(m.b, doc), m.a2 && this.entity(m.a2, doc), m.b2 && this.entity(m.b2, doc)]; const bad = ents.find((e): e is string => typeof e === 'string'); if (bad) { problems.set(m.id, bad); continue; } - const [a, b] = ents as SolverEntity[]; - const a2 = m.a2 ? (ents[2] as SolverEntity) : undefined, b2 = m.b2 ? (ents[ents.length - 1] as SolverEntity) : undefined; + const [a, b, a2, b2] = ents as (SolverEntity | undefined)[] as [SolverEntity, SolverEntity, SolverEntity | undefined, SolverEntity | undefined]; let value = 0, value2: number | undefined, limit: { min: number; max: number } | undefined; try { value = this.mateValue(m); @@ -448,9 +476,31 @@ export class AssemblyMode { const e = g?.edges[m.edgeLocal[it.index]]; return c && e ? { comp: c.id, edge: { name: e.name, sig: { type: e.type, m: e.mid, len: e.length } } } : null; } + if (it.kind === 'vertex') { + const v = this.vertexOf(it.p); + return v ? { comp: v.comp, point: v.local } : null; + } return null; } + /** The component a picked vertex is a vertex of, and where it is in its part. */ + vertexOf(p: Vec3): { comp: Id; local: Vec3 } | null { + let best: { comp: Id; local: Vec3 } | null = null, bestD = Infinity; + for (const c of this.doc.components) { + const g = !c.suppressed && !c.hidden ? this.geometryOf(c.part) : null; + const pl = g?.mesh && this.shownPlacement(c.id); + if (!g?.mesh || !pl) continue; + const q: Quat = [-pl.q[0], -pl.q[1], -pl.q[2], pl.q[3]]; + const local = rotateBy(q, sub(p, pl.p)); + const vs = g.mesh.vertices; + for (let k = 0; k < vs.length; k += 3) { + const d = Math.hypot(vs[k] - local[0], vs[k + 1] - local[1], vs[k + 2] - local[2]); + if (d < bestD) { bestD = d; best = { comp: c.id, local: [vs[k], vs[k + 1], vs[k + 2]] }; } + } + } + return best && bestD < 1e-3 * Math.max(1, this.scale()) ? best : null; + } + /** The item a mate reference shows as (to highlight it). */ itemOf(ref: MateRef): SelItem | null { if ('plane' in ref) return { kind: 'plane', ref: { kind: 'base', plane: ref.plane } }; @@ -461,6 +511,10 @@ export class AssemblyMode { const i = this.combinedFace(c.id, findFace(g.faces, ref.face)); return i >= 0 ? { kind: 'face', index: i, name: combinedName(c.id, ref.face.name) } : null; } + if ('point' in ref) { + const pl = this.shownPlacement(c.id); + return pl ? { kind: 'vertex', p: applyPlacement(pl, ref.point) } : null; + } if ('edge' in ref) { const m = this.model; const local = findEdge(g.edges, ref.edge); @@ -673,6 +727,17 @@ export class AssemblyMode { inputs.push({ id: mo.id, name: mo.name, kind: 'mate', mate: mt.id, at: profileOf('mate', values(mt.type === 'angle' ? 'angle' : 'length'), st.duration, sm.value) }); continue; } + if (mo.mate) { + // On a hinge (rotary) or a slider (linear): its second component turns or slides relative to its first. + const mt = this.doc.mates.find((x) => x.id === mo.mate); + const sm = held.find((x) => x.id === mo.mate); + const want = mo.kind === 'rotary' ? 'hinge' : 'slider'; + if (!mt || mt.type !== want) return `${mo.name}: a ${mo.kind} motor goes on a ${want} mate.`; + if (!sm) return `${mo.name}: ${mt.name} does not hold (suppressed, or with an error). Fix it to drive it.`; + if (mateBodies(sm).every((id) => this.component(id)?.fixed)) return `${mo.name}: both components of ${mt.name} are fixed.`; + inputs.push({ id: mo.id, name: mo.name, kind: mo.kind, on: sm, at: profileOf(mo.kind, values(mo.kind === 'rotary' ? 'angle' : 'length'), st.duration) }); + continue; + } const e = mo.ref ? this.entity(mo.ref) : 'It has no axis or direction'; if (typeof e === 'string') return `${mo.name}: ${e}.`; const comp = e.body ? this.component(e.body) : undefined; @@ -741,6 +806,40 @@ export class AssemblyMode { } /** Lets the browser handle input and paint before going on (a message, not a timer: timers are slowed in background tabs). */ +/** A cam's profile from the faces of its part, or why it cannot be one. */ +function camProfileOf(g: PartGeometry, refs: FaceRef[], name: string): CamProfile | string { + const arcs: ProfileArc[] = [], points: Vec3[] = []; + let d: Vec3 | null = null; + const normals: Vec3[] = []; + for (const ref of refs) { + const i = findFace(g.faces, ref); + if (i < 0) return `A face of the cam's profile on ${name} no longer exists`; + const f = g.faces[i]; + const edges = g.edges.filter((e) => e.faces.includes(i)); + if (f.type === 'cylinder' && f.axis && f.radius) { + const ax = normalize(f.axis.d); + if (d && Math.abs(dot(d, ax)) < 0.9999) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides)'; + d ??= ax; + // Its extent from a circular edge: a whole circle closes on itself. + const e = edges.find((x) => x.type === 'circle' && x.radius && Math.abs(x.radius - f.radius!) < 1e-6 * Math.max(1, f.radius!)); + const whole = !e || Math.abs(e.length - 2 * Math.PI * f.radius) < 1e-6 * f.radius; + arcs.push({ c: f.axis.p, r: f.radius, ...(whole ? {} : { ends: [e!.a, e!.b, e!.mid] as [Vec3, Vec3, Vec3] }) }); + continue; + } + if (f.type === 'plane' && f.normal) normals.push(normalize(f.normal)); + for (const e of edges) points.push(e.a, e.b, e.mid); + // Curved faces of other kinds: their mesh vertices (as close as the mesh is to the face). + const m = g.mesh; + if (m && f.type !== 'plane') for (let k = 0; k < m.vertexFace.length; k++) if (m.vertexFace[k] === i) points.push([m.positions[k * 3], m.positions[k * 3 + 1], m.positions[k * 3 + 2]]); + } + if (!d) { + for (let i = 0; i < normals.length && !d; i++) for (let j = i + 1; j < normals.length && !d; j++) { const x = cross(normals[i], normals[j]); if (Math.hypot(...x) > 1e-3) d = normalize(x); } + } + if (!d) return 'Select the faces around the cam (its sides): their direction cannot be told from these'; + if (normals.some((n) => Math.abs(dot(n, d!)) > 1e-6)) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides, not its ends)'; + return camProfile(d, arcs, points); +} + function yieldToUI(): Promise { return new Promise((resolve) => { const ch = new MessageChannel(); diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index c9ece22aa4..d1d9f875ce 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -184,7 +184,7 @@ export class MotionStudyPanel extends PropertyPanel { const lengthy = m.kind === 'linear' || mt?.type === 'distance'; const v = (p: Param | undefined, len = lengthy) => (p === undefined ? '?' : typeof p === 'string' ? p : String(Math.round((len ? p / u.scale : p) * 1000) / 1000)); const unit = m.kind === 'rotary' ? (m.rpm ? ' rpm' : '°/s') : lengthy ? ` ${u.length}/s` : '°/s'; - const what = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate)?.name ?? '?' : m.ref && 'comp' in m.ref ? this.mode.component(m.ref.comp)?.name ?? '?' : '?'; + const what = m.mate ? this.mode.doc.mates.find((x) => x.id === m.mate)?.name ?? '?' : m.ref && 'comp' in m.ref ? this.mode.component(m.ref.comp)?.name ?? '?' : '?'; const how = m.profile === 'constant' ? `${v(m.speed)}${unit}` : m.profile === 'oscillate' ? `±${v(m.amplitude)} at ${v(m.frequency, false)} Hz` : `${v(m.from)} to ${v(m.to)}`; return `${KIND_LABELS[m.kind]}, ${what}: ${how}${m.reverse ? ', reversed' : ''}`; } @@ -471,7 +471,7 @@ export class MotionStudyPanel extends PropertyPanel { h('div', { class: 'field-label' }, 'Motor type'), segmented('Motor type', m.kind, [{ value: 'rotary', label: 'Rotary' }, { value: 'linear', label: 'Linear' }, { value: 'mate', label: 'Mate' }], (v) => { const p: MotionProfile = v !== 'mate' && m.profile === 'ramp' ? 'constant' : m.profile; - Object.assign(this.motor!, { kind: v, profile: p, ref: v === 'mate' ? undefined : m.ref, mate: v === 'mate' ? m.mate : undefined, rpm: v === 'rotary' ? m.rpm : undefined }); + Object.assign(this.motor!, { kind: v, profile: p, ref: v === 'mate' ? undefined : m.ref, mate: undefined, rpm: v === 'rotary' ? m.rpm : undefined }); if (p === 'constant' && m.speed === undefined) this.motor!.speed = 10; this.app.refreshPanel(); }), @@ -484,6 +484,16 @@ export class MotionStudyPanel extends PropertyPanel { items.push(selectField('Mate to drive', m.mate!, mates.map((x) => ({ value: x.id, label: `${x.name} (${MATE_LABELS[x.type]})` })), (v) => set({ mate: v }), 'mate')); } } else { + // On a hinge or slider, or on a face or edge of the component to move. + const want = m.kind === 'rotary' ? 'hinge' : 'slider'; + const mounts = this.mode.doc.mates.filter((x) => x.type === want); + if (m.mate && !mounts.some((x) => x.id === m.mate)) delete m.mate; + items.push(selectField('Motor on', m.mate ?? '', [{ value: '', label: 'A face or edge (select it below)' }, ...mounts.map((x) => ({ value: x.id, label: `${x.name} (${MATE_LABELS[x.type]})` }))], (v) => { + if (v) { this.motor!.mate = v; delete this.motor!.ref; } else delete this.motor!.mate; + this.app.refreshPanel(); + }, 'mate')); + } + if (m.kind !== 'mate' && !m.mate) { const box = new SelectionBox(this, m.kind === 'rotary' ? 'Motor axis' : 'Motor direction', { face: true, edge: true }, (it) => { const r = this.mode.refOf(it); if (!r || !('comp' in r) || !('face' in r || 'edge' in r)) return null; @@ -534,14 +544,14 @@ export class MotionStudyPanel extends PropertyPanel { if (!m) return; if (save) { if (!this.checkFields()) return; - if (m.kind !== 'mate' && !m.ref) { this.setMessage('error', m.kind === 'rotary' ? 'Select the motor\'s axis: a round face or edge of the component to turn.' : 'Select the motor\'s direction: a straight edge or face of the component to move.'); return; } + if (m.kind !== 'mate' && !m.ref && !m.mate) { this.setMessage('error', m.kind === 'rotary' ? 'Select the motor\'s axis (a round face or edge of the component to turn), or a hinge to put it on.' : 'Select the motor\'s direction (a straight edge or face of the component to move), or a slider to put it on.'); return; } if (m.kind === 'mate' && !m.mate) { this.setMessage('error', 'Select the mate to drive.'); return; } // Only the fields of its kind and profile are kept. const keep: (keyof MotionMotor)[] = m.profile === 'constant' ? ['speed'] : m.profile === 'oscillate' ? ['amplitude', 'frequency'] : ['from', 'to']; for (const k of ['speed', 'amplitude', 'frequency', 'from', 'to'] as const) if (!keep.includes(k)) delete m[k]; if (m.kind !== 'rotary') delete m.rpm; if (m.profile === 'ramp') delete m.reverse; - if (m.kind === 'mate') delete m.ref; else delete m.mate; + if (m.kind === 'mate' || m.mate) delete m.ref; else delete m.mate; if (this.motorIndex < 0) { // Ids and names are allocated as the document's would be (the study's own motors counted too). const draft = { ...this.mode.doc, studies: [...(this.mode.doc.studies ?? []).filter((s) => s.id !== this.key), this.study] }; diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts index 1d68316c2c..b1d5fd7673 100644 --- a/src/parametric/src/app/assembly/panels.ts +++ b/src/parametric/src/app/assembly/panels.ts @@ -8,7 +8,7 @@ import { type Vec3, add, normalize, qAxisAngle, qMul, scale } from '../../math/v import { allocateId, newDocument, parseDocument, serializeDocument } from '../../model/document'; import { defaultName } from '../../model/features'; import { BASE_PLANE_NAMES } from '../../model/planes'; -import type { Id, Param, PartDocument } from '../../model/types'; +import type { FaceRef, Id, Param, PartDocument } from '../../model/types'; import { UNIT_SYSTEMS } from '../../model/units'; import { type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MateType, type MechanicalMateType, type PartSource, type Placement, MATE_LABELS, MECHANICAL_MATES, assemblyBom, bomCsv, instanceName, @@ -203,6 +203,15 @@ const MECH_BOXES: Record ({ comp: (existing.a as { comp: Id }).comp, face }))]; this.refs2 = [existing.b]; } else if (t === 'hinge') { this.refs = [existing.a, existing.b]; this.refs2 = [existing.a2!, existing.b2!]; } else this.refs = [existing.a, existing.b]; } else { @@ -265,6 +276,7 @@ export class MatePanel extends PropertyPanel { const c = this.mode.component(r.comp)?.name ?? '?'; if ('face' in r) return `Face (${r.face.sig.type}) of ${c}`; if ('edge' in r) return `Edge (${r.edge.sig.type}) of ${c}`; + if ('point' in r) return `Vertex of ${c}`; return c; } @@ -293,6 +305,7 @@ export class MatePanel extends PropertyPanel { private limitAround(v: number) { if (this.type === 'angle') { this.min = Math.max(0, Math.round(v - 30)); this.max = Math.min(180, Math.round(v + 30)); } else if (this.type === 'hinge') { this.min = -45; this.max = 45; } + else if (this.type === 'slider') { this.min = -25; this.max = 25; } else { this.min = Math.max(0, Math.round((v - 10) * 1000) / 1000); this.max = Math.round((v + 10) * 1000) / 1000; } } @@ -314,6 +327,12 @@ export class MatePanel extends PropertyPanel { if (ga && gb) this.aligned2 = initialMateSettings('coincident', ga, gb).aligned; } if (t === 'screw' && typeof this.value === 'number' && this.value === 10 && !this.existing) this.value = 1; + if (t === 'slider') { + // Each pair's alignment as the entities are now (the first entity of each component, then the second). + const al = (x?: MateRef, y?: MateRef) => { const gx = x && this.geo(x), gy = y && this.geo(y); return gx && gy ? initialMateSettings('coincident', gx, gy).aligned : null; }; + this.aligned = al(this.refs[0], this.refs2[0]) ?? this.aligned; + this.aligned2 = al(this.refs[1], this.refs2[1]) ?? this.aligned2; + } } /** A hinge's two faces, the one on the first round entity's component first. */ @@ -339,7 +358,9 @@ export class MatePanel extends PropertyPanel { this.mechDefaults(mech); // A full box hands the picks on to the next one. const next = made[i + 1]; - if (refs.length === spec.count && next && next.items.length < boxes[i + 1].count) this.activate(next); + // (A slider's component takes one edge or axis, or two faces.) + const axisOnly = mech === 'slider' && refs.length === 1 && (() => { const g = this.geo(refs[0]); return g?.kind === 'line' || g?.kind === 'axis'; })(); + if ((refs.length === spec.count || axisOnly) && next && next.items.length < boxes[i + 1].count) this.activate(next); this.mode.app.refreshPanel(); this.update(); }, { placeholder: spec.placeholder, icon: 'mate', single: spec.count === 1 }); @@ -390,9 +411,9 @@ export class MatePanel extends PropertyPanel { if (!was && now) { this.refs2 = []; this.refs = this.refs.filter((r) => !('comp' in r) || 'face' in r || 'edge' in r).slice(0, 2); } if (was && !now) this.refs = this.refs.slice(0, 2); if (now === 'gear' && this.by === 'revolution') this.by = null; - if (now === 'rackPinion' && this.by === 'ratio') this.by = null; - if (!now && this.by) this.by = null; - if (this.limitOn && v !== 'distance' && v !== 'angle' && v !== 'hinge') this.limitOn = false; + if (this.by && !((now === 'gear' && this.by === 'ratio') || (now === 'rackPinion' && this.by === 'revolution') || (now === 'universal' && this.by === 'point'))) this.by = null; + if (now === 'universal' && !this.existing) this.value = 0; + if (this.limitOn && v !== 'distance' && v !== 'angle' && v !== 'hinge' && v !== 'slider') this.limitOn = false; this.pickDefaults(); this.mode.app.refreshPanel(); this.update(); @@ -487,6 +508,22 @@ export class MatePanel extends PropertyPanel { ...this.alignment(), ); break; + case 'slider': + out.push(...this.alignment(), checkbox('Limit the travel (from where it is now)', this.limitOn, (v) => { + this.limitOn = v; + if (v) this.limitAround(0); + this.mode.app.refreshPanel(); + this.update(); + })); + if (this.limitOn) out.push(...this.limitFields('length', ctx)); + break; + case 'cam': + if (this.refs2[0] && this.geo(this.refs2[0])?.kind === 'plane') out.push(checkbox('Flip the follower face (the cam on its other side)', this.flip, (v) => { this.flip = v; this.update(); })); + break; + case 'universal': + out.push(checkbox('Joint point: the shafts\' axes meet', this.by === 'point', (v) => { this.by = v ? 'point' : null; this.mode.app.refreshPanel(); this.update(); })); + if (this.by === 'point') out.push(numberField({ label: 'Joint point offset (along the first shaft)', icon: 'smartDimension', value: this.value, kind: 'length', ctx, onChange: (v) => { this.value = v; this.update(); } })); + break; default: break; } @@ -536,9 +573,29 @@ export class MatePanel extends PropertyPanel { } private mechMate(t: MechanicalMateType, base: Omit): Mate | null { + const [r0, r1] = this.refs; + // The position captured when the mate was added stays while its entities do. + const kept = (a: MateRef, b: MateRef) => (this.existing?.type === t && this.existing.rel && JSON.stringify([this.existing.a, this.existing.b]) === JSON.stringify([a, b]) ? this.existing.rel : this.relNow(a, b)); + if (t === 'slider') { + const n = this.refs.length; + if (!n || n !== this.refs2.length) return null; + const rel = kept(r0, this.refs2[0]); + return { + ...base, a: r0, b: this.refs2[0], ...(n === 2 ? { a2: r1, b2: this.refs2[1], aligned2: this.aligned2 } : {}), + ...(this.limitOn ? { limit: { min: this.min, max: this.max } } : {}), ...(rel ? { rel } : {}), + }; + } + if (t === 'cam') { + if (!this.refs.length || this.refs2.length !== 1 || !this.refs.every((r) => 'face' in r && 'comp' in r0 && r.comp === r0.comp)) return null; + return { ...base, a: r0, b: this.refs2[0], ...(this.refs.length > 1 ? { chain: this.refs.slice(1).map((r) => (r as { face: FaceRef }).face) } : {}), ...(this.flip ? { flip: true } : {}) }; + } + if (t === 'universal') { + if (this.refs.length !== 2) return null; + const rel = kept(r0, r1); + return { ...base, a: r0, b: r1, ...(rel ? { rel } : {}), ...(this.by === 'point' ? { by: 'point', value: this.value } : {}) }; + } const counts = MECH_BOXES[t].map((x) => x.count); if (this.refs.length !== counts[0] || (counts[1] && this.refs2.length !== counts[1])) return null; - const [r0, r1] = this.refs; switch (t) { case 'hinge': { const [a2, b2] = this.hingeFaces(); @@ -552,6 +609,7 @@ export class MatePanel extends PropertyPanel { case 'width': return { ...base, a: r0, a2: r1, b: this.refs2[0], b2: this.refs2[1] }; case 'slot': return { ...base, a: r0, a2: r1, b: this.refs2[0] }; } + return null; } private withMate(d: AssemblyDocument, m: Mate) { @@ -559,8 +617,9 @@ export class MatePanel extends PropertyPanel { else { m.id = nextAsmId(d, 'm'); // Limit mates are named for what they limit, as in "LimitDistance1". - const kind = m.limit && m.type !== 'hinge' ? `Limit${MATE_LABELS[m.type]}` : MATE_LABELS[m.type]; - const n = d.mates.filter((x) => x.type === m.type && !!x.limit === !!m.limit).length + 1; + const limited = !!m.limit && (m.type === 'distance' || m.type === 'angle'); + const kind = limited ? `Limit${MATE_LABELS[m.type]}` : MATE_LABELS[m.type]; + const n = d.mates.filter((x) => x.type === m.type && (!!x.limit && (x.type === 'distance' || x.type === 'angle')) === limited).length + 1; let name = `${kind}${n}`; for (let k = n + 1; d.mates.some((x) => x.name === name); k++) name = `${kind}${k}`; m.name = name; diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index 626c5b8d73..409f9aa276 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -13,11 +13,11 @@ // differences. import type { Quat, Vec3 } from '../math/vec'; -import { add, dot, len, normalize, qMul } from '../math/vec'; +import { add, dot, len, normalize, qMul, qRotate } from '../math/vec'; import type { MotionMotor, Placement } from '../model/assembly'; import type { Id } from '../model/types'; import { - CONFLICT_TOL, type Drive, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, mateMeasure, placeGeo, quatRotVec, + CONFLICT_TOL, type Drive, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, mateMeasure, placeGeo, quatRotVec, sliderDirection, } from './solver'; /** A motor ready to run: what it moves and its motion over time. */ @@ -30,6 +30,8 @@ export interface MotorInput { entity?: SolverEntity; /** Mate driver: the mate whose value it sets. */ mate?: Id; + /** A rotary motor on a hinge, a linear one on a slider: it turns or slides the mate's second component relative to its first. */ + on?: SolverMate; /** Rotary: the turn (radians); linear: the travel (mm), from the start of the study. Mate driver: the mate's value (mm or degrees). */ at: (t: number) => number; } @@ -117,7 +119,7 @@ export class MotionRun { const floating = new Set(setup.bodies.filter((b) => !b.fixed).map((b) => b.id)); for (const m of setup.motors) { // (A fixed component links nothing: from it, every mate to the ground would be solved.) - const ids = (m.body ? [m.body] : setup.mates.filter((x) => x.id === m.mate).flatMap(mateBodies)).filter((id) => floating.has(id)); + const ids = (m.on ? mateBodies(m.on) : m.body ? [m.body] : setup.mates.filter((x) => x.id === m.mate).flatMap(mateBodies)).filter((id) => floating.has(id)); for (const id of ids) for (const x of matesMoving(id, setup.bodies, setup.mates)) moving.add(x); } this.solverMates = setup.mates.filter((x) => moving.has(x)); @@ -148,6 +150,7 @@ export class MotionRun { mates = mates.map((x) => (x.id === m.mate ? { ...x, value: v } : x)); continue; } + if (m.on) { const d = mountedDrive(m.on, prev, s.bodies, m.kind, m.at(t1) - m.at(t0)); if (d) drives.push(d); continue; } if (!m.body || !m.entity) continue; const g = placeGeo(m.entity.geo, m.entity.body ? prev.get(m.entity.body) ?? null : null); const dir = directionOf(g); @@ -192,6 +195,29 @@ export class MotionRun { } } +/** + * The drive of a motor on a hinge or slider: the second component turns + * about the hinge's axis, or slides along the slider, relative to the first + * (in the first's coordinates). When the second is fixed, the first moves + * the other way, measured in the second's coordinates. + */ +function mountedDrive(on: SolverMate, prev: Map, bodies: SolverBody[], kind: MotorInput['kind'], amount: number): Drive | null { + const fixed = (id: Id | null) => !id || !!bodies.find((b) => b.id === id)?.fixed; + const dir = kind === 'rotary' ? (on.a.geo.kind === 'axis' || on.a.geo.kind === 'line' ? normalize(on.a.geo.d) : null) : sliderDirection(on); + if (!dir) return null; + const pa = (on.a.body && prev.get(on.a.body)) || IDENT, pb = (on.b.body && prev.get(on.b.body)) || IDENT; + const pointB = pointOfGeo(on.b.geo) ?? [0, 0, 0], pointA = pointOfGeo(on.a.geo) ?? [0, 0, 0]; + if (!fixed(on.b.body)) { + return kind === 'rotary' ? { kind: 'relTurn', body: on.b.body!, base: on.a.body, axis: dir, amount } : { kind: 'relSlide', body: on.b.body!, base: on.a.body, local: pointB, dir, amount }; + } + if (fixed(on.a.body)) return null; + // a's direction in b's coordinates (where they are now). + const inB = qRotate([-pb.q[0], -pb.q[1], -pb.q[2], pb.q[3]], qRotate(pa.q, dir)); + return kind === 'rotary' ? { kind: 'relTurn', body: on.a.body!, base: on.b.body, axis: inB, amount: -amount } : { kind: 'relSlide', body: on.a.body!, base: on.b.body, local: pointA, dir: inB, amount: -amount }; +} + +const IDENT: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const directionOf = (g: Geo): Vec3 | null => (g.kind === 'plane' ? normalize(g.n) : g.kind === 'axis' || g.kind === 'line' ? normalize(g.d) : null); const pointOfGeo = (g: Geo): Vec3 | null => (g.kind === 'plane' ? g.o : g.kind === 'axis' || g.kind === 'line' || g.kind === 'point' ? g.p : g.kind === 'sphere' ? g.c : null); diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index 01f281370d..b4e2801f0c 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -25,8 +25,8 @@ // (a drag step, a motion study frame, the document after a commit), so the // turns add up: a gear driven round and round keeps its ratio past ±180°. -import type { Quat, Vec3 } from '../math/vec'; -import { add, cross, dot, len, normalize, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; +import type { Quat, Vec2, Vec3 } from '../math/vec'; +import { add, cross, dot, len, normalize, perpendicular, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; import type { Id } from '../model/types'; import { type MateType, type Placement, isMechanical } from '../model/assembly'; @@ -39,7 +39,25 @@ export type Geo = | { kind: 'point'; p: Vec3 } | { kind: 'sphere'; c: Vec3; r: number } /** A whole component (lock mates). */ - | { kind: 'body' }; + | { kind: 'body' } + /** A cam's profile: a closed curve swept along d, in its plane (o, u, v): see camProfile. */ + | CamProfile; + +/** + * A cam's profile in the cam's coordinates. Followers touch its convex + * outline: a circle (exactly) or a polygon (arcs finely divided). `concave`: + * how deep the profile dips inside that outline (zero when it is convex). + */ +export interface CamProfile { + kind: 'profile'; + o: Vec3; d: Vec3; u: Vec3; v: Vec3; + circle: { c: Vec2; r: number } | null; + /** Counter-clockwise convex polygon (when not a circle): the arcs divided, with the corners. */ + hull: Vec2[]; + /** The arcs themselves (counter-clockwise from a0 by span), so contact on them is exact. */ + arcs: { c: Vec2; r: number; a0: number; span: number }[]; + concave: number; +} export interface SolverEntity { /** The component the geometry belongs to; null for the assembly itself (its planes). */ @@ -67,8 +85,8 @@ export interface SolverMate { limit?: { min: number; max: number }; /** Gear: b's pitch diameter or part of the ratio (value is a's). */ value2?: number; - /** Rack and pinion: value is the travel per turn (not the pitch diameter). */ - by?: 'ratio' | 'revolution'; + /** Rack and pinion: value is the travel per turn (not the pitch diameter). Universal joint: the axes meet at a joint point. */ + by?: 'ratio' | 'revolution' | 'point'; /** Gear, rack and pinion: the other way round; screw: left-hand. */ reverse?: boolean; } @@ -80,7 +98,15 @@ export interface SolverMate { */ export type Drive = | { kind: 'rotate'; body: Id; axis: Vec3; amount: number } - | { kind: 'translate'; body: Id; local: Vec3; dir: Vec3; amount: number }; + | { kind: 'translate'; body: Id; local: Vec3; dir: Vec3; amount: number } + /** + * A motor on a hinge or slider: body turns about `axis`, or its point + * `local` moves along `dir`, relative to `base` (both in base's coordinates). + */ + | { kind: 'relTurn'; body: Id; base: Id | null; axis: Vec3; amount: number } + | { kind: 'relSlide'; body: Id; base: Id | null; local: Vec3; dir: Vec3; amount: number }; + +const driveBodies = (d: Drive): Id[] => (d.kind === 'relTurn' || d.kind === 'relSlide') && d.base ? [d.body, d.base] : [d.body]; export interface SolverBody { id: Id; @@ -509,6 +535,59 @@ function mechanicalEquations(c: MechContext): number[] | null { const mid = (p: Vec3, q: Vec3) => scale(add(p, q), 0.5); return [...cross(ga.n, gb.n), dot(sub(mid(gb.o, gb2.o), mid(ga.o, ga2.o)), ga.n) / L]; } + case 'slider': { + if (!m.rel) return null; + const rel = relativePlacement(c.pa, c.pb); + let rows: number[] | null, dir: Vec3 | null; + if (!ga2 || !gb2) { + // Axes or straight edges: on one line, and no turn about it from where it was added. + if (!isAxisLike(ga) || !isAxisLike(gb) || !isAxisLike(m.a.geo)) return null; + dir = normalize(dirOf(m.a.geo)!); + const da = normalize(dirOf(ga)!), db = normalize(dirOf(gb)!); + rows = [...(m.aligned ? sub(da, db) : add(da, db)), ...scale(cross(sub(pointOf(gb)!, pointOf(ga)!), da), 1 / L), turnAbout(rel.q, m.rel.q, dir)]; + } else { + // Two pairs of faces flush: they slide along the line where the faces meet. + const p1 = equations('coincident', ga, gb, o, null, null), p2 = equations('coincident', ga2, gb2, { ...o, aligned: !!m.aligned2 }, null, null); + if (!p1 || !p2 || m.a.geo.kind !== 'plane' || m.a2?.geo.kind !== 'plane') return null; + dir = normalize(cross(m.a.geo.n, m.a2.geo.n)); + rows = [...p1, ...p2]; + } + if (!m.limit) return rows; + return [...rows, ...(c.ineq ? [outside(sliderTravel(m, rel, dir), m.limit.min, m.limit.max) / L] : [])]; + } + case 'cam': { + const prof = m.a.geo; + if (prof.kind !== 'profile') return null; + // The follower in the cam's coordinates, then in its profile's plane. + const qi: Quat = [-c.pa.q[0], -c.pa.q[1], -c.pa.q[2], c.pa.q[3]]; + const local = (p: Vec3) => qRotate(qi, sub(p, c.pa.p)); + const in2 = (p: Vec3): Vec2 => { const w = sub(local(p), prof.o); return [dot(w, prof.u), dot(w, prof.v)]; }; + if (gb.kind === 'point') return [profileDistance(prof, in2(gb.p)) / L]; + if (gb.kind === 'sphere') return [(profileDistance(prof, in2(gb.c)) - gb.r) / L]; + if (gb.kind === 'axis') return [(profileDistance(prof, in2(gb.p)) - gb.r) / L]; + if (gb.kind === 'plane') { + // A flat face touches the cam where the cam reaches furthest toward it (the cam on its outer side). + const n = qRotate(qi, scale(gb.n, m.flip ? -1 : 1)); + const n2: Vec2 = [dot(n, prof.u), dot(n, prof.v)]; + const nl = Math.hypot(n2[0], n2[1]); + if (nl < 1e-9) return null; + const u2: Vec2 = [n2[0] / nl, n2[1] / nl]; + const o2 = in2(gb.o); + return [(-profileSupport(prof, [-u2[0], -u2[1]]) - (o2[0] * u2[0] + o2[1] * u2[1])) / L]; + } + return null; + } + case 'universal': { + if (!m.rel || !isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; + const y = yokes(m); + if (!y) return null; + // The cross piece holds the two yokes square to each other. + const rows = [dot(qRotate(c.pa.q, y.a), qRotate(c.pb.q, y.b))]; + if (m.by !== 'point') return rows; + // The axes meet at the joint point, `value` along a's axis. + const j = applyPlacement(c.pa, add(pointOf(m.a.geo)!, scale(normalize(dirOf(m.a.geo)!), m.value))); + return [...rows, ...scale(cross(sub(j, pointOf(gb)!), normalize(dirOf(gb)!)), 1 / L)]; + } case 'slot': { if (!ga2 || !isAxisLike(ga) || !isAxisLike(ga2)) return null; const da = normalize(dirOf(ga)!), p1 = pointOf(ga)!, w = sub(pointOf(ga2)!, p1); @@ -528,14 +607,170 @@ function mechanicalEquations(c: MechContext): number[] | null { const placeGeoDir = (g: Geo, pl: Placement): Vec3 => normalize(qRotate(pl.q, dirOf(g) ?? [0, 0, 1])); +/** A slider's travel (mm) from where it was added: b's entity along the slide, in a's coordinates. */ +function sliderTravel(m: SolverMate, rel: Placement, dir: Vec3): number { + const p = pointOf(m.b.geo) ?? [0, 0, 0]; + return dot(sub(applyPlacement(rel, p), applyPlacement(m.rel!, p)), dir); +} + +/** The direction a slider slides, in a's coordinates. */ +export function sliderDirection(m: SolverMate): Vec3 | null { + if (m.a2?.geo.kind === 'plane' && m.a.geo.kind === 'plane') { const d = cross(m.a.geo.n, m.a2.geo.n); return len(d) > 1e-9 ? normalize(d) : null; } + const d = dirOf(m.a.geo); + return d ? normalize(d) : null; +} + +/** + * The yokes of a universal joint, each in its shaft's coordinates: a's in + * the plane of the two axes where the joint was added, b's square to it and + * to b's axis. Measured from there, b turns by atan(tan φ / cos β) as a + * turns by φ (β the angle between the axes). + */ +function yokes(m: SolverMate): { a: Vec3; b: Vec3 } | null { + const da = dirOf(m.a.geo), db = dirOf(m.b.geo); + if (!da || !db || !m.rel) return null; + const a = normalize(da); + const bInA = normalize(qRotate(m.rel.q, db)); + const off = sub(bInA, scale(a, dot(bInA, a))); + const ya = len(off) > 1e-9 ? normalize(off) : perpendicular(a); + const yb = normalize(cross(bInA, ya)); + return { a: ya, b: qRotate([-m.rel.q[0], -m.rel.q[1], -m.rel.q[2], m.rel.q[3]], yb) }; +} + +// ---------- cam profiles ---------- + +/** A circular arc of a cam's profile: centre and radius, and (unless it is a whole circle) its ends and a point between them. */ +export interface ProfileArc { c: Vec3; r: number; ends?: [Vec3, Vec3, Vec3] } + +/** + * A cam's profile from its round faces (arcs about axes along d) and the + * corners of its other faces (points), all in the cam's coordinates. A + * single whole circle stays a circle (exact); otherwise arcs are divided + * finely (a 20 mm radius by at most 0.4 µm) and the outline is their convex + * hull with the points. Where the profile lies inside that outline it is + * concave, and `concave` says by how much. + */ +export function camProfile(d0: Vec3, arcs: ProfileArc[], points: Vec3[]): CamProfile { + const d = normalize(d0); + const u = perpendicular(d), v = cross(d, u); + const o = arcs[0]?.c ?? points[0] ?? [0, 0, 0]; + const in2 = (p: Vec3): Vec2 => { const w = sub(p, o); return [dot(w, u), dot(w, v)]; }; + const base = { kind: 'profile' as const, o, d, u, v }; + const whole = arcs.filter((a) => !a.ends); + if (arcs.length === 1 && whole.length === 1) { + const c = in2(whole[0].c), r = whole[0].r; + // Corners of other faces on the circle (its caps' edges, say) change nothing. + if (points.every((p) => Math.abs(Math.hypot(in2(p)[0] - c[0], in2(p)[1] - c[1]) - r) < 1e-6 * Math.max(1, r))) return { ...base, circle: { c, r }, hull: [], arcs: [], concave: 0 }; + } + const pts: Vec2[] = points.map(in2); + const exact: CamProfile['arcs'] = []; + for (const a of arcs) { + const c = in2(a.c); + const ang = (p: Vec3) => { const q = in2(p); return Math.atan2(q[1] - c[1], q[0] - c[0]); }; + let a0 = 0, sweep = 2 * Math.PI; + if (a.ends) { + // From one end through the middle point to the other. + a0 = ang(a.ends[0]); + const am = ang(a.ends[2]), a1 = ang(a.ends[1]); + const ccw = (x: number) => ((x - a0) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI); + sweep = ccw(am) <= ccw(a1) ? ccw(a1) : ccw(a1) - 2 * Math.PI; + } + exact.push({ c, r: a.r, a0: sweep >= 0 ? a0 : a0 + sweep, span: Math.abs(sweep) }); + const n = Math.max(8, Math.ceil(Math.abs(sweep) / (0.2 * Math.PI / 180))); + for (let k = 0; k <= n; k++) { const t = a0 + (sweep * k) / n; pts.push([c[0] + a.r * Math.cos(t), c[1] + a.r * Math.sin(t)]); } + } + const hull = convexHull(pts); + let concave = 0; + for (const p of pts) concave = Math.max(concave, -polygonDistance(hull, p)); + return { ...base, circle: null, hull, arcs: exact, concave }; +} + +/** Whether the direction of w lies on an arc (counter-clockwise from a0 by span). */ +const onArc = (a: CamProfile['arcs'][number], w: Vec2) => (((Math.atan2(w[1], w[0]) - a.a0) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI) <= a.span + 1e-12; + +/** Counter-clockwise convex hull (monotone chain). */ +function convexHull(pts: Vec2[]): Vec2[] { + const p = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]); + if (p.length < 3) return p; + const turn = (o: Vec2, a: Vec2, b: Vec2) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); + const lower: Vec2[] = [], upper: Vec2[] = []; + for (const x of p) { while (lower.length >= 2 && turn(lower[lower.length - 2], lower[lower.length - 1], x) <= 1e-12) lower.pop(); lower.push(x); } + for (let i = p.length - 1; i >= 0; i--) { const x = p[i]; while (upper.length >= 2 && turn(upper[upper.length - 2], upper[upper.length - 1], x) <= 1e-12) upper.pop(); upper.push(x); } + return [...lower.slice(0, -1), ...upper.slice(0, -1)]; +} + +/** Signed distance from a point to a convex polygon (negative inside). */ +function polygonDistance(h: Vec2[], x: Vec2): number { + let inside = true, best = Infinity, depth = Infinity; + for (let i = 0; i < h.length; i++) { + const a = h[i], b = h[(i + 1) % h.length]; + const ex = b[0] - a[0], ey = b[1] - a[1], l2 = ex * ex + ey * ey || 1; + const wx = x[0] - a[0], wy = x[1] - a[1]; + const side = (ex * wy - ey * wx) / Math.sqrt(l2); + if (side < 0) inside = false; + depth = Math.min(depth, side); + const t = Math.max(0, Math.min(1, (wx * ex + wy * ey) / l2)); + best = Math.min(best, Math.hypot(wx - t * ex, wy - t * ey)); + } + return inside ? -depth : best; +} + +/** Signed distance from a point in the profile's plane to its outline. */ +export function profileDistance(p: CamProfile, x: Vec2): number { + if (p.circle) return Math.hypot(x[0] - p.circle.c[0], x[1] - p.circle.c[1]) - p.circle.r; + const poly = polygonDistance(p.hull, x); + // The arcs a point faces give its exact distance; the polygon's chords lie a little inside them. + let out = Infinity, inside = -Infinity; + for (const a of p.arcs) { + const w: Vec2 = [x[0] - a.c[0], x[1] - a.c[1]]; + if (!onArc(a, w)) continue; + const d = Math.hypot(w[0], w[1]) - a.r; + out = Math.min(out, d); + inside = Math.max(inside, d); + } + // Outside (or between a chord and its arc): the nearest of the edges and arcs, none nearer than the outline. + if (poly >= 0) return Math.min(poly, out); + // Inside, near an arc (no deeper than the chords' sag, 0.2° apart): the arc's. + return inside >= poly - 2e-6 * Math.max(1, ...p.arcs.map((a) => a.r)) ? inside : poly; +} + +/** How far the outline reaches along a unit direction (its support function). */ +export function profileSupport(p: CamProfile, u: Vec2): number { + if (p.circle) return p.circle.c[0] * u[0] + p.circle.c[1] * u[1] + p.circle.r; + let best = -Infinity; + for (const q of p.hull) best = Math.max(best, q[0] * u[0] + q[1] * u[1]); + for (const a of p.arcs) if (onArc(a, u)) best = Math.max(best, a.c[0] * u[0] + a.c[1] * u[1] + a.r); + return best; +} + /** Why the entities (and values) of a mechanical mate do not make one, or null when they do. */ -export function mechanicalProblem(m: Pick): string | null { +export function mechanicalProblem(m: Pick): string | null { const { a, b, a2, b2 } = m; const axis = (e?: SolverEntity) => !!e && (e.geo.kind === 'axis' || e.geo.kind === 'line'); const round = (e?: SolverEntity) => !!e && e.geo.kind === 'axis'; const plane = (e?: SolverEntity) => !!e && e.geo.kind === 'plane'; const parallel = (x: SolverEntity, y: SolverEntity) => x.body === y.body && Math.abs(dot(normalize(dirOf(x.geo)!), normalize(dirOf(y.geo)!))) > 0.9999; switch (m.type) { + case 'slider': + if (!a.body && !b.body) return 'A slider needs a component'; + if (!m.rel) return 'The slider has no stored position'; + if (a2 || b2) { + if (!plane(a) || !plane(a2) || !plane(b) || !plane(b2)) return 'A slider needs a straight edge or axis on each component, or two planar faces on each'; + if (a2!.body !== a.body || b2!.body !== b.body) return 'Each component\'s two faces must be faces of that component'; + if (Math.abs(dot(normalize(dirOf(a.geo)!), normalize(dirOf(a2!.geo)!))) > 0.999) return 'The two faces on each component must not be parallel (the slider moves along the line where they meet)'; + } else if (!axis(a) || !axis(b)) return 'A slider needs a straight edge or axis on each component, or two planar faces on each'; + return m.limit && !(m.limit.min <= m.limit.max) ? 'The smallest travel must not be more than the largest' : null; + case 'cam': { + if (a.geo.kind !== 'profile') return 'A cam mate needs the faces of the cam\'s profile and a follower'; + if (!a.body || a.body === b.body) return 'The cam and the follower must be different components'; + if (!['point', 'sphere', 'axis', 'plane'].includes(b.geo.kind)) return 'The follower must be a vertex, a round face or edge (a roller) or a planar face'; + const size = a.geo.circle ? a.geo.circle.r : Math.max(1, ...a.geo.hull.map((q) => Math.hypot(q[0], q[1]))); + if (a.geo.concave > 1e-6 * Math.max(1, size)) return `The cam's profile has a hollow ${Math.round(a.geo.concave * 1000) / 1000} mm deep: a follower cannot stay in contact there. Cam mates follow convex profiles (an eccentric, lobes and flats).`; + return b.geo.kind === 'plane' && Math.abs(dot(normalize(b.geo.n), a.geo.d)) > 0.999 ? 'The flat follower face must face the cam across its axis, not along it' : null; + } + case 'universal': + if (!axis(a) || !axis(b) || !a.body || !b.body) return 'A universal joint needs a round face or edge (or an axis) on each of two shafts'; + return m.rel ? null : 'The universal joint has no stored position'; case 'hinge': if (!round(a) || !round(b) || !plane(a2) || !plane(b2)) return 'A hinge needs two round faces or edges (the pin and its hole) and two planar faces that touch'; if (a2!.body !== a.body || b2!.body !== b.body) return 'Each planar face of a hinge must be on the component of the round entity selected with it'; @@ -580,6 +815,10 @@ export function mateMeasure(m: SolverMate, pl: Map, L = 100): { v if (!rel || m.a.geo.kind !== 'axis') return null; return { value: (turnAbout(relativePlacement(pa, pb).q, rel.q, normalize(m.a.geo.d)) * 180) / Math.PI, kind: 'angle' }; } + if (m.type === 'slider' && m.rel) { + const dir = sliderDirection(m); + return dir ? { value: sliderTravel(m, relativePlacement(at(m.a) ?? IDENT, at(m.b) ?? IDENT), dir), kind: 'length' } : null; + } if (m.type === 'slot' && m.a2) { const ga2 = placeGeo(m.a2.geo, at(m.a2)); const da = dirOf(ga), p1 = pointOf(ga), p2 = pointOf(ga2), pb = pointOf(gb); @@ -619,7 +858,7 @@ export class MateSolver { for (const m of mates) for (const id of mateBodies(m)) involved.add(id); if (opts.drag) involved.add(opts.drag.body); const drives = opts.drives ?? []; - for (const d of drives) involved.add(d.body); + for (const d of drives) for (const id of driveBodies(d)) involved.add(id); const vars = [...involved].filter((id) => bodies.has(id) && !bodies.get(id)!.fixed); const sys: System = { vars, index: new Map(vars.map((id, i) => [id, i])), bodies, centers: new Map(vars.map((id) => [id, bodies.get(id)!.center ?? [0, 0, 0]])) }; const placements = new Map([...bodies].map(([id, b]) => [id, b.placement])); @@ -778,7 +1017,7 @@ export class MateSolver { block(row, mateBodies(mt), f); row += len0; } - for (const d of drives) { block(row, [d.body], (pl) => driveResidual([d], pl, base, L)); row++; } + for (const d of drives) { block(row, driveBodies(d), (pl) => driveResidual([d], pl, base, L)); row++; } if (drag) block(row, [drag.body], (pl) => dragResidual(drag, pl, L).map((v) => v * dragWeight)); return J; } @@ -949,7 +1188,11 @@ function driveResidual(drives: Drive[], pl: Map, ref: Map (MECHANICAL_MATES as readonly string[]).includes(t); /** What a mate references: a face or edge of a component (by name, as features reference faces), an assembly plane, or a whole component (lock). */ export type MateRef = | { comp: Id; face: FaceRef } | { comp: Id; edge: EdgeRef } + /** A vertex of a component, in its part's coordinates (cam followers). */ + | { comp: Id; point: Vec3 } | { comp: Id } | { plane: BasePlane }; @@ -91,17 +93,25 @@ export interface Mate { /** Distance and tangent mates: the second entity lies on the other side of the first. */ flip?: boolean; suppressed?: boolean; - /** Lock mates: where b sits in a's frame. Hinges with angle limits: where b sat in a's frame at 0°. */ + /** + * Lock mates: where b sits in a's frame. Hinges with angle limits: where b + * sat in a's frame at 0°. Sliders: where b sat when added (their turn is + * held, their travel measured from there). Universal joints: where the + * shafts were when added (the yokes' directions are taken from it). + */ rel?: Placement; /** * The second pair of entities: a hinge's coincident faces (a2 on a's * component, b2 on b's), a width mate's groove (a, a2) and tab (b, b2) - * faces, a slot's two end faces (a, a2; b is the pin). + * faces, a slot's two end faces (a, a2; b is the pin), a slider's second + * planar face on each component. */ a2?: MateRef; b2?: MateRef; - /** Hinge: alignment of the coincident faces (aligned is that of the axes). */ + /** Hinge, slider: alignment of the second pair (aligned is that of the first). */ aligned2?: boolean; + /** Cam: the profile's faces after a (all on a's component); b is the follower. */ + chain?: FaceRef[]; /** * Distance and angle mates: the entities move freely between these values * (value is where they were set up). Hinges: the turn from where the hinge @@ -113,10 +123,12 @@ export interface Mate { /** * Gear: 'ratio' when the values are a ratio rather than pitch diameters. * Rack and pinion: 'revolution' when value is the rack's travel per turn - * rather than the pinion's pitch diameter. + * rather than the pinion's pitch diameter. Universal joint: 'point' when + * the shafts' axes meet at a joint point, value along a's axis from its + * entity. */ - by?: 'ratio' | 'revolution'; - /** Gear, rack and pinion: the other way round. Screw: a left-hand thread. */ + by?: 'ratio' | 'revolution' | 'point'; + /** Gear, rack and pinion: the other way round. Screw: a left-hand thread. Cam: the flat follower's other side. */ reverse?: boolean; } @@ -133,9 +145,9 @@ export interface MotionMotor { id: Id; name: string; kind: 'rotary' | 'linear' | 'mate'; - /** Rotary and linear: the axis or direction, on the component it moves. */ + /** Rotary and linear: the axis or direction, on the component it moves (or `mate`). */ ref?: MateRef; - /** Mate driver: the distance or angle mate. */ + /** Mate driver: the distance or angle mate. Rotary: a hinge it turns; linear: a slider it moves (b relative to a). */ mate?: Id; profile: MotionProfile; /** Constant: speed (mm/s, deg/s, or rpm when `rpm`). */ @@ -187,7 +199,7 @@ export interface AssemblyDocument extends Omit = { coincident: 'Coincident', parallel: 'Parallel', perpendicular: 'Perpendicular', distance: 'Distance', angle: 'Angle', concentric: 'Concentric', tangent: 'Tangent', lock: 'Lock', - hinge: 'Hinge', gear: 'Gear', rackPinion: 'Rack Pinion', screw: 'Screw', width: 'Width', slot: 'Slot', + hinge: 'Hinge', slider: 'Slider', gear: 'Gear', rackPinion: 'Rack Pinion', screw: 'Screw', width: 'Width', slot: 'Slot', cam: 'Cam', universal: 'Universal Joint', }; /** Distinct component colours, picked in turn for each new part. */ @@ -257,6 +269,7 @@ function validMateRef(v: unknown, comps: Set): boolean { if (!isStr(v.comp) || !comps.has(v.comp)) return false; if ('face' in v) return validFaceRef(v.face); if ('edge' in v) return validEdgeRef(v.edge); + if ('point' in v) return isVec(v.point); return true; } @@ -265,17 +278,26 @@ function validMateExtras(m: Record, comps: Set): boolea const t = m.type as MateType; const has = (k: string) => m[k] !== undefined; const isBool = (k: string) => !has(k) || typeof m[k] === 'boolean'; - if (has('a2') && (!['hinge', 'width', 'slot'].includes(t) || !validMateRef(m.a2, comps))) return false; - if (has('b2') && (!['hinge', 'width'].includes(t) || !validMateRef(m.b2, comps))) return false; + if (has('a2') && (!['hinge', 'width', 'slot', 'slider'].includes(t) || !validMateRef(m.a2, comps))) return false; + if (has('b2') && (!['hinge', 'width', 'slider'].includes(t) || !validMateRef(m.b2, comps))) return false; if (!isBool('aligned2') || !isBool('reverse')) return false; if (has('value2') && (t !== 'gear' || !isParam(m.value2))) return false; - if (has('limit') && (!['distance', 'angle', 'hinge'].includes(t) || !isObj(m.limit) || !isParam(m.limit.min) || !isParam(m.limit.max))) return false; - if (has('by') && !((t === 'gear' && m.by === 'ratio') || (t === 'rackPinion' && m.by === 'revolution'))) return false; + if (has('limit') && (!['distance', 'angle', 'hinge', 'slider'].includes(t) || !isObj(m.limit) || !isParam(m.limit.min) || !isParam(m.limit.max))) return false; + if (has('by') && !((t === 'gear' && m.by === 'ratio') || (t === 'rackPinion' && m.by === 'revolution') || (t === 'universal' && m.by === 'point'))) return false; + // A cam's other profile faces: faces of its component. + if (has('chain') && (t !== 'cam' || !Array.isArray(m.chain) || m.chain.length > 500 || !m.chain.every(validFaceRef) || !isObj(m.a) || !('face' in m.a))) return false; + // Vertices are followers of cams only. + if ([m.a, m.a2, m.b2, ...(t === 'cam' ? [] : [m.b])].some((r) => isObj(r) && 'point' in r)) return false; if (!isMechanical(t)) return !has('aligned2') && !has('reverse'); - // What each mechanical mate needs; its entities are faces, edges or planes (not whole components). - const needs: Record = { hinge: ['a2', 'b2'], width: ['a2', 'b2'], slot: ['a2'], gear: ['value', 'value2'], rackPinion: ['value'], screw: ['value'] }; + // What each mechanical mate needs; its entities are faces, edges, vertices or planes (not whole components). + const needs: Record = { + hinge: ['a2', 'b2'], slider: ['rel'], width: ['a2', 'b2'], slot: ['a2'], gear: ['value', 'value2'], rackPinion: ['value'], screw: ['value'], cam: [], universal: ['rel'], + }; if (needs[t].some((k) => !has(k))) return false; - return [m.a, m.b, m.a2, m.b2].every((r) => r === undefined || (isObj(r) && ('plane' in r || 'face' in r || 'edge' in r))); + // A slider takes one entity, or two faces, on each component; a joint point has its offset. + if (t === 'slider' && has('a2') !== has('b2')) return false; + if (t === 'universal' && (m.by === 'point') !== has('value')) return false; + return [m.a, m.b, m.a2, m.b2].every((r) => r === undefined || (isObj(r) && ('plane' in r || 'face' in r || 'edge' in r || 'point' in r))); } function validMotor(v: unknown, comps: Set, mates: Set): boolean { @@ -285,8 +307,10 @@ function validMotor(v: unknown, comps: Set, mates: Set): boolean const need = v.profile === 'constant' ? ['speed'] : v.profile === 'oscillate' ? ['amplitude', 'frequency'] : ['from', 'to']; if (need.some((k) => v[k] === undefined)) return false; if (v.kind === 'mate') return isStr(v.mate) && mates.has(v.mate) && v.ref === undefined && v.rpm === undefined; - // Rotary and linear motors move the component of a face or edge, at a constant speed or back and forth. - return v.mate === undefined && v.profile !== 'ramp' && (v.rpm === undefined || v.kind === 'rotary') && isObj(v.ref) && isStr(v.ref.comp) && ('face' in v.ref || 'edge' in v.ref) && validMateRef(v.ref, comps); + // Rotary and linear motors move the component of a face or edge (or turn a hinge, move a slider), at a constant speed or back and forth. + if (v.profile === 'ramp' || (v.rpm !== undefined && v.kind !== 'rotary')) return false; + if (v.mate !== undefined) return isStr(v.mate) && mates.has(v.mate) && v.ref === undefined; + return isObj(v.ref) && isStr(v.ref.comp) && ('face' in v.ref || 'edge' in v.ref) && validMateRef(v.ref, comps); } function validSource(v: unknown): v is PartSource | null { @@ -467,8 +491,11 @@ export function nextPartColor(doc: AssemblyDocument): string { return PART_COLORS.find((c) => !used.has(c)) ?? PART_COLORS[doc.parts.length % PART_COLORS.length]; } -/** The entities a mate references (its second pair too). */ -export const mateRefs = (m: Mate): MateRef[] => [m.a, m.b, ...(m.a2 ? [m.a2] : []), ...(m.b2 ? [m.b2] : [])]; +/** The entities a mate references (its second pair, and a cam's other faces, too). */ +export const mateRefs = (m: Mate): MateRef[] => [ + m.a, m.b, ...(m.a2 ? [m.a2] : []), ...(m.b2 ? [m.b2] : []), + ...(m.chain && 'comp' in m.a ? m.chain.map((face) => ({ comp: (m.a as { comp: Id }).comp, face })) : []), +]; /** The components a mate references. */ export function mateComps(m: Mate): Id[] { diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 8c526a4497..a32dd5a252 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, mateBodies, mateMeasure, matesMoving, placeGeo, relativePlacement, turnAbout } from '../src/assembly/solver'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, relativePlacement, turnAbout } from '../src/assembly/solver'; import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, mateSeries, pointPath, profileOf, resultsCsv, turnPath, vectorDerivatives } from '../src/assembly/motion'; import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; import type { MateType, Placement } from '../src/model/assembly'; @@ -353,3 +353,168 @@ describe('motion studies', () => { expect(len(sub(pointPath({ times: [0], frames: [new Map([['a', { p: [1, 2, 3], q: [0, 0, 0, 1] }]])], stop: null, duration: 1 }, 'a', [1, 0, 0])[0], [2, 2, 3]))).toBe(0); }); }); + +describe('slider, cam and universal joint mates', () => { + const X: Vec3 = [1, 0, 0], Y: Vec3 = [0, 1, 0]; + const line = (p: Vec3, d: Vec3): Geo => ({ kind: 'line', p, d }); + const at0: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + /** A slider of `b` along x on the ground's x axis (straight edges), from where b is. */ + const slider = (b: SolverBody, extra: Partial = {}) => mate('slider', ['g', line([0, 0, 0], X)], [b.id, line([0, 0, 0], X)], { rel: relativePlacement(at0, b.placement), ...extra }); + + it('a slider on straight edges leaves one move along them, no turn, and stops at its travel limits', () => { + const blk = body('blk', false, [5, 3, -2]); + const s = new MateSolver([body('g', true), blk], [slider(blk, { limit: { min: -10, max: 20 } })]); + const r = s.analyze(); + expect(r.status).toBe('under'); + expect(r.dof).toBe(1); + const p = r.placements.get('blk')!; + expect(Math.hypot(p.p[1], p.p[2])).toBeLessThan(1e-6); + expect(p.q[3]).toBeCloseTo(1, 9); + // Dragged up and along: it only slides, and stops 20 mm from where it was added. + let pl = r.placements; + for (let k = 1; k <= 8; k++) pl = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [5 + 5 * k, 30, 0] } }, s.mates, pl).placements; + expect(pl.get('blk')!.p[0]).toBeCloseTo(25, 4); + expect(pl.get('blk')!.p[1]).toBeCloseTo(0, 6); + expect(mateMeasure(s.mates[0], pl)!.value).toBeCloseTo(20, 4); + // A turn about the edge is held too. + const turned = s.solve({ drag: { kind: 'rotate', body: 'blk', q: qAxisAngle(X, 0.8) } }, s.mates, pl); + expect(turned.placements.get('blk')!.q[3]).toBeCloseTo(1, 6); + }); + + it('a slider on two faces of each component slides along the line where they meet', () => { + const m = mate('slider', ['g', plane([0, 0, 0], Y)], ['blk', plane([0, 0, 0], [0, -1, 0])], { + a2: { body: 'g', geo: plane([0, 0, 0], Z) }, b2: { body: 'blk', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned: false, aligned2: false, rel: at0, + }); + const r = new MateSolver([body('g', true), body('blk', false, [7, 4, 3], qAxisAngle(normalize([1, 1, 1]), 0.2))], [m]).analyze(); + expect(r.dof).toBe(1); + const p = r.placements.get('blk')!; + expect(Math.hypot(p.p[1], p.p[2])).toBeLessThan(1e-6); + const bad = { ...m, a2: { body: 'g', geo: plane([0, 5, 0], Y) } }; + expect(new MateSolver([body('g', true), body('blk', false)], [bad]).analyze().invalid.get(bad.id)).toMatch(/must not be parallel/); + }); + + it('motors on a slider and on a hinge drive them directly', () => { + const blk = body('blk', false, [0, 0, 0]); + const sl = slider(blk); + const lin: MotorInput = { id: 'mo', name: 'LinearMotor1', kind: 'linear', on: sl, at: profileOf('linear', { profile: 'constant', speed: 4 }, 3) }; + const res = computeMotion({ bodies: [body('g', true), blk], mates: [sl], motors: [lin], duration: 3, fps: 10, scale: 100 }); + expect(res.stop).toBeNull(); + res.frames.forEach((f, i) => expect(f.get('blk')!.p[0]).toBeCloseTo(4 * res.times[i], 6)); + // A hinge whose second component is fixed: the first turns, the other way. + const h = hinge('arm', [0, 0, 0], 'g', [0, 0, 0]); + const rot: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: h, at: profileOf('rotary', { profile: 'constant', speed: 90 }, 1) }; + const r2 = computeMotion({ bodies: [body('g', true), body('arm', false)], mates: [h], motors: [rot], duration: 1, fps: 20, scale: 100 }); + expect(r2.stop).toBeNull(); + expect(degreesAbout(turnPath(r2, 'arm'), Z)[20]).toBeCloseTo(-90, 5); + }); + + /** A cam turning on a hinge about z at the origin; a follower sliding along y on the line x = 0. */ + const camRig = (profile: Geo, follower: Geo, y0: number) => { + const fol = body('fol', false, [0, y0, 0]); + const mates = [ + hinge('g', [0, 0, 0], 'cam', [0, 0, 0]), + mate('slider', ['g', line([0, 0, 0], Y)], ['fol', line([0, 0, 0], Y)], { rel: relativePlacement(at0, fol.placement) }), + mate('cam', ['cam', profile], ['fol', follower]), + ]; + const drive: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: mates[0], at: profileOf('rotary', { profile: 'constant', speed: 90 }, 4) }; + return { bodies: [body('g', true), body('cam', false), fol], mates, motors: [drive] }; + }; + const e = 6, R = 20; + /** An eccentric: a round face of radius R whose axis is e from the turning axis (its low side up at first). */ + const eccentric = camProfile(Z, [{ c: [0, -e, 0], r: R }], []); + + it('an eccentric cam lifts a flat follower by e(1 − cos θ) over a turn', () => { + expect(eccentric.circle).not.toBeNull(); + const rig = camRig(eccentric, plane([0, 0, 0], [0, -1, 0]), R - e); + expect(new MateSolver(rig.bodies, rig.mates).analyze().dof).toBe(1); + const res = computeMotion({ ...rig, duration: 4, fps: 60, scale: 100 }); + expect(res.stop).toBeNull(); + const theta = degreesAbout(turnPath(res, 'cam'), Z).map((d) => (d * Math.PI) / 180); + expect(theta[240]).toBeCloseTo(2 * Math.PI, 6); + res.frames.forEach((f, i) => expect(f.get('fol')!.p[1] - (R - e)).toBeCloseTo(e * (1 - Math.cos(theta[i])), 7)); + }); + + it('roller and knife-edge followers on an eccentric match the closed form', () => { + const rho = 5; + const lift = (th: number, r: number) => { const cx = e * Math.sin(th), cy = -e * Math.cos(th); return cy + Math.sqrt(r * r - cx * cx); }; + for (const [follower, r] of [[axis([0, 0, 0], Z, rho), R + rho], [{ kind: 'point', p: [0, 0, 0] } as Geo, R]] as [Geo, number][]) { + const rig = camRig(eccentric, follower, r - e); + const res = computeMotion({ ...rig, duration: 4, fps: 60, scale: 100 }); + expect(res.stop).toBeNull(); + const theta = degreesAbout(turnPath(res, 'cam'), Z).map((d) => (d * Math.PI) / 180); + res.frames.forEach((f, i) => expect(f.get('fol')!.p[1]).toBeCloseTo(lift(theta[i], r), 7)); + } + }); + + it('a lobed cam (arcs and corners) lifts a flat follower to its nose; a hollow profile is refused', () => { + // A base circle of 20 and a nose of 5 at 25 above the axis, joined by tangent lines (touching both at 90° ± 53.13°). + const p = (r: number, deg: number, c: Vec3 = [0, 0, 0]): Vec3 => [c[0] + r * Math.cos((deg * Math.PI) / 180), c[1] + r * Math.sin((deg * Math.PI) / 180), 0]; + const t = (Math.acos(0.6) * 180) / Math.PI, nose: Vec3 = [0, 25, 0]; + const lobed = camProfile(Z, [{ c: [0, 0, 0], r: 20, ends: [p(20, 90 + t), p(20, 90 - t), p(20, 270)] }, { c: nose, r: 5, ends: [p(5, 90 - t, nose), p(5, 90 + t, nose), p(5, 90, nose)] }], []); + expect(lobed.concave).toBeLessThan(1e-9); + const rig = camRig(lobed, plane([0, 0, 0], [0, -1, 0]), 30); + const res = computeMotion({ ...rig, duration: 2, fps: 60, scale: 100 }); + expect(res.stop).toBeNull(); + expect(res.frames[0].get('fol')!.p[1]).toBeCloseTo(30, 6); + // Half a turn: the base circle under the follower. + expect(res.frames[120].get('fol')!.p[1]).toBeCloseTo(20, 7); + // A notch: corners of a square with one side dented in. + const notched = camProfile(Z, [], [[-10, -10, 0], [10, -10, 0], [10, 10, 0], [0, 4, 0], [-10, 10, 0]]); + expect(notched.concave).toBeCloseTo(6, 9); + const bad = new MateSolver(rig.bodies, [...rig.mates.slice(0, 2), mate('cam', ['cam', notched], ['fol', plane([0, 0, 0], [0, -1, 0])])]).analyze(); + expect([...bad.invalid.values()][0]).toMatch(/hollow 6 mm deep/); + }); + + /** Two shafts on hinges, meeting at the origin: a along z, b at β to it in the xz plane. */ + const uJoint = (betaDeg: number) => { + const b = (betaDeg * Math.PI) / 180; + const db: Vec3 = [Math.sin(b), 0, Math.cos(b)]; + const qb = qAxisAngle(Y, b); + const bodies = [body('g', true), body('A', false), body('B', false, [0, 0, 0], qb)]; + const mates = [ + hinge('g', [0, 0, 0], 'A', [0, 0, 0]), + mate('hinge', ['g', { kind: 'axis', p: [0, 0, 0], d: db, r: 2, surface: 'cylinder' }], ['B', axis([0, 0, 0])], { a2: { body: 'g', geo: plane([0, 0, 0], db) }, b2: { body: 'B', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: false }), + mate('universal', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0])], { rel: relativePlacement(at0, { p: [0, 0, 0], q: qb }) }), + ]; + return { bodies, mates, db, b }; + }; + + it('a universal joint turns its output by atan(tan φ / cos β) over a full turn, with that velocity ratio', () => { + const u = uJoint(30); + expect(new MateSolver(u.bodies, u.mates).analyze().dof).toBe(1); + const motor: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: u.mates[0], at: profileOf('rotary', { profile: 'constant', speed: 90 }, 4) }; + const res = computeMotion({ bodies: u.bodies, mates: u.mates, motors: [motor], duration: 4, fps: 90, scale: 100 }); + expect(res.stop).toBeNull(); + const phi = degreesAbout(turnPath(res, 'A'), Z).map((d) => (d * Math.PI) / 180); + const out = degreesAbout(turnPath(res, 'B'), u.db).map((d) => (d * Math.PI) / 180); + // The closed form, unwrapped past ±90° and ±180°. + let prev = 0, acc = 0; + const expected = phi.map((f) => { const a = Math.atan2(Math.sin(f), Math.cos(u.b) * Math.cos(f)); let d = a - prev; d -= 2 * Math.PI * Math.round(d / (2 * Math.PI)); acc += d; prev = a; return acc; }); + expect(phi[360]).toBeCloseTo(2 * Math.PI, 6); + out.forEach((v, i) => expect(v).toBeCloseTo(expected[i], 6)); + expect(out[360]).toBeCloseTo(2 * Math.PI, 6); + // Velocity ratio from the frames against cos β / (cos²β cos²φ + sin²φ). + const w1 = derivatives(res.times, phi).d1, w2 = derivatives(res.times, out).d1; + for (const i of [0, 45, 90, 135, 200, 300]) { + const f = phi[i], k = Math.cos(u.b) / (Math.cos(u.b) ** 2 * Math.cos(f) ** 2 + Math.sin(f) ** 2); + expect(w2[i] / w1[i]).toBeCloseTo(k, 2); + } + }); + + it('a universal joint with straight shafts turns 1:1, and can hold its joint point', () => { + const u = uJoint(0); + const motor: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: u.mates[0], at: profileOf('rotary', { profile: 'constant', speed: 120 }, 3) }; + const res = computeMotion({ bodies: u.bodies, mates: u.mates, motors: [motor], duration: 3, fps: 30, scale: 100 }); + const a = degreesAbout(turnPath(res, 'A'), Z), b = degreesAbout(turnPath(res, 'B'), Z); + a.forEach((v, i) => expect(b[i]).toBeCloseTo(v, 6)); + expect(a[90]).toBeCloseTo(360, 5); + // Free shafts with a joint point 10 along a's axis: b's axis passes through it. + const joint = mate('universal', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0])], { rel: relativePlacement(at0, { p: [3, 4, 30], q: qAxisAngle(Y, 0.4) }), by: 'point', value: 10 }); + const r = new MateSolver([body('A', true), body('B', false, [3, 4, 30], qAxisAngle(Y, 0.4))], [joint]).analyze(); + expect(r.dof).toBe(3); + const pb = r.placements.get('B')!; + const db = qRotate(pb.q, Z); + const off = sub([0, 0, 10], pb.p); + expect(len([off[1] * db[2] - off[2] * db[1], off[2] * db[0] - off[0] * db[2], off[0] * db[1] - off[1] * db[0]])).toBeLessThan(1e-6); + }); +}); diff --git a/src/parametric/tests/assembly-model.test.ts b/src/parametric/tests/assembly-model.test.ts index 0ddea582b3..8276319811 100644 --- a/src/parametric/tests/assembly-model.test.ts +++ b/src/parametric/tests/assembly-model.test.ts @@ -232,4 +232,39 @@ describe('mechanical mates and motion studies in files', () => { const back = parseAssembly(JSON.stringify({ ...JSON.parse(text), studies: [{ ...JSON.parse(text).studies[0], motors: [{ ...JSON.parse(text).studies[0].motors[0], extra: 1 }] }] })); expect('extra' in back.studies![0].motors[0]).toBe(false); }); + + it('round-trips sliders, cams and universal joints, and motors on hinges and sliders; refuses them malformed', () => { + const doc = kinematic(); + const edge = { name: 'e', sig: { type: 'line', m: [0, 0, 0] as [number, number, number], len: 5 } }; + const rel = { p: [1, 2, 3] as [number, number, number], q: [0, 0, 0, 1] as [number, number, number, number] }; + doc.mates.push( + { id: 'm40', name: 'Slider1', type: 'slider', a: { comp: 'c3', edge }, b: { comp: 'c4', edge }, aligned: true, rel, limit: { min: -5, max: '=Gap*10' } }, + { id: 'm41', name: 'Slider2', type: 'slider', a: { comp: 'c3', face: face('f1') }, a2: { comp: 'c3', face: face('f2') }, b: { comp: 'c4', face: face('f3') }, b2: { comp: 'c4', face: face('f4') }, aligned: false, aligned2: true, rel }, + { id: 'm42', name: 'Cam1', type: 'cam', a: { comp: 'c3', face: cyl('lobe') }, chain: [face('flank'), cyl('nose')], b: { comp: 'c4', point: [1, 2, 3] }, aligned: true, flip: true }, + { id: 'm43', name: 'Universal Joint1', type: 'universal', a: { comp: 'c3', face: cyl('h') }, b: { comp: 'c4', face: cyl('k') }, aligned: true, rel, by: 'point', value: '=Gap' }, + ); + doc.studies![0].motors.push( + { id: 'o44', name: 'RotaryMotor2', kind: 'rotary', mate: 'm20', profile: 'constant', speed: 30 }, + { id: 'o45', name: 'LinearMotor2', kind: 'linear', mate: 'm40', profile: 'oscillate', amplitude: 3, frequency: 1 }, + ); + const text = serializeDocument(doc as never); + expect(parseAssembly(text)).toEqual({ ...doc, nextId: 46 }); + const edit = (patch: (d: Record) => void) => { const raw = JSON.parse(text); patch(raw); return () => parseAssembly(JSON.stringify(raw)); }; + const mate = (id: string) => (d: Record) => d.mates.find((m: { id: string }) => m.id === id); + expect(edit((d) => { delete mate('m40')(d).rel; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m41')(d).b2; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m40')(d).limit = { min: 'x' , max: null }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).chain = 'flank'; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).chain = [{ name: 'x' }]; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).b = { comp: 'c4', point: [1, 2] }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).a = { comp: 'c3', point: [1, 2, 3] }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).chain = [face('x')]; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).b = { comp: 'c5', point: [0, 0, 0] }; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m43')(d).value; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m43')(d).rel; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m43')(d).by = 'ratio'; })).toThrow(/invalid mate/); + expect(edit((d) => { d.studies[0].motors[3].ref = d.studies[0].motors[0].ref; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[3].mate = 'm99'; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[4].profile = 'ramp'; d.studies[0].motors[4].from = 0; d.studies[0].motors[4].to = 1; })).toThrow(/invalid motor/); + }); }); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 467b6da8d4..72c7b9039d 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -18,6 +18,16 @@ const disc = (r: number) => [ { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: circle('k', 0, 0, r), constraints: [] }, extrude('E1', 'S1', 5), ]; +/** An eccentric cam: a Ø40 disc whose Ø8 bore is 5 off its centre, 10 thick. */ +const CAM = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [...circle('k', 5, 0, 20), ...circle('hb', 0, 0, 4)], constraints: [] }, + extrude('E1', 'S1', 10), +]; +/** A Ø8 shaft, 30 long. */ +const SHAFT = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: circle('k', 0, 0, 4), constraints: [] }, + extrude('E1', 'S1', 30), +]; /** A 100 × 10 × 10 bar (a rack, or a tab). */ const BAR = [ { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: pts('r', [[0, 0], [100, 0], [100, 10], [0, 10]]), constraints: [] }, @@ -377,3 +387,145 @@ test('limit, width, slot, screw and rack and pinion mates through the Mate panel await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('slider, cam follower and universal joint through the Mate panel; motors on a slider and a hinge', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Cam', CAM], ['Shaft', SHAFT]], ['Plate', 'Bar', 'Cam', 'Shaft', 'Shaft']); + await built(page, ['Plate<1>', 'Bar<1>', 'Cam<1>', 'Shaft<1>', 'Shaft<2>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + const pm = page.locator('.pm'); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + + // Slider: the bar flush on the plate's front and right faces, sliding along y, at most 25 mm either way. + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await expect(pm.getByRole('group', { name: 'Second component' })).toHaveClass(/active/); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap0' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await pm.getByRole('checkbox', { name: /Limit the travel/ }).check(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('25'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Slider1/ })).toBeVisible(); + const bar = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + return m.solved.get(m.doc.components.find((c) => c.name === 'Bar<1>')!.id)!.p; + }); + expect((await bar())[0]).toBeCloseTo(0, 4); + expect((await bar())[2]).toBeCloseTo(10, 4); + // A linear motor on the slider at 10 mm/s: it stops at the limit after 2.5 s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Slider1 (Slider)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await expect(pm.getByRole('listitem').filter({ hasText: 'LinearMotor1' })).toContainText('Slider1: 10 mm/s'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert').filter({ hasText: /Slider1 reached its limit at 2\.5\d* s/ })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + // Without the limit, for the cam to push it. + await tree.getByRole('treeitem', { name: /^Slider1/ }).dblclick(); + await pm.getByRole('checkbox', { name: /Limit the travel/ }).uncheck(); + await pm.getByRole('button', { name: 'OK' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Slider1')!.limit)).toBeUndefined(); + + // The cam on a hinge in the plate's first hole. + await select(page, [{ comp: 'Cam<1>', face: 'E1:side:hb' }, { comp: 'Plate<1>', face: 'E1:side:h1' }]); + await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Cam<1>', face: 'E1:cap0' }); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Hinge1/ })).toBeVisible(); + + // Cam: the eccentric's round face, the bar's bottom face as a flat follower. + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + await openMate(page, 'cam'); + await pick(page, { comp: 'Cam<1>', face: 'E1:side:k' }); + await pm.getByRole('group', { name: 'Follower' }).click(); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl0' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Cam1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /^Cam1/ })).not.toHaveAttribute('aria-description', /Error/); + + // A rotary motor on the hinge turns the cam a full turn: the bar's bottom stays on the eccentric's top. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge1 (Hinge)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('90'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('4'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 121 frames' })).toBeVisible(); + const follow = await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const res = (a.panel as unknown as { result(): { frames: Map[] } }).result(); + const id = (n: string) => m.doc.components.find((c) => c.name === n)!.id; + const rot = (q: number[], v: number[]) => { + const [x, y, z, w] = q; + const t = [2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])]; + return [v[0] + w * t[0] + y * t[2] - z * t[1], v[1] + w * t[1] + z * t[0] - x * t[2], v[2] + w * t[2] + x * t[1] - y * t[0]]; + }; + let worst = 0, lo = Infinity, hi = -Infinity; + for (const f of res.frames) { + const cam = f.get(id('Cam<1>'))!, b = f.get(id('Bar<1>'))!; + // The eccentric's top: its centre (5 off the bore, in the cam) plus its radius. + const top = rot(cam.q, [5, 0, 0])[1] + cam.p[1] + 20; + worst = Math.max(worst, Math.abs(b.p[1] - top)); + lo = Math.min(lo, b.p[1]); hi = Math.max(hi, b.p[1]); + } + return { worst, lift: hi - lo }; + }); + expect(follow.worst).toBeLessThan(1e-6); + // The follower rises and falls by twice the eccentricity. + expect(follow.lift).toBeCloseTo(10, 3); + await pm.getByRole('button', { name: 'Cancel' }).click(); + + // Universal joint between the two shafts, with a joint point. + await select(page, [{ comp: 'Shaft<1>', face: 'E1:side:k' }, { comp: 'Shaft<2>', face: 'E1:side:k' }]); + await openMate(page, 'universal'); + await expect(pm.getByRole('group', { name: 'Shafts' })).toContainText('Shaft<2>'); + await pm.getByRole('checkbox', { name: /Joint point/ }).check(); + await pm.getByRole('textbox', { name: 'Joint point offset (along the first shaft)' }).fill('15'); + await pm.getByRole('textbox', { name: 'Joint point offset (along the first shaft)' }).press('Enter'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Universal Joint1/ })).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Universal Joint1'))).toMatchObject({ type: 'universal', by: 'point', value: 15, rel: { q: expect.any(Array) } }); + + // Flip and suppress from the Mates folder; undo; the edits survive saving and opening again. + await tree.getByRole('treeitem', { name: /^Cam1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Flip Follower Face' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Cam1')!.flip)).toBe(true); + await page.keyboard.press('Meta+z'); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Cam1')!.flip)).toBeUndefined(); + await tree.getByRole('treeitem', { name: /^Universal Joint1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Universal Joint1/ })).toHaveAttribute('aria-description', /Suppressed/); + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const name = (await page.title()).replace(' - Parametric', ''); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('new'); }); + await expect(page).toHaveTitle(/^Part\d+ - Parametric$/); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('open'); }); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(page).toHaveTitle(`${name} - Parametric`); + for (const n of [/^Slider1/, /^Hinge1/, /^Cam1/]) await expect(tree.getByRole('treeitem', { name: n })).not.toHaveAttribute('aria-description', /Error|Suppressed/); + await expect(tree.getByRole('treeitem', { name: /^Universal Joint1/ })).toHaveAttribute('aria-description', /Suppressed/); + // Edited from the tree, the cam shows its faces and follower. + await tree.getByRole('treeitem', { name: /^Cam1/ }).dblclick(); + await expect(pm.getByRole('group', { name: 'Cam faces' })).toContainText('Face (cylinder) of Cam<1>'); + await expect(pm.getByRole('group', { name: 'Follower' })).toContainText('Face (plane) of Bar<1>'); + expect(await axeViolations(page)).toEqual([]); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From 76626de1275a4f7dc56fbd5100605f161c9f2e83 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:25:44 -0700 Subject: [PATCH 018/116] Parametric: analysis code and test cleanup --- src/parametric/src/app/fea/index.ts | 3 +-- src/parametric/src/app/fea/panels.ts | 4 +--- src/parametric/src/fea/amg.ts | 2 +- src/parametric/src/fea/static.ts | 4 +--- src/parametric/tests/fea-solver.test.ts | 8 ++------ 5 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/parametric/src/app/fea/index.ts b/src/parametric/src/app/fea/index.ts index 7c5d34a7c7..f9e1e25557 100644 --- a/src/parametric/src/app/fea/index.ts +++ b/src/parametric/src/app/fea/index.ts @@ -5,7 +5,7 @@ // costs nothing more to open. import { FIXTURE_ICONS, FIXTURE_LABELS, LOAD_ICONS, type FixtureType, type FeaLoadType, type StaticStudy } from '../../model/fea'; -import type { FaceRef, Id } from '../../model/types'; +import type { FaceRef } from '../../model/types'; import { addIcons } from '../../ui/icons'; import { toast } from '../../ui/overlay'; import type { App, AppHooks } from '../app'; @@ -161,4 +161,3 @@ export function feaTreeRows(app: App, expanded: (key: string) => boolean): CamRo return rows; } -export type { Id }; diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 12ee2a3147..997db275ff 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -105,7 +105,6 @@ export class StudyPanel extends FeaPanel { const matText = !mat ? 'No material chosen.' : el ? `${mat.name}: E ${formatNumber(el.E / 1000, 1)} GPa, ν ${el.nu}, yield ${el.yield} MPa` : `${mat.name}: no elastic properties (cannot be analyzed).`; const matBtn = h('button', { class: 'btn small', type: 'button', onclick: () => app.commands.run('material') }, icon('material', 16), 'Material...'); // Mesh: coarse to fine. - const sizes = ws.sizes(this.fineness); const u = feaUnits(app.store.doc.units); const slider = h('input', { type: 'range', min: '0', max: '1', step: '0.05', value: String(this.fineness), 'aria-label': 'Mesh density, coarse to fine', class: 'fea-slider' }) as HTMLInputElement; const sizeText = h('div', { class: 'field-label', 'aria-live': 'polite' }); @@ -136,12 +135,11 @@ export class StudyPanel extends FeaPanel { if (!m.key.startsWith(`${app.geometryVersion}|`)) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part changed since it was meshed.')); } if (ws.error?.message && !ws.busy) stats.push(h('p', { class: 'pm-msg error', role: 'alert' }, ws.error.message)); - void sizes; return [ section('Study', [h('label', { class: 'field-label' }, 'Name'), nameInput, h('p', { class: 'field-label' }, 'Linear static: small displacements, linear elastic isotropic material.')], { icon: 'feaStudy' }), section('Material', [h('p', { class: 'field-label fea-material' }, matText), matBtn], { icon: 'material' }), section('Mesh', [h('div', { class: 'row fea-slider-row' }, h('span', { class: 'field-label' }, 'Coarse'), slider, h('span', { class: 'field-label' }, 'Fine')), sizeText, h('div', { class: 'row' }, meshBtn, runBtn), ...stats], { icon: 'feaMesh' }), - section('Study', [h('button', { class: 'btn small danger', type: 'button', onclick: () => ws.deleteStudy() }, icon('trash', 16), 'Delete Study')], { collapsed: true }), + section('Delete', [h('button', { class: 'btn small danger', type: 'button', onclick: () => ws.deleteStudy() }, icon('trash', 16), 'Delete Study')], { collapsed: true }), ]; } diff --git a/src/parametric/src/fea/amg.ts b/src/parametric/src/fea/amg.ts index 19ccf45f26..49470313a8 100644 --- a/src/parametric/src/fea/amg.ts +++ b/src/parametric/src/fea/amg.ts @@ -229,7 +229,7 @@ export function smoothedAggregation(A: BlockMatrix, coords: Float64Array, opts: levels.push(lvl); if (N <= coarsest) break; let t = performance.now(); - const lap = (what: string) => { const n = performance.now(); opts.debug?.(`level ${depth} ${what}: ${(n - t).toFixed(0)} ms`); t = n; }; + const lap = (what: string) => { if (!opts.debug) return; const n = performance.now(); opts.debug(`level ${depth} ${what}: ${(n - t).toFixed(0)} ms`); t = n; }; const agg = aggregate(cur, depth === 0 ? THETA : THETA * 0.5 ** depth); lap(`aggregate (${agg.count} of ${cur.n})`); if (agg.count * 6 >= N * 0.8 || agg.count < 2) break; diff --git a/src/parametric/src/fea/static.ts b/src/parametric/src/fea/static.ts index 653331b4da..8d9cfca22d 100644 --- a/src/parametric/src/fea/static.ts +++ b/src/parametric/src/fea/static.ts @@ -6,7 +6,7 @@ // Units: millimetres, newtons, megapascals (N/mm^2), tonnes per cubic // millimetre for density (so density times mm/s^2 is N/mm^3). -import { type BlockMatrix, type Preconditioner, blockAt, blockJacobi, matvec, meshPattern, pcg, smoothedAggregation } from './amg'; +import { type Preconditioner, blockAt, blockJacobi, meshPattern, pcg, smoothedAggregation } from './amg'; import { addBodyForce, elementNodeStrains, elementStiffness, integrateTriangle, lame, principal } from './elements'; import type { TetMesh } from './mesher'; @@ -500,5 +500,3 @@ export function solveStatic(mesh: TetMesh, input: StaticInput, progress: (stage: }; } -export type { BlockMatrix }; -void matvec; diff --git a/src/parametric/tests/fea-solver.test.ts b/src/parametric/tests/fea-solver.test.ts index b1c72935c1..9c4ebc30c4 100644 --- a/src/parametric/tests/fea-solver.test.ts +++ b/src/parametric/tests/fea-solver.test.ts @@ -52,16 +52,14 @@ describe('static analysis accuracy', () => { const fixed = planar(faces, [-1, 0, 0]), tip = planar(faces, [1, 0, 0]); const F = 500, L = 200, I = (10 * 20 ** 3) / 12; const input: StaticInput = { ...STEEL, fixtures: [{ kind: 'fixed', faces: [fixed] }], loads: [{ kind: 'force', faces: [tip], total: F, dir: [0, -1, 0] }] }; - const r = solveStatic(mesh, input, undefined, console.log); + const r = solveStatic(mesh, input); const theory = (F * L ** 3) / (3 * STEEL.E * I); const tipDy = at(mesh.nodes, r.U, [200, 10, 5], 3, 1); - console.log(`cantilever: ${r.dofs} dof, ${r.iterations} iterations, ${r.solver}, ms ${JSON.stringify(r.ms)}; tip ${tipDy} vs ${-theory}`); expect(-tipDy / theory).toBeGreaterThan(0.99); expect(-tipDy / theory).toBeLessThan(1.03); // Bending stress at mid span on the top and bottom fibres: M c / I. const sigma = (F * (L / 2) * 10) / I; const top = at(mesh.nodes, r.stress, [100, 20, 5], 6, 0), bottom = at(mesh.nodes, r.stress, [100, 0, 5], 6, 0); - console.log(`bending stress ${top}, ${bottom} vs ${sigma}`); expect(top / sigma).toBeCloseTo(1, 1); expect(-bottom / sigma).toBeCloseTo(1, 1); // Equilibrium: the reaction balances the load. @@ -86,7 +84,6 @@ describe('static analysis accuracy', () => { expect(ux / ((F * L) / (A * STEEL.E))).toBeCloseTo(1, 2); let lo = Infinity, hi = -Infinity; for (let v = 0; v < mesh.nodes.length / 3; v++) { lo = Math.min(lo, r.stress[v * 6]); hi = Math.max(hi, r.stress[v * 6]); } - console.log(`bar: stress ${lo}..${hi} vs ${F / A}; elongation ${ux}`); expect(Math.abs(lo / (F / A) - 1)).toBeLessThan(0.01); expect(Math.abs(hi / (F / A) - 1)).toBeLessThan(0.01); const total = r.reactions.reduce((s, x) => [s[0] + x[0], s[1] + x[1], s[2] + x[2]], [0, 0, 0]); @@ -103,10 +100,9 @@ describe('static analysis accuracy', () => { loads: [{ kind: 'pressure', faces: [planar(faces, [1, 0, 0])], value: -sNom }], }; // Symmetry would need a roller at y = 0; a roller on the bottom edge face holds y instead (it carries no load in x). - const r = solveStatic(mesh, input, undefined, console.log); + const r = solveStatic(mesh, input); let peak = 0; for (let v = 0; v < mesh.nodes.length / 3; v++) if (Math.hypot(mesh.nodes[v * 3], mesh.nodes[v * 3 + 1]) < 5.5) peak = Math.max(peak, r.stress[v * 6]); - console.log(`plate with hole: peak ${peak}, Kt ${peak / sNom}, ${r.dofs} dof, ${r.iterations} iterations, ms ${JSON.stringify(r.ms)}`); expect(peak / sNom).toBeGreaterThan(2.7); expect(peak / sNom).toBeLessThan(3.4); }, 120000); From d1813cb4a6ba32796d15096cb6b2315dcb9ad9d6 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:26:09 -0700 Subject: [PATCH 019/116] Parametric: cam profiles read from part faces in compose.ts, with a test of a lobed cam's arcs and flanks --- src/parametric/src/app/assembly/mode.ts | 40 ++----------------- src/parametric/src/assembly/compose.ts | 38 +++++++++++++++++- .../tests/assembly-kinematics.test.ts | 39 +++++++++++++++++- 3 files changed, 76 insertions(+), 41 deletions(-) diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index a5a178157e..eb89b2f3db 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -10,14 +10,14 @@ import { KernelRestartError } from '../../kernel/client'; import { type Quat, type Vec3, add, cross, dot, normalize, qAxisAngle, qMul, scale, sub } from '../../math/vec'; import { DocStore, parseDocument } from '../../model/document'; import { BASE_FRAMES, BASE_PLANE_NAMES } from '../../model/planes'; -import type { FaceRef, Id, PartDocument } from '../../model/types'; +import type { Id, PartDocument } from '../../model/types'; import { UNIT_SYSTEMS } from '../../model/units'; import { type AsmComponent, type AsmPart, type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MotionStudy, type Placement, MATE_LABELS, PartCache, asAssembly, mateComps, mateRefs, } from '../../model/assembly'; -import { type ComposedModel, type PartGeometry, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; +import { type ComposedModel, type PartGeometry, camProfileOf, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; import { - type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type ProfileArc, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, camProfile, mateBodies, matesMoving, + type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, } from '../../assembly/solver'; import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, profileOf } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; @@ -806,40 +806,6 @@ export class AssemblyMode { } /** Lets the browser handle input and paint before going on (a message, not a timer: timers are slowed in background tabs). */ -/** A cam's profile from the faces of its part, or why it cannot be one. */ -function camProfileOf(g: PartGeometry, refs: FaceRef[], name: string): CamProfile | string { - const arcs: ProfileArc[] = [], points: Vec3[] = []; - let d: Vec3 | null = null; - const normals: Vec3[] = []; - for (const ref of refs) { - const i = findFace(g.faces, ref); - if (i < 0) return `A face of the cam's profile on ${name} no longer exists`; - const f = g.faces[i]; - const edges = g.edges.filter((e) => e.faces.includes(i)); - if (f.type === 'cylinder' && f.axis && f.radius) { - const ax = normalize(f.axis.d); - if (d && Math.abs(dot(d, ax)) < 0.9999) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides)'; - d ??= ax; - // Its extent from a circular edge: a whole circle closes on itself. - const e = edges.find((x) => x.type === 'circle' && x.radius && Math.abs(x.radius - f.radius!) < 1e-6 * Math.max(1, f.radius!)); - const whole = !e || Math.abs(e.length - 2 * Math.PI * f.radius) < 1e-6 * f.radius; - arcs.push({ c: f.axis.p, r: f.radius, ...(whole ? {} : { ends: [e!.a, e!.b, e!.mid] as [Vec3, Vec3, Vec3] }) }); - continue; - } - if (f.type === 'plane' && f.normal) normals.push(normalize(f.normal)); - for (const e of edges) points.push(e.a, e.b, e.mid); - // Curved faces of other kinds: their mesh vertices (as close as the mesh is to the face). - const m = g.mesh; - if (m && f.type !== 'plane') for (let k = 0; k < m.vertexFace.length; k++) if (m.vertexFace[k] === i) points.push([m.positions[k * 3], m.positions[k * 3 + 1], m.positions[k * 3 + 2]]); - } - if (!d) { - for (let i = 0; i < normals.length && !d; i++) for (let j = i + 1; j < normals.length && !d; j++) { const x = cross(normals[i], normals[j]); if (Math.hypot(...x) > 1e-3) d = normalize(x); } - } - if (!d) return 'Select the faces around the cam (its sides): their direction cannot be told from these'; - if (normals.some((n) => Math.abs(dot(n, d!)) > 1e-6)) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides, not its ends)'; - return camProfile(d, arcs, points); -} - function yieldToUI(): Promise { return new Promise((resolve) => { const ch = new MessageChannel(); diff --git a/src/parametric/src/assembly/compose.ts b/src/parametric/src/assembly/compose.ts index 33b4ebb00e..68caf6a686 100644 --- a/src/parametric/src/assembly/compose.ts +++ b/src/parametric/src/assembly/compose.ts @@ -7,10 +7,10 @@ import type { EdgeInfo, FaceInfo, MeshData } from '../kernel/protocol'; import type { Frame, Vec3 } from '../math/vec'; -import { qRotate } from '../math/vec'; +import { cross, dot, normalize, qRotate } from '../math/vec'; import type { AsmComponent, Placement } from '../model/assembly'; import type { EdgeRef, FaceRef, Id } from '../model/types'; -import { type Geo, applyPlacement } from './solver'; +import { type CamProfile, type Geo, type ProfileArc, applyPlacement, camProfile } from './solver'; /** What the worker built for a part. */ export interface PartGeometry { @@ -191,3 +191,37 @@ export function edgeGeo(geom: PartGeometry, index: number): Geo | null { if (e.type === 'circle' && e.center && e.axis) return { kind: 'axis', p: e.center, d: e.axis, r: e.radius ?? 0, surface: 'circle' }; return null; } + +/** A cam's profile from the faces of its part, or why it cannot be one. */ +export function camProfileOf(g: PartGeometry, refs: FaceRef[], name: string): CamProfile | string { + const arcs: ProfileArc[] = [], points: Vec3[] = []; + let d: Vec3 | null = null; + const normals: Vec3[] = []; + for (const ref of refs) { + const i = findFace(g.faces, ref); + if (i < 0) return `A face of the cam's profile on ${name} no longer exists`; + const f = g.faces[i]; + const edges = g.edges.filter((e) => e.faces.includes(i)); + if (f.type === 'cylinder' && f.axis && f.radius) { + const ax = normalize(f.axis.d); + if (d && Math.abs(dot(d, ax)) < 0.9999) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides)'; + d ??= ax; + // Its extent from a circular edge: a whole circle closes on itself. + const e = edges.find((x) => x.type === 'circle' && x.radius && Math.abs(x.radius - f.radius!) < 1e-6 * Math.max(1, f.radius!)); + const whole = !e || Math.abs(e.length - 2 * Math.PI * f.radius) < 1e-6 * f.radius; + arcs.push({ c: f.axis.p, r: f.radius, ...(whole ? {} : { ends: [e!.a, e!.b, e!.mid] as [Vec3, Vec3, Vec3] }) }); + continue; + } + if (f.type === 'plane' && f.normal) normals.push(normalize(f.normal)); + for (const e of edges) points.push(e.a, e.b, e.mid); + // Curved faces of other kinds: their mesh vertices (as close as the mesh is to the face). + const m = g.mesh; + if (m && f.type !== 'plane') for (let k = 0; k < m.vertexFace.length; k++) if (m.vertexFace[k] === i) points.push([m.positions[k * 3], m.positions[k * 3 + 1], m.positions[k * 3 + 2]]); + } + if (!d) { + for (let i = 0; i < normals.length && !d; i++) for (let j = i + 1; j < normals.length && !d; j++) { const x = cross(normals[i], normals[j]); if (Math.hypot(...x) > 1e-3) d = normalize(x); } + } + if (!d) return 'Select the faces around the cam (its sides): their direction cannot be told from these'; + if (normals.some((n) => Math.abs(dot(n, d!)) > 1e-6)) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides, not its ends)'; + return camProfile(d, arcs, points); +} diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index a32dd5a252..be414b4014 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -1,10 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, relativePlacement, turnAbout } from '../src/assembly/solver'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, profileSupport, relativePlacement, turnAbout } from '../src/assembly/solver'; +import { type PartGeometry, camProfileOf } from '../src/assembly/compose'; import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, mateSeries, pointPath, profileOf, resultsCsv, turnPath, vectorDerivatives } from '../src/assembly/motion'; import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; import type { MateType, Placement } from '../src/model/assembly'; -const Z: Vec3 = [0, 0, 1]; +const Z: Vec3 = [0, 0, 1], Y3: Vec3 = [0, 1, 0]; const plane = (o: Vec3, n: Vec3): Geo => ({ kind: 'plane', o, n }); const axis = (p: Vec3, d: Vec3 = Z, r = 2): Geo => ({ kind: 'axis', p, d, r, surface: 'cylinder' }); const body = (id: string, fixed: boolean, p: Vec3 = [0, 0, 0], q: Quat = [0, 0, 0, 1]): SolverBody => ({ id, fixed, placement: { p, q }, center: [0, 0, 0] }); @@ -518,3 +519,37 @@ describe('slider, cam and universal joint mates', () => { expect(len([off[1] * db[2] - off[2] * db[1], off[2] * db[0] - off[0] * db[2], off[0] * db[1] - off[1] * db[0]])).toBeLessThan(1e-6); }); }); + +describe('cam profiles from part faces', () => { + const deg = (r: number, a: number, c: Vec3 = [0, 0, 0], z = 0): Vec3 => [c[0] + r * Math.cos((a * Math.PI) / 180), c[1] + r * Math.sin((a * Math.PI) / 180), z]; + const t = (Math.acos(0.6) * 180) / Math.PI, nose: Vec3 = [0, 25, 0]; + const cyl = (name: string, c: Vec3, r: number) => ({ name, type: 'cylinder', center: c, area: 1, axis: { p: c, d: Z }, radius: r, feature: 'E1' }); + const flat = (name: string, n: Vec3, c: Vec3) => ({ name, type: 'plane', center: c, area: 1, normal: n, feature: 'E1' }); + const arc = (name: string, face: number, c: Vec3, r: number, a0: number, a1: number, am: number) => ({ name, type: 'circle', a: deg(r, a0, c), b: deg(r, a1, c), mid: deg(r, am, c), length: (r * Math.abs(a1 - a0) * Math.PI) / 180, faces: [face], center: c, axis: Z, radius: r }); + const seg = (name: string, face: number, a: Vec3, b: Vec3) => ({ name, type: 'line', a, b, mid: [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, 0] as Vec3, length: len(sub(b, a)), faces: [face], dir: normalize(sub(b, a)) }); + // A lobed cam: base circle 20, nose 5 at 25, two flanks tangent to both. + const lobed = { + mesh: null, bbox: null, cones: {}, + faces: [cyl('base', [0, 0, 0], 20), cyl('nose', nose, 5), flat('right', normalize(deg(1, 90 - t)), deg(20, 90 - t)), flat('left', normalize(deg(1, 90 + t)), deg(20, 90 + t))], + edges: [ + arc('e0', 0, [0, 0, 0], 20, 90 + t, 90 - t + 360, 270), arc('e1', 1, nose, 5, 90 - t, 90 + t, 90), + seg('e2', 2, deg(20, 90 - t), deg(5, 90 - t, nose)), seg('e3', 3, deg(20, 90 + t), deg(5, 90 + t, nose)), + ], + } as unknown as PartGeometry; + const ref = (name: string) => ({ name, sig: { type: 'x', c: [0, 0, 0] as Vec3, area: 1 } }); + + it('reads arcs from round faces and their edges, corners from flat faces, and an eccentric as a circle', () => { + const p = camProfileOf(lobed, ['base', 'nose', 'right', 'left'].map(ref), 'Cam<1>'); + if (typeof p === 'string') throw new Error(p); + expect(p.circle).toBeNull(); + expect(p.concave).toBeLessThan(1e-9); + const up = profileSupport(p, [dot(Y3, p.u), dot(Y3, p.v)]), down = profileSupport(p, [-dot(Y3, p.u), -dot(Y3, p.v)]); + expect(up).toBeCloseTo(30, 9); + expect(down).toBeCloseTo(20, 9); + // Just the base face, whole: a circle. + const whole = camProfileOf({ ...lobed, faces: [cyl('base', [5, 0, 0], 20)], edges: [{ ...arc('e', 0, [5, 0, 0], 20, 0, 360, 180), a: deg(20, 0, [5, 0, 0]), b: deg(20, 0, [5, 0, 0]) }] } as unknown as PartGeometry, [ref('base')], 'Cam<1>'); + expect(typeof whole !== 'string' && whole.circle?.r).toBe(20); + // An end face (across the axis) is not part of a profile. + expect(camProfileOf({ ...lobed, faces: [...lobed.faces, flat('end', Z, [0, 0, 10])] } as unknown as PartGeometry, ['base', 'end'].map(ref), 'Cam<1>')).toMatch(/one direction/); + }); +}); From 1be016dbc1a1b8a96a733f194a7bbbe9a1cf5fea Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:26:09 -0700 Subject: [PATCH 020/116] Parametric: README for slider, cam follower and universal joint mates --- src/parametric/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/parametric/README.md b/src/parametric/README.md index f1a2d5f696..3bdfa10dd6 100644 --- a/src/parametric/README.md +++ b/src/parametric/README.md @@ -54,9 +54,9 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to **Assemblies** - File > New Assembly. Insert Components places parts from your cloud, this browser or your device (a part file or a STEP model); insert a part several times for several instances (bracket<1>, bracket<2>). The first component is fixed; the others float. - Mates: coincident, parallel, perpendicular, distance, angle, concentric, tangent and lock, between faces, edges and the assembly planes, with aligned or anti-aligned alignment and values that take equations. Distance and angle mates can be limited to a range instead of a value (the component moves freely between a minimum and a maximum). The Mates folder in the design tree edits, flips, suppresses and deletes them. The status bar shows whether the assembly is under, fully or over defined; conflicting mates are marked. -- Mechanical mates: hinge (concentric and coincident in one, with optional angle limits from where it was added), gear (two axes turning by a ratio of pitch diameters or teeth, reversible for internal gears), rack and pinion (the rack's travel by the pinion's pitch diameter or a distance per turn), screw (a nut travelling a pitch per turn, right- or left-hand), width (a tab centred in a groove) and slot (a pin travelling along a slot between its ends). Gear, rack and screw mates hold from wherever the components are when they are added, and their turns add up past a full turn. +- Mechanical mates: hinge (concentric and coincident in one, with optional angle limits from where it was added), slider (a straight edge or axis, or two planar faces, on each component: one move along it and no turn, with optional travel limits), gear (two axes turning by a ratio of pitch diameters or teeth, reversible for internal gears), rack and pinion (the rack's travel by the pinion's pitch diameter or a distance per turn), screw (a nut travelling a pitch per turn, right- or left-hand), width (a tab centred in a groove), slot (a pin travelling along a slot between its ends), cam follower (a vertex, a roller or a flat face kept on the cam's profile faces as it turns; convex profiles, exactly for round faces; a profile with a hollow is refused with its depth) and universal joint (two shafts at an angle β, the output turning by atan(tan φ / cos β), with an optional joint point where their axes meet). Gear, rack and screw mates hold from wherever the components are when they are added, and their turns add up past a full turn. - Drag a component (Alt+drag, or Rotate Component, turns it): it moves only as its mates allow, so a lid on a hinge pin turns about the pin, turning one gear turns the other, dragging a rack turns its pinion, and a drag stops at a mate's limits. Fixed components do not move. -- Motion studies (Motion Study): rotary motors (a constant speed in °/s or rpm, or oscillating), linear motors (constant speed or oscillating) and mate drivers (a distance or angle mate's value at a constant speed, harmonic, or ramped between two values) drive the mechanism for a duration at a frame rate. Frames are calculated without freezing the interface (with progress, and a Cancel); the study stops and says why when a limit is reached or the mechanism locks up. Play, pause, loop and scrub through the motion; plot a point of a component (its displacement, velocity, acceleration, or its turn, angular velocity and acceleration) or what a mate measures against time, download the results as CSV, and check the frames for interference. Studies are listed in the design tree and saved with the assembly; editing the assembly puts their results out of date. +- Motion studies (Motion Study): rotary motors (a constant speed in °/s or rpm, or oscillating; on a face or edge, or on a hinge), linear motors (constant speed or oscillating; along a face or edge, or on a slider) and mate drivers (a distance or angle mate's value at a constant speed, harmonic, or ramped between two values) drive the mechanism for a duration at a frame rate. Frames are calculated without freezing the interface (with progress, and a Cancel); the study stops and says why when a limit is reached or the mechanism locks up. Play, pause, loop and scrub through the motion; plot a point of a component (its displacement, velocity, acceleration, or its turn, angular velocity and acceleration) or what a mate measures against time, download the results as CSV, and check the frames for interference. Studies are listed in the design tree and saved with the assembly; editing the assembly puts their results out of date. - Exploded view steps, interference detection with the overlapping volumes, a bill of materials (item, part, quantity, material; copy or download as CSV), mass properties with each part's material, measure, section view, and STEP (components as named solids) and STL export of the whole assembly. - An assembly references its part files and keeps a copy of each, so it opens even when a part file is moved, shared or downloaded. Open Part edits a component's part; save it and go back, and the assembly takes the change (Update Parts reads the part files again). @@ -120,7 +120,7 @@ npm run build # type check, license check, production build in dist/ | Area | Where | Notes | |---|---|---| | Document model | `src/model` | Plain JSON parts: features, sketches, variables. Undo/redo by snapshots. Parameters may be expressions. | -| Assemblies | `src/model/assembly.ts`, `src/assembly`, `src/app/assembly`, `src/kernel/assembly.ts` | Assembly documents embed their parts as blobs. Rigid-body mate solver: damped least squares over mate residuals, six degrees of freedom per floating component, rank analysis for the definition, conflicts found by adding mates one at a time. Limits are one-sided residuals, left out of the rank analysis. Gear, rack and pinion and screw mates relate the motion since the start of each solve, and every solve starts where the last ended, so turns accumulate. Motion studies (`src/assembly/motion.ts`) solve frame by frame from the frame before with the motors as hard goals; results are finite differences of the frames. Components' meshes are placed on the main thread (dragging needs no kernel call); the worker keeps the placed solids for measure, interference, mass, projection and export. | +| Assemblies | `src/model/assembly.ts`, `src/assembly`, `src/app/assembly`, `src/kernel/assembly.ts` | Assembly documents embed their parts as blobs. Rigid-body mate solver: damped least squares over mate residuals, six degrees of freedom per floating component, rank analysis for the definition, conflicts found by adding mates one at a time. Limits are one-sided residuals, left out of the rank analysis. Cam followers touch the convex outline of the profile (exact arcs, and a polygon of finely divided arcs and corners), by its signed distance or, for a flat face, its support function. A universal joint holds its two yokes square (one equation), which gives the Cardan relation. Gear, rack and pinion and screw mates relate the motion since the start of each solve, and every solve starts where the last ended, so turns accumulate. Motion studies (`src/assembly/motion.ts`) solve frame by frame from the frame before with the motors as hard goals; results are finite differences of the frames. Components' meshes are placed on the main thread (dragging needs no kernel call); the worker keeps the placed solids for measure, interference, mass, projection and export. | | Sketch solver | `src/sketch/solver.ts` | Minimum-norm damped Gauss-Newton per independent cluster, with a rank analysis for degrees of freedom and redundant or conflicting constraints. | | Profiles | `src/sketch/profiles.ts` | Planar face finding on the sketch graph; nested loops alternate material and holes. | | Geometry kernel | `src/kernel` | OpenCascade (WebAssembly) in a Web Worker. Each feature is cached under a hash of everything before it, so edits rebuild only what changed. Faces are named after the feature and sketch entity that created them. | From 5e3b19afc4578ba02225d0569ed7ec60af48345e Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:26:40 -0700 Subject: [PATCH 021/116] Parametric: Mesh Now button, calibrated unknowns estimate --- src/parametric/src/app/fea/panels.ts | 2 +- src/parametric/src/fea/mesher.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 997db275ff..ca11a2c2bf 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -115,7 +115,7 @@ export class StudyPanel extends FeaPanel { describe(); slider.addEventListener('input', () => { this.fineness = Number(slider.value); describe(); }); slider.addEventListener('change', () => this.commit()); - const meshBtn = h('button', { class: 'btn small', type: 'button', disabled: !!ws.busy, onclick: () => void ws.meshNow() }, icon('feaMesh', 16), 'Mesh'); + const meshBtn = h('button', { class: 'btn small', type: 'button', disabled: !!ws.busy, onclick: () => void ws.meshNow() }, icon('feaMesh', 16), 'Mesh Now'); const runBtn = h('button', { class: 'btn small primary', type: 'button', disabled: !!ws.busy, onclick: () => void ws.run() }, icon('feaRun', 16), 'Run'); const m = ws.mesh; const stats: HTMLElement[] = []; diff --git a/src/parametric/src/fea/mesher.ts b/src/parametric/src/fea/mesher.ts index f2b6eccfe2..4b185af54b 100644 --- a/src/parametric/src/fea/mesher.ts +++ b/src/parametric/src/fea/mesher.ts @@ -111,8 +111,8 @@ export function defaultElementSize(volume: number, area: number, diag: number): // 2V/A is the thickness of a plate (and a third of a cube's side). const wall = area > 0 ? (2 * volume) / area : diag / 10; const h = Math.min(diag / 25, wall / 1.5); - // About 48 degrees of freedom per h^3 of a quadratic BCC mesh; keep the default near 150k. - const floor = Math.cbrt(Math.max(volume, 1e-9) / 3000); + // About 66 degrees of freedom per h^3 of the quadratic mesh (measured); keep the default below about 150k. + const floor = Math.cbrt(Math.max(volume, 1e-9) / 2300); return Math.max(h, floor, diag / 400); } @@ -124,7 +124,7 @@ export function maxElementSize(volume: number, area: number, diag: number): numb /** Estimated degrees of freedom of a mesh of the given element size. */ export function estimateDofs(volume: number, size: number): number { - return Math.round((48 * volume) / size ** 3); + return Math.round((66 * volume) / size ** 3); } export function meshSolid(surf: SurfaceIndex, opts: MeshOptions): TetMesh { From 9b79e6f3c1a830395f8e709056f66674e1e3e35f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 13:26:47 -0700 Subject: [PATCH 022/116] Parametric: cam outlines divide arcs at every degree (contact on the arcs is exact) --- src/parametric/src/assembly/solver.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index b4e2801f0c..e93ce7c644 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -45,7 +45,8 @@ export type Geo = /** * A cam's profile in the cam's coordinates. Followers touch its convex - * outline: a circle (exactly) or a polygon (arcs finely divided). `concave`: + * outline: a circle, or a polygon (arcs divided at every degree, with the + * corners) whose arcs are kept too, so contact on them is exact. `concave`: * how deep the profile dips inside that outline (zero when it is convex). */ export interface CamProfile { @@ -645,9 +646,9 @@ export interface ProfileArc { c: Vec3; r: number; ends?: [Vec3, Vec3, Vec3] } /** * A cam's profile from its round faces (arcs about axes along d) and the * corners of its other faces (points), all in the cam's coordinates. A - * single whole circle stays a circle (exact); otherwise arcs are divided - * finely (a 20 mm radius by at most 0.4 µm) and the outline is their convex - * hull with the points. Where the profile lies inside that outline it is + * single whole circle stays a circle; otherwise the outline is the convex + * hull of the arcs (divided at every degree) and the points, the arcs kept + * for exact contact. Where the profile lies inside that outline it is * concave, and `concave` says by how much. */ export function camProfile(d0: Vec3, arcs: ProfileArc[], points: Vec3[]): CamProfile { @@ -676,7 +677,7 @@ export function camProfile(d0: Vec3, arcs: ProfileArc[], points: Vec3[]): CamPro sweep = ccw(am) <= ccw(a1) ? ccw(a1) : ccw(a1) - 2 * Math.PI; } exact.push({ c, r: a.r, a0: sweep >= 0 ? a0 : a0 + sweep, span: Math.abs(sweep) }); - const n = Math.max(8, Math.ceil(Math.abs(sweep) / (0.2 * Math.PI / 180))); + const n = Math.max(8, Math.ceil(Math.abs(sweep) / (Math.PI / 180))); for (let k = 0; k <= n; k++) { const t = a0 + (sweep * k) / n; pts.push([c[0] + a.r * Math.cos(t), c[1] + a.r * Math.sin(t)]); } } const hull = convexHull(pts); @@ -730,8 +731,8 @@ export function profileDistance(p: CamProfile, x: Vec2): number { } // Outside (or between a chord and its arc): the nearest of the edges and arcs, none nearer than the outline. if (poly >= 0) return Math.min(poly, out); - // Inside, near an arc (no deeper than the chords' sag, 0.2° apart): the arc's. - return inside >= poly - 2e-6 * Math.max(1, ...p.arcs.map((a) => a.r)) ? inside : poly; + // Inside, near an arc (no deeper than the sag of its chords, 1° apart): the arc's. + return inside >= poly - 4e-5 * Math.max(1, ...p.arcs.map((a) => a.r)) ? inside : poly; } /** How far the outline reaches along a unit direction (its support function). */ From e4c7a9197d8bf3e875520f7e193d54361e462732 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:05:31 -0700 Subject: [PATCH 023/116] Parametric: fast motors in motion studies run instead of locking up (frames over half a turn are solved in smaller steps) --- src/parametric/src/assembly/motion.ts | 47 ++++++++++++++----- .../tests/assembly-kinematics.test.ts | 16 +++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index 409f9aa276..d8c3ab5321 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -136,12 +136,45 @@ export class MotionRun { return this.k / this.count; } - /** Computes the next frame; false once the study is over (or stopped). */ + /** + * Computes the next frame; false once the study is over (or stopped). A + * frame the solver cannot reach in one step (a fast motor turns a part more + * than half a turn in it, which no solve can tell from the turn back) is + * computed again in smaller steps, each kept as a frame of its own (so the + * turns read from the frames add up). + */ step(): boolean { if (this.done) return false; - const s = this.setup; const t0 = this.k * this.dt, t1 = (this.k + 1) * this.dt; const prev = this.result.frames[this.result.frames.length - 1]; + this.k++; + let failed: ReturnType | null = null; + for (const parts of [1, 4, 16]) { + const times: number[] = [], frames: Map[] = []; + let from = prev; + failed = null; + for (let j = 1; j <= parts; j++) { + const ta = t0 + ((t1 - t0) * (j - 1)) / parts, tb = j === parts ? t1 : t0 + ((t1 - t0) * j) / parts; + const r = this.span(from, ta, tb); + if (!r.r.ok) { failed = r; break; } + times.push(tb); + frames.push(r.r.placements); + from = r.r.placements; + } + if (!failed) { + this.result.times.push(...times); + this.result.frames.push(...frames); + return !this.done; + } + } + const f = failed!; + this.result.stop = this.whyStopped(f.solver, f.r.placements, f.from, f.mates, f.r.residuals, t1); + return false; + } + + /** Solves the motion from `prev` (at time t0) to time t1. */ + private span(prev: Map, t0: number, t1: number) { + const s = this.setup; const drives: Drive[] = []; let mates = this.solverMates; for (const m of s.motors) { @@ -165,15 +198,7 @@ export class MotionRun { } const bodies = s.bodies.map((b) => ({ ...b, placement: prev.get(b.id) ?? b.placement })); const solver = new MateSolver(bodies, mates); - const r = solver.solve({ scale: s.scale, drives, maxIter: 80 }); - this.k++; - if (!r.ok) { - this.result.stop = this.whyStopped(solver, r.placements, prev, mates, r.residuals, t1); - return false; - } - this.result.times.push(t1); - this.result.frames.push(r.placements); - return !this.done; + return { r: solver.solve({ scale: s.scale, drives, maxIter: 80 }), solver, mates, from: prev }; } private whyStopped(solver: MateSolver, pl: Map, prev: Map, mates: SolverMate[], residuals: Map, t: number): MotionStop { diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index be414b4014..9356bea46c 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -162,6 +162,22 @@ describe('mechanical mates', () => { expect(w[30]).toBeCloseTo(-180, 3); }); + it('a motor (or a gear it drives) turning more than half a turn a frame is followed in smaller steps', () => { + // 1000 rpm at 30 frames a second: 200° a frame. + const s = gears(); + const fast = computeMotion({ bodies: s.bodies, mates: s.mates, motors: [rotary('A', axis([0, 0, 0]), 1000, { at: profileOf('rotary', { profile: 'constant', speed: 1000, rpm: true }, 1) })], duration: 0.5, fps: 30, scale: 100 }); + expect(fast.stop).toBeNull(); + expect(fast.times[fast.times.length - 1]).toBeCloseTo(0.5, 12); + for (let i = 1; i < fast.times.length; i++) expect(fast.times[i]).toBeGreaterThan(fast.times[i - 1]); + expect(degreesAbout(turnPath(fast, 'A'), Z).at(-1)).toBeCloseTo(3000, 3); + expect(degreesAbout(turnPath(fast, 'B'), Z).at(-1)).toBeCloseTo(-1500, 3); + // A slow motor on the large gear: the small one turns 240° a frame. + const big = new MateSolver(s.bodies, [s.mates[0], s.mates[1], { ...s.mates[2], value: 40, value2: 10 }]); + const res = computeMotion({ bodies: big.bodies, mates: big.mates, motors: [rotary('A', axis([0, 0, 0]), 1800)], duration: 0.5, fps: 30, scale: 100 }); + expect(res.stop).toBeNull(); + expect(degreesAbout(turnPath(res, 'B'), Z).at(-1)).toBeCloseTo(-3600, 3); + }); + /** A pinion (Ø20) on a hinge at the origin, its rack below it sliding along x. */ const rackAndPinion = (extra: Partial = {}) => { const bodies = [body('g', true), body('P', false), body('R', false, [0, -10, 0])]; From d5ead035fbd8e670ccfd81a742fedb53f6728255 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:06:07 -0700 Subject: [PATCH 024/116] =?UTF-8?q?Parametric:=20hinge=20angle=20limits=20?= =?UTF-8?q?past=20=C2=B1180=C2=B0=20hold=20at=20their=20ends=20(a=20door?= =?UTF-8?q?=20can=20open=20270=C2=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/parametric/src/assembly/solver.ts | 16 +++++++++++++- .../tests/assembly-kinematics.test.ts | 21 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index e93ce7c644..def294722e 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -439,6 +439,20 @@ export function angleOf(a: Geo, b: Geo, aligned: boolean): number | null { /** The overshoot of v past [min, max] (zero inside). */ const outside = (v: number, min: number, max: number) => (v > max ? v - max : v < min ? v - min : 0); +/** + * The overshoot of a turn t (radians, in (-π, π]) past [min, max], read on + * the circle: a hinge kept between 0° and 270° is inside at 190° (which + * reads as -170°), and past the nearer end outside the range. + */ +function outsideTurn(t: number, min: number, max: number): number { + const full = 2 * Math.PI; + if (max - min >= full) return 0; + const u = min + ((((t - min) % full) + full) % full); + if (u <= max) return 0; + const over = u - max, under = u - (min + full); + return over <= -under ? over : under; +} + /** A distance or angle mate kept between limits: its other conditions, and the overshoot (when `ineq`). */ function limitEquations(type: 'distance' | 'angle', a: Geo, b: Geo, o: EqOpts, lim: { min: number; max: number }, ineq: boolean): number[] | null { if (type === 'angle') { @@ -497,7 +511,7 @@ function mechanicalEquations(c: MechContext): number[] | null { if (!m.limit) return [...conc, ...plane]; const t = hingeTurn(m, c.pa, c.pb); if (t === null) return null; - return [...conc, ...plane, ...(c.ineq ? [outside(t, (m.limit.min * Math.PI) / 180, (m.limit.max * Math.PI) / 180)] : [])]; + return [...conc, ...plane, ...(c.ineq ? [outsideTurn(t, (m.limit.min * Math.PI) / 180, (m.limit.max * Math.PI) / 180)] : [])]; } case 'gear': { if (!isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 9356bea46c..530cb7ed41 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -107,6 +107,27 @@ describe('mechanical mates', () => { expect(new MateSolver([body('base', true), body('lid', false)], [crossed]).analyze().invalid.get(crossed.id)).toMatch(/component of the round entity/); }); + it('hinge limits past ±180° (a door that opens 270°) stop at their ends, not at 180°', () => { + const start: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const door = hinge('base', [0, 0, 0], 'lid', [0, 0, 0], { rel: relativePlacement(start, start), limit: { min: 0, max: 270 } }); + const bodies = [body('base', true), body('lid', false)]; + const run = (speed: number) => computeMotion({ bodies, mates: [door], motors: [{ id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: door, at: profileOf('rotary', { profile: 'constant', speed }, 4) }], duration: 4, fps: 10, scale: 100 }); + const open = run(90); + expect(open.stop?.kind).toBe('limit'); + expect(open.stop?.time).toBeCloseTo(3.1, 6); + expect(degreesAbout(turnPath(open, 'lid'), Z).at(-1)).toBeCloseTo(270, 4); + expect(mateSeries(open, door)!.values.at(-1)).toBeCloseTo(270, 4); + // The other way it is at its end already. + const shut = run(-90); + expect(shut.stop?.kind).toBe('limit'); + expect(shut.frames).toHaveLength(1); + // Dragged round past 180°, it stops at 270°. + const s = new MateSolver(bodies, [door]); + let pl = new Map([['base', start], ['lid', start]]); + for (let k = 1; k <= 32; k++) pl = s.solve({ drag: { kind: 'rotate', body: 'lid', q: qAxisAngle(Z, (k * 10 * Math.PI) / 180) } }, s.mates, pl).placements; + expect(mateMeasure(door, pl)!.value).toBeCloseTo(-90, 3); + }); + /** Two gears on hinges, 30 mm apart: A (pitch Ø20) at the origin, B (Ø40) beside it. */ const gears = (extra: Partial = {}) => { const bodies = [body('g', true), body('A', false), body('B', false, [30, 0, 0])]; From b75d6aeb1acdd325a4252a5799f0165584005303 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:08:18 -0700 Subject: [PATCH 025/116] Parametric: motion results' velocity and acceleration are accurate at the first and last frames --- src/parametric/src/assembly/motion.ts | 15 ++++++++++++++- src/parametric/tests/assembly-kinematics.test.ts | 8 ++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index d8c3ab5321..3b12dbcbd2 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -297,7 +297,12 @@ export function mateSeries(res: MotionResult, mate: SolverMate, L = 100): { valu return { values, kind: first.kind }; } -/** First and second derivatives of samples at times t (central differences; one-sided at the ends). */ +/** + * First and second derivatives of samples at times t: central differences, + * and at the first and last samples one-sided differences as accurate (the + * slope through three samples; the second derivative carried on in a line + * from the two beside it). + */ export function derivatives(t: number[], v: number[]): { d1: number[]; d2: number[] } { const n = v.length; const d1 = new Array(n).fill(0), d2 = new Array(n).fill(0); @@ -307,12 +312,20 @@ export function derivatives(t: number[], v: number[]): { d1: number[]; d2: numbe d1[i] = (v[b] - v[a]) / (t[b] - t[a] || 1); } if (n < 3) return { d1, d2 }; + // The slope at an end of the parabola through it and the two samples beside it (steps h1 then h2 away). + const end = (f0: number, f1: number, f2: number, h1: number, h2: number) => (-(2 * h1 + h2) / (h1 * (h1 + h2))) * f0 + ((h1 + h2) / (h1 * h2)) * f1 - (h1 / (h2 * (h1 + h2))) * f2; + d1[0] = end(v[0], v[1], v[2], t[1] - t[0], t[2] - t[1]); + d1[n - 1] = -end(v[n - 1], v[n - 2], v[n - 3], t[n - 1] - t[n - 2], t[n - 2] - t[n - 3]); for (let i = 0; i < n; i++) { const j = Math.min(n - 2, Math.max(1, i)); const h1 = t[j] - t[j - 1], h2 = t[j + 1] - t[j]; // Second difference on uneven steps (the last frame of a study can be shorter). d2[i] = (2 * ((v[j + 1] - v[j]) / h2 - (v[j] - v[j - 1]) / h1)) / (h1 + h2); } + if (n >= 4) { + d2[0] = d2[1] + ((d2[1] - d2[2]) * (t[1] - t[0])) / (t[2] - t[1]); + d2[n - 1] = d2[n - 2] + ((d2[n - 2] - d2[n - 3]) * (t[n - 1] - t[n - 2])) / (t[n - 2] - t[n - 3]); + } return { d1, d2 }; } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 530cb7ed41..584a10e9a3 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -387,6 +387,14 @@ describe('motion studies', () => { expect(d1[2]).toBeCloseTo(0.4, 12); expect(d2[2]).toBeCloseTo(2, 9); expect(d2[0]).toBeCloseTo(2, 9); + // At the first and last samples too: the velocity of t² there, and of a harmonic motion's acceleration (zero at its middle position). + expect(d1[0]).toBeCloseTo(0, 12); + expect(d1[4]).toBeCloseTo(0.8, 12); + const ts = Array.from({ length: 31 }, (_, i) => i / 30), x = ts.map((s) => 10 * Math.sin(2 * Math.PI * s)); + const h = derivatives(ts, x), peak = 10 * (2 * Math.PI) ** 2; + expect(Math.abs(h.d2[0])).toBeLessThan(0.02 * peak); + expect(Math.abs(h.d2[30])).toBeLessThan(0.02 * peak); + expect(h.d1[0] / (20 * Math.PI)).toBeCloseTo(1, 1); expect(resultsCsv([{ name: 'Time (s)', values: [0, 0.5] }, { name: 'X, mm', values: [1, 2.25] }])).toBe('Time (s),"X, mm"\n0,1\n0.5,2.25'); expect(len(sub(pointPath({ times: [0], frames: [new Map([['a', { p: [1, 2, 3], q: [0, 0, 0, 1] }]])], stop: null, duration: 1 }, 'a', [1, 0, 0])[0], [2, 2, 3]))).toBe(0); }); From dc8b8265a10e8f78906586c948f85272112b78e2 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:10:04 -0700 Subject: [PATCH 026/116] Parametric: long motion studies of large assemblies keep only the moving components per frame (300 components, 20000 frames: 335 MB to 16 MB, 2.7 s to 0.9 s) --- src/parametric/src/assembly/motion.ts | 30 +++++++++++++++++-- .../tests/assembly-kinematics.test.ts | 19 ++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index 3b12dbcbd2..3bd267755a 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -92,7 +92,11 @@ export interface MotionStop { export interface MotionResult { /** Seconds, one per frame computed. */ times: number[]; - /** Placements of every component in each frame. */ + /** + * Placements of every component in each frame. Frames after the first keep + * only the components that move (get and has give the others' placements + * from the first frame), so long studies of large assemblies fit in memory. + */ frames: Map[]; /** Why the study stopped before its end, or null. */ stop: MotionStop | null; @@ -110,6 +114,8 @@ export class MotionRun { readonly result: MotionResult; private k = 0; private solverMates: SolverMate[]; + /** The components the solved mates and the motors reference: the others stay where they are. */ + private bodies: SolverBody[]; constructor(private setup: MotionSetup) { this.count = Math.max(1, Math.round(setup.duration * setup.fps)); @@ -123,6 +129,9 @@ export class MotionRun { for (const id of ids) for (const x of matesMoving(id, setup.bodies, setup.mates)) moving.add(x); } this.solverMates = setup.mates.filter((x) => moving.has(x)); + const used = new Set(this.solverMates.flatMap(mateBodies)); + for (const m of setup.motors) for (const id of m.on ? mateBodies(m.on) : m.body ? [m.body] : []) used.add(id); + this.bodies = setup.bodies.filter((b) => used.has(b.id)); const first = new Map(setup.bodies.map((b) => [b.id, b.placement])); this.result = { times: [0], frames: [first], stop: null, duration: setup.duration }; } @@ -158,7 +167,7 @@ export class MotionRun { const r = this.span(from, ta, tb); if (!r.r.ok) { failed = r; break; } times.push(tb); - frames.push(r.r.placements); + frames.push(new LaterFrame(r.r.placements, this.result.frames[0])); from = r.r.placements; } if (!failed) { @@ -196,7 +205,7 @@ export class MotionRun { drives.push({ kind: 'translate', body: m.body, local, dir, amount }); } } - const bodies = s.bodies.map((b) => ({ ...b, placement: prev.get(b.id) ?? b.placement })); + const bodies = this.bodies.map((b) => ({ ...b, placement: prev.get(b.id) ?? b.placement })); const solver = new MateSolver(bodies, mates); return { r: solver.solve({ scale: s.scale, drives, maxIter: 80 }), solver, mates, from: prev }; } @@ -243,6 +252,21 @@ function mountedDrive(on: SolverMate, prev: Map, bodies: SolverBo const IDENT: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; +/** A frame after the first: the components that move, and the others where the first frame has them. */ +class LaterFrame extends Map { + constructor(moved: Map, private first: Map) { + super(moved); + } + + override get(id: Id): Placement | undefined { + return super.get(id) ?? this.first.get(id); + } + + override has(id: Id): boolean { + return super.has(id) || this.first.has(id); + } +} + const directionOf = (g: Geo): Vec3 | null => (g.kind === 'plane' ? normalize(g.n) : g.kind === 'axis' || g.kind === 'line' ? normalize(g.d) : null); const pointOfGeo = (g: Geo): Vec3 | null => (g.kind === 'plane' ? g.o : g.kind === 'axis' || g.kind === 'line' || g.kind === 'point' ? g.p : g.kind === 'sphere' ? g.c : null); diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 584a10e9a3..260c86c690 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -381,6 +381,25 @@ describe('motion studies', () => { res.frames.forEach((f, i) => expect(f.get('s')!.p[0]).toBeCloseTo(10 * Math.sin(Math.PI * res.times[i]), 6)); }); + it('frames keep only the components that move (a long study of a large assembly fits in memory)', () => { + const cs = crankSlider(30); + // 500 components the mechanism does not touch, one of them turned and floating. + const idle = Array.from({ length: 500 }, (_, i) => body(`idle${i}`, i > 0, [i, 50, 0], i === 1 ? qAxisAngle(Z, 0.5) : [0, 0, 0, 1])); + const res = computeMotion({ bodies: [...cs.bodies, ...idle], mates: cs.mates, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 4, fps: 25, scale: 200 }); + expect(res.stop).toBeNull(); + expect(res.frames).toHaveLength(101); + expect(res.frames[50].size).toBeLessThan(10); + // The others read where they are. + expect(res.frames[50].has('idle1')).toBe(true); + expect(res.frames[50].get('idle1')).toEqual(idle[1].placement); + expect(pointPath(res, 'idle1', [1, 0, 0])[100]).toEqual(pointPath(res, 'idle1', [1, 0, 0])[0]); + expect(degreesAbout(turnPath(res, 'idle1'), Z)[100]).toBe(0); + res.frames.forEach((f, i) => expect(f.get('slider')!.p[0]).toBeCloseTo(slide(30 + 90 * res.times[i]), 4)); + const gap = mate('distance', ['idle1', plane([0, 0, 0], [1, 0, 0])], ['slider', plane([0, 0, 0], [1, 0, 0])], { value: 0 }); + const series = mateSeries(res, gap)!.values; + expect(series[100] - series[0]).toBeCloseTo(slide(390) - slide(30), 4); + }); + it('differentiates samples and writes CSV', () => { const t = [0, 0.1, 0.2, 0.3, 0.4]; const { d1, d2 } = derivatives(t, t.map((x) => x * x)); From 516aea9d99e14643c99fd8ceb428b5c475639565 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:11:41 -0700 Subject: [PATCH 027/116] =?UTF-8?q?Parametric:=20a=20universal=20joint=20b?= =?UTF-8?q?etween=20shafts=20at=2090=C2=B0=20says=20it=20cannot=20turn=20i?= =?UTF-8?q?nstead=20of=20holding=20nothing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/parametric/src/assembly/solver.ts | 4 +++- src/parametric/tests/assembly-kinematics.test.ts | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index def294722e..b75d2ac9b3 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -785,7 +785,9 @@ export function mechanicalProblem(m: Pick { const off = sub([0, 0, 10], pb.p); expect(len([off[1] * db[2] - off[2] * db[1], off[2] * db[0] - off[0] * db[2], off[0] * db[1] - off[1] * db[0]])).toBeLessThan(1e-6); }); + + it('a universal joint between shafts at 90° is refused (it cannot turn), one at 89° works', () => { + const square = uJoint(90); + const r = new MateSolver(square.bodies, square.mates).analyze(); + expect(r.status).toBe('error'); + expect(r.invalid.get(square.mates[2].id)).toMatch(/90°/); + const steep = uJoint(89); + const s = new MateSolver(steep.bodies, steep.mates).analyze(); + expect(s.invalid.size).toBe(0); + expect(s.dof).toBe(1); + }); }); describe('cam profiles from part faces', () => { From 4598862908536afb429a85cd449dbc468f66b281 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:13:44 -0700 Subject: [PATCH 028/116] Parametric: a cam profile missing some of the cam's side faces is refused (the follower rode across the gap as if the cam were flat there) --- src/parametric/src/assembly/compose.ts | 8 ++++++++ src/parametric/tests/assembly-kinematics.test.ts | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/src/parametric/src/assembly/compose.ts b/src/parametric/src/assembly/compose.ts index 68caf6a686..92a9de6d5f 100644 --- a/src/parametric/src/assembly/compose.ts +++ b/src/parametric/src/assembly/compose.ts @@ -223,5 +223,13 @@ export function camProfileOf(g: PartGeometry, refs: FaceRef[], name: string): Ca } if (!d) return 'Select the faces around the cam (its sides): their direction cannot be told from these'; if (normals.some((n) => Math.abs(dot(n, d!)) > 1e-6)) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides, not its ends)'; + // The profile goes all the way round: the sides meet along straight edges in the direction + // of the axis, and a face beside a selected one there must be selected too (else the + // follower would ride across the gap as if the cam were flat there). + const picked = new Set(refs.map((r) => findFace(g.faces, r))); + for (const e of g.edges) { + if (e.type !== 'line' || !e.dir || Math.abs(dot(normalize(e.dir), d)) < 0.9999 || !e.faces.some((i) => picked.has(i))) continue; + if (e.faces.some((i) => !picked.has(i))) return 'Select all the faces around the cam (its sides): the profile must go all the way round'; + } return camProfile(d, arcs, points); } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 4264ae1844..19d8d83a6e 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -609,6 +609,8 @@ describe('cam profiles from part faces', () => { edges: [ arc('e0', 0, [0, 0, 0], 20, 90 + t, 90 - t + 360, 270), arc('e1', 1, nose, 5, 90 - t, 90 + t, 90), seg('e2', 2, deg(20, 90 - t), deg(5, 90 - t, nose)), seg('e3', 3, deg(20, 90 + t), deg(5, 90 + t, nose)), + // Where the sides meet, along the axis (base and right flank, right flank and nose, ...). + ...([[0, 2, deg(20, 90 - t)], [2, 1, deg(5, 90 - t, nose)], [1, 3, deg(5, 90 + t, nose)], [3, 0, deg(20, 90 + t)]] as [number, number, Vec3][]).map(([f, g, p], k) => ({ ...seg(`s${k}`, f, p, [p[0], p[1], 10]), faces: [f, g] })), ], } as unknown as PartGeometry; const ref = (name: string) => ({ name, sig: { type: 'x', c: [0, 0, 0] as Vec3, area: 1 } }); @@ -627,4 +629,9 @@ describe('cam profiles from part faces', () => { // An end face (across the axis) is not part of a profile. expect(camProfileOf({ ...lobed, faces: [...lobed.faces, flat('end', Z, [0, 0, 10])] } as unknown as PartGeometry, ['base', 'end'].map(ref), 'Cam<1>')).toMatch(/one direction/); }); + + it('refuses a profile that does not go all the way round (the follower would ride across the gap)', () => { + for (const some of [['base', 'nose'], ['right', 'left'], ['base', 'nose', 'right']]) expect(camProfileOf(lobed, some.map(ref), 'Cam<1>')).toMatch(/all the way round/); + expect(typeof camProfileOf(lobed, ['left', 'nose', 'base', 'right'].map(ref), 'Cam<1>')).toBe('object'); + }); }); From 77f638570af6a7c912a38a5df60a352e261497f8 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:17:11 -0700 Subject: [PATCH 029/116] Parametric: a rack, gear or screw dragged far in one pointer move follows the pointer instead of jumping the other way --- src/parametric/src/assembly/solver.ts | 26 +++++++++++++++++-- .../tests/assembly-kinematics.test.ts | 8 ++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index b75d2ac9b3..40dc604ff2 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -180,6 +180,12 @@ export function rotVecQuat(w: Vec3): Quat { const qConj = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]]; +/** The angle (radians, 0 to π) orientation q is turned from q0. */ +const turnAngle = (q: Quat, q0: Quat): number => { + const d = qMul(q, qConj(q0)); + return 2 * Math.atan2(Math.hypot(d[0], d[1], d[2]), Math.abs(d[3])); +}; + /** How far (radians, in (-π, π]) orientation q is turned from q0 about the unit direction d (both in the same frame). */ export function turnAbout(q: Quat, q0: Quat, d: Vec3): number { const dq = qMul(q, qConj(q0)); @@ -867,8 +873,11 @@ function placementWith(base: Placement, center: Vec3, x: number[], o: number, L: export class MateSolver { constructor(readonly bodies: SolverBody[], readonly mates: SolverMate[]) {} - /** Placements with all mates (and the drag goal) satisfied as far as possible. */ - solve(opts: SolveOptions = {}, mates = this.mates, start?: Map): SolveResult { + /** + * Placements with all mates (and the drag goal) satisfied as far as possible. + * `depth`: how many times a drag was halved (see the end). + */ + solve(opts: SolveOptions = {}, mates = this.mates, start?: Map, depth = 0): SolveResult { const L = opts.scale && opts.scale > 0 ? opts.scale : 100; const bodies = new Map(this.bodies.map((b) => [b.id, { ...b, placement: start?.get(b.id) ?? b.placement }])); const involved = new Set(); @@ -992,6 +1001,19 @@ export class MateSolver { run(false, maxIter); } else run(false, maxIter); const final = at(x); + // Gear, rack and pinion and screw mates measure turns within a solve, up to half a turn + // either way: a drag that turns a component further (a rack pulled far in one pointer + // move) could land on the turn the other way round, so it is made in two halves. + if (drag && depth < 4 && mates.some((m) => m.type === 'gear' || m.type === 'rackPinion' || m.type === 'screw') && vars.some((id) => turnAngle(final.get(id)!.q, placements.get(id)!.q) > Math.PI / 2)) { + const from = placements.get(drag.body); + if (from) { + const half: DragGoal = drag.kind === 'move' + ? { ...drag, target: scale(add(applyPlacement(from, drag.local), drag.target), 0.5) } + : { ...drag, q: qNormalize(qMul(rotVecQuat(scale(quatRotVec(qMul(drag.q, qConj(from.q))), 0.5)), from.q)) }; + const first = this.solve({ ...opts, drag: half }, mates, placements, depth + 1); + return this.solve(opts, mates, first.placements, depth + 1); + } + } const worst = evalMates(final), dw = driveWorst(final); return { placements: final, ok: worst < CONFLICT_TOL && dw < CONFLICT_TOL, residuals, iterations, driveResidual: dw }; } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 19d8d83a6e..7f2d027138 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -223,6 +223,14 @@ describe('mechanical mates', () => { for (let k = 1; k <= 10; k++) pl = s.solve({ drag: { kind: 'move', body: 'R', local: [0, 0, 0], target: [k * Math.PI, -10, 0] } }, s.mates, pl).placements; expect(pl.get('R')!.p[0]).toBeCloseTo(10 * Math.PI, 3); expect(Math.abs(deg(angleZ(pl.get('P')!.q)))).toBeCloseTo(180, 2); + // Pulled 50 mm in one pointer move (more than half a turn of the pinion): the rack follows, the pinion turns 5 rad with it. + for (const dx of [50, 80]) { + const one = s.solve({ drag: { kind: 'move', body: 'R', local: [0, 0, 0], target: [dx, -10, 0] } }, s.mates, s.analyze().placements); + expect(one.ok).toBe(true); + expect(one.placements.get('R')!.p[0]).toBeCloseTo(dx, 3); + const t = dx / 10; + expect(dot(qRotate(one.placements.get('P')!.q, [1, 0, 0]), [Math.cos(t), Math.sin(t), 0])).toBeCloseTo(1, 6); + } // By travel per turn, and reversed. const per = rackAndPinion({ by: 'revolution', value: 50, reverse: true }); const r2 = computeMotion({ bodies: per.bodies, mates: per.mates, motors: [rotary('P', axis([0, 0, 0]), 360)], duration: 1, fps: 30, scale: 100 }); From 565600a8114bd0f092d390e4c61fb501782556b5 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:22:03 -0700 Subject: [PATCH 030/116] Parametric: gears, racks and screws turn any amount in one solve (a new mate value that moves a rack far is no longer a false conflict) Their turns are read from the solver's rotation variables instead of the orientations (which wrap at half a turn). This replaces the drag halving of the previous commit. Motion frames in which a part turns more than a quarter turn are recorded in smaller steps, so the turns read from the frames add up. --- src/parametric/src/assembly/motion.ts | 14 ++-- src/parametric/src/assembly/solver.ts | 76 +++++++++++-------- .../tests/assembly-kinematics.test.ts | 8 ++ 3 files changed, 59 insertions(+), 39 deletions(-) diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index 3bd267755a..aa37c552b9 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -17,7 +17,7 @@ import { add, dot, len, normalize, qMul, qRotate } from '../math/vec'; import type { MotionMotor, Placement } from '../model/assembly'; import type { Id } from '../model/types'; import { - CONFLICT_TOL, type Drive, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, mateMeasure, placeGeo, quatRotVec, sliderDirection, + CONFLICT_TOL, type Drive, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, mateMeasure, placeGeo, quatRotVec, sliderDirection, turnAngle, } from './solver'; /** A motor ready to run: what it moves and its motion over time. */ @@ -148,9 +148,10 @@ export class MotionRun { /** * Computes the next frame; false once the study is over (or stopped). A * frame the solver cannot reach in one step (a fast motor turns a part more - * than half a turn in it, which no solve can tell from the turn back) is - * computed again in smaller steps, each kept as a frame of its own (so the - * turns read from the frames add up). + * than half a turn in it, which no solve can tell from the turn back), or in + * which a part turns more than a quarter turn (a small gear driven by a + * large one), is computed again in smaller steps, each kept as a frame of + * its own (so the turns read from the frames add up). */ step(): boolean { if (this.done) return false; @@ -160,17 +161,18 @@ export class MotionRun { let failed: ReturnType | null = null; for (const parts of [1, 4, 16]) { const times: number[] = [], frames: Map[] = []; - let from = prev; + let from = prev, fast = false; failed = null; for (let j = 1; j <= parts; j++) { const ta = t0 + ((t1 - t0) * (j - 1)) / parts, tb = j === parts ? t1 : t0 + ((t1 - t0) * j) / parts; const r = this.span(from, ta, tb); if (!r.r.ok) { failed = r; break; } + if (parts < 16 && this.bodies.some((b) => !b.fixed && turnAngle(r.r.placements.get(b.id)?.q ?? b.placement.q, from.get(b.id)?.q ?? b.placement.q) > Math.PI / 2)) { fast = true; break; } times.push(tb); frames.push(new LaterFrame(r.r.placements, this.result.frames[0])); from = r.r.placements; } - if (!failed) { + if (!failed && !fast) { this.result.times.push(...times); this.result.frames.push(...frames); return !this.done; diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index 40dc604ff2..c79009c9a1 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -21,9 +21,12 @@ // // Gear, rack and pinion and screw mates relate motions, not positions: how // far a component turned or slid since the start of the solve (the -// placements it started from). Every solve starts where the last one ended -// (a drag step, a motion study frame, the document after a commit), so the -// turns add up: a gear driven round and round keeps its ratio past ±180°. +// placements it started from), read from the solver's own rotation +// variables, so a single solve can turn them any amount (a rack pulled far +// in one pointer move, or moved by a mate's new value). Every solve starts +// where the last one ended (a drag step, a motion study frame, the document +// after a commit), so the turns add up: a gear driven round and round keeps +// its ratio past ±180°. import type { Quat, Vec2, Vec3 } from '../math/vec'; import { add, cross, dot, len, normalize, perpendicular, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; @@ -181,7 +184,7 @@ export function rotVecQuat(w: Vec3): Quat { const qConj = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]]; /** The angle (radians, 0 to π) orientation q is turned from q0. */ -const turnAngle = (q: Quat, q0: Quat): number => { +export const turnAngle = (q: Quat, q0: Quat): number => { const d = qMul(q, qConj(q0)); return 2 * Math.atan2(Math.hypot(d[0], d[1], d[2]), Math.abs(d[3])); }; @@ -483,6 +486,8 @@ interface MechContext { /** Placement of an entity's component, now and at the start. */ now: (e: SolverEntity) => Placement; start: (e: SolverEntity) => Placement; + /** How far an entity's component turned about a direction (in the assembly) since the start, in radians. */ + turned: (e: SolverEntity, d: Vec3) => number; L: number; ineq: boolean; } @@ -524,7 +529,7 @@ function mechanicalEquations(c: MechContext): number[] | null { const da = normalize(dirOf(ga)!), db0 = normalize(dirOf(gb)!); // Parallel axes turn about the same direction: external gears turn opposite ways. const db = dot(da, db0) < 0 ? scale(db0, -1) : db0; - const ta = turnAbout(c.pa.q, c.ra.q, da), tb = turnAbout(c.pb.q, c.rb.q, db); + const ta = c.turned(m.a, da), tb = c.turned(m.b, db); const va = m.value, vb = m.value2 ?? 0; if (!(va > 0) || !(vb > 0)) return null; return [(va * ta + (m.reverse ? -1 : 1) * vb * tb) / Math.max(va, vb)]; @@ -533,7 +538,7 @@ function mechanicalEquations(c: MechContext): number[] | null { // a: the pinion (an axis), b: the rack (a straight edge, along which it moves). if (!isAxisLike(ga) || gb.kind !== 'line' || m.b.geo.kind !== 'line' || !(m.value > 0)) return null; const dp = normalize(dirOf(ga)!), u = normalize(gb.d); - const turn = m.a.body ? turnAbout(c.pa.q, c.ra.q, dp) : 0; + const turn = m.a.body ? c.turned(m.a, dp) : 0; const local = m.b.geo.p; const moved = dot(sub(applyPlacement(c.pb, local), applyPlacement(c.rb, local)), u); const sense = rackSense(placeGeoDir(m.a.geo, c.ra), pointOf(placeGeo(m.a.geo, c.ra))!, normalize(qRotate(c.rb.q, m.b.geo.d)), applyPlacement(c.rb, local)); @@ -546,7 +551,8 @@ function mechanicalEquations(c: MechContext): number[] | null { // b's turn and travel along a's axis, in a's frame (a nut on a screw that itself moves). const dl = normalize(m.a.geo.d); const rel = relativePlacement(c.pa, c.pb), rel0 = relativePlacement(c.ra, c.rb); - const turn = turnAbout(rel.q, rel0.q, dl); + const dw = normalize(qRotate(c.pa.q, dl)); + const turn = c.turned(m.b, dw) - c.turned(m.a, dw); const travel = dot(sub(applyPlacement(rel, m.b.geo.p), applyPlacement(rel0, m.b.geo.p)), dl); return [...conc, (travel - ((m.reverse ? -1 : 1) * m.value * turn) / (2 * Math.PI)) / L]; } @@ -873,11 +879,8 @@ function placementWith(base: Placement, center: Vec3, x: number[], o: number, L: export class MateSolver { constructor(readonly bodies: SolverBody[], readonly mates: SolverMate[]) {} - /** - * Placements with all mates (and the drag goal) satisfied as far as possible. - * `depth`: how many times a drag was halved (see the end). - */ - solve(opts: SolveOptions = {}, mates = this.mates, start?: Map, depth = 0): SolveResult { + /** Placements with all mates (and the drag goal) satisfied as far as possible. */ + solve(opts: SolveOptions = {}, mates = this.mates, start?: Map): SolveResult { const L = opts.scale && opts.scale > 0 ? opts.scale : 100; const bodies = new Map(this.bodies.map((b) => [b.id, { ...b, placement: start?.get(b.id) ?? b.placement }])); const involved = new Set(); @@ -893,11 +896,14 @@ export class MateSolver { const weights = vars.map((id) => Math.sqrt(Math.max(1e-6, opts.weight?.(id) ?? 1))); const n = vars.length * 6; const residuals = new Map(); + // Gear, rack and pinion and screw mates read the components' turns from the variables (see mateResidual). + const coupled = mates.some((m) => m.type === 'gear' || m.type === 'rackPinion' || m.type === 'screw'); + const turnsOf = coupled ? new WeakMap, Map>() : null; const evalMates = (pl: Map) => { residuals.clear(); let worst = 0; for (const m of mates) { - const r = this.mateResidual(m, pl, L, ref); + const r = this.mateResidual(m, pl, L, ref, true, turnsOf?.get(pl)); const v = r ? Math.max(0, ...r.map(Math.abs)) : Infinity; residuals.set(m.id, v); worst = Math.max(worst, v); @@ -924,12 +930,14 @@ export class MateSolver { const at = (xv: number[]): Map => { const out = new Map(placements); vars.forEach((id, i) => out.set(id, placementWith(bodies.get(id)!.placement, sys.centers.get(id)!, xv, i * 6, L))); + turnsOf?.set(out, turnsAt(vars, xv)); return out; }; const dragWeight = 0.05; const rows = (pl: Map, withDrag: boolean): number[] => { const out: number[] = []; - for (const m of mates) out.push(...(this.mateResidual(m, pl, L, ref) ?? [])); + const turns = turnsOf?.get(pl); + for (const m of mates) out.push(...(this.mateResidual(m, pl, L, ref, true, turns) ?? [])); if (drives.length) out.push(...driveResidual(drives, pl, ref, L)); if (withDrag && opts.drag) out.push(...dragResidual(opts.drag, pl, L).map((v) => v * dragWeight)); return out; @@ -946,7 +954,7 @@ export class MateSolver { iterations++; const mateCost = withDrag ? sumSq(rows(at(x), false)) : cost; if (!withDrag && Math.sqrt(mateCost) < TOL) break; - const J = this.jacobian(x, sys, placements, mates, withDrag ? opts.drag ?? null : null, dragWeight, r.length, n, vw, L, drives); + const J = this.jacobian(x, sys, placements, mates, withDrag ? opts.drag ?? null : null, dragWeight, r.length, n, vw, L, drives, coupled); const g = new Array(n).fill(0); const A = Array.from({ length: n }, () => new Array(n).fill(0)); for (let i = 0; i < r.length; i++) { @@ -1001,19 +1009,6 @@ export class MateSolver { run(false, maxIter); } else run(false, maxIter); const final = at(x); - // Gear, rack and pinion and screw mates measure turns within a solve, up to half a turn - // either way: a drag that turns a component further (a rack pulled far in one pointer - // move) could land on the turn the other way round, so it is made in two halves. - if (drag && depth < 4 && mates.some((m) => m.type === 'gear' || m.type === 'rackPinion' || m.type === 'screw') && vars.some((id) => turnAngle(final.get(id)!.q, placements.get(id)!.q) > Math.PI / 2)) { - const from = placements.get(drag.body); - if (from) { - const half: DragGoal = drag.kind === 'move' - ? { ...drag, target: scale(add(applyPlacement(from, drag.local), drag.target), 0.5) } - : { ...drag, q: qNormalize(qMul(rotVecQuat(scale(quatRotVec(qMul(drag.q, qConj(from.q))), 0.5)), from.q)) }; - const first = this.solve({ ...opts, drag: half }, mates, placements, depth + 1); - return this.solve(opts, mates, first.placements, depth + 1); - } - } const worst = evalMates(final), dw = driveWorst(final); return { placements: final, ok: worst < CONFLICT_TOL && dw < CONFLICT_TOL, residuals, iterations, driveResidual: dw }; } @@ -1023,7 +1018,7 @@ export class MateSolver { * differences: each mate depends on the variables of its two components only. * Columns are divided by the variables' weights (`vw`, one per variable). */ - private jacobian(x: number[], sys: System, base: Map, mates: SolverMate[], drag: DragGoal | null, dragWeight: number, m: number, n: number, vw: number[], L: number, drives: Drive[] = []): number[][] { + private jacobian(x: number[], sys: System, base: Map, mates: SolverMate[], drag: DragGoal | null, dragWeight: number, m: number, n: number, vw: number[], L: number, drives: Drive[] = [], coupled = false): number[][] { const J = Array.from({ length: m }, () => new Array(n).fill(0)); const h = 1e-6; const current = new Map(base); @@ -1031,11 +1026,13 @@ export class MateSolver { // One component moved at a time, in one map put back after each (a copy // of every placement per evaluation made large assemblies drag slowly). const work = new Map(current); + const turns = coupled ? turnsAt(sys.vars, x) : undefined; const perturbed = (id: Id, j: number, d: number): Map => { const i = sys.index.get(id)!; const xv = x.slice(i * 6, i * 6 + 6); xv[j] += d; work.set(id, placementWith(sys.bodies.get(id)!.placement, sys.centers.get(id)!, xv, 0, L)); + turns?.set(id, [xv[3], xv[4], xv[5]]); return work; }; const block = (row: number, bodies: (Id | null)[], f: (pl: Map) => number[]) => { @@ -1047,11 +1044,12 @@ export class MateSolver { for (let i = 0; i < rp.length; i++) J[row + i][k + j] = (rp[i] - rm[i]) / (2 * h) / vw[k + j]; } work.set(id, current.get(id)!); + turns?.set(id, [x[k + 3], x[k + 4], x[k + 5]]); } }; let row = 0; for (const mt of mates) { - const f = (pl: Map) => this.mateResidual(mt, pl, L, base) ?? []; + const f = (pl: Map) => this.mateResidual(mt, pl, L, base, true, turns) ?? []; const len0 = f(current).length; block(row, mateBodies(mt), f); row += len0; @@ -1065,9 +1063,12 @@ export class MateSolver { * A mate's residuals with the components where `pl` puts them; null when * it cannot be formed. `ref`: where the components started (what coupling * mates measure motion from). `ineq`: with the rows of limits (left out of - * the rank analysis: a limit takes no freedom away). + * the rank analysis: a limit takes no freedom away). `turns`: how far each + * moving component turned from `ref` (a rotation vector, which unlike the + * orientation itself goes on past half a turn); without it the turns are + * read from the orientations. */ - mateResidual(m: SolverMate, pl: Map, L: number, ref: Map = pl, ineq = true): number[] | null { + mateResidual(m: SolverMate, pl: Map, L: number, ref: Map = pl, ineq = true, turns?: Map): number[] | null { const pa = m.a.body ? pl.get(m.a.body) ?? null : null; const pb = m.b.body ? pl.get(m.b.body) ?? null : null; if ((m.a.body && !pa) || (m.b.body && !pb)) return null; @@ -1080,9 +1081,15 @@ export class MateSolver { const now = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? IDENT : IDENT); const start = (e: SolverEntity) => (e.body ? ref.get(e.body) ?? now(e) : IDENT); for (const e of [m.a2, m.b2]) if (e?.body && !pl.get(e.body)) return null; + const turned = (e: SolverEntity, d: Vec3) => { + if (!e.body) return 0; + if (!turns) return turnAbout(now(e).q, start(e).q, d); + const w = turns.get(e.body); + return w ? dot(w, d) : 0; + }; return mechanicalEquations({ m, ga: placeGeo(m.a.geo, pa), gb: placeGeo(m.b.geo, pb), ga2: m.a2 ? placeGeo(m.a2.geo, m.a2.body ? now(m.a2) : null) : null, gb2: m.b2 ? placeGeo(m.b2.geo, m.b2.body ? now(m.b2) : null) : null, - pa: now(m.a), pb: now(m.b), ra: start(m.a), rb: start(m.b), now, start, L, ineq, + pa: now(m.a), pb: now(m.b), ra: start(m.a), rb: start(m.b), now, start, turned, L, ineq, }); } @@ -1247,6 +1254,9 @@ function dragResidual(goal: DragGoal, pl: Map, L: number): number const sumSq = (r: number[]) => r.reduce((s, v) => s + v * v, 0); +/** The rotation vectors of the variables (each component's turn from where the solve started). */ +const turnsAt = (vars: Id[], x: number[]): Map => new Map(vars.map((id, i) => [id, [x[i * 6 + 3], x[i * 6 + 4], x[i * 6 + 5]] as Vec3])); + /** Solves the symmetric positive definite system A x = b (null when it is not positive definite). */ function choleskySolve(A: number[][], b: number[]): number[] | null { const n = b.length; diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 7f2d027138..15ac824756 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -231,6 +231,14 @@ describe('mechanical mates', () => { const t = dx / 10; expect(dot(qRotate(one.placements.get('P')!.q, [1, 0, 0]), [Math.cos(t), Math.sin(t), 0])).toBeCloseTo(1, 6); } + // A mate's new value moving the rack 50 or 100 mm at once: the pinion turns with it (not a conflict). + for (const v of [50, 100]) { + const to = mate('distance', ['g', plane([0, 0, 0], [1, 0, 0])], ['R', plane([0, 0, 0], [1, 0, 0])], { value: v }); + const r = new MateSolver(s.bodies, [...s.mates, to]).analyze(); + expect(r.status).toBe('full'); + expect(r.placements.get('R')!.p[0]).toBeCloseTo(v, 6); + expect(dot(qRotate(r.placements.get('P')!.q, [1, 0, 0]), [Math.cos(v / 10), Math.sin(v / 10), 0])).toBeCloseTo(1, 6); + } // By travel per turn, and reversed. const per = rackAndPinion({ by: 'revolution', value: 50, reverse: true }); const r2 = computeMotion({ bodies: per.bodies, mates: per.mates, motors: [rotary('P', axis([0, 0, 0]), 360)], duration: 1, fps: 30, scale: 100 }); From 8a5ef7f62b697c70834e0802db4ba8e95f900e50 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:24:17 -0700 Subject: [PATCH 031/116] Parametric: motion velocities stay accurate where a study took smaller steps (frames not evenly spaced) --- src/parametric/src/assembly/motion.ts | 13 +++++++++---- src/parametric/tests/assembly-kinematics.test.ts | 9 +++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index aa37c552b9..b26d11957c 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -333,11 +333,16 @@ export function derivatives(t: number[], v: number[]): { d1: number[]; d2: numbe const n = v.length; const d1 = new Array(n).fill(0), d2 = new Array(n).fill(0); if (n < 2) return { d1, d2 }; - for (let i = 0; i < n; i++) { - const a = Math.max(0, i - 1), b = Math.min(n - 1, i + 1); - d1[i] = (v[b] - v[a]) / (t[b] - t[a] || 1); + if (n < 3) { + d1[0] = d1[1] = (v[1] - v[0]) / (t[1] - t[0] || 1); + return { d1, d2 }; + } + // The slope of the parabola through each sample and the two beside it (steps h1 before, h2 after: + // the frames of a study are not evenly spaced where it took smaller steps). + for (let i = 1; i < n - 1; i++) { + const h1 = t[i] - t[i - 1], h2 = t[i + 1] - t[i]; + d1[i] = (-h2 / (h1 * (h1 + h2))) * v[i - 1] + ((h2 - h1) / (h1 * h2)) * v[i] + (h1 / (h2 * (h1 + h2))) * v[i + 1]; } - if (n < 3) return { d1, d2 }; // The slope at an end of the parabola through it and the two samples beside it (steps h1 then h2 away). const end = (f0: number, f1: number, f2: number, h1: number, h2: number) => (-(2 * h1 + h2) / (h1 * (h1 + h2))) * f0 + ((h1 + h2) / (h1 * h2)) * f1 - (h1 / (h2 * (h1 + h2))) * f2; d1[0] = end(v[0], v[1], v[2], t[1] - t[0], t[2] - t[1]); diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 15ac824756..faed391a9c 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -430,6 +430,15 @@ describe('motion studies', () => { expect(Math.abs(h.d2[0])).toBeLessThan(0.02 * peak); expect(Math.abs(h.d2[30])).toBeLessThan(0.02 * peak); expect(h.d1[0] / (20 * Math.PI)).toBeCloseTo(1, 1); + // Frames not evenly spaced (a study took smaller steps between 0.5 s and 0.8 s): the slope where the steps change is as good as elsewhere. + const tu: number[] = []; + for (let k = 0; k <= 20; k++) { if (k > 5 && k <= 8) for (let j = 1; j < 4; j++) tu.push((k - 1 + j / 4) / 10); tu.push(k / 10); } + const f = (s: number) => 400 * Math.sin(2 * Math.PI * s), df = (s: number) => 800 * Math.PI * Math.cos(2 * Math.PI * s); + const even = Array.from({ length: 21 }, (_, k) => k / 10), de = derivatives(even, even.map(f)).d1; + const worstEven = Math.max(...even.map((s, i) => Math.abs(de[i] - df(s)))); + const du = derivatives(tu, tu.map(f)).d1; + tu.forEach((s, i) => expect(Math.abs(du[i] - df(s))).toBeLessThanOrEqual(worstEven + 1e-9)); + expect(derivatives([0, 0.5], [1, 2]).d1).toEqual([2, 2]); expect(resultsCsv([{ name: 'Time (s)', values: [0, 0.5] }, { name: 'X, mm', values: [1, 2.25] }])).toBe('Time (s),"X, mm"\n0,1\n0.5,2.25'); expect(len(sub(pointPath({ times: [0], frames: [new Map([['a', { p: [1, 2, 3], q: [0, 0, 0, 1] }]])], stop: null, duration: 1 }, 'a', [1, 0, 0])[0], [2, 2, 3]))).toBe(0); }); From e3e464b0ed3a5e9734bd8bf07c648a9872a50a5f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:27:00 -0700 Subject: [PATCH 032/116] Parametric: interference over a motion study checks frames spread evenly in time (not bunched where the study took smaller steps) --- src/parametric/src/app/assembly/mode.ts | 6 +++--- src/parametric/src/assembly/motion.ts | 17 +++++++++++++++++ .../tests/assembly-kinematics.test.ts | 13 ++++++++++++- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index eb89b2f3db..fffafd6936 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -19,7 +19,7 @@ import { type ComposedModel, type PartGeometry, camProfileOf, combinedName, comp import { type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, } from '../../assembly/solver'; -import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, profileOf } from '../../assembly/motion'; +import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, framesSpread, profileOf } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; import { confirmDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; @@ -780,8 +780,8 @@ export class AssemblyMode { * shows are put back in the worker's scene afterwards. Null when cancelled. */ async motionInterference(res: MotionResult, most: number, onProgress: (f: number) => void, cancelled: () => boolean): Promise<{ time: number; pairs: [Id, Id][] }[] | null> { - const n = res.frames.length; - const picks = [...new Set(Array.from({ length: Math.min(n, most) }, (_, k) => Math.round((k * (n - 1)) / Math.max(1, Math.min(n, most) - 1))))]; + // Spread over the time (a study's frames are closer where it took smaller steps). + const picks = framesSpread(res.times, most); const out: { time: number; pairs: [Id, Id][] }[] = []; try { for (const [k, i] of picks.entries()) { diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index b26d11957c..61c461fa30 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -281,6 +281,23 @@ export function computeMotion(setup: MotionSetup): MotionResult { // ---------- results ---------- +/** `most` frames (or all of them) spread evenly over a study's time: their indices, the first and last included. */ +export function framesSpread(times: number[], most: number): number[] { + const n = times.length, m = Math.min(n, Math.max(1, most)); + if (m < 2) return [0]; + if (m === n) return times.map((_, i) => i); + const end = times[n - 1], out: number[] = []; + for (let k = 0; k < m; k++) { + const t = (end * k) / (m - 1); + let lo = 0, hi = n - 1; + while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (times[mid] <= t) lo = mid; else hi = mid - 1; } + const near = lo + 1 < n && times[lo + 1] - t < t - times[lo] ? lo + 1 : lo; + // Each a frame of its own, with room left for the rest. + out.push(Math.min(Math.max(near, k ? out[k - 1] + 1 : 0), n - m + k)); + } + return out; +} + /** Where a point of a component (its local coordinates) is in each frame. */ export function pointPath(res: MotionResult, body: Id, local: Vec3): Vec3[] { return res.frames.map((f) => applyPlacement(f.get(body) ?? { p: [0, 0, 0], q: [0, 0, 0, 1] }, local)); diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index faed391a9c..8f895c3cdf 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, profileSupport, relativePlacement, turnAbout } from '../src/assembly/solver'; import { type PartGeometry, camProfileOf } from '../src/assembly/compose'; -import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, mateSeries, pointPath, profileOf, resultsCsv, turnPath, vectorDerivatives } from '../src/assembly/motion'; +import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, framesSpread, mateSeries, pointPath, profileOf, resultsCsv, turnPath, vectorDerivatives } from '../src/assembly/motion'; import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; import type { MateType, Placement } from '../src/model/assembly'; @@ -416,6 +416,17 @@ describe('motion studies', () => { expect(series[100] - series[0]).toBeCloseTo(slide(390) - slide(30), 4); }); + it('spreads interference checks over the time (frames closer where a study took smaller steps)', () => { + // Frames 0.1 s apart, then (a fast stretch) 0.025 s apart. + const times = [0, 0.1, 0.2, 0.225, 0.25, 0.275, 0.3, 0.325, 0.35, 0.375, 0.4]; + expect(framesSpread(times, 5)).toEqual([0, 1, 2, 6, 10]); + expect(framesSpread(times, 50)).toHaveLength(11); + // As many as asked for, each a frame of its own (frames 0.1 s apart where 0.05 s would be wanted). + const picks = framesSpread([0, 0.1, 0.2, 0.3, 0.325, 0.35, 0.375, 0.4], 7); + expect(picks).toEqual([0, 1, 2, 3, 4, 5, 7]); + expect(framesSpread([0], 40)).toEqual([0]); + }); + it('differentiates samples and writes CSV', () => { const t = [0, 0.1, 0.2, 0.3, 0.4]; const { d1, d2 } = derivatives(t, t.map((x) => x * x)); From e9181e7720ead230dd8e4de6df5180482380e7f7 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:29:20 -0700 Subject: [PATCH 033/116] Parametric: interference over a motion study skips pairs that did not move relative to each other and the overlap meshes it does not show (15 components, 40 frames: 2.0 s to 0.5 s) --- src/parametric/src/app/assembly/mode.ts | 14 ++++++++++---- src/parametric/src/assembly/motion.ts | 19 +++++++++++++++++++ src/parametric/src/kernel/assembly.ts | 12 +++++++++--- src/parametric/src/kernel/worker.ts | 2 +- src/parametric/tests/assembly-kernel.test.ts | 10 ++++++++++ .../tests/assembly-kinematics.test.ts | 13 +++++++++++-- 6 files changed, 60 insertions(+), 10 deletions(-) diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index fffafd6936..69d3f9141b 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -19,7 +19,7 @@ import { type ComposedModel, type PartGeometry, camProfileOf, combinedName, comp import { type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, } from '../../assembly/solver'; -import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, framesSpread, profileOf } from '../../assembly/motion'; +import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, framesSpread, profileOf, sameMotionGroups } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; import { confirmDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; @@ -783,14 +783,20 @@ export class AssemblyMode { // Spread over the time (a study's frames are closer where it took smaller steps). const picks = framesSpread(res.times, most); const out: { time: number; pairs: [Id, Id][] }[] = []; + // The first frame checked: pairs that have not moved relative to each other since overlap as they did there. + let first: { placements: Placement[]; hits: [number, number][] } | null = null; try { for (const [k, i] of picks.entries()) { const all = this.doc.components.filter((c) => !c.suppressed && this.geometryOf(c.part)).map((comp) => ({ comp, placement: res.frames[i].get(comp.id) ?? this.solved.get(comp.id) ?? comp.placement })); await this.app.kernel.assembly({ op: 'scene', items: this.sceneItems(all) }); - const pairs = await this.app.kernel.assembly({ op: 'interference' }); + const groups: number[] | undefined = first ? sameMotionGroups(first.placements, all.map((x) => x.placement)) : undefined; + const pairs = await this.app.kernel.assembly({ op: 'interference', mesh: false, ...(groups ? { groups } : {}) }); if (cancelled() || this.app.assembly !== this) return null; - const hit = pairs.filter((p) => !p.failed && p.volume > 1e-6).map((p) => [all[p.a].comp.id, all[p.b].comp.id] as [Id, Id]); - if (hit.length) out.push({ time: res.times[i], pairs: hit }); + const hits: [number, number][] = pairs.filter((p) => !p.failed && p.volume > 1e-6).map((p) => [p.a, p.b] as [number, number]); + if (!first) first = { placements: all.map((x) => x.placement), hits }; + else hits.push(...first.hits.filter(([a, b]) => groups![a] === groups![b])); + hits.sort((x, y) => x[0] - y[0] || x[1] - y[1]); + if (hits.length) out.push({ time: res.times[i], pairs: hits.map(([a, b]) => [all[a].comp.id, all[b].comp.id] as [Id, Id]) }); onProgress((k + 1) / picks.length); } } finally { diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index 61c461fa30..d40c3dbd04 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -298,6 +298,25 @@ export function framesSpread(times: number[], most: number): number[] { return out; } +/** + * Groups of placements that moved the same rigid way from `from` to `to` + * (a group number for each): two components in one group did not move + * relative to each other, so they overlap now just as they did there. + */ +export function sameMotionGroups(from: Placement[], to: Placement[]): number[] { + const keys = new Map(); + return to.map((b, i) => { + const a = from[i]; + // The motion: a turn dq, then a move dp (b = dq a + dp). + let dq = qMul(b.q, [-a.q[0], -a.q[1], -a.q[2], a.q[3]]); + if (dq[3] < 0) dq = [-dq[0], -dq[1], -dq[2], -dq[3]]; + const r = qRotate(dq, a.p), dp = [b.p[0] - r[0], b.p[1] - r[1], b.p[2] - r[2]]; + const key = [...dq.map((v) => Math.round(v * 1e9)), ...dp.map((v) => Math.round(v * 1e6))].join(','); + if (!keys.has(key)) keys.set(key, keys.size); + return keys.get(key)!; + }); +} + /** Where a point of a component (its local coordinates) is in each frame. */ export function pointPath(res: MotionResult, body: Id, local: Vec3): Vec3[] { return res.frames.map((f) => applyPlacement(f.get(body) ?? { p: [0, 0, 0], q: [0, 0, 0, 1] }, local)); diff --git a/src/parametric/src/kernel/assembly.ts b/src/parametric/src/kernel/assembly.ts index f5dd43208c..036a08adae 100644 --- a/src/parametric/src/kernel/assembly.ts +++ b/src/parametric/src/kernel/assembly.ts @@ -80,7 +80,12 @@ export type AsmRequest = | { op: 'build'; parts: AsmPartBuild[] } | { op: 'scene'; items: AsmSceneItem[] } | { op: 'drop'; keep: string[] } - | { op: 'interference' } + /** + * groups: a group per scene item; pairs in one group are not checked (they did not + * move relative to each other since a check the caller keeps). mesh: false leaves + * out the meshes of the shared solids. + */ + | { op: 'interference'; groups?: number[]; mesh?: boolean } /** densities: kg/m³ for each scene item. */ | { op: 'mass'; densities: number[] } /** Drawing projections of components placed as given (the scene is left as it is). */ @@ -314,7 +319,7 @@ export class AssemblyBuilder { * Pairs of components whose solids overlap, with the volume they share, and * pairs whose overlap could not be computed (`failed`: never reported as clear). */ - interference(): InterferencePair[] { + interference(opts: { groups?: number[]; mesh?: boolean } = {}): InterferencePair[] { const list = this.bodies().map((b) => ({ ...b, box: bbox(b.shape) })); const all = this.combined(); const ab = all ? bbox(all) : null; @@ -324,6 +329,7 @@ export class AssemblyBuilder { for (let x = 0; x < list.length; x++) { for (let y = x + 1; y < list.length; y++) { const A = list[x], B = list[y]; + if (opts.groups && opts.groups[A.i] === opts.groups[B.i]) continue; if (!A.box || !B.box || !boxesOverlap(A.box, B.box)) continue; let shared: Sh, v: number; try { @@ -335,7 +341,7 @@ export class AssemblyBuilder { } if (!Number.isFinite(v)) { out.push({ a: A.i, b: B.i, volume: 0, mesh: null, failed: true }); continue; } if (!(v > minVolume)) continue; - out.push({ a: A.i, b: B.i, volume: v, mesh: meshOf(shared, diag) }); + out.push({ a: A.i, b: B.i, volume: v, mesh: opts.mesh === false ? null : meshOf(shared, diag) }); } } return out; diff --git a/src/parametric/src/kernel/worker.ts b/src/parametric/src/kernel/worker.ts index 6fa6a0b190..d3d6136f10 100644 --- a/src/parametric/src/kernel/worker.ts +++ b/src/parametric/src/kernel/worker.ts @@ -130,7 +130,7 @@ async function handle(ev: MessageEvent) { : r.op === 'scene' ? (assembly.setScene(r.items), true) : r.op === 'drop' ? (assembly.drop(r.keep), true) : r.op === 'project' ? assembly.projectItems(r.items, r.views) - : r.op === 'interference' ? assembly.interference() + : r.op === 'interference' ? assembly.interference({ groups: r.groups, mesh: r.mesh }) : assembly.mass(r.densities); // The heap lets the main thread replace a worker that grew too big, as after part builds. reply({ id: msg.id, ok: true, result, heap: memory?.buffer.byteLength }, r.op === 'build' || r.op === 'interference' ? asmTransfers(result) : []); diff --git a/src/parametric/tests/assembly-kernel.test.ts b/src/parametric/tests/assembly-kernel.test.ts index 5b097382d4..85fd89cee2 100644 --- a/src/parametric/tests/assembly-kernel.test.ts +++ b/src/parametric/tests/assembly-kernel.test.ts @@ -95,6 +95,16 @@ describe('assembly geometry', () => { expect(a.interference()).toEqual([]); }); + it('checks only pairs in different groups, and leaves out meshes when asked (a motion study frame by frame)', async () => { + const a = new AssemblyBuilder(); + await built(a); + a.setScene([item('box', at([0, 0, 0]), 'box<1>'), item('box', at([15, 0, 0]), 'box<2>'), item('pin', at([5, 5, -10]), 'pin<1>')]); + const pairs = a.interference({ mesh: false, groups: [0, 0, 1] }); + expect(pairs.map((p) => [p.a, p.b])).toEqual([[0, 2]]); + expect(pairs[0].volume).toBeCloseTo(Math.PI * 9 * 10, 1); + expect(pairs[0].mesh).toBeNull(); + }); + it('reports a pair whose overlap cannot be computed as not checked, never as clear', async () => { const a = new AssemblyBuilder(); await built(a); diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 8f895c3cdf..d55717a0c3 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, profileSupport, relativePlacement, turnAbout } from '../src/assembly/solver'; import { type PartGeometry, camProfileOf } from '../src/assembly/compose'; -import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, framesSpread, mateSeries, pointPath, profileOf, resultsCsv, turnPath, vectorDerivatives } from '../src/assembly/motion'; +import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, framesSpread, mateSeries, pointPath, profileOf, resultsCsv, sameMotionGroups, turnPath, vectorDerivatives } from '../src/assembly/motion'; import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; import type { MateType, Placement } from '../src/model/assembly'; @@ -416,7 +416,7 @@ describe('motion studies', () => { expect(series[100] - series[0]).toBeCloseTo(slide(390) - slide(30), 4); }); - it('spreads interference checks over the time (frames closer where a study took smaller steps)', () => { + it('spreads interference checks over the time, and groups components that moved together', () => { // Frames 0.1 s apart, then (a fast stretch) 0.025 s apart. const times = [0, 0.1, 0.2, 0.225, 0.25, 0.275, 0.3, 0.325, 0.35, 0.375, 0.4]; expect(framesSpread(times, 5)).toEqual([0, 1, 2, 6, 10]); @@ -425,6 +425,15 @@ describe('motion studies', () => { const picks = framesSpread([0, 0.1, 0.2, 0.3, 0.325, 0.35, 0.375, 0.4], 7); expect(picks).toEqual([0, 1, 2, 3, 4, 5, 7]); expect(framesSpread([0], 40)).toEqual([0]); + const at = (p: Vec3, q: Quat = [0, 0, 0, 1]): Placement => ({ p, q }); + const turn = qAxisAngle(Z, 0.7); + const from = [at([0, 0, 0]), at([10, 0, 0]), at([0, 5, 0]), at([3, 3, 3]), at([1, 2, 3])]; + // 0 and 1 still; 2 and 3 turned together about z; 4 moved. + const rot = (p: Placement): Placement => ({ p: qRotate(turn, p.p), q: turn }); + const g = sameMotionGroups(from, [from[0], from[1], rot(from[2]), rot(from[3]), at([1, 2, 4])]); + expect(g[0]).toBe(g[1]); + expect(g[2]).toBe(g[3]); + expect(new Set([g[0], g[2], g[4]]).size).toBe(3); }); it('differentiates samples and writes CSV', () => { From 2b1d057abc0c8e506be04085cc24c16accc7899b Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:37:17 -0700 Subject: [PATCH 034/116] Parametric: assembly drag is back to its old cost for assemblies with plain mates (no per-call allocation for mechanical mates, mate bodies found once per drag step) 10-component chain, 60 drag steps, plain node: origin/main 1.92 ms/step, PR 1.97, now 1.94 (medians of 30, within run-to-run noise). --- src/parametric/src/assembly/solver.ts | 48 ++++++++++++++++----------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index c79009c9a1..57d538e5cd 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -200,6 +200,8 @@ const IDENT: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; /** The components a mate's entities belong to (each once). */ export function mateBodies(m: SolverMate): Id[] { + // Most mates have one entity on each side (the hot path of every drag step). + if (!m.a2 && !m.b2) return m.a.body ? (m.b.body && m.b.body !== m.a.body ? [m.a.body, m.b.body] : [m.a.body]) : m.b.body ? [m.b.body] : []; const out: Id[] = []; for (const e of [m.a, m.b, m.a2, m.b2]) if (e?.body && !out.includes(e.body)) out.push(e.body); return out; @@ -1072,25 +1074,10 @@ export class MateSolver { const pa = m.a.body ? pl.get(m.a.body) ?? null : null; const pb = m.b.body ? pl.get(m.b.body) ?? null : null; if ((m.a.body && !pa) || (m.b.body && !pb)) return null; + if (isMechanical(m.type)) return mechanicalResidual(m, pl, ref, pa, pb, L, ineq, turns); const o = { aligned: m.aligned, value: m.value, flip: m.flip, scale: L, rel: m.rel }; - if (!isMechanical(m.type)) { - const ga = placeGeo(m.a.geo, pa), gb = placeGeo(m.b.geo, pb); - if (m.limit && (m.type === 'distance' || m.type === 'angle')) return limitEquations(m.type, ga, gb, o, m.limit, ineq); - return equations(m.type, ga, gb, o, pa, pb); - } - const now = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? IDENT : IDENT); - const start = (e: SolverEntity) => (e.body ? ref.get(e.body) ?? now(e) : IDENT); - for (const e of [m.a2, m.b2]) if (e?.body && !pl.get(e.body)) return null; - const turned = (e: SolverEntity, d: Vec3) => { - if (!e.body) return 0; - if (!turns) return turnAbout(now(e).q, start(e).q, d); - const w = turns.get(e.body); - return w ? dot(w, d) : 0; - }; - return mechanicalEquations({ - m, ga: placeGeo(m.a.geo, pa), gb: placeGeo(m.b.geo, pb), ga2: m.a2 ? placeGeo(m.a2.geo, m.a2.body ? now(m.a2) : null) : null, gb2: m.b2 ? placeGeo(m.b2.geo, m.b2.body ? now(m.b2) : null) : null, - pa: now(m.a), pb: now(m.b), ra: start(m.a), rb: start(m.b), now, start, turned, L, ineq, - }); + if (m.limit && (m.type === 'distance' || m.type === 'angle')) return limitEquations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, m.limit, ineq); + return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, pa, pb); } /** @@ -1209,6 +1196,26 @@ export class MateSolver { } } +/** + * A mechanical mate's residuals (see mateResidual). On its own: the closures + * here would make every call of mateResidual allocate, plain mates too. + */ +function mechanicalResidual(m: SolverMate, pl: Map, ref: Map, pa: Placement | null, pb: Placement | null, L: number, ineq: boolean, turns?: Map): number[] | null { + const now = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? IDENT : IDENT); + const start = (e: SolverEntity) => (e.body ? ref.get(e.body) ?? now(e) : IDENT); + for (const e of [m.a2, m.b2]) if (e?.body && !pl.get(e.body)) return null; + const turned = (e: SolverEntity, d: Vec3) => { + if (!e.body) return 0; + if (!turns) return turnAbout(now(e).q, start(e).q, d); + const w = turns.get(e.body); + return w ? dot(w, d) : 0; + }; + return mechanicalEquations({ + m, ga: placeGeo(m.a.geo, pa), gb: placeGeo(m.b.geo, pb), ga2: m.a2 ? placeGeo(m.a2.geo, m.a2.body ? now(m.a2) : null) : null, gb2: m.b2 ? placeGeo(m.b2.geo, m.b2.body ? now(m.b2) : null) : null, + pa: now(m.a), pb: now(m.b), ra: start(m.a), rb: start(m.b), now, start, turned, L, ineq, + }); +} + /** * The mates that can move a component: those of the floating components * linked to it through mates between floating components. Mates of other @@ -1218,10 +1225,11 @@ export class MateSolver { export function matesMoving(body: Id, bodies: SolverBody[], mates: SolverMate[]): SolverMate[] { const floating = new Set(bodies.filter((b) => !b.fixed).map((b) => b.id)); const linked = new Set([body]); + // The floating components of each mate, found once (this runs on every drag step). + const each = mates.map((m) => mateBodies(m).filter((id) => floating.has(id))); for (let grew = true; grew;) { grew = false; - for (const m of mates) { - const ids = mateBodies(m).filter((id) => floating.has(id)); + for (const ids of each) { if (ids.length > 1 && ids.some((id) => linked.has(id)) && ids.some((id) => !linked.has(id))) { for (const id of ids) linked.add(id); grew = true; } } } From ab17fbd8a2e586d490dc034d9c730cbf9632d4e6 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:39:28 -0700 Subject: [PATCH 035/116] Parametric: a gear, rack or screw mate that contradicts the mates before it (another ratio between the same gears, an odd ring of gears) is over defined, not fully defined --- src/parametric/src/assembly/solver.ts | 47 +++++++++++++++++++ .../tests/assembly-kinematics.test.ts | 23 +++++++++ 2 files changed, 70 insertions(+) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index 57d538e5cd..0e225f0707 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -1142,6 +1142,10 @@ export class MateSolver { if (!g.mates.length) { dof += n; continue; } const index = new Map(g.bodies.map((b, i) => [b.id, i])); const J: number[][] = []; + // Gear, rack and pinion and screw mates hold at the start of every solve whatever their + // ratio, so one that contradicts the mates before it is found here: see contradicts. + const coupled = g.mates.some(isCoupling) ? new Map(g.bodies.map((b) => [b.id, b.id])) : null; + const top = (id: Id): Id => { let r = id; while (coupled!.get(r) !== r) r = coupled!.get(r)!; return r; }; for (const m of g.mates) { const base = this.mateResidual(m, pl, L, pl, false); if (!base) continue; @@ -1162,6 +1166,15 @@ export class MateSolver { } work.set(id, pl.get(id)!); } + if (coupled) { + const ids = mateBodies(m).filter((id) => index.has(id)); + // Only where the mates before it already link its components (a loop) can it contradict them. + if (isCoupling(m) && ids.length > 1 && ids.every((id) => top(id) === top(ids[0])) && contradicts(J, block[block.length - 1], ids.map((id) => index.get(id)!), n)) { + conflicts.add(m.id); + continue; + } + for (const id of ids.slice(1)) coupled.set(top(id), top(ids[0])); + } J.push(...block); } // A component is fully defined when no motion the mates allow moves it: @@ -1236,6 +1249,40 @@ export function matesMoving(body: Id, bodies: SolverBody[], mates: SolverMate[]) return mates.filter((m) => mateBodies(m).some((id) => linked.has(id))); } +const isCoupling = (m: SolverMate) => m.type === 'gear' || m.type === 'rackPinion' || m.type === 'screw'; + +/** + * Whether a coupling mate (its row `c` of the Jacobian) contradicts the mates + * before it (rows J, n variables): they let its components (`bodies`, by + * index) move, related another way, and with it they cannot move at all (two + * gear mates with different ratios between the same gears: they hold only + * while nothing turns). + */ +function contradicts(J: number[][], c: number[], bodies: number[], n: number): boolean { + const { basis } = nullSpace(J, n); + if (!basis.length) return false; + let vmax = 0, cmax = 0; + for (const v of basis) for (const x of v) vmax = Math.max(vmax, Math.abs(x)); + for (const x of c) cmax = Math.max(cmax, Math.abs(x)); + // What the mate asks of each motion the others allow. + const g = basis.map((v) => v.reduce((s, x, j) => s + x * c[j], 0)); + const gg = g.reduce((s, x) => s + x * x, 0); + if (Math.sqrt(gg) <= 1e-7 * cmax * vmax) return false; + let moved = false; + for (const b of bodies) { + for (let j = b * 6; j < b * 6 + 6; j++) { + const row = basis.map((v) => v[j]); + const rmax = Math.max(...row.map(Math.abs)); + if (rmax <= 1e-6 * vmax) continue; + moved = true; + // With the mate, this variable can still change unless it changes only along g. + const k = row.reduce((s, x, i) => s + x * g[i], 0) / gg; + if (row.some((x, i) => Math.abs(x - k * g[i]) > 1e-6 * rmax)) return false; + } + } + return moved; +} + /** How far each drive is from its motion: radians for turns, lengths over L for moves. */ function driveResidual(drives: Drive[], pl: Map, ref: Map, L: number): number[] { return drives.map((d) => { diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index d55717a0c3..64b4496435 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -160,6 +160,29 @@ describe('mechanical mates', () => { expect(turnAbout(turned.placements.get('B')!.q, [0, 0, 0, 1], Z)).toBeCloseTo(0.25, 5); }); + it('a gear mate contradicting the mates before it is over defined; a repeated or consistent one is not', () => { + const s = gears(); + const [h1, h2, g1] = s.mates; + const other = { ...g1, id: 'g2', value2: 60 }; + const r = new MateSolver(s.bodies, [h1, h2, g1, other]).analyze(); + expect(r.status).toBe('over'); + expect([...r.conflicts]).toEqual(['g2']); + expect(r.dof).toBe(1); + expect(new MateSolver(s.bodies, [h1, h2, g1, { ...g1, id: 'g3' }]).analyze().status).toBe('under'); + // Three external gears in a ring cannot turn; with an internal one (reversed) they can. + const C = body('C', false, [15, 26, 0]); + const ring = (reverse: boolean) => [h1, h2, hinge('g', [15, 26, 0], 'C', [0, 0, 0]), { ...g1, value2: 20 }, mate('gear', ['B', axis([0, 0, 0])], ['C', axis([0, 0, 0])], { value: 20, value2: 20 }), mate('gear', ['C', axis([0, 0, 0])], ['A', axis([0, 0, 0])], { value: 20, value2: 20, reverse, id: 'last' })]; + const odd = new MateSolver([...s.bodies, C], ring(false)).analyze(); + expect([...odd.conflicts]).toEqual(['last']); + const even = new MateSolver([...s.bodies, C], ring(true)).analyze(); + expect(even.status).toBe('under'); + expect(even.dof).toBe(1); + // A gear meshing with a fixed one just holds it. + const held = new MateSolver(s.bodies, [h1, h2, mate('gear', ['A', axis([0, 0, 0])], ['g', axis([30, 0, 0])], { value: 20, value2: 40 })]).analyze(); + expect(held.conflicts.size).toBe(0); + expect(held.defined.has('A')).toBe(true); + }); + it('dragging one gear by a tooth turns the other', () => { const s = gears(); let pl = s.analyze().placements; From 68c65909c27aef1f712e79cecd93ca1bbfd145b1 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:39:53 -0700 Subject: [PATCH 036/116] Parametric: a rack along its pinion's axis is refused with a message (it moved like a screw) --- src/parametric/src/assembly/solver.ts | 9 ++++++++- src/parametric/tests/assembly-kinematics.test.ts | 5 +++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index 0e225f0707..b26d12965b 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -1204,9 +1204,16 @@ export class MateSolver { if (m.type === 'angle' && (m.limit.min < 0 || m.limit.max > 180)) return 'Angle limits are between 0° and 180°'; if (m.type === 'hinge' && !m.rel) return 'The hinge has no stored position to measure its angle from'; } - if (isMechanical(m.type)) return mechanicalProblem(m); + if (isMechanical(m.type)) return mechanicalProblem(m) ?? (m.type === 'rackPinion' ? this.rackProblem(m) : null); return m.type === 'lock' ? null : mateProblem(m.type, m.a.geo, m.b.geo); } + + /** A rack along its pinion's axis (where the components are) is no rack and pinion: it would move as a screw. */ + private rackProblem(m: SolverMate): string | null { + const at = (e: SolverEntity) => (e.body ? this.bodies.find((b) => b.id === e.body)?.placement ?? null : null); + const dp = dirOf(placeGeo(m.a.geo, at(m.a))), u = dirOf(placeGeo(m.b.geo, at(m.b))); + return dp && u && Math.abs(dot(normalize(dp), normalize(u))) > 0.999 ? 'The rack must run across the pinion\'s axis, not along it' : null; + } } /** diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 64b4496435..d6b40db0f6 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -262,6 +262,11 @@ describe('mechanical mates', () => { expect(r.placements.get('R')!.p[0]).toBeCloseTo(v, 6); expect(dot(qRotate(r.placements.get('P')!.q, [1, 0, 0]), [Math.cos(v / 10), Math.sin(v / 10), 0])).toBeCloseTo(1, 6); } + // A rack along the pinion's axis is refused. + const along = { ...s.mates[3], b: { body: 'R', geo: { kind: 'line', p: [0, 0, 0], d: [0, 0, 1] } as Geo } }; + const bad = new MateSolver(s.bodies, [...s.mates.slice(0, 3), along]).analyze(); + expect(bad.status).toBe('error'); + expect(bad.invalid.get(along.id)).toMatch(/across the pinion's axis/); // By travel per turn, and reversed. const per = rackAndPinion({ by: 'revolution', value: 50, reverse: true }); const r2 = computeMotion({ bodies: per.bodies, mates: per.mates, motors: [rotary('P', axis([0, 0, 0]), 360)], duration: 1, fps: 30, scale: 100 }); From 3e14632caa724b11e4029e2276270f287d537665 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:06:45 -0700 Subject: [PATCH 037/116] Parametric: a load's "Along a picked edge or face" direction stays chosen until the edge or face is picked --- src/parametric/src/app/fea/panels.ts | 11 +++---- src/parametric/tests/e2e/analysis.spec.ts | 36 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index ca11a2c2bf..5177506aee 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -256,7 +256,7 @@ export class LoadPanel extends FeaPanel { : valueField('Acceleration', l.value, u.accel, u.accelScale, (v) => { l.value = v; }, { positive: true }); const items: HTMLElement[] = [value]; if (l.type === 'force' || l.type === 'gravity') { - const choice: DirChoice = !l.dir ? 'normal' : l.dir.kind === 'base' ? l.dir.axis : 'ref'; + const choice: DirChoice = this.pickRef ? 'ref' : !l.dir ? 'normal' : l.dir.kind === 'base' ? l.dir.axis : 'ref'; const options: { value: DirChoice; label: string }[] = [ ...(l.type === 'force' ? [{ value: 'normal' as DirChoice, label: 'Normal to the faces' }] : []), { value: 'x', label: 'Along X' }, { value: 'y', label: 'Along Y' }, { value: 'z', label: 'Along Z' }, @@ -266,14 +266,15 @@ export class LoadPanel extends FeaPanel { if (v === 'normal' && l.type === 'force') l.dir = null; else if (v === 'x' || v === 'y' || v === 'z') l.dir = { kind: 'base', axis: v }; else if (v === 'ref') l.dir = (this.refItems[0]?.data as FeaDir | undefined) ?? (l.type === 'force' ? null : l.dir); - if (v === 'ref' && !this.refItems.length) this.pickRef = true; - else this.pickRef = false; + // Picking a reference: the choice stays shown while the direction is not picked yet. + this.pickRef = v === 'ref' && !this.refItems.length; app.refreshPanel(); })); - if (choice === 'ref' || this.pickRef) { + if (choice === 'ref') { const ref = new SelectionBox(this, 'Direction reference', { face: true, edge: true }, (it) => this.toDir(it), (sel) => { this.refItems = sel; if (sel[0]) l.dir = sel[0].data as FeaDir; + else this.pickRef = true; }, { single: true, placeholder: 'Pick an edge or a face', icon: 'axis' }); ref.setItems(this.refItems); items.push(ref.el); @@ -293,7 +294,7 @@ export class LoadPanel extends FeaPanel { const l = this.l; if (l.type !== 'gravity' && !l.faces.length) { this.setMessage('error', 'Pick at least one face.'); return false; } if (!(l.value > 0) || !Number.isFinite(l.value)) { this.setMessage('error', 'Enter a value greater than 0.'); return false; } - if (this.pickRef && (l.type === 'force' || l.type === 'gravity') && (!l.dir || l.dir.kind === 'base')) { this.setMessage('error', 'Pick an edge or face for the direction.'); return false; } + if (this.pickRef && (l.type === 'force' || l.type === 'gravity') && !this.refItems.length) { this.setMessage('error', 'Pick an edge or face for the direction.'); return false; } this.app.store.change(this.creating ? `Add ${l.name}` : `Edit ${l.name}`, (d) => { if (!d.study) return; const i = d.study.loads.findIndex((x) => x.id === l.id); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index f34b0cc50c..7939218c86 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -137,3 +137,39 @@ test('explains a study that cannot run', async ({ page }) => { await expect(page.getByRole('alert').filter({ hasText: /unstable/ })).toBeVisible({ timeout: 60_000 }); expect(errors).toEqual([]); }); + +/** The bracket with Alloy Steel and a study holding one fixture and one force (set in the document, one undo step). */ +async function bracketStudy(page: Page) { + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const ref = (n: string) => { const f = a.faces.find((x) => x.name === n)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + a.store.change('Set up', (d) => { + d.material = { name: 'Alloy Steel', density: 7700, E: 205000, nu: 0.29, yield: 415, uts: 655 }; + d.study = { id: 'st900', name: 'Static Study', fixtures: [{ id: 'fx901', name: 'Fixed-1', type: 'fixed', faces: [ref('f1:side:bl1')] }], loads: [{ id: 'ld902', name: 'Force-1', type: 'force', faces: [ref('f1:side:bl4')], value: 500, dir: null, flip: false }], mesh: { fineness: 0.2 } }; + }); + }); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); +} + +test('a load direction to pick stays chosen until it is picked', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // "Along a picked edge or face" stays chosen while the edge is picked. + for (const cmd of ['fea:force', 'fea:gravity']) { + await page.locator(`[data-cmd="${cmd}"]`).click(); + const dir = page.getByLabel('Direction', { exact: true }); + await dir.selectOption('ref'); + await expect(page.getByRole('group', { name: 'Direction reference' })).toBeVisible(); + await expect(dir).toHaveValue('ref'); + if (cmd === 'fea:gravity') { + await page.locator('.confirm-corner .ok').click(); + await expect(page.locator('.pm-msg')).toContainText('Pick an edge or face for the direction'); + } + await page.locator('.confirm-corner .cancel').click(); + } + expect(errors).toEqual([]); +}); From 7ebbcb7074d4d66f4150a0d726d6d4940454d02f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:06:52 -0700 Subject: [PATCH 038/116] Parametric: the panel of a fixture or load closes when it is deleted or its study is undone, so OK cannot bring it back --- src/parametric/src/app/fea/panels.ts | 4 ++-- src/parametric/src/app/fea/workspace.ts | 5 +++++ src/parametric/tests/e2e/analysis.spec.ts | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 5177506aee..e8a27dd61d 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -164,7 +164,7 @@ export class FixturePanel extends FeaPanel { } get present(): boolean { - return this.creating || !!this.ws.study?.fixtures.some((x) => x.id === this.f.id); + return !!this.ws.study && (this.creating || this.ws.study.fixtures.some((x) => x.id === this.f.id)); } get edited() { return true; } @@ -213,7 +213,7 @@ export class LoadPanel extends FeaPanel { } get present(): boolean { - return this.creating || !!this.ws.study?.loads.some((x) => x.id === this.l.id); + return !!this.ws.study && (this.creating || this.ws.study.loads.some((x) => x.id === this.l.id)); } get edited() { return true; } diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 81b16eca67..276a0a00e0 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -66,6 +66,11 @@ export class FeaWorkspace { constructor(readonly app: App) { app.store.on((reason) => { if (reason === 'load') this.reset(); + const s = this.study; + if (this.focus && !s?.fixtures.some((f) => f.id === this.focus) && !s?.loads.some((l) => l.id === this.focus)) this.focus = null; + // A fixture or load deleted (or its study undone) while its panel is open: OK would bring it back. + const p = app.panel; + if ((p instanceof FixturePanel || p instanceof LoadPanel) && !p.present) void app.closePanel(false); this.changed(); }); app.ribbonTabListeners.push(() => this.redraw()); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 7939218c86..548b3b56d8 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -173,3 +173,22 @@ test('a load direction to pick stays chosen until it is picked', async ({ page } } expect(errors).toEqual([]); }); + +test('the panel of a fixture or load closes when it is deleted', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // Editing Force-1 when it is deleted (here by Undo of its study): OK must not bring it back. + await page.getByRole('treeitem', { name: /^Force-1/ }).dblclick(); + await expect(page.locator('.pm-head').getByText('Force-1', { exact: true })).toBeVisible(); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Delete Force-1', (d) => { d.study!.loads = []; })); + await expect(page.locator('.pm-head')).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads)).toEqual([]); + // A new fixture when the study goes (Undo): its panel closes too. + await page.locator('[data-cmd="fea:fixed"]').click(); + await expect(page.locator('.pm-head').getByText('Fixed', { exact: true })).toBeVisible(); + await page.keyboard.press('Meta+z'); + await page.keyboard.press('Meta+z'); + await expect.poll(() => page.evaluate(() => (window as unknown as W).__parametric.store.doc.study ?? null)).toBeNull(); + await expect(page.locator('.pm-head')).toHaveCount(0); + expect(errors).toEqual([]); +}); From f2a1387231a74d9a7ffb1d3037f714ec55bff5c9 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:11:56 -0700 Subject: [PATCH 039/116] Parametric: the Results and Study panels show a run's progress and Cancel from its start (the first run showed "Run the study") --- src/parametric/src/app/fea/panels.ts | 12 ++++++++---- src/parametric/src/app/fea/workspace.ts | 3 ++- src/parametric/tests/e2e/analysis.spec.ts | 21 +++++++++++++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index e8a27dd61d..00a3032dbc 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -78,11 +78,13 @@ export class StudyPanel extends FeaPanel { this.fineness = s.mesh.fineness; } - progress(_b: { stage: string; progress: number }) { + /** Shows the progress; false when the panel has no progress bar yet (it is drawn again). */ + progress(b: { stage: string; progress: number }): boolean { const bar = this.el.querySelector('progress'); const label = this.el.querySelector('.fea-stage'); - if (bar) bar.value = _b.progress; - if (label) label.textContent = _b.stage; + if (bar) bar.value = b.progress; + if (label) label.textContent = b.stage; + return !!bar; } private commit() { @@ -317,11 +319,13 @@ export class ResultsPanel extends FeaPanel { private plotted: unknown = null; private field: FieldName = 'vonMises'; - progress(b: { stage: string; progress: number }) { + /** Shows the progress; false when the panel has no progress bar yet (it is drawn again). */ + progress(b: { stage: string; progress: number }): boolean { const bar = this.el.querySelector('progress'); const label = this.el.querySelector('.fea-stage'); if (bar) bar.value = b.progress; if (label) label.textContent = b.stage; + return !!bar; } render(): HTMLElement[] { diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 276a0a00e0..a9e9017a6d 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -196,7 +196,8 @@ export class FeaWorkspace { if (was !== stage || Math.round(progress * 100) % 5 === 0) { this.app.renderTrees(); const p = this.app.panel; - if (p instanceof ResultsPanel || p instanceof StudyPanel) p.progress(this.busy); + // A panel drawn before the run started shows it now (its progress bar, Cancel, disabled buttons). + if ((p instanceof ResultsPanel || p instanceof StudyPanel) && !p.progress(this.busy)) this.app.refreshPanel(); } } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 548b3b56d8..d15aebe4a4 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -192,3 +192,24 @@ test('the panel of a fixture or load closes when it is deleted', async ({ page } await expect(page.locator('.pm-head')).toHaveCount(0); expect(errors).toEqual([]); }); + +test('the results panel shows the progress of the first run, with Cancel', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Finer', (d) => { d.study!.mesh.fineness = 0.7; })); + await page.locator('[data-cmd="fea:run"]').click(); + const bar = page.getByRole('progressbar', { name: 'Analysis progress' }); + await expect(bar).toBeVisible(); + await expect(page.locator('.fea-stage')).not.toBeEmpty(); + await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); + await expect(bar).toHaveCount(0); + await expect(page.getByText('Run the study to see its results.')).toBeVisible(); + // Mesh Now in the study panel shows its progress too. + await page.locator('[data-cmd="fea:study"]').click(); + await page.getByRole('button', { name: 'Mesh Now' }).click(); + await expect(page.getByRole('progressbar', { name: 'Progress' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Mesh Now' })).toBeDisabled(); + await expect(page.locator('.fea-stats')).toBeVisible({ timeout: 120_000 }); + expect(errors).toEqual([]); +}); From 5699622ed40eeb8bb1d94638133ab1a8246d24bd Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:11:56 -0700 Subject: [PATCH 040/116] Parametric: cancelling an analysis while the part is being prepared says so in the status bar --- src/parametric/src/app/fea/workspace.ts | 2 ++ src/parametric/tests/e2e/analysis.spec.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index a9e9017a6d..d525eda977 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -358,6 +358,8 @@ export class FeaWorkspace { this.generation++; this.client.cancel(); this.busy = null; + // Also when it stops before the worker started (preparing the part): the status no longer shows a stage. + this.app.setStatus('Analysis cancelled'); this.changed(); } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index d15aebe4a4..ed74f38553 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -205,6 +205,7 @@ test('the results panel shows the progress of the first run, with Cancel', async await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); await expect(bar).toHaveCount(0); await expect(page.getByText('Run the study to see its results.')).toBeVisible(); + await expect(page.locator('.statusbar .msg')).toHaveText('Analysis cancelled'); // Mesh Now in the study panel shows its progress too. await page.locator('[data-cmd="fea:study"]').click(); await page.getByRole('button', { name: 'Mesh Now' }).click(); From c77f30b17eb9f9ea8194bec0f9475c0590258491 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:13:16 -0700 Subject: [PATCH 041/116] Parametric: results of a study or material edited during the run show as out of date (they were solved with the old values) --- src/parametric/src/app/fea/workspace.ts | 24 +++++++++++++++-------- src/parametric/tests/e2e/analysis.spec.ts | 17 ++++++++++++++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index d525eda977..210dc6ab7d 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -55,7 +55,7 @@ export class FeaWorkspace { focus: Id | null = null; private surface: SurfaceState | null = null; private surfaceLoading: Promise | null = null; - mesh: { key: string; info: FeaMeshInfo; size: number } | null = null; + mesh: { key: string; info: FeaMeshInfo; size: number; version: number } | null = null; result: FeaResult | null = null; busy: { stage: string; progress: number } | null = null; error: { key: string; message: string } | null = null; @@ -105,10 +105,15 @@ export class FeaWorkspace { // ---------- state ---------- /** What the results depend on: the part's shape, the mesh size, the study's fixtures and loads, the material. */ - solveKey(size?: number): string { + solveKey(size?: number, version?: number, study?: string): string { + return JSON.stringify([version ?? this.app.geometryVersion, size ?? this.sizeOf(), study ?? this.studyKey()]); + } + + /** The study's fixtures and loads and the material, as the results depend on them. */ + private studyKey(): string { const s = this.study; const strip = (x: FeaFixture | FeaLoad) => { const { name: _n, ...rest } = x; void _n; return rest; }; - return JSON.stringify([this.app.geometryVersion, size ?? this.sizeOf(), s ? [s.fixtures.map(strip), s.loads.map(strip)] : null, elasticOf(this.app.store.doc.material), this.app.store.doc.material?.density]); + return JSON.stringify([s ? [s.fixtures.map(strip), s.loads.map(strip)] : null, elasticOf(this.app.store.doc.material), this.app.store.doc.material?.density]); } private sizeOf(): number { @@ -202,7 +207,7 @@ export class FeaWorkspace { } /** Meshes the part at the study's size if the mesh is not current. */ - async ensureMesh(): Promise<{ info: FeaMeshInfo; size: number } | null> { + async ensureMesh(): Promise<{ info: FeaMeshInfo; size: number; version: number } | null> { const s = this.study; if (!s) return null; const gen = this.generation; @@ -217,7 +222,7 @@ export class FeaWorkspace { const surface = { positions: sf.data.positions.slice(), indices: sf.data.indices.slice(), triFace: sf.data.triFace.slice() }; const info = await this.client.mesh(surface, size, (stage, v) => this.setBusy(`Meshing: ${stage.toLowerCase()}`, v)); if (gen !== this.generation) return null; - this.mesh = { key, info, size }; + this.mesh = { key, info, size, version: sf.version }; return this.mesh; } @@ -321,6 +326,8 @@ export class FeaWorkspace { if (this.busy) return; const gen = ++this.generation; let resolved: ReturnType; + // What is solved is the study and material as they are now (they may change while it runs). + const studyKey = this.studyKey(); try { resolved = this.inputOf(s); } catch (e) { @@ -330,17 +337,18 @@ export class FeaWorkspace { return; } this.error = null; + const el = elasticOf(this.app.store.doc.material)!, matName = this.app.store.doc.material?.name ?? ''; void this.openResults(); try { const m = await this.ensureMesh(); if (!m || gen !== this.generation) return; - const key = this.solveKey(m.size); + // The shape meshed and the study read at the start: a change during the run leaves the results out of date. + const key = this.solveKey(m.size, m.version, studyKey); const t0 = performance.now(); const sol = await this.client.solve(resolved.input, (stage, v) => this.setBusy(stage, v)); if (gen !== this.generation) return; - const el = elasticOf(this.app.store.doc.material)!; this.result = { - key, mesh: m.info, sol, input: resolved.input, yield: el.yield, uts: el.uts, material: this.app.store.doc.material?.name ?? '', size: m.size, + key, mesh: m.info, sol, input: resolved.input, yield: el.yield, uts: el.uts, material: matName, size: m.size, fixtureNames: resolved.fixtureNames, loadNames: resolved.loadNames, when: Date.now(), }; this.busy = null; diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index ed74f38553..4fc1570f2b 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -214,3 +214,20 @@ test('the results panel shows the progress of the first run, with Cancel', async await expect(page.locator('.fea-stats')).toBeVisible({ timeout: 120_000 }); expect(errors).toEqual([]); }); + +test('a study edited while it runs leaves its results out of date', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Finer', (d) => { d.study!.mesh.fineness = 0.7; })); + await page.locator('[data-cmd="fea:run"]').click(); + // While the part is being meshed, the force goes from 500 to 900 N. + await expect(page.locator('.fea-stage')).toContainText('Meshing', { timeout: 60_000 }); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Edit', (d) => { d.study!.loads[0].value = 900; })); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + // Solved with 500 N: shown as out of date. + await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); + await expect(page.getByRole('note').filter({ hasText: 'Out of date' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Run Again' })).toBeVisible(); + expect(errors).toEqual([]); +}); From 11c04367c7f58b938cf8c894cae0a6e8ceb58a4a Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:15:20 -0700 Subject: [PATCH 042/116] Parametric: analysis results stay up to date when the part is back to the shape solved (an edit cancelled, undone and redone) --- src/parametric/src/app/fea/panels.ts | 2 +- src/parametric/src/app/fea/workspace.ts | 60 ++++++++++++++++++----- src/parametric/tests/e2e/analysis.spec.ts | 29 +++++++++++ 3 files changed, 78 insertions(+), 13 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 00a3032dbc..7f163c3be2 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -134,7 +134,7 @@ export class StudyPanel extends FeaPanel { ['Volume against the part', `${volErr >= 0 ? '+' : ''}${volErr.toFixed(2)}%`], ] as [string, string][]).map(([k, v]) => h('tr', {}, h('th', {}, k), h('td', { class: 'num' }, v)))))); if (Math.abs(volErr) > 2) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The mesh misses part of the volume: some walls are thinner than the elements. Use a finer mesh.')); - if (!m.key.startsWith(`${app.geometryVersion}|`)) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part changed since it was meshed.')); + if (!ws.meshCurrent()) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part changed since it was meshed.')); } if (ws.error?.message && !ws.busy) stats.push(h('p', { class: 'pm-msg error', role: 'alert' }, ws.error.message)); return [ diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 210dc6ab7d..668093d495 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -23,7 +23,8 @@ import { reportDialog } from './report'; export type StudyState = 'none' | 'busy' | 'ok' | 'stale' | 'error'; interface SurfaceState { - version: number; + /** The part's shape it was read from (see shapeKey). */ + version: string; data: FeaSurface; auto: number; max: number; @@ -55,11 +56,13 @@ export class FeaWorkspace { focus: Id | null = null; private surface: SurfaceState | null = null; private surfaceLoading: Promise | null = null; - mesh: { key: string; info: FeaMeshInfo; size: number; version: number } | null = null; + mesh: { key: string; info: FeaMeshInfo; size: number; version: string } | null = null; result: FeaResult | null = null; busy: { stage: string; progress: number } | null = null; error: { key: string; message: string } | null = null; private generation = 0; + private seenVersion = -1; + private shape: { version: number; key: string } | null = null; /** Results panel open: it draws the plot (the study's symbols are hidden). */ plotting = false; @@ -75,8 +78,12 @@ export class FeaWorkspace { }); app.ribbonTabListeners.push(() => this.redraw()); app.commands.onChange(() => { - // A new part shape: the surface, the mesh and the results are out of date (results stay, marked). - if (this.surface && this.surface.version !== app.geometryVersion) { this.surface = null; this.changed(); } + // A new part shape: the mesh and the results are out of date (results stay, marked), or current + // again when the shape is back (an edit cancelled, undone and redone). + if (this.seenVersion !== app.geometryVersion) { + this.seenVersion = app.geometryVersion; + if (this.surface) this.changed(); + } }); } @@ -105,8 +112,37 @@ export class FeaWorkspace { // ---------- state ---------- /** What the results depend on: the part's shape, the mesh size, the study's fixtures and loads, the material. */ - solveKey(size?: number, version?: number, study?: string): string { - return JSON.stringify([version ?? this.app.geometryVersion, size ?? this.sizeOf(), study ?? this.studyKey()]); + solveKey(size?: number, version?: string, study?: string): string { + return JSON.stringify([version ?? this.shapeKey(), size ?? this.sizeOf(), study ?? this.studyKey()]); + } + + /** + * The part's shape: a hash of its body mesh and face names. The geometry + * version moves on with every new mesh, also one of the same shape (an edit + * cancelled, an undo and a redo), which would put results out of date for nothing. + */ + shapeKey(): string { + const app = this.app, v = app.geometryVersion; + if (this.shape?.version === v) return this.shape.key; + const m = app.modelMesh; + let a = 0x811c9dc5, b = 0x2545f491; + const mix = (x: number) => { a = Math.imul(a ^ x, 0x01000193); b = Math.imul(b ^ x, 0x5bd1e995); b ^= b >>> 13; }; + if (m) { + // The points and their faces (the triangles between them follow from the shape). + for (const arr of [new Uint32Array(m.positions.buffer, m.positions.byteOffset, m.positions.length), new Uint32Array(m.vertexFace.buffer, m.vertexFace.byteOffset, m.vertexFace.length)]) { + mix(arr.length); + for (let i = 0; i < arr.length; i++) mix(arr[i]); + } + } + for (const f of app.faces) for (let i = 0; i < f.name.length; i++) mix(f.name.charCodeAt(i)); + const key = m ? `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}:${m.indices.length}:${app.faces.length}` : 'none'; + this.shape = { version: v, key }; + return key; + } + + /** Whether the mesh is of the part's current shape. */ + meshCurrent(): boolean { + return !!this.mesh && this.mesh.version === this.shapeKey(); } /** The study's fixtures and loads and the material, as the results depend on them. */ @@ -125,7 +161,7 @@ export class FeaWorkspace { if (this.busy) return 'busy'; if (this.error && !this.result) return 'error'; if (!this.result) return 'none'; - if (!this.surface || this.surface.version !== this.app.geometryVersion || this.result.key !== this.solveKey()) return 'stale'; + if (!this.surface || this.surface.version !== this.shapeKey() || this.result.key !== this.solveKey()) return 'stale'; return 'ok'; } @@ -141,7 +177,7 @@ export class FeaWorkspace { const m = this.mesh; if (!m) return ''; const st = m.info.stats; - return `(${st.elements.toLocaleString('en-US')} elements${m.key.startsWith(`${this.app.geometryVersion}|`) ? '' : ', out of date'})`; + return `(${st.elements.toLocaleString('en-US')} elements${this.meshCurrent() ? '' : ', out of date'})`; } /** Can the study run now (a part with a solid, nothing being edited)? */ @@ -159,7 +195,7 @@ export class FeaWorkspace { async surfaceState(): Promise { const app = this.app; await app.whenBuilt(); - const version = app.geometryVersion; + const version = this.shapeKey(); if (this.surface && this.surface.version === version) return this.surface; if (this.surfaceLoading) return this.surfaceLoading; this.surfaceLoading = (async () => { @@ -175,7 +211,7 @@ export class FeaWorkspace { area += 0.5 * Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx); } const st: SurfaceState = { version, data, diag, auto: defaultElementSize(data.volume, area, diag), max: maxElementSize(data.volume, area, diag) }; - if (app.geometryVersion !== version) return this.surfaceState(); + if (this.shapeKey() !== version) return this.surfaceState(); this.surface = st; return st; } finally { @@ -207,7 +243,7 @@ export class FeaWorkspace { } /** Meshes the part at the study's size if the mesh is not current. */ - async ensureMesh(): Promise<{ info: FeaMeshInfo; size: number; version: number } | null> { + async ensureMesh(): Promise<{ info: FeaMeshInfo; size: number; version: string } | null> { const s = this.study; if (!s) return null; const gen = this.generation; @@ -564,7 +600,7 @@ export class FeaWorkspace { r.setLines('feaArrows', arrows.length ? { positions: new Float32Array(arrows), colors: new Uint8Array(acol), width: 2.5, depth: 'always', order: 8 } : null); // The mesh while the study panel is open. const m = this.mesh; - if (m && this.app.panel instanceof StudyPanel && m.key.startsWith(`${this.app.geometryVersion}|`)) { + if (m && this.app.panel instanceof StudyPanel && this.meshCurrent()) { r.setLines('feaMesh', { positions: m.info.lines, colors: new Uint8Array((m.info.lines.length / 6) * 4).fill(0).map((_, i) => (i % 4 === 3 ? 200 : 40)), width: 1, depth: 'test', order: 6, bias: 4e-5 }); } else if (!this.plotting) r.setLines('feaMesh', null); } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 4fc1570f2b..d35ba478db 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -231,3 +231,32 @@ test('a study edited while it runs leaves its results out of date', async ({ pag await expect(page.getByRole('button', { name: 'Run Again' })).toBeVisible(); expect(errors).toEqual([]); }); + +test('results stay up to date when the part is edited back to the shape solved', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await page.getByRole('button', { name: 'Close', exact: true }).click(); + const results = page.getByRole('treeitem', { name: /^Results/ }); + await expect(results).not.toHaveAttribute('aria-description', /Out of date/); + // A feature opened for editing and cancelled: the same shape. + const v0 = await page.evaluate(() => (window as unknown as W).__parametric.geometryVersion); + await page.getByRole('treeitem', { name: /^Extrude1/ }).dblclick(); + await expect(page.locator('.pm-head').getByText('Extrude1')).toBeVisible(); + await page.locator('.confirm-corner .cancel').click(); + await expect(page.locator('.pm-head')).toHaveCount(0); + await page.evaluate(() => (window as unknown as W).__parametric.whenBuilt()); + expect(await page.evaluate(() => (window as unknown as W).__parametric.geometryVersion)).toBeGreaterThan(v0); + await expect(results).not.toHaveAttribute('aria-description', /Out of date/); + // A new shape puts them out of date; Undo brings the solved shape back. + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Deeper', (d) => { const f = d.features.find((x) => x.name === 'Extrude1') as unknown as { depth: number }; f.depth = 33.3; }); + }); + await expect(results).toHaveAttribute('aria-description', /Out of date/); + await page.keyboard.press('Meta+z'); + await expect(results).not.toHaveAttribute('aria-description', /Out of date/); + expect(errors).toEqual([]); +}); From 24a2ee1c8f21cf7d9bcb19e43f5fc558e5603a51 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:16:08 -0700 Subject: [PATCH 043/116] Parametric: Mesh Now can be cancelled from the study panel, and a cancelled mesh leaves the status saying so --- src/parametric/src/app/fea/panels.ts | 2 +- src/parametric/src/app/fea/workspace.ts | 11 ++++++++--- src/parametric/tests/e2e/analysis.spec.ts | 8 ++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 7f163c3be2..46f7ca22a2 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -121,7 +121,7 @@ export class StudyPanel extends FeaPanel { const runBtn = h('button', { class: 'btn small primary', type: 'button', disabled: !!ws.busy, onclick: () => void ws.run() }, icon('feaRun', 16), 'Run'); const m = ws.mesh; const stats: HTMLElement[] = []; - if (ws.busy) stats.push(h('p', { class: 'field-label fea-stage', role: 'status' }, ws.busy.stage), h('progress', { max: '1', value: String(ws.busy.progress), 'aria-label': 'Progress' })); + if (ws.busy) stats.push(h('p', { class: 'field-label fea-stage', role: 'status' }, ws.busy.stage), h('progress', { max: '1', value: String(ws.busy.progress), 'aria-label': 'Progress' }), h('button', { class: 'btn small', type: 'button', onclick: () => ws.cancel() }, 'Cancel')); if (m) { const st = m.info.stats; const volErr = (st.volume / st.surfaceVolume - 1) * 100; diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 668093d495..21c4787557 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -266,15 +266,20 @@ export class FeaWorkspace { async meshNow(): Promise { const why = this.ready(); if (why) { toast({ kind: 'info', message: why }); return; } + if (this.busy) return; + const gen = this.generation; try { await this.ensureMesh(); this.error = null; } catch (e) { if (!(e instanceof FeaCancelled)) this.error = { key: '', message: (e as Error).message }; } finally { - this.busy = null; - this.app.setStatus(this.mesh ? `Meshed: ${this.mesh.info.stats.elements.toLocaleString('en-US')} elements, ${this.mesh.info.stats.nodes.toLocaleString('en-US')} nodes` : this.error?.message ?? '', !this.mesh); - this.changed(); + // Cancelled (or the part closed): the status says so already, and a run started since keeps its progress. + if (gen === this.generation) { + this.busy = null; + this.app.setStatus(this.mesh ? `Meshed: ${this.mesh.info.stats.elements.toLocaleString('en-US')} elements, ${this.mesh.info.stats.nodes.toLocaleString('en-US')} nodes` : this.error?.message ?? '', !this.mesh); + this.changed(); + } } } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index d35ba478db..f356144ae3 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -208,9 +208,17 @@ test('the results panel shows the progress of the first run, with Cancel', async await expect(page.locator('.statusbar .msg')).toHaveText('Analysis cancelled'); // Mesh Now in the study panel shows its progress too. await page.locator('[data-cmd="fea:study"]').click(); + // The cancelled run may have finished meshing before it was cancelled (its mesh's stats stay shown). + const statsBefore = await page.locator('.fea-stats').count(); await page.getByRole('button', { name: 'Mesh Now' }).click(); await expect(page.getByRole('progressbar', { name: 'Progress' })).toBeVisible(); await expect(page.getByRole('button', { name: 'Mesh Now' })).toBeDisabled(); + // It can be cancelled there (no new mesh is shown), and meshed again. + await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); + await expect(page.getByRole('progressbar', { name: 'Progress' })).toHaveCount(0); + await expect(page.locator('.fea-stats')).toHaveCount(statsBefore); + await expect(page.locator('.statusbar .msg')).toHaveText('Analysis cancelled'); + await page.getByRole('button', { name: 'Mesh Now' }).click(); await expect(page.locator('.fea-stats')).toBeVisible({ timeout: 120_000 }); expect(errors).toEqual([]); }); From 13f34685a6306489f9548cf7c5f42e6a283e0c62 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:17:27 -0700 Subject: [PATCH 044/116] Parametric: a new pressure on an inch part starts at 100 psi (it showed 99.999996) --- src/parametric/src/app/fea/workspace.ts | 9 +++++---- src/parametric/tests/e2e/analysis.spec.ts | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 21c4787557..b2b60c2cfd 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -9,7 +9,7 @@ import type { FeaMeshInfo, FeaSolution } from '../../fea/results'; import type { FixtureInput, LoadInput, StaticInput, Vec3 } from '../../fea/static'; import { defaultElementSize, estimateDofs, maxElementSize } from '../../fea/mesher'; import type { FeaSurface } from '../../kernel/protocol'; -import { FIXTURE_LABELS, LOAD_LABELS, elementSizeFor, newStudy, nextStudyName, type FeaDir, type FeaFixture, type FeaLoad, type FeaLoadType, type FixtureType, type StaticStudy } from '../../model/fea'; +import { FIXTURE_LABELS, LOAD_LABELS, elementSizeFor, feaUnits, newStudy, nextStudyName, type FeaDir, type FeaFixture, type FeaLoad, type FeaLoadType, type FixtureType, type StaticStudy } from '../../model/fea'; import { elasticOf } from '../../model/materials'; import { allocateId } from '../../model/document'; import type { Id } from '../../model/types'; @@ -453,9 +453,10 @@ export class FeaWorkspace { const faces = this.app.selection.ofKind('face').map((it) => this.app.faces[it.index]).filter((f) => f && !f.body).map((x) => ({ name: x.name, sig: { type: x.type, c: x.center, n: x.normal, area: x.area } })); const id = allocateId(this.app.store.doc, 'ld'); const name = nextStudyName(s, LOAD_LABELS[type]); - const inch = this.app.store.doc.units === 'IPS'; - const l: FeaLoad = type === 'force' ? { id, name, type, faces, value: inch ? 444.8221615 : 100, dir: null, flip: false } - : type === 'pressure' ? { id, name, type, faces, value: inch ? 0.6894757 : 1, flip: false } + // 100 N or 100 lbf, 1 MPa or 100 psi: round numbers in the part's units. + const u = feaUnits(this.app.store.doc.units), inch = this.app.store.doc.units === 'IPS'; + const l: FeaLoad = type === 'force' ? { id, name, type, faces, value: 100 * u.forceScale, dir: null, flip: false } + : type === 'pressure' ? { id, name, type, faces, value: (inch ? 100 : 1) * u.stressScale, flip: false } : { id, name, type, value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }; this.app.exitModes(); void this.app.openPanel(new LoadPanel(this.app, this, l, true)); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index f356144ae3..351c020137 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -268,3 +268,26 @@ test('results stay up to date when the part is edited back to the shape solved', await expect(results).not.toHaveAttribute('aria-description', /Out of date/); expect(errors).toEqual([]); }); + +test('loads of an inch part are in pounds-force and psi, with round defaults', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Units', (d) => { d.units = 'IPS'; })); + await page.locator('[data-cmd="fea:force"]').click(); + await expect(page.getByLabel('Total force (lbf)')).toHaveValue('100'); + await page.locator('.confirm-corner .cancel').click(); + await page.locator('[data-cmd="fea:pressure"]').click(); + await expect(page.getByLabel('Pressure (psi)')).toHaveValue('100'); + await page.locator('.confirm-corner .cancel').click(); + await page.locator('[data-cmd="fea:gravity"]').click(); + await expect(page.getByLabel('Acceleration (in/s²)')).toHaveValue('386.08858'); + await page.locator('.confirm-corner .cancel').click(); + // Force-1 (500 N) reads in lbf, and a value typed in lbf is kept in newtons. + await page.getByRole('treeitem', { name: /^Force-1/ }).dblclick(); + await expect(page.getByLabel('Total force (lbf)')).toHaveValue('112.40447'); + await page.getByLabel('Total force (lbf)').fill('50'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.locator('.pm-head')).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads[0].value)).toBeCloseTo(222.411, 3); + expect(errors).toEqual([]); +}); From 0f938689da8d61b50bef0d51a0014fce966f6e08 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:18:59 -0700 Subject: [PATCH 045/116] Parametric: the printable analysis report says what its plot shows (quantity, range and units, colours, deformation scale) --- src/parametric/src/app/fea/panels.ts | 3 +++ src/parametric/src/app/fea/plot.ts | 11 +++++++++++ src/parametric/src/app/fea/report.ts | 8 ++++---- src/parametric/src/app/fea/workspace.ts | 2 ++ src/parametric/tests/e2e/analysis.spec.ts | 18 ++++++++++++++++++ 5 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 46f7ca22a2..db092640f0 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -358,6 +358,8 @@ export class ResultsPanel extends FeaPanel { this.plot.onProbe = () => this.drawProbes(); this.plotted = res; this.ws.plotting = true; + const plot = this.plot; + this.ws.plotCaption = () => plot.caption(); this.ws.redraw(); this.plot.field = this.field; this.plot.draw(); @@ -434,6 +436,7 @@ export class ResultsPanel extends FeaPanel { this.plot.dispose(); this.plot = null; this.ws.plotting = false; + this.ws.plotCaption = null; this.ws.redraw(); } diff --git a/src/parametric/src/app/fea/plot.ts b/src/parametric/src/app/fea/plot.ts index 8654214465..5b420a1e9e 100644 --- a/src/parametric/src/app/fea/plot.ts +++ b/src/parametric/src/app/fea/plot.ts @@ -165,6 +165,17 @@ export class ResultPlot { } } + /** What the plot shows, in words (the printed report has no legend of its own). */ + caption(): string { + const [lo, hi] = this.range(); + const kind = fieldKind(this.field); + const top = this.field === 'fos' && hi >= FOS_CAP ? `${FOS_CAP} or more` : formatValue(this.app, hi, kind); + const colours = this.field === 'fos' ? 'red lowest, blue highest' : 'blue lowest, red highest'; + const k = this.scale(); + const shape = this.deform === 'none' ? 'undeformed shape' : `deformation scale ${k >= 100 ? Math.round(k).toLocaleString('en-US') : Number(k.toPrecision(3))}${this.deform === 'true' ? ' (true scale)' : ''}`; + return `${FIELD_LABELS[this.field]} from ${formatValue(this.app, lo, kind)} to ${top} (${colours}); ${shape}.`; + } + private drawLegend(lo: number, hi: number) { const app = this.app; this.legend?.remove(); diff --git a/src/parametric/src/app/fea/report.ts b/src/parametric/src/app/fea/report.ts index ff78e1a77d..b16de7c9ea 100644 --- a/src/parametric/src/app/fea/report.ts +++ b/src/parametric/src/app/fea/report.ts @@ -73,14 +73,14 @@ export function summaryCsv(rows: Line[]): string { const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!); -export function reportHtml(title: string, rows: Line[], image: string | null): string { +export function reportHtml(title: string, rows: Line[], image: string | null, caption = ''): string { const sections = [...new Set(rows.map((r) => r.section))]; const body = sections.map((s) => `

${esc(s)}

${rows.filter((r) => r.section === s).map((r) => ``).join('')}
${esc(r.name)}${esc(r.value)}${r.unit ? ` ${esc(r.unit)}` : ''}
`).join(''); return `${esc(title)}

${esc(title)}

${image ? `Result plot` : ''}${body} +img{max-width:100%;border:1px solid #ddd;margin-top:8px}figure{margin:0}figcaption{color:#333;margin-top:4px}.note{color:#555;font-size:12px;margin-top:18px} +

${esc(title)}

${image ? `
${esc(caption || 'Result plot')}${caption ? `
${esc(caption)}
` : ''}
` : ''}${body}

Linear static analysis: small displacements, linear elastic isotropic material, no contact. Stresses at sharp inner corners and at the edges of fixed faces can grow without bound as the mesh is refined (stress singularities); judge them by the stresses a little away from such spots.

`; } @@ -95,7 +95,7 @@ export async function reportDialog(app: App, ws: FeaWorkspace, r: FeaResult) { if (v === 'csv') download(summaryCsv(rows), `${name}.csv`, 'text/csv'); if (v === 'html') { const image = ws.plotting ? app.renderer.capture(1400) : null; - const html = reportHtml(name, rows, image); + const html = reportHtml(name, rows, image, image ? ws.plotCaption?.() ?? '' : ''); const w = window.open('', '_blank'); if (!w) { download(html, `${name}.html`, 'text/html'); toast({ kind: 'info', message: 'The report was downloaded (the browser blocked the new window): open it and print it.' }); return; } w.document.write(html); diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index b2b60c2cfd..6a033136c4 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -65,6 +65,8 @@ export class FeaWorkspace { private shape: { version: number; key: string } | null = null; /** Results panel open: it draws the plot (the study's symbols are hidden). */ plotting = false; + /** What the open plot shows, in words (for the report). */ + plotCaption: (() => string) | null = null; constructor(readonly app: App) { app.store.on((reason) => { diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 351c020137..9a820ead50 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -291,3 +291,21 @@ test('loads of an inch part are in pounds-force and psi, with round defaults', a expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads[0].value)).toBeCloseTo(222.411, 3); expect(errors).toEqual([]); }); + +test('the printable report says what its plot shows', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await page.getByLabel('Plot', { exact: true }).selectOption('disp'); + await page.getByRole('button', { name: 'Report...' }).click(); + const popup = page.waitForEvent('popup'); + await page.getByRole('dialog', { name: 'Results Report' }).getByRole('button', { name: 'Printable Report' }).click(); + const report = await popup; + await report.evaluate(() => { window.print = () => {}; }); + await expect(report.locator('figcaption')).toContainText(/^Displacement from 0 mm to 0\.\d+ mm \(blue lowest, red highest\); deformation scale \d+/); + await expect(report.locator('img')).toHaveAttribute('alt', /^Displacement from/); + await report.close(); + expect(errors).toEqual([]); +}); From 6409bef51541e457c72d522b40622f75f60a5260 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:20:18 -0700 Subject: [PATCH 046/116] Parametric: the material dialog marks and focuses the elastic property that is wrong, and describes the fields with the error --- src/parametric/src/app/dialogs.ts | 14 +++++++++++-- src/parametric/tests/e2e/dialogs.spec.ts | 26 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/dialogs.ts b/src/parametric/src/app/dialogs.ts index 79319ae35e..7b41ff49a2 100644 --- a/src/parametric/src/app/dialogs.ts +++ b/src/parametric/src/app/dialogs.ts @@ -232,6 +232,15 @@ export async function materialDialog(app: App) { const error = h('div', { id: nextDomId('density-error'), class: 'field-label', role: 'alert', style: { color: 'var(--danger)' } }); customDensity.setAttribute('aria-describedby', error.id); const elasticFields = [customE, customNu, customYield, customUts]; + for (const f of elasticFields) f.setAttribute('aria-describedby', error.id); + // The elastic fields that keep the set from being used (all empty is no set, not an error). + const badElastic = () => { + if (elasticFields.every((f) => !f.value.trim())) return []; + return elasticFields.filter((f) => { + const v = Number(f.value); + return !f.value.trim() || !Number.isFinite(v) || (f === customNu ? v < 0 || v >= 0.5 : v <= 0); + }); + }; const customElastic = (): ElasticProps | null | 'invalid' => { if (elasticFields.every((f) => !f.value.trim())) return null; const e = { E: Number(customE.value) * 1000, nu: Number(customNu.value), yield: Number(customYield.value), uts: Number(customUts.value) }; @@ -244,7 +253,8 @@ export async function materialDialog(app: App) { error.textContent = !densityOk ? 'Enter a finite, positive density.' : !elasticOk ? 'Enter all four elastic properties as positive numbers, with a Poisson\'s ratio from 0 to below 0.5 (or leave them all empty).' : ''; if (densityOk) customDensity.removeAttribute('aria-invalid'); else customDensity.setAttribute('aria-invalid', 'true'); - for (const f of elasticFields) { if (elasticOk) f.removeAttribute('aria-invalid'); else f.setAttribute('aria-invalid', 'true'); } + const bad = elasticOk ? [] : badElastic(); + for (const f of elasticFields) { if (bad.includes(f)) f.setAttribute('aria-invalid', 'true'); else f.removeAttribute('aria-invalid'); } return densityOk && elasticOk; }; for (const f of [customDensity, ...elasticFields]) f.addEventListener('input', () => { if (error.textContent) validate(); }); @@ -263,7 +273,7 @@ export async function materialDialog(app: App) { body: [h('p', {}, 'The material sets the density used for mass properties, and the elastic properties used for stress analysis.'), select, props, custom, customHint, error], buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Apply', value: 'ok', primary: true }], onAction: (action) => { - if (action === 'ok' && !validate()) { (customDensity.getAttribute('aria-invalid') ? customDensity : customE).focus(); return false; } + if (action === 'ok' && !validate()) { (customDensity.getAttribute('aria-invalid') ? customDensity : (badElastic()[0] ?? customE)).focus(); return false; } }, }); if (v !== 'ok' || signal.aborted) return; diff --git a/src/parametric/tests/e2e/dialogs.spec.ts b/src/parametric/tests/e2e/dialogs.spec.ts index 845f326dbd..c3e2aa3617 100644 --- a/src/parametric/tests/e2e/dialogs.spec.ts +++ b/src/parametric/tests/e2e/dialogs.spec.ts @@ -200,3 +200,29 @@ test('Equations shows what a value being typed evaluates to, and what uses it, b await dialog.getByRole('button', { name: 'Cancel' }).click(); expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.variables.map((v) => v.expr))).toEqual(['10', 'Width/2']); }); + +test('an invalid elastic property of a custom material is the field marked and focused', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => (window as unknown as Handle).__parametric.commands.run('material')); + const dialog = page.getByRole('dialog', { name: 'Material', exact: true }); + await dialog.getByRole('combobox').selectOption('__custom'); + const e = dialog.getByLabel('Elastic modulus in GPa'), nu = dialog.getByLabel("Poisson's ratio"), sy = dialog.getByLabel('Yield strength in MPa'), uts = dialog.getByLabel('Tensile strength in MPa'); + await e.fill('200'); + await nu.fill('0.5'); + await sy.fill('250'); + await uts.fill('400'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(nu).toBeFocused(); + await expect(nu).toHaveAttribute('aria-invalid', 'true'); + for (const ok of [e, sy, uts]) await expect(ok).not.toHaveAttribute('aria-invalid'); + await expect(nu).toHaveAccessibleDescription(/Poisson's ratio from 0 to below 0\.5/); + // Corrected: applied with the modulus in MPa. + await nu.fill('0.3'); + await expect(nu).not.toHaveAttribute('aria-invalid'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(dialog).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.material)) + .toEqual({ name: 'Custom material', density: 1000, E: 200000, nu: 0.3, yield: 250, uts: 400 }); + expect(errors).toEqual([]); +}); From badaac261aefdc4ec33e42fcb9d8f88d9d6d25f6 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:20:55 -0700 Subject: [PATCH 047/116] Parametric: a study with a zero or negative load is refused (in the file, and at Run) instead of solving to all-zero results --- src/parametric/src/app/fea/workspace.ts | 1 + src/parametric/src/model/fea.ts | 3 ++- src/parametric/tests/fea-model.test.ts | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 6a033136c4..bed8cca2b4 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -335,6 +335,7 @@ export class FeaWorkspace { const loadNames: string[] = []; for (const l of s.loads) { if (l.suppressed) continue; + if (!(l.value > 0) || !Number.isFinite(l.value)) throw new Error(`${l.name}: its value must be greater than 0.`); const sign = l.flip ? -1 : 1; if (l.type === 'gravity') { const d = this.dirOf(l.dir); diff --git a/src/parametric/src/model/fea.ts b/src/parametric/src/model/fea.ts index b042dd4fe8..5e3adf6387 100644 --- a/src/parametric/src/model/fea.ts +++ b/src/parametric/src/model/fea.ts @@ -169,7 +169,8 @@ export function parseStudy(raw: unknown): StaticStudy { const loads = (r.loads as unknown[]).map((l): FeaLoad => { if (!isObj(l)) return bad('load'); const base = ident(l, 'load'); - if (!finite(l.value)) bad('load value'); + // Loads are positive amounts (their direction says which way): the panels never write others. + if (!finite(l.value) || (l.value as number) <= 0) bad('load value'); if (typeof l.flip !== 'boolean') bad('load direction'); const value = l.value as number, flip = l.flip as boolean; if (l.type === 'force') { diff --git a/src/parametric/tests/fea-model.test.ts b/src/parametric/tests/fea-model.test.ts index 2a124732ce..0245e12c58 100644 --- a/src/parametric/tests/fea-model.test.ts +++ b/src/parametric/tests/fea-model.test.ts @@ -43,6 +43,8 @@ describe('static study in the part file', () => { ['face without signature', (s) => { (s.fixtures as { faces: unknown[] }[])[0].faces = [{ name: 'x' }]; }], ['duplicate ids', (s) => { (s.loads as Record[])[0].id = 'fx4'; }], ['value not a number', (s) => { (s.loads as Record[])[1].value = '2 MPa'; }], + ['zero force', (s) => { (s.loads as Record[])[0].value = 0; }], + ['negative pressure', (s) => { (s.loads as Record[])[1].value = -2; }], ['unknown load type', (s) => { (s.loads as Record[])[1].type = 'torque'; }], ['gravity without a direction', (s) => { delete (s.loads as Record[])[2].dir; }], ['bad direction', (s) => { (s.loads as Record[])[0].dir = { kind: 'base', axis: 'w' }; }], From e2371e65e837729ba2bc03f3282d56f063a66a29 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:23:06 -0700 Subject: [PATCH 048/116] Parametric: fixture and load symbols move with the part when it is rebuilt (they stayed on the old faces) --- src/parametric/src/app/fea/workspace.ts | 2 ++ src/parametric/tests/e2e/analysis.spec.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index bed8cca2b4..14780d0d91 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -84,7 +84,9 @@ export class FeaWorkspace { // again when the shape is back (an edit cancelled, undone and redone). if (this.seenVersion !== app.geometryVersion) { this.seenVersion = app.geometryVersion; + // The fixtures' and loads' symbols go on the new faces. if (this.surface) this.changed(); + else this.redraw(); } }); } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 9a820ead50..712b3af9c2 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -309,3 +309,20 @@ test('the printable report says what its plot shows', async ({ page }) => { await report.close(); expect(errors).toEqual([]); }); + +test('the fixture and load symbols follow the part when it is edited', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // Highest Z of the tinted faces of the fixtures and loads. + const top = () => page.evaluate(() => { + const r = (window as unknown as W).__parametric.renderer as unknown as { tris: Map }; + const p = r.tris.get('feaFix')?.positions; + let z = -Infinity; + for (let i = 2; p && i < p.length; i += 3) z = Math.max(z, p[i]); + return z; + }); + await expect.poll(top).toBeCloseTo(30, 3); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Deeper', (d) => { (d.features.find((x) => x.name === 'Extrude1') as unknown as { depth: number }).depth = 80; })); + await expect.poll(top).toBeCloseTo(80, 3); + expect(errors).toEqual([]); +}); From becf166264f57cb70f13cb27b5e1f472521dd43a Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:27:10 -0700 Subject: [PATCH 049/116] Parametric: a part with a study opened while the Analysis tab is shown draws its fixtures and loads --- src/parametric/src/app/fea/index.ts | 2 ++ src/parametric/tests/e2e/analysis.spec.ts | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/parametric/src/app/fea/index.ts b/src/parametric/src/app/fea/index.ts index f9e1e25557..bef0edc59f 100644 --- a/src/parametric/src/app/fea/index.ts +++ b/src/parametric/src/app/fea/index.ts @@ -115,6 +115,8 @@ export function installFea(app: App, hooks: AppHooks) { hooks.ribbonTabs.splice(at < 0 ? hooks.ribbonTabs.length : at, 0, tab); // A part opened with a study shows its symbols when the tab is chosen (the workspace loads then). app.ribbonTabListeners.push((id) => { if (id === 'analysis' && app.store.doc.study && partOnly()) void feaWorkspace(app).then((ws) => ws.redraw()); }); + // ...and when it is opened while the tab is shown (the symbols follow its first build). + app.store.on((reason) => { if (reason === 'load' && app.ribbonTabId === 'analysis' && app.store.doc.study && partOnly()) void feaWorkspace(app).then((ws) => ws.redraw()); }); } // ---------- design tree ---------- diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 712b3af9c2..5ea58d05bc 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -326,3 +326,26 @@ test('the fixture and load symbols follow the part when it is edited', async ({ await expect.poll(top).toBeCloseTo(80, 3); expect(errors).toEqual([]); }); + +test('a part with a study opened while the Analysis tab is shown shows its fixtures and loads', async ({ page, browser }) => { + const errors = await openApp(page); + await bracketStudy(page); + const text = await page.evaluate(async (url) => { + const { serializeDocument } = await import(url) as typeof import('../../src/model/document'); + return serializeDocument((window as unknown as W).__parametric.store.doc); + }, '/src/model/document.ts'); + // A new window, where the analysis has not been loaded yet. + const other = await (await browser.newContext({ viewport: { width: 1440, height: 900 } })).newPage(); + const otherErrors = await openApp(other); + await other.getByRole('button', { name: /New part/ }).click(); + await other.getByRole('tab', { name: 'Analysis' }).click(); + await other.evaluate(async ({ text, url }) => { + const { parseDocument } = await import(url) as typeof import('../../src/model/document'); + (window as unknown as W).__parametric.loadDocument(parseDocument(text), null); + }, { text, url: '/src/model/document.ts' }); + await expect(other.getByRole('tab', { name: 'Analysis' })).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => other.evaluate(() => ((window as unknown as W).__parametric.renderer as unknown as { tris: Map }).tris.has('feaFix'))).toBe(true); + await other.context().close(); + expect(errors).toEqual([]); + expect(otherErrors).toEqual([]); +}); From dd196620f76fff45847902624d045189eb79fe2d Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:29:16 -0700 Subject: [PATCH 050/116] Parametric: on phones the result legend shows below the view toolbar instead of under the panel sheet, with its ticks inside the scale --- src/parametric/src/styles/app.css | 8 ++++++-- src/parametric/tests/e2e/analysis.spec.ts | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index d7b43a8975..4320741d1d 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -773,6 +773,10 @@ a.icon-btn { text-decoration: none; } .fea-summary th, .fea-forces th, .fea-solve th, .fea-stats th { font-weight: 500; } .fea-material-props { margin-top: 6px; } @media (max-width: 760px) { - .fea-legend { top: auto; bottom: 12px; right: 8px; max-width: 170px; } - .fea-legend-scale { height: 120px; } + /* Under the view toolbar: the bottom of the graphics area is under the panel sheet on phones. */ + .fea-legend { top: 52px; right: 8px; max-width: 200px; padding: 6px 8px; } + .fea-legend-title { margin-bottom: 4px; } + .fea-legend-scale { height: 96px; } + .fea-legend-ticks { line-height: 1.15; } + .fea-legend-note { margin-top: 2px; font-size: 11px; } } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 5ea58d05bc..0f1b5ad10b 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -349,3 +349,24 @@ test('a part with a study opened while the Analysis tab is shown shows its fixtu expect(errors).toEqual([]); expect(otherErrors).toEqual([]); }); + +test.describe('on a phone', () => { + test.use({ viewport: { width: 412, height: 839 }, isMobile: true, hasTouch: true }); + + test('the result legend shows above the panel sheet, below the view toolbar', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.commands.run('fea:run')); + await expect(page.locator('.fea-summary')).toBeAttached({ timeout: 120_000 }); + const legend = (await page.locator('.fea-legend').boundingBox())!; + const sheet = (await page.locator('.leftpane').boundingBox())!; + expect(legend.y + legend.height).toBeLessThanOrEqual(sheet.y); + expect(legend.x + legend.width).toBeLessThanOrEqual(412); + // The ticks stay inside the colour scale. + const ticks = (await page.locator('.fea-legend-ticks').boundingBox())!; + const bar = (await page.locator('.fea-legend-bar').boundingBox())!; + expect(ticks.y + ticks.height).toBeLessThanOrEqual(bar.y + bar.height + 1); + expect(errors).toEqual([]); + }); +}); From f87ff4e180bd84e32203713ef61408ca21497285 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:31:17 -0700 Subject: [PATCH 051/116] Parametric: Tab from the study name moves the focus on to the next control instead of losing it --- src/parametric/src/app/fea/panels.ts | 3 ++- src/parametric/tests/e2e/analysis.spec.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index db092640f0..370ab97463 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -101,7 +101,8 @@ export class StudyPanel extends FeaPanel { const s = ws.study; if (!s) return [section('Study', [h('p', { class: 'pm-msg' }, 'The study was deleted.')])]; const nameInput = h('input', { class: 'input', value: this.name, 'aria-label': 'Study name' }) as HTMLInputElement; - nameInput.addEventListener('change', () => { this.name = nameInput.value; this.commit(); }); + // Taken after the focus moved on (Tab): the panel is drawn again then, and the focus stays where it went. + nameInput.addEventListener('change', () => { this.name = nameInput.value; setTimeout(() => this.commit()); }); const mat = app.store.doc.material; const el = elasticOf(mat); const matText = !mat ? 'No material chosen.' : el ? `${mat.name}: E ${formatNumber(el.E / 1000, 1)} GPa, ν ${el.nu}, yield ${el.yield} MPa` : `${mat.name}: no elastic properties (cannot be analyzed).`; diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 0f1b5ad10b..c36f52079a 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -370,3 +370,16 @@ test.describe('on a phone', () => { expect(errors).toEqual([]); }); }); + +test('Tab from the study name keeps the keyboard focus in the study panel', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:study"]').click(); + await page.getByLabel('Study name').fill('Bracket Load Case'); + await page.keyboard.press('Tab'); + await expect.poll(() => page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.name)).toBe('Bracket Load Case'); + // The panel was drawn again with the new name: the focus is on the next control, not lost to the page. + await page.waitForTimeout(100); + expect(await page.evaluate(() => !!document.activeElement?.closest('.pm-content') && document.activeElement.getAttribute('aria-label') !== 'Study name')).toBe(true); + expect(errors).toEqual([]); +}); From 52d97fd1c3e7eac27e2a91f467c66713682b36ec Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:32:43 -0700 Subject: [PATCH 052/116] Parametric: the result legend's ticks share their decimals, so they line up and read evenly --- src/parametric/src/app/fea/plot.ts | 7 ++++++- src/parametric/tests/e2e/analysis.spec.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/fea/plot.ts b/src/parametric/src/app/fea/plot.ts index 5b420a1e9e..2f49f6b568 100644 --- a/src/parametric/src/app/fea/plot.ts +++ b/src/parametric/src/app/fea/plot.ts @@ -184,9 +184,14 @@ export class ResultPlot { const unit = kind === 'stress' ? u.stress : kind === 'length' ? u.length : ''; const ticks = h('div', { class: 'fea-legend-ticks' }); const N = 6; + // The ticks share their decimals (enough for the step between them), so they line up and read evenly. + const scaleOf = kind === 'stress' ? u.stressScale : kind === 'length' ? u.lengthScale : 1; + const step = (hi - lo) / scaleOf / (N - 1); + const digits = step > 0 ? 2 - Math.floor(Math.log10(step)) : NaN; for (let i = 0; i < N; i++) { const v = hi - ((hi - lo) * i) / (N - 1); - const top = this.field === 'fos' && i === 0 && hi >= FOS_CAP ? `≥ ${FOS_CAP}` : formatValue(app, v, kind).replace(` ${unit}`, ''); + const fixed = digits <= 8 ? (v / scaleOf).toFixed(Math.max(0, digits)).replace(/^-(0\.?0*)$/, '$1') : null; + const top = this.field === 'fos' && i === 0 && hi >= FOS_CAP ? `≥ ${FOS_CAP}` : fixed ?? formatValue(app, v, kind).replace(` ${unit}`, ''); ticks.append(h('span', {}, top)); } const stops = Array.from({ length: 9 }, (_, i) => { const c = colorAt(this.field === 'fos' ? i / 8 : 1 - i / 8); return `rgb(${c.join(',')}) ${(i / 8) * 100}%`; }); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index c36f52079a..2aeb289875 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -383,3 +383,22 @@ test('Tab from the study name keeps the keyboard focus in the study panel', asyn expect(await page.evaluate(() => !!document.activeElement?.closest('.pm-content') && document.activeElement.getAttribute('aria-label') !== 'Study name')).toBe(true); expect(errors).toEqual([]); }); + +test('the legend ticks share their decimals', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + const decimals = async () => (await page.locator('.fea-legend-ticks span').allInnerTexts()).filter((t) => !t.startsWith('≥')).map((t) => { + expect(t).toMatch(/^-?\d+(\.\d+)?$/); + return t.split('.')[1]?.length ?? 0; + }); + for (const field of ['vonMises', 'disp', 'strain', 'fos']) { + await page.getByLabel('Plot', { exact: true }).selectOption(field); + const d = await decimals(); + expect(d.length, field).toBeGreaterThan(3); + expect(new Set(d).size, field).toBe(1); + } + expect(errors).toEqual([]); +}); From 77ffe8afed38fd6d9c3503b8b82cd6c8f28e0eeb Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:33:34 -0700 Subject: [PATCH 053/116] Parametric: Analysis ribbon labels break only between words on phones ("Roller/Slid er") --- src/parametric/src/styles/app.css | 8 ++++---- src/parametric/tests/e2e/analysis.spec.ts | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 4320741d1d..10d4f9fa74 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -251,8 +251,8 @@ a.icon-btn { text-decoration: none; } } .tool .lbl { white-space: normal; overflow-wrap: anywhere; } /* The sheet metal, surfaces, weldments, drawing and assembly tabs: labels break between words only, and a word wider than the button widens it. */ -:is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool:not(.row) { max-width: none; } -:is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool:not(.row) .lbl { overflow-wrap: normal; min-width: min-content; max-width: 68px; } +:is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly'], .cm-tools[data-tab='analysis']) .tool:not(.row) { max-width: none; } +:is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly'], .cm-tools[data-tab='analysis']) .tool:not(.row) .lbl { overflow-wrap: normal; min-width: min-content; max-width: 68px; } .tool:hover:not(:disabled) { background: var(--hover); } .tool:active:not(:disabled) { background: var(--active); } .tool[aria-pressed='true'] { background: var(--accent-weak); border-color: var(--accent-border); } @@ -629,8 +629,8 @@ a.icon-btn { text-decoration: none; } .cm-stack { flex-direction: row; align-items: stretch; } .tool.row { flex-direction: column; height: auto; min-width: 46px; max-width: 64px; padding: 4px; } .tool.row .lbl { white-space: normal; font-size: 10px; } - :is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool { max-width: none; } - :is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool:is(:not(.row), .row) .lbl { overflow-wrap: normal; min-width: min-content; max-width: 54px; } + :is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly'], .cm-tools[data-tab='analysis']) .tool { max-width: none; } + :is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly'], .cm-tools[data-tab='analysis']) .tool:is(:not(.row), .row) .lbl { overflow-wrap: normal; min-width: min-content; max-width: 54px; } .leftpane { position: absolute; z-index: 20; left: 0; right: 0; bottom: 0; top: auto; width: 100% !important; max-width: none; height: min(52dvh, 460px); border-right: 0; border-top: 1px solid var(--border-strong); border-radius: 12px 12px 0 0; transform: translateY(105%); transition: transform 0.18s ease, height 0.18s ease; diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 2aeb289875..da9fbdc85b 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -369,6 +369,22 @@ test.describe('on a phone', () => { expect(ticks.y + ticks.height).toBeLessThanOrEqual(bar.y + bar.height + 1); expect(errors).toEqual([]); }); + + test('the Analysis ribbon labels break only between words', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // Words of a label wider than the label: a word broken across lines ("Roller/Slid er"). + const broken = await page.evaluate(() => { + const c = document.createElement('canvas').getContext('2d')!; + return [...document.querySelectorAll('.cm-tools .tool .lbl')].flatMap((l) => { + const cs = getComputedStyle(l); + c.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`; + return l.textContent!.split(/\s+/).some((w) => c.measureText(w).width > l.clientWidth + 0.5) ? [l.textContent!] : []; + }); + }); + expect(broken).toEqual([]); + expect(errors).toEqual([]); + }); }); test('Tab from the study name keeps the keyboard focus in the study panel', async ({ page }) => { From 4f250166a0812a8dedd61da97139071d7ec5fad0 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:35:04 -0700 Subject: [PATCH 054/116] Parametric: the analysis CSV has one quantity per row with its unit in the unit column, and gives gravity's acceleration --- src/parametric/src/app/fea/report.ts | 8 ++++++-- src/parametric/tests/e2e/analysis.spec.ts | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/fea/report.ts b/src/parametric/src/app/fea/report.ts index b16de7c9ea..7a3fc6a146 100644 --- a/src/parametric/src/app/fea/report.ts +++ b/src/parametric/src/app/fea/report.ts @@ -41,9 +41,13 @@ export function summaryRows(app: App, ws: FeaWorkspace, r: FeaResult): Line[] { add('Results', 'Max equivalent strain', s.maxStrain.value); for (const w of s.warnings ?? []) add('Results', 'Note', w); add('Results', 'Yielding', s.maxVonMises.value > r.yield ? 'yes: stress above yield, the linear analysis no longer holds there' : 'no'); + // One quantity per row, its unit in the unit column. r.loadNames.forEach((n, i) => { const ld = r.input.loads[i]; - add('Loads', n, ld.kind === 'gravity' ? 'gravity' : ld.kind === 'pressure' ? `${Number(S(ld.value).toPrecision(6))} ${u.stress} on ${formatNumber(s.loadAreas[i] / u.lengthScale ** 2, 2)} ${u.length}²` : `${Number(F(ld.total).toPrecision(6))} ${u.force} on ${formatNumber(s.loadAreas[i] / u.lengthScale ** 2, 2)} ${u.length}²`); + if (ld.kind === 'gravity') { add('Loads', `${n} acceleration`, Math.hypot(...ld.accel) / u.accelScale, u.accel); return; } + if (ld.kind === 'pressure') add('Loads', `${n} pressure`, S(ld.value), u.stress); + else add('Loads', `${n} force`, F(ld.total), u.force); + add('Loads', `${n} area`, s.loadAreas[i] / u.lengthScale ** 2, `${u.length}²`); }); for (const [k, v] of [['X', 0], ['Y', 1], ['Z', 2]] as const) add('Forces', `Applied loads (sum) ${k}`, F(s.applied[v]), u.force); r.fixtureNames.forEach((n, i) => { for (const [k, v] of [['X', 0], ['Y', 1], ['Z', 2]] as const) add('Forces', `Reaction ${n} ${k}`, F(s.reactions[i][v]), u.force); }); @@ -57,7 +61,7 @@ export function summaryRows(app: App, ws: FeaWorkspace, r: FeaResult): Line[] { add('Mesh', 'Unknowns', s.dofs); add('Mesh', 'Worst element quality (mean ratio)', st.minQuality); add('Mesh', 'Mean element quality', st.meanQuality); - add('Mesh', 'Volume against the part', `${((st.volume / st.surfaceVolume - 1) * 100).toFixed(3)}%`); + add('Mesh', 'Volume against the part', `${((st.volume / st.surfaceVolume - 1) * 100).toFixed(3)}`, '%'); add('Solver', 'Method', `Conjugate gradients, ${s.solver}`); add('Solver', 'Iterations', s.iterations); add('Solver', 'Relative residual', s.residual); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index da9fbdc85b..3e79555930 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -418,3 +418,24 @@ test('the legend ticks share their decimals', async ({ page }) => { } expect(errors).toEqual([]); }); + +test('the CSV summary has one quantity per row, with its unit in the unit column', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Gravity', (d) => { d.study!.loads.push({ id: 'ld903', name: 'Gravity-1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); })); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await page.getByRole('button', { name: 'Report...' }).click(); + const download = page.waitForEvent('download'); + await page.getByRole('dialog', { name: 'Results Report' }).getByRole('button', { name: 'Download CSV' }).click(); + const file = await download; + expect(file.suggestedFilename()).toBe('Mounting Bracket - Static Study.csv'); + const csv = (await (await file.createReadStream()).toArray()).join(''); + expect(csv).toContain('\nLoads,Force-1 force,500,N\n'); + expect(csv).toContain('\nLoads,Force-1 area,240,mm²\n'); + expect(csv).toContain('\nLoads,Gravity-1 acceleration,9.80665,m/s²\n'); + // Every row: section, quantity, a value without its unit, the unit. + for (const line of csv.trim().split('\n').slice(1)) expect(line, line).not.toMatch(/,[-\d.e]+ (N|MPa|mm|%)/); + expect(errors).toEqual([]); +}); From 4ab32017a9273d4a9818513010a9c1aa0be74de8 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:37:09 -0700 Subject: [PATCH 055/116] Parametric: Run right after a part edit waits for the rebuild, so loads and fixtures go on the faces picked (renumbered faces got them) --- src/parametric/src/app/fea/workspace.ts | 11 +++++++++-- src/parametric/tests/e2e/analysis.spec.ts | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts index 14780d0d91..a94763a243 100644 --- a/src/parametric/src/app/fea/workspace.ts +++ b/src/parametric/src/app/fea/workspace.ts @@ -371,12 +371,17 @@ export class FeaWorkspace { if (why) { toast({ kind: 'info', message: why }); return; } if (this.busy) return; const gen = ++this.generation; + // The faces are found in the part as it is built: a change just made (Run right after an edit) is built first. + this.setBusy('Preparing the part', 0); + await this.app.whenBuilt(); + if (gen !== this.generation) return; let resolved: ReturnType; // What is solved is the study and material as they are now (they may change while it runs). - const studyKey = this.studyKey(); + const studyKey = this.studyKey(), shape = this.shapeKey(); try { - resolved = this.inputOf(s); + resolved = this.inputOf(this.study ?? s); } catch (e) { + this.busy = null; this.error = { key: this.solveKey(), message: (e as Error).message }; this.changed(); void this.openResults(); @@ -388,6 +393,8 @@ export class FeaWorkspace { try { const m = await this.ensureMesh(); if (!m || gen !== this.generation) return; + // The faces were found in another shape than the one meshed (the part changed while it started). + if (m.version !== shape) throw new Error('The part changed while the analysis started. Run it again.'); // The shape meshed and the study read at the start: a change during the run leaves the results out of date. const key = this.solveKey(m.size, m.version, studyKey); const t0 = performance.now(); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 3e79555930..2eef8c56cc 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -439,3 +439,21 @@ test('the CSV summary has one quantity per row, with its unit in the unit column for (const line of csv.trim().split('\n').slice(1)) expect(line, line).not.toMatch(/,[-\d.e]+ (N|MPa|mm|%)/); expect(errors).toEqual([]); }); + +test('Run right after an edit that renumbers the faces loads the faces picked', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:study"]').click(); + await page.getByRole('button', { name: 'Close', exact: true }).click(); + // Suppressing the fillet renumbers the faces; Run comes before the part is rebuilt. + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Suppress', (d) => { d.features.find((x) => x.name === 'Fillet1')!.suppressed = true; }); + a.commands.run('fea:run'); + }); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + // The force on the top of the upright, held at the end of the base. + await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); + expect(errors).toEqual([]); +}); From 847f246733c1d122374cadd2a4286cbd8ee6c481 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:39:01 -0700 Subject: [PATCH 056/116] Parametric: a custom material with its yield strength above its tensile strength is refused (most likely swapped) --- src/parametric/src/app/dialogs.ts | 11 +++++++---- src/parametric/tests/e2e/dialogs.spec.ts | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/dialogs.ts b/src/parametric/src/app/dialogs.ts index 7b41ff49a2..7ba0040a68 100644 --- a/src/parametric/src/app/dialogs.ts +++ b/src/parametric/src/app/dialogs.ts @@ -236,24 +236,27 @@ export async function materialDialog(app: App) { // The elastic fields that keep the set from being used (all empty is no set, not an error). const badElastic = () => { if (elasticFields.every((f) => !f.value.trim())) return []; - return elasticFields.filter((f) => { + const bad = elasticFields.filter((f) => { const v = Number(f.value); return !f.value.trim() || !Number.isFinite(v) || (f === customNu ? v < 0 || v >= 0.5 : v <= 0); }); + return bad.length ? bad : yieldAboveUts() ? [customYield, customUts] : []; }; + // Yield above the tensile strength: the two are most likely swapped. + const yieldAboveUts = () => Number(customYield.value) > Number(customUts.value); const customElastic = (): ElasticProps | null | 'invalid' => { if (elasticFields.every((f) => !f.value.trim())) return null; const e = { E: Number(customE.value) * 1000, nu: Number(customNu.value), yield: Number(customYield.value), uts: Number(customUts.value) }; - return elasticFields.some((f) => !f.value.trim()) || !validElastic(e) ? 'invalid' : e; + return elasticFields.some((f) => !f.value.trim()) || !validElastic(e) || yieldAboveUts() ? 'invalid' : e; }; const validate = () => { const density = Number(customDensity.value); const densityOk = select.value !== '__custom' || (Number.isFinite(density) && density > 0); const elasticOk = select.value !== '__custom' || customElastic() !== 'invalid'; - error.textContent = !densityOk ? 'Enter a finite, positive density.' : !elasticOk ? 'Enter all four elastic properties as positive numbers, with a Poisson\'s ratio from 0 to below 0.5 (or leave them all empty).' : ''; + const bad = elasticOk ? [] : badElastic(); + error.textContent = !densityOk ? 'Enter a finite, positive density.' : !elasticOk ? (bad[0] === customYield && bad.length === 2 && yieldAboveUts() ? 'The yield strength cannot be above the tensile strength.' : 'Enter all four elastic properties as positive numbers, with a Poisson\'s ratio from 0 to below 0.5 (or leave them all empty).') : ''; if (densityOk) customDensity.removeAttribute('aria-invalid'); else customDensity.setAttribute('aria-invalid', 'true'); - const bad = elasticOk ? [] : badElastic(); for (const f of elasticFields) { if (bad.includes(f)) f.setAttribute('aria-invalid', 'true'); else f.removeAttribute('aria-invalid'); } return densityOk && elasticOk; }; diff --git a/src/parametric/tests/e2e/dialogs.spec.ts b/src/parametric/tests/e2e/dialogs.spec.ts index c3e2aa3617..14ba29d69d 100644 --- a/src/parametric/tests/e2e/dialogs.spec.ts +++ b/src/parametric/tests/e2e/dialogs.spec.ts @@ -226,3 +226,24 @@ test('an invalid elastic property of a custom material is the field marked and f .toEqual({ name: 'Custom material', density: 1000, E: 200000, nu: 0.3, yield: 250, uts: 400 }); expect(errors).toEqual([]); }); + +test('a custom material whose yield strength is above its tensile strength is refused', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => (window as unknown as Handle).__parametric.commands.run('material')); + const dialog = page.getByRole('dialog', { name: 'Material', exact: true }); + await dialog.getByRole('combobox').selectOption('__custom'); + await dialog.getByLabel('Elastic modulus in GPa').fill('200'); + await dialog.getByLabel("Poisson's ratio").fill('0.3'); + await dialog.getByLabel('Yield strength in MPa').fill('400'); + await dialog.getByLabel('Tensile strength in MPa').fill('250'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(dialog.getByRole('alert')).toHaveText('The yield strength cannot be above the tensile strength.'); + await expect(dialog.getByLabel('Yield strength in MPa')).toBeFocused(); + await expect(dialog.getByLabel('Tensile strength in MPa')).toHaveAttribute('aria-invalid', 'true'); + await dialog.getByLabel('Tensile strength in MPa').fill('450'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(dialog).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.material)).toMatchObject({ yield: 400, uts: 450 }); + expect(errors).toEqual([]); +}); From 209cfcfef353f1fe5cbf53b7ededd0b11ceb6435 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:41:19 -0700 Subject: [PATCH 057/116] Parametric: a limit mate whose smallest and largest values are equal counts as fixing the component (it showed a degree of freedom that could not move) --- src/parametric/src/assembly/solver.ts | 11 ++++++++--- src/parametric/tests/assembly-kinematics.test.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index b26d12965b..30ad34dbaa 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -524,7 +524,8 @@ function mechanicalEquations(c: MechContext): number[] | null { if (!m.limit) return [...conc, ...plane]; const t = hingeTurn(m, c.pa, c.pb); if (t === null) return null; - return [...conc, ...plane, ...(c.ineq ? [outsideTurn(t, (m.limit.min * Math.PI) / 180, (m.limit.max * Math.PI) / 180)] : [])]; + // (Kept at one angle, the limit is an equation: it takes the turn away.) + return [...conc, ...plane, ...(c.ineq || m.limit.min === m.limit.max ? [outsideTurn(t, (m.limit.min * Math.PI) / 180, (m.limit.max * Math.PI) / 180)] : [])]; } case 'gear': { if (!isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; @@ -582,7 +583,7 @@ function mechanicalEquations(c: MechContext): number[] | null { rows = [...p1, ...p2]; } if (!m.limit) return rows; - return [...rows, ...(c.ineq ? [outside(sliderTravel(m, rel, dir), m.limit.min, m.limit.max) / L] : [])]; + return [...rows, ...(c.ineq || m.limit.min === m.limit.max ? [outside(sliderTravel(m, rel, dir), m.limit.min, m.limit.max) / L] : [])]; } case 'cam': { const prof = m.a.geo; @@ -1076,7 +1077,11 @@ export class MateSolver { if ((m.a.body && !pa) || (m.b.body && !pb)) return null; if (isMechanical(m.type)) return mechanicalResidual(m, pl, ref, pa, pb, L, ineq, turns); const o = { aligned: m.aligned, value: m.value, flip: m.flip, scale: L, rel: m.rel }; - if (m.limit && (m.type === 'distance' || m.type === 'angle')) return limitEquations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, m.limit, ineq); + if (m.limit && (m.type === 'distance' || m.type === 'angle')) { + // Kept at one value it is that value's mate (it takes the freedom away). + if (m.limit.min === m.limit.max) return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), { ...o, value: m.limit.min }, pa, pb); + return limitEquations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, m.limit, ineq); + } return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, pa, pb); } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index d6b40db0f6..ea7c8791b0 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -66,6 +66,18 @@ describe('limit mates', () => { expect([...bad.invalid.values()][0]).toMatch(/smallest/); }); + it('a limit whose smallest and largest values are equal holds the component there (it takes the freedom away)', () => { + const r = blockOnSlide({ min: 12, max: 12 }).analyze(); + expect(r.status).toBe('full'); + expect(r.dof).toBe(0); + expect(r.defined.has('blk')).toBe(true); + expect(gap(r.placements)).toBeCloseTo(12, 6); + const start: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const held = new MateSolver([body('base', true), body('lid', false)], [mate('hinge', ['base', axis([0, 0, 0])], ['lid', axis([0, 0, 0])], { a2: { body: 'base', geo: plane([0, 0, 0], Z) }, b2: { body: 'lid', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: false, rel: start, limit: { min: 20, max: 20 } })]).analyze(); + expect(held.dof).toBe(0); + expect(deg(angleZ(held.placements.get('lid')!.q))).toBeCloseTo(20, 4); + }); + it('an angle limit stops a lid turning on its hinge', () => { const lidTop = plane([20, 1, 0], [0, 1, 0]); const mates = [ From d99b973f67e7d33bc57a6c44d628cd8e3fcf04b3 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:42:14 -0700 Subject: [PATCH 058/116] Parametric: a motion study stopped by a limit kept at one value says the limit was reached (not that the mechanism locks up) --- src/parametric/src/assembly/motion.ts | 4 +++- src/parametric/tests/assembly-kinematics.test.ts | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts index d40c3dbd04..30eb838218 100644 --- a/src/parametric/src/assembly/motion.ts +++ b/src/parametric/src/assembly/motion.ts @@ -220,7 +220,9 @@ export class MotionRun { if (!(m.limit || m.type === 'slot')) continue; const all = solver.mateResidual(m, pl, this.setup.scale, prev, true) ?? []; const eq = solver.mateResidual(m, pl, this.setup.scale, prev, false) ?? []; - if (Math.abs(all[all.length - 1] ?? 0) > CONFLICT_TOL && all.length > eq.length) { + // (Kept at one value, the limit is an equation: the mate not holding is the limit reached.) + const fixed = m.limit && m.limit.min === m.limit.max && (residuals.get(m.id) ?? 0) > CONFLICT_TOL; + if (fixed || (Math.abs(all[all.length - 1] ?? 0) > CONFLICT_TOL && all.length > eq.length)) { return { time, kind: 'limit', mate: m.id, message: `${name(m.id)} reached its limit at ${time} s: the motion stops there.` }; } } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index ea7c8791b0..828dd88287 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -129,6 +129,11 @@ describe('mechanical mates', () => { expect(open.stop?.time).toBeCloseTo(3.1, 6); expect(degreesAbout(turnPath(open, 'lid'), Z).at(-1)).toBeCloseTo(270, 4); expect(mateSeries(open, door)!.values.at(-1)).toBeCloseTo(270, 4); + // Kept at one angle, it cannot turn: the study stops at that limit. + const shut0 = { ...door, limit: { min: 0, max: 0 } }; + const stuck = computeMotion({ bodies, mates: [shut0], motors: [{ id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: shut0, at: profileOf('rotary', { profile: 'constant', speed: 90 }, 4) }], duration: 4, fps: 10, scale: 100 }); + expect(stuck.stop?.kind).toBe('limit'); + expect(stuck.stop?.mate).toBe(door.id); // The other way it is at its end already. const shut = run(-90); expect(shut.stop?.kind).toBe('limit'); From f13aa7e17b7c2dae2129fc3a356c8deba01c3463 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:47:23 -0700 Subject: [PATCH 059/116] Parametric: a rack is checked against its pinion's axis where the mates put them, so an assembly opened again reports the same --- src/parametric/src/assembly/solver.ts | 24 ++++++++++++------- .../tests/assembly-kinematics.test.ts | 8 +++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index 30ad34dbaa..ec569334b1 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -1110,7 +1110,15 @@ export class MateSolver { } res = this.solve(opts, kept, placements); } - const active = usable.filter((m) => !conflicts.has(m.id)); + // A rack along its pinion's axis, where the mates put them, is no rack and pinion + // (told where they end up, so solving again from there says the same). + let racks = false; + for (const m of usable) { + const why = m.type === 'rackPinion' && !conflicts.has(m.id) ? rackProblem(m, res.placements) : null; + if (why) { invalid.set(m.id, why); racks = true; } + } + if (racks) res = this.solve(opts, usable.filter((m) => !conflicts.has(m.id) && !invalid.has(m.id)), res.placements); + const active = usable.filter((m) => !conflicts.has(m.id) && !invalid.has(m.id)); const floating = this.bodies.filter((b) => !b.fixed); const pl = res.placements; // The Jacobian of the mates at the solution (all components free to move) is @@ -1209,16 +1217,16 @@ export class MateSolver { if (m.type === 'angle' && (m.limit.min < 0 || m.limit.max > 180)) return 'Angle limits are between 0° and 180°'; if (m.type === 'hinge' && !m.rel) return 'The hinge has no stored position to measure its angle from'; } - if (isMechanical(m.type)) return mechanicalProblem(m) ?? (m.type === 'rackPinion' ? this.rackProblem(m) : null); + if (isMechanical(m.type)) return mechanicalProblem(m); return m.type === 'lock' ? null : mateProblem(m.type, m.a.geo, m.b.geo); } +} - /** A rack along its pinion's axis (where the components are) is no rack and pinion: it would move as a screw. */ - private rackProblem(m: SolverMate): string | null { - const at = (e: SolverEntity) => (e.body ? this.bodies.find((b) => b.id === e.body)?.placement ?? null : null); - const dp = dirOf(placeGeo(m.a.geo, at(m.a))), u = dirOf(placeGeo(m.b.geo, at(m.b))); - return dp && u && Math.abs(dot(normalize(dp), normalize(u))) > 0.999 ? 'The rack must run across the pinion\'s axis, not along it' : null; - } +/** A rack along its pinion's axis (where `pl` puts them) is no rack and pinion: it would move as a screw. */ +function rackProblem(m: SolverMate, pl: Map): string | null { + const at = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? null : null); + const dp = dirOf(placeGeo(m.a.geo, at(m.a))), u = dirOf(placeGeo(m.b.geo, at(m.b))); + return dp && u && Math.abs(dot(normalize(dp), normalize(u))) > 0.999 ? 'The rack must run across the pinion\'s axis, not along it' : null; } /** diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 828dd88287..acbd20fed7 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -284,6 +284,14 @@ describe('mechanical mates', () => { const bad = new MateSolver(s.bodies, [...s.mates.slice(0, 3), along]).analyze(); expect(bad.status).toBe('error'); expect(bad.invalid.get(along.id)).toMatch(/across the pinion's axis/); + // Along the axis where it was put, across it where the other mates put it: told where they end up + // (so the assembly opened again, solved where it was saved, says the same). + const turnedR = body('R', false, [0, -10, 0], qAxisAngle([0, 1, 0], -Math.PI / 2)); + const squared = [...s.mates.slice(0, 2), mate('parallel', ['g', plane([0, 0, 0], Z)], ['R', plane([0, 0, 0], Z)]), s.mates[3]]; + const first = new MateSolver([s.bodies[0], s.bodies[1], turnedR], squared).analyze(); + expect(first.invalid.size).toBe(0); + const reopened = new MateSolver([s.bodies[0], s.bodies[1], { ...turnedR, placement: first.placements.get('R')! }], squared).analyze(); + expect([reopened.status, reopened.dof]).toEqual([first.status, first.dof]); // By travel per turn, and reversed. const per = rackAndPinion({ by: 'revolution', value: 50, reverse: true }); const r2 = computeMotion({ bodies: per.bodies, mates: per.mates, motors: [rotary('P', axis([0, 0, 0]), 360)], duration: 1, fps: 30, scale: 100 }); From 0efdbfa94c6a4ab6be14fad5e3aeaef0172a3237 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:48:31 -0700 Subject: [PATCH 060/116] Parametric: a slider on edges set to the other alignment turns the component over with one freedom left (it showed two, and settled at a random turn) --- src/parametric/src/assembly/solver.ts | 16 +++++++++++++++- src/parametric/tests/assembly-kinematics.test.ts | 13 +++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index ec569334b1..a0cf8dcc42 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -574,7 +574,7 @@ function mechanicalEquations(c: MechContext): number[] | null { if (!isAxisLike(ga) || !isAxisLike(gb) || !isAxisLike(m.a.geo)) return null; dir = normalize(dirOf(m.a.geo)!); const da = normalize(dirOf(ga)!), db = normalize(dirOf(gb)!); - rows = [...(m.aligned ? sub(da, db) : add(da, db)), ...scale(cross(sub(pointOf(gb)!, pointOf(ga)!), da), 1 / L), turnAbout(rel.q, m.rel.q, dir)]; + rows = [...(m.aligned ? sub(da, db) : add(da, db)), ...scale(cross(sub(pointOf(gb)!, pointOf(ga)!), da), 1 / L), turnAbout(rel.q, sliderStart(m, dir), dir)]; } else { // Two pairs of faces flush: they slide along the line where the faces meet. const p1 = equations('coincident', ga, gb, o, null, null), p2 = equations('coincident', ga2, gb2, { ...o, aligned: !!m.aligned2 }, null, null); @@ -643,6 +643,20 @@ function sliderTravel(m: SolverMate, rel: Placement, dir: Vec3): number { return dot(sub(applyPlacement(rel, p), applyPlacement(m.rel!, p)), dir); } +/** + * Where b was in a's frame (its orientation) when a slider on straight edges + * was added, turned over (half a turn across b's edge) when the slider's + * alignment is the other way from the edges' there: its turn about the + * slide is measured from that (from where it was added, half a turn away, + * it has no turn to measure: the slider showed a freedom it did not have). + */ +function sliderStart(m: SolverMate, dir: Vec3): Quat { + const q = m.rel!.q, db = normalize(dirOf(m.b.geo)!); + if ((dot(dir, qRotate(q, db)) >= 0) === m.aligned) return q; + const e = perpendicular(db); + return qMul(q, [e[0], e[1], e[2], 0]); +} + /** The direction a slider slides, in a's coordinates. */ export function sliderDirection(m: SolverMate): Vec3 | null { if (m.a2?.geo.kind === 'plane' && m.a.geo.kind === 'plane') { const d = cross(m.a.geo.n, m.a2.geo.n); return len(d) > 1e-9 ? normalize(d) : null; } diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index acbd20fed7..7ce39b77f4 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -544,6 +544,19 @@ describe('slider, cam and universal joint mates', () => { expect(turned.placements.get('blk')!.q[3]).toBeCloseTo(1, 6); }); + it('a slider on straight edges set to the other alignment turns the component over, and leaves one freedom', () => { + const blk = body('blk', false, [3, 4, 5]); + const m = slider(blk, { aligned: false }); + const r = new MateSolver([body('g', true), blk], [m]).analyze(); + expect(r.dof).toBe(1); + const q = r.placements.get('blk')!.q; + expect(qRotate(q, X)[0]).toBeCloseTo(-1, 6); + expect(qRotate(q, Z)[2]).toBeCloseTo(1, 6); + const again = new MateSolver([body('g', true), { ...blk, placement: r.placements.get('blk')! }], [m]).analyze(); + expect(again.dof).toBe(1); + expect(again.placements.get('blk')!.q.map((v, i) => Math.abs(v - q[i]) < 1e-6 || Math.abs(v + q[i]) < 1e-6).every(Boolean)).toBe(true); + }); + it('a slider on two faces of each component slides along the line where they meet', () => { const m = mate('slider', ['g', plane([0, 0, 0], Y)], ['blk', plane([0, 0, 0], [0, -1, 0])], { a2: { body: 'g', geo: plane([0, 0, 0], Z) }, b2: { body: 'blk', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned: false, aligned2: false, rel: at0, From 63bea9b9341d6ea8d197fdad5d03c25c89042f88 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:51:17 -0700 Subject: [PATCH 061/116] Parametric: bevel gears (square axes) keep which way they turn as their axes tilt a hair (the gear flipped direction between solver steps) --- src/parametric/src/assembly/solver.ts | 7 +++++-- src/parametric/tests/assembly-kinematics.test.ts | 13 ++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index a0cf8dcc42..1b913bfd2e 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -530,8 +530,11 @@ function mechanicalEquations(c: MechContext): number[] | null { case 'gear': { if (!isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; const da = normalize(dirOf(ga)!), db0 = normalize(dirOf(gb)!); - // Parallel axes turn about the same direction: external gears turn opposite ways. - const db = dot(da, db0) < 0 ? scale(db0, -1) : db0; + // Parallel axes turn about the same direction: external gears turn opposite ways. Which + // way round is told where the solve started (bevel gears' axes are square: that the + // way did not change with every tiny tilt of them). + const sense = dot(normalize(qRotate(c.ra.q, dirOf(m.a.geo)!)), normalize(qRotate(c.rb.q, dirOf(m.b.geo)!))); + const db = sense < -1e-9 ? scale(db0, -1) : db0; const ta = c.turned(m.a, da), tb = c.turned(m.b, db); const va = m.value, vb = m.value2 ?? 0; if (!(va > 0) || !(vb > 0)) return null; diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts index 7ce39b77f4..6b02029ac8 100644 --- a/src/parametric/tests/assembly-kinematics.test.ts +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, profileSupport, relativePlacement, turnAbout } from '../src/assembly/solver'; import { type PartGeometry, camProfileOf } from '../src/assembly/compose'; import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, framesSpread, mateSeries, pointPath, profileOf, resultsCsv, sameMotionGroups, turnPath, vectorDerivatives } from '../src/assembly/motion'; -import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; +import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qMul, qRotate, sub } from '../src/math/vec'; import type { MateType, Placement } from '../src/model/assembly'; const Z: Vec3 = [0, 0, 1], Y3: Vec3 = [0, 1, 0]; @@ -200,6 +200,17 @@ describe('mechanical mates', () => { expect(held.defined.has('A')).toBe(true); }); + it('bevel gears (square axes) keep their sense as the axes tilt a little either way', () => { + const X3: Vec3 = [1, 0, 0]; + const g = mate('gear', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0], X3)], { value: 20, value2: 20 }); + const s = new MateSolver([body('A', false), body('B', false, [20, 0, 10])], [g]); + const start = new Map(s.bodies.map((b) => [b.id, b.placement])); + // A turned 0.01 about z, B 0.01 about x and tilted a hair about y one way or the other. + const at = (tilt: number) => new Map(start).set('A', { p: [0, 0, 0], q: qAxisAngle(Z, 0.01) }).set('B', { p: [20, 0, 10], q: qMul(qAxisAngle([0, 1, 0], tilt), qAxisAngle(X3, 0.01)) }); + const r1 = s.mateResidual(g, at(1e-7), 100, start)![0], r2 = s.mateResidual(g, at(-1e-7), 100, start)![0]; + expect(Math.abs(r1 - r2)).toBeLessThan(1e-6); + }); + it('dragging one gear by a tooth turns the other', () => { const s = gears(); let pl = s.analyze().placements; From 3d0529cc6665315f0528ddf55a3f627bd3a19508 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:52:10 -0700 Subject: [PATCH 062/116] Parametric: random small assemblies with every kind of mate are checked for the solver's invariants (degrees of freedom, no NaN, the same after reopening, motion within limits) --- src/parametric/tests/assembly-fuzz.test.ts | 162 +++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 src/parametric/tests/assembly-fuzz.test.ts diff --git a/src/parametric/tests/assembly-fuzz.test.ts b/src/parametric/tests/assembly-fuzz.test.ts new file mode 100644 index 0000000000..aa0344a4f1 --- /dev/null +++ b/src/parametric/tests/assembly-fuzz.test.ts @@ -0,0 +1,162 @@ +// Random small assemblies (a fixed seed each): plain and mechanical mates with +// limits, gears, racks, screws, slots, width, cams and universal joints between +// 3 to 8 components, one of them grounded. Every one must keep the invariants: +// the degrees of freedom are the rank deficiency of the mates' Jacobian, every +// motion called free keeps the mates (to second order), nothing turns NaN or +// throws, solving again where it was saved changes nothing, and a motion study +// on each hinge or slider stays within every limit and stops with a message. +import { expect, it } from 'vitest'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateMeasure, matrixRank, nullSpace, relativePlacement, rotVecQuat } from '../src/assembly/solver'; +import { type MotorInput, computeMotion, profileOf } from '../src/assembly/motion'; +import { type Quat, type Vec3, add, qMul, qNormalize, qRotate, sub, normalize } from '../src/math/vec'; +import type { MateType, Placement } from '../src/model/assembly'; + +function rng(seed: number) { let s = seed >>> 0; return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; }; } +const Z: Vec3 = [0, 0, 1], X: Vec3 = [1, 0, 0]; +type R = () => number; +const pickOf = (r: R, a: T[]) => a[Math.floor(r() * a.length)]; + +function makeAssembly(seed: number) { + const r = rng(seed); + const nb = 3 + Math.floor(r() * 6); + const bodies: SolverBody[] = [{ id: 'g', fixed: true, placement: { p: [0, 0, 0], q: [0, 0, 0, 1] }, center: [0, 0, 0] }]; + for (let i = 1; i < nb; i++) { + const q = qNormalize([r() - 0.5, r() - 0.5, r() - 0.5, 1 + r()] as Quat); + bodies.push({ id: `b${i}`, fixed: r() < 0.1, placement: { p: [(r() - 0.5) * 80, (r() - 0.5) * 80, (r() - 0.5) * 80], q: r() < 0.5 ? [0, 0, 0, 1] : q }, center: [r() * 10, r() * 10, r() * 10] }); + } + const pl = new Map(bodies.map((b) => [b.id, b.placement])); + const rel = (a: string, b: string) => relativePlacement(pl.get(a)!, pl.get(b)!); + const axis = (p: Vec3 = [0, 0, 0], d: Vec3 = Z, rad = 2): Geo => ({ kind: 'axis', p, d, r: rad, surface: 'cylinder' }); + const plane = (o: Vec3, n: Vec3): Geo => ({ kind: 'plane', o, n }); + const line = (p: Vec3, d: Vec3): Geo => ({ kind: 'line', p, d }); + const mates: SolverMate[] = []; + const nm = 1 + Math.floor(r() * (nb + 2)); + let k = 0; + for (let i = 0; i < nm; i++) { + const ids = bodies.map((b) => b.id); + const a = pickOf(r, ids); + let b = pickOf(r, ids); + if (b === a) b = ids[(ids.indexOf(a) + 1) % ids.length]; + const base = { id: `m${++k}`, aligned: r() < 0.7, value: 0, flip: r() < 0.2 }; + const lim = (lo: number, hi: number) => { const x = lo + r() * (hi - lo), y = lo + r() * (hi - lo); return r() < 0.15 ? { min: x, max: x } : { min: Math.min(x, y), max: Math.max(x, y) }; }; + const t: MateType = pickOf(r, ['coincident', 'concentric', 'distance', 'angle', 'parallel', 'hinge', 'hinge', 'slider', 'gear', 'rackPinion', 'screw', 'width', 'slot', 'cam', 'universal', 'distance', 'angle'] as MateType[]); + const P = (): Vec3 => [Math.round((r() - 0.5) * 20), Math.round((r() - 0.5) * 20), Math.round((r() - 0.5) * 20)]; + const N = (): Vec3 => pickOf(r, [X, Z, [0, 1, 0], [0, 0, -1], [-1, 0, 0]] as Vec3[]); + let m: SolverMate; + switch (t) { + case 'coincident': case 'parallel': m = { ...base, type: t, a: { body: a, geo: plane(P(), N()) }, b: { body: b, geo: plane(P(), N()) } }; break; + case 'concentric': m = { ...base, type: t, a: { body: a, geo: axis(P(), N()) }, b: { body: b, geo: axis(P(), N()) } }; break; + case 'distance': m = { ...base, type: t, value: r() * 30, a: { body: a, geo: r() < 0.5 ? plane(P(), N()) : { kind: 'point', p: P() } }, b: { body: b, geo: r() < 0.5 ? plane(P(), N()) : { kind: 'point', p: P() } }, ...(r() < 0.6 ? { limit: lim(-10, 40) } : {}) }; break; + case 'angle': m = { ...base, type: t, value: r() * 180, a: { body: a, geo: plane(P(), N()) }, b: { body: b, geo: plane(P(), N()) }, ...(r() < 0.6 ? { limit: lim(0, 180) } : {}) }; break; + case 'hinge': m = { ...base, type: t, a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P()) }, a2: { body: a, geo: plane([0, 0, 0], Z) }, b2: { body: b, geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: r() < 0.3, ...(r() < 0.5 ? { rel: rel(a, b), limit: lim(-200, 200) } : {}) }; break; + case 'slider': m = { ...base, type: t, rel: rel(a, b), a: { body: a, geo: line(P(), X) }, b: { body: b, geo: line(P(), X) }, ...(r() < 0.5 ? { limit: lim(-30, 30) } : {}) }; break; + case 'gear': m = { ...base, type: t, value: 5 + r() * 40, value2: 5 + r() * 40, reverse: r() < 0.3, a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P(), r() < 0.3 ? X : Z) } }; break; + case 'rackPinion': m = { ...base, type: t, value: 5 + r() * 40, by: r() < 0.3 ? 'revolution' : undefined, a: { body: a, geo: axis(P()) }, b: { body: b, geo: line(P(), pickOf(r, [X, [0, 1, 0], Z] as Vec3[])) } }; break; + case 'screw': m = { ...base, type: t, value: (r() - 0.5) * 6, a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P()) } }; break; + case 'width': { const w = 5 + r() * 10, tw = r() * 8; m = { ...base, type: t, a: { body: a, geo: plane([-w, 0, 0], X) }, a2: { body: a, geo: plane([w, 0, 0], [-1, 0, 0]) }, b: { body: b, geo: plane([-tw, 0, 0], [-1, 0, 0]) }, b2: { body: b, geo: plane([tw, 0, 0], X) } }; break; } + case 'slot': m = { ...base, type: t, a: { body: a, geo: axis([0, 0, 0]) }, a2: { body: a, geo: axis([r() < 0.1 ? 0 : 5 + r() * 30, 0, 0]) }, b: { body: b, geo: r() < 0.5 ? axis(P()) : { kind: 'point', p: P() } } }; break; + case 'cam': { const prof = r() < 0.5 ? camProfile(Z, [{ c: [0, -3 - r() * 5, 0], r: 10 + r() * 10 }], []) : camProfile(Z, [], [[-10, -10, 0], [10, -10, 0], [10, 10, 0], [r() < 0.3 ? 0 : -10, r() < 0.3 ? 4 : 10, 0]]); m = { ...base, type: t, a: { body: a, geo: prof }, b: { body: b, geo: pickOf(r, [{ kind: 'point', p: P() }, axis(P(), Z, 3), plane(P(), [0, -1, 0]), plane(P(), Z)] as Geo[]) } }; break; } + default: m = { ...base, type: 'universal', rel: rel(a, b), a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P(), r() < 0.5 ? Z : normalize([0.3, 0, 1])) }, ...(r() < 0.3 ? { by: 'point', value: r() * 10 } : {}) }; + } + mates.push(m); + } + return { bodies, mates }; +} + +const finitePl = (pl: Map) => [...pl.values()].every((p) => [...p.p, ...p.q].every(Number.isFinite)); + +function placementWith(base: Placement, center: Vec3, x: number[], L: number): Placement { + const dq = rotVecQuat([x[3], x[4], x[5]]); + const c = applyPlacement(base, center); + return { p: add(add(qRotate(dq, sub(base.p, c)), c), [x[0] * L, x[1] * L, x[2] * L]), q: qNormalize(qMul(dq, base.q)) }; +} + +function fuzzOne(seed: number, log: string[]) { + const { bodies, mates } = makeAssembly(seed); + const L = 100; + const s = new MateSolver(bodies, mates); + let an; + try { an = s.analyze({ scale: L }); } catch (e) { log.push(`seed ${seed}: analyze threw ${(e as Error).stack}`); return; } + if (!finitePl(an.placements)) { log.push(`seed ${seed}: non-finite placements`); return; } + // (a) DOF vs rank of an independent Jacobian of the active mates (all floating bodies). + const active = mates.filter((m) => !an.conflicts.has(m.id) && !an.invalid.has(m.id)); + const floating = bodies.filter((b) => !b.fixed); + const n = floating.length * 6; + const pl = an.placements; + const rows: number[][] = []; + const allHold = active.every((m) => (s.mateResidual(m, pl, L, pl, true) ?? [Infinity]).every((v) => Math.abs(v) < 1e-6)); + for (const m of active) { + const r0 = s.mateResidual(m, pl, L, pl, false) ?? []; + const blk = r0.map(() => new Array(n).fill(0)); + floating.forEach((b, bi) => { + for (let j = 0; j < 6; j++) { + const x = [0, 0, 0, 0, 0, 0]; + x[j] = 1e-6; const rp = s.mateResidual(m, new Map(pl).set(b.id, placementWith(pl.get(b.id)!, b.center ?? [0, 0, 0], x, L)), L, pl, false) ?? []; + x[j] = -1e-6; const rm = s.mateResidual(m, new Map(pl).set(b.id, placementWith(pl.get(b.id)!, b.center ?? [0, 0, 0], x, L)), L, pl, false) ?? []; + for (let i = 0; i < r0.length; i++) blk[i][bi * 6 + j] = (rp[i] - rm[i]) / 2e-6; + } + }); + rows.push(...blk); + } + const dof = n - matrixRank(rows, n); + // Every motion the rank calls free keeps the mates to second order (a residual with a vanishing gradient would not). + if (allHold && n) { + for (const v of nullSpace(rows, n).basis) { + const mx = Math.max(...v.map(Math.abs)); + const moved = new Map(pl); + floating.forEach((b, bi) => moved.set(b.id, placementWith(pl.get(b.id)!, b.center ?? [0, 0, 0], v.slice(bi * 6, bi * 6 + 6).map((x) => (x / mx) * 1e-4), L))); + let worst = 0, who = ''; + for (const m of active) { if (m.type === 'cam') continue; const rr = s.mateResidual(m, moved, L, pl, false) ?? []; for (const x of rr) if (Math.abs(x) > worst) { worst = Math.abs(x); who = `${m.id} ${m.type}`; } } + if (worst > 1e-5) { log.push(`seed ${seed}: a free motion breaks ${who} by ${worst.toExponential(2)}`); break; } + } + } + if (dof !== an.dof && allHold) log.push(`seed ${seed}: dof ${an.dof} reported, rank says ${dof} (status ${an.status}, types ${active.map((m) => m.type).join(',')})`); + // (b) drags never produce NaN or throw. + const r = rng(seed + 7); + for (const b of floating.slice(0, 3)) { + try { + const d = s.solve({ scale: L, drag: r() < 0.5 ? { kind: 'move', body: b.id, local: [0, 0, 0], target: [(r() - 0.5) * 100, (r() - 0.5) * 100, (r() - 0.5) * 100] } : { kind: 'rotate', body: b.id, q: qNormalize([r() - 0.5, r() - 0.5, r() - 0.5, r()]) }, maxIter: 25 }, active, pl); + if (!finitePl(d.placements)) log.push(`seed ${seed}: drag gave non-finite placements`); + } catch (e) { log.push(`seed ${seed}: drag threw ${(e as Error).stack}`); } + } + // (c) solving again from the solved (saved) placements keeps them. + if (an.status !== 'over' && allHold) { + const again = new MateSolver(bodies.map((b) => ({ ...b, placement: pl.get(b.id)! })), mates).analyze({ scale: L }); + let worst = 0; + for (const [id, p] of again.placements) { const q = pl.get(id)!; worst = Math.max(worst, Math.hypot(...sub(p.p, q.p)), Math.min(Math.hypot(...p.q.map((v, i) => v - q.q[i])), Math.hypot(...p.q.map((v, i) => v + q.q[i])))); } + if (worst > 1e-3) log.push(`seed ${seed}: re-solve moved by ${worst.toExponential(2)}`); + if (again.dof !== an.dof || again.status !== an.status) log.push(`seed ${seed}: re-solve status ${an.status}/${an.dof} -> ${again.status}/${again.dof}`); + } + // (d) a motion study over each hinge or slider. + for (const m of active.filter((x) => x.type === 'hinge' || x.type === 'slider')) { + if (mates.every((x) => x === m || !x)) continue; + const motor: MotorInput = { id: 'mo', name: 'Motor', kind: m.type === 'hinge' ? 'rotary' : 'linear', on: m, at: profileOf(m.type === 'hinge' ? 'rotary' : 'linear', { profile: 'oscillate', amplitude: m.type === 'hinge' ? 120 : 25, frequency: 0.5 }, 2) }; + if (m.a.body && m.b.body && bodies.find((b) => b.id === m.a.body)?.fixed && bodies.find((b) => b.id === m.b.body)?.fixed) continue; + let res; + try { res = computeMotion({ bodies: bodies.map((b) => ({ ...b, placement: pl.get(b.id)! })), mates: active, motors: [motor], duration: 2, fps: 15, scale: L, names: new Map(mates.map((x) => [x.id, `Mate ${x.id}`])) }); } catch (e) { log.push(`seed ${seed}: motion threw ${(e as Error).stack}`); continue; } + if (!res.frames.every(finitePl)) log.push(`seed ${seed}: motion NaN`); + if (res.stop && (!res.stop.message || /undefined|NaN/.test(res.stop.message))) log.push(`seed ${seed}: bad stop message ${res.stop.message}`); + for (const x of active) { + if (!x.limit) continue; + for (const f of res.frames) { + const v = mateMeasure(x, f, L); + if (!v) continue; + let val = v.value; + if (x.type === 'hinge') { if (x.limit.max - x.limit.min >= 360) continue; const mid = (x.limit.min + x.limit.max) / 2; val = mid + ((((val - mid + 180) % 360) + 360) % 360) - 180; } + const tol = v.kind === 'angle' ? 1e-3 : 1e-3; + if (x.type === 'angle' || x.type === 'distance' || x.type === 'slider' || x.type === 'hinge') { + if (x.type === 'distance' && x.limit.min < 0 && !(x.a.geo.kind === 'plane' || x.b.geo.kind === 'plane')) continue; + if (val < x.limit.min - tol || val > x.limit.max + tol) { log.push(`seed ${seed}: ${x.type} limit [${x.limit.min.toFixed(2)}, ${x.limit.max.toFixed(2)}] exceeded: ${val.toFixed(4)} (motor on ${m.type} ${m.id}, frame ok)`); break; } + } + } + } + } +} + + +it('random assemblies keep the solver invariants', () => { + const log: string[] = []; + // Seeds 5, 187 (and 402) and 2107 found a rack checked where it started, bevel gears flipping sense and a turned-over slider. + for (const seed of [...Array.from({ length: 40 }, (_, i) => i + 1), 187, 402, 2107]) fuzzOne(seed, log); + expect(log).toEqual([]); +}, 60_000); From 9dbe9db660ea7d8c3908dbaa1744cb55b88cfb85 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:15:27 -0700 Subject: [PATCH 063/116] Parametric: a new motion study starts without the out-of-date results of one cancelled before it --- src/parametric/src/app/assembly/mode.ts | 6 +++ .../src/app/assembly/motion-panel.ts | 2 + .../tests/e2e/assembly-kinematics.spec.ts | 49 +++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index 69d3f9141b..4578fdb7d8 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -697,9 +697,15 @@ export class AssemblyMode { /** A study added to the document keeps the results computed while it was set up. */ keepMotion(from: Id, to: Id) { const r = this.motions.get(from); + this.motions.delete(from); if (r) this.motions.set(to, r); } + /** Drops a study's results (those of a new study that was set up and cancelled, before the next one). */ + forgetMotion(id: Id) { + this.motions.delete(id); + } + /** The solver input of a study, or why it cannot run. Components start where the mates put them now. */ motionSetup(st: MotionStudy): MotionSetup | string { const motors = st.motors.filter((m) => !m.suppressed); diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index d1d9f875ce..e739dd071c 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -65,6 +65,8 @@ export class MotionStudyPanel extends PropertyPanel { this.original = JSON.stringify(this.study); this.key = existing?.id ?? ''; if (existing) { this.editingId = existing.id; this.title = `Motion Study: ${existing.name}`; } + // A new study starts without results (not with those of one set up before and cancelled). + else mode.forgetMotion(''); this.helpText = 'Add motors that turn or move components (or drive a distance or angle mate), then Calculate. Play the motion back and plot how a component or mate moves. The study starts from where the components are now.'; mode.app.selection.clear(); } diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 72c7b9039d..2f02ff54e1 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -529,3 +529,52 @@ test('slider, cam follower and universal joint through the Mate panel; motors on await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +/** The plate with the two discs on hinges in its holes, geared together; the Mates folder then has Hinge1, Hinge2 and Gear1. */ +async function hingedGears(page: Page) { + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + const pm = page.locator('.pm'); + for (const [gear, hole] of [['Small<1>', 'E1:side:h1'], ['Large<1>', 'E1:side:h2']]) { + await select(page, [{ comp: gear, face: 'E1:side:k' }, { comp: 'Plate<1>', face: hole }]); + await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: gear, face: 'E1:cap0' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + } + await select(page, [{ comp: 'Small<1>', face: 'E1:side:k' }, { comp: 'Large<1>', face: 'E1:side:k' }]); + await openMate(page, 'gear'); + await expect(pm.getByRole('status').filter({ hasText: '1 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + return pm; +} + +/** Adds a rotary motor on Hinge1 to the open Motion Study panel. */ +async function hingeMotor(page: Page, speed = '90') { + const pm = page.locator('.pm'); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge1 (Hinge)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill(speed); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); +} + +test('the Motion Study panel: a new study starts without results', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + // A study set up, calculated and cancelled: the next new study has no results, not out of date ones. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await expect(pm.getByText('No motors yet')).toBeVisible(); + await expect(pm.locator('.pm-msg.warn')).toHaveCount(0); + await expect(pm.getByText(/out of date/)).toHaveCount(0); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From 590a23c6b1a054b4d44d83dee6e5629f4002df0a Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:16:15 -0700 Subject: [PATCH 064/116] Parametric: long motion studies plot instead of leaving the panel stuck on Calculating --- .../src/app/assembly/motion-panel.ts | 32 +++++++++++++++++-- .../tests/e2e/assembly-kinematics.spec.ts | 31 ++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index e739dd071c..b40749f048 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -401,12 +401,15 @@ export class MotionStudyPanel extends PropertyPanel { private plot(res: MotionResult, s: { values: number[]; name: string; unit: string }): HTMLElement { const end = res.times[res.times.length - 1]; - const min = Math.min(...s.values), max = Math.max(...s.values); + // (A loop, not Math.min(...values): a long study has more frames than a call takes arguments.) + let min = Infinity, max = -Infinity; + for (const v of s.values) { if (v < min) min = v; if (v > max) max = v; } + if (!(min <= max)) min = max = 0; // A constant is drawn across the middle. const flat = !(max - min > 1e-9 * Math.max(1, Math.abs(max))); const lo = flat ? min - 1 : min, hi = flat ? max + 1 : max; const y = (v: number) => PLOT.top + (1 - (v - lo) / (hi - lo)) * (PLOT.h - PLOT.top - PLOT.bottom); - const pts = s.values.map((v, i) => `${plotX(res.times[i], end).toFixed(1)},${y(v).toFixed(1)}`).join(' '); + const pts = plotPoints(res.times, s.values, end).map((i) => `${plotX(res.times[i], end).toFixed(1)},${y(s.values[i]).toFixed(1)}`).join(' '); const ns = 'http://www.w3.org/2000/svg'; const el = (tag: K, attrs: Record, text?: string): SVGElementTagNameMap[K] => { const e = document.createElementNS(ns, tag); @@ -614,6 +617,31 @@ const INTERFERENCE_FRAMES = 40; const PLOT = { w: 280, h: 150, left: 44, right: 8, top: 8, bottom: 18 }; const plotX = (t: number, end: number) => PLOT.left + (t / Math.max(end, 1e-9)) * (PLOT.w - PLOT.left - PLOT.right); +/** + * The frames a plot line is drawn through: all of them, or for a long study + * the first, lowest, highest and last of each half unit across the plot (the + * line looks the same, with a few thousand points instead of every frame). + */ +function plotPoints(times: number[], values: number[], end: number): number[] { + const n = values.length; + const columns = 2 * (PLOT.w - PLOT.left - PLOT.right); + if (n <= 4 * columns) return values.map((_, i) => i); + const out: number[] = []; + let i = 0; + while (i < n) { + const c = Math.min(columns - 1, Math.floor((times[i] / Math.max(end, 1e-9)) * columns)); + let lo = i, hi = i, j = i; + while (j + 1 < n && Math.min(columns - 1, Math.floor((times[j + 1] / Math.max(end, 1e-9)) * columns)) === c) { + j++; + if (values[j] < values[lo]) lo = j; + if (values[j] > values[hi]) hi = j; + } + for (const k of [...new Set([i, lo, hi, j])].sort((a, b) => a - b)) out.push(k); + i = j + 1; + } + return out; +} + /** The frame nearest time t. */ function frameAt(res: MotionResult, t: number): number { let lo = 0, hi = res.times.length - 1; diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 2f02ff54e1..5634e48136 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -578,3 +578,34 @@ test('the Motion Study panel: a new study starts without results', async ({ page await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('the Motion Study panel plots a study of more frames than a function call takes arguments', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + // The frames of a 1000 s study at 200 frames a second (as long to compute as 25 s here), from the 151 calculated. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + type R = { times: number[]; frames: unknown[]; duration: number }; + const r = (a.assembly as unknown as { motions: Map }).motions.get('')!.result; + const n = 200_001, frames = r.frames.slice(0, 150), times = Array.from({ length: n }, (_, i) => i / 200); + r.frames = times.map((_, i) => frames[i % 150]); + r.times = times; + r.duration = 1000; + a.refreshPanel(); + }); + await expect(pm.locator('.kin-clock')).toContainText('/ 1000.00 s'); + const plot = pm.getByRole('img', { name: /^Plot of Small<1> linear displacement/ }); + await expect(plot).toBeVisible(); + // The line is drawn through a few points a pixel, not all 200 001. + const points = await plot.locator('polyline').evaluate((e) => (e.getAttribute('points') ?? '').split(' ').length); + expect(points).toBeGreaterThan(400); + expect(points).toBeLessThan(2000); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From 14e4110a6c8c1d96aae38c614f9dcd680f1e4955 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:19:12 -0700 Subject: [PATCH 065/116] Parametric: Escape and Enter in a motion study's motor cancel or add the motor instead of closing the study, and keyboard focus follows --- .../src/app/assembly/motion-panel.ts | 35 +++++++++++++++---- .../tests/e2e/assembly-kinematics.spec.ts | 32 +++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index b40749f048..4e7808c625 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -162,19 +162,19 @@ export class MotionStudyPanel extends PropertyPanel { private motorsSection(): HTMLElement { const list = h('div', { class: 'file-list', role: 'list', 'aria-label': 'Motors' }); this.study.motors.forEach((m, i) => { - const edit = h('button', { class: 'file-item', type: 'button' }, + const edit = h('button', { class: 'file-item', type: 'button', 'data-motor': m.id }, h('span', { 'aria-hidden': 'true' }, icon(m.kind === 'mate' ? 'smartDimension' : m.kind === 'rotary' ? 'rotateComponent' : 'moveComponent', 16)), h('span', { class: 'txt' }, h('span', { class: 'n' }, `${m.name}${m.suppressed ? ' (suppressed)' : ''}`), h('span', { class: 'meta' }, this.describeMotor(m)))); - edit.addEventListener('click', () => { this.motor = structuredClone(m); this.motorIndex = i; this.app.refreshPanel(); }); + edit.addEventListener('click', () => { this.motor = structuredClone(m); this.motorIndex = i; this.refreshTo(MOTOR_FIRST); }); const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': `Delete ${m.name}` }, icon('trash', 14)); - del.addEventListener('click', () => { this.study.motors.splice(i, 1); this.stale(); this.app.refreshPanel(); }); + del.addEventListener('click', () => { this.study.motors.splice(i, 1); this.stale(); this.refreshTo('.kin-add-motor'); }); list.append(h('div', { class: 'file-row kin-motor', role: 'listitem' }, edit, del)); }); - const add = h('button', { class: 'btn small', type: 'button' }, icon('add', 14), 'Add Motor'); + const add = h('button', { class: 'btn small kin-add-motor', type: 'button' }, icon('add', 14), 'Add Motor'); add.addEventListener('click', () => { this.motor = { id: '', name: '', kind: 'rotary', profile: 'constant', speed: 60 }; this.motorIndex = -1; - this.app.refreshPanel(); + this.refreshTo(MOTOR_FIRST); }); return section('Motors', [...(this.study.motors.length ? [list] : [h('p', { class: 'field-label' }, 'No motors yet: add one to drive the mechanism.')]), add]); } @@ -541,12 +541,23 @@ export class MotionStudyPanel extends PropertyPanel { const back = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); back.addEventListener('click', () => this.finishMotor(false)); items.push(h('div', { class: 'row kin-motor-buttons' }, done, back)); - return [section(this.motorIndex < 0 ? 'Add Motor' : `Motor: ${m.name}`, items, { icon: 'motionStudy' })]; + const form = section(this.motorIndex < 0 ? 'Add Motor' : `Motor: ${m.name}`, items, { icon: 'motionStudy' }); + form.classList.add('kin-motor-form'); + // Escape and Enter are the motor's Cancel and Add (or Apply), not the whole study's. + form.addEventListener('keydown', (e) => { + if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return; + const t = e.target as HTMLElement; + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.finishMotor(false); } + // (Enter on a button presses it; in a number field it enters the value.) + else if (e.key === 'Enter' && !(t instanceof HTMLButtonElement) && !(t instanceof HTMLInputElement && t.type !== 'checkbox')) { e.preventDefault(); e.stopPropagation(); this.finishMotor(true); } + }); + return [form]; } private finishMotor(save: boolean) { const m = this.motor; if (!m) return; + const had = this.el.contains(document.activeElement); if (save) { if (!this.checkFields()) return; if (m.kind !== 'mate' && !m.ref && !m.mate) { this.setMessage('error', m.kind === 'rotary' ? 'Select the motor\'s axis (a round face or edge of the component to turn), or a hinge to put it on.' : 'Select the motor\'s direction (a straight edge or face of the component to move), or a slider to put it on.'); return; } @@ -571,6 +582,15 @@ export class MotionStudyPanel extends PropertyPanel { this.motor = null; this.setMessage(null); this.stale(); + // Keyboard focus goes back to the motor in the list (or to Add Motor). + if (had) (this.el.querySelector(`[data-motor="${CSS.escape(m.id)}"]`) ?? this.el.querySelector('.kin-add-motor'))?.focus(); + } + + /** Shows the panel again, with keyboard focus (when it was in the panel) on the first of `to` rather than lost. */ + private refreshTo(to: string) { + const had = this.el.contains(document.activeElement); + this.app.refreshPanel(); + if (had) this.el.querySelector(to)?.focus(); } ok(): boolean { @@ -611,6 +631,9 @@ export class MotionStudyPanel extends PropertyPanel { } } +/** The first control of the motor form (where keyboard focus goes when it opens). */ +const MOTOR_FIRST = '.kin-motor-form .sec-body :is(button, select, input):not([disabled])'; + /** The most frames checked for interference (each is a boolean check of every pair in the worker). */ const INTERFERENCE_FRAMES = 40; diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 5634e48136..d3a8c89c78 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -609,3 +609,35 @@ test('the Motion Study panel plots a study of more frames than a function call t await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('the Motion Study panel: Escape and Enter in a motor cancel or add the motor, not the study, and keyboard focus follows', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + // Opened from the keyboard, the motor's first control takes focus. + await pm.getByRole('button', { name: 'Delete RotaryMotor1' }).focus(); + await page.keyboard.press('Tab'); + await expect(pm.getByRole('button', { name: 'Add Motor' })).toBeFocused(); + await page.keyboard.press('Enter'); + await expect(pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Rotary' })).toBeFocused(); + // Escape leaves the motor: the study and its first motor stay, focus is on Add Motor again. + await pm.getByRole('checkbox', { name: 'Reverse direction' }).focus(); + await page.keyboard.press('Escape'); + await expect(pm.getByRole('heading', { name: 'Motion Study' })).toBeVisible(); + await expect(pm.getByRole('listitem')).toHaveCount(1); + await expect(pm.getByRole('button', { name: 'Add Motor' })).toBeFocused(); + // Enter on a checkbox of the motor adds it. + await page.keyboard.press('Enter'); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge2 (Hinge)' }); + await pm.getByRole('checkbox', { name: 'Reverse direction' }).focus(); + await page.keyboard.press('Enter'); + await expect(pm.getByRole('listitem')).toHaveCount(2); + await expect(pm.getByRole('listitem').nth(1)).toContainText('Hinge2'); + await expect(pm.getByRole('listitem').nth(1).getByRole('button').first()).toBeFocused(); + // Escape outside a motor still cancels the panel. + await page.keyboard.press('Escape'); + await expect(pm).toHaveCount(0); + expect(errors).toEqual([]); +}); From 37e69bd06265bb3566c7de47d69faa09e6c17541 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:23:52 -0700 Subject: [PATCH 066/116] Parametric: moving a component with the Motion Study panel open shows its results as out of date --- .../src/app/assembly/motion-panel.ts | 13 ++++++ .../tests/e2e/assembly-kinematics.spec.ts | 44 +++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index 4e7808c625..b3c0e1c484 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -58,6 +58,9 @@ export class MotionStudyPanel extends PropertyPanel { private plotCursor: SVGLineElement | null = null; private playBtn: HTMLButtonElement | null = null; private bar: HTMLProgressElement | null = null; + /** The results the panel shows (to see when an edit of the assembly puts them out of date). */ + private shown: MotionResult | null = null; + private readonly unwatch: () => void; constructor(private mode: AssemblyMode, private existing: MotionStudy | null = null) { super(); @@ -69,6 +72,14 @@ export class MotionStudyPanel extends PropertyPanel { else mode.forgetMotion(''); this.helpText = 'Add motors that turn or move components (or drive a distance or angle mate), then Calculate. Play the motion back and plot how a component or mate moves. The study starts from where the components are now.'; mode.app.selection.clear(); + // The assembly can change while the panel is open (a component dragged into a new start position): + // playback stops, and the results show as out of date. + this.unwatch = mode.app.store.on(() => { + if (this.disposed || this.computing || this.result() === this.shown) return; + this.play(false); + this.mode.previewPlacements(null); + this.app.refreshPanel(); + }); } private get app(): App { @@ -86,6 +97,7 @@ export class MotionStudyPanel extends PropertyPanel { render(): HTMLElement[] { if (this.motor) return this.renderMotor(); const res = this.result(); + this.shown = res; const out = [this.studySection(), this.motorsSection(), this.calcSection(res)]; if (res && res.frames.length > 1) out.push(this.playSection(res), this.resultsSection(res), this.interferenceSection(res)); return out; @@ -625,6 +637,7 @@ export class MotionStudyPanel extends PropertyPanel { dispose() { this.disposed = true; + this.unwatch(); this.playing = false; cancelAnimationFrame(this.raf); this.mode.previewPlacements(null); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index d3a8c89c78..728dc56197 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -641,3 +641,47 @@ test('the Motion Study panel: Escape and Enter in a motor cancel or add the moto await expect(pm).toHaveCount(0); expect(errors).toEqual([]); }); + +test('the Motion Study panel: dragging a component while it plays stops the playback and puts the results out of date', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page, '30'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await expect(pm.getByRole('button', { name: 'Pause' })).toBeVisible(); + // Drag the large gear round (it turns on its hinge) while the study plays. + const at = await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const id = a.assembly!.doc.components.find((c) => c.name === 'Large<1>')!.id; + const f = a.faces.find((x) => x.name === `${id}#E1:cap1`)!; + return a.viewport.project([f.center[0] + 12, f.center[1] + 12, f.center[2]]); + }); + const box = (await page.locator('canvas.gl').boundingBox())!; + await page.mouse.move(box.x + at[0], box.y + at[1]); + await page.mouse.down(); + await page.mouse.move(box.x + at[0] + 30, box.y + at[1] - 30, { steps: 5 }); + await expect(pm.getByRole('button', { name: 'Play', exact: true })).toBeVisible(); + // (Playback no longer moves the gears under the drag.) + const clock = await pm.locator('.kin-clock').innerText(); + await page.waitForTimeout(300); + await expect(pm.locator('.kin-clock')).toHaveText(clock); + await page.mouse.move(box.x + at[0] + 40, box.y + at[1] - 70, { steps: 5 }); + await page.mouse.up(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.undoLabel)).toBe('Move component'); + await expect(pm.getByRole('status').filter({ hasText: 'The results are out of date' })).toBeVisible(); + await expect(pm.getByRole('button', { name: /^(Play|Pause)$/ })).toHaveCount(0); + // The components are shown where the drag left them, not at a frame of the old motion. + const shown = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const id = m.doc.components.find((c) => c.name === 'Large<1>')!.id; + return [m.shownPlacement(id)!.q, m.solved.get(id)!.q]; + }); + for (let i = 0; i < 4; i++) expect(shown[0][i]).toBeCloseTo(shown[1][i], 9); + // Calculated again from there, it plays. + await pm.getByRole('button', { name: 'Calculate', exact: true }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From d79f163e1053dcfc0309819a286b1993b693ec52 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:26:26 -0700 Subject: [PATCH 067/116] Parametric: a motion study plots a slider's travel --- .../src/app/assembly/motion-panel.ts | 2 +- .../tests/e2e/assembly-kinematics.spec.ts | 35 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index b3c0e1c484..2093f466af 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -313,7 +313,7 @@ export class MotionStudyPanel extends PropertyPanel { /** The mates a result can be plotted for (those that measure something). */ private measurable(): SolverMate[] { const { mates } = this.mode.solverInput(); - return mates.filter((m) => m.type === 'distance' || m.type === 'angle' || (m.type === 'hinge' && m.rel) || m.type === 'slot'); + return mates.filter((m) => m.type === 'distance' || m.type === 'angle' || ((m.type === 'hinge' || m.type === 'slider') && m.rel) || m.type === 'slot'); } private resultsSection(res: MotionResult): HTMLElement { diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 728dc56197..a47a3eb9e8 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -685,3 +685,38 @@ test('the Motion Study panel: dragging a component while it plays stops the play await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('a motion study plots how far a slider travels', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR]], ['Plate', 'Bar']); + await built(page, ['Plate<1>', 'Bar<1>']); + const pm = page.locator('.pm'); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap0' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + // A linear motor on the slider at 10 mm/s for 2 s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Slider1 (Slider)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('2'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 61 frames' })).toBeVisible(); + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Mate: Slider1' }); + await expect(pm.getByRole('img', { name: /^Plot of Slider1 value \(mm\)/ })).toHaveAttribute('aria-label', /from -?0 to 20$|from -20 to -?0$/); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Rate of change' }); + await expect(pm.getByRole('img', { name: /^Plot of Slider1 rate of change \(mm\/s\)/ })).toHaveAttribute('aria-label', /from (-10 to -10|10 to 10)$/); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From e3c7cfcb2325e411a5825697191471d46d0cd6a2 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:28:21 -0700 Subject: [PATCH 068/116] Parametric: motion study plots read 0 for rounding noise and their value labels fit beside the plot --- .../src/app/assembly/motion-panel.ts | 14 +++++---- .../tests/e2e/assembly-kinematics.spec.ts | 30 +++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index 2093f466af..cb3a343ec3 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -417,8 +417,10 @@ export class MotionStudyPanel extends PropertyPanel { let min = Infinity, max = -Infinity; for (const v of s.values) { if (v < min) min = v; if (v > max) max = v; } if (!(min <= max)) min = max = 0; + // Differences smaller than this are rounding (a velocity or acceleration of a constant motion reads 1e-11, not 0). + const eps = 1e-6 * Math.max(1, Math.abs(min), Math.abs(max)); // A constant is drawn across the middle. - const flat = !(max - min > 1e-9 * Math.max(1, Math.abs(max))); + const flat = !(max - min > eps); const lo = flat ? min - 1 : min, hi = flat ? max + 1 : max; const y = (v: number) => PLOT.top + (1 - (v - lo) / (hi - lo)) * (PLOT.h - PLOT.top - PLOT.bottom); const pts = plotPoints(res.times, s.values, end).map((i) => `${plotX(res.times[i], end).toFixed(1)},${y(s.values[i]).toFixed(1)}`).join(' '); @@ -430,14 +432,15 @@ export class MotionStudyPanel extends PropertyPanel { return e; }; const fmtN = (v: number) => (Math.abs(v) >= 1000 || (Math.abs(v) < 0.01 && v !== 0) ? v.toExponential(2) : String(Math.round(v * 100) / 100)); - const svg = el('svg', { viewBox: `0 0 ${PLOT.w} ${PLOT.h}`, class: 'kin-plot', role: 'img', 'aria-label': `Plot of ${s.name} (${s.unit}) against time, from ${fmtN(min)} to ${fmtN(max)}` }); + const fmtV = (v: number) => (Math.abs(v) < eps ? '0' : fmtN(v)); + const svg = el('svg', { viewBox: `0 0 ${PLOT.w} ${PLOT.h}`, class: 'kin-plot', role: 'img', 'aria-label': `Plot of ${s.name} (${s.unit}) against time, from ${fmtV(min)} to ${fmtV(max)}` }); const x0 = PLOT.left, x1 = PLOT.w - PLOT.right, yb = PLOT.h - PLOT.bottom; svg.append( el('rect', { x: x0, y: PLOT.top, width: x1 - x0, height: yb - PLOT.top, class: 'kin-plot-frame' }), ...(lo < 0 && hi > 0 ? [el('line', { x1: x0, x2: x1, y1: y(0), y2: y(0), class: 'kin-plot-zero' })] : []), el('polyline', { points: pts, class: 'kin-plot-line' }), - el('text', { x: x0 - 4, y: flat ? y(max) + 3 : PLOT.top + 4, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtN(flat ? max : hi)), - ...(flat ? [] : [el('text', { x: x0 - 4, y: yb, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtN(lo))]), + el('text', { x: x0 - 4, y: flat ? y(max) + 3 : PLOT.top + 4, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtV(flat ? max : hi)), + ...(flat ? [] : [el('text', { x: x0 - 4, y: yb, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtV(lo))]), el('text', { x: x0, y: PLOT.h - 4, class: 'kin-plot-text' }, '0 s'), el('text', { x: x1, y: PLOT.h - 4, 'text-anchor': 'end', class: 'kin-plot-text' }, `${fmtN(end)} s`), ); @@ -650,7 +653,8 @@ const MOTOR_FIRST = '.kin-motor-form .sec-body :is(button, select, input):not([d /** The most frames checked for interference (each is a boolean check of every pair in the worker). */ const INTERFERENCE_FRAMES = 40; -const PLOT = { w: 280, h: 150, left: 44, right: 8, top: 8, bottom: 18 }; +/** (The left margin fits a value label of 8 characters, as -1.23e-3.) */ +const PLOT = { w: 280, h: 150, left: 50, right: 8, top: 8, bottom: 18 }; const plotX = (t: number, end: number) => PLOT.left + (t / Math.max(end, 1e-9)) * (PLOT.w - PLOT.left - PLOT.right); /** diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index a47a3eb9e8..7f74e0bf65 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -720,3 +720,33 @@ test('a motion study plots how far a slider travels', async ({ page }) => { await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('motion study plots label their values within the plot, without rounding noise', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + const labels = () => pm.locator('.kin-plot text').evaluateAll((ts) => ts.map((t) => ({ text: t.textContent, x: (t as SVGTextElement).getBBox().x }))); + // The small gear turns about its own origin: that point does not move. + const plot = pm.getByRole('img', { name: /^Plot of Small<1> linear displacement/ }); + await expect(plot).toHaveAttribute('aria-label', /from 0 to 0$/); + for (const l of await labels()) expect(l.x, l.text ?? '').toBeGreaterThanOrEqual(0); + // Every label of a small value fits too. + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Component: Large<1>' }); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular acceleration' }); + await expect(pm.getByRole('img', { name: /^Plot of Large<1> angular acceleration/ })).toHaveAttribute('aria-label', /from 0 to 0$/); + for (const l of await labels()) expect(l.x, l.text ?? '').toBeGreaterThanOrEqual(0); + // The longest label (8 characters) fits too. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const svg = a.panel!.el.querySelector('.kin-plot text')!; + svg.textContent = '-1.23e-3'; + }); + for (const l of await labels()) expect(l.x, l.text ?? '').toBeGreaterThanOrEqual(0); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From 20e4aa08fb3fe1fde4c43bf3ad97e59df341ca66 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:29:02 -0700 Subject: [PATCH 069/116] Parametric: the motion study time slider reads out the time to screen readers --- .../src/app/assembly/motion-panel.ts | 2 ++ .../tests/e2e/assembly-kinematics.spec.ts | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index cb3a343ec3..16b926899d 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -301,6 +301,8 @@ export class MotionStudyPanel extends PropertyPanel { const end = res.times[res.times.length - 1]; if (this.slider && document.activeElement !== this.slider) this.slider.value = String(Math.round((t / Math.max(end, 1e-9)) * 1000)); if (this.clock) this.clock.textContent = `${t.toFixed(2)} s / ${end.toFixed(2)} s`; + // (Read out as the time, not as the slider's 0 to 1000.) + this.slider?.setAttribute('aria-valuetext', `${t.toFixed(2)} s of ${end.toFixed(2)} s`); if (this.plotCursor) { const x = plotX(res.times[i], end); this.plotCursor.setAttribute('x1', String(x)); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 7f74e0bf65..3efb806c1a 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -750,3 +750,25 @@ test('motion study plots label their values within the plot, without rounding no await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('the motion study time slider works from the keyboard and reads out the time', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + await pm.getByRole('button', { name: 'To the start' }).click(); + const slider = pm.getByRole('slider', { name: 'Study time' }); + await expect(slider).toHaveAttribute('aria-valuetext', '0.00 s of 5.00 s'); + await slider.focus(); + await page.keyboard.press('End'); + await expect(pm.locator('.kin-clock')).toHaveText('5.00 s / 5.00 s'); + await expect(slider).toHaveAttribute('aria-valuetext', '5.00 s of 5.00 s'); + await page.keyboard.press('PageDown'); + await expect(slider).toHaveAttribute('aria-valuetext', '4.50 s of 5.00 s'); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); From 31f1fb8a27033ec02a0ffe3d90ce4bbbe273599b Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:30:18 -0700 Subject: [PATCH 070/116] Parametric: an interference check over a motion has a Cancel button --- .../src/app/assembly/motion-panel.ts | 25 ++++++++++++---- .../tests/e2e/assembly-kinematics.spec.ts | 30 +++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index 16b926899d..fc15de560c 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -113,9 +113,12 @@ export class MotionStudyPanel extends PropertyPanel { const items: HTMLElement[] = []; if (this.checking) { this.bar = h('progress', { max: '1', value: '0', 'aria-label': 'Interference check progress' }) as HTMLProgressElement; - items.push(h('p', { class: 'field-label', role: 'status' }, 'Checking frames for interference...'), this.bar); + const cancel = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); + // (The check stops after the frame it is on, and puts the scene back.) + cancel.addEventListener('click', () => { this.runs++; this.checking = false; this.refreshTo('.kin-check'); }); + items.push(h('p', { class: 'field-label', role: 'status' }, 'Checking frames for interference...'), this.bar, cancel); } else { - const run = h('button', { class: 'btn small', type: 'button' }, icon('interference', 14), 'Check Interference'); + const run = h('button', { class: 'btn small kin-check', type: 'button' }, icon('interference', 14), 'Check Interference'); run.addEventListener('click', () => void this.checkInterference(res)); items.push(h('p', { class: 'field-label' }, `Finds components that overlap in ${Math.min(INTERFERENCE_FRAMES, res.frames.length)} frames spread over the motion.`), run); const c = this.clashes?.result === res ? this.clashes.list : null; @@ -135,18 +138,30 @@ export class MotionStudyPanel extends PropertyPanel { return section('Interference', items, { collapsed: false }); } + /** Settles when the last interference check has stopped using the worker's scene (a cancelled one finishes its frame). */ + private checked: Promise = Promise.resolve(); + private checkRun = 0; + private async checkInterference(res: MotionResult) { const run = ++this.runs; + this.checkRun = run; this.play(false); this.checking = true; this.app.refreshPanel(); let list: { time: number; pairs: [Id, Id][] }[] | null = null; + const before = this.checked; + let done = () => {}; + this.checked = new Promise((resolve) => { done = resolve; }); try { - list = await this.mode.motionInterference(res, INTERFERENCE_FRAMES, (f) => { if (this.bar) this.bar.value = f; }, () => run !== this.runs || this.disposed); + await before; + if (run === this.runs && !this.disposed) list = await this.mode.motionInterference(res, INTERFERENCE_FRAMES, (f) => { if (this.bar) this.bar.value = f; }, () => run !== this.runs || this.disposed); } catch (e) { - if (!this.disposed) this.error = (e as Error).message; + if (!this.disposed && run === this.runs) this.error = (e as Error).message; + } finally { + done(); } - this.checking = false; + // (Unless a newer check started after this one was cancelled.) + if (this.checkRun === run) this.checking = false; if (this.disposed || run !== this.runs) return; if (list) this.clashes = { result: res, list }; this.app.refreshPanel(); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 3efb806c1a..de88b2c249 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -772,3 +772,33 @@ test('the motion study time slider works from the keyboard and reads out the tim await pm.getByRole('button', { name: 'Cancel' }).click(); expect(errors).toEqual([]); }); + +test('an interference check over a motion can be cancelled, and checked again', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + // Each frame's check waits a while in the worker, so the check is still running when Cancel is pressed. + await page.evaluate(() => { + const k = (window as unknown as { __parametric: A }).__parametric.kernel as unknown as { assembly: (op: { op: string }) => Promise }; + const real = k.assembly.bind(k); + k.assembly = async (op) => { const r = await real(op); if (op.op === 'interference') await new Promise((done) => setTimeout(done, 100)); return r; }; + }); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + const section = pm.locator('.pm-section').filter({ has: page.getByRole('progressbar', { name: 'Interference check progress' }) }); + await section.getByRole('button', { name: 'Cancel' }).click(); + await expect(pm.getByRole('progressbar', { name: 'Interference check progress' })).toHaveCount(0); + await expect(pm.getByRole('button', { name: 'Check Interference' })).toBeFocused(); + await expect(pm.getByText('No interference in the frames checked.')).toHaveCount(0); + // The panel stays open, plays, and checks again to the end. + await expect(pm.getByRole('heading', { name: 'Motion Study' })).toBeVisible(); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(pm.getByText('No interference in the frames checked.')).toBeVisible({ timeout: 30_000 }); + await pm.getByRole('button', { name: 'Play', exact: true }).click(); + await expect(pm.getByRole('button', { name: 'Pause' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From eba57d8be42e98c1dbd1865f81eb56aadd76ba62 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:33:10 -0700 Subject: [PATCH 071/116] Parametric: a motion study takes a picked vertex as a point of its own component, not of the one whose face centre is nearest --- .../src/app/assembly/motion-panel.ts | 11 +----- .../tests/e2e/assembly-kinematics.spec.ts | 37 +++++++++++++++++++ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index fc15de560c..acab160c1d 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -378,7 +378,7 @@ export class MotionStudyPanel extends PropertyPanel { private pointOf(it: SelItem, comp: Id): SelBoxItem | null { const mode = this.mode; let world: Vec3 | null = null, owner: Id | undefined, label = ''; - if (it.kind === 'vertex') { world = it.p; label = 'Vertex'; owner = this.nearestComp(it.p); } + if (it.kind === 'vertex') { world = it.p; label = 'Vertex'; owner = mode.vertexOf(it.p)?.comp; } if (it.kind === 'face') { const f = this.app.faces[it.index]; owner = mode.faceComponent(it.index)?.id; world = f?.center ?? null; label = `Face (${f?.type}) centre`; } if (it.kind === 'edge') { const e = this.app.edges[it.index]; owner = mode.edgeComponent(it.index)?.id; world = e ? e.center ?? e.mid : null; label = `Edge (${e?.type}) ${e?.center ? 'centre' : 'midpoint'}`; } const pl = mode.shownPlacement(comp); @@ -387,15 +387,6 @@ export class MotionStudyPanel extends PropertyPanel { return { item: it, data: { comp, local, label }, label }; } - private nearestComp(p: Vec3): Id | undefined { - let best: Id | undefined, d = Infinity; - this.app.faces.forEach((f, i) => { - const x = len([f.center[0] - p[0], f.center[1] - p[1], f.center[2] - p[2]]); - if (x < d) { d = x; best = this.mode.faceComponent(i)?.id; } - }); - return best; - } - /** The plotted series: values per frame, with its name and unit. */ private series(res: MotionResult): { values: number[]; name: string; unit: string } | null { const u = UNIT_SYSTEMS[this.mode.doc.units]; diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index de88b2c249..729450d4c1 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -802,3 +802,40 @@ test('an interference check over a motion can be cancelled, and checked again', await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('a motion study plots a picked vertex of the component even where another component touches it', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Small', disc(10)]], ['Plate', 'Bar', 'Small']); + await built(page, ['Plate<1>', 'Bar<1>', 'Small<1>']); + const pm = page.locator('.pm'); + // The disc's face centre sits on the bar's corner (both at the same place, 50 mm in front of the plate). + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + m.commit('Place', (d) => { for (const c of d.components) if (!c.fixed) c.placement = { p: [0, 0, 50], q: [0, 0, 0, 1] }; }); + }); + await page.waitForFunction(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + return m.doc.components.every((c) => c.fixed || m.shownPlacement(c.id)!.p[2] === 50); + }); + // A linear motor moving the bar along x at 10 mm/s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('group', { name: 'Motor direction' }).click(); + await pick(page, { comp: 'Bar<1>', edge: 'x' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + await pm.getByRole('button', { name: 'To the start' }).click(); + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Component: Bar<1>' }); + // The bar's corner vertex (where the disc's face centre is) is a point of the bar. + await pm.getByRole('group', { name: 'Point (optional)' }).click(); + await page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.panel!.onPick({ kind: 'vertex', p: [0, 0, 50] }, false); }); + await expect(pm.getByRole('group', { name: 'Point (optional)' })).toContainText('Vertex'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From fe3ce5a59a3eedb35f92795b1b86b42fe6838c62 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:34:17 -0700 Subject: [PATCH 072/116] Parametric: Calculate refuses a motion study duration or frame rate it could not take instead of using the last good one --- .../src/app/assembly/motion-panel.ts | 3 +++ .../tests/e2e/assembly-kinematics.spec.ts | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index acab160c1d..0c4f7a0c6b 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -247,6 +247,9 @@ export class MotionStudyPanel extends PropertyPanel { } private async calculate() { + // Not with a value it could not take (a duration of 0 would be calculated with the last good one). + if (!this.checkFields()) return; + this.setMessage(null); const run = ++this.runs; this.play(false); this.computing = true; diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 729450d4c1..d8b81cb64c 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -839,3 +839,26 @@ test('a motion study plots a picked vertex of the component even where another c await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('a motion study is not calculated with a duration it refused', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + const duration = pm.getByRole('spinbutton', { name: 'Duration (s)' }); + await duration.fill('0'); + await duration.press('Enter'); + await expect(duration).toHaveAttribute('aria-invalid', 'true'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert')).toContainText('Duration (s): Between 0.1 and 3600'); + await expect(duration).toBeFocused(); + await expect(pm.getByText(/Calculated \d+ frames/)).toHaveCount(0); + await duration.fill('2'); + await duration.press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 61 frames' })).toBeVisible(); + await expect(pm.getByRole('alert')).toHaveCount(0); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From 03c0bfc22d19dd6d346a27f324499231418b978d Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:38:56 -0700 Subject: [PATCH 073/116] Parametric: Flip Mate Alignment on a hinge turns the component over instead of making the hinge over defined --- src/parametric/src/app/assembly/index.ts | 2 +- src/parametric/src/app/assembly/mode.ts | 27 ++++++++- .../tests/e2e/assembly-kinematics.spec.ts | 58 +++++++++++++++++++ 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts index 31b96e69a2..4e1f171944 100644 --- a/src/parametric/src/app/assembly/index.ts +++ b/src/parametric/src/app/assembly/index.ts @@ -302,7 +302,7 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { return [ { label: 'Edit Mate', icon: 'edit', run: () => m.edit(mate.id) }, { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(mate.id) }, - ...(aligns ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.commit('Flip alignment', (x) => { for (const y of x.mates) if (y.id === mate.id) y.aligned = !y.aligned; }) } as MenuItem] : []), + ...(aligns ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.flipAlignment(mate.id) } as MenuItem] : []), ...(mate.type === 'cam' ? [{ label: 'Flip Follower Face', icon: 'reset', run: () => m.commit('Flip follower', (x) => { for (const y of x.mates) if (y.id === mate.id) y.flip = y.flip ? undefined : true; }) } as MenuItem] : []), ...(reverses ? [{ label: 'Reverse Direction', icon: 'reset', run: () => m.commit('Reverse direction', (x) => { for (const y of x.mates) if (y.id === mate.id) y.reverse = y.reverse ? undefined : true; }) } as MenuItem] : []), { label: mate.suppressed ? 'Unsuppress' : 'Suppress', icon: mate.suppressed ? 'eye' : 'eyeOff', run: () => m.commit(mate.suppressed ? 'Unsuppress' : 'Suppress', (x) => { for (const y of x.mates) if (ids.includes(y.id)) y.suppressed = mate.suppressed ? undefined : true; }) }, diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index 4578fdb7d8..b6c347aa43 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -17,7 +17,7 @@ import { } from '../../model/assembly'; import { type ComposedModel, type PartGeometry, camProfileOf, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; import { - type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, + type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, relativePlacement, } from '../../assembly/solver'; import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, framesSpread, profileOf, sameMotionGroups } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; @@ -604,6 +604,31 @@ export class AssemblyMode { }, false); } + /** + * Flip Mate Alignment. A hinge's touching faces flip with its axis (the + * component turns over; flipped alone, the axis could not hold with the + * faces), and its angle limits then count from where it turned over to. + */ + flipAlignment(id: Id) { + this.commit('Flip alignment', (d) => { + const m = d.mates.find((x) => x.id === id); + if (!m) return; + m.aligned = !m.aligned; + if (m.type !== 'hinge') return; + m.aligned2 = !m.aligned2; + if (!m.limit || !m.rel || !('comp' in m.a) || !('comp' in m.b)) return; + const limit = m.limit; + delete m.limit; + // (The components are put where it turned over to, so the solve with the limit starts there, at 0°.) + const pl = this.solveDoc(d).placements; + for (const c of d.components) { const p = pl.get(c.id); if (p && !c.fixed && !c.suppressed) c.placement = p; } + const at = (c: Id) => pl.get(c) ?? d.components.find((x) => x.id === c)?.placement; + const pa = at(m.a.comp), pb = at(m.b.comp); + if (pa && pb) m.rel = relativePlacement(pa, pb); + m.limit = limit; + }); + } + study(id: Id): MotionStudy | undefined { return this.doc.studies?.find((s) => s.id === id); } diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index d8b81cb64c..5c0a31ca36 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -862,3 +862,61 @@ test('a motion study is not calculated with a duration it refused', async ({ pag await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('Flip Mate Alignment turns a hinged component over instead of making the hinge over defined', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + const pm = page.locator('.pm'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + // Hinge1 free, Hinge2 limited to ±45°. + for (const [gear, hole] of [['Small<1>', 'E1:side:h1'], ['Large<1>', 'E1:side:h2']]) { + await select(page, [{ comp: gear, face: 'E1:side:k' }, { comp: 'Plate<1>', face: hole }]); + await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: gear, face: 'E1:cap0' }); + if (gear === 'Large<1>') await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + } + const capZ = (name: string) => page.evaluate((name) => { + // Where the disc's back face (z = 0 in the part) is: on the plate's front (z = 10), or turned over into the plate. + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const pl = m.solved.get(m.doc.components.find((c) => c.name === name)!.id)!; + const [x, y] = pl.q; + return { z: pl.p[2], nz: 1 - 2 * (x * x + y * y) }; + }, name); + for (const name of ['Hinge1', 'Hinge2']) { + const row = tree.getByRole('treeitem', { name: new RegExp(`^${name}`) }); + await row.click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Flip Mate Alignment' }).click(); + await expect(row).not.toHaveAttribute('aria-description', /Error|Over/); + await expect(page.locator('.statusbar')).not.toContainText('Over Defined'); + } + // Both discs turned over: their back faces now face the other way. + expect((await capZ('Small<1>')).nz).toBeCloseTo(-1, 6); + expect((await capZ('Large<1>')).nz).toBeCloseTo(-1, 6); + // The limited hinge still turns 45° either way from where it turned over to, and no further. + const turned = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const id = m.doc.components.find((c) => c.name === 'Large<1>')!.id; + const mul = (a: number[], b: number[]) => [a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1], a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0], a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3], a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]]; + const q0 = m.solved.get(id)!.q; + return [1, -1].map((dir) => { + let pl = new Map(m.solved); + for (let k = 1; k <= 8; k++) pl = m.dragSolve({ kind: 'rotate', body: id, q: mul([0, 0, Math.sin((dir * k * 10 * Math.PI) / 360), Math.cos((k * 10 * Math.PI) / 360)], q0) as [number, number, number, number] }, pl); + const d = mul(pl.get(id)!.q, [-q0[0], -q0[1], -q0[2], q0[3]]); + return (2 * Math.acos(Math.min(1, Math.abs(d[3]))) * 180) / Math.PI; + }); + }); + expect(turned[0]).toBeCloseTo(45, 3); + expect(turned[1]).toBeCloseTo(45, 3); + // One undo step each. + await page.keyboard.press('Meta+z'); + await page.keyboard.press('Meta+z'); + expect((await capZ('Small<1>')).nz).toBeCloseTo(1, 6); + expect((await capZ('Large<1>')).nz).toBeCloseTo(1, 6); + expect(errors).toEqual([]); +}); From f6e52a79b4c75283c1d2dbed106bea8cfadbeb09 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:42:57 -0700 Subject: [PATCH 074/116] Parametric: switching a rack and pinion between pitch diameter and travel per turn converts a value given as an equation too --- src/parametric/src/app/assembly/panels.ts | 5 ++++- .../tests/e2e/assembly-kinematics.spec.ts | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts index b1d5fd7673..8eda3a90a6 100644 --- a/src/parametric/src/app/assembly/panels.ts +++ b/src/parametric/src/app/assembly/panels.ts @@ -491,7 +491,10 @@ export class MatePanel extends PropertyPanel { const per = this.by === 'revolution'; out.push(h('div', { class: 'field-label' }, 'Rack travel from'), segmented('Rack travel from', per ? 'revolution' : 'diameter', [{ value: 'diameter', label: 'Pitch diameter' }, { value: 'revolution', label: 'Travel per turn' }], (v) => { this.by = v === 'revolution' ? 'revolution' : null; - if (typeof this.value === 'number') this.value = Math.round((v === 'revolution' ? this.value * Math.PI : this.value / Math.PI) * 1000) / 1000; + // (An equation is converted too, as its value: a pitch diameter is not a travel per turn.) + let now: number | null = null; + try { now = this.mode.app.store.evalParam(this.value, 'length'); } catch { /* left as it is: the field shows its error */ } + if (now !== null) this.value = Math.round((v === 'revolution' ? now * Math.PI : now / Math.PI) * 1000) / 1000; this.mode.app.refreshPanel(); this.update(); })); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 5c0a31ca36..cec485c1bc 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -920,3 +920,21 @@ test('Flip Mate Alignment turns a hinged component over instead of making the hi expect((await capZ('Large<1>')).nz).toBeCloseTo(1, 6); expect(errors).toEqual([]); }); + +test('a rack and pinion pitch diameter given as an equation turns into the travel per turn', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Small', disc(10)]], ['Plate', 'Bar', 'Small']); + await built(page, ['Plate<1>', 'Bar<1>', 'Small<1>']); + await select(page, [{ comp: 'Bar<1>', edge: 'x' }, { comp: 'Small<1>', face: 'E1:side:k' }]); + const pm = await openMate(page, 'rackPinion'); + const diameter = pm.getByRole('textbox', { name: 'Pinion pitch diameter' }); + await diameter.fill('=10*2'); + await diameter.press('Enter'); + await pm.getByRole('group', { name: 'Rack travel from' }).getByRole('button', { name: 'Travel per turn' }).click(); + await expect(pm.getByRole('textbox', { name: 'Rack travel per turn of the pinion' })).toHaveValue('62.832'); + await pm.getByRole('group', { name: 'Rack travel from' }).getByRole('button', { name: 'Pitch diameter' }).click(); + await expect(diameter).toHaveValue('20'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From 38a4c85b3001161a171259690ceec37e35f57650 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:43:35 -0700 Subject: [PATCH 075/116] Parametric: a motion study does not start playing under a motor being set up while it calculated --- .../src/app/assembly/motion-panel.ts | 3 +- .../tests/e2e/assembly-kinematics.spec.ts | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts index 0c4f7a0c6b..5d7c134d2b 100644 --- a/src/parametric/src/app/assembly/motion-panel.ts +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -263,7 +263,8 @@ export class MotionStudyPanel extends PropertyPanel { if (typeof r === 'string') this.error = r; this.t = 0; this.app.refreshPanel(); - if (r && typeof r !== 'string') { this.showAt(0); if (r.frames.length > 1 && !r.stop) this.play(true); } + // (Not while a motor added meanwhile is being set up: its axis is picked on components that stand still.) + if (r && typeof r !== 'string') { this.showAt(0); if (r.frames.length > 1 && !r.stop && !this.motor) this.play(true); } } // ---------- playback ---------- diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index cec485c1bc..2a594f03f0 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -938,3 +938,32 @@ test('a rack and pinion pitch diameter given as an equation turns into the trave await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('a motion study does not start playing while a motor added during the calculation is set up', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('60'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('spinbutton', { name: 'Frames per second' }).fill('240'); + await pm.getByRole('spinbutton', { name: 'Frames per second' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('progressbar', { name: 'Calculation progress' })).toBeVisible(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + const state = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const p = a.panel as unknown as { computing: boolean; playing: boolean }; + return { computing: p.computing, playing: p.playing }; + }); + await expect.poll(async () => (await state()).computing, { timeout: 60_000 }).toBe(false); + await page.waitForTimeout(300); + expect((await state()).playing).toBe(false); + // Back from the motor, the results are there to play. + await pm.getByRole('button', { name: 'Cancel' }).last().click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 14401 frames' })).toBeVisible(); + await expect(pm.getByRole('button', { name: 'Play', exact: true })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From 06c52e0b7581c3c1cb3e1a5756f6097d1185a6a2 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:44:38 -0700 Subject: [PATCH 076/116] Parametric: a motion study whose motors are all suppressed says so instead of asking for a motor --- src/parametric/src/app/assembly/mode.ts | 2 +- .../tests/e2e/assembly-kinematics.spec.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index b6c347aa43..5a9ffc858a 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -734,7 +734,7 @@ export class AssemblyMode { /** The solver input of a study, or why it cannot run. Components start where the mates put them now. */ motionSetup(st: MotionStudy): MotionSetup | string { const motors = st.motors.filter((m) => !m.suppressed); - if (!motors.length) return 'Add a motor to drive the mechanism.'; + if (!motors.length) return st.motors.length ? 'Every motor is suppressed: unsuppress one to drive the mechanism.' : 'Add a motor to drive the mechanism.'; const { bodies, mates } = this.solverInput(); const a = this.analysis; const held = mates.filter((m) => !a?.conflicts.has(m.id) && !a?.invalid.has(m.id)); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 2a594f03f0..537445d7d8 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -967,3 +967,19 @@ test('a motion study does not start playing while a motor added during the calcu await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('a motion study whose motors are all suppressed says so when calculated', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge1 (Hinge)' }); + await pm.getByRole('checkbox', { name: 'Suppressed' }).check(); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await expect(pm.getByRole('listitem')).toContainText('RotaryMotor1 (suppressed)'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert')).toHaveText('Every motor is suppressed: unsuppress one to drive the mechanism.'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From 12084f106732ff720becd46828be257489e9a876 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:45:22 -0700 Subject: [PATCH 077/116] Parametric: the Mate panel gives a hinge or slider its own default limits when the type changes, not the last type's in other units --- src/parametric/src/app/assembly/panels.ts | 2 ++ .../tests/e2e/assembly-kinematics.spec.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts index 8eda3a90a6..576e6ec68f 100644 --- a/src/parametric/src/app/assembly/panels.ts +++ b/src/parametric/src/app/assembly/panels.ts @@ -414,6 +414,8 @@ export class MatePanel extends PropertyPanel { if (this.by && !((now === 'gear' && this.by === 'ratio') || (now === 'rackPinion' && this.by === 'revolution') || (now === 'universal' && this.by === 'point'))) this.by = null; if (now === 'universal' && !this.existing) this.value = 0; if (this.limitOn && v !== 'distance' && v !== 'angle' && v !== 'hinge' && v !== 'slider') this.limitOn = false; + // (Limits in degrees are not limits in millimetres: a hinge's or slider's start from its defaults.) + if (this.limitOn && (now === 'hinge' || now === 'slider') && was !== now) this.limitAround(0); this.pickDefaults(); this.mode.app.refreshPanel(); this.update(); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 537445d7d8..34ae0a5cbe 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -983,3 +983,22 @@ test('a motion study whose motors are all suppressed says so when calculated', a await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('the Mate panel does not carry a hinge\'s angle limits over to a slider as lengths', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR]], ['Plate', 'Bar']); + await built(page, ['Plate<1>', 'Bar<1>']); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + const pm = await openMate(page, 'hinge'); + await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('45'); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await expect(pm.getByRole('checkbox', { name: /Limit the travel/ })).toBeChecked(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('25'); + await expect(pm.getByRole('textbox', { name: 'Minimum' })).toHaveValue('-25'); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('hinge'); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('45'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); From c3eaf4fdfd1db3fcd6754f62b90fcd0fa3cc8415 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:47:45 -0700 Subject: [PATCH 078/116] Parametric: Flip Follower Face is offered only for a cam's flat follower face, where it does something --- src/parametric/src/app/assembly/index.ts | 3 ++- .../tests/e2e/assembly-kinematics.spec.ts | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts index 4e1f171944..cc5c835546 100644 --- a/src/parametric/src/app/assembly/index.ts +++ b/src/parametric/src/app/assembly/index.ts @@ -303,7 +303,8 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { { label: 'Edit Mate', icon: 'edit', run: () => m.edit(mate.id) }, { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(mate.id) }, ...(aligns ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.flipAlignment(mate.id) } as MenuItem] : []), - ...(mate.type === 'cam' ? [{ label: 'Flip Follower Face', icon: 'reset', run: () => m.commit('Flip follower', (x) => { for (const y of x.mates) if (y.id === mate.id) y.flip = y.flip ? undefined : true; }) } as MenuItem] : []), + // (Only a flat follower face has sides: a vertex or roller follower has nothing to flip.) + ...(mate.type === 'cam' && 'face' in mate.b && mate.b.face.sig.type === 'plane' ? [{ label: 'Flip Follower Face', icon: 'reset', run: () => m.commit('Flip follower', (x) => { for (const y of x.mates) if (y.id === mate.id) y.flip = y.flip ? undefined : true; }) } as MenuItem] : []), ...(reverses ? [{ label: 'Reverse Direction', icon: 'reset', run: () => m.commit('Reverse direction', (x) => { for (const y of x.mates) if (y.id === mate.id) y.reverse = y.reverse ? undefined : true; }) } as MenuItem] : []), { label: mate.suppressed ? 'Unsuppress' : 'Suppress', icon: mate.suppressed ? 'eye' : 'eyeOff', run: () => m.commit(mate.suppressed ? 'Unsuppress' : 'Suppress', (x) => { for (const y of x.mates) if (ids.includes(y.id)) y.suppressed = mate.suppressed ? undefined : true; }) }, sep, diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts index 34ae0a5cbe..23ce8a38bc 100644 --- a/src/parametric/tests/e2e/assembly-kinematics.spec.ts +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -1002,3 +1002,29 @@ test('the Mate panel does not carry a hinge\'s angle limits over to a slider as await pm.getByRole('button', { name: 'Cancel' }).first().click(); expect(errors).toEqual([]); }); + +test('a cam mate with a roller follower offers no Flip Follower Face', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Cam', CAM], ['Shaft', SHAFT], ['Bar', BAR]], ['Plate', 'Cam', 'Shaft', 'Bar']); + await built(page, ['Plate<1>', 'Cam<1>', 'Shaft<1>', 'Bar<1>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + // The shaft's round face rolls on the cam; the bar's flat face follows it too. + for (const follower of [{ comp: 'Shaft<1>', face: 'E1:side:k' }, { comp: 'Bar<1>', face: 'E1:side:rl0' }]) { + const pm = await openMate(page, 'cam'); + await pick(page, { comp: 'Cam<1>', face: 'E1:side:k' }); + await pm.getByRole('group', { name: 'Follower' }).click(); + await pick(page, follower); + await expect(pm.getByRole('group', { name: 'Follower' })).toContainText(follower.comp); + await pm.getByRole('button', { name: 'OK' }).click(); + } + await tree.getByRole('treeitem', { name: /^Cam1/ }).click({ button: 'right' }); + await expect(page.getByRole('menuitem', { name: 'Suppress' })).toBeVisible(); + await expect(page.getByRole('menuitem', { name: 'Flip Follower Face' })).toHaveCount(0); + await page.keyboard.press('Escape'); + await tree.getByRole('treeitem', { name: /^Cam2/ }).click({ button: 'right' }); + await expect(page.getByRole('menuitem', { name: 'Flip Follower Face' })).toBeVisible(); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); +}); From d8246088a5f7c2a5098cf676c4c0973968f42e69 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:43:36 -0700 Subject: [PATCH 079/116] Parametric: the analysis code loads again on the next try after it failed to load, with a plain message (and no unhandled errors from the design tree) --- src/parametric/src/app/fea/index.ts | 23 ++++++++++++++++------- src/parametric/tests/e2e/analysis.spec.ts | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/parametric/src/app/fea/index.ts b/src/parametric/src/app/fea/index.ts index bef0edc59f..9dc0d58a55 100644 --- a/src/parametric/src/app/fea/index.ts +++ b/src/parametric/src/app/fea/index.ts @@ -38,12 +38,21 @@ let workspace: FeaWorkspace | null = null; /** The analysis workspace, loaded (with the panels and the worker) the first time it is needed. */ export async function feaWorkspace(app: App): Promise { - loading ??= import('./workspace'); + // A failed load (offline, an update replaced the files) is tried again by the next command. + loading ??= import('./workspace').catch((e: unknown) => { loading = null; throw e; }); const m = await loading; workspace ??= new m.FeaWorkspace(app); return workspace; } +/** Runs fn with the workspace, loading it first; a failure to load or to start is told in a toast. */ +export function withWorkspace(app: App, fn: (ws: FeaWorkspace) => unknown) { + void feaWorkspace(app).then( + (ws) => Promise.resolve().then(() => fn(ws)).catch((e) => toast({ kind: 'error', message: `The analysis could not start: ${(e as Error).message}` })), + () => toast({ kind: 'error', message: 'The analysis could not be loaded. Check your connection and try again.' }), + ); +} + /** The workspace if it has been loaded (the design tree shows results only then). */ export function loadedFeaWorkspace(): FeaWorkspace | null { return workspace; @@ -67,7 +76,7 @@ export function installFea(app: App, hooks: AppHooks) { const partOnly = () => !app.assembly && !app.inDrawing; const withWs = (fn: (ws: FeaWorkspace) => void | Promise) => () => { if (!partOnly()) return; - void feaWorkspace(app).then(fn).catch((e) => toast({ kind: 'error', message: `The analysis could not start: ${(e as Error).message}` })); + withWorkspace(app, fn); }; const hasStudy = () => partOnly() && !!app.store.doc.study; const fixture = (type: FixtureType, desc: string, keywords: string): Command => ({ @@ -114,9 +123,9 @@ export function installFea(app: App, hooks: AppHooks) { const at = hooks.ribbonTabs.findIndex((t) => t.id === 'drawing'); hooks.ribbonTabs.splice(at < 0 ? hooks.ribbonTabs.length : at, 0, tab); // A part opened with a study shows its symbols when the tab is chosen (the workspace loads then). - app.ribbonTabListeners.push((id) => { if (id === 'analysis' && app.store.doc.study && partOnly()) void feaWorkspace(app).then((ws) => ws.redraw()); }); + app.ribbonTabListeners.push((id) => { if (id === 'analysis' && app.store.doc.study && partOnly()) withWorkspace(app, (ws) => ws.redraw()); }); // ...and when it is opened while the tab is shown (the symbols follow its first build). - app.store.on((reason) => { if (reason === 'load' && app.ribbonTabId === 'analysis' && app.store.doc.study && partOnly()) void feaWorkspace(app).then((ws) => ws.redraw()); }); + app.store.on((reason) => { if (reason === 'load' && app.ribbonTabId === 'analysis' && app.store.doc.study && partOnly()) withWorkspace(app, (ws) => ws.redraw()); }); } // ---------- design tree ---------- @@ -125,7 +134,7 @@ export function feaTreeRows(app: App, expanded: (key: string) => boolean): CamRo const s: StaticStudy | null | undefined = app.store.doc.study; if (!s || app.assembly) return []; const ws = loadedFeaWorkspace(); - const run = (fn: (ws: FeaWorkspace) => void) => () => void feaWorkspace(app).then(fn); + const run = (fn: (ws: FeaWorkspace) => void) => () => withWorkspace(app, fn); const open = expanded('fea'); const state = ws?.state() ?? 'none'; const rows: CamRow[] = [{ @@ -140,13 +149,13 @@ export function feaTreeRows(app: App, expanded: (key: string) => boolean): CamRo for (const f of s.fixtures) { rows.push({ key: `fea:${f.id}`, label: f.name, icon: FIXTURE_ICONS[f.type], depth: 2, selected: ws?.focus === f.id, suppressed: !!f.suppressed, badge: missing(f.faces), - action: run((w) => w.focusItem(f.id)), open: run((w) => w.editItem(f.id)), menu: (x, y) => void feaWorkspace(app).then((w) => w.itemMenu(f.id, x, y)), + action: run((w) => w.focusItem(f.id)), open: run((w) => w.editItem(f.id)), menu: (x, y) => withWorkspace(app, (w) => w.itemMenu(f.id, x, y)), }); } for (const l of s.loads) { rows.push({ key: `fea:${l.id}`, label: l.name, icon: LOAD_ICONS[l.type], depth: 2, selected: ws?.focus === l.id, suppressed: !!l.suppressed, badge: l.type === 'gravity' ? undefined : missing(l.faces), - action: run((w) => w.focusItem(l.id)), open: run((w) => w.editItem(l.id)), menu: (x, y) => void feaWorkspace(app).then((w) => w.itemMenu(l.id, x, y)), + action: run((w) => w.focusItem(l.id)), open: run((w) => w.editItem(l.id)), menu: (x, y) => withWorkspace(app, (w) => w.itemMenu(l.id, x, y)), }); } const mesh = ws?.meshText() ?? ''; diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 2eef8c56cc..5adf26bce4 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -457,3 +457,18 @@ test('Run right after an edit that renumbers the faces loads the faces picked', await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); expect(errors).toEqual([]); }); + +test('the analysis loads on a later try when its code failed to load', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.route(/\/src\/app\/fea\/workspace\.ts/, (r) => r.abort()); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await page.locator('[data-cmd="fea:study"]').click(); + await expect(page.locator('.toast')).toContainText('The analysis could not be loaded. Check your connection and try again.'); + await page.unroute(/\/src\/app\/fea\/workspace\.ts/); + await page.locator('[data-cmd="fea:study"]').click(); + await expect(page.locator('.pm-head').getByText('Static Study')).toBeVisible(); + // The failed fetch is the only error. + expect(errors.filter((e) => !/workspace\.ts|ERR_FAILED/.test(e))).toEqual([]); +}); From 58ff34aee22bd061b9a0754a4ddd326e33320c89 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:44:16 -0700 Subject: [PATCH 080/116] Parametric: clicking Results in the design tree opens the results panel (with Run) instead of starting a solve, as CAM's rows do --- src/parametric/src/app/fea/index.ts | 3 ++- src/parametric/tests/e2e/analysis.spec.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/fea/index.ts b/src/parametric/src/app/fea/index.ts index 9dc0d58a55..10e3a2e7d2 100644 --- a/src/parametric/src/app/fea/index.ts +++ b/src/parametric/src/app/fea/index.ts @@ -167,7 +167,8 @@ export function feaTreeRows(app: App, expanded: (key: string) => boolean): CamRo key: 'fea:results', label: 'Results', icon: 'feaResults', depth: 2, selected: false, muted: state === 'none' ? ' (not run)' : state === 'busy' ? ' (running)' : '', badge: state === 'stale' ? { kind: 'warn', text: 'Out of date: the part or the study changed since it was run. Run it again.' } : state === 'error' ? { kind: 'error', text: ws?.errorText() ?? 'The study could not be solved' } : undefined, - action: run((w) => w.showResults()), open: run((w) => w.showResults()), menu: (x, y) => app.openCommandMenu(['fea:results', 'fea:run', 'fea:report'], x, y, 'Results menu'), + // Shows the results panel (with Run when there are none): a click in the tree does not start a solve. + action: run((w) => void w.openResults()), open: run((w) => void w.openResults()), menu: (x, y) => app.openCommandMenu(['fea:results', 'fea:run', 'fea:report'], x, y, 'Results menu'), }); return rows; } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 5adf26bce4..ea0951414d 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -472,3 +472,16 @@ test('the analysis loads on a later try when its code failed to load', async ({ // The failed fetch is the only error. expect(errors.filter((e) => !/workspace\.ts|ERR_FAILED/.test(e))).toEqual([]); }); + +test('clicking Results in the design tree shows the results panel without starting a solve', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + await page.getByRole('treeitem', { name: /^Results/ }).click(); + await expect(page.getByText('Run the study to see its results.')).toBeVisible(); + await expect(page.getByRole('progressbar')).toHaveCount(0); + await expect(page.locator('.statusbar .msg')).not.toContainText(/Preparing|Meshing|Solv/); + // Its Run button solves it. + await page.locator('.pm-content').getByRole('button', { name: 'Run', exact: true }).click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + expect(errors).toEqual([]); +}); From 4afafa3d376f4f2e63826b73978dd46656139818 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:45:38 -0700 Subject: [PATCH 081/116] Parametric: new fixtures and loads are named like features and CAM operations (Fixed1, FixedHinge1, Force1) --- src/parametric/src/model/fea.ts | 4 +-- src/parametric/tests/e2e/analysis.spec.ts | 30 +++++++++++------------ src/parametric/tests/fea-model.test.ts | 22 ++++++++++++----- 3 files changed, 33 insertions(+), 23 deletions(-) diff --git a/src/parametric/src/model/fea.ts b/src/parametric/src/model/fea.ts index 5e3adf6387..286166f021 100644 --- a/src/parametric/src/model/fea.ts +++ b/src/parametric/src/model/fea.ts @@ -196,9 +196,9 @@ export function studyOf(doc: PartDocument): StaticStudy | null { return doc.study ?? null; } -/** Name for a new fixture or load: the label followed by the first number not taken. */ +/** Name for a new fixture or load, as features and CAM operations are named: the label's words run together and the first number not taken ("FixedHinge1"). */ export function nextStudyName(s: StaticStudy, label: string): string { const used = new Set([...s.fixtures, ...s.loads].map((x) => x.name.toLowerCase())); const base = label.replace(/[^A-Za-z]/g, ''); - for (let i = 1; ; i++) if (!used.has(`${base}-${i}`.toLowerCase())) return `${base}-${i}`; + for (let i = 1; ; i++) if (!used.has(`${base}${i}`.toLowerCase())) return `${base}${i}`; } diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index ea0951414d..7637d42cf1 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -47,7 +47,7 @@ test('sets up a static study, runs it, reads the plot and saves it with the part await page.mouse.click(p.x, p.y); await expect(page.getByRole('group', { name: 'Faces' })).toContainText('Face'); await page.locator('.confirm-corner .ok').click(); - await expect(page.getByRole('treeitem', { name: /^Fixed-1/ })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: /^Fixed1/ })).toBeVisible(); // A 500 N force pressing on the top of the upright. await page.locator('[data-cmd="fea:force"]').click(); @@ -55,7 +55,7 @@ test('sets up a static study, runs it, reads the plot and saves it with the part await page.mouse.click(p.x, p.y); await page.getByLabel('Total force (N)').fill('500'); await page.locator('.confirm-corner .ok').click(); - await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: /^Force1/ })).toBeVisible(); expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads[0])).toMatchObject({ type: 'force', value: 500, dir: null, faces: [{ name: 'f1:side:bl4' }] }); // Run: the plot, its legend and the summary. @@ -107,7 +107,7 @@ test('sets up a static study, runs it, reads the plot and saves it with the part a.loadDocument(parseDocument(text), null); }, { text: JSON.stringify(saved), url: '/src/model/document.ts' }); await page.getByRole('tab', { name: 'Analysis' }).click(); - await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: /^Force1/ })).toBeVisible(); await page.locator('[data-cmd="fea:run"]').click(); await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); await expect(page.locator('.fea-forces')).toContainText('0.000, 600.000, 0.000 N'); @@ -148,11 +148,11 @@ async function bracketStudy(page: Page) { const ref = (n: string) => { const f = a.faces.find((x) => x.name === n)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; a.store.change('Set up', (d) => { d.material = { name: 'Alloy Steel', density: 7700, E: 205000, nu: 0.29, yield: 415, uts: 655 }; - d.study = { id: 'st900', name: 'Static Study', fixtures: [{ id: 'fx901', name: 'Fixed-1', type: 'fixed', faces: [ref('f1:side:bl1')] }], loads: [{ id: 'ld902', name: 'Force-1', type: 'force', faces: [ref('f1:side:bl4')], value: 500, dir: null, flip: false }], mesh: { fineness: 0.2 } }; + d.study = { id: 'st900', name: 'Static Study', fixtures: [{ id: 'fx901', name: 'Fixed1', type: 'fixed', faces: [ref('f1:side:bl1')] }], loads: [{ id: 'ld902', name: 'Force1', type: 'force', faces: [ref('f1:side:bl4')], value: 500, dir: null, flip: false }], mesh: { fineness: 0.2 } }; }); }); await page.getByRole('tab', { name: 'Analysis' }).click(); - await expect(page.getByRole('treeitem', { name: /^Force-1/ })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: /^Force1/ })).toBeVisible(); } test('a load direction to pick stays chosen until it is picked', async ({ page }) => { @@ -177,10 +177,10 @@ test('a load direction to pick stays chosen until it is picked', async ({ page } test('the panel of a fixture or load closes when it is deleted', async ({ page }) => { const errors = await openApp(page); await bracketStudy(page); - // Editing Force-1 when it is deleted (here by Undo of its study): OK must not bring it back. - await page.getByRole('treeitem', { name: /^Force-1/ }).dblclick(); - await expect(page.locator('.pm-head').getByText('Force-1', { exact: true })).toBeVisible(); - await page.evaluate(() => (window as unknown as W).__parametric.store.change('Delete Force-1', (d) => { d.study!.loads = []; })); + // Editing Force1 when it is deleted (here by Undo of its study): OK must not bring it back. + await page.getByRole('treeitem', { name: /^Force1/ }).dblclick(); + await expect(page.locator('.pm-head').getByText('Force1', { exact: true })).toBeVisible(); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Delete Force1', (d) => { d.study!.loads = []; })); await expect(page.locator('.pm-head')).toHaveCount(0); expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads)).toEqual([]); // A new fixture when the study goes (Undo): its panel closes too. @@ -282,8 +282,8 @@ test('loads of an inch part are in pounds-force and psi, with round defaults', a await page.locator('[data-cmd="fea:gravity"]').click(); await expect(page.getByLabel('Acceleration (in/s²)')).toHaveValue('386.08858'); await page.locator('.confirm-corner .cancel').click(); - // Force-1 (500 N) reads in lbf, and a value typed in lbf is kept in newtons. - await page.getByRole('treeitem', { name: /^Force-1/ }).dblclick(); + // Force1 (500 N) reads in lbf, and a value typed in lbf is kept in newtons. + await page.getByRole('treeitem', { name: /^Force1/ }).dblclick(); await expect(page.getByLabel('Total force (lbf)')).toHaveValue('112.40447'); await page.getByLabel('Total force (lbf)').fill('50'); await page.locator('.confirm-corner .ok').click(); @@ -423,7 +423,7 @@ test('the CSV summary has one quantity per row, with its unit in the unit column test.setTimeout(180_000); const errors = await openApp(page); await bracketStudy(page); - await page.evaluate(() => (window as unknown as W).__parametric.store.change('Gravity', (d) => { d.study!.loads.push({ id: 'ld903', name: 'Gravity-1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); })); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Gravity', (d) => { d.study!.loads.push({ id: 'ld903', name: 'Gravity1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); })); await page.locator('[data-cmd="fea:run"]').click(); await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); await page.getByRole('button', { name: 'Report...' }).click(); @@ -432,9 +432,9 @@ test('the CSV summary has one quantity per row, with its unit in the unit column const file = await download; expect(file.suggestedFilename()).toBe('Mounting Bracket - Static Study.csv'); const csv = (await (await file.createReadStream()).toArray()).join(''); - expect(csv).toContain('\nLoads,Force-1 force,500,N\n'); - expect(csv).toContain('\nLoads,Force-1 area,240,mm²\n'); - expect(csv).toContain('\nLoads,Gravity-1 acceleration,9.80665,m/s²\n'); + expect(csv).toContain('\nLoads,Force1 force,500,N\n'); + expect(csv).toContain('\nLoads,Force1 area,240,mm²\n'); + expect(csv).toContain('\nLoads,Gravity1 acceleration,9.80665,m/s²\n'); // Every row: section, quantity, a value without its unit, the unit. for (const line of csv.trim().split('\n').slice(1)) expect(line, line).not.toMatch(/,[-\d.e]+ (N|MPa|mm|%)/); expect(errors).toEqual([]); diff --git a/src/parametric/tests/fea-model.test.ts b/src/parametric/tests/fea-model.test.ts index 0245e12c58..9958c095a0 100644 --- a/src/parametric/tests/fea-model.test.ts +++ b/src/parametric/tests/fea-model.test.ts @@ -2,7 +2,7 @@ // results summary export: round trips, old files, refused damage. import { describe, expect, it } from 'vitest'; import { newDocument, parseDocument, serializeDocument } from '../src/model/document'; -import { type StaticStudy, elementSizeFor, feaUnits, newStudy, parseStudy, studyIds } from '../src/model/fea'; +import { type StaticStudy, elementSizeFor, feaUnits, newStudy, nextStudyName, parseStudy, studyIds } from '../src/model/fea'; import { MATERIALS, elasticOf, normalizeMaterial, validElastic } from '../src/model/materials'; import { colorAt, interpolate } from '../src/fea/results'; import { principal } from '../src/fea/elements'; @@ -12,11 +12,11 @@ const face = (name: string) => ({ name, sig: { type: 'plane', c: [1, 2, 3] as [n function study(): StaticStudy { const s = newStudy('st3'); - s.fixtures.push({ id: 'fx4', name: 'Fixed-1', type: 'fixed', faces: [face('f1:cap0')] }); - s.fixtures.push({ id: 'fx5', name: 'Hinge-1', type: 'hinge', faces: [{ name: 'f2:h1:1', sig: { type: 'cylinder', c: [0, 0, 0], area: 50 } }], suppressed: true }); - s.loads.push({ id: 'ld6', name: 'Force-1', type: 'force', faces: [face('f1:cap1')], value: 250, dir: { kind: 'edge', edge: { name: 'e1', sig: { type: 'line', m: [0, 0, 0], len: 10 } } }, flip: true }); - s.loads.push({ id: 'ld7', name: 'Pressure-1', type: 'pressure', faces: [face('f1:side:bl2')], value: 2, flip: false }); - s.loads.push({ id: 'ld8', name: 'Gravity-1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); + s.fixtures.push({ id: 'fx4', name: 'Fixed1', type: 'fixed', faces: [face('f1:cap0')] }); + s.fixtures.push({ id: 'fx5', name: 'Hinge1', type: 'hinge', faces: [{ name: 'f2:h1:1', sig: { type: 'cylinder', c: [0, 0, 0], area: 50 } }], suppressed: true }); + s.loads.push({ id: 'ld6', name: 'Force1', type: 'force', faces: [face('f1:cap1')], value: 250, dir: { kind: 'edge', edge: { name: 'e1', sig: { type: 'line', m: [0, 0, 0], len: 10 } } }, flip: true }); + s.loads.push({ id: 'ld7', name: 'Pressure1', type: 'pressure', faces: [face('f1:side:bl2')], value: 2, flip: false }); + s.loads.push({ id: 'ld8', name: 'Gravity1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); s.mesh.fineness = 0.75; return s; } @@ -134,3 +134,13 @@ describe('result helpers', () => { expect(csv).toContain('Study,Part,"Bracket, ""A""",'); }); }); + +describe('names of new fixtures and loads', () => { + it('runs the label words together with the first free number, like features and CAM operations', () => { + const s = newStudy('st1'); + expect(nextStudyName(s, 'Fixed Hinge')).toBe('FixedHinge1'); + expect(nextStudyName(s, 'Roller')).toBe('Roller1'); + s.loads.push({ id: 'ld2', name: 'force1', type: 'pressure', faces: [], value: 1, flip: false }); + expect(nextStudyName(s, 'Force')).toBe('Force2'); + }); +}); From 74e1b7a067fde249ad0c92ac2c72cc5dc37a0915 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:46:02 -0700 Subject: [PATCH 082/116] Parametric: the study panel gives an inch part's material stiffness and yield strength in psi, like its results --- src/parametric/src/app/fea/panels.ts | 6 +++++- src/parametric/tests/e2e/analysis.spec.ts | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts index 370ab97463..aaf6b7b9e1 100644 --- a/src/parametric/src/app/fea/panels.ts +++ b/src/parametric/src/app/fea/panels.ts @@ -105,7 +105,11 @@ export class StudyPanel extends FeaPanel { nameInput.addEventListener('change', () => { this.name = nameInput.value; setTimeout(() => this.commit()); }); const mat = app.store.doc.material; const el = elasticOf(mat); - const matText = !mat ? 'No material chosen.' : el ? `${mat.name}: E ${formatNumber(el.E / 1000, 1)} GPa, ν ${el.nu}, yield ${el.yield} MPa` : `${mat.name}: no elastic properties (cannot be analyzed).`; + // In the part's stress unit, as the results are (psi in an inch part). + const su = feaUnits(app.store.doc.units); + const psi = (v: number) => `${Number((v / su.stressScale).toPrecision(3)).toLocaleString('en-US')} ${su.stress}`; + const elText = (e: NonNullable) => (su.stressScale === 1 ? `E ${formatNumber(e.E / 1000, 1)} GPa, ν ${e.nu}, yield ${e.yield} MPa` : `E ${psi(e.E)}, ν ${e.nu}, yield ${psi(e.yield)}`); + const matText = !mat ? 'No material chosen.' : el ? `${mat.name}: ${elText(el)}` : `${mat.name}: no elastic properties (cannot be analyzed).`; const matBtn = h('button', { class: 'btn small', type: 'button', onclick: () => app.commands.run('material') }, icon('material', 16), 'Material...'); // Mesh: coarse to fine. const u = feaUnits(app.store.doc.units); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts index 7637d42cf1..b97ecef9bc 100644 --- a/src/parametric/tests/e2e/analysis.spec.ts +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -282,6 +282,10 @@ test('loads of an inch part are in pounds-force and psi, with round defaults', a await page.locator('[data-cmd="fea:gravity"]').click(); await expect(page.getByLabel('Acceleration (in/s²)')).toHaveValue('386.08858'); await page.locator('.confirm-corner .cancel').click(); + // The material's stiffness and strength in psi, as the results are. + await page.locator('[data-cmd="fea:study"]').click(); + await expect(page.locator('.fea-material')).toHaveText('Alloy Steel: E 29,700,000 psi, ν 0.29, yield 60,200 psi'); + await page.getByRole('button', { name: 'Close', exact: true }).click(); // Force1 (500 N) reads in lbf, and a value typed in lbf is kept in newtons. await page.getByRole('treeitem', { name: /^Force1/ }).dblclick(); await expect(page.getByLabel('Total force (lbf)')).toHaveValue('112.40447'); From 5c81267fc1d50006fba15a09037ba408ec67697a Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 16:47:20 -0700 Subject: [PATCH 083/116] Parametric: the printed analysis report keeps headings with their tables, and rows, the plot and the closing note whole across pages --- src/parametric/src/app/fea/report.ts | 1 + src/parametric/tests/fea-model.test.ts | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/fea/report.ts b/src/parametric/src/app/fea/report.ts index 7a3fc6a146..eaff784943 100644 --- a/src/parametric/src/app/fea/report.ts +++ b/src/parametric/src/app/fea/report.ts @@ -84,6 +84,7 @@ export function reportHtml(title: string, rows: Line[], image: string | null, ca body{font:13px/1.45 system-ui,sans-serif;margin:24px;color:#111}h1{font-size:20px}h2{font-size:15px;margin:18px 0 6px;border-bottom:1px solid #ccc} table{border-collapse:collapse;width:100%}th{text-align:left;font-weight:500;width:45%;padding:3px 8px 3px 0;color:#333}td{padding:3px 0} img{max-width:100%;border:1px solid #ddd;margin-top:8px}figure{margin:0}figcaption{color:#333;margin-top:4px}.note{color:#555;font-size:12px;margin-top:18px} +h2{break-after:avoid}tr,figure,.note{break-inside:avoid}

${esc(title)}

${image ? `
${esc(caption || 'Result plot')}${caption ? `
${esc(caption)}
` : ''}
` : ''}${body}

Linear static analysis: small displacements, linear elastic isotropic material, no contact. Stresses at sharp inner corners and at the edges of fixed faces can grow without bound as the mesh is refined (stress singularities); judge them by the stresses a little away from such spots.

`; } diff --git a/src/parametric/tests/fea-model.test.ts b/src/parametric/tests/fea-model.test.ts index 9958c095a0..24bf8e526f 100644 --- a/src/parametric/tests/fea-model.test.ts +++ b/src/parametric/tests/fea-model.test.ts @@ -6,7 +6,7 @@ import { type StaticStudy, elementSizeFor, feaUnits, newStudy, nextStudyName, pa import { MATERIALS, elasticOf, normalizeMaterial, validElastic } from '../src/model/materials'; import { colorAt, interpolate } from '../src/fea/results'; import { principal } from '../src/fea/elements'; -import { summaryCsv } from '../src/app/fea/report'; +import { reportHtml, summaryCsv } from '../src/app/fea/report'; const face = (name: string) => ({ name, sig: { type: 'plane', c: [1, 2, 3] as [number, number, number], n: [0, 0, 1] as [number, number, number], area: 12 } }); @@ -133,6 +133,14 @@ describe('result helpers', () => { expect(csv).toContain('Results,Max von Mises stress,12.5,MPa'); expect(csv).toContain('Study,Part,"Bracket, ""A""",'); }); + + it('prints the report without splitting a row, the plot or the closing note across pages, nor leaving a heading at a page foot', () => { + const html = reportHtml('Part - Study', [{ section: 'Results', name: 'Max von Mises stress', value: '12.5', unit: 'MPa' }], 'data:image/png;base64,AA==', 'von Mises stress '); + const css = /