Compare commits

..
136 Commits
Author SHA1 Message Date
jyvikoandClaude Opus 5.5 c012a9e442 ui: collapse the Relax-around-worst-element condition (clippy)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 15:22:18 -04:00
jyvikoandClaude Opus 5.5 5a0605741b release: version 0.6.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 15:13:31 -04:00
jyvikoandClaude Opus 5.5 ef77deff5f build(deps): finish the zip 9 port and lock it
The 3MF reader's name_for_index now returns a Result in zip 9, and the
geometry test writer still wrapped last_modified_time in Some. Cargo.lock
gains zip 9.0.3 beside SolidCraft's zip 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 15:08:13 -04:00
Skywalkingzulu1 4ffce253f2 fix(io): adapt to zip 9 API
- last_modified_time takes DateTime directly, drop the Some() wrapper
- file_names() returns Result<Cow<str>, ZipError>: propagate errors, compare
  the Cow<str>, and push the resolved name into seen
- test helper: ZipFile::name() now returns Result, unwrap it
- update the Cargo.toml comment explaining why we moved ahead of
  SolidCraft (still on zip 3)
- update Cargo.lock to zip 9.0.3
2026-10-15 15:08:13 -04:00
Skywalkingzulu1 8e28283dad build(deps): upgrade zip 3 → 9
Bump the zip crate from 3 to 9 in the workspace Cargo.toml and
adapt to the API change in 2.0+: last_modified_time now takes
Option<DateTime> instead of DateTime directly.

- crates/io/src/lib.rs: wrap DateTime::default() in Some(...)
- crates/geometry/src/tagged_mesh.rs: same fix in the 3MF writer

Closes #134
2026-10-15 15:08:13 -04:00
jyvikoandClaude Opus 5.5 a6f1a6dbeb ui: Relax around worst element at the top of Mesh Quality; plain preview text (#398)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 14:40:00 -04:00
jyvikoandClaude Opus 5.5 87af68f550 docs: node relaxation in features, MCP guide, control protocol, literature and the meshing skill (#398)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 14:40:00 -04:00
jyvikoandClaude Opus 5.5 94fdbf0fca engine, ui: mesh.node.relax and relaxation fields, Relax Nodes tool with sphere and preview (#398)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 14:40:00 -04:00
jyvikoandClaude Opus 5.5 75f9e5ae6e mesh: node relaxation with UV surface slides and relaxation fields (#398)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 14:40:00 -04:00
Preetinder Kalsi 2030a81327 Share static equilibrium core with buckling preload 2026-10-15 14:27:01 -04:00
Preetinder Kalsi 4c42a708f7 Allow explicit solve factor caps up to two billion entries 2026-10-15 14:00:56 -04:00
Preetinder Kalsi a530a0d914 Report factor value bytes and preserve overflow-safe reduction limits 2026-10-15 14:00:56 -04:00
jyvikoandClaude Opus 5.5 c7d0a82079 geometry: cuts stay on their plane; risky cuts are named (#384)
A partition intersects the body with a box on each side of the plane as
large as the body itself. SolidCraft's split_by_plane uses boxes several
times larger, and its boolean then put the cut up to 1.8 um off the plane
on the enclosure's air, so the cut faces were not recognized and the cells
did not close. A plane along a face of a body it cuts, or a cell whose
boundary does not tessellate into one a mesher takes (a cut through a
hole's axis), is a warning naming the partition, the body and where.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:43:45 -04:00
jyvikoandClaude Opus 5.5 09323ddb45 geometry: meshes go with the bodies a partition change removes (#385)
Deleting, suppressing or editing a partition (or its datum), or cutting a
meshed body, removes the meshes of the bodies that are gone, reported as
replaced, in the same undo step. model.check lists meshes of partition
cells the open design no longer has (a model saved before the cut
changed), and mesh.clear removes them, or the meshes of named bodies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:43:45 -04:00
jyvikoandClaude Opus 5.5 c6eeac35c1 solver: a node in several ties gets one constraint; ties both ways are an error (#389)
A node on the secondary surfaces of two ties (a chip's underside and its
sides, a cut face and an outer face) got one constraint per tie. When the
main nodes of one follow the other's main surface, the second constraint is
nearly the first again, and eliminating it divided by round-off: the Pi 5
heat model put 21.9 W more in than its 8 W. Such a node now follows the
main faces of all its ties together (balanced to 5e-11 of the power), a
node following a node that follows it back (a tie each way on one
interface) is an error naming both ties, and a tie row that still nearly
repeats the constraints before it is an error naming them.

mesh.cells ties one way by a fixed order of the cells (hex main to tet)
and makes one tie per tied cell, tie_<cell>, replacing the ties an earlier
run made, so its own ties never hold a node twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:43:45 -04:00
jyvikoandClaude Opus 5.5 755576de8a mesh.cells: sweep the cells of a body together, conforming with no seeds (#288)
hex_mesh_swept_cells lays out one cross-section for several cells: every
cell's walls (its cut faces included) are imprinted together, every cell's
levels are levels of all, one interval assignment and one set of layers,
and each region of each level interval is filled by the cell it lies in.
Cells meet node for node across every cut, T-junctions included.

mesh.cells sweeps the cells of each design body together first and meshes
cell by cell only what does not sweep together (saying why); the reply
gives every cell's volume, scaled Jacobian and edge ratio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:43:45 -04:00
jyvikoandClaude Opus 5.5 c3a1712069 mesh: interval assignment repairs parity round a point with coupled curves too
Four triangles round a point (a square cut along both diagonals) share their
free half-diagonals in pairs, so those alone cannot make every loop even when
the square's perimeter is odd; the parity repair kept raising them until the
step cap. A loop that keeps coming back now lets its coupled curves move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:43:45 -04:00
jyvikoandClaude Opus 5.5 92c3588099 geometry: a partition's pieces that do not touch become separate cells (#388)
split_by_plane gives one body per side, which may hold several shells when
the side falls apart; every lump is now its own cell (B/a1, B/a2), at every
cut, as the partition docs promise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:43:45 -04:00
jyvikoandClaude Opus 5.5 df7f7f0769 docs: what CI runs when (affected crates on develop, everything nightly and at release)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:31:40 -04:00
jyvikoandClaude Opus 5.5 1e88839575 ci: release verifies the full gate, heavy tests and oracle (Linux, macOS) before packaging
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:31:40 -04:00
jyvikoandClaude Opus 5.5 b90554561f ci: test the crates a change affects since the last green run; heavy and oracle only when it reaches them
A plan job picks the base (the newest develop commit whose push run
passed and that HEAD contains; a pull request's merge base; none for
nightly and manual runs, which run everything) and runs cargo xtask
affected. The ci job runs `cargo xtask ci --affected BASE`; heavy and
oracle run only when the change reaches the solvers, the oracle or
everything. Cancelling superseded push runs stays: the tip's run covers
everything since the last green one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:31:40 -04:00
jyvikoandClaude Opus 5.5 b3098f8739 xtask: affected --base REV and ci --affected REV test only what a change reaches
`cargo xtask affected` maps the changed files to workspace packages (by
directory from cargo metadata; files outside every package to the
packages whose sources name their top-level directory), adds every
reverse dependency, and flags everything (manifest, lock file,
toolchain, xtask, workflows), solver (the oracle's package or a package
with #[ignore]d heavy tests) and wasm (a crate the wasm check builds).
`cargo xtask ci --affected REV` runs the quick whole-tree gates, then
clippy and the tests of the affected packages, and the wasm check only
when flagged. Without the flag the gate is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:31:40 -04:00
jyvikoandClaude Opus 5.5 21072a23de xtask: drop the licences --check gate; THIRD-PARTY-LICENSES.txt is a release artifact
The file is no longer committed: dependency pull requests from forks failed CI only because
it was out of date. The Dependabot workflow that regenerated it is gone. licences now fails
when a shipped crate names no licence and carries no licence file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:24:45 -04:00
jyvikoandClaude Opus 5.5 840b4b7dc5 ci: generate THIRD-PARTY-LICENSES.txt in every release job and attach it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:24:45 -04:00
jyvikoandClaude Opus 5.5 e85300234f ci: check dependency licences with cargo-deny on every pull request
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 13:24:45 -04:00
Preetinder Kalsi e3d42d8be1 build(deps): adapt 3MF reader to quick-xml 0.42 2026-10-15 13:12:49 -04:00
jyvikoandClaude Opus 5.5 f220c7108b solver: a job cancelled before it starts stops before any setup work
The cancel check came only at the factorization, so on a busy CI runner a
pre-cancelled frequency solve still spent 17 s on setup (cancel_tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 12:44:16 -04:00
Preetinder Kalsi 3e997dab43 Make empty text fields visible in the light theme 2026-10-15 12:20:33 -04:00
jyvikoandClaude Opus 5.5 29667e63e8 skills: agentic hex meshing (fieldcraft-meshing)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 12:06:55 -04:00
jyvikoandClaude Opus 5.5 7a9cb2cb22 ci: release secrets from the main-only release environment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 12:01:16 -04:00
jyvikoandClaude Opus 5.5 1dc4c27dc1 docs: ROADMAP lists what landed for 0.6.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:53:52 -04:00
jyvikoandClaude Opus 5.5 0a0bac2bf2 mcp: the solve tool runs nonlinear and buckling steps too, and its docs list heat
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:53:52 -04:00
jyvikoandClaude Opus 5.5 fe1fc30be5 docs: regenerate the gallery captures, Start-card thumbnails and setup-symbols picture for 0.6.0
Window captures (light theme, 1400 x 860) of every sample solved on the current UI; the
thumbnails that were viewport crops are now clean ui.render images like the others; the drop
test's figure at 0.1 ms reads 129 MPa.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:53:52 -04:00
jyvikoandClaude Opus 5.5 cc83e01c57 engine: New Step's description lists the buckle, heat transfer and coupled procedures
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:53:52 -04:00
jyvikoandClaude Opus 5.5 4a5d897782 engine: a free body in explicit dynamics needs no boundary condition in the setup checklist
The drop-test and impact samples have no supports, by design, yet the browser marked Loads &
BCs as the next stage with an Add boundary condition row even after they were solved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:53:52 -04:00
jyvikoandClaude Opus 5.5 c983987c64 results: Export CSV takes every parameter its description names (set, at, mode, frame, about)
results.export.csv's form listed only nodes and sets, so the parameter check refused the
probe's set, at, mode and frame and the reactions' about point that the command documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:53:52 -04:00
jyvikoandClaude Opus 5.5 05dc20a70b ui: preview Merge Nodes and select what Check Duplicates finds (#234)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 198ead4015 mesh: node tools commands: merge, duplicate check, renumber (#234)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 57f7bd3d7e mesh: merge plans, duplicate and crack checks, reverse Cuthill-McKee order (#234)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 1a91bb324d mesh: renumber nodes and elements in the model, every reference following (#234)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 b5e54cb802 mesh: regression test for hex20 on the crank with tangent root arcs (#197)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 3385209c6f mesh: carry a biased seed's spacing to the edges tied to it (#257)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 d23c2efaec mesh: report a kernel failure to partition as the kernel's, not a plane that misses (#283)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 22f2e0c9cc mesh: keep tet improvement insertions apart from existing vertices (#311)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:11:14 -04:00
jyvikoandClaude Opus 5.5 1f85a8caa3 ui: typed form fields for label lists, point lists, multi-choices and number-or-auto (#169)
Four field kinds in the schema, each checked and described in JSON Schema: labels (nodes or
elements, typed as 1-5, 8 with Use selection taking the viewport's picks), points (rows of
x, y, z, added and removed), multi (checkboxes: coupling DOFs, step output) and number or
auto (the deformed scale). Node and element lists, probe and Delaunay points and block
corners use them; the remaining JSON fields hold geometry-specific shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 c0cbcadf3d ui: Mesh Quality shows counts, a histogram per metric and the worst elements (#113)
The context panel reads mesh.quality's reply as the counts (an area only for a surface mesh),
each metric's min, mean and max over its histogram (the bad end warm), and its worst element: a
click selects and frames it. Invalid and undetermined elements have a button that selects
and frames them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 d1557a87fe results: export probe and reaction results to CSV (results.export.csv, #92)
results.export.csv runs solve.probe or results.reactions and writes their reply as an RFC 4180
CSV: a row per node (node, x, y, z and the quantities the step has, columns it does not have
left out) or per set with the total and the applied load; numbers in shortest round-trip form,
so they read back bit for bit. A stale result is refused. The results panel has Export CSV…
beside Reaction sums and under the probed node: the save picker, or the form without one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 5112855b83 results: clamp the contour legend's range; values above it in an over colour (#191)
results.contour takes range {min?, max?} (or "auto"), kept until the field changes: a
singular peak no longer squeezes the field into the bottom bands. Values above a clamped
maximum go to an extra band drawn in the over colour, split exactly at the clamp; the legend
shows that band up to the true maximum and says it is clamped. The results panel has Legend
max/min (Auto or a value), the MCP show_results tool a range argument, and headless pictures
follow the clamp too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 441f03d093 ui: Help › Crash Reports lists the saved reports to report, copy or delete (#300)
diagnostics.crash_reports.delete deletes one report or all. The window lists each report
(when, what, how many times) with Report…, Copy Path and Delete, and Delete All; ui.prompt
answers it over the control channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 4711f9474a engine: the I-beam cantilever sample (ibeam, #143)
The README video's model as a sample: the corpus cantilever-i-beam design opened as geometry,
swept all-hex, clamped at F2:start, 1 kN on F2:top through a kinematic coupling; static step
Load. It has a Start-card thumbnail and a gallery capture; a test checks its tip deflection
against beam theory with shear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 0625125ed7 ui: File › New starts an empty model (file.new, #144); an unknown sample name opens the samples (#200)
file.new replaces the session with an empty one: no design, mesh, definitions, results or
journal, nothing to save, the undo history empty. The File menu and Cmd/Ctrl+N run it, asking
first over unsaved changes. A sample name the app does not know (a typo, an old ?sample= link)
opens the samples to choose from, and the status names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 92b6225a72 mcp: the probe tool takes at, points whose nearest nodes are probed (#105)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 11:07:46 -04:00
jyvikoandClaude Opus 5.5 5aace9b5b3 jobs: Cancel and job.cancel interrupt the running command (#371)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:39:40 -04:00
jyvikoandClaude Opus 5.5 5fcbee028e solvers, meshers: stop with Cancelled at each loop's natural points
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:39:40 -04:00
jyvikoandClaude Opus 5.5 a2d646a75e model: a cancel flag on Progress and progress::check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:39:40 -04:00
jyvikoandClaude Opus 5.5 3363181a01 docs: attribute the void-shell test designs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:20:08 -04:00
jyvikoandClaude Opus 5.5 84f42f6f8a ui: Suppress/Unsuppress on datums and partitions, greyed in the browser (#291)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 5189554a6a model: suppress datums and partitions: kept, but left out of the model (#291)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 dcf03e3378 ui: Rename… in a definition's item menu; the selection follows the new name (#290)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 a0ae8b2111 model: rename a definition and every reference to it (model.rename, #290)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 587cbc3b01 ui: seed ticks show where the mesh has another number of divisions (#342, #371)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 980a50c1d9 ui: the Partition form highlights the bodies it would cut (#347, #371)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 3a023f3e25 ui: selecting the Mesh node shows the commands and parameters that made the mesh (#343, #371)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 f9c1c3cb24 ui: the selection filter follows what the selection holds (#341, #371)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 2908a77850 ui: every sample has a thumbnail on the Start card and a gallery capture (#294)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 bbf2dba092 render: translucent faces in both renderers; datum planes get a light fill (#302)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 89dfc62c2f render: perspective hides edges behind faces in CPU renders (#282)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 1f36693c8f ui: one symbol-unit helper for the window, ui.render and headless renders (#285)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 b377c882d6 ui: the sampled-symbols note wraps short of the navigation bar (#206)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 3458117357 ui: the command search runs a command typed with its parameters (#202)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:17:28 -04:00
jyvikoandClaude Opus 5.5 750f5f5a61 model: geometry names up to 64 KiB everywhere, so long persistent face names mesh
Persistent names grow with a design's split history; opening accepted them but mesh tags, sets
and loads capped geometry names at 256 characters. One cap (64 KiB, against hostile input)
now holds for geometry references, partitions and saved views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 10:09:04 -04:00
jyvikoandClaude Opus 5.5 7a078b1c04 ui: results show units, clean numbers, extremes, reaction sums and a solve summary
One formatter (four significant digits, thousands separators, round-off as
0) and the model's units through every results readout:
- legend title with its unit, a mode shape normalised; Max/Min with units,
  clickable to show and probe the node; markers at both in the viewport
  (#321, #330)
- the deformation scale field shows the scale Deformed would use, never 0,
  in the shared format; true scale named (#325, #326)
- setup symbols off over results by default (Show › Loads & BCs), and then
  only the shown step's (#327)
- reaction sums in the results panel however they are run: per set and in
  all, force and moment with units, applied beside reacted (#328)
- the probe: U [mm], |U|, Mises, stresses and principals with units, the
  label kept inside the viewport, rows in the results panel (#329)
- hiding the mesh over a plot hides the element edges, not the contours
  (#317); a hidden body's contours go with it, the range follows what is
  shown (#365)
- the solve summary: peaks with units, n/a rows left out, counts grouped,
  internals under Details (#321, #319)
- the energies plot: axes with units, a cursor at the frame (click or drag
  to move it), hover to read (#331)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:36:54 -04:00
jyvikoandClaude Opus 5.5 91e8467e4f engine, render: hidden bodies hide their mesh and results; solve totals without round-off
- DisplayMesh::from_model_hiding leaves out a hidden body's elements (and the
  nodes only they use); Session::hidden_elements names them, so the viewport,
  probing and headless pictures skip hidden bodies (#365).
- A solve summary's applied and reaction totals set the round-off of
  cancelling sums to 0 (#319).
- results::principal for the probe's principal stresses (#329).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:36:54 -04:00
jyvikoandClaude Opus 5.5 0966dfa2a6 engine: result units, per-step staleness, step symbols, true-scale nonlinear results
- Quantity names the unit of every number the results show from the model's
  unit system (mm, MPa, N, N·mm, mJ, mW, °C or K); Field::title puts it in the
  legend title, and calls a mode shape normalised (#321).
- A solved step's result stays current through edits that leave what it reads
  alone (Model::step_inputs: other steps and what only they use), and comes
  back current on undo (#318).
- Session::step_glyphs: the symbols of what a solved step used, for drawing
  over its results; no load arrows on a frequency step's modes (#327).
- Nonlinear static steps open deformed at true scale like explicit ones, and
  their automatic scale is 1 (auto_scale, shared by the viewport and the
  headless pictures) (#326).
- results.reactions with an empty sets list sums the step's boundary-condition
  sets, as its form says (#328).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:36:54 -04:00
jyvikoandClaude Opus 5.5 a09e3c856b ui: pick vertices, points and cells from the viewport
- Select: Vertices picks the design's B-rep vertices (meshed or not), and
  a selected vertex is marked (#346).
- Use selection on Datum Point (vertex, edge, face, or a hole's centre)
  and Reference Point (geometry.centre: a hole's centre, a vertex, nodes)
  (#346, #351).
- Partitioned Mesh: Use selection takes the picked bodies as cells; the
  cell list has All, None and Invert; hovering a cell's row (or its method
  row) highlights the cell in the viewport (#344).
- Rigid Wall's form takes its set from the selection; the Interactions
  branch lists the explicit steps' rigid walls, each opening its step
  (#350).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:27:39 -04:00
jyvikoandClaude Opus 5.5 1372094f8a engine: pick-driven points, cells' methods per cell, rigid walls as interactions
- geometry.bodies lists each body's vertices; geometry.datum.point by
  vertex takes the design's vertex names (labelled Vertex, not Mesh
  vertex) (#346).
- geometry.centre: the point for what is picked: a vertex, nodes, a
  hole's centre (cylindrical faces or circular edges), else a centroid
  (#351).
- mesh.cells' form: the cells first, and a method drop-down per cell
  (schema kind RefChoices) instead of JSON (#344).
- interaction.rigid_wall(.delete): rigid walls of an explicit step from
  the Interactions tab, no longer coming soon (#350).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:27:39 -04:00
jyvikoandClaude Opus 5.5 e8e0b92d87 geometry: persistent names of B-rep vertices (#346)
A vertex is named after the faces that meet there, sorted and joined by |
as edges are, numbered ~k where several touch the same faces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:27:39 -04:00
jyvikoandClaude Opus 5.5 25dfbcce42 geometry: number the pieces of a split body by position (#349)
SolidCraft names the pieces of a split body by stacking suffixes
(Bracket (1) (1)' (1)). On opening a design, the pieces of one body are
named <body>.1 … <body>.N, ordered by centroid, so the tree, tooltips,
forms and picks read as one part with numbered cells.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:27:39 -04:00
jyvikoandClaude Opus 5.5 d78a4c2e52 ui: a selected design edge is drawn over the mesh too (#338)
Meshes that do not tag their element edges with the design's edge names
(tet, hex, blocks) left a selected edge with no highlight while the mesh
was shown. The edge is now marked along its own polyline, which the scene
already draws over the mesh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:27:39 -04:00
jyvikoandClaude Opus 5.5 8ba59701b4 geometry: tests open a closed hollow box, a post on its void floor and an open tray (#364)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:23:40 -04:00
jyvikoandClaude Opus 5.5 358ed2f54f geometry: a feature that fails to rebuild names the bodies it changes, and opening warns
The design file stores no measure to compare with, so the rebuild's own
failures are the guard: each failed feature lists the bodies it names (all of
them when it names none), and geometry.open replies with a warning per failure,
which the window shows with the open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:23:40 -04:00
jyvikoandClaude Opus 5.5 ecd78b9ee6 geometry: rebuild designs with SolidCraft b1695873, whose joins onto a void shell's floor succeed
FieldCraft pinned SolidCraft a629236, which predates #1244: a cylinder joined
onto the floor of a closed hollow body (a coplanar touching face) failed to
rebuild there, and the design opened without it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:23:40 -04:00
jyvikoandClaude Opus 5.5 4ee855bb27 ui: jobs with progress, refusals listed, datum preview, form filters and defaults
- A solve or a mesher runs as a job with one progress mechanism: the overlay
  shows the step, stage, count and elapsed time with a bar when bounded, OK
  waits while it runs, and the status sums it up (elements, smallest angle,
  time) (#322, #357).
- Over the control channel such a command is a job too: answered when it
  ends however long it runs, or at once with wait: false, then job.status,
  job.wait, job.cancel; ui.inspect gives job; MCP waits for it (#367).
- A command that cannot run yet lists what it misses in the context panel,
  each with a button to the command that provides it (#323).
- A cancelled or refused solve stays in its workspace (#324, test).
- A mesher form starts from the parameters of the mesh it would replace (#343).
- Seed Edges and edge/vertex/face datum points switch the selection filter
  while open and restore it (#341).
- Datum forms draw the datum live, the Partition form shows its datum, and
  new datums and partitions get the next free name (#347).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 3eaca26246 engine: a mesh made before its seeds changed is out of date; a remesh names a type change
The setup checklist marks the mesh Outdated (a warm ⚠ in the browser, with
what changed and where to remesh) when seeds, partitions or datum planes
changed after the last mesher ran, and model.check warns (#342). Replacing
a mesh asks with the element type change it makes, such as tet10 → tet4 (#343).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 464a4d50c1 solver: heat flow through each heat load, and the imbalance (#362)
solve.heat's reply and the results report give heat_flows: each convection,
flux and source load's heat into the body, the prescribed temperatures'
total and their sum; the results panel lists them for a heat step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 0e0d8bd114 model: progress of long commands, reported by the solvers and the tet mesher
fieldcraft_model::progress: a host installs a Progress on the worker thread
and reads its snapshot from another; the engine names the step being solved,
the nonlinear solver its load factor, the explicit solver its time, the
fluid solver its steps, transient heat its increments and the tet mesher its
stage and pass. Without one installed every report is a no-op (#322, #357).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 a7bb67c452 ui: forms show defaults, JSON hints and whole vectors; spaces in names become _
A checkbox whose key is unset shows the field's default (#353). An empty JSON
field shows its format hint (#340). Vector components share a line only when
each fits a value such as -12000, else take a line each (#339). A space typed
in a definition name becomes _ and the form says why (#320).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 c2ad804fed ui: Mesh Block under Structured Hex, Mirror Mesh its own Edit entry (#348)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 7dd4043afe engine: refuse unknown command parameters, suggest a valid name, document heat loads and thermal materials
Every command with a schema now refuses a top-level key it does not take,
naming the key and the accepted ones (#316). A bad definition name's error
suggests the nearest valid one (#320). The load and material params docs list
the heat loads and the thermal block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 09:14:34 -04:00
jyvikoandClaude Opus 5.5 35ee88aa18 ui: ties listed under Interactions, selected, edited and deleted like the others (#366)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 47bdbf981d ui: a new document clears the viewport's picks; opening a sample says so
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 b89efb55c1 render, ui: prescribed motion and thermal conditions get their own symbols and tree icons (#354, #355)
A non-zero prescribed displacement is an arrow leaving the nodes along the
motion (its held degrees of freedom stay supports); a prescribed temperature
is a thermometer, convection a wave off the faces, a heat flux an arrow onto
them. In the tree, thermal conditions carry the heat icon and a moving
boundary condition a motion arrow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 27af5e19b7 ui: the Bodies list by name with sizes, faces and edges; journal deletions and edits badged, tooltips in words (#345, #359)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 de8cdd0b03 ui: a selected set is highlighted in the viewport; seeds are selected, described, edited and deleted from the browser (#336, #352)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 a53c79cb55 ui: properties and status lines in words, current card on top, Use selection makes its set on OK, marks on the left (#335, #333, #360, #337, #315, #361)
- describe.rs: a definition's fields in its form's labels and units (sets by
  members and what they resolve to), for the context panel.
- reply::done: status lines that say what changed ("Showing Load deformed",
  "Mode 2: 1637 Hz", "Added material Al").
- The context panel puts the form and the selection above reports; opening
  another document clears both; what a form makes is selected.
- Use selection reuses a set with the same members, otherwise names one made
  on OK; Cancel leaves the model unchanged. The Target's set row is labelled.
- The browser's state marks sit in one column at its left edge; a right click
  selects the row its menu acts on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 b65f1696b2 ui: name a sample's document after it until saved (#334); "Solve cancelled"
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 8819ff787c engine: a prescribed displacement or temperature satisfies the loads stage (#356)
The setup checklist asked for a load on rubber-seal, driven only by a
prescribed displacement, while model.check called it ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:55:25 -04:00
jyvikoandClaude Opus 5.5 febcffefd6 verification: series-resistance heat flow across a tie (#358)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:27:01 -04:00
jyvikoandClaude Opus 5.5 836513ddfe solver: heat transfer across ties (#358)
Ties constrain temperatures with the displacement tie's mortar weights in
steady and transient heat and in coupled temperature-displacement steps; the
heat solver eliminates them with the prescribed temperatures through
constraints::Reduction. refuse_ties is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:27:01 -04:00
jyvikoandClaude Opus 5.5 0ec1882697 solver: tie weights and constraint reduction independent of the structural mesh (#358)
The tie's mortar rows take any node numbering and degree-of-freedom kinds, and
Reduction takes a DofLayout, so heat transfer can reuse both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 08:27:01 -04:00
jyvikoandClaude Opus 5.5 507e8e32d2 release: version 0.5.9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 02:57:11 -04:00
jyvikoandClaude Opus 5.5 491b3f6212 engine: the heated-bracket guard checks its element count, not wall time
The 60 s limit failed on the Linux CI heavy job (106 s in the test profile) while the
mesh was within its band; the count is what #303's blow-up changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 02:37:31 -04:00
jyvikoandClaude Opus 5.5 111a6f1a94 Mesh: a face edge split that encroaches a feature edge splits the feature edge
Delaunay refinement split a boundary face edge at its midpoint even when that
midpoint lay inside the diametral sphere of a feature edge beside it. Each such
split halves the face vertices' distance to the curve, so they piled up against
it (the heated bracket grew face vertices 0.016 mm from a 4 mm-sized edge), the
improvement schedule could not lift the tetrahedra there to its target, and
inserted vertex after vertex around them: 29257 elements and about two minutes
to open instead of 23641 and 6 s. The SolidCraft pin move (4c91f9b) added one
interior vertex to the bracket's end faces, which changed the CDT enough to
expose it.

Following Shewchuk (1998), an encroaching midpoint now splits the encroached
feature edge instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 02:17:00 -04:00
jyvikoandClaude Opus 5.5 43e2144090 Docs: the crank's one-datum workflow, its gallery images and the Decompose status
examples.md and mcp.md tell the one-datum workflow and its numbers; the
crank gallery captures and Start card thumbnails are taken again on this
build; ROADMAP marks the automatic blocks of extruded cross-sections done,
and features.md's Decompose entry says what is left (3D parts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:50:49 -04:00
jyvikoandClaude Opus 5.5 8e45f2c275 Samples: the crank meshed from one datum, its half extruded in automatic blocks
crank-arm and crank-mirror now take one datum (Sym) and its partition:
mesh.hex.generate extrudes the half CrankArm/a, cutting its cross-section
into blocks itself, with no seeds, and mesh.mirror reflects it. 8 664
hex20, scaled Jacobian min 0.371; root sigma_xx -62.44/+62.44 MPa against
M/Z 62.6 (0.25 %), spindle reaction 1500 N. The seven partitions and
eleven exact seeds go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:50:49 -04:00
jyvikoandClaude Opus 5.5 86ba1bda5c Release: sign SHA256SUMS.txt with the release key; docs/updates.md (#231)
The release job signs SHA256SUMS.txt into SHA256SUMS.txt.minisig with rsign2 when the
FIELDCRAFT_SIGNING_KEY secret exists, and checks the signature against the public key the app
is built with; without the secret the draft is unsigned, the run warns and the notes say the
app cannot install that release itself. docs/releasing.md says how the key is set up, kept
and rotated; docs/updates.md describes checking, verifying and installing, the web app's
Reload to update, and FIELDCRAFT_UPDATE_HOST for tests. privacy.md, control-protocol.md,
web.md and the roadmap say what changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 93b2ae343c Web: offer Reload to update when a new deployment is out (#231)
Every half hour the page fetches its own address past the browser's cache; when it loads
another content-hashed build of the app than the running one, the status bar offers "Reload
to update" (the page's unsaved-changes question still guards the reload). Rust only, no
service worker: the browser build has no other update path and none of the desktop's
download code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 7dd50a3ca4 App: run update jobs in the background and swap the release in after closing (#231)
The desktop app checks, downloads, verifies and stages on its own threads for the window, and
once the window has closed (autosave closed) swaps a staged release in and starts it. Staging
folders an earlier update left are removed at start-up. Automatic checks stay off under
--control automation and CI unless FIELDCRAFT_UPDATE_HOST names a test server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 2e28a69c04 UI: update notice, Help › Check for Updates and Reinstall, Settings › Updates (#231)
The window checks at start-up at most once a day when automatic checks are on (Settings and
the first run's question), never while that question is open and never without a host, so the
browser and tests make no network call. A newer release shows a quiet notice in the status bar
("FieldCraft X is available — What's new · Install · Skip"); Install downloads and verifies
through the host, then asks to restart, saving or asking about unsaved changes first, and the
host swaps the release in after the window closes. A .deb/.rpm install offers the system's
installer and the command instead. Skip this version is kept in the preferences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 69c1440cbe CLI: fieldcraft-cli update --check | --install (#231)
--check runs app.update.check and prints its JSON; --install downloads the latest release for
this install, verifies the checksum list's signature and the asset's checksum, and swaps it in
(or, for .deb/.rpm, prints the package manager command for the verified download). Tested
against a local release server through FIELDCRAFT_UPDATE_HOST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 12487794a3 Engine: app.update.check reports whether a newer release is published (#231)
The same check as the app's Help › Check for Updates and fieldcraft-cli update --check: the
latest release, whether it is newer, its page, whether it is signed and the asset this install
would download. It only reports. Checking reaches the network, so only the desktop app and the
CLI switch it on; tests, scratch sessions and the browser build refuse without asking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 8fe31545ea Update: check, verify and stage releases in a new fieldcraft-update crate (#231)
Versions ordered as SemVer, the GitHub Releases API reply read as hostile input, how this
copy is installed (macOS app or CLI, Windows folder, AppImage, tar.gz folder, .deb/.rpm) and
which release asset updates it, the checksum list's minisign signature checked against the
built-in release key, the asset's SHA-256 checked against the list, archives unpacked inside
the staging folder, and the swap planned and applied by renames with undo on failure. The
network and unpacking parts are native only; a mock release server drives the tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 4c18322a34 Engine: the half crank extrudes in blocks through mesh.hex.generate and mesh.cells
The extrusion's automatic cross-section blocks reach both commands; the
half crank arm, cut only on its symmetry plane, meshes all-structured
(sJ >= 0.37) with no seeds either way, and mesh.hex.generate's
description says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:26:30 -04:00
jyvikoandClaude Opus 5.5 02172f9a7e Mesh: swept cross-sections cut into blocks automatically
A region of an extrusion's (or revolution's) cross-section that no
structured scheme fits is now cut by straight lines into blocks that fit,
before interval assignment, so the cuts are curves of the arrangement and
their counts are assigned with the rest; nothing reaches the model
(hex::decompose, after Tam and Armstrong's medial-axis subdivision and Li,
Armstrong and McKeag's primitives).

Per region: several holes are separated by lines across the gaps between
neighbouring holes; a piece with one hole gets the O-grid layout whose
pieces score best (lines from the outer corners towards the hole or along
their bisectors, from the hole's corners, or along four directions from
the hole); pieces without holes are cut by a two-ply search over lines
from concave corners and fillets and from convex corners. Candidates are
scored by meshing the pieces with their schemes (smallest corner scaled
Jacobian). A region's blocks are kept when fair (at least 0.5) or no worse
than its free mesh, and cuts never end inside a seeded curve.

This replaces the cuts from reflex corners along an edge. Tests on an L,
a T, a plate with a hole, with a slot and with three holes, and the half
crank's cross-section: every region structured, the quads conforming and
the smallest corner scaled Jacobian bounded. The half crank arm now
extrudes in 12 structured regions with a hex20 minimum scaled Jacobian of
0.37 (the arm meeting the bosses 20 degrees off tangent bounds it) where
it had 2 free regions and 0.009.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:17:30 -04:00
jyvikoandClaude Opus 5.5 a0b4a69452 Mesh: the swept cross-section's quad mesh as its own module
The schemes, interval constraints, curve nodes and region meshes of a
multi-level sweep's cross-section move out of layered::mesh into
hex::section, with the curve placement (seeds, projection onto walls)
passed in, so the cross-section can be meshed on its own.
region::mesh_structured gives a scheme's mesh or None where it would fold,
without falling back to the free mesher. No change in behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:17:30 -04:00
jyvikoandClaude Opus 5.5 c83b803f63 web: the deployed browser build carries the PostHog key (#305)
Pages builds main with the repository secret POSTHOG_KEY, so web users are asked
the same consent question as desktop users; develop builds stay keyless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:13:55 -04:00
jyvikoandClaude Opus 5.5 db80b75814 Docs: privacy.md lists every usage event; release builds get the key (#238)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 31bc886c7a Web: usage through fetch, preferences in local storage (#238)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 ed9ec7748d App: send usage batches to PostHog Cloud EU from a background thread (#238)
ureq over rustls (ring) with the OS certificate verifier. The project key
is the build-time FIELDCRAFT_POSTHOG_KEY; without it nothing is asked or
sent. FIELDCRAFT_TELEMETRY=0 turns it off; --control and CI runs only with
FIELDCRAFT_TELEMETRY=1. A failed post drops its batch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 79d583ea0f UI: ask once about anonymous usage; Help › Settings › Privacy (#238)
The first run asks whether to share anonymous usage (only when the host
says this run may), the answer and a random install id are kept in the
preferences, and Help › Settings… changes it. Commands are counted by
where they came from (ui, palette, script; mcp when the MCP server says
so), and cancelled forms and clicks on commands that cannot run yet are
recorded. The preferences go through a PrefsStore (a file, or the
browser's storage). Control channel: ui.settings, ui.prompt answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 162bb421f1 Engine: anonymous usage events, counted in Session::execute (#238)
fieldcraft_engine::usage holds the events docs/privacy.md lists, typed so
that only registry names (command ids, sample names, requirements) and
durations can go in them, a bounded queue that records nothing until the
host enables it, and the PostHog batch body. Session::execute counts each
top-level command of a session with an origin (ui, palette, script, mcp):
its id, kind, duration and error class, and the funnel's milestones and
opened samples. Nothing here touches the network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 54f50f9518 Gallery: every example image captured again on the current build
All six docs/media/examples images at 1400 x 860 in the light theme, the
solved sample in the home view (the crank mirror from below, as its text
says), with the wireframe symbols, no SETUP card and the crank's planes
hidden; the Start card thumbnails cropped to the model from them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:01:43 -04:00
jyvikoandClaude Opus 5.5 a0d11f1c22 Partitions hide their datum plane
geometry.partition hides the plane it cuts by (view state, saved with the
model): the cut shows as edges on the cells. The eye or selecting it in
the browser shows it again. The crank samples so open without their
planes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:01:43 -04:00
jyvikoandClaude Opus 5.5 dddb2d0584 Datums: drawn at the model's extent, never framed, the selected one shown
A datum plane is drawn as the model's extent within it (where it cuts the
model's box, in the plane's axes) plus a 5 % margin, a datum axis along the
model's extent plus the margin, instead of squares 1.2 diagonals wide.
Fit, Home, the standard views and headless pictures frame the model
without the datums (they stay inside the clipping radius). The datum
selected in the browser is drawn highlighted and on top, even when hidden.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:01:43 -04:00
jyvikoandClaude Opus 5.5 b19277ae7a Docs: crash reports, the log file, Report a Bug and privacy (#107)
docs/crash-reports.md: what is kept where, what a bug report carries
(and only when ticked), the CLI and commands for agents; README's
privacy note; the control protocol's new prompt answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 e06c85eb9e App: crash reports and a log file; Help › Report a Bug (#107)
The desktop app installs the crash reporter and a log file at start
(both in a temporary folder in --control and CI runs, #266), journals
the window's commands (background jobs included) and every control
request's method, and ends the journal on a clean exit. A start after a
crash asks: "FieldCraft closed unexpectedly", Report It… or Not Now.

Help › Report a Bug (also Tools › Help and ui.start
diagnostics.bug_report) shows exactly what the GitHub bug form will be
filled with: the version, the OS, the last error, and for a crash where
it happened. Share my session adds the replayable commands, Include the
model file the model. Open GitHub Issue opens the form in the browser
through the system's opener; files to attach are saved to
bug-reports/<time>/ and a long session goes on the clipboard. Nothing is
sent without that click and the user's submit on GitHub.

The control channel answers the new prompts (crashed: report, close;
report_bug: set, close) and ui.inspect shows the draft; it never opens
the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 cb7e3a2711 CLI: fieldcraft-cli crashes [list|show|replay|dir|clear] (#107)
Lists, shows, replays and deletes the crash reports the desktop app
wrote. A replay opens the report's model, runs its commands with writes
confined to a scratch folder, and says whether the same internal error
happens again. Adapted from SolidCraft's solidcraft-cli crashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 080ff048c6 Engine: crash reports, a log file and bug report drafts (#107)
crash: a panic hook and a locked per-run command journal (adapted from
SolidCraft's crash reports). A panic in a command becomes a report with
the model from before it and the command; one outside commands, or an
unclean exit found at the next start (abort, segfault, a crash in a
graphics driver, a kill: what #248 needs), a report with the model the
journal starts from (autosave, file or a copy) and the commands since,
the last control request and the dead run's log lines. Reports are
bounded, deduplicated by signature and replayable (crash::replay, with
writes confined to a scratch folder). The crash folder follows the
automation temp area in --control and CI runs.

logfile: a small size-rotated file logger behind the log facade.

bug_report: GitHub bug-form drafts. Version, OS and what happened by
default, home folder shown as ~; the command journal only with Share my
session, the model only with Include the model as well; a session too
long for the link becomes a file to attach and the clipboard text.

Commands: diagnostics.crash_reports, diagnostics.crash_report,
diagnostics.bug_report (Tools › Help, with its icon) and
diagnostics.crash_test (FIELDCRAFT_CRASH_TEST=1 only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 3d51bde9dd io: the app's data folder, and confining writes alone
recovery::data_dir() names the per-user data folder (the temporary
fieldcraft-automation folder in automated runs) that the recovery, crash
and log folders live in. Roots::writes_within lets reads go anywhere
while writes stay in one folder, for replaying a crash report safely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 d3ed8ffb05 Start card: every sample as a card with its thumbnail, flagship first, scrolling (#245)
The Start card and File › Samples show a grid of sample cards (thumbnail, name,
one-line description, the full text on hover) in a scroll area with a solid
scrollbar; Help › Samples keeps rows in the same order. The card stays clear of
the view cube and the navigation bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:06:20 -04:00
jyvikoandClaude Opus 5.5 072139353f Samples: 320 px thumbnails cropped from the gallery captures
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:06:20 -04:00
jyvikoandClaude Opus 5.5 08f669acad Browser and viewport: item menu, per-item eyes, Delete key with confirmation
Right-click on any browser item (body, surface, datum, partition, set,
material, section, step, boundary condition, load, reference point,
coupling, contact, fluid domain) opens its menu: Edit…, Hide/Show,
Isolate, Show All, Active in step (boundary conditions and loads) and
Delete…. A right click on a datum or a partition's cut face in the
viewport opens the same menu. Each item the viewport draws on its own
has an eye; hidden items are neither drawn nor picked. Datums and
partitions are selectable with properties. Delete… and the Delete key
ask first (the prompt lists what uses the item: a datum's partitions
are deleted with it, other definitions in use are refused); ui.prompt
answers it. Every entry runs the same command as the ribbon and forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 d7ec7f486a View state: hide, show and isolate viewport items, saved with the model
view.hide, view.show, view.isolate and view.show_all change which
bodies, surfaces, datums, boundary conditions, loads, reference points
and couplings the viewport draws. The hidden items are view state: the
manifest's `view` keeps them, a change marks the model unsaved, but it
is neither journalled nor undone and leaves results current. Items that
go away are forgotten. Headless pictures leave hidden items out; the
glyph builders take a filter. Tools > View > Show All claims the
commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 d9824de4a5 Engine: geometry.datum.point; planes and axes through datum points; datum edits and cascading delete
A datum point by coordinates, at a mesh vertex, a fraction along a
design edge, at a face's centre, or where a datum axis crosses a datum
plane. Datum planes take three datum points or a normal to a datum axis;
axes take two datum points. geometry.datum.edit, .axis.edit and
.point.edit redefine a datum of their kind (partitions cut again);
geometry.datum.delete with cascade also deletes the partitions that cut
by it. The ribbon shows Datum Plane, Datum Axis, Datum Point and
Partition, each with its own icon; edit and delete leave the ribbon
(still commands, claimed by their entries).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 fbaba5fecd Geometry: a face's area centroid and a point a fraction along an edge
Shape::face_centre and Edge::point_at place datum points on a design's
named faces and edges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 0bf150633c Model: datum points, drawn as a small cross; each definition's users are public
Datum::Point joins planes and axes (checked like them, refused by
partitions with the kind named). The users each remove_* refuses with
(sets, materials, boundary conditions, loads, reference points, fluid
domains, datums) are public functions, so a caller can list them before
deleting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
256 changed files with 27037 additions and 15212 deletions

No files matched your search

+11
View File
@@ -1,2 +1,13 @@
# Every change to FieldCraft needs the maintainer's review before it merges.
* @jyviko
# Release and supply-chain paths, named explicitly so they stay owner-reviewed if the rule above
# is ever relaxed: workflows and secrets use, packaging and signing, the updater, dependencies,
# licences.
/.github/ @jyviko
/packaging/ @jyviko
/crates/update/ @jyviko
/Cargo.toml @jyviko
/Cargo.lock @jyviko
/ATTRIBUTION.md @jyviko
/deny.toml @jyviko
+1 -1
View File
@@ -41,6 +41,6 @@ body:
id: version
attributes:
label: Version and platform
placeholder: "v0.5.8 (or commit), macOS 15 arm64"
placeholder: "v0.6.0 (or commit), macOS 15 arm64"
validations:
required: true
+2
View File
@@ -21,6 +21,8 @@ modal problems with its own solver. AI agents can drive it over MCP (`fieldcraft
To start with a sample model, run the app with `--sample cantilever` (macOS:
`/Applications/FieldCraft.app/Contents/MacOS/FieldCraft --sample cantilever`).
**Updates.** {update_signing}
**Signing.** {macos_signing} The Linux and Windows builds are not signed; on Windows, SmartScreen
may say "Windows protected your PC": choose **More info**, then **Run anyway**.
+88 -16
View File
@@ -6,6 +6,13 @@ name: CI
# Pull requests from forks (outside contributors) run the full gate, once the maintainer approves
# the run, so the review sees it; so do Dependabot's (.github/dependabot.yml), which nobody tests
# locally. The heavy job stays off pull requests.
#
# What runs when (docs/releasing.md, "What CI runs when"): the `plan` job picks a base, the last
# `develop` commit whose CI run passed (a pull request: its merge base; nightly and manual runs:
# none), and `cargo xtask affected` maps the change since it to crates. `cargo xtask ci --affected`
# then lints and tests those crates and their dependents only; the heavy and oracle jobs run when
# the change reaches the solvers, the oracle or everything (Cargo.toml/Cargo.lock/xtask/workflows).
# Nightly and manual runs, and every release (release.yml), run all of it.
on:
pull_request:
paths:
@@ -26,7 +33,7 @@ on:
- 'docs/features.md'
- 'docs/oracle.md'
schedule:
# Nightly, on the default branch (develop): the heavy tests.
# Nightly, on the default branch (develop): the whole gate, the heavy tests and the oracle.
- cron: '23 3 * * *'
# Weekly: the oracle on macOS too, so results that differ by platform show up in CI (the
# fixtures are often blessed on a Mac; #115).
@@ -37,7 +44,8 @@ permissions:
contents: read
# A newer merge cancels the run still going for the one before it, so a burst of merges is tested
# once, at the tip. Nightly and manual runs are grouped apart and never cancelled by a merge.
# once, at the tip; nothing is missed, since the tip's run tests everything since the last green
# run. Nightly and manual runs are grouped apart and never cancelled by a merge.
concurrency:
group: ci-${{ github.ref }}-${{ github.event_name }}
cancel-in-progress: ${{ github.event_name == 'push' || github.event_name == 'pull_request' }}
@@ -46,13 +54,75 @@ env:
CARGO_TERM_COLOR: always
jobs:
plan:
name: Plan (affected crates)
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
runs-on: ubuntu-24.04
timeout-minutes: 15
permissions:
contents: read
# To find the last green run on develop.
actions: read
outputs:
base: ${{ steps.base.outputs.base }}
everything: ${{ steps.affected.outputs.everything }}
solver: ${{ steps.affected.outputs.solver }}
wasm: ${{ steps.affected.outputs.wasm }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: plan
save-if: ${{ github.ref == 'refs/heads/develop' }}
- name: Pick the base
id: base
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
EVENT: ${{ github.event_name }}
PR_BASE: ${{ github.base_ref }}
run: |
base=""
case "$EVENT" in
push)
# The newest develop commit whose push run passed and that this commit contains.
# Runs that were cancelled or failed are skipped, so their changes are tested here.
for sha in $(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/ci.yml/runs?branch=develop&event=push&status=success&per_page=100" --jq '.workflow_runs[].head_sha'); do
if [ "$sha" != "$GITHUB_SHA" ] && git merge-base --is-ancestor "$sha" HEAD; then
base="$sha"
break
fi
done
;;
pull_request)
base="$(git merge-base "origin/$PR_BASE" HEAD || true)"
;;
esac
# Nightly and manual runs, or no green run to start from: everything.
echo "base=$base" >>"$GITHUB_OUTPUT"
echo "### Base: \`${base:-none (everything)}\`" >>"$GITHUB_STEP_SUMMARY"
- name: cargo xtask affected
id: affected
env:
BASE: ${{ steps.base.outputs.base }}
run: |
if [ -n "$BASE" ]; then
cargo xtask affected --base "$BASE" --github-output | tee -a "$GITHUB_STEP_SUMMARY"
else
printf 'everything=true\nsolver=true\nwasm=true\n' >>"$GITHUB_OUTPUT"
fi
ci:
name: cargo xtask ci
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
needs: plan
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
@@ -60,18 +130,18 @@ jobs:
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
save-if: ${{ github.ref == 'refs/heads/develop' }}
# A dependency update changes THIRD-PARTY-LICENSES.txt, which Dependabot cannot regenerate:
# regenerate it here so the gate checks everything else, and dependabot-licences.yml commits
# it to the pull request.
- name: Regenerate THIRD-PARTY-LICENSES.txt (Dependabot)
if: github.event.pull_request.user.login == 'dependabot[bot]'
run: cargo xtask licences
- run: cargo xtask ci
- name: cargo xtask ci (the affected crates, or everything)
env:
BASE: ${{ needs.plan.outputs.base }}
run: |
if [ -n "$BASE" ]; then cargo xtask ci --affected "$BASE"; else cargo xtask ci; fi
heavy:
# The heavy verification and corpus tests (#[ignore]d) and the doc tests.
# The heavy verification and corpus tests (#[ignore]d) and the doc tests, when the change
# reaches them.
name: cargo xtask test --heavy
if: github.event.schedule != '41 4 * * 0' && github.event_name != 'pull_request'
needs: plan
if: github.event_name != 'pull_request' && (needs.plan.outputs.solver == 'true' || needs.plan.outputs.everything == 'true')
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
@@ -85,9 +155,11 @@ jobs:
oracle:
# Verification and validation (docs/verification.md): every case against its reference and
# its fixture, and docs/oracle.md must be the table the cases produce. Cases marked `slow`
# run here too while the whole set stays within a few minutes; `--quick` skips them.
# run here too while the whole set stays within a few minutes; `--quick` skips them. It runs
# when the change reaches the solvers or the oracle's package.
name: cargo xtask oracle
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
needs: plan
if: needs.plan.outputs.solver == 'true' || needs.plan.outputs.everything == 'true'
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
@@ -120,7 +192,7 @@ jobs:
run: git diff --exit-code docs/oracle.md
advisories:
name: Dependency advisories and sources
name: Dependency licences, advisories and sources
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
runs-on: ubuntu-24.04
timeout-minutes: 20
@@ -129,4 +201,4 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
- name: Install cargo-deny
run: cargo install cargo-deny --version 0.20.2 --locked
- run: cargo deny --locked check --warn unmaintained advisories bans sources
- run: cargo deny --locked check --warn unmaintained advisories bans licenses sources
-40
View File
@@ -1,40 +0,0 @@
# Dependabot's Cargo updates change THIRD-PARTY-LICENSES.txt (`cargo xtask licences`), which
# Dependabot cannot regenerate: this commits the regenerated file to its pull request. CI's own
# run on the pull request regenerates it too, so its result covers everything else.
name: Dependabot licences
on:
pull_request:
branches: [develop]
paths: [Cargo.lock]
permissions:
contents: write
concurrency:
group: dependabot-licences-${{ github.head_ref }}
cancel-in-progress: true
jobs:
licences:
if: github.event.pull_request.user.login == 'dependabot[bot]'
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.head_ref }}
- uses: dtolnay/rust-toolchain@stable
- run: cargo xtask licences
- name: Commit the regenerated file
run: |
if git diff --quiet -- THIRD-PARTY-LICENSES.txt; then
echo "THIRD-PARTY-LICENSES.txt is up to date"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
# [skip ci]: the pull request's CI run already regenerated this file and tested the
# tree with it; a bot-authored commit would otherwise wait for a maintainer's approval.
git commit -m "deps: regenerate THIRD-PARTY-LICENSES.txt [skip ci]" -- THIRD-PARTY-LICENSES.txt
git push origin "HEAD:${GITHUB_HEAD_REF}"
+8
View File
@@ -33,6 +33,10 @@ env:
jobs:
build:
# POSTHOG_KEY lives in the `release` environment (main only, docs/releasing.md). The deploy job
# already uses github-pages and a job has one environment, so the build job reads the key: on
# main it runs in `release`, elsewhere in no environment and with an empty key.
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
@@ -53,6 +57,10 @@ jobs:
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: Build the web app
working-directory: apps/fieldcraft-web
env:
# Usage analytics only in the deployed build (main), and only with the user's consent
# (docs/privacy.md); develop builds get an empty key, which sends nothing.
FIELDCRAFT_POSTHOG_KEY: ${{ github.ref == 'refs/heads/main' && secrets.POSTHOG_KEY || '' }}
run: trunk build --release --public-url /fieldcraft/
- name: Bundle size
run: |
+131 -10
View File
@@ -3,10 +3,12 @@
#
# A push to `main` (fast-forwarded from a verified `develop` commit; main holds released code only)
# builds every package and creates or updates the
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt and generated notes. The
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt (signed with the release key
# into SHA256SUMS.txt.minisig when the FIELDCRAFT_SIGNING_KEY secret exists) and generated notes. The
# version is [workspace.package] version in Cargo.toml; a suffix (0.2.0-rc.1) makes a
# pre-release. A person verifies the draft and publishes it; this workflow never publishes,
# and pushes to develop or tags never start it.
# pre-release. Every package, and the release itself, carries THIRD-PARTY-LICENSES.txt, generated
# here by `cargo xtask licences` (it is not committed). A person verifies the draft and publishes
# it; this workflow never publishes, and pushes to develop or tags never start it.
#
# macOS universal (arm64 + x86_64) .dmg with FieldCraft.app, the CLI as a .zip packaging/macos
# Linux x86_64 (glibc 2.35+) .tar.gz, .AppImage, .deb and .rpm packaging/linux
@@ -15,7 +17,11 @@
# macOS: signed with a Developer ID and notarized when the APPLE_* secrets exist, ad-hoc
# otherwise (the release notes say which). Linux and Windows builds are not signed.
#
# Dry run: `gh workflow run release.yml --ref <branch>` builds everything and uploads the
# Before anything is packaged, the verify jobs run everything CI can: the full `cargo xtask ci`,
# `cargo xtask test --heavy` and `cargo xtask oracle` on Linux, and the oracle on macOS. Develop's
# CI tests only what each change affects (ci.yml), so this is where a release proves all of it.
#
# Dry run: `gh workflow run release.yml --ref <branch>` verifies and builds everything and uploads the
# `release-assets` artifact without creating a release. `-f draft=true` on `main` retries
# the draft.
name: Release
@@ -69,9 +75,65 @@ jobs:
{ echo "version=$VERSION"; echo "prerelease=$pre"; echo "draft=$REQUEST_DRAFT"; } >>"$GITHUB_OUTPUT"
echo "### FieldCraft v$VERSION (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
# The full gate, the heavy tests and the oracle on Linux and macOS: every packaging job needs
# them, so a release (or a dry run) never builds from a commit that fails any of them.
verify-ci:
name: Verify (cargo xtask ci)
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo xtask ci
verify-heavy:
name: Verify (cargo xtask test --heavy)
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo xtask test --heavy
verify-oracle:
name: Verify (cargo xtask oracle, ${{ matrix.os }})
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-24.04
cache: release-oracle-linux
- os: macos-14
cache: release-oracle-macos
runs-on: ${{ matrix.os }}
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: ${{ matrix.cache }}
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo xtask oracle
- name: docs/oracle.md is current
run: git diff --exit-code docs/oracle.md
macos:
name: macOS universal
needs: version
needs: [version, verify-ci, verify-heavy, verify-oracle]
# Signing, notarization and analytics secrets live in the `release` environment, which only
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
runs-on: macos-14
timeout-minutes: 120
outputs:
@@ -88,6 +150,8 @@ jobs:
key: release-macos-universal
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Generate THIRD-PARTY-LICENSES.txt (fails when a crate's licence can't be resolved)
run: cargo xtask licences
- name: Import the signing certificate (skipped without APPLE_CERTIFICATE)
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
@@ -97,6 +161,8 @@ jobs:
- name: Build, sign, notarize and package (the dmg is mounted and checked)
id: package
env:
# The analytics project key (docs/privacy.md), built in; never printed.
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
@@ -113,8 +179,11 @@ jobs:
linux:
name: Linux x86_64
needs: version
needs: [version, verify-ci, verify-heavy, verify-oracle]
# The oldest GitHub-hosted image, so the binaries need only glibc >= 2.35.
# Signing, notarization and analytics secrets live in the `release` environment, which only
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
@@ -134,11 +203,16 @@ jobs:
key: release-linux-x86_64
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Generate THIRD-PARTY-LICENSES.txt (fails when a crate's licence can't be resolved)
run: cargo xtask licences
- name: Install cargo-deb and cargo-generate-rpm
run: |
cargo install --locked --version "$CARGO_DEB_VERSION" cargo-deb
cargo install --locked --version "$CARGO_GENERATE_RPM_VERSION" cargo-generate-rpm
- name: Build and package (tar.gz, AppImage, deb, rpm)
env:
# The analytics project key (docs/privacy.md), built in; never printed.
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
run: packaging/linux/package.sh
- name: Check the packages
run: |
@@ -194,7 +268,10 @@ jobs:
windows:
name: Windows x64
needs: version
needs: [version, verify-ci, verify-heavy, verify-oracle]
# Signing, notarization and analytics secrets live in the `release` environment, which only
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
runs-on: windows-latest
timeout-minutes: 90
env:
@@ -209,8 +286,13 @@ jobs:
key: release-windows-x64
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Generate THIRD-PARTY-LICENSES.txt (fails when a crate's licence can't be resolved)
run: cargo xtask licences
- name: Build and package (zip)
shell: pwsh
env:
# The analytics project key (docs/privacy.md), built in; never printed.
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
run: ./packaging/windows/package.ps1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -221,6 +303,9 @@ jobs:
release:
name: Draft release (or dry-run artifacts)
needs: [version, macos, linux, windows]
# Signing, notarization and analytics secrets live in the `release` environment, which only
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
runs-on: ubuntu-24.04
permissions:
contents: write
@@ -237,22 +322,58 @@ jobs:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Check the set, checksums and notes
- uses: dtolnay/rust-toolchain@stable
# The same file every package carries, attached to the release on its own.
- name: Generate THIRD-PARTY-LICENSES.txt
run: cargo xtask licences && cp THIRD-PARTY-LICENSES.txt artifacts/
- name: Check the set and write the checksums
run: |
for f in "fieldcraft-$VERSION-macos-universal.dmg" "fieldcraft-cli-$VERSION-macos-universal.zip" \
"fieldcraft-$VERSION-linux-x86_64.tar.gz" "fieldcraft-$VERSION-linux-x86_64.AppImage" \
"fieldcraft_${VERSION}_amd64.deb" "fieldcraft-$VERSION.x86_64.rpm" \
"fieldcraft-$VERSION-windows-x64.zip"; do
"fieldcraft-$VERSION-windows-x64.zip" THIRD-PARTY-LICENSES.txt; do
test -s "artifacts/$f" || { echo "::error::missing $f"; exit 1; }
done
(cd artifacts && sha256sum -- * | tee SHA256SUMS.txt)
- name: Sign SHA256SUMS.txt with the release key (skipped without FIELDCRAFT_SIGNING_KEY)
id: sign
env:
FIELDCRAFT_SIGNING_KEY: ${{ secrets.FIELDCRAFT_SIGNING_KEY }}
# rsign2 (MIT), a minisign-compatible signer, pinned.
RSIGN_VERSION: 0.6.7
run: |
if [ -z "$FIELDCRAFT_SIGNING_KEY" ]; then
echo "::warning::FIELDCRAFT_SIGNING_KEY is not set: SHA256SUMS.txt is not signed, so the app cannot install this release itself (docs/releasing.md)"
echo "signed=false" >>"$GITHUB_OUTPUT"
exit 0
fi
cargo install --locked --quiet --root "$RUNNER_TEMP/rsign" rsign2 --version "$RSIGN_VERSION"
rsign="$RUNNER_TEMP/rsign/bin/rsign"
key="$RUNNER_TEMP/release.key"
(umask 077 && printf '%s\n' "$FIELDCRAFT_SIGNING_KEY" >"$key")
"$rsign" sign -W -s "$key" -t "FieldCraft v$VERSION SHA256SUMS.txt" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
rm -f "$key"
# The signature must verify with the public key the app is built with.
public="$(sed -n 's/^pub const PUBLIC_KEY: &str = "\(.*\)";$/\1/p' crates/update/src/lib.rs)"
"$rsign" verify -q -P "$public" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
echo "signed=true" >>"$GITHUB_OUTPUT"
- name: Write the notes
env:
SIGNED: ${{ steps.sign.outputs.signed }}
run: |
# The macOS paragraph says how the app was signed (packaging/macos/package.sh).
case "$MACOS_SIGNING" in
notarized) macos="The macOS app is signed with a Developer ID and notarized by Apple." ;;
signed) macos="The macOS app is signed with a Developer ID but **not notarized**: the first time, right-click \`FieldCraft.app\` in Applications and choose **Open**." ;;
*) macos="The macOS app is **ad-hoc signed and not notarized**: macOS blocks the first launch. Right-click \`FieldCraft.app\` in Applications and choose **Open** (then **Open** again), or run \`xattr -dr com.apple.quarantine /Applications/FieldCraft.app\`." ;;
esac
awk -v v="$VERSION" -v m="$macos" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); print }' \
# The updates paragraph says whether the app can install this release itself.
if [ "$SIGNED" = true ]; then
updates="\`SHA256SUMS.txt\` is signed with the FieldCraft release key (\`SHA256SUMS.txt.minisig\`), so FieldCraft's Help › Check for Updates can verify and install this release."
else
updates="This release's \`SHA256SUMS.txt\` is **not signed**: FieldCraft's in-app updates can't verify it and won't install it; download it from this page instead."
fi
awk -v v="$VERSION" -v m="$macos" -v u="$updates" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); gsub(/\{update_signing\}/, u); print }' \
.github/release-notes.md >notes.md
cat notes.md >>"$GITHUB_STEP_SUMMARY"
- name: Upload the dry-run artifacts
+1
View File
@@ -7,3 +7,4 @@
.DS_Store
*.swp
__pycache__/
/THIRD-PARTY-LICENSES.txt
+10 -5
View File
@@ -119,17 +119,22 @@ People trust FieldCraft with their models; a crash loses their work. **This outr
contributors' pull requests wait for the maintainer's review (CONTRIBUTING.md). Never squash.
Then remove your worktree and delete your local branch.
5. Never run the full gate locally: no `cargo xtask ci`, no `cargo clippy --workspace`, no
`cargo xtask wasm` or `oracle` unless step 2 calls for it. Never watch CI. GitHub CI runs
`cargo xtask ci` (fmt, assets, licences, layers, clippy -D warnings, tests, wasm), the
oracle, the heavy tests and the advisories once per merge on `develop`; the coordinator
`cargo xtask wasm` or `oracle` unless step 2 calls for it. Never watch CI. GitHub CI runs,
per merge on `develop`, `cargo xtask ci --affected <last green commit>` (fmt, assets,
layers on the whole tree; clippy and tests on the crates the change reaches; wasm when one
of them builds for it), the oracle and heavy tests when the change reaches the solvers or
the oracle, and the dependency licences and advisories; a change to Cargo.toml, Cargo.lock,
xtask or the workflows, the nightly run and every release run all of it (docs/releasing.md,
"What CI runs when"). `cargo xtask affected --base origin/develop` shows what your branch
reaches. The coordinator
watches it and sends a failure back to the change that caused it, which is fixed forward
at once.
- **Keep the trunk gate fast** (under ~3 minutes on CI). A test that takes more than a few seconds
(convergence studies, the whole corpus, cross-checks between solvers) is
`#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]`, with a fast representative
test left in the trunk gate. The `heavy` CI job runs `cargo xtask test --heavy` (every ignored
test, benchmarks included, and the doc tests) on every merge to `develop`, nightly and on
demand (`gh workflow run CI --ref <branch>`). Hostile-input tests run commands on sessions with small
test, benchmarks included, and the doc tests) on merges to `develop` that reach a crate with
heavy tests, nightly, before every release and on demand (`gh workflow run CI --ref <branch>`). Hostile-input tests run commands on sessions with small
work caps (`Session::limits`) so refusals are instant; never lower the production caps for a
test.
- **Publishing**: `origin` is github.com/jyviko/fieldcraft. Changes land through pull requests
+26
View File
@@ -24,12 +24,31 @@ is committed and listed here with its exports.
| docs/media/examples/bracket-hex.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved bracket-hex sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/crank-arm.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-arm sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/crank-mirror.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-mirror sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/flow-past.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the flow-past sample (its bracket; the viewport does not draw flow results yet) (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/cantilever.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved cantilever sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/impact.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved impact sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/ibeam.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved ibeam sample (docs/examples.md) | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/ibeam.png | FieldCraft contributors | Original: the solved ibeam sample rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the ibeam sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| docs/media/examples/parts.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the parts sample (meshes only, nothing to solve) (docs/examples.md) | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/flow-past.png | FieldCraft contributors | Original: the flow-past sample as docs/media/examples/flow-past.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the flow-past sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/cantilever.png | FieldCraft contributors | Original: the cantilever sample as docs/media/examples/cantilever.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the cantilever sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/impact.png | FieldCraft contributors | Original: the impact sample as docs/media/examples/impact.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the impact sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/parts.png | FieldCraft contributors | Original: the parts sample as docs/media/examples/parts.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the parts sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/bracket-hex.png | FieldCraft contributors | Original: the bracket-hex sample as docs/media/examples/bracket-hex.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the bracket-hex sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/crank-arm.png | FieldCraft contributors | Original: the crank-arm sample as docs/media/examples/crank-arm.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-arm sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/crank-mirror.png | FieldCraft contributors | Original: the crank-mirror sample as docs/media/examples/crank-mirror.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-mirror sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/drop-test.png | FieldCraft contributors | Original: the drop-test sample as docs/media/examples/drop-test.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the drop-test sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/heated-bracket.png | FieldCraft contributors | Original: the heated-bracket sample as docs/media/examples/heated-bracket.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the heated-bracket sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/rubber-seal.png | FieldCraft contributors | Original: the rubber-seal sample as docs/media/examples/rubber-seal.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the rubber-seal sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/decks/tests/golden/nastran/*.bdf | FieldCraft contributors | Written by our Nastran writer from our own test models (crates/decks/tests/nastran.rs) | MIT OR Apache-2.0 |
| crates/engine/tests/designs/pi5-enclosure.json | FieldCraft contributors | Original SolidCraft recipe (solid.* commands) of an enclosure for a single-board computer, for thermal analysis: base, lid, heat sink, board, chips, connectors and the air inside | MIT OR Apache-2.0 |
| crates/geometry/tests/designs/hollow-box.solidcraft, crates/geometry/tests/designs/hollow-box-post.solidcraft, crates/geometry/tests/designs/open-tray-post.solidcraft | FieldCraft contributors | Built with `solidcraft-cli run` from the recipes beside them (crates/geometry/tests/designs/*.json) | MIT OR Apache-2.0 |
| assets/icons/assembly.instance.svg, assets/icons/assembly.instance.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/assembly.instance.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.read.svg, assets/icons/deck.read.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.read.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.write.abaqus.svg, assets/icons/deck.write.abaqus.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.abaqus.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.write.lsdyna.svg, assets/icons/deck.write.lsdyna.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.lsdyna.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.write.nastran.svg, assets/icons/deck.write.nastran.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.nastran.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/diagnostics.bug_report.svg, assets/icons/diagnostics.bug_report.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/diagnostics.bug_report.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/edit.redo.svg, assets/icons/edit.redo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.redo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/edit.undo.svg, assets/icons/edit.undo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.undo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/file.open.svg, assets/icons/file.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -38,6 +57,8 @@ is committed and listed here with its exports.
| assets/icons/file.save.svg, assets/icons/file.save.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.save.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.bodies.svg, assets/icons/geometry.bodies.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.bodies.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.datum.svg, assets/icons/geometry.datum.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.datum.axis.svg, assets/icons/geometry.datum.axis.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.axis.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.datum.point.svg, assets/icons/geometry.datum.point.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.point.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.import.mesh.svg, assets/icons/geometry.import.mesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.import.mesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.midsurface.svg, assets/icons/geometry.midsurface.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.midsurface.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.open.svg, assets/icons/geometry.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -49,6 +70,8 @@ is committed and listed here with its exports.
| assets/icons/interaction.contact.general.svg, assets/icons/interaction.contact.general.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.contact.general.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/interaction.contact.pair.svg, assets/icons/interaction.contact.pair.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.contact.pair.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/interaction.fsi.svg, assets/icons/interaction.fsi.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.fsi.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.block.svg, assets/icons/mesh.block.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.block.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.mirror.svg, assets/icons/mesh.mirror.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.mirror.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/model.mass.create.svg, assets/icons/model.mass.create.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/model.mass.create.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/interaction.rigid_wall.svg, assets/icons/interaction.rigid_wall.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.rigid_wall.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/model.spring.create.svg, assets/icons/model.spring.create.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/model.spring.create.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -65,6 +88,7 @@ is committed and listed here with its exports.
| assets/icons/mesh.layers.svg, assets/icons/mesh.layers.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.layers.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.node.add.svg, assets/icons/mesh.node.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.node.merge.svg, assets/icons/mesh.node.merge.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.merge.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.node.relax.svg, assets/icons/mesh.node.relax.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.relax.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.order.quadratic.svg, assets/icons/mesh.order.quadratic.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.order.quadratic.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.quad.faces.svg, assets/icons/mesh.quad.faces.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.quad.faces.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.quality.svg, assets/icons/mesh.quality.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.quality.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -141,6 +165,7 @@ is committed and listed here with its exports.
| assets/icons/ui.sun.svg, assets/icons/ui.sun.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.sun.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/ui.views.svg, assets/icons/ui.views.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.views.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/ui.zoom.svg, assets/icons/ui.zoom.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.zoom.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/view.show_all.svg, assets/icons/view.show_all.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/view.show_all.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/app-icon/icon.vectorcraft, assets/app-icon/icon.svg, assets/app-icon/icon.png | FieldCraft contributors | Original application icon (a hexahedral-meshed cube with a banded colour fringe on its faces on a rounded-square backdrop), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs); editable source, SVG and 1024 × 1024 PNG export | MIT OR Apache-2.0 |
| assets/app-icon/icon-small.vectorcraft, assets/app-icon/icon-small.svg, assets/app-icon/icon-small.png | FieldCraft contributors | Original simplified application icon for 16–32 px (the fringe cube alone; no mesh or floor grid), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
| assets/app-icon/layers/01-floor.vectorcraft, assets/app-icon/FieldCraft.icon/Assets/01-floor.svg | FieldCraft contributors | Original isometric floor grid with a radial fade (Default appearance), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
@@ -177,6 +202,7 @@ is committed and listed here with its exports.
| crates/ui-egui/src/fields.rs (form rows: a label column of fixed width, then the field) | SolidCraft `crates/ui-egui/src/dialogs.rs` | MIT OR Apache-2.0 |
| crates/io/src/fs.rs (atomic writes) | SolidCraft `crates/io/src/safe_write.rs` | MIT OR Apache-2.0 |
| crates/io/src/recovery.rs (recovery folder, entries, locks) | SolidCraft `crates/engine/src/recovery.rs` | MIT OR Apache-2.0 |
| crates/engine/src/crash.rs, crates/engine/src/crash_tests.rs (crash reports: panic hook, locked command journal, unclean-exit detection, report folders and limits, replay), apps/fieldcraft-cli/src/crashes.rs, docs/crash-reports.md (structure) | SolidCraft `crates/engine/src/crash.rs`, `crash_tests.rs`, `apps/solidcraft-cli/src/crashes.rs`, `docs/crash-reports.md` | MIT OR Apache-2.0 |
| apps/fieldcraft/src/control_server.rs | SolidCraft `apps/solidcraft/src/control_server.rs` | MIT OR Apache-2.0 |
| crates/mcp/src/ (JSON-RPC framing, MCP lifecycle, tool schema checks, the control-channel backend, base64) | SolidCraft `crates/mcp/src/` | MIT OR Apache-2.0 |
| crates/io/src/roots.rs (the rules of read and write roots) | VectorCraft's automation roots (docs/mcp.md there) | MIT OR Apache-2.0 |
Generated
+462 -49
View File
@@ -431,6 +431,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -661,6 +667,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -731,6 +747,16 @@ dependencies = [
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -744,7 +770,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation 0.9.4",
"core-graphics-types",
"foreign-types",
"libc",
@@ -757,7 +783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation 0.9.4",
"libc",
]
@@ -846,6 +872,12 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "ct-codecs"
version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd"
[[package]]
name = "cursor-icon"
version = "1.2.0"
@@ -890,6 +922,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer 0.10.4",
"crypto-common 0.1.7",
"subtle",
]
[[package]]
@@ -1019,7 +1052,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.36.2"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"ahash",
"bytemuck",
@@ -1170,7 +1203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -1237,7 +1270,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
[[package]]
name = "fieldcraft"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"eframe",
"egui",
@@ -1245,24 +1278,29 @@ dependencies = [
"fieldcraft-engine",
"fieldcraft-io",
"fieldcraft-ui-egui",
"fieldcraft-update",
"getrandom 0.3.4",
"log",
"rfd",
"rustls",
"serde_json",
"ureq",
]
[[package]]
name = "fieldcraft-cli"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-engine",
"fieldcraft-io",
"fieldcraft-mcp",
"fieldcraft-update",
"serde_json",
]
[[package]]
name = "fieldcraft-decks"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-model",
"serde_json",
@@ -1271,7 +1309,7 @@ dependencies = [
[[package]]
name = "fieldcraft-engine"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-decks",
"fieldcraft-explicit",
@@ -1284,17 +1322,18 @@ dependencies = [
"fieldcraft-parallel",
"fieldcraft-render",
"fieldcraft-solver",
"fieldcraft-update",
"log",
"png",
"serde",
"serde_json",
"thiserror 2.0.21",
"zip",
"zip 9.0.3",
]
[[package]]
name = "fieldcraft-explicit"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-fem",
"fieldcraft-model",
@@ -1305,7 +1344,7 @@ dependencies = [
[[package]]
name = "fieldcraft-fem"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-model",
"thiserror 2.0.21",
@@ -1313,10 +1352,10 @@ dependencies = [
[[package]]
name = "fieldcraft-geometry"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-model",
"quick-xml",
"quick-xml 0.42.0",
"serde_json",
"solidcraft-doc",
"solidcraft-engine",
@@ -1324,12 +1363,12 @@ dependencies = [
"solidcraft-io",
"solidcraft-kernel",
"thiserror 2.0.21",
"zip",
"zip 9.0.3",
]
[[package]]
name = "fieldcraft-io"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-model",
"log",
@@ -1337,12 +1376,12 @@ dependencies = [
"serde_json",
"sha2 0.11.1",
"thiserror 2.0.21",
"zip",
"zip 9.0.3",
]
[[package]]
name = "fieldcraft-lbm"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-mesh",
"fieldcraft-model",
@@ -1352,7 +1391,7 @@ dependencies = [
[[package]]
name = "fieldcraft-mcp"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-engine",
"fieldcraft-io",
@@ -1363,7 +1402,7 @@ dependencies = [
[[package]]
name = "fieldcraft-mesh"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-model",
"num-bigint",
@@ -1375,7 +1414,7 @@ dependencies = [
[[package]]
name = "fieldcraft-model"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"serde",
"serde_json",
@@ -1384,14 +1423,14 @@ dependencies = [
[[package]]
name = "fieldcraft-parallel"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"rayon",
]
[[package]]
name = "fieldcraft-render"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-model",
"png",
@@ -1401,7 +1440,7 @@ dependencies = [
[[package]]
name = "fieldcraft-solver"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-fem",
"fieldcraft-mesh",
@@ -1413,7 +1452,7 @@ dependencies = [
[[package]]
name = "fieldcraft-testkit"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"fieldcraft-engine",
"fieldcraft-geometry",
@@ -1424,7 +1463,7 @@ dependencies = [
[[package]]
name = "fieldcraft-ui-egui"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"craft-ui",
"egui",
@@ -1435,17 +1474,36 @@ dependencies = [
"fieldcraft-geometry",
"fieldcraft-model",
"fieldcraft-render",
"fieldcraft-update",
"log",
"png",
"resvg",
"serde",
"serde_json",
]
[[package]]
name = "fieldcraft-web"
version = "0.5.8"
name = "fieldcraft-update"
version = "0.6.0"
dependencies = [
"base64",
"flate2",
"log",
"minisign",
"minisign-verify",
"rustls",
"serde_json",
"sha2 0.11.1",
"tar",
"thiserror 2.0.21",
"ureq",
"zip 9.0.3",
]
[[package]]
name = "fieldcraft-web"
version = "0.6.0"
dependencies = [
"base64 0.22.1",
"eframe",
"egui",
"fieldcraft-engine",
@@ -1460,6 +1518,16 @@ dependencies = [
"web-sys",
]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
@@ -1632,8 +1700,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"wasm-bindgen",
]
[[package]]
@@ -1820,6 +1890,31 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -1885,6 +1980,15 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "itertools"
version = "0.13.0"
@@ -2104,7 +2208,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "matext4cgmath"
version = "0.1.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"cgmath",
"katexit",
@@ -2135,6 +2239,24 @@ dependencies = [
"autocfg",
]
[[package]]
name = "minisign"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aefd422a7a8b5efced01cd7cdf3771e62ebecbc90e3d27695002d3af6af94586"
dependencies = [
"ct-codecs",
"getrandom 0.4.3",
"rpassword",
"scrypt",
]
[[package]]
name = "minisign-verify"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2233,6 +2355,18 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -2627,6 +2761,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -2685,6 +2825,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest 0.10.7",
"hmac",
]
[[package]]
name = "peniko"
version = "0.6.1"
@@ -2949,6 +3099,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -3148,6 +3307,20 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "robust"
version = "1.2.0"
@@ -3163,6 +3336,27 @@ dependencies = [
"memchr",
]
[[package]]
name = "rpassword"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
dependencies = [
"libc",
"rtoolbox",
"windows-sys 0.61.2",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3207,7 +3401,81 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
@@ -3216,6 +3484,15 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "salsa20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
dependencies = [
"cipher",
]
[[package]]
name = "same-file"
version = "1.0.6"
@@ -3225,6 +3502,15 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
@@ -3237,6 +3523,40 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scrypt"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"
dependencies = [
"pbkdf2",
"salsa20",
"sha2 0.10.9",
]
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "self_cell"
version = "1.3.0"
@@ -3493,7 +3813,7 @@ dependencies = [
[[package]]
name = "solidcraft-doc"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"log",
"serde",
@@ -3510,7 +3830,7 @@ dependencies = [
[[package]]
name = "solidcraft-engine"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"log",
"serde",
@@ -3527,7 +3847,7 @@ dependencies = [
[[package]]
name = "solidcraft-geom"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -3536,9 +3856,9 @@ dependencies = [
[[package]]
name = "solidcraft-io"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"quick-xml",
"quick-xml 0.41.0",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -3546,13 +3866,13 @@ dependencies = [
"solidcraft-geom",
"solidcraft-kernel",
"thiserror 2.0.21",
"zip",
"zip 3.0.0",
]
[[package]]
name = "solidcraft-kernel"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"log",
"rayon",
@@ -3571,9 +3891,10 @@ dependencies = [
[[package]]
name = "solidcraft-render"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"image",
"png",
"serde",
"solidcraft-geom",
]
@@ -3581,7 +3902,7 @@ dependencies = [
[[package]]
name = "solidcraft-sketch"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"serde",
"solidcraft-geom",
@@ -3625,6 +3946,12 @@ dependencies = [
"float-cmp",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "svgtypes"
version = "0.16.1"
@@ -3667,6 +3994,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -3677,7 +4014,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -3913,7 +4250,7 @@ dependencies = [
[[package]]
name = "truck-meshalgo"
version = "0.4.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"array-macro",
"derive_more",
@@ -3963,7 +4300,7 @@ dependencies = [
[[package]]
name = "truck-shapeops"
version = "0.4.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"derive_more",
"itertools 0.13.0",
@@ -3978,7 +4315,7 @@ dependencies = [
[[package]]
name = "truck-stepio"
version = "0.3.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
source = "git+https://github.com/bherbruck/solidcraft?rev=b1695873f5d0031f51a8d5e7ec036fced6f000e2#b1695873f5d0031f51a8d5e7ec036fced6f000e2"
dependencies = [
"chrono",
"truck-geometry",
@@ -4018,6 +4355,12 @@ dependencies = [
"rustc-hash 2.1.3",
]
[[package]]
name = "typed-path"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
[[package]]
name = "typenum"
version = "1.20.1"
@@ -4032,7 +4375,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -4059,6 +4402,40 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
dependencies = [
"base64 0.23.1",
"log",
"percent-encoding",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"ureq-proto",
"utf8-zero",
]
[[package]]
name = "ureq-proto"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
dependencies = [
"base64 0.23.1",
"http",
"httparse",
"log",
]
[[package]]
name = "usvg"
version = "0.48.1"
@@ -4078,6 +4455,12 @@ dependencies = [
"tiny-skia-path",
]
[[package]]
name = "utf8-zero"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
[[package]]
name = "uuid"
version = "1.28.0"
@@ -4342,7 +4725,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
"quick-xml",
"quick-xml 0.41.0",
"quote",
]
@@ -4378,6 +4761,15 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
@@ -4573,7 +4965,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -4866,7 +5258,7 @@ dependencies = [
"calloop 0.13.0",
"cfg_aliases",
"concurrent-queue",
"core-foundation",
"core-foundation 0.9.4",
"core-graphics",
"cursor-icon",
"dpi",
@@ -4918,7 +5310,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
dependencies = [
"cfg-if",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -4992,7 +5384,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.5.8"
version = "0.6.0"
dependencies = [
"serde_json",
]
@@ -5123,6 +5515,12 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]]
name = "zip"
version = "3.0.0"
@@ -5137,6 +5535,21 @@ dependencies = [
"zopfli",
]
[[package]]
name = "zip"
version = "9.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2d98561b612a84ae525331a7a094429ef8a5772514ed507ff6db5f54badc971"
dependencies = [
"crc32fast",
"flate2",
"indexmap",
"memchr",
"nix",
"typed-path",
"zopfli",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
+15 -14
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.5.8"
version = "0.6.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -27,6 +27,7 @@ fieldcraft-testkit = { path = "crates/testkit" }
fieldcraft-render = { path = "crates/render" }
fieldcraft-ui-egui = { path = "crates/ui-egui" }
fieldcraft-mcp = { path = "crates/mcp" }
fieldcraft-update = { path = "crates/update" }
# foundation
thiserror = "2"
@@ -34,9 +35,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
# 3MF packages (docs/formats/tagged-mesh.md): the same versions SolidCraft uses.
zip = { version = "3", default-features = false, features = ["deflate"] }
quick-xml = "0.41"
# 3MF packages (docs/formats/tagged-mesh.md). zip is ahead of SolidCraft (still on 3), so both are built.
zip = { version = "9", default-features = false, features = ["deflate"] }
quick-xml = "0.42"
# content hashes and part checksums of .fieldcraft files (the version SolidCraft uses)
sha2 = "0.11"
@@ -58,13 +59,13 @@ rfd = "0.17"
# Geometry: SolidCraft's B-rep kernel (MIT OR Apache-2.0), pinned. Only crates/geometry uses it
# (plan/adr/0001-libraries.md).
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
# Runs SolidCraft command scripts (the test corpus recipes); only behind fieldcraft-geometry's
# `scripts` feature.
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -128,10 +129,10 @@ debug = "line-tables-only"
# reach a dependent workspace, so FieldCraft applies the same ones from the same pinned commit;
# keep this list and the rev in step with SolidCraft's [patch.crates-io].
[patch.crates-io]
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
# egui-wgpu with SolidCraft's fixes (vendor/egui-wgpu there): MSAA clamped to what the device
# supports and 1x on OpenGL adapters, so the requested 4x never fails pipeline validation at start.
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
+1 -1
View File
@@ -6,7 +6,7 @@ Licensed under the MIT License or the Apache License, Version 2.0, at your optio
Third-party material
Software dependencies are listed in Cargo.lock; their licences are in THIRD-PARTY-LICENSES.txt
(`cargo xtask licences`). Geometry comes from SolidCraft (https://github.com/bherbruck/solidcraft,
(generated by `cargo xtask licences`, in every release package). Geometry comes from SolidCraft (https://github.com/bherbruck/solidcraft,
MIT OR Apache-2.0), which builds on the truck crates (https://github.com/ricosjp/truck, Apache-2.0,
Copyright (c) RICOS Co. Ltd.), some with SolidCraft's modifications.
+13 -2
View File
@@ -114,7 +114,7 @@ against a closed form or a reference solution ([docs/examples.md](docs/examples.
## Build
```sh
cargo xtask ci # fmt, assets, licences, layers, clippy, tests, wasm
cargo xtask ci # fmt, assets, layers, clippy, tests, wasm
cargo xtask test --heavy # the heavy (ignored) tests and the doc tests
cargo run -p fieldcraft-cli -- commands # every command and its parameters
cargo run -p fieldcraft-cli -- run script.json # run a command script
@@ -135,10 +135,21 @@ Rust 1.95 or later, with the `wasm32-unknown-unknown` target for `cargo xtask ci
- [Releasing](docs/releasing.md): how a release is built, verified and published
- [Contributing](CONTRIBUTING.md) and [agent instructions](AGENTS.md)
## Privacy
FieldCraft sends nothing until you agree. The first start asks once whether to share anonymous
usage (which tools you use, nothing from your models); Help › Settings… changes it, and
`FIELDCRAFT_TELEMETRY=0` turns it off. File names, paths, geometry, model contents, parameter
values and messages are never sent: [docs/privacy.md](docs/privacy.md) lists every event and
property. Crash reports and the log stay on your computer; Help › Report a Bug opens a GitHub issue
you review and submit yourself, with your session or model attached only if you tick them
([docs/crash-reports.md](docs/crash-reports.md)).
## License
Dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. Notices
are in [NOTICE](NOTICE); third-party licences in [THIRD-PARTY-LICENSES.txt](THIRD-PARTY-LICENSES.txt).
are in [NOTICE](NOTICE); third-party licences in
THIRD-PARTY-LICENSES.txt, which every release package carries (`cargo xtask licences` writes it).
FieldCraft is an independent project, not affiliated with, sponsored or endorsed by Dassault
Systèmes, MSC Software, Siemens or Ansys. Abaqus, Nastran, MSC Nastran, Simcenter Nastran and
+40 -3
View File
@@ -31,8 +31,8 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
| M2 Tet meshing and size field | Size field (global, curvature and proximity; edge seeds done: `mesh.seed.edge` on persistent design edge names (`<face>|<face>`) with a count or size, geometric bias and an exact, min or free constraint, shown as ticks and under Mesh › Seeds, honoured by the hex sweep, extrude, revolve, mapped, blocks and cells meshers through interval assignment (conflicting exact seeds named) and by the tet mesher, which divides the edge at the seed's nodes and grades its size field from them; per-face seeds to do; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
| M3 First deck | Sets and surfaces bound to SolidCraft face, edge, vertex and body names, resolved after meshing; materials (isotropic and orthotropic elastic, density) with a unit-system label and consistency check; sections (solid, shell, beam profiles) assigned by set; element formulation per region mapped to each solver; BCs (fixed, displacement, symmetry); loads (force and moment on reference points, pressure, gravity); reference points with kinematic and distributing coupling; steps (linear static, frequency) with explicit per-step load and BC tables and output presets; `model.check` naming every missing or bad item; `model.*` and `mesh.tag` commands (model definition: done); writers for Abaqus input (done: `deck.write`), Nastran SOL 101/103 (done: `deck.write`) and LS-DYNA implicit (done); the `.fieldcraft` file (text definition, binary mesh, geometry references reopened on load, journal; atomic saves, autosave and recovery; undo/redo on the journal: done) | in progress |
| M4 Own solver and first results | Element library per docs/elements.md (1D and 2D first); Linear static and modal solver (tet4/10, wedge6, hex8, hex20; sparse direct, Lanczos), verified against analytic solutions (solver: done — `fieldcraft-fem` kernels, `fieldcraft-solver` with nested dissection, sparse Cholesky and block Lanczos, `solve.static`/`solve.frequency`/`solve.probe`, patch, cantilever, Lamé, Kirsch and beam-frequency tests; reference points with kinematic and distributing couplings and moments by master–slave constraint elimination, verified by rigid motion, clamping, Saint-Venant tension, bending and tube torsion; 1D elements I: rod2/rod3 trusses, point masses, rotary inertia, springs and dashpots in both solvers and all three decks, verified by the method of joints, the three-bar truss, spring–mass, two-mass chain and torsional pendulum frequencies, and damped decay; 2D elements: plane stress, plane strain and axisymmetric tri3, tri6, quad4 (incompatible modes QM6), quad8 with two degrees of freedom per node, centrifugal loads, `mesh.planar` 2D meshes of polygons and planar faces, verified by patch tests, Kirsch, Lamé (plane strain and axisymmetric), rotating discs and cylinders, and a plane stress cantilever; deck mapping to Abaqus CPS/CPE/CAX, Nastran membranes, LS-DYNA ELFORM 12/13); shells and beams (done: quad4 MITC4 and tri3 MITC3 flat shells with a Hughes–Brezzi drilling rotation, two-node Timoshenko beams with profile properties and orientations, six degrees of freedom at shell and beam nodes shared with solids and trusses, section forces and surface stresses, verified by shell patch tests, Navier's plate, cantilever and portal-frame beams, and the Scordelis–Lo and pinched-cylinder benchmarks); results display (done: `results.*` commands, deformed shape to scale, banded contours of displacement, von Mises, principal and component stresses with a legend, mode shapes with their frequencies and animation, probing a node by clicking it, reaction force and moment sums per set, stale results marked after an edit; explicit steps: field frames by slider or animation with contours per frame, energy histories plotted) | started |
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); partitions inside FieldCraft (done: datum planes and axes, `geometry.partition` cuts the open design by a datum plane, kept in the model and replayed when the design opens, the two faces of each cut paired by name); cells meshed each with its own method into one mesh (done: `mesh.cells` — hex where a method fits, else tet; matching interfaces merged node for node, others, such as hex next to tet, tied by dual mortar, verified by a tied hex–tet bar in tension to 1e-6); meshing half a symmetric part and mirroring it (done: `mesh.mirror` reflects hex8/hex20/tet4/tet10/wedge6 across a datum plane, right-handed, nodes on the plane merged, tags carried to the image half; a mirrored half bar equals the whole bar's mesh and bending deflection to 1e-12; samples `crank-arm` and `crank-mirror`: the half cut into seven cells, each swept structured, seeded to merge, and mirrored, scaled Jacobian ≥ 0.37; or solving the half: `model.boundary_condition.symmetry` on a datum plane, a half bar with half the load bends as the whole to 1e-11); three-sided sweep regions mapped as triangle primitives (done: midpoint subdivision, dominance constraints in interval assignment); pyramid transitions; automatic decomposition into sweepable and mappable regions, proposed as SolidCraft splits | started |
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing and orphan-mesh import | started |
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); partitions inside FieldCraft (done: datum planes and axes, `geometry.partition` cuts the open design by a datum plane, kept in the model and replayed when the design opens, the two faces of each cut paired by name); cells meshed each with its own method into one mesh (done: `mesh.cells` — hex where a method fits, else tet; matching interfaces merged node for node, others, such as hex next to tet, tied by dual mortar, verified by a tied hex–tet bar in tension to 1e-6); meshing half a symmetric part and mirroring it (done: `mesh.mirror` reflects hex8/hex20/tet4/tet10/wedge6 across a datum plane, right-handed, nodes on the plane merged, tags carried to the image half; a mirrored half bar equals the whole bar's mesh and bending deflection to 1e-12; samples `crank-arm` and `crank-mirror`: one datum, the half extruded in automatic blocks and mirrored, scaled Jacobian ≥ 0.37; or solving the half: `model.boundary_condition.symmetry` on a datum plane, a half bar with half the load bends as the whole to 1e-11); three-sided sweep regions mapped as triangle primitives (done: midpoint subdivision, dominance constraints in interval assignment); automatic blocks of extruded cross-sections (done: `hex::decompose` — holes separated, O-grids, cuts from concave corners and fillets chosen by block quality, kept only when no worse than the free mesh; nothing added to the model); pyramid transitions; automatic decomposition of 3D parts into sweepable and mappable regions | started |
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing (node tools done: `mesh.node.merge` equivalences coincident nodes with sets and tags following the survivors and element collapses left out, previewed in its form; `mesh.check.duplicates` lists unmerged nodes, repeated elements, cracks and free edges and selects them; `mesh.renumber` compact, by body or in reverse Cuthill–McKee order, every reference following) and orphan-mesh import | started |
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar: done — `interaction.tie`, dual mortar constraints in the implicit analyses, Abaqus `*TIE` and LS-DYNA tied contact, the tie patch test); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection (mortar contact pairs with Coulomb friction in nonlinear static steps: done — segment-to-segment mortar with the consistent tangent by automatic differentiation of the segmentation, augmented Lagrangian with Uzawa updates to a gap tolerance, semismooth active set with a chattering cutback, small sliding without nonlinear geometry and finite sliding with it, overclosure adjusted or refused, Coulomb friction (stick/slip return map, static and kinetic coefficients, symmetrised tangent), pressure, gap, status, shear and slip output; verified by the contact patch test, Hertz cylinder and sphere, Newton's quadratic rate and sliding blocks; the linear analyses refuse contact by name); friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | started |
| M8 Materials, explicit, shells, composites | Plasticity, hyperelasticity, damage data per solver; explicit dynamics decks (Abaqus/Explicit, LS-DYNA); midsurface shells; composite layups and material orientations, continuum shells on swept hex; hybrid (mixed u–p) hex8/hex20/tet10 for nearly incompressible materials (done); heat transfer (solids done: steady and θ-method transient conduction with flux, convection and sources, thermal strain in static steps (solids and 2D) and explicit dynamics (with plasticity), coupled temperature–displacement, `solve.heat`; deck output, 2D/shell/beam conduction planned) | started |
| M9 Post-processing and deck readers | Results readers for public formats (Nastran OP2, LS-DYNA d3plot, Abaqus `.fil`); XY and path plots, cuts, display groups, free-body forces; deck readers that keep unknown keywords; mesh convergence studies | planned |
@@ -52,7 +52,44 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
| M23 Wave propagation and ultrasound | Elastic, acoustic and coupled waves from the explicit solver's 1D bar today to guided and ultrasonic waves, by two methods. Finite differences first, for fast 2D (then 3D) ultrasound on regular grids: staggered-grid velocity–stress FDTD (Virieux) and the elastodynamic finite integration technique for solids, the rotated staggered grid for anisotropic media, a k-space pseudospectral scheme for weakly heterogeneous tissue and water, all on grids voxelised from the face-tagged geometry by the LBM's exact voxeliser, with heterogeneous, layered and fluid–solid media, CPML boundaries, threads and the GPU backend; staircased curved boundaries scatter spuriously, so the FD grid is checked against the finite elements on curved parts. Finite elements for curved geometry and coupling with structures: spectral elements (high-order Gauss–Lobatto–Legendre hexes with diagonal mass) on the hex meshes, and a mesh check in elements per wavelength with the dispersion error it implies; absorbing boundaries (convolutional PML, absorbing layers with increasing damping) and infinite media; tone-burst sources (Hann-windowed cycles), point, line and surface excitation, and piezoelectric transducers (M19); anisotropic media (composites, crystals) and viscoelastic, power-law-in-frequency attenuation; fluid–solid interfaces and fluid-loaded plates; ultrasound in water and tissue, nonlinear acoustics (Westervelt, KZK) for focused ultrasound. Guided waves: dispersion curves by semi-analytical finite elements (SAFE) for plates, pipes, rails and layered and anisotropic laminates — Lamb, Rayleigh, Love and SH modes — with phase and group velocities and mode shapes; mode-selective excitation. Output: A-scans and B-scans at sensors, wavefield snapshots, 2D FFT (frequency–wavenumber) for mode identification, and time–frequency diagrams of any signal — short-time Fourier spectrograms, continuous wavelet transforms (Morlet), reassigned spectrograms and smoothed pseudo Wigner–Ville — with the SAFE or Rayleigh–Lamb group-velocity curves overlaid as arrival times, and group velocities extracted from the ridges. GPU paths (M12's backend) for long runs. Verified by Lamb's problem (point load on a half-space), Rayleigh-wave speed, Rayleigh–Lamb dispersion, Love waves in a layer over a half-space, reflection and transmission at interfaces, and published guided-wave measurements | planned |
| Continuous: verification and validation | Every capability checked against theory (closed forms), experiments (published measurements) and published benchmarks (NAFEMS, vendor benchmark and verification manuals such as Abaqus's), each case our own model in `tests/oracle/` with its cited reference and tolerance; `cargo xtask oracle` runs them and writes docs/oracle.md; once a case matches, our result is frozen as a fixture so fidelity cannot regress (docs/verification.md). Runner, fixtures and CI job: done; 26 theory cases (patch tests of every solid element, cantilevers, Lamé in 3D, plane strain and axisymmetric, Kirsch in 3D and plane stress, rotating disc and cylinder, beam frequencies, couplings, explicit waves, impact and J2 plasticity, CDT invariants), 9 published benchmarks (MacNeal–Harder solid tests, Scordelis–Lo with solids, NAFEMS LE1 in 3D and 2D, LE10, FV32) and 9 pending cases with citations (shells, thermal, static plasticity, Taylor bar, CFD); `mesh.block` mapped blocks and 2D patches build their meshes | started |
| Continuous: performance | CPU first, deterministic: results never depend on the thread count (fixed partitions, sums in a fixed order; checked by hashing results on 1, 2 and 7 threads). Supernodal left-looking Cholesky (11–15× faster than the column solver on one thread), parallel element matrices, stresses and Lanczos products, explicit element updates and LBM cell blocks on rayon threads (done — `fieldcraft-parallel`, `threads` on the solve commands, `FIELDCRAFT_THREADS`); parallel forward/back substitution and explicit tet4 assembly; GPU paths later, within a stated tolerance of the CPU | started |
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; symbols as wireframes, one mark per constrained degree of freedom, a constant size on screen with a size setting, highlighted with their selected definition, concentrated loads drawn over the part: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done), command schema as the public API | started |
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; symbols as wireframes, one mark per constrained degree of freedom, a constant size on screen with a size setting, highlighted with their selected definition, concentrated loads drawn over the part: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done; in-app updates — a daily check of GitHub Releases, Help › Check for Updates and Reinstall, downloads verified against the release key's signature of SHA256SUMS.txt and swapped in after closing, `app.update.check`, `fieldcraft-cli update`, Reload to update in the browser, docs/updates.md: done), command schema as the public API | started |
## 0.6.0: the UI/UX release
What landed for 0.6.0 (milestone 0.6.0 on GitHub):
- **Browser:** status checks in one aligned column, Interactions counting ties, a selected set
highlighted in the viewport, seeds selectable, editable and deletable, definitions shown with
units instead of raw JSON, one highlighted item per context menu, given names shown as typed,
and a setup checklist that does not ask for a load on a displacement-driven model or for a
support or load on a free body in explicit dynamics (#315, #335, #336, #352, #356, #361, #366).
- **Results:** units on every legend, summary, probe and reaction sum; legend ranges that can be
clamped; max and min markers in the viewport; an energies plot with axes and the current frame;
the deformed shape kept when the field changes; a sensible auto scale for large strains; setup
symbols off over contours; heat flow through each convection and flux load; probe and reaction
results exported to CSV (#92, #191, #319, #321, #325–#332, #362).
- **Forms, progress and jobs:** solves and meshers run as jobs with their step, stage, count and
elapsed time and a Cancel that interrupts every solver and mesher; the control channel and MCP
wait for a long solve; mesher forms report what they made; typed fields for label lists, point
lists, multi-choices and number-or-auto, JSON fields with hints, defaults shown as set; forms
without orphan sets on Cancel; unknown parameters refused (#169, #316, #322–#324, #337, #339,
#340, #353, #357, #367, #371).
- **Picking and preparation:** vertices pickable, selected edges visible over the mesh, a
reference point placed by a pick or a hole's centre, Seed Edges switching the filter to edges,
live previews and default names for datums and partitions, readable partition cell names, the
Partitioned Mesh form with picks and per-cell methods, a mesh marked out of date when its seeds
or partitions change, remeshing from the current mesh's settings (#338, #341–#349, #351).
- **UI conveniences:** File › New (`file.new`), Help › Crash Reports, the I-beam sample, every
sample with a Start-card thumbnail and a gallery capture, node tools (merge, duplicates, free
edges, renumber), the mesh quality panel's histograms and worst elements, Mirror Mesh and Mesh
Block on the ribbon, Rigid Wall in Interactions, readable journal entries and status messages,
a sample's name on its document tab, the web build naming an unknown sample (#113, #143, #144,
#200, #234, #300, #333, #334, #348, #350, #354, #355, #359, #360, #365).
- **Mesh soundness:** tet improvement that no longer crowds one vertex, hex20 extrudes that pass
the validity gate where hex8 does, biased seeds carried to the opposite edge of a mapped face,
designs with a closed internal void and face names over 256 characters meshed (#197, #257,
#311, #364, #374).
- **Heat:** heat transfer across ties for bonded multi-body thermal models (#358).
## Next
File diff suppressed because it is too large. Load diff
+4
View File
@@ -12,4 +12,8 @@ workspace = true
fieldcraft-engine = { workspace = true }
fieldcraft-io = { workspace = true }
fieldcraft-mcp = { workspace = true }
fieldcraft-update = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
fieldcraft-update = { workspace = true, features = ["mock"] }
+80
View File
@@ -0,0 +1,80 @@
//! `fieldcraft-cli crashes`: the crash reports the desktop app wrote on this computer
//! (docs/crash-reports.md): list them, show one, replay one, delete them.
use std::path::Path;
use fieldcraft_engine::crash;
use serde_json::json;
pub const USAGE: &str = "usage: fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]";
pub fn run(args: &[String]) -> Result<(), String> {
let dir = crash::default_dir().ok_or("no crash folder on this system (set FIELDCRAFT_CRASH_DIR)")?;
let id = || args.get(1).map(String::as_str).ok_or_else(|| USAGE.to_string());
match args.first().map(String::as_str) {
None | Some("list") => {
let reports = crash::list(&dir);
if args.iter().any(|a| a == "--json") {
return print_json(&json!({ "dir": dir.to_string_lossy(), "reports": reports }));
}
println!("crash reports in {}", dir.display());
if reports.is_empty() {
println!(" (none)");
}
for r in reports {
let times = if r.count > 1 { format!(" ×{}", r.count) } else { String::new() };
let cmd = r.command.map(|c| format!(" in {c}")).unwrap_or_default();
let replay = if r.replayable { " [replayable]" } else { "" };
println!(" {} {}{times}{cmd} v{}{replay}\n {}", r.id, r.kind, r.version, r.message);
}
Ok(())
}
Some("show") => print_json(&crash::read(&dir, id()?)?),
Some("replay") => replay(&dir, id()?),
Some("dir") => {
println!("{}", dir.display());
Ok(())
}
Some("clear") => {
println!("deleted {} report(s)", crash::clear(&dir, args.get(1).map(String::as_str)));
Ok(())
}
_ => Err(USAGE.to_string()),
}
}
fn print_json(v: &serde_json::Value) -> Result<(), String> {
println!("{}", serde_json::to_string_pretty(v).map_err(|e| e.to_string())?);
Ok(())
}
/// Run a report's commands on its model and say whether the crash happens again. Files the
/// commands write go to a scratch folder, never over the user's files.
fn replay(dir: &Path, id: &str) -> Result<(), String> {
let report = crash::read(dir, id)?;
let scratch = std::env::temp_dir().join(format!("fieldcraft-replay-{}", std::process::id()));
std::fs::create_dir_all(&scratch).map_err(|e| format!("{}: {e}", scratch.display()))?;
if report["kind"] == "unclean_exit" {
println!("this crash ended the app without a report: if this process ends abruptly, it reproduced");
}
println!("replaying on {}", report["model_path"].as_str().unwrap_or("a new model"));
let r = crash::replay(&report, &scratch);
let _ = std::fs::remove_dir_all(&scratch);
let r = r?;
for (i, (cmd, outcome)) in r.steps.iter().enumerate() {
match outcome {
Ok(()) => println!(" {:>3}. {cmd}: ok", i + 1),
Err(e) => println!(" {:>3}. {cmd}: {e}", i + 1),
}
}
let said = |k: &str| report[k].as_str().unwrap_or_default().to_string();
if r.reproduced {
println!("reproduced: the same internal error ({}) at {}", said("message"), said("location"));
} else if let Some((l, m)) = r.panics.first() {
println!("an internal error happened, but not the reported one: {m} at {l}");
println!("(the report says: {} at {})", said("message"), said("location"));
} else {
println!("did not reproduce: no internal error (fixed, or it depends on something the replay does not have)");
}
Ok(())
}
+15
View File
@@ -2,10 +2,15 @@
//! fieldcraft-cli run <script.json>
//! fieldcraft-cli features
//! fieldcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR] [--automation-write-root DIR]
//! fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]
//! fieldcraft-cli update --check | --install
//! fieldcraft-cli --version
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod crashes;
mod update;
use std::path::Path;
use std::process::ExitCode;
@@ -28,6 +33,14 @@ usage:
--automation-read-root DIR files may be read only inside DIR
--automation-write-root DIR files may be written only inside DIR (with either root,
the access a root left out is not granted)
fieldcraft-cli crashes [list|show <id>|replay <id>|dir|clear [<id>]]
the crash reports the desktop app wrote on this
computer (docs/crash-reports.md): list them (--json),
show one, replay one (does the crash happen again?),
print their folder, delete them
fieldcraft-cli update --check is a newer FieldCraft published? (app.update.check; JSON)
fieldcraft-cli update --install download the latest release, verify its signature and
checksum, and install it over this copy (docs/updates.md)
fieldcraft-cli --version print the version
";
@@ -52,6 +65,8 @@ fn main() -> ExitCode {
Ok(())
}
Some("mcp") => mcp(args.get(1..).unwrap_or(&[])),
Some("crashes") => crashes::run(args.get(1..).unwrap_or(&[])),
Some("update") => update::run(args.get(1..).unwrap_or(&[])),
Some("run") => args.get(1).ok_or_else(|| format!("run needs a script\n\n{USAGE}")).and_then(|p| run(p)),
Some("-V" | "--version") => {
println!("fieldcraft-cli {}", env!("CARGO_PKG_VERSION"));
+56
View File
@@ -0,0 +1,56 @@
//! `fieldcraft-cli update --check | --install` (docs/updates.md): the same check as the app's
//! Help › Check for Updates (`app.update.check`), and installing the latest release over this
//! copy of the CLI's install, verified against the release key first. `FIELDCRAFT_UPDATE_HOST`
//! points both at a local test server.
use fieldcraft_engine::Session;
use fieldcraft_update::install::{self, Finish};
use fieldcraft_update::net::Client;
use fieldcraft_update::stage::{self, Options};
use serde_json::json;
pub const USAGE: &str = "usage: fieldcraft-cli update --check | --install";
pub fn run(args: &[String]) -> Result<(), String> {
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
["--check"] => check(),
["--install"] => install(),
_ => Err(USAGE.into()),
}
}
fn check() -> Result<(), String> {
fieldcraft_engine::enable_update_checks(true);
let report = Session::default().execute("app.update.check", &json!({})).map_err(|e| e.to_string())?;
println!("{}", serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?);
Ok(())
}
fn install() -> Result<(), String> {
let client = Client::from_env();
let check = client.check().map_err(|e| e.to_string())?;
if !check.newer() {
println!("FieldCraft {} is up to date (the latest release is {}).", check.current, check.latest.version);
return Ok(());
}
let here = install::here();
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
eprintln!("Downloading FieldCraft {} for {}…", check.latest.version, here.describe());
let progress = |done: u64, total: u64| {
if total > 0 && done == total {
eprintln!("Downloaded {} MB; verifying…", total / (1024 * 1024));
}
};
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
let staged = stage::stage(&client, &check.latest, &here, &options).map_err(|e| e.to_string())?;
match install::plan(&staged, false).map_err(|e| e.to_string())? {
Finish::Swap(plan) => {
stage::apply(&plan).map_err(|e| e.to_string())?;
println!("Installed FieldCraft {} ({}). A running FieldCraft app uses it from its next start.", staged.version, here.describe());
}
Finish::Package { file, command } => {
println!("Downloaded and verified {}.\nInstall it with the system's package manager:\n {command}", file.display());
}
}
Ok(())
}
+75
View File
@@ -0,0 +1,75 @@
//! `fieldcraft-cli crashes` on a crash folder of its own (`FIELDCRAFT_CRASH_DIR`).
use std::path::{Path, PathBuf};
use std::process::Command;
use fieldcraft_engine::Session;
use serde_json::{Value, json};
const ID: &str = "20261014-101500-00000000deadbeef";
/// A replayable report: a model with two nodes and a replay that adds a third.
fn folder() -> PathBuf {
let d = std::env::temp_dir().join(format!("fieldcraft-cli-crashes-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let r = d.join(ID);
std::fs::create_dir_all(&r).unwrap();
let mut s = Session::default();
for l in 1..=2 {
s.execute("mesh.node.add", &json!({"label": l, "xyz": [l, 0, 0]})).unwrap();
}
std::fs::write(r.join("model.fieldcraft"), s.file_bytes(None).unwrap()).unwrap();
let replay = json!({"commands": [
{"command": "mesh.node.add", "params": {"label": 3, "xyz": [3, 0, 0]}},
{"command": "file.save", "params": {"path": d.join("overwritten.fieldcraft")}},
]});
std::fs::write(r.join("replay.json"), replay.to_string()).unwrap();
let report = json!({
"format": "fieldcraft-crash/1", "id": ID, "kind": "unclean_exit", "signature": "00000000deadbeef", "count": 2,
"first_seen": "2026-10-14T10:15:00Z", "message": "FieldCraft ended without a clean exit while running `mesh.node.add`",
"location": "unclean exit in mesh.node.add", "command": {"command": "mesh.node.add", "params": {}},
"app": {"version": "9.9.9"}, "backtrace": [],
});
std::fs::write(r.join("report.json"), report.to_string()).unwrap();
d
}
fn cli(dir: &Path, args: &[&str]) -> (String, bool) {
let out = Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_CRASH_DIR", dir).output().unwrap();
(format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)), out.status.success())
}
#[test]
fn crashes_list_show_replay_and_clear() {
let d = folder();
let (out, ok) = cli(&d, &["crashes"]);
assert!(ok, "{out}");
assert!(out.contains(ID) && out.contains("unclean_exit ×2 in mesh.node.add") && out.contains("[replayable]"), "{out}");
let (out, ok) = cli(&d, &["crashes", "list", "--json"]);
assert!(ok);
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!(v["reports"][0]["id"], ID);
let (out, ok) = cli(&d, &["crashes", "show", ID]);
assert!(ok);
let v: Value = serde_json::from_str(&out).unwrap();
assert!(v["model_path"].as_str().unwrap().ends_with("model.fieldcraft"));
let (out, ok) = cli(&d, &["crashes", "replay", ID]);
assert!(ok, "{out}");
assert!(out.contains("1. mesh.node.add: ok"), "{out}");
// A command that writes a file is refused outside the scratch folder: the replay never
// writes over the user's files.
assert!(out.contains("2. file.save: ") && out.contains("outside the write root"), "{out}");
assert!(!d.join("overwritten.fieldcraft").exists());
assert!(out.contains("did not reproduce"), "{out}");
let (out, ok) = cli(&d, &["crashes", "show", "../etc"]);
assert!(!ok && out.contains("no crash report"), "{out}");
let (out, ok) = cli(&d, &["crashes", "dir"]);
assert!(ok && out.trim() == d.to_string_lossy(), "{out}");
let (out, ok) = cli(&d, &["crashes", "clear"]);
assert!(ok && out.contains("deleted 1 report(s)"), "{out}");
let (out, _) = cli(&d, &["crashes"]);
assert!(out.contains("(none)"), "{out}");
let (out, ok) = cli(&d, &["crashes", "nope"]);
assert!(!ok && out.contains("usage"), "{out}");
let _ = std::fs::remove_dir_all(&d);
}
+36
View File
@@ -0,0 +1,36 @@
//! `fieldcraft-cli update --check` against a local release server (FIELDCRAFT_UPDATE_HOST).
use std::process::Command;
use fieldcraft_update::mock::Server;
use serde_json::{Value, json};
fn cli(host: &str, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_UPDATE_HOST", host).output().unwrap()
}
#[test]
fn update_check_reports_the_latest_release() {
let server = Server::start().unwrap();
server.release("latest", &json!({"tag_name": "v99.0.0", "html_url": "https://github.com/jyviko/fieldcraft/releases/tag/v99.0.0", "assets": []}));
let out = cli(&server.url(), &["update", "--check"]);
assert!(out.status.success(), "{out:?}");
let report: Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(report["current"], env!("CARGO_PKG_VERSION"));
assert_eq!((report["latest"].as_str(), report["newer"].as_bool(), report["signed"].as_bool()), (Some("99.0.0"), Some(true), Some(false)));
// A test build is not a release package: it checks but would not install.
assert_eq!(report["asset"], Value::Null);
assert_eq!(server.requests(), 1);
// The same version: not newer, and --install has nothing to do.
server.release("latest", &json!({"tag_name": format!("v{}", env!("CARGO_PKG_VERSION")), "assets": []}));
let out = cli(&server.url(), &["update", "--check"]);
assert_eq!(serde_json::from_slice::<Value>(&out.stdout).unwrap()["newer"], false);
let out = cli(&server.url(), &["update", "--install"]);
assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("is up to date"), "{out:?}");
// Unreachable: an error, not a crash.
let out = cli("http://127.0.0.1:1", &["update", "--check"]);
assert!(!out.status.success() && String::from_utf8_lossy(&out.stderr).contains("could not reach"), "{out:?}");
assert!(!cli(&server.url(), &["update"]).status.success());
}
+1 -1
View File
@@ -29,6 +29,6 @@ rfd = { workspace = true, features = ["file-handle-inner"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage", "Crypto", "Headers", "Request", "RequestInit", "RequestCache", "Response"] }
# Autosaves kept in the browser's local storage, which holds text.
base64 = "0.22"
+75
View File
@@ -0,0 +1,75 @@
//! A new deployment of the web app: every half hour the page's own address is fetched past the browser's cache, and when it loads another build
//! of the app than the one running (Trunk names each build's files by their content hash), the
//! status bar offers "Reload to update" (docs/updates.md). Reloading asks first when the model
//! has unsaved changes, as closing the page does.
use std::cell::Cell;
use std::rc::Rc;
use wasm_bindgen::JsCast as _;
/// How often the page looks for a new deployment (seconds).
pub const INTERVAL: f64 = 30.0 * 60.0;
/// Watches for a new deployment.
pub struct Watch {
/// The build this page runs.
running: Option<String>,
/// A fetch found another build.
found: Rc<Cell<bool>>,
/// App time of the last look.
pub looked_at: f64,
}
impl Watch {
pub fn start() -> Watch {
let html = web_sys::window().and_then(|w| w.document()).and_then(|d| d.document_element()).map(|e| e.outer_html()).unwrap_or_default();
let running = crate::build_in_page(&html).map(str::to_string);
if running.is_none() {
log::info!("deploy: no hashed build in the page (a development server?); not watching");
}
Watch { running, found: Rc::default(), looked_at: 0.0 }
}
/// Whether a newer deployment was found.
pub fn found(&self) -> bool {
self.found.get()
}
/// Fetch the page again and compare its build with the running one.
pub fn look(&self) {
let (Some(running), Some(window)) = (self.running.clone(), web_sys::window()) else { return };
if self.found.get() {
return;
}
let url = window.location().pathname().unwrap_or_else(|_| "./".into());
let init = web_sys::RequestInit::new();
init.set_cache(web_sys::RequestCache::NoStore);
let promise = window.fetch_with_str_and_init(&url, &init);
let found = self.found.clone();
wasm_bindgen_futures::spawn_local(async move {
let text = async {
let response: web_sys::Response = wasm_bindgen_futures::JsFuture::from(promise).await.ok()?.dyn_into().ok()?;
if !response.ok() {
return None;
}
wasm_bindgen_futures::JsFuture::from(response.text().ok()?).await.ok()?.as_string()
};
// Offline or refused: look again next time.
if let Some(html) = text.await
&& let Some(deployed) = crate::build_in_page(&html)
&& deployed != running
{
log::info!("deploy: {deployed} is deployed (running {running})");
found.set(true);
}
});
}
}
/// Reload the page (the new deployment loads).
pub fn reload() {
if let Some(w) = web_sys::window() {
let _ = w.location().reload();
}
}
+37 -1
View File
@@ -8,7 +8,8 @@
//! - files live in the page ([`fieldcraft_io::fs`] keeps them in memory): File › Open and drops
//! read the computer's files into it; Save, Save As and Write Deck hand the written file out as
//! a download;
//! - autosaves for recovery are kept in the browser's local storage ([`storage`]);
//! - autosaves for recovery and the preferences are kept in the browser's local storage
//! ([`storage`], [`usage`]), and anonymous usage (when agreed) goes out with `fetch`;
//! - no control channel (a page can't listen on a socket);
//! - background jobs (meshing, solving) run on the page's one thread once the window has shown
//! that they run.
@@ -17,9 +18,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(target_arch = "wasm32")]
mod deploy;
#[cfg(target_arch = "wasm32")]
mod storage;
#[cfg(target_arch = "wasm32")]
mod usage;
#[cfg(target_arch = "wasm32")]
mod web;
#[cfg(target_arch = "wasm32")]
@@ -42,6 +47,25 @@ fn sample_in_query(query: &str) -> Option<String> {
})
}
/// The build of the app a page loads: the content-hashed name Trunk gives its WebAssembly
/// (`fieldcraft-web-<hash>_bg.wasm`). A new deployment loads another one.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
fn build_in_page(html: &str) -> Option<&str> {
const HEAD: &str = "fieldcraft-web-";
const TAIL: &str = "_bg.wasm";
let mut rest = html;
while let Some(at) = rest.find(HEAD) {
let candidate = rest.get(at..)?;
let hash = candidate.get(HEAD.len()..)?;
let len = hash.bytes().take_while(u8::is_ascii_alphanumeric).count();
if len > 0 && hash.get(len..)?.starts_with(TAIL) {
return candidate.get(..HEAD.len() + len + TAIL.len());
}
rest = candidate.get(HEAD.len()..)?;
}
None
}
/// The name a file from the computer is kept under in the page: its last path part, without
/// characters a path would read as folders.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
@@ -64,6 +88,18 @@ mod tests {
assert_eq!(sample_in_query("?samples=x"), None);
}
#[test]
fn the_running_build_is_found_in_the_page() {
let page = r#"<link rel="modulepreload" href="/fieldcraft/fieldcraft-web-1a2b3c.js"><link rel="preload" href="/fieldcraft/fieldcraft-web-1a2b3c_bg.wasm" as="fetch">"#;
assert_eq!(build_in_page(page), Some("fieldcraft-web-1a2b3c_bg.wasm"));
let next = page.replace("1a2b3c", "9f8e7d");
assert_ne!(build_in_page(page), build_in_page(&next));
// A development page (no hash) and other text: nothing to compare.
assert_eq!(build_in_page(r#"<script src="fieldcraft-web.js"></script>"#), None);
assert_eq!(build_in_page("fieldcraft-web-"), None);
assert_eq!(build_in_page(""), None);
}
#[test]
fn file_names_stay_in_their_folder() {
assert_eq!(safe_name("beam.fieldcraft"), "beam.fieldcraft");
+86
View File
@@ -0,0 +1,86 @@
//! Anonymous usage in the browser (docs/privacy.md): the same events and the same consent as the
//! desktop app, the choice kept in the browser's local storage with the other preferences. Queued
//! events are posted with `fetch` every half minute and when the page is closed or left (`keepalive`, so
//! a closing page still sends them); a failed post is dropped silently.
//!
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`: a build without one asks nothing
//! and sends nothing.
use fieldcraft_engine::usage;
use fieldcraft_ui_egui::files::PrefsStore;
use fieldcraft_ui_egui::privacy::UsageHost;
use wasm_bindgen::JsCast as _;
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
/// Where the preferences are kept in local storage.
const PREFS_KEY: &str = "fieldcraft-prefs";
/// How often queued events are sent (seconds).
pub const INTERVAL: f64 = 30.0;
fn key() -> Option<&'static str> {
KEY.map(str::trim).filter(|k| !k.is_empty())
}
fn local_storage() -> Option<web_sys::Storage> {
web_sys::window()?.local_storage().ok().flatten()
}
/// The preferences in local storage (navigation, privacy).
pub fn prefs_store() -> PrefsStore {
PrefsStore {
load: Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten().map(String::into_bytes)),
save: Box::new(|bytes| {
let text = std::str::from_utf8(bytes).map_err(|e| e.to_string())?;
local_storage().ok_or("browser storage is turned off")?.set_item(PREFS_KEY, text).map_err(crate::web::js_err)
}),
}
}
/// What the window needs to ask and record, when the build has a key.
pub fn host() -> Option<UsageHost> {
// The browser's clock for command durations (the plain wasm target has none).
usage::set_clock(js_sys::Date::now);
key().is_some().then(|| UsageHost {
platform: "web",
os: "web",
arch: "wasm32",
new_id: Box::new(|| web_sys::window()?.crypto().ok().map(|c| c.random_uuid())),
})
}
/// Post what is queued.
pub fn send() {
let (Some(key), Some(window)) = (key(), web_sys::window()) else { return };
let url = format!("{}/batch/", usage::DEFAULT_HOST);
while let Some(batch) = usage::take_batch() {
let init = web_sys::RequestInit::new();
init.set_method("POST");
init.set_body(&wasm_bindgen::JsValue::from_str(&batch.body(key)));
// The Fetch standard's `keepalive` (a closing page still sends it); web-sys has no setter.
let _ = js_sys::Reflect::set(&init, &"keepalive".into(), &true.into());
let headers = web_sys::Headers::new().ok();
if let Some(h) = &headers {
let _ = h.set("Content-Type", "application/json");
init.set_headers(h);
}
let promise = window.fetch_with_str_and_init(&url, &init);
wasm_bindgen_futures::spawn_local(async move {
// Offline or refused: the batch is dropped.
if let Err(e) = wasm_bindgen_futures::JsFuture::from(promise).await {
log::debug!("usage: not sent: {}", crate::web::js_err(e));
}
});
}
}
/// When the page is closed or left: the session's length, then send.
pub fn send_when_hidden(window: &web_sys::Window) {
let on_hide = wasm_bindgen::closure::Closure::<dyn FnMut()>::new(|| {
usage::closing();
send();
});
if let Err(e) = window.add_event_listener_with_callback("pagehide", on_hide.as_ref().unchecked_ref()) {
log::warn!("usage: {}", crate::web::js_err(e));
}
on_hide.forget();
}
+27 -3
View File
@@ -74,6 +74,7 @@ pub fn start() {
fieldcraft_io::recovery::set_clock(|| js_sys::Date::now().max(0.0) as u64);
let Some(window) = web_sys::window() else { return };
ask_before_unload(&window);
crate::usage::send_when_hidden(&window);
let Some(canvas) = element(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
@@ -86,6 +87,10 @@ pub fn start() {
Box::new(|cc| {
let inbox = Inbox::default();
let mut app = ModelApp::new(Session::default()).with_services(services(inbox.clone(), cc.egui_ctx.clone()));
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
if let Some(host) = crate::usage::host() {
app = app.with_usage(host);
}
if let Some(rs) = &cc.wgpu_render_state {
let info = rs.adapter.get_info();
log::info!("fieldcraft-web: graphics {:?} {}, MSAA {}x", info.backend, info.name, rs.msaa_samples);
@@ -102,7 +107,8 @@ pub fn start() {
if recoverable > 0 {
app.set_status(format!("{recoverable} autosaved model(s) can be recovered: File › Recover…"), false);
}
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false }))
let deploy = crate::deploy::Watch::start();
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false, sent_at: 0.0, deploy }))
}),
)
.await;
@@ -188,8 +194,10 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
pick_save: Some(Box::new(|name: &str, _: &[Filter]| Some(page_path(name)))),
// The recent list holds the page's files, which go with the page.
recent_path: None,
// Preferences last for the page's run.
prefs_path: None,
// Preferences are kept in the browser's local storage.
prefs: Some(crate::usage::prefs_store()),
// egui opens links itself in the browser.
open_url: None,
}
}
@@ -204,6 +212,10 @@ struct Shell {
autosaved_at: f64,
/// The last autosave did not fit in the browser's storage (said once until one fits).
storage_error: bool,
/// App time usage events were last sent.
sent_at: f64,
/// Looks for a new deployment of the app.
deploy: crate::deploy::Watch,
}
impl Shell {
@@ -269,7 +281,19 @@ impl eframe::App for Shell {
self.open_arrived();
self.app.logic(ctx);
self.autosave(ctx);
if self.app.now - self.sent_at >= crate::usage::INTERVAL {
self.sent_at = self.app.now;
crate::usage::send();
}
UNSAVED.with(|u| u.set(self.app.session.is_dirty() && !self.app.session.journal.is_empty()));
if self.app.now - self.deploy.looked_at >= crate::deploy::INTERVAL || self.app.now < self.deploy.looked_at {
self.deploy.looked_at = self.app.now;
self.deploy.look();
}
if self.deploy.found() && !self.app.reload_offered() {
self.app.offer_reload(Box::new(crate::deploy::reload));
}
ctx.request_repaint_after(std::time::Duration::from_secs_f64(crate::deploy::INTERVAL));
}
/// Dropped files are read here (browsers read them asynchronously) and arrive through the
+6
View File
@@ -13,11 +13,17 @@ workspace = true
fieldcraft-engine = { workspace = true }
fieldcraft-ui-egui = { workspace = true }
fieldcraft-io = { workspace = true }
fieldcraft-update = { workspace = true }
rfd = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# Usage analytics (docs/privacy.md): an HTTPS POST with rustls on ring, checked against the
# operating system's certificates (no bundled root list), and a random install id.
ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "platform-verifier"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
getrandom = "0.3"
[build-dependencies]
# The Windows executable's icon resource (build.rs).
+5
View File
@@ -115,6 +115,11 @@ fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
}
ctx.request_repaint();
let mut r = rrx.recv_timeout(REPLY_TIMEOUT).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
// A request waiting for a job (a solve, a mesher): its reply comes when the job
// ends, however long it runs; the job always answers, even when cancelled.
if r.get(fieldcraft_ui_egui::control::PENDING).is_some() {
r = rrx.recv().unwrap_or_else(|_| json!({"ok": false, "error": "the job ended without a reply"}));
}
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
+89 -6
View File
@@ -12,9 +12,11 @@
#![forbid(unsafe_code)]
mod control_server;
mod update;
mod usage;
use fieldcraft_engine::Session;
use fieldcraft_engine::autosave::{self, Autosaver};
use fieldcraft_engine::{Session, crash, logfile};
use fieldcraft_ui_egui::{Filter, ModelApp, Services};
const USAGE: &str =
@@ -47,6 +49,10 @@ struct App {
autosaver: Option<Autosaver>,
/// App time of the last autosave check.
autosaved_at: f64,
/// The first frame was drawn (the crash journal says the app is up).
running: bool,
/// Sends the anonymous usage events, when this run may (docs/privacy.md).
usage: Option<usage::Sender>,
}
impl App {
@@ -61,6 +67,10 @@ impl App {
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
if !self.running {
self.running = true;
crash::activity("running");
}
self.app.logic(ctx);
if self.app.now - self.autosaved_at >= AUTOSAVE_SECONDS {
self.autosaved_at = self.app.now;
@@ -76,6 +86,16 @@ impl eframe::App for App {
{
log::warn!("autosave: {e}");
}
self.app.usage_closing();
if let Some(u) = self.usage.take() {
u.finish();
}
// An update the user chose to install: swapped in now that the window has closed.
if let Some(staged) = self.app.take_staged_update() {
update::finish(&staged);
}
log::info!("FieldCraft closed");
crash::end_session();
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(raw);
@@ -95,10 +115,57 @@ fn services() -> Services {
})),
// Beside the recovery folder in the per-user data folder.
recent_path: fieldcraft_io::recovery::default_dir().and_then(|d| d.parent().map(|p| p.join("recent.json"))),
prefs_path: fieldcraft_io::recovery::default_dir().and_then(|d| d.parent().map(|p| p.join("prefs.json"))),
prefs: fieldcraft_io::recovery::default_dir()
.and_then(|d| d.parent().map(|p| fieldcraft_ui_egui::files::PrefsStore::file(p.join("prefs.json")))),
open_url: Some(Box::new(open_url)),
}
}
/// Open a web link in the default browser, with the system's own opener: `open` (macOS),
/// `xdg-open` (Linux and the BSDs), `explorer` (Windows). The link is one argument, never
/// passed through a shell. Only https links are opened.
fn open_url(url: &str) -> Result<(), String> {
if !url.starts_with("https://") {
return Err(format!("not a web link: {}", url.chars().take(80).collect::<String>()));
}
let opener = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
};
let mut child = std::process::Command::new(opener).arg(url).spawn().map_err(|e| format!("{opener}: {e}"))?;
// Reaped off the window thread; its exit status says nothing (`explorer` exits with 1 even
// when it opened the link).
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
/// Crash reports and the log file (docs/crash-reports.md): reports of earlier runs that crashed
/// come back, for the window to offer. Both live in the app's data folder (a temporary one in
/// runs driven by automation); `FIELDCRAFT_CRASH_DIR` moves the crash folder.
fn start_reporting() -> Vec<crash::Summary> {
// First the crash reports: an unclean exit's report takes the dead run's lines from the log.
let crashed = crash::default_dir().map(|dir| crash::install(dir, crash::Build::current())).unwrap_or_default();
match fieldcraft_io::recovery::data_dir().map(|d| logfile::install(&d.join("logs"), log::LevelFilter::Info)) {
Some(Ok(path)) => eprintln!("fieldcraft: log {}", path.display()),
Some(Err(e)) => eprintln!("fieldcraft: no log file: {e}"),
None => {}
}
let b = crash::Build::current();
log::info!(
"FieldCraft {} started ({}), crash reports in {}",
b.version,
b.version_line(),
crash::default_dir().map(|d| d.display().to_string()).unwrap_or_default()
);
crash::activity("startup");
crashed
}
/// Command-line options.
#[derive(Debug, Default, PartialEq)]
struct Args {
@@ -152,9 +219,10 @@ fn main() -> eframe::Result {
};
if args.control.is_some() {
// A run driven by automation keeps its autosaves (and recent files and preferences, which
// live beside them) in a temporary folder, never the user's.
// live beside them), its crash reports and its log in a temporary folder, never the user's.
fieldcraft_io::recovery::use_automation_dir();
}
let crashed = start_reporting();
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("FieldCraft")
@@ -177,12 +245,26 @@ fn main() -> eframe::Result {
"FieldCraft",
options,
Box::new(move |cc| {
let mut app = ModelApp::new(Session::default()).with_services(services());
let mut session = Session::default();
// The window's model: its commands go into the crash journal.
session.crash_journal = crash::enabled();
let mut app = ModelApp::new(session).with_services(services());
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
let usage = match usage::host(args.control.is_some()) {
Some(host) => {
app = app.with_usage(host);
usage::start()
}
None => None,
};
// Updates (docs/updates.md): checked at most daily when on, installed only on a click.
fieldcraft_engine::enable_update_checks(true);
app = app.with_updates(update::host(cc.egui_ctx.clone(), args.control.is_some()));
app.custom_titlebar = CUSTOM_TITLEBAR;
app.integrated_titlebar = cfg!(target_os = "macos");
if let Some(rs) = &cc.wgpu_render_state {
let info = rs.adapter.get_info();
eprintln!("fieldcraft: graphics {:?} {}, MSAA {}x (requested {MSAA}x)", info.backend, info.name, rs.msaa_samples);
log::info!("graphics {:?} {} ({}), MSAA {}x (requested {MSAA}x)", info.backend, info.name, info.driver, rs.msaa_samples);
app.set_wgpu(rs, DEPTH_BITS, rs.msaa_samples, &cc.egui_ctx);
}
if let Some(port) = args.control {
@@ -202,7 +284,8 @@ fn main() -> eframe::Result {
}
Autosaver::new(&dir).map_err(|e| log::warn!("autosave unavailable: {e}")).ok()
});
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0 }))
app.announce_crashes(&crashed);
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0, running: false, usage }))
}),
)
}
+105
View File
@@ -0,0 +1,105 @@
//! The desktop app's side of updates (docs/updates.md): it runs the window's update jobs
//! ([`fieldcraft_ui_egui::updates`]) on background threads with [`fieldcraft_update`], and swaps
//! a staged release in after the window has closed ([`finish`]).
//!
//! Automatic checks are off in runs driven by automation (`--control`) and under CI, so test
//! and agent runs never reach GitHub on their own; `FIELDCRAFT_UPDATE_HOST` (a local test
//! server) turns them back on. Help › Check for Updates works in every run.
use std::cell::Cell;
use std::path::Path;
use std::sync::mpsc;
use fieldcraft_ui_egui::updates::{Event, Job, UpdateHost};
use fieldcraft_update::install::{self, Finish, Install};
use fieldcraft_update::net::{Client, Which};
use fieldcraft_update::stage::{self, Options};
use fieldcraft_update::{Release, Staged};
/// What the window needs for updates.
pub fn host(ctx: egui::Context, automation: bool) -> UpdateHost {
let here = install::here();
log::info!("updates: {}", here.describe());
stage::clean_stale(&here);
let env = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());
let automatic = env(fieldcraft_update::HOST_ENV) || !(automation || env("CI"));
let (tx, events) = mpsc::channel::<Event>();
let unsupported = here.unsupported();
let start = move |job: Job| {
let (tx, ctx, here) = (tx.clone(), ctx.clone(), here.clone());
let spawned = std::thread::Builder::new().name("fieldcraft update".into()).spawn(move || {
let send = |e: Event| {
let _ = tx.send(e);
ctx.request_repaint();
};
let client = Client::from_env();
match job {
Job::Check { manual } => send(Event::Checked { manual, result: client.check().map_err(|e| e.to_string()) }),
Job::Stage(release) => send(Event::Staged(stage_release(&client, &release, &here, &send))),
Job::Reinstall => {
let staged = client
.release(&Which::Version(fieldcraft_update::current()))
.map_err(|e| e.to_string())
.and_then(|r| stage_release(&client, &r, &here, &send));
send(Event::Staged(staged));
}
}
});
if let Err(e) = spawned {
log::warn!("updates: no thread: {e}");
}
};
UpdateHost { unsupported, automatic, start: Box::new(start), events, now: Box::new(now), open_file: Box::new(open_file) }
}
/// Download, verify and stage `release`, reporting each whole percent.
fn stage_release(client: &Client, release: &Release, here: &Install, send: &dyn Fn(Event)) -> Result<Staged, String> {
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
let last = Cell::new(u64::MAX);
let progress = |done: u64, total: u64| {
let step = done.saturating_mul(100).checked_div(total).unwrap_or(done / (1024 * 1024));
if last.replace(step) != step {
send(Event::Progress(done, total));
}
};
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
let staged = stage::stage(client, release, here, &options).map_err(|e| e.to_string());
match &staged {
Ok(s) => log::info!("updates: FieldCraft {} verified and staged at {}", s.version, s.payload.display()),
Err(e) => log::warn!("updates: FieldCraft {} not staged: {e}", release.version),
}
staged
}
/// Swap `staged` in and start it: the window has closed, its autosave is closed.
pub fn finish(staged: &Staged) {
match install::plan(staged, true) {
Ok(Finish::Swap(plan)) => match stage::apply(&plan) {
Ok(()) => log::info!("updates: FieldCraft {} installed ({})", staged.version, staged.install.describe()),
Err(e) => log::error!("updates: FieldCraft {} not installed, the previous version is kept: {e}", staged.version),
},
Ok(Finish::Package { .. }) => {}
Err(e) => log::error!("updates: {e}"),
}
}
/// Seconds since the Unix epoch.
fn now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Open a downloaded package with the system's handler for it (Linux: the software installer).
fn open_file(path: &Path) -> Result<(), String> {
let opener = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
};
let mut child = std::process::Command::new(opener).arg(path).spawn().map_err(|e| format!("{opener}: {e}"))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
+116
View File
@@ -0,0 +1,116 @@
//! Sending the anonymous usage events (docs/privacy.md) to PostHog Cloud EU: a background
//! thread posts the queued events ([`fieldcraft_engine::usage`]) in batches every half minute and
//! when the window closes. A failed post (offline, a slow network) drops its batch silently;
//! nothing waits on it but the thread.
//!
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`, which only the release workflow
//! sets: local, development and fork builds have none and send nothing.
use std::sync::mpsc;
use std::time::Duration;
use fieldcraft_engine::usage;
use fieldcraft_ui_egui::privacy::UsageHost;
/// The PostHog project key the release build was made with.
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
/// How often queued events are sent.
const INTERVAL: Duration = Duration::from_secs(30);
/// The longest one post may take.
const TIMEOUT: Duration = Duration::from_secs(10);
/// How long closing the window waits for the last batch.
const LAST_WAIT: Duration = Duration::from_secs(2);
fn key() -> Option<&'static str> {
KEY.map(str::trim).filter(|k| !k.is_empty())
}
/// What the window needs to ask and record, when this run may share usage: the build has a key,
/// `FIELDCRAFT_TELEMETRY` is not `0`, and neither CI nor `--control` automation runs it (unless
/// `FIELDCRAFT_TELEMETRY=1`).
pub fn host(automation: bool) -> Option<UsageHost> {
let telemetry = std::env::var("FIELDCRAFT_TELEMETRY").ok();
let ci = std::env::var_os("CI").is_some_and(|v| !v.is_empty());
usage::allowed(key().is_some(), telemetry.as_deref(), automation, ci).then(|| UsageHost {
platform: "desktop",
os: std::env::consts::OS,
arch: std::env::consts::ARCH,
new_id: Box::new(new_id),
})
}
/// A random (version 4) UUID from the operating system's random source.
fn new_id() -> Option<String> {
let mut b = [0u8; 16];
getrandom::fill(&mut b).ok()?;
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
Some(format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]))
}
/// The sending thread; [`Sender::finish`] sends what is left and stops it.
pub struct Sender {
stop: mpsc::Sender<()>,
finished: mpsc::Receiver<()>,
}
/// Start the sending thread (only when the build has a key). `FIELDCRAFT_TELEMETRY_HOST`
/// replaces PostHog's host, for checking the payload against a local listener.
pub fn start() -> Option<Sender> {
let key = key()?;
let host = std::env::var("FIELDCRAFT_TELEMETRY_HOST").ok().filter(|h| !h.trim().is_empty()).unwrap_or_else(|| usage::DEFAULT_HOST.into());
let url = format!("{}/batch/", host.trim_end_matches('/'));
// rustls's process-wide crypto (ring); another part of the app may have installed it first.
let _ = rustls::crypto::ring::default_provider().install_default();
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(TIMEOUT))
.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build())
.build()
.into();
let (stop, stopped) = mpsc::channel::<()>();
let (done, finished) = mpsc::channel::<()>();
let spawned = std::thread::Builder::new().name("fieldcraft usage".into()).spawn(move || {
loop {
let last = !matches!(stopped.recv_timeout(INTERVAL), Err(mpsc::RecvTimeoutError::Timeout));
while let Some(batch) = usage::take_batch() {
if let Err(e) = agent.post(&url).header("Content-Type", "application/json").send(batch.body(key)) {
// Offline or refused: this batch is dropped, the rest waits for the next try.
log::debug!("usage: {} event(s) not sent: {e}", batch.events.len());
break;
}
}
if last {
let _ = done.send(());
return;
}
}
});
match spawned {
Ok(_) => Some(Sender { stop, finished }),
Err(e) => {
log::warn!("usage: no sending thread: {e}");
None
}
}
}
impl Sender {
/// Send what is queued (waiting briefly) and stop.
pub fn finish(self) {
let _ = self.stop.send(());
let _ = self.finished.recv_timeout(LAST_WAIT);
}
}
#[cfg(test)]
mod tests {
#[test]
fn install_ids_are_random_version_4_uuids() {
let (a, b) = (super::new_id().unwrap(), super::new_id().unwrap());
assert_ne!(a, b);
assert_eq!(a.len(), 36);
assert_eq!(a.as_bytes()[14], b'4');
assert!(matches!(a.as_bytes()[19], b'8' | b'9' | b'a' | b'b'), "{a}");
}
}
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>diagnostics.bug_report</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M12 8.5 L12 8.5 C14.209 8.5 16 10.291 16 12.5 L16 15.5 C16 17.709 14.209 19.5 12 19.5 L12 19.5 C9.791 19.5 8 17.709 8 15.5 L8 12.5 C8 10.291 9.791 8.5 12 8.5 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.9 5.8 C9.9 4.64 10.84 3.7 12 3.7 C13.16 3.7 14.1 4.64 14.1 5.8 C14.1 6.96 13.16 7.9 12 7.9 C10.84 7.9 9.9 6.96 9.9 5.8 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 10.5 L12 18" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 11.5 L4.8 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 14.5 L4.4 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.3 17.4 L5 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16 11.5 L19.2 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16 14.5 L19.6 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.7 17.4 L19 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>geometry.datum.axis</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M7 17 L19 5" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M20 4 L15 5.2 M20 4 L18.8 9" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 18.5 L2.5 21.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
<path d="M8.8 12 C8.8 10.233 10.233 8.8 12 8.8 C13.767 8.8 15.2 10.233 15.2 12 C15.2 13.767 13.767 15.2 12 15.2 C10.233 15.2 8.8 13.767 8.8 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.6 12 C10.6 11.227 11.227 10.6 12 10.6 C12.773 10.6 13.4 11.227 13.4 12 C13.4 12.773 12.773 13.4 12 13.4 C11.227 13.4 10.6 12.773 10.6 12 Z" fill="#f0b44a"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>geometry.datum.point</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M3 16 L9 10 L21 10 L15 16 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 3 L12 11 M8 7 L16 7" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.2 7 C10.2 6.006 11.006 5.2 12 5.2 C12.994 5.2 13.8 6.006 13.8 7 C13.8 7.994 12.994 8.8 12 8.8 C11.006 8.8 10.2 7.994 10.2 7 Z" fill="#f0b44a"/>
<path d="M12 12.5 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 846 B

Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.block</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M4 6 L16 3 L20 15 L8 19 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 5 L12.33 16.33 M12 4 L16.67 17.67 M5.33 10.33 L17.33 7 M6.67 14.67 L18.67 11" fill="none" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 559 B

Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.mirror</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M12 2 L12 22" fill="none" stroke="#4f9ce8" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="2 1.5"/>
<path d="M10 5 L3 7 L3 17 L10 19 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3 12 L10 12 M6.5 6 L6.5 18" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 5 L21 7 L21 17 L14 19 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 12 L21 12 M17.5 6 L17.5 18" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 923 B

Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.node.relax</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M3 12 C3 7.029 7.029 3 12 3 C16.971 3 21 7.029 21 12 C21 16.971 16.971 21 12 21 C7.029 21 3 16.971 3 12 Z" fill="none" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="2 2"/>
<path d="M5 12 L19 12 M12 5 L12 19" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.5 8 L16.5 8 M7.5 16 L16.5 16 M8 7.5 L8 16.5 M16 7.5 L16 16.5" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.6 12 C9.6 10.675 10.675 9.6 12 9.6 C13.325 9.6 14.4 10.675 14.4 12 C14.4 13.325 13.325 14.4 12 14.4 C10.675 14.4 9.6 13.325 9.6 12 Z" fill="#4f9ce8" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1017 B

Binary file not shown.
@@ -0,0 +1 @@
{"shapes": [{"rect": [8, 8.5, 8, 11], "radius": 4, "stroke": "line", "width": 1.6}, {"circle": [12, 5.8, 2.1], "stroke": "line", "width": 1.6}, {"line": [12, 10.5, 12, 18], "stroke": "accent", "width": 1.5}, {"line": [8, 11.5, 4.8, 9.8], "stroke": "line"}, {"line": [8, 14.5, 4.4, 14.5], "stroke": "line"}, {"line": [8.3, 17.4, 5, 19.4], "stroke": "line"}, {"line": [16, 11.5, 19.2, 9.8], "stroke": "line"}, {"line": [16, 14.5, 19.6, 14.5], "stroke": "line"}, {"line": [15.7, 17.4, 19, 19.4], "stroke": "line"}]}
@@ -0,0 +1 @@
{"shapes": [{"d": "M7 17 L19 5", "stroke": "accent", "width": 2}, {"d": "M20 4 L15 5.2 M20 4 L18.8 9", "stroke": "accent", "width": 2}, {"d": "M5.5 18.5 L2.5 21.5", "stroke": "line", "dash": [1.5, 2]}, {"circle": [12, 12, 3.2], "fill": "soft", "stroke": "line", "width": 1.25}, {"circle": [12, 12, 1.4], "fill": "warm", "stroke": null}]}
@@ -0,0 +1 @@
{"shapes": [{"d": "M3 16 L9 10 L21 10 L15 16 Z", "fill": "soft", "stroke": "line", "width": 1.25}, {"d": "M12 3 L12 11 M8 7 L16 7", "stroke": "accent", "width": 2}, {"circle": [12, 7, 1.8], "fill": "warm", "stroke": null}, {"d": "M12 12.5 L12 20", "stroke": "line", "dash": [1.5, 2]}]}
+1
View File
@@ -0,0 +1 @@
{"shapes": [{"d": "M4 6 L16 3 L20 15 L8 19 Z", "fill": "soft", "stroke": "line"}, {"d": "M8 5 L12.33 16.33 M12 4 L16.67 17.67 M5.33 10.33 L17.33 7 M6.67 14.67 L18.67 11", "stroke": "accent", "width": 1}]}
+1
View File
@@ -0,0 +1 @@
{"shapes": [{"d": "M12 2 L12 22", "stroke": "accent", "width": 1.25, "dash": [2, 1.5]}, {"d": "M10 5 L3 7 L3 17 L10 19 Z", "fill": "soft", "stroke": "line"}, {"d": "M3 12 L10 12 M6.5 6 L6.5 18", "stroke": "line", "width": 1}, {"d": "M14 5 L21 7 L21 17 L14 19 Z", "fill": "soft", "stroke": "line"}, {"d": "M14 12 L21 12 M17.5 6 L17.5 18", "stroke": "line", "width": 1}]}
+1
View File
@@ -0,0 +1 @@
{"shapes": [{"circle": [12, 12, 9], "stroke": "line", "width": 1.25, "dash": [2, 2]}, {"d": "M5 12 L19 12 M12 5 L12 19", "stroke": "line", "width": 1.0}, {"d": "M7.5 8 L16.5 8 M7.5 16 L16.5 16 M8 7.5 L8 16.5 M16 7.5 L16 16.5", "stroke": "line", "width": 1.0}, {"circle": [12, 12, 2.4], "fill": "accent", "stroke": "accent"}]}
+1
View File
@@ -0,0 +1 @@
{"shapes": [{"d": "M2.5 13 C5.5 7.5 18.5 7.5 21.5 13 C18.5 18.5 5.5 18.5 2.5 13 Z", "fill": "soft", "stroke": "line"}, {"circle": [12, 13, 2.6], "fill": "accent", "stroke": "accent", "width": 1}, {"d": "M12 2.5 L12 5 M5.5 4.5 L7 6.5 M18.5 4.5 L17 6.5", "stroke": "warm", "width": 1.5}]}
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>view.show_all</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M2.5 13 C5.5 7.5 18.5 7.5 21.5 13 C18.5 18.5 5.5 18.5 2.5 13 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.4 13 C9.4 11.564 10.564 10.4 12 10.4 C13.436 10.4 14.6 11.564 14.6 13 C14.6 14.436 13.436 15.6 12 15.6 C10.564 15.6 9.4 14.436 9.4 13 Z" fill="#4f9ce8" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 2.5 L12 5 M5.5 4.5 L7 6.5 M18.5 4.5 L17 6.5" fill="none" stroke="#f0b44a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 820 B

Binary file not shown.
+2
View File
@@ -25,6 +25,8 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# app.update.check (docs/updates.md); the browser build has no update check.
fieldcraft-update = { workspace = true }
[dev-dependencies]
png = { workspace = true }
+1
View File
@@ -47,6 +47,7 @@ impl Autosaver {
let bytes = s.file_bytes(None)?;
self.slot.write(&bytes, s.path.as_deref(), s.model.nodes().len(), s.model.elements().len())?;
self.saved = Some(s.revision());
crate::crash::autosaved(s, &self.slot.file());
Ok(true)
}
+393
View File
@@ -0,0 +1,393 @@
//! Bug report drafts (Help › Report a Bug, and Report it after a crash): a GitHub new-issue link
//! that fills in the bug form (`.github/ISSUE_TEMPLATE/bug.yml`), and the files to attach.
//!
//! Nothing here sends anything. The user reviews the draft, then their browser opens the issue
//! form, which they submit or not.
//!
//! What a draft holds by default: the version, the OS, what went wrong (the user's words, the
//! last error or the crash's message) and, for a crash, where it happened. The user's home
//! folder is shown as `~`. Only with **Share my session** does it also carry the commands that
//! built the model (the replayable journal, which can name the user's files), and only with
//! **Include the model** as well the model file. A session too long for the link (GitHub
//! refuses long new-issue links) goes out as a file to attach and on the clipboard instead; the
//! model file is always one to attach.
use serde_json::{Value, json};
use crate::crash::without_home;
/// The issue form.
pub const ISSUE_URL: &str = "https://github.com/jyviko/fieldcraft/issues/new";
/// The longest link a draft opens: GitHub refuses new-issue links much past 8 KB.
pub const MAX_URL: usize = 7000;
/// The session file a draft attaches.
pub const SESSION_FILE: &str = "fieldcraft-session.json";
/// The model file a draft attaches.
pub const MODEL_FILE: &str = "model.fieldcraft";
/// Backtrace frames a crash's draft quotes.
const FRAMES: usize = 12;
/// A field's text is cut at this many bytes.
const MAX_FIELD: usize = 3000;
/// What to put in a draft.
#[derive(Clone, Debug, Default)]
pub struct Input {
pub title: String,
/// What happened: the user's words, or the last error.
pub observed: String,
/// A crash report (`crash::read`), when reporting one.
pub crash: Option<Value>,
/// Attach the replayable commands.
pub share_session: bool,
/// The commands (each `{command, params}`) that rebuild the model from `model` (or from an
/// empty model when there is none).
pub commands: Vec<Value>,
/// Attach the model file too (only with `share_session`).
pub include_model: bool,
pub model: Option<Vec<u8>>,
}
/// A file the user attaches to the issue.
#[derive(Clone, Debug, PartialEq)]
pub struct Attachment {
pub name: String,
pub bytes: Vec<u8>,
/// What it is, for the review.
pub what: String,
}
/// A draft ready for review.
#[derive(Clone, Debug, PartialEq)]
pub struct Draft {
pub title: String,
/// The bug form's fields by id (`observed`, `reproduction`, `evidence`, `version`), as the
/// link fills them.
pub fields: Vec<(&'static str, String)>,
/// The link that opens the filled form.
pub url: String,
/// Files to attach (the session when too long for the link, the model).
pub attachments: Vec<Attachment>,
/// Text to put on the clipboard (the session, when it is an attachment).
pub clipboard: Option<String>,
}
impl Draft {
/// The draft as JSON (attachments by name, size and what they are).
pub fn to_json(&self) -> Value {
json!({
"title": self.title,
"fields": self.fields.iter().map(|(k, v)| (k.to_string(), json!(v))).collect::<serde_json::Map<String, Value>>(),
"url": self.url,
"attachments": self.attachments.iter().map(|a| json!({"name": a.name, "bytes": a.bytes.len(), "what": a.what})).collect::<Vec<_>>(),
"clipboard": self.clipboard.as_ref().map(String::len),
})
}
}
/// `v0.5.8 (abc1234), macos aarch64`.
pub fn version_line(version: &str, commit: &str) -> String {
let commit = if commit.is_empty() { String::new() } else { format!(" ({commit})") };
format!("v{version}{commit}, {} {}", std::env::consts::OS, std::env::consts::ARCH)
}
/// Percent-encode `s` for a query value (RFC 3986 unreserved characters stay).
pub fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(char::from(b));
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
fn cut(s: &str, n: usize) -> String {
if s.len() <= n {
return s.to_string();
}
let mut end = n;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}\n[cut: {} bytes in all]", s.get(..end).unwrap_or_default(), s.len())
}
fn link(title: &str, fields: &[(&'static str, String)]) -> String {
let mut url = format!("{ISSUE_URL}?template=bug.yml&title={}", encode(title));
for (k, v) in fields {
if !v.is_empty() {
url.push_str(&format!("&{k}={}", encode(v)));
}
}
url
}
/// What a crash report says, for the evidence field: its kind, message, place, command (its id;
/// its parameters only with the session) and the top of its backtrace.
fn crash_evidence(report: &Value, share: bool) -> String {
let s = |k: &str| report.get(k).and_then(Value::as_str).unwrap_or("?");
let mut out =
format!("Crash report `{}` ({}), seen {} time(s)\n\n", s("id"), s("kind"), report.get("count").and_then(Value::as_u64).unwrap_or(1));
out.push_str(&format!("Message: {}\nAt: {}\n", without_home(s("message")), without_home(s("location"))));
if let Some(c) = report.get("command").filter(|c| !c.is_null()) {
let id = c.get("command").and_then(Value::as_str).unwrap_or("?");
match c.get("params").filter(|_| share) {
Some(p) => out.push_str(&format!("Command: `{id}` {}\n", without_home(&p.to_string()))),
None => out.push_str(&format!("Command: `{id}`\n")),
}
}
if let Some(a) = report.get("last_activity").and_then(Value::as_str) {
out.push_str(&format!("Last activity: {a}\n"));
}
let frames: Vec<&str> = report.get("backtrace").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).take(FRAMES).collect();
if !frames.is_empty() {
out.push_str("\nBacktrace (top):\n```\n");
for f in frames {
out.push_str(&without_home(f));
out.push('\n');
}
out.push_str("```\n");
}
out
}
/// The draft for `input`, by the [`version_line`] `version`.
pub fn draft(input: &Input, version: &str) -> Draft {
let crash = input.crash.as_ref();
let mut title = input.title.trim().to_string();
if title.is_empty() {
title = match crash.and_then(|c| c.get("kind")).and_then(Value::as_str) {
Some("unclean_exit") => "FieldCraft closed unexpectedly".to_string(),
Some(_) => "Internal error".to_string(),
None => match input.observed.trim().lines().next().filter(|l| !l.is_empty()) {
Some(line) => format!("Bug: {}", line.chars().take(100).collect::<String>()),
None => "Bug report".to_string(),
},
};
if let Some(c) = crash.and_then(|c| c.get("command")).and_then(|c| c.get("command")).and_then(Value::as_str) {
title.push_str(&format!(" in {c}"));
}
}
let title = cut(&without_home(&title), 200);
let mut observed = without_home(input.observed.trim());
if observed.is_empty()
&& let Some(m) = crash.and_then(|c| c.get("message")).and_then(Value::as_str)
{
observed = without_home(m);
}
let observed = cut(&observed, MAX_FIELD);
let share = input.share_session;
let mut evidence = crash.map(|c| crash_evidence(c, share)).unwrap_or_default();
let mut attachments = Vec::new();
let mut clipboard = None;
let mut reproduction = String::new();
// The session: the replayable script, from the attached model when there is one.
let model = input.model.as_ref().filter(|_| share && input.include_model);
let script = share.then(|| {
let mut steps = Vec::new();
if model.is_some() {
steps.push(json!({"command": "file.open", "params": {"path": MODEL_FILE}}));
}
steps.extend(input.commands.iter().cloned());
Value::Array(steps)
});
if let Some(m) = model {
attachments.push(Attachment { name: MODEL_FILE.into(), bytes: m.clone(), what: format!("the model ({} KB)", m.len().div_ceil(1024)) });
}
if let Some(script) = &script {
let n = script.as_array().map_or(0, Vec::len);
reproduction = format!("Replay the attached session ({n} command(s)): `fieldcraft-cli run {SESSION_FILE}`");
if model.is_some() {
reproduction.push_str(&format!(" in a folder holding `{MODEL_FILE}` too"));
} else if crash.is_some_and(|c| c.get("files").and_then(|f| f.get("model")).is_some()) {
reproduction.push_str(" (the crash replays from the model, which is not attached)");
}
reproduction.push('.');
}
let inline = |evidence: &str, script: &Value| {
let text = serde_json::to_string_pretty(script).unwrap_or_default();
format!("{evidence}\nSession ({SESSION_FILE}):\n```json\n{text}\n```\n")
};
let fields = |evidence: String| {
vec![("observed", observed.clone()), ("reproduction", reproduction.clone()), ("evidence", evidence), ("version", version.to_string())]
};
// The session in the link when it fits, else a file to attach (also on the clipboard).
let mut url = String::new();
if let Some(script) = &script {
let candidate = fields(inline(&evidence, script));
let u = link(&title, &candidate);
if u.len() <= MAX_URL {
evidence = inline(&evidence, script);
url = u;
} else {
let text = serde_json::to_string_pretty(script).unwrap_or_default();
evidence.push_str(&format!(
"\nThe session is too long for this form: FieldCraft saved it as `{SESSION_FILE}` and copied it to the clipboard. Attach the file here (drag it in) or paste it.\n"
));
attachments.insert(0, Attachment { name: SESSION_FILE.into(), bytes: text.clone().into_bytes(), what: "the session's commands".into() });
clipboard = Some(text);
}
}
if model.is_some() {
evidence.push_str(&format!("\nThe model is attached as `{MODEL_FILE}` (drag it in from the folder FieldCraft saved it to).\n"));
}
if url.is_empty() || model.is_some() {
let mut f = fields(evidence.clone());
url = link(&title, &f);
// Still too long (a very long message): cut the longest field until it fits.
while url.len() > MAX_URL {
let Some((i, len)) = f.iter().enumerate().map(|(i, (_, v))| (i, v.len())).max_by_key(|(_, l)| *l) else { break };
if len < 200 {
break;
}
if let Some((_, v)) = f.get_mut(i) {
*v = cut(v, len.saturating_sub(url.len() - MAX_URL + 64).min(len / 2 + 1));
}
url = link(&title, &f);
}
evidence = f.get(2).map(|(_, v)| v.clone()).unwrap_or_default();
}
let fields = fields(evidence);
// The fields as the link carries them (a cut field included).
let fields = if url == link(&title, &fields) { fields } else { decode_fields(&url) };
Draft { title, fields, url, attachments, clipboard }
}
/// Write a draft's attachments to `bug-reports/<time>/` in the app's data folder (the user
/// attaches them from there); returns the folder.
pub fn save_attachments(draft: &Draft) -> Result<std::path::PathBuf, String> {
let root = fieldcraft_io::recovery::data_dir().ok_or("no data folder on this system")?;
let dir = root.join("bug-reports").join(crate::crash::stamp_now());
fieldcraft_io::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
for a in &draft.attachments {
fieldcraft_io::fs::write_atomic(&dir.join(&a.name), &a.bytes, false).map_err(|e| e.to_string())?;
}
Ok(dir)
}
/// The fields a link carries (for the review, when a field had to be cut).
fn decode_fields(url: &str) -> Vec<(&'static str, String)> {
let query = url.split_once('?').map_or("", |(_, q)| q);
["observed", "reproduction", "evidence", "version"]
.into_iter()
.map(|k| {
let v = query.split('&').find_map(|kv| kv.strip_prefix(k).and_then(|r| r.strip_prefix('='))).unwrap_or_default();
(k, decode(v))
})
.collect()
}
fn decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
let hex = b.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok());
match (c, hex) {
(b'%', Some(v)) => {
out.push(v);
i += 3;
}
_ => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
fn home() -> String {
std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_else(|_| "/home/someone".into())
}
fn crash() -> Value {
json!({
"id": "20261014-101500-00000000deadbeef", "kind": "command_panic", "count": 2,
"message": format!("index out of bounds in {}/model.fieldcraft", home()),
"location": "crates/mesh/src/tet.rs:42",
"command": {"command": "mesh.tet.generate", "params": {"body": "Plate", "path": format!("{}/secret/plate.step", home())}},
"backtrace": ["fieldcraft_mesh::tet::insert (crates/mesh/src/tet.rs:42)"],
"files": {"model": "model.fieldcraft", "replay": "replay.json"},
})
}
#[test]
fn without_sharing_a_draft_names_no_paths_commands_or_model() {
let input = Input {
observed: format!("cannot open {}/parts/bracket.solidcraft", home()),
crash: Some(crash()),
commands: vec![json!({"command": "geometry.open", "params": {"path": format!("{}/parts/bracket.solidcraft", home())}})],
model: Some(b"model bytes".to_vec()),
include_model: true,
..Default::default()
};
let d = draft(&input, "v1.2.3, testos x");
assert!(d.url.starts_with("https://github.com/jyviko/fieldcraft/issues/new?template=bug.yml&title="), "{}", d.url);
assert!(d.attachments.is_empty() && d.clipboard.is_none(), "nothing attached without Share my session");
let all = format!("{} {:?} {}", d.title, d.fields, decode(&d.url));
assert!(!all.contains(&home()), "no home folder: {all}");
assert!(!all.contains("secret") && !all.contains("geometry.open"), "no parameters or commands: {all}");
assert!(all.contains("~/parts/bracket.solidcraft"), "the error, its home shown as ~: {all}");
assert!(all.contains("mesh.tet.generate") && all.contains("tet.rs:42") && all.contains("v1.2.3, testos x"), "{all}");
assert_eq!(d.title, "Internal error in mesh.tet.generate");
assert_eq!(decode_fields(&d.url), d.fields, "the review shows what the link carries");
}
#[test]
fn a_short_session_goes_in_the_link() {
let input = Input {
title: "Solve fails".into(),
share_session: true,
commands: vec![json!({"command": "file.sample", "params": {"name": "cantilever"}}), json!({"command": "solve.run", "params": {}})],
..Default::default()
};
let d = draft(&input, "v1");
assert!(d.attachments.is_empty() && d.clipboard.is_none());
let evidence = &d.fields.iter().find(|(k, _)| *k == "evidence").unwrap().1;
assert!(evidence.contains("\"command\": \"solve.run\""), "{evidence}");
assert!(d.url.len() <= MAX_URL);
assert!(decode(&d.url).contains("file.sample"));
}
#[test]
fn a_long_session_and_the_model_are_attachments() {
let commands: Vec<Value> = (0..400).map(|i| json!({"command": "mesh.node.add", "params": {"label": i + 1, "xyz": [i, 0, 0]}})).collect();
let input =
Input { share_session: true, include_model: true, commands, model: Some(vec![7; 3000]), crash: Some(crash()), ..Default::default() };
let d = draft(&input, "v1");
assert!(d.url.len() <= MAX_URL, "{}", d.url.len());
let names: Vec<&str> = d.attachments.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, [SESSION_FILE, MODEL_FILE]);
let session: Value = serde_json::from_slice(&d.attachments[0].bytes).unwrap();
assert_eq!(session[0], json!({"command": "file.open", "params": {"path": MODEL_FILE}}), "the replay opens the attached model");
assert_eq!(session.as_array().unwrap().len(), 401);
assert_eq!(d.clipboard.as_deref().map(str::as_bytes), Some(d.attachments[0].bytes.as_slice()));
let text = decode(&d.url);
assert!(text.contains("too long for this form") && text.contains(MODEL_FILE) && !text.contains("\"label\": 399"), "{text}");
// With the session shared, the crash's command parameters are shown (home as ~).
assert!(text.contains("~/secret/plate.step"), "{text}");
}
#[test]
fn a_huge_message_is_cut_to_fit_the_link() {
let input = Input { observed: "é".repeat(20_000), ..Default::default() };
let d = draft(&input, "v1");
assert!(d.url.len() <= MAX_URL, "{}", d.url.len());
assert!(d.fields[0].1.contains("[cut:"));
assert_eq!(decode_fields(&d.url), d.fields);
}
#[test]
fn encoding_round_trips() {
let s = "a b&c=d/é\n```json";
assert_eq!(decode(&encode(s)), s);
assert_eq!(encode("a b&"), "a%20b%26");
}
}
+130
View File
@@ -0,0 +1,130 @@
//! A cancelled job ([`fieldcraft_model::progress::Progress::cancel`]) stops every solver and
//! mesher promptly with `cancelled` and leaves the model as it was.
use std::time::{Duration, Instant};
use fieldcraft_geometry::sample::Plate;
use fieldcraft_model::progress::{self, Progress};
use serde_json::{Value, json};
use crate::Session;
use crate::sample::impact;
/// How long a cancelled command may keep running: one increment, time step or pass, far
/// below the minutes the runs below would take uncancelled.
const PROMPT: Duration = Duration::from_secs(5);
/// Run `command` on `s` the way a job does and cancel it once it reports the stage `stage`
/// (mid-run), or before it starts (`None`): it must fail with `cancelled`, soon after, leaving
/// the model and the journal as they were.
fn cancel(s: &mut Session, command: &str, params: Value, stage: Option<&str>) {
let (model, journal) = (s.model.clone(), s.journal.len());
let p = Progress::new();
if stage.is_none() {
p.cancel();
}
let (r, waited) = std::thread::scope(|scope| {
let worker = {
let p = p.clone();
let s = &mut *s;
let params = params.clone();
scope.spawn(move || progress::scoped(Some(p), || s.execute(command, &params)))
};
let mut at = Instant::now();
if let Some(stage) = stage {
let deadline = Instant::now() + Duration::from_secs(600);
while !worker.is_finished() && Instant::now() < deadline {
let now = p.snapshot();
if now.stage.starts_with(stage) && now.done > 0.0 {
at = Instant::now();
p.cancel();
break;
}
std::thread::sleep(Duration::from_millis(1));
}
assert!(p.is_cancelled(), "{command}: never reached stage `{stage}` ({:?})", p.snapshot());
}
let r = worker.join().unwrap();
(r, at.elapsed())
});
let e = r.expect_err(&format!("{command}: ran to the end although cancelled"));
assert!(e.is_cancelled(), "{command}: {e}");
assert_eq!(e.to_string(), "cancelled", "{command}");
assert!(waited < PROMPT, "{command}: stopped {waited:?} after the cancel");
assert!(s.model == model, "{command}: the model changed");
assert_eq!(s.journal.len(), journal, "{command}: journalled");
}
/// A sample's script run on a fresh session.
fn session(script: &Value) -> Session {
let mut s = Session::default();
s.run_script(script).unwrap();
s
}
fn plate() -> (crate::tests::TempDir, Session) {
let (dir, path) = crate::tests::sample_design_file(&Plate::default());
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
(dir, s)
}
#[test]
fn explicit_stops_between_time_steps() {
// A hundred times as long as the sample: hundreds of thousands of increments.
let mut script = impact();
for c in script.as_array_mut().unwrap() {
if c["command"] == "model.step.create" {
let p = &mut c["params"]["procedure"];
(p["end_time"], p["output_interval"], p["history_interval"]) = (json!(4e-3), json!(4e-4), json!(2e-5));
}
}
let mut s = session(&script);
cancel(&mut s, "solve.explicit", json!({}), Some("Time"));
}
#[test]
fn fluid_stops_between_lattice_steps() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "flow-past"})).unwrap();
cancel(&mut s, "solve.fluid", json!({}), Some("Fluid steps"));
}
#[test]
fn nonlinear_stops_between_increments() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "rubber-seal"})).unwrap();
cancel(&mut s, "solve.nonlinear", json!({}), Some("Load factor"));
}
#[test]
fn transient_heat_stops_between_increments() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "heated-bracket"})).unwrap();
s.execute(
"model.step.create",
&json!({"name": "Warm", "procedure": {"type": "heat_transfer", "transient": {"end_time": 1e5, "increment": 1}},
"boundary_conditions": ["Heater"], "loads": ["Air"]}),
)
.unwrap();
cancel(&mut s, "solve.heat", json!({"step": "Warm"}), Some("Time increment"));
}
#[test]
fn static_frequency_and_solve_all_stop_at_the_factorization() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
cancel(&mut s, "solve.static", json!({}), None);
cancel(&mut s, "solve.frequency", json!({}), None);
cancel(&mut s, "solve.run", json!({}), None);
}
#[test]
fn meshers_stop_and_leave_no_mesh() {
let (_dir, mut s) = plate();
cancel(&mut s, "mesh.tet.generate", json!({"body": "Body1", "size": 0.4}), Some("Refinement round"));
cancel(&mut s, "mesh.tet.generate", json!({"body": "Body1", "size": 2.5}), None);
cancel(&mut s, "mesh.hex.generate", json!({"body": "Body1", "size": 2.5}), None);
cancel(&mut s, "mesh.hex.octree", json!({"body": "Body1", "size": 5.0, "max_depth": 2}), None);
assert!(s.model.nodes().is_empty());
}
+87 -19
View File
@@ -155,8 +155,9 @@ pub struct Capability {
pub status: Status,
/// Related commands in the entry's drop-down (edit, delete…).
pub more: &'static [&'static str],
/// Commands the entry's own form covers (an option of it does the same): claimed by the entry
/// for the command search and the ribbon's stage, but not listed in the ribbon.
/// Commands the entry's own form covers (an option of it does the same), or that act on what
/// it makes from the browser's item menu (edit, delete): claimed by the entry for the command
/// search and the ribbon's stage, but not listed in the ribbon.
pub covers: &'static [&'static str],
}
@@ -237,7 +238,14 @@ pub static CATALOGUE: &[Capability] = &[
// ---- Geometry ----
ready("geometry.open", "Open Design", Geometry, "Import", "Open a SolidCraft design: its bodies with persistent face names"),
ready("geometry.import.mesh", "Tagged Mesh", Geometry, "Import", "Read a face-tagged surface mesh (3MF)"),
ready("geometry.bodies", "Bodies", Geometry, "Inspect", "List the open design's bodies, volumes and named faces"),
ready_more(
"geometry.bodies",
"Bodies",
Geometry,
"Inspect",
"List the open design's bodies, volumes and named faces, edges and vertices",
&["geometry.centre"],
),
ready("geometry.tessellate", "Tessellate", Geometry, "Inspect", "Tessellate a body into a face-tagged boundary surface"),
ready(
"mesh.surface.check",
@@ -246,21 +254,38 @@ pub static CATALOGUE: &[Capability] = &[
"Inspect",
"Weld, closed, manifold, orientation and self-intersection checks; feature edges",
),
ready_more(
// Edit and delete of datums and partitions are on the browser's item menu, not the ribbon.
covering(
"geometry.datum",
"Datum Plane",
Geometry,
"Prepare",
"Datum planes (principal plane and offset, three points, point and normal) and axes",
&["geometry.datum.axis", "geometry.datum.delete"],
"A datum plane: principal plane and offset, three points or datum points, point and normal, normal to an axis",
&["geometry.datum.edit", "geometry.datum.delete", "geometry.datum.suppress"],
),
ready_more(
covering(
"geometry.datum.axis",
"Datum Axis",
Geometry,
"Prepare",
"A datum axis: principal axis, two points or datum points, point and direction",
&["geometry.datum.axis.edit"],
),
covering(
"geometry.datum.point",
"Datum Point",
Geometry,
"Prepare",
"A datum point: coordinates, a mesh vertex, along an edge, a face's centre, an axis through a plane",
&["geometry.datum.point.edit"],
),
covering(
"geometry.partition",
"Partition",
Geometry,
"Prepare",
"Cut bodies into cells by a datum plane; the two faces of each cut are paired by name",
&["geometry.partition.delete"],
&["geometry.partition.delete", "geometry.partition.suppress"],
),
soon("geometry.midsurface", "Midsurface", Geometry, "Prepare", "M8", "Extract midsurfaces of thin parts for shell meshes"),
// ---- Mesh ----
@@ -307,7 +332,15 @@ pub static CATALOGUE: &[Capability] = &[
"One mesh of a partitioned part, a method per cell (hex, tet, or all hex as conforming blocks); cells joined across partitions",
&["mesh.hex.blocks"],
),
soon("mesh.hex.decompose", "Decompose", Mesh, "Structured Hex", "M5", "Find sweepable and mappable regions and propose the splits"),
ready("mesh.block", "Mesh Block", Mesh, "Structured Hex", "A mapped block of hex, wedge or quad elements between corner points"),
soon(
"mesh.hex.decompose",
"Decompose",
Mesh,
"Structured Hex",
"M5",
"Find sweepable and mappable regions of 3D parts (extruded cross-sections are already cut into blocks by Hex Mesh)",
),
soon("mesh.transition", "Transition", Mesh, "Structured Hex", "M5", "Conforming tet–hex interfaces with pyramids"),
ready(
"mesh.hex.octree",
@@ -321,16 +354,25 @@ pub static CATALOGUE: &[Capability] = &[
soon("mesh.smooth", "Smooth", Mesh, "Improve", "M6", "Smooth node positions, keeping every element valid"),
soon("mesh.untangle", "Untangle", Mesh, "Improve", "M6", "Repair inverted elements"),
soon("mesh.layers", "Layers", Mesh, "Improve", "M6", "Boundary padding and layers through thin walls"),
ready_more("mesh.node.add", "Node", Mesh, "Edit", "Add a node", &["mesh.node.remove"]),
ready_more(
"mesh.element.add",
"Element",
"mesh.node.relax",
"Relax Nodes",
Mesh,
"Improve",
"Relax the nodes inside a sphere to fix spikes and slivers; surface nodes slide on the geometry; kept as a field to apply again after a remesh",
&["mesh.node.relax.apply"],
),
ready_more("mesh.node.add", "Node", Mesh, "Edit", "Add a node", &["mesh.node.remove"]),
ready_more("mesh.element.add", "Element", Mesh, "Edit", "Add an element on existing nodes", &["mesh.element.remove", "mesh.clear"]),
ready("mesh.mirror", "Mirror Mesh", Mesh, "Edit", "Mirror a body's mesh across a plane, joined on the plane (mesh half a symmetric part)"),
ready_more(
"mesh.node.merge",
"Merge Nodes",
Mesh,
"Edit",
"Add an element on existing nodes, or a mapped block of them",
&["mesh.element.remove", "mesh.block", "mesh.mirror"],
"Merge coincident nodes, keeping sets, loads and boundary conditions on the survivors; check for duplicates and cracks, renumber",
&["mesh.check.duplicates", "mesh.renumber"],
),
soon("mesh.node.merge", "Merge Nodes", Mesh, "Edit", "M6", "Merge coincident nodes"),
soon("mesh.region.remesh", "Remesh Region", Mesh, "Edit", "M6", "Remesh a region in place; split and collapse elements"),
soon("mesh.import.orphan", "Orphan Mesh", Mesh, "Edit", "M6", "Import a mesh without geometry"),
ready("mesh.quality", "Quality", Mesh, "Verify", "Quality metrics and the certified validity check, failing elements listed"),
@@ -473,7 +515,14 @@ pub static CATALOGUE: &[Capability] = &[
"Contact",
"Find the parts of the mesh that touch, and make contact pairs of them",
),
soon("interaction.rigid_wall", "Rigid Wall", Interactions, "Contact", "M10", "Rigid walls for explicit dynamics"),
ready_more(
"interaction.rigid_wall",
"Rigid Wall",
Interactions,
"Contact",
"A fixed rigid plane a set's nodes cannot pass, with friction, in an explicit dynamics step",
&["interaction.rigid_wall.delete"],
),
soon("interaction.bolt", "Bolt Load", Interactions, "Connectors", "M7", "Bolt pretension"),
ready_more(
"model.spring.create",
@@ -539,7 +588,7 @@ pub static CATALOGUE: &[Capability] = &[
"Displacement, rotation, reaction and stress at nodes, element section forces, a mode shape, or an explicit field frame (or click the model)",
&["solve.history"],
),
ready("results.reactions", "Reactions", Results, "Query", "Reaction force and moment sums per set"),
ready_more("results.reactions", "Reactions", Results, "Query", "Reaction force and moment sums per set", &["results.export.csv"]),
soon("results.free_body", "Free Body", Results, "Query", "M9", "Free-body forces across a cut"),
soon("results.xy", "XY Plot", Results, "Plots", "M9", "Plot a quantity against time or another"),
soon("results.path", "Path Plot", Results, "Plots", "M9", "Plot a quantity along a path"),
@@ -549,8 +598,10 @@ pub static CATALOGUE: &[Capability] = &[
soon("results.read", "Read Results", Results, "Files", "M9", "Read results in public formats"),
soon("results.convergence", "Convergence", Results, "Files", "M9", "Mesh convergence studies"),
// ---- Tools ----
ready("model.info", "Model Info", Tools, "Model", "Node and element counts and the model summary"),
ready("file.open", "Open Model", Tools, "File", "Open a .fieldcraft model"),
// Renaming starts from a definition's item menu (Rename…); the search finds it here too.
ready_more("model.info", "Model Info", Tools, "Model", "Node and element counts and the model summary", &["model.rename"]),
// New starts from the File menu; the search finds it here too.
ready_more("file.open", "Open Model", Tools, "File", "Open a .fieldcraft model", &["file.new"]),
ready("file.sample", "Samples", Tools, "File", "Open a sample model, ready to solve"),
ready("file.save", "Save", Tools, "File", "Save the model to its .fieldcraft file"),
ready("file.save_as", "Save As", Tools, "File", "Save the model to a new .fieldcraft file"),
@@ -562,8 +613,25 @@ pub static CATALOGUE: &[Capability] = &[
"Open a model autosaved by an app that crashed or closed with unsaved changes",
&["file.recovery.list", "file.recovery.discard"],
),
// Hide, show and isolate act on the browser's items, from their eyes and item menus.
covering(
"view.show_all",
"Show All",
Tools,
"View",
"Show every item hidden in the viewport (hide, show and isolate items from the browser)",
&["view.hide", "view.show", "view.isolate"],
),
ready("edit.undo", "Undo", Tools, "History", "Undo the last command that changed the model"),
ready("edit.redo", "Redo", Tools, "History", "Redo the command undone last"),
ready_more(
"diagnostics.bug_report",
"Report a Bug",
Tools,
"Help",
"Draft a GitHub bug report with the version, the OS and the last error; you review it, and nothing is sent until you submit it",
&["diagnostics.crash_reports", "diagnostics.crash_report", "diagnostics.crash_reports.delete", "diagnostics.crash_test", "app.update.check"],
),
];
/// The catalogue entry with this id.
+423 -47
View File
@@ -2,13 +2,23 @@
//! typically made by `geometry.partition`) with its own method, all into one mesh, and the cells
//! joined across the partitions that divide them.
//!
//! **Sweeping together (#288).** The cells of one body of the design whose method may sweep
//! (`auto`, `hex`, `swept`, `extrude`, `revolve`) are first meshed together
//! ([`hex_mesh_swept_cells`]): one cross-section with every cell's cut faces imprinted, one
//! interval assignment and one set of layers, so cells meet node for node across every cut — a
//! cut that ends on another included — with no edge seeds, and their nodes are shared. When they
//! do not sweep together in one frame (the reply says why, per cell, as `not_swept_together`),
//! each cell is meshed alone as below.
//!
//! **Joining.** Two cells on either side of a partition `P` meet on faces named
//! `partition:P:a` and `partition:P:b`. Where the element faces of the two sides match node for
//! node (the same divisions and kind on both sides, e.g. a mesh and its mirror image) the
//! coincident nodes are merged and the mesh is conforming there. Elsewhere — a hex cell next to a
//! tet cell, or two cells meshed with different divisions — the two surfaces are tied: a set on
//! each side's partition faces and a tie between them (`interaction.tie`; dual mortar
//! constraints in the implicit analyses, so a constant stress crosses the interface exactly).
//! tet cell, or two cells meshed with different divisions — the two surfaces are tied
//! (`interaction.tie`; dual mortar constraints in the implicit analyses, so a constant stress
//! crosses the interface exactly). Each tie goes one way, by a fixed order of the cells (hex cells
//! main to tet cells), and each cell's tied cut faces make one tie, so no node is a secondary
//! node of two of them and no interface is tied both ways: either would over-constrain it (#389).
//! The tie is the transition between hex and tet cells; pyramid elements are not used, because
//! they need their own element formulation in every solver and deck, while the tie works for any
//! pair of meshes and keeps each cell's mesh as its method made it. The reply lists every
@@ -17,12 +27,14 @@
use std::collections::{BTreeMap, BTreeSet};
use fieldcraft_mesh::cdt::CdtOptions;
use fieldcraft_mesh::hex::{HexMesh, HexMethod};
use fieldcraft_mesh::hex::{Cell, CellsMesh, HexMesh, HexMethod, HexOptions, hex_mesh_swept_cells};
use fieldcraft_mesh::size::UniformSize;
use fieldcraft_mesh::surface::BoundarySurface;
use fieldcraft_model::geometry::Entity;
use fieldcraft_model::{ElementFace, GeometryRef, Model, Set, Tie};
use serde_json::{Value, json};
use super::hex::{Input, add_hex, hex_body};
use super::hex::{Input, add_cells, add_hex, hex_body};
use super::mesh::{BodyTets, add_tets, mesh_body, quality_options};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
@@ -30,7 +42,7 @@ use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const CELLS: CommandSpec = CommandSpec {
id: "mesh.cells",
label: "Partitioned Mesh",
params: r#"{"methods": {"Body1/a": "tet", "Body1/b": "swept"} (per cell; default `default`), "default": "auto", "bodies": ["Body1/a", "Body1/b"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 | 2 (hex8 and tet4, or hex20 and tet10), "tolerance": 0.05 (chordal tolerance, mm)} — replaces the cells' meshes (as mesh.tet.generate; other bodies keep theirs) with one mesh of the cells, each with its method: "auto" (structured hex where a method fits, else tet), "hex" (any structured hex method), "swept", "extrude", "sweep", "revolve", "mapped" or "tet"; or "default": "blocks" (with no `methods`): every cell a mapped block, division counts assigned over all cells together, exactly mesh.hex.blocks with the same parameters. Cells on either side of a partition (faces `partition:<name>:a` and `:b`) are joined: where their element faces match node for node the nodes are merged (conforming); otherwise, as between a hex and a tet cell, a set on each side and a tie between them are made (`tie_<partition>_<k>`, sets `<tie>_main` and `<tie>_secondary`: the side with fewer nodes is the main surface), replacing ties of those names from an earlier run. Reports each cell's method (and why auto fell back to tet), and each interface: `merged` with the nodes merged, or `tied`"#,
params: r#"{"methods": {"Body1/a": "tet", "Body1/b": "swept"} (per cell; default `default`), "default": "auto", "bodies": ["Body1/a", "Body1/b"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 | 2 (hex8 and tet4, or hex20 and tet10), "tolerance": 0.05 (chordal tolerance, mm)} — replaces the cells' meshes (as mesh.tet.generate; other bodies keep theirs) with one mesh of the cells, each with its method: "auto" (structured hex where a method fits, else tet), "hex" (any structured hex method), "swept", "extrude", "sweep", "revolve", "mapped" or "tet"; or "default": "blocks" (with no `methods`): every cell a mapped block, division counts assigned over all cells together, exactly mesh.hex.blocks with the same parameters. Cells on either side of a partition (faces `partition:<name>:a` and `:b`) are joined: where their element faces match node for node the nodes are merged (conforming); otherwise, as between a hex and a tet cell, they are tied: each cell's tied cut faces make one tie, `tie_<cell>` (`/` as `_`; sets `<tie>_main`, the facing cells' cut faces, and `<tie>_secondary`, the cell's own), hex cells main to tet cells and otherwise by name, so a node is a secondary node of one such tie only; the ties an earlier run made on these cells are replaced. The cells of one design body that may sweep (auto, hex, swept, extrude, revolve) are swept together first: one cross-section and one set of layers for all of them, so they share their nodes across every cut, T-junctions included, with no edge seeds (`swept_together` names the body; `not_swept_together` says why not, and those cells are meshed one by one). Reports each cell's method (and why auto fell back to tet), its `quality` (volume, smallest and mean scaled Jacobian, largest edge ratio), and each interface: `merged` with the nodes merged or shared, or `tied`"#,
form: Some(super::forms::CELLS),
kind: CommandKind::Model,
requires: &[Requirement::Design],
@@ -148,9 +160,55 @@ fn cells(s: &mut Session, p: &Value) -> Result<Value> {
let cdt = CdtOptions { max_steiner: s.limits.max_steiner, max_tets: tet_options.max_tets };
let seeds = super::seeds::edge_seeds(s)?;
let method_of = |n: &str| methods.get(n).copied().unwrap_or(default);
// The cells of one body that may sweep are swept together first (#288): one cross-section
// and one set of layers for all of them, so they meet node for node across their cuts. Cells
// that do not sweep together are meshed one by one, as below.
let mut groups: BTreeMap<(String, HexMethod), Vec<usize>> = BTreeMap::new();
for (i, shape) in shapes.iter().enumerate() {
let sweep = match method_of(&shape.name) {
Method::Auto | Method::Hex(HexMethod::Auto | HexMethod::Swept) => Some(HexMethod::Swept),
Method::Hex(m @ (HexMethod::Extrude | HexMethod::Revolve)) => Some(m),
Method::Hex(_) | Method::Tet => None,
};
if let (Some(m), Some(source)) = (sweep, design.source_of(&shape.name)) {
groups.entry((source.to_string(), m)).or_default().push(i);
}
}
let mut joint: Vec<Option<usize>> = vec![None; shapes.len()];
let mut not_together: BTreeMap<usize, String> = BTreeMap::new();
let mut swept: Vec<(String, Vec<usize>, Vec<Input>, CellsMesh)> = Vec::new();
for ((source, m), members) in groups {
if members.len() < 2 {
continue;
}
let inputs: Vec<Input> = members
.iter()
.filter_map(|&i| shapes.get(i))
.map(|shape| Ok(Input { seeds: seeds.clone(), ..super::hex::shape_input(shape, Some(tolerance))? }))
.collect::<Result<_>>()?;
match swept_together(p, &inputs, m, quadratic, size, tolerance, &seeds)? {
Ok(cm) => {
for &i in &members {
if let Some(slot) = joint.get_mut(i) {
*slot = Some(swept.len());
}
}
swept.push((source, members, inputs, cm));
}
Err(why) => {
for &i in &members {
not_together.insert(i, why.clone());
}
}
}
}
let mut meshed: Vec<(Meshed, Value)> = Vec::with_capacity(shapes.len());
for shape in shapes {
let method = methods.get(&shape.name).copied().unwrap_or(default);
for (i, shape) in shapes.iter().enumerate() {
if joint.get(i).copied().flatten().is_some() {
continue;
}
let method = method_of(&shape.name);
let input = || Ok::<_, EngineError>(Input { seeds: seeds.clone(), ..super::hex::shape_input(shape, Some(tolerance))? });
let hex = |m: HexMethod| -> Result<(Input<'static>, HexMesh)> {
let b = input()?;
@@ -175,6 +233,9 @@ fn cells(s: &mut Session, p: &Value) -> Result<Value> {
};
if let Some(o) = info.as_object_mut() {
o.insert("body".into(), json!(shape.name));
if let Some(why) = not_together.get(&i) {
o.insert("not_swept_together".into(), json!(why));
}
}
meshed.push((cell, info));
}
@@ -183,9 +244,29 @@ fn cells(s: &mut Session, p: &Value) -> Result<Value> {
// and the definitions stay.
let model = &mut s.model;
let cleared = super::replace::clear(model, names.iter().map(String::as_str));
let mut report = Vec::with_capacity(meshed.len());
for (cell, mut info) in meshed {
let (kind, elements, nodes) = match &cell {
let mut report: Vec<(usize, Value)> = Vec::with_capacity(shapes.len());
let mut interfaces = Vec::new();
for (source, members, inputs, cm) in &swept {
add_cells(model, inputs, cm)?;
let m = &cm.mesh;
for (c, (&i, b)) in members.iter().zip(inputs).enumerate() {
let elements: Vec<usize> = (0..m.element_count()).filter(|&e| cm.element_cell.get(e).is_some_and(|&x| x as usize == c)).collect();
let nodes: BTreeSet<u32> = elements.iter().filter_map(|&e| m.element(e)).flatten().copied().collect();
report.push((
i,
json!({"body": b.name, "method": m.report.method.name(), "swept_together": source, "description": m.report.description, "kind": m.kind.name(), "elements": elements.len(), "nodes": nodes.len()}),
));
}
interfaces.extend(swept_interfaces(&design, inputs, cm));
}
let mut k = 0;
for (i, _) in shapes.iter().enumerate() {
if joint.get(i).copied().flatten().is_some() {
continue;
}
let Some((cell, mut info)) = meshed.get_mut(k).map(|(c, v)| (c, std::mem::take(v))) else { break };
k += 1;
let (kind, elements, nodes) = match &*cell {
Meshed::Hex(b, m) => {
add_hex(model, b, m)?;
(m.kind, m.element_count(), m.nodes.len())
@@ -200,13 +281,135 @@ fn cells(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("elements".into(), json!(elements));
o.insert("nodes".into(), json!(nodes));
}
report.push(info);
report.push((i, info));
}
let interfaces = join(model, &names, COINCIDENT * diagonal)?;
report.sort_by_key(|r| r.0);
let report: Vec<Value> = report
.into_iter()
.map(|(_, mut info)| {
let quality = info.get("body").and_then(Value::as_str).map(|b| cell_quality(model, b));
if let (Some(o), Some(q)) = (info.as_object_mut(), quality) {
o.insert("quality".into(), q);
}
info
})
.collect();
let tet: BTreeSet<String> = report
.iter()
.filter(|r| r.get("kind").and_then(Value::as_str).is_some_and(|k| k.starts_with("tet")))
.filter_map(|r| r.get("body").and_then(Value::as_str).map(String::from))
.collect();
interfaces.extend(join(model, &names, &tet, COINCIDENT * diagonal)?);
let (nodes, elements) = (model.nodes().len(), model.elements().len());
Ok(cleared.report(s, json!({"cells": report, "interfaces": interfaces, "nodes": nodes, "elements": elements, "size": size})))
}
/// Sweep the cells `inputs` together ([`hex_mesh_swept_cells`]) with `method` (extrude,
/// revolve, or swept: either). `Ok(Err(why))` when they do not sweep together; limits and a
/// cancel are errors.
fn swept_together(
p: &Value,
inputs: &[Input],
method: HexMethod,
quadratic: bool,
size: Option<f64>,
tolerance: f64,
seeds: &[fieldcraft_mesh::seeds::EdgeSeed],
) -> Result<std::result::Result<CellsMesh, String>> {
let h = size.ok_or_else(|| EngineError::Params("no element size".into()))?;
let mut surfaces = Vec::with_capacity(inputs.len());
for b in inputs {
let options = super::mesh::surface_options(p, &b.mesh)?;
match BoundarySurface::new(&b.mesh.positions, &b.mesh.triangles, &b.mesh.tri_face, &options) {
Ok(surface) => surfaces.push(surface),
Err(e) => return Ok(Err(format!("body `{}`: {e}", b.name))),
}
}
let cells: Vec<Cell> = surfaces.iter().zip(inputs).map(|(surface, b)| Cell { name: &b.name, surface, faces: &b.surfaces }).collect();
let options = HexOptions {
method,
quadratic,
chordal_tolerance: tolerance,
max_elements: fieldcraft_model::MAX_ELEMENTS / 8,
seeds: seeds.to_vec(),
..HexOptions::default()
};
match hex_mesh_swept_cells(&cells, &UniformSize(h), &options) {
Ok(cm) => Ok(Ok(cm)),
Err(fieldcraft_mesh::Error::Model(fieldcraft_model::Error::Cancelled)) => Err(EngineError::Model(fieldcraft_model::Error::Cancelled)),
Err(e @ fieldcraft_mesh::Error::Limit(_)) => Err(EngineError::Params(e.to_string())),
Err(e) => Ok(Err(e.to_string())),
}
}
/// The interfaces of cells swept together: each pair of cells whose elements share faces, with
/// the partition between them and the nodes they share (one mesh: merged by construction).
fn swept_interfaces(design: &fieldcraft_geometry::Design, inputs: &[Input], cm: &CellsMesh) -> Vec<Value> {
let m = &cm.mesh;
let mut owner: BTreeMap<[u32; 4], u32> = BTreeMap::new();
let mut pairs: BTreeMap<(u32, u32), BTreeSet<u32>> = BTreeMap::new();
for e in 0..m.element_count() {
let (Some(h), Some(&c)) = (m.element(e), cm.element_cell.get(e)) else { continue };
for local in fieldcraft_model::ElementKind::Hex8.faces() {
let mut key = [0u32; 4];
for (slot, &i) in key.iter_mut().zip(local.iter()) {
*slot = h.get(i).copied().unwrap_or(0);
}
key.sort_unstable();
match owner.insert(key, c) {
Some(o) if o != c => pairs.entry((o.min(c), o.max(c))).or_default().extend(key),
_ => {}
}
}
}
// The partitions whose cut faces a cell has, with the side: two cells meet across a
// partition they are on opposite sides of.
let cuts = |c: u32| -> BTreeSet<(String, String)> {
let name = inputs.get(c as usize).map_or("", |b| b.name.as_str());
let faces = design.body(name).map(|b| b.faces().iter().map(|f| f.name.clone()).collect::<Vec<_>>()).unwrap_or_default();
faces
.iter()
.filter_map(|f| {
let (p, side) = f.strip_prefix("partition:")?.rsplit_once(':')?;
let side = side.split_once('#').map_or(side, |(s, _)| s);
Some((p.to_string(), side.to_string()))
})
.collect()
};
pairs
.into_iter()
.map(|((a, b), nodes)| {
let (na, nb) = (inputs.get(a as usize).map_or("", |x| x.name.as_str()), inputs.get(b as usize).map_or("", |x| x.name.as_str()));
let theirs = cuts(b);
let partition =
cuts(a).into_iter().find(|(p, side)| theirs.iter().any(|(q, other)| q == p && other != side)).map(|(p, _)| p).unwrap_or_default();
json!({"partition": partition, "cells": [na, nb], "joined": "merged", "nodes": nodes.len(), "swept_together": true})
})
.collect()
}
/// A cell's mesh in numbers: its volume, smallest and mean scaled Jacobian and largest edge
/// ratio.
fn cell_quality(model: &Model, body: &str) -> Value {
let (mut volume, mut min, mut sum, mut n, mut ratio) = (0.0, f64::INFINITY, 0.0, 0usize, None::<f64>);
for label in model.body_elements(body) {
let Some(e) = model.element(label) else { continue };
let xyz: Vec<[f64; 3]> = e.nodes.iter().filter_map(|&l| model.node(l).map(|x| x.xyz)).collect();
let Ok(q) = fieldcraft_mesh::quality::element_quality(e.kind, &xyz) else { continue };
volume += q.size;
if let Some(r) = q.get(fieldcraft_mesh::quality::Metric::EdgeRatio) {
ratio = Some(ratio.map_or(r, |x| x.max(r)));
}
if let Some(sj) = q.get(fieldcraft_mesh::quality::Metric::ScaledJacobian) {
min = min.min(sj);
sum += sj;
n += 1;
}
}
let min = if n > 0 { Some(min) } else { None };
json!({"volume": volume, "min_scaled_jacobian": min, "mean_scaled_jacobian": if n > 0 { Some(sum / n as f64) } else { None }, "max_edge_ratio": ratio})
}
/// One side of an interface: a cell's element faces on one side of a partition.
struct Side {
body: String,
@@ -268,54 +471,114 @@ fn sides(model: &Model, cells: &[String]) -> BTreeMap<String, [Vec<Side>; 2]> {
/// Join the cells across every partition: merge where the two sides match node for node, tie
/// where they do not. Returns the interfaces.
fn join(model: &mut Model, cells: &[String], tol: f64) -> Result<Vec<Value>> {
///
/// Ties go one way between any two cells, by a fixed order of the cells (hex before tet, then by
/// name; the earlier one is the main side), so no two ties hold one interface both ways, and
/// each cell's tied cut faces make one tie, `tie_<cell>` (its secondary surface; the main one is
/// the facing cells' cut faces), so a node where two of them meet is a secondary node once.
/// The ties of an earlier run on these cells are replaced.
fn join(model: &mut Model, cells: &[String], tet: &BTreeSet<String>, tol: f64) -> Result<Vec<Value>> {
remove_cut_ties(model, cells)?;
let rank = |cell: &str| (tet.contains(cell), cell.to_string());
let mut out = Vec::new();
// Per secondary cell: its cut faces and the facing cells' ones, as (body, face).
let mut tied: BTreeMap<String, (BTreeSet<(String, String)>, BTreeSet<(String, String)>)> = BTreeMap::new();
let mut tied_pairs: Vec<Value> = Vec::new();
for (partition, [a_sides, b_sides]) in sides(model, cells) {
let mut k = 0;
for a in &a_sides {
for b in &b_sides {
let overlap = (0..3).all(|i| a.lo[i] <= b.hi[i] + tol && b.lo[i] <= a.hi[i] + tol);
if !overlap {
// Faces on one plane overlap when their boxes share an area, not just an edge.
let shared = (0..3).filter(|&i| a.lo[i].max(b.lo[i]) < a.hi[i].min(b.hi[i]) - tol).count();
let touching = (0..3).all(|i| a.lo[i] <= b.hi[i] + tol && b.lo[i] <= a.hi[i] + tol);
if !(touching && shared >= 2) {
continue;
}
k += 1;
let matched = matching(model, a, b, tol);
if let Some(map) = matched {
if let Some(map) = matching(model, a, b, tol) {
let count = map.len();
model.merge_nodes(&map)?;
out.push(json!({"partition": partition, "cells": [a.body, b.body], "joined": "merged", "nodes": count}));
} else {
let name = format!("tie_{partition}_{k}");
let (main, secondary) = if a.nodes.len() <= b.nodes.len() { (a, b) } else { (b, a) };
let set = |side: &Side| -> Result<Set> { Ok(Set::of_geometry(vec![GeometryRef::face(side.body.as_str(), side.face.as_str())?])) };
let (main_set, secondary_set) = (format!("{name}_main"), format!("{name}_secondary"));
for (n, side) in [(&main_set, main), (&secondary_set, secondary)] {
if model.set(n).is_some() {
model.replace_set(n, set(side)?)?;
} else {
model.add_set(n, set(side)?)?;
}
}
if model.tie(&name).is_some() {
model.remove_tie(&name)?;
}
model.add_tie(&name, Tie::new(&main_set, &secondary_set))?;
out.push(json!({
"partition": partition,
"cells": [a.body, b.body],
"joined": "tied",
"tie": name,
"main": main.body,
"secondary": secondary.body,
"faces": [a.faces.len(), b.faces.len()],
}));
continue;
}
let (main, secondary) = if rank(&a.body) <= rank(&b.body) { (a, b) } else { (b, a) };
let entry = tied.entry(secondary.body.clone()).or_default();
entry.0.insert((secondary.body.clone(), secondary.face.clone()));
entry.1.insert((main.body.clone(), main.face.clone()));
tied_pairs.push(json!({
"partition": partition,
"cells": [a.body, b.body],
"joined": "tied",
"main": main.body,
"secondary": secondary.body,
"faces": [a.faces.len(), b.faces.len()],
}));
}
}
}
let mut names: BTreeMap<String, String> = BTreeMap::new();
for (cell, (own, facing)) in tied {
let base = tie_name(&cell);
let mut name = base.clone();
let mut k = 1;
while model.tie(&name).is_some() || model.set(&format!("{name}_main")).is_some() || model.set(&format!("{name}_secondary")).is_some() {
k += 1;
name = format!("{base}_{k}");
}
let set = |faces: &BTreeSet<(String, String)>| -> Result<Set> {
Ok(Set::of_geometry(faces.iter().map(|(b, f)| GeometryRef::face(b.as_str(), f.as_str())).collect::<fieldcraft_model::Result<_>>()?))
};
let (main_set, secondary_set) = (format!("{name}_main"), format!("{name}_secondary"));
model.add_set(&main_set, set(&facing)?)?;
model.add_set(&secondary_set, set(&own)?)?;
model.add_tie(&name, Tie::new(&main_set, &secondary_set))?;
names.insert(cell, name);
}
for mut pair in tied_pairs {
let name = pair.get("secondary").and_then(Value::as_str).and_then(|c| names.get(c)).cloned();
if let (Some(o), Some(name)) = (pair.as_object_mut(), name) {
o.insert("tie".into(), json!(name));
}
out.push(pair);
}
Ok(out)
}
/// The name of the tie that holds `cell`'s tied cut faces.
fn tie_name(cell: &str) -> String {
let name = format!("tie_{cell}");
fieldcraft_model::suggest_name(&name).unwrap_or(name)
}
/// Remove the ties an earlier run of mesh.cells made on `cells` (and their two sets): ties
/// between sets `<tie>_main` and `<tie>_secondary` that hold only cut faces of these cells.
fn remove_cut_ties(model: &mut Model, cells: &[String]) -> Result<()> {
let cut_faces_of_cells = |set: &str| {
model.set(set).is_some_and(|s| {
!s.geometry.is_empty()
&& s.nodes.is_empty()
&& s.elements.is_empty()
&& s.faces.is_empty()
&& s.edges.is_empty()
&& s.geometry.iter().all(|g| cells.contains(&g.body) && matches!(&g.entity, Entity::Face(f) if f.starts_with("partition:")))
})
};
let stale: Vec<(String, String, String)> = model
.ties()
.iter()
.filter(|(n, t)| t.main == format!("{n}_main") && t.secondary == format!("{n}_secondary"))
.filter(|(_, t)| cut_faces_of_cells(&t.main) && cut_faces_of_cells(&t.secondary))
.map(|(n, t)| (n.clone(), t.main.clone(), t.secondary.clone()))
.collect();
for (tie, main, secondary) in stale {
model.remove_tie(&tie)?;
for set in [main, secondary] {
if model.set_users(&set).is_empty() {
model.remove_set(&set)?;
}
}
}
Ok(())
}
/// When the two sides' nodes coincide one to one (within `tol`) and their faces are the same
/// in number, the merge: each node of side `b` to the node of side `a` at its place (or the other
/// way round, so the lower label survives).
@@ -349,14 +612,15 @@ mod tests {
#[test]
fn hex_and_tet_cells_are_tied_and_matching_hex_cells_merged() {
let (_dir, mut s) = cut_plate();
// A tet cell next to a hex cell: tied, main the coarser side.
// A tet cell next to a hex cell: tied, the hex cell main.
let r = s.execute("mesh.cells", &json!({"methods": {"Body1/a": "tet", "Body1/b": "mapped"}, "size": 2.5})).unwrap();
assert_eq!(r["cells"][0]["kind"], "tet4", "{r}");
assert_eq!(r["cells"][1]["kind"], "hex8", "{r}");
let i = &r["interfaces"][0];
assert_eq!(i["joined"], "tied", "{r}");
assert_eq!(s.model.ties().len(), 1);
for set in ["tie_P_1_main", "tie_P_1_secondary"] {
assert_eq!((i["main"].as_str(), i["secondary"].as_str(), i["tie"].as_str()), (Some("Body1/b"), Some("Body1/a"), Some("tie_Body1_a")), "{r}");
for set in ["tie_Body1_a_main", "tie_Body1_a_secondary"] {
assert!(s.model.resolve_set(set).unwrap().faces.len() > 4, "{set}");
}
// Both cells hex at one size: the plane faces match node for node and merge.
@@ -371,6 +635,27 @@ mod tests {
assert_eq!(s.model.ties().len(), 1);
}
/// The half crank arm (cut on its symmetry plane only) has no cell that maps or sweeps as
/// the design gives it; the extrusion decomposes its cross-section into blocks itself, alike
/// through mesh.hex.generate (auto) and mesh.cells, with no seeds.
#[test]
fn the_half_crank_extrudes_in_blocks_without_partitions() {
let bytes = fieldcraft_geometry::script_design(crate::sample::CRANK_ARM).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
s.execute("geometry.datum", &json!({"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}})).unwrap();
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Sym"})).unwrap();
let r = s.execute("mesh.hex.generate", &json!({"body": "CrankArm/a", "size": 3})).unwrap();
let body = &r["bodies"][0];
assert_eq!(body["method"], "extrude", "{r}");
assert!(body["description"].as_str().unwrap().contains(" 0 free)"), "{r}");
assert!(body["quality"]["min_scaled_jacobian"].as_f64().unwrap() >= 0.37, "{r}");
let r = s.execute("mesh.cells", &json!({"bodies": ["CrankArm/a"], "default": "extrude", "size": 3})).unwrap();
assert_eq!(r["cells"][0]["method"], "extrude", "{r}");
assert_eq!(r["elements"], body["elements"], "{r}");
}
#[test]
fn auto_falls_back_to_tet_and_says_why() {
let (_dir, mut s) = cut_plate();
@@ -470,4 +755,95 @@ mod tests {
assert!((u - expected).abs() < 1e-6 * expected, "{u} vs {expected}: {n}");
}
}
/// A box cut by planes into cells, `methods` per cell, a heat source in every cell and
/// convection on its outer faces: the heat flows of the steady solve.
fn cut_box_heat(cuts: &[(&str, f64)], methods: Value, size: f64) -> (Value, Value) {
let commands = json!({"commands": [
{"command": "solid.box", "params": {"length": 30, "width": 20, "height": 10, "body_name": "Box"}},
]});
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
for (i, (plane, offset)) in cuts.iter().enumerate() {
let name = format!("D{i}");
s.execute("geometry.datum", &json!({"name": name, "by": {"type": "offset", "plane": plane, "offset": offset}})).unwrap();
s.execute("geometry.partition", &json!({"name": format!("P{i}"), "datum": name})).unwrap();
}
let r = s.execute("mesh.cells", &json!({"methods": methods, "default": "hex", "size": size})).unwrap();
let bodies = s.execute("geometry.bodies", &json!({})).unwrap();
let outer: Vec<Value> = bodies
.as_array()
.unwrap()
.iter()
.flat_map(|b| {
b["faces"]
.as_array()
.unwrap()
.iter()
.filter(|f| !f["name"].as_str().unwrap().starts_with("partition:"))
.map(|f| json!({"body": b["name"], "face": f["name"]}))
.collect::<Vec<_>>()
})
.collect();
let script = json!([
{"command": "model.set.create", "params": {"name": "all", "elements": s.model.elements().keys().collect::<Vec<_>>()}},
{"command": "model.set.create", "params": {"name": "skin", "geometry": outer}},
{"command": "model.material.create", "params": {"name": "M", "elastic": {"type": "isotropic", "young": 1000, "poisson": 0.3}, "thermal": {"conductivity": 0.5}}},
{"command": "model.section.create", "params": {"name": "S", "set": "all", "material": "M", "kind": {"type": "solid"}}},
{"command": "model.load.create", "params": {"name": "Q", "type": "heat_source", "set": "all", "power": 1}},
{"command": "model.load.create", "params": {"name": "Air", "type": "convection", "set": "skin", "film": 0.01, "sink": 25}},
{"command": "model.step.create", "params": {"name": "Steady", "procedure": {"type": "heat_transfer"}, "loads": ["Q", "Air"]}},
]);
s.run_script(&script).unwrap();
let h = s.execute("solve.heat", &json!({"step": "Steady"})).unwrap();
(r, h)
}
/// A tet cell among hex cells (#389, #288): the hex cells sweep together and share their
/// nodes, the tet cell is tied once (one tie for all its cut faces, the hex cells main), and
/// the heat balances to round-off.
#[test]
fn a_tet_cell_among_swept_hex_cells_is_tied_once_and_the_heat_balances() {
let (r, h) = cut_box_heat(&[("yz", 10.0), ("yz", 20.0), ("zx", 10.0)], json!({"Box/b/a/a": "tet"}), 2.5);
let interfaces = r["interfaces"].as_array().unwrap();
let tied: Vec<&Value> = interfaces.iter().filter(|i| i["joined"] == "tied").collect();
assert_eq!(tied.len(), 3, "{r}");
assert!(tied.iter().all(|i| i["secondary"] == "Box/b/a/a" && i["tie"] == "tie_Box_b_a_a"), "{r}");
let merged: Vec<&Value> = interfaces.iter().filter(|i| i["joined"] == "merged").collect();
assert_eq!(merged.len(), 4, "{r}");
// Box/a/a and Box/a/b meet across y = 10, the third cut.
assert!(merged.iter().any(|i| i["cells"] == json!(["Box/a/a", "Box/a/b"]) && i["partition"] == "P2"), "{r}");
let flows = &h["heat_flows"];
let supplied = flows["loads"].as_array().unwrap().iter().find(|l| l["name"] == "Q").unwrap()["heat"].as_f64().unwrap();
assert!(flows["imbalance"].as_f64().unwrap().abs() < 1e-9 * supplied, "{flows}");
assert!(h["min_temperature"]["value"].as_f64().unwrap() > 25.0, "{h}");
}
/// Cells cut from one box by planes, one of them (`y = 10`) cutting only the cell left of
/// `x = 10`, so a cut ends on another (a T-junction): with no seeds the cells sweep together
/// and every interface merges node for node (#288), and the mesh fills the box.
#[test]
fn cells_of_a_body_sweep_together_and_merge_without_seeds() {
let (_dir, mut s) = super::super::datum::tests::scripted(json!([
{"command": "solid.box", "params": {"length": 30, "width": 20, "height": 10, "corner": [0, 0, 0], "body_name": "Box"}},
]));
super::super::datum::tests::cut_at(&mut s, &[(0, 10.0), (0, 21.0)]);
s.execute("geometry.datum", &json!({"name": "Y", "by": {"type": "offset", "plane": "zx", "offset": 7.5}})).unwrap();
s.execute("geometry.partition", &json!({"name": "PY", "datum": "Y", "bodies": ["Box/a"]})).unwrap();
let r = s.execute("mesh.cells", &json!({"default": "auto", "size": 2.0})).unwrap();
let cells = r["cells"].as_array().unwrap();
assert_eq!(cells.len(), 4, "{r}");
assert!(cells.iter().all(|c| c["swept_together"] == "Box" && c["kind"] == "hex8"), "{r}");
let interfaces = r["interfaces"].as_array().unwrap();
assert_eq!(interfaces.len(), 4, "{r}");
assert!(interfaces.iter().all(|i| i["joined"] == "merged"), "{r}");
assert!(s.model.ties().is_empty());
let q = s.execute("mesh.quality", &json!({})).unwrap();
let volume = q["volume"].as_f64().unwrap();
assert!((volume - 6000.0).abs() < 1e-6, "{q}");
let d = s.execute("mesh.check.duplicates", &json!({})).unwrap();
assert_eq!((d["counts"]["coincident"].as_u64(), d["counts"]["cracks"].as_u64()), (Some(0), Some(0)), "{d}");
}
}
+116 -2
View File
@@ -1,5 +1,7 @@
//! `interaction.contact.*`: contact definitions (pairs of surfaces, general contact) and the
//! search for surfaces that touch; `interaction.tie*`: ties between non-matching meshes.
//! search for surfaces that touch; `interaction.tie*`: ties between non-matching meshes;
//! `interaction.rigid_wall*`: rigid walls, which belong to an explicit dynamics step (its
//! `rigid_walls`, also edited in the step's form).
//!
//! A contact's surfaces are sets of element faces, or of element edges in a 2D model
//! ([`fieldcraft_model::contact`]). The commands
@@ -16,7 +18,7 @@ use crate::schema::ProblemKind;
use std::collections::BTreeMap;
use fieldcraft_fem::contact::{Grid, bounds, closest_point};
use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, Friction, InitialPenetration, Model, Set, Tie};
use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, Friction, InitialPenetration, Model, Procedure, RigidWall, Set, Step, Tie};
use serde_json::{Value, json};
use super::{name, opt};
@@ -38,6 +40,88 @@ fn text<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
p.get(key).and_then(Value::as_str).ok_or_else(|| EngineError::param(key, ProblemKind::NotAName))
}
pub const RIGID_WALL: CommandSpec = CommandSpec {
id: "interaction.rigid_wall",
label: "Rigid Wall",
params: r#"{"step": "Impact" (an explicit dynamics step; default: the model's only one), "set": "front" (the nodes the wall stops), "point": [x, y, z] (on the wall), "normal": [nx, ny, nz] (toward the side the nodes stay on), "friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb; default frictionless)} — a fixed rigid plane the set's nodes cannot pass, added to the step's rigid walls (the same list as model.step.create's `rigid_walls`). Replies the step and the wall's index in it"#,
form: Some(super::forms::RIGID_WALL),
kind: CommandKind::Model,
requires: &[Requirement::Step, Requirement::Set],
run: rigid_wall,
};
pub const RIGID_WALL_DELETE: CommandSpec = CommandSpec {
id: "interaction.rigid_wall.delete",
label: "Delete Rigid Wall",
params: r#"{"step": "Impact", "index": 0} — removes a rigid wall from an explicit dynamics step (its index in the step's `rigid_walls`, from 0)"#,
form: Some(super::forms::RIGID_WALL_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Step],
run: rigid_wall_delete,
};
/// The explicit dynamics step `step` names, or the model's only one when it names none.
fn explicit_step(m: &Model, p: &Value) -> Result<Step> {
let explicit = |s: &&Step| matches!(s.procedure, Procedure::ExplicitDynamic(_));
let step = match p.get("step") {
None | Some(Value::Null) => {
let mut all = m.steps().iter().filter(explicit);
match (all.next(), all.next()) {
(Some(s), None) => s,
(None, _) => {
return Err(EngineError::Params(
"the model has no explicit dynamics step, where rigid walls act: create one (Steps › Step, Dynamic, explicit)".into(),
));
}
(Some(_), Some(_)) => {
return Err(EngineError::param("step", ProblemKind::Invalid("name the explicit dynamics step: the model has several".into())));
}
}
}
Some(_) => {
let n = text(p, "step")?;
let s = m.steps().iter().find(|s| s.name == n).ok_or_else(|| EngineError::Params(format!("no step `{n}`")))?;
if !explicit(&s) {
return Err(EngineError::Params(format!("step `{n}` is not an explicit dynamics step: rigid walls act only there")));
}
s
}
};
Ok(step.clone())
}
fn rigid_wall(s: &mut Session, p: &Value) -> Result<Value> {
let mut step = explicit_step(&s.model, p)?;
let set = text(p, "set")?.to_string();
if s.model.set(&set).is_none() {
return Err(EngineError::Params(format!("no set `{set}`")));
}
let wall = RigidWall {
set,
point: super::req(p, "point")?,
normal: super::req(p, "normal")?,
friction: opt::<Friction>(p, "friction")?.unwrap_or(Friction::NONE),
};
let Procedure::ExplicitDynamic(e) = &mut step.procedure else { return Err(EngineError::Params("not an explicit dynamics step".into())) };
e.rigid_walls.push(wall);
let index = e.rigid_walls.len() - 1;
let name = step.name.clone();
s.model.replace_step(step)?;
Ok(json!({"step": name, "index": index}))
}
fn rigid_wall_delete(s: &mut Session, p: &Value) -> Result<Value> {
let mut step = explicit_step(&s.model, p)?;
let index: usize = super::req(p, "index")?;
let Procedure::ExplicitDynamic(e) = &mut step.procedure else { return Err(EngineError::Params("not an explicit dynamics step".into())) };
if index >= e.rigid_walls.len() {
return Err(EngineError::param("index", ProblemKind::Invalid(format!("step `{}` has {} rigid walls", step.name, e.rigid_walls.len()))));
}
e.rigid_walls.remove(index);
s.model.replace_step(step)?;
Ok(Value::Null)
}
pub const PAIR: CommandSpec = CommandSpec {
id: "interaction.contact.pair",
label: "Contact Pair",
@@ -322,6 +406,36 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
mod tests {
use super::*;
/// Rigid walls go into the explicit step (the model's only one, or the one named) and come
/// out by index; a model without an explicit step, or a step of another kind, is refused.
#[test]
fn rigid_walls_belong_to_the_explicit_step() {
let mut s = Session::default();
super::super::define::tests::defined_bar(&mut s);
let wall = json!({"set": "end", "point": [3, 0, 0], "normal": [-1, 0, 0], "friction": {"static": 0.2}});
assert!(s.execute("interaction.rigid_wall", &wall).is_err(), "no explicit step yet");
let mut on_bend = wall.clone();
on_bend["step"] = json!("Bend");
assert!(s.execute("interaction.rigid_wall", &on_bend).is_err(), "a static step");
s.execute("model.step.create", &json!({"name": "Hit", "procedure": {"type": "explicit_dynamic", "end_time": 1e-4}})).unwrap();
let r = s.execute("interaction.rigid_wall", &wall).unwrap();
assert_eq!(r, json!({"step": "Hit", "index": 0}));
let walls = |s: &Session| match &s.model.step("Hit").unwrap().procedure {
Procedure::ExplicitDynamic(e) => e.rigid_walls.clone(),
_ => panic!(),
};
assert_eq!(walls(&s).len(), 1);
assert_eq!(walls(&s)[0].set, "end");
for bad in [json!({"set": "nope", "point": [0, 0, 0], "normal": [1, 0, 0]}), json!({"set": "end", "point": [0, 0, 0], "normal": [0, 0, 0]})] {
assert!(s.execute("interaction.rigid_wall", &bad).is_err(), "{bad}");
}
assert!(s.execute("interaction.rigid_wall.delete", &json!({"step": "Hit", "index": 1})).is_err());
s.execute("interaction.rigid_wall.delete", &json!({"step": "Hit", "index": 0})).unwrap();
assert!(walls(&s).is_empty());
s.execute("model.step.create", &json!({"name": "Hit2", "procedure": {"type": "explicit_dynamic", "end_time": 1e-4}})).unwrap();
assert!(s.execute("interaction.rigid_wall", &wall).is_err(), "two explicit steps: name one");
}
/// Two unit cubes of 2×2×2 hex8 each, the second resting on the first (separate nodes), and
/// a third cube far away.
fn stacked(s: &mut Session) {
+642 -43
View File
@@ -1,6 +1,10 @@
//! Datum planes and axes, and partitions of the open design by datum planes.
//! Datum planes, axes and points, and partitions of the open design by datum planes.
//!
//! Datums and partitions are part of the model (`fieldcraft_model::datums`). A partition cuts the
//! Datums and partitions are part of the model (`fieldcraft_model::datums`). A datum point is
//! placed by coordinates, at a mesh vertex, along a design edge, at a design face's centre or
//! where a datum axis crosses a datum plane; planes and axes can be made through datum points.
//! Each takes the coordinates of what it is made from when it is made (a later edit of a datum
//! point leaves the planes and axes made through it where they are). A partition cuts the
//! design in memory (`fieldcraft_geometry::partition`); the model's partitions are applied again,
//! in order, whenever the design is opened (`geometry.open`, `file.open`, samples), so an edit
//! of the design followed by a re-open replays them.
@@ -9,6 +13,7 @@ use crate::schema::ProblemKind;
use std::sync::Arc;
use fieldcraft_geometry::{Cut, Design};
use fieldcraft_io::{Item, ItemKind, MAX_HIDDEN};
use fieldcraft_model::{Datum, Model, Partition};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -19,7 +24,7 @@ use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const DATUM_PLANE: CommandSpec = CommandSpec {
id: "geometry.datum",
label: "Datum Plane",
params: r#"{"name": "Mid", "by": {"type": "offset", "plane": "yz" | "zx" | "xy", "offset": 15} | {"type": "three_points", "a": [x, y, z], "b": […], "c": […]} | {"type": "point_normal", "point": [x, y, z], "normal": [nx, ny, nz]}} — a named datum plane (model coordinates, mm for SolidCraft geometry): a principal plane moved along its normal (yz: normal +x, zx: normal +y, xy: normal +z), through three points (normal (b − a) × (c − a)), or through a point with a normal. Partitions (geometry.partition) cut by it; shown in the viewport"#,
params: r#"{"name": "Mid", "by": {"type": "offset", "plane": "yz" | "zx" | "xy", "offset": 15} | {"type": "three_points", "a": [x, y, z], "b": […], "c": […]} | {"type": "point_normal", "point": [x, y, z], "normal": [nx, ny, nz]} | {"type": "datum_points", "a": "P1", "b": "P2", "c": "P3"} | {"type": "normal_to_axis", "axis": "Spindle", "point"?: "P1"}} — a named datum plane (model coordinates, mm for SolidCraft geometry): a principal plane moved along its normal (yz: normal +x, zx: normal +y, xy: normal +z), through three points or three datum points (normal (b − a) × (c − a)), through a point with a normal, or normal to a datum axis through a datum point (the axis's point by default). Partitions (geometry.partition) cut by it; shown in the viewport"#,
form: Some(super::forms::DATUM_PLANE),
kind: CommandKind::Model,
requires: &[],
@@ -29,17 +34,57 @@ pub const DATUM_PLANE: CommandSpec = CommandSpec {
pub const DATUM_AXIS: CommandSpec = CommandSpec {
id: "geometry.datum.axis",
label: "Datum Axis",
params: r#"{"name": "Spindle", "by": {"type": "principal", "axis": "x" | "y" | "z", "through"?: [x, y, z] (default the origin)} | {"type": "two_points", "a": [x, y, z], "b": […]} | {"type": "point_direction", "point": [x, y, z], "direction": [dx, dy, dz]}} — a named datum axis, shown in the viewport"#,
params: r#"{"name": "Spindle", "by": {"type": "principal", "axis": "x" | "y" | "z", "through"?: [x, y, z] (default the origin)} | {"type": "two_points", "a": [x, y, z], "b": […]} | {"type": "point_direction", "point": [x, y, z], "direction": [dx, dy, dz]} | {"type": "datum_points", "a": "P1", "b": "P2"}} — a named datum axis, shown in the viewport"#,
form: Some(super::forms::DATUM_AXIS),
kind: CommandKind::Model,
requires: &[],
run: datum_axis,
};
pub const DATUM_POINT: CommandSpec = CommandSpec {
id: "geometry.datum.point",
label: "Datum Point",
params: r#"{"name": "P1", "by": {"type": "coordinates", "point": [x, y, z]} | {"type": "vertex", "body": "Body1", "vertex": "F1:top|F2:side:l1|F2:side:l2"} | {"type": "edge", "body": "Body1", "edge": "F1:top|F2:side", "fraction"?: 0.5} | {"type": "face_centre", "body": "Body1", "face": "F2:top"} | {"type": "axis_plane", "axis": "Spindle", "plane": "Mid"}} — a named datum point, shown in the viewport as a small cross: at coordinates, at a vertex of the open design (its persistent name, as geometry.bodies lists it and Select: Vertices picks it) or of the mesh (as its geometry tags name it), a fraction along an edge of the open design (0.5: its midpoint), at the area centre of a face of the open design, or where a datum axis crosses a datum plane. Datum planes and axes can be made through datum points"#,
form: Some(super::forms::DATUM_POINT),
kind: CommandKind::Model,
requires: &[],
run: datum_point,
};
pub const DATUM_EDIT: CommandSpec = CommandSpec {
id: "geometry.datum.edit",
label: "Edit Datum Plane",
params: r#"{"name": "Mid", "by": …} — redefines a datum plane (the parameters of geometry.datum); the partitions that cut by it cut again"#,
form: Some(super::forms::DATUM_PLANE),
kind: CommandKind::Model,
requires: &[Requirement::DatumPlane],
run: |s, p| datum_edit(s, p, "plane"),
};
pub const DATUM_AXIS_EDIT: CommandSpec = CommandSpec {
id: "geometry.datum.axis.edit",
label: "Edit Datum Axis",
params: r#"{"name": "Spindle", "by": …} — redefines a datum axis (the parameters of geometry.datum.axis)"#,
form: Some(super::forms::DATUM_AXIS),
kind: CommandKind::Model,
requires: &[Requirement::DatumAxis],
run: |s, p| datum_edit(s, p, "axis"),
};
pub const DATUM_POINT_EDIT: CommandSpec = CommandSpec {
id: "geometry.datum.point.edit",
label: "Edit Datum Point",
params: r#"{"name": "P1", "by": …} — redefines a datum point (the parameters of geometry.datum.point); planes and axes made through it stay where they are"#,
form: Some(super::forms::DATUM_POINT),
kind: CommandKind::Model,
requires: &[Requirement::DatumPoint],
run: |s, p| datum_edit(s, p, "point"),
};
pub const DATUM_DELETE: CommandSpec = CommandSpec {
id: "geometry.datum.delete",
label: "Delete Datum",
params: r#"{"name": "Mid"} — deletes a datum plane or axis no partition uses"#,
params: r#"{"name": "Mid", "cascade"?: false} — deletes a datum plane, axis or point; one a partition cuts by is refused (naming the partitions), unless `cascade` deletes those partitions too (their cells lose their meshes: `replaced`)"#,
form: Some(super::forms::DATUM_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Datum],
@@ -49,17 +94,37 @@ pub const DATUM_DELETE: CommandSpec = CommandSpec {
pub const PARTITION: CommandSpec = CommandSpec {
id: "geometry.partition",
label: "Partition",
params: r#"{"name": "Half", "datum": "Mid", "bodies"?: ["Body1"] (default: every body the plane divides)} — cuts bodies of the open design into cells by a datum plane, in memory (the design file is not changed); the model keeps the partition and applies it again whenever the design is opened, after the partitions before it. A cut body `B` becomes the cells `B/a` (on the plane's negative side) and `B/b` (several pieces on a side: `B/a1`, `B/a2`, …). The two faces of the cut are paired by name: `partition:<name>:a` on the cells on the negative side, `partition:<name>:b` on the positive side (`…#0`, `…#1` where a cell has several); every other face keeps the persistent name of the face it is a piece of (`<face>#k` for several pieces on one cell), so sets by face name still select it. Reports the cells made and the cut faces named; a plane that divides no body, or a listed body it does not divide, is an error"#,
params: r#"{"name": "Half", "datum": "Mid", "bodies"?: ["Body1"] (default: every body the plane divides)} — cuts bodies of the open design into cells by a datum plane, in memory (the design file is not changed); the model keeps the partition and applies it again whenever the design is opened, after the partitions before it. A cut body `B` becomes the cells `B/a` (on the plane's negative side) and `B/b` (several pieces on a side: `B/a1`, `B/a2`, …). The two faces of the cut are paired by name: `partition:<name>:a` on the cells on the negative side, `partition:<name>:b` on the positive side (`…#0`, `…#1` where a cell has several); every other face keeps the persistent name of the face it is a piece of (`<face>#k` for several pieces on one cell), so sets by face name still select it. Reports the cells made and the cut faces named, and `warnings` when the plane lies on a face of a body it cuts or a cell's boundary does not tessellate into one a mesher takes (a cut through existing edges or vertices, such as a hole's axis), naming the plane, the cell and where; a body it cuts loses its mesh (`replaced`, as a mesher reports it; remesh the cells); a plane that divides no body, a listed body it does not divide, or a body the kernel fails to cut (its message) is an error"#,
form: Some(super::forms::PARTITION),
kind: CommandKind::Model,
requires: &[Requirement::Design, Requirement::DatumPlane],
run: partition,
};
pub const DATUM_SUPPRESS: CommandSpec = CommandSpec {
id: "geometry.datum.suppress",
label: "Suppress Datum",
params: r#"{"name": "Mid", "suppressed"?: true} — keeps the datum but leaves it out of the model (false brings it back): it cannot be an input to another datum, a partition, a mirror or a symmetry while suppressed, and the partitions that cut by it stop cutting (the design is cut again without them)"#,
form: Some(super::forms::DATUM_SUPPRESS),
kind: CommandKind::Model,
requires: &[Requirement::Datum],
run: datum_suppress,
};
pub const PARTITION_SUPPRESS: CommandSpec = CommandSpec {
id: "geometry.partition.suppress",
label: "Suppress Partition",
params: r#"{"name": "Half", "suppressed"?: true} — keeps the partition but leaves it out (false brings it back): the design is cut again without it, so its cells merge back into the bodies they came from and lose their meshes (`replaced`)"#,
form: Some(super::forms::PARTITION_SUPPRESS),
kind: CommandKind::Model,
requires: &[Requirement::Partition],
run: partition_suppress,
};
pub const PARTITION_DELETE: CommandSpec = CommandSpec {
id: "geometry.partition.delete",
label: "Delete Partition",
params: r#"{"name": "Half"} — removes a partition; the design is cut again by the ones left"#,
params: r#"{"name": "Half"} — removes a partition; the design is cut again by the ones left, and the cells that are gone lose their meshes (`replaced`)"#,
form: Some(super::forms::PARTITION_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Partition],
@@ -91,6 +156,16 @@ enum PlaneBy {
point: [f64; 3],
normal: [f64; 3],
},
DatumPoints {
a: String,
b: String,
c: String,
},
NormalToAxis {
axis: String,
#[serde(default)]
point: Option<String>,
},
}
#[derive(Deserialize)]
@@ -117,13 +192,76 @@ enum AxisBy {
point: [f64; 3],
direction: [f64; 3],
},
DatumPoints {
a: String,
b: String,
},
}
fn half() -> f64 {
0.5
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum PointBy {
Coordinates {
point: [f64; 3],
},
Vertex {
body: String,
vertex: String,
},
Edge {
body: String,
edge: String,
#[serde(default = "half")]
fraction: f64,
},
FaceCentre {
body: String,
face: String,
},
AxisPlane {
axis: String,
plane: String,
},
}
fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn plane_datum(by: PlaneBy) -> Result<Datum> {
/// The coordinates of datum point `name`.
fn datum_point_at(m: &Model, name: &str) -> Result<[f64; 3]> {
let d = m.usable_datum(name)?;
d.point().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not a point", d.kind())))
}
/// The point and unit direction of datum axis `name`.
fn datum_axis_of(m: &Model, name: &str) -> Result<([f64; 3], [f64; 3])> {
let d = m.usable_datum(name)?;
d.axis().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not an axis", d.kind())))
}
/// The point and unit normal of datum plane `name`.
pub(crate) fn datum_plane_of(m: &Model, name: &str) -> Result<([f64; 3], [f64; 3])> {
let d = m.usable_datum(name)?;
d.plane().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not a plane", d.kind())))
}
/// A plane through three points; collinear points are refused relative to their spread.
fn three_points(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Result<Datum> {
let (u, v) = (sub(b, a), sub(c, a));
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let size = u.iter().chain(&v).map(|x| x * x).sum::<f64>();
if !(n.iter().map(|x| x * x).sum::<f64>() > 1e-20 * size * size) {
return Err(EngineError::Params("the three points must not lie on one line".into()));
}
Ok(Datum::Plane { point: a, normal: n })
}
fn plane_datum(m: &Model, by: PlaneBy) -> Result<Datum> {
Ok(match by {
PlaneBy::Offset { plane, offset } => {
if !offset.is_finite() {
@@ -136,22 +274,22 @@ fn plane_datum(by: PlaneBy) -> Result<Datum> {
};
Datum::Plane { point: normal.map(|n| n * offset), normal }
}
PlaneBy::ThreePoints { a, b, c } => {
let (u, v) = (sub(b, a), sub(c, a));
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
// Collinear points: refused relative to the points' spread.
let size = u.iter().chain(&v).map(|x| x * x).sum::<f64>();
if !(n.iter().map(|x| x * x).sum::<f64>() > 1e-20 * size * size) {
return Err(EngineError::Params("the three points must not lie on one line".into()));
}
Datum::Plane { point: a, normal: n }
}
PlaneBy::ThreePoints { a, b, c } => three_points(a, b, c)?,
PlaneBy::PointNormal { point, normal } => Datum::Plane { point, normal },
PlaneBy::DatumPoints { a, b, c } => three_points(datum_point_at(m, &a)?, datum_point_at(m, &b)?, datum_point_at(m, &c)?)?,
PlaneBy::NormalToAxis { axis, point } => {
let (on_axis, direction) = datum_axis_of(m, &axis)?;
let point = match point {
Some(p) => datum_point_at(m, &p)?,
None => on_axis,
};
Datum::Plane { point, normal: direction }
}
})
}
fn axis_datum(by: AxisBy) -> Datum {
match by {
fn axis_datum(m: &Model, by: AxisBy) -> Result<Datum> {
Ok(match by {
AxisBy::Principal { axis, through } => {
let direction = match axis {
Axis::X => [1.0, 0.0, 0.0],
@@ -162,6 +300,103 @@ fn axis_datum(by: AxisBy) -> Datum {
}
AxisBy::TwoPoints { a, b } => Datum::Axis { point: a, direction: sub(b, a) },
AxisBy::PointDirection { point, direction } => Datum::Axis { point, direction },
AxisBy::DatumPoints { a, b } => {
let a = datum_point_at(m, &a)?;
Datum::Axis { point: a, direction: sub(datum_point_at(m, &b)?, a) }
}
})
}
/// Most mesh nodes a vertex is looked for among.
const MAX_VERTEX_NODES: usize = 10_000_000;
fn point_datum(s: &Session, by: PointBy) -> Result<Datum> {
let shape = |body: &str| -> Result<&fieldcraft_geometry::Shape> {
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
design.body(body).ok_or_else(|| EngineError::Params(format!("the design has no body `{body}`")))
};
let point = match by {
PointBy::Coordinates { point } => point,
PointBy::Vertex { body, vertex } => {
// A vertex of the open design by its persistent name, else one the mesh tags.
let design_vertex = match s.design.as_deref().and_then(|d| d.body(&body)) {
Some(shape) => shape.vertices()?.into_iter().find(|v| v.name == vertex).map(|v| v.point),
None => None,
};
match design_vertex {
Some(point) => point,
None => {
let m = &s.model;
let at = fieldcraft_model::GeometryRef::new(body.clone(), fieldcraft_model::Entity::Vertex(vertex.clone()))?;
let tags = m.classification().tags_selected_by(&at);
let node = m
.classification()
.nodes()
.iter()
.take(MAX_VERTEX_NODES)
.find(|(_, t)| tags.contains(t))
.and_then(|(n, _)| m.node(*n))
.ok_or_else(|| EngineError::Params(format!("body `{body}` has no vertex `{vertex}` (geometry.bodies lists its vertices)")))?;
node.xyz
}
}
}
PointBy::Edge { body, edge, fraction } => {
if !(0.0..=1.0).contains(&fraction) {
return Err(EngineError::invalid("fraction", "is a number from 0 to 1".to_string()));
}
let edges = shape(&body)?.edges()?;
let e = edges.iter().find(|e| e.name == edge).ok_or_else(|| EngineError::Params(format!("body `{body}` has no edge `{edge}`")))?;
e.point_at(fraction).ok_or_else(|| EngineError::Params(format!("edge `{edge}` of body `{body}` has no points")))?
}
PointBy::FaceCentre { body, face } => shape(&body)?.face_centre(&face)?,
PointBy::AxisPlane { axis, plane } => {
let (p, d) = datum_axis_of(&s.model, &axis)?;
let (q, n) = datum_plane_of(&s.model, &plane)?;
let along = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let across = along(d, n);
// Unit vectors: the sine of the angle between the axis and the plane.
if across.abs() < 1e-9 {
return Err(EngineError::Params(format!("axis `{axis}` is parallel to plane `{plane}`: they do not cross")));
}
let t = along(sub(q, p), n) / across;
[p[0] + t * d[0], p[1] + t * d[1], p[2] + t * d[2]]
}
};
Ok(Datum::Point { point })
}
/// The datum `by` defines for a datum of `kind` (`plane`, `axis` or `point`).
fn datum_of(s: &Session, kind: &str, p: &Value) -> Result<Datum> {
match kind {
"plane" => plane_datum(&s.model, super::req(p, "by")?),
"axis" => axis_datum(&s.model, super::req(p, "by")?),
_ => point_datum(s, super::req(p, "by")?),
}
}
/// The datum a datum form's `params` define so far, for drawing it before OK; `None` when
/// `command` makes no datum or the parameters do not define one yet. The model is not changed.
pub fn preview(s: &Session, command: &str, params: &Value) -> Option<Datum> {
let kind = match command {
"geometry.datum" | "geometry.datum.edit" => "plane",
"geometry.datum.axis" | "geometry.datum.axis.edit" => "axis",
"geometry.datum.point" | "geometry.datum.point.edit" => "point",
_ => return None,
};
datum_of(s, kind, params).ok()
}
/// The parameters of the command that edits datum `name`, describing it as it is (a plane by
/// its point and normal, an axis by its point and direction, a point by its coordinates); and
/// that command.
pub fn edit_params(name: &str, d: &Datum) -> (&'static str, Value) {
match *d {
Datum::Plane { point, normal } => (DATUM_EDIT.id, json!({"name": name, "by": {"type": "point_normal", "point": point, "normal": normal}})),
Datum::Axis { point, direction } => {
(DATUM_AXIS_EDIT.id, json!({"name": name, "by": {"type": "point_direction", "point": point, "direction": direction}}))
}
Datum::Point { point } => (DATUM_POINT_EDIT.id, json!({"name": name, "by": {"type": "coordinates", "point": point}})),
}
}
@@ -173,24 +408,53 @@ fn datum_json(name: &str, d: &Datum) -> Value {
v
}
fn datum_plane(s: &mut Session, p: &Value) -> Result<Value> {
fn datum_create(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let name = super::name(p)?;
let datum = plane_datum(super::req(p, "by")?)?;
let datum = datum_of(s, kind, p)?;
s.model.add_datum(name, datum)?;
Ok(datum_json(name, s.model.datum(name).unwrap_or(&datum)))
}
fn datum_plane(s: &mut Session, p: &Value) -> Result<Value> {
datum_create(s, p, "plane")
}
fn datum_axis(s: &mut Session, p: &Value) -> Result<Value> {
datum_create(s, p, "axis")
}
fn datum_point(s: &mut Session, p: &Value) -> Result<Value> {
datum_create(s, p, "point")
}
/// Redefine datum `name` of `kind`; the partitions that cut by a plane cut again.
fn datum_edit(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let name = super::name(p)?;
let datum = axis_datum(super::req(p, "by")?);
s.model.add_datum(name, datum)?;
Ok(datum_json(name, s.model.datum(name).unwrap_or(&datum)))
match s.model.datum(name) {
Some(d) if d.kind() == kind => {}
Some(d) => return Err(EngineError::Params(format!("datum `{name}` is a datum {}, not a {kind}", d.kind()))),
None => return Err(EngineError::Params(format!("no datum {kind} `{name}`"))),
}
let datum = datum_of(s, kind, p)?;
s.model.replace_datum(name, datum)?;
let cleared = if s.model.datum_users(name).is_empty() { super::replace::Cleared::default() } else { recut(s)? };
let reply = datum_json(name, s.model.datum(name).unwrap_or(&datum));
Ok(cleared.report_if_any(s, reply))
}
fn datum_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?;
let cascade: bool = super::opt(p, "cascade")?.unwrap_or(false);
let partitions: Vec<String> = s.model.partitions().iter().filter(|x| x.datum == name).map(|x| x.name.clone()).collect();
if cascade {
for partition in &partitions {
s.model.remove_partition(partition)?;
}
}
s.model.remove_datum(name)?;
Ok(json!({"deleted": name}))
let cleared = if cascade && !partitions.is_empty() { recut(s)? } else { super::replace::Cleared::default() };
let reply = json!({"deleted": name, "partitions": if cascade { partitions } else { Vec::new() }});
Ok(cleared.report_if_any(s, reply))
}
/// The model's partitions as cuts of the geometry.
@@ -198,6 +462,7 @@ fn cuts(model: &Model) -> Vec<Cut> {
model
.partitions()
.iter()
.filter(|p| model.partition_cuts(p))
.filter_map(|p| {
let (point, normal) = model.datum(&p.datum)?.plane()?;
Some(Cut { name: p.name.clone(), point, normal, bodies: p.bodies.clone() })
@@ -210,21 +475,24 @@ pub(crate) fn partitioned(design: &Design, model: &Model) -> Result<Design> {
Ok(design.partitioned(&cuts(model))?)
}
/// Cut the session's design by its model's partitions again.
fn recut(s: &mut Session) -> Result<()> {
if let Some(d) = &s.design {
let cut = partitioned(d, &s.model)?;
s.design = Some(Arc::new(cut));
}
Ok(())
/// Cut the session's design by its model's partitions again. The bodies that are gone (cells
/// whose partition went, a body a new partition cut) take their meshes with them (#385): what
/// went is in the returned [`super::replace::Cleared`], which the command reports.
fn recut(s: &mut Session) -> Result<super::replace::Cleared> {
let Some(d) = &s.design else { return Ok(super::replace::Cleared::default()) };
let cut = partitioned(d, &s.model)?;
let gone: Vec<String> = d.bodies.iter().filter(|b| cut.body(&b.name).is_none()).map(|b| b.name.clone()).collect();
s.design = Some(Arc::new(cut));
Ok(super::replace::clear(&mut s.model, gone.iter().map(String::as_str)))
}
fn partition(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?.to_string();
let datum: String = super::req(p, "datum")?;
let bodies: Vec<String> = super::opt(p, "bodies")?.unwrap_or_default();
s.model.add_partition(Partition { name: name.clone(), datum, bodies })?;
recut(s)?;
datum_plane_of(&s.model, &datum)?;
s.model.add_partition(Partition { name: name.clone(), datum: datum.clone(), bodies, suppressed: false })?;
let cleared = recut(s)?;
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
let feature = format!("partition {name}");
let errors: Vec<&str> = design.errors.iter().filter(|e| e.feature == feature).map(|e| e.message.as_str()).collect();
@@ -236,22 +504,70 @@ fn partition(s: &mut Session, p: &Value) -> Result<Value> {
if split.is_empty() {
return Err(EngineError::Params(format!("partition `{name}`: the plane divides no body of the design")));
}
let cells: Vec<&str> = design.bodies.iter().map(|b| b.name.as_str()).filter(|b| split.iter().any(|x| b.starts_with(&format!("{x}/")))).collect();
Ok(json!({
let cells: Vec<String> = design.bodies.iter().map(|b| b.name.clone()).filter(|b| split.iter().any(|x| b.starts_with(&format!("{x}/")))).collect();
let (faces, bodies): (usize, Vec<String>) = (report.map_or(0, |r| r.faces), design.bodies.iter().map(|b| b.name.clone()).collect());
let mut warnings: Vec<String> = report.map(|r| r.warnings.clone()).unwrap_or_default();
for cell in &cells {
if let Some(why) = design.body(cell).and_then(|shape| unmeshable(shape).err()) {
warnings.push(format!(
"partition `{name}`: cell `{cell}` has a boundary no mesher takes ({why}): the plane passes within the kernel's tolerance of a face, edge or vertex it cut (along a face, through the axis of a hole); move the plane off it (by a fraction of the element size)"
));
}
}
// The cut shows as edges on the cells, so the plane steps out of the way (view state, #295):
// selecting it in the browser or its eye shows it again.
if s.view.hidden.len() < MAX_HIDDEN {
s.view.hidden.insert(Item { kind: ItemKind::Datum, name: datum });
}
let mut reply = json!({
"name": name,
"split": split,
"cells": cells,
"cut_faces": report.map_or(0, |r| r.faces),
"bodies": design.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
}))
"cut_faces": faces,
"bodies": bodies,
});
if !warnings.is_empty()
&& let Some(o) = reply.as_object_mut()
{
o.insert("warnings".into(), json!(warnings));
}
Ok(cleared.report_if_any(s, reply))
}
/// Whether a cell's boundary, tessellated as the meshers take it by default, bounds a volume mesh:
/// the defects (open edges, edges on three triangles) when it does not.
fn unmeshable(shape: &fieldcraft_geometry::Shape) -> Result<()> {
let input = super::hex::shape_input(shape, None)?;
let options = fieldcraft_mesh::surface::SurfaceOptions { weld_distance: input.mesh.weld_distance, ..Default::default() };
fieldcraft_mesh::surface::BoundarySurface::new(&input.mesh.positions, &input.mesh.triangles, &input.mesh.tri_face, &options)
.map(|_| ())
.map_err(|e| EngineError::Params(e.to_string()))
}
fn datum_suppress(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?;
let suppressed = super::opt(p, "suppressed")?.unwrap_or(true);
s.model.set_datum_suppressed(name, suppressed)?;
let cleared = recut(s)?;
let bodies: Vec<String> = s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect();
Ok(cleared.report_if_any(s, json!({"name": name, "suppressed": suppressed, "bodies": bodies})))
}
fn partition_suppress(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?;
let suppressed = super::opt(p, "suppressed")?.unwrap_or(true);
s.model.set_partition_suppressed(name, suppressed)?;
let cleared = recut(s)?;
let bodies: Vec<String> = s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect();
Ok(cleared.report_if_any(s, json!({"name": name, "suppressed": suppressed, "bodies": bodies})))
}
fn partition_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?;
s.model.remove_partition(name)?;
recut(s)?;
let cleared = recut(s)?;
let bodies: Vec<String> = s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect();
Ok(json!({"deleted": name, "bodies": bodies}))
Ok(cleared.report_if_any(s, json!({"deleted": name, "bodies": bodies})))
}
#[cfg(test)]
@@ -322,6 +638,31 @@ pub(crate) mod tests {
assert!(s.journal.is_empty());
}
/// Suppressing a partition merges its cells back; suppressing its datum does too and stops
/// the datum being an input; unsuppressing cuts again; each is one undo step (#291).
#[test]
fn suppressed_partitions_and_datums_leave_the_design_uncut() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
let count = |s: &Session| s.design.as_ref().map_or(0, |d| d.bodies.len());
assert_eq!(count(&s), 2);
let r = s.execute("geometry.partition.suppress", &json!({"name": "Half"})).unwrap();
assert_eq!((r["suppressed"].as_bool(), count(&s)), (Some(true), 1));
s.execute("geometry.partition.suppress", &json!({"name": "Half", "suppressed": false})).unwrap();
assert_eq!(count(&s), 2);
s.execute("geometry.datum.suppress", &json!({"name": "Mid"})).unwrap();
assert_eq!(count(&s), 1);
let e = s.execute("geometry.partition", &json!({"name": "Again", "datum": "Mid"})).unwrap_err().to_string();
assert!(e.contains("suppressed"), "{e}");
let e = s.execute("geometry.datum.point", &json!({"name": "P", "by": {"type": "axis_plane", "axis": "Mid", "plane": "Mid"}}));
assert!(e.is_err());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(count(&s), 2, "undo cuts again");
assert!(s.execute("geometry.datum.suppress", &json!({"name": "Nope"})).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_partition_cuts_the_design_and_is_replayed_when_it_opens_again() {
let (mut s, dir) = plate();
@@ -330,8 +671,13 @@ pub(crate) mod tests {
let body = r["split"][0].as_str().unwrap().to_string();
assert_eq!(r["cells"], json!([format!("{body}/a"), format!("{body}/b")]));
assert_eq!(r["cut_faces"], json!(4));
// The datum is in use.
// The datum is in use, and hidden: the cut shows as edges on the cells (#295). Its eye
// shows it again.
assert!(s.execute("geometry.datum.delete", &json!({"name": "Mid"})).is_err());
assert!(!s.shows(ItemKind::Datum, "Mid"));
s.execute("view.show", &json!({"items": [{"kind": "datum", "name": "Mid"}]})).unwrap();
assert!(s.shows(ItemKind::Datum, "Mid"));
s.execute("view.hide", &json!({"items": [{"kind": "datum", "name": "Mid"}]})).unwrap();
// A set on a cut face selects the cut face's pieces.
let r = s.execute("geometry.bodies", &json!({})).unwrap();
@@ -344,6 +690,7 @@ pub(crate) mod tests {
let mut t = Session::default();
t.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
assert_eq!(bodies(&t), bodies(&s));
assert!(!t.shows(ItemKind::Datum, "Mid"), "still hidden when opened again");
// geometry.open again keeps the model, so its partition.
let design = dir.join("plate.solidcraft");
let r = t.execute("geometry.open", &json!({"path": design.to_str().unwrap()})).unwrap();
@@ -362,6 +709,117 @@ pub(crate) mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn datum_points_by_each_definition_and_planes_and_axes_through_them() {
let (mut s, dir) = plate();
let point = |s: &Session, n: &str| s.model.datum(n).and_then(Datum::point).unwrap();
let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6);
s.execute("geometry.datum.point", &json!({"name": "O", "by": {"type": "coordinates", "point": [0, 0, 0]}})).unwrap();
s.execute("geometry.datum.point", &json!({"name": "X", "by": {"type": "coordinates", "point": [10, 0, 0]}})).unwrap();
s.execute("geometry.datum.point", &json!({"name": "Y", "by": {"type": "coordinates", "point": [0, 10, 0]}})).unwrap();
// The plate's edge along x at y = 0, z = 0, its midpoint and a quarter along it.
let body = s.design.as_ref().unwrap().bodies[0].clone();
let edge = body.edges().unwrap().into_iter().find(|e| e.points.iter().all(|p| p[1].abs() < 1e-9 && p[2].abs() < 1e-9)).unwrap();
let by = |fraction: f64| json!({"type": "edge", "body": body.name, "edge": edge.name, "fraction": fraction});
s.execute("geometry.datum.point", &json!({"name": "Mid", "by": {"type": "edge", "body": body.name, "edge": edge.name}})).unwrap();
assert!(close(point(&s, "Mid"), [20.0, 0.0, 0.0]), "{:?}", point(&s, "Mid"));
s.execute("geometry.datum.point", &json!({"name": "Q", "by": by(0.25)})).unwrap();
let q = point(&s, "Q");
assert!((q[0] - 10.0).abs() < 1e-6 || (q[0] - 30.0).abs() < 1e-6, "{q:?}");
// The centre of the face at x = 0.
let side =
body.face_surfaces().unwrap().iter().position(
|f| matches!(f, Some(fieldcraft_geometry::FaceSurface::Plane { normal, point }) if normal[0] < -0.5 && point[0].abs() < 1e-9),
);
let face = body.faces()[side.unwrap()].name.clone();
s.execute("geometry.datum.point", &json!({"name": "C", "by": {"type": "face_centre", "body": body.name, "face": face}})).unwrap();
assert!(close(point(&s, "C"), [0.0, 15.0, 5.0]), "{:?}", point(&s, "C"));
// Planes and axes through datum points; a point where an axis crosses a plane.
let r = s.execute("geometry.datum", &json!({"name": "Base", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Y"}})).unwrap();
assert_eq!(r["normal"], json!([0.0, 0.0, 1.0]));
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "datum_points", "a": "O", "b": "X"}})).unwrap();
assert_eq!(s.model.datum("Ax"), Some(&Datum::Axis { point: [0.0; 3], direction: [1.0, 0.0, 0.0] }));
s.execute("geometry.datum", &json!({"name": "Cut", "by": {"type": "normal_to_axis", "axis": "Ax", "point": "Mid"}})).unwrap();
assert_eq!(s.model.datum("Cut"), Some(&Datum::Plane { point: point(&s, "Mid"), normal: [1.0, 0.0, 0.0] }));
s.execute("geometry.datum.point", &json!({"name": "Hit", "by": {"type": "axis_plane", "axis": "Ax", "plane": "Cut"}})).unwrap();
assert!(close(point(&s, "Hit"), [20.0, 0.0, 0.0]));
let journal = s.journal.len();
for p in [
json!({"name": "Z", "by": {"type": "axis_plane", "axis": "Ax", "plane": "Base"}}),
json!({"name": "Z", "by": {"type": "axis_plane", "axis": "Base", "plane": "Cut"}}),
json!({"name": "Z", "by": {"type": "edge", "body": body.name, "edge": edge.name, "fraction": 2}}),
json!({"name": "Z", "by": {"type": "edge", "body": body.name, "edge": "nope"}}),
json!({"name": "Z", "by": {"type": "edge", "body": "Nope", "edge": edge.name}}),
json!({"name": "Z", "by": {"type": "face_centre", "body": body.name, "face": "nope"}}),
// No mesh: no vertex is named.
json!({"name": "Z", "by": {"type": "vertex", "body": body.name, "vertex": "v1"}}),
json!({"name": "Z", "by": {"type": "coordinates", "point": [f64::MAX, 0, 0]}}),
json!({"name": "Z", "by": {"type": "coordinates", "point": [0, 0]}}),
] {
assert!(s.execute("geometry.datum.point", &p).is_err(), "{p}");
}
for (command, p) in [
("geometry.datum", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Mid"}})),
("geometry.datum", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Ax"}})),
("geometry.datum", json!({"name": "Z", "by": {"type": "normal_to_axis", "axis": "Nope"}})),
("geometry.datum.axis", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "O"}})),
] {
assert!(s.execute(command, &p).is_err(), "{p}");
}
assert_eq!(s.journal.len(), journal);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_vertex_point_is_at_the_tagged_mesh_node() {
let mut s = Session::default();
s.execute(
"mesh.block",
&json!({"body": "Bar", "kind": "hex8", "corners": [[0,0,0],[4,0,0],[4,1,0],[0,1,0],[0,0,1],[4,0,1],[4,1,1],[0,1,1]], "divisions": [2, 1, 1], "vertices": {"7": "tip"}}),
)
.unwrap();
s.execute("geometry.datum.point", &json!({"name": "Tip", "by": {"type": "vertex", "body": "Bar", "vertex": "tip"}})).unwrap();
assert_eq!(s.model.datum("Tip").and_then(Datum::point), Some([4.0, 1.0, 1.0]));
}
#[test]
fn editing_and_deleting_datums_follow_their_partitions() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
let cut_at = |s: &Session| s.design.as_ref().unwrap().bodies[0].measure().unwrap().bbox_max[0];
assert!((cut_at(&s) - 15.0).abs() < 1e-6);
// Moving the plane cuts again; an edit of the wrong kind or to an axis is refused.
s.execute("geometry.datum.edit", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 25}})).unwrap();
assert!((cut_at(&s) - 25.0).abs() < 1e-6);
assert!(s.execute("geometry.datum.axis.edit", &json!({"name": "Mid", "by": {"type": "principal", "axis": "y"}})).is_err());
assert!(s.execute("geometry.datum.edit", &json!({"name": "Ax", "by": {"type": "offset", "plane": "xy"}})).is_err());
s.execute("geometry.datum.axis.edit", &json!({"name": "Ax", "by": {"type": "principal", "axis": "y"}})).unwrap();
assert_eq!(s.model.datum("Ax"), Some(&Datum::Axis { point: [0.0; 3], direction: [0.0, 1.0, 0.0] }));
// The edit commands take the parameters edit_params gives back.
for name in ["Mid", "Ax"] {
let (command, params) = edit_params(name, s.model.datum(name).unwrap());
s.execute(command, &params).unwrap();
}
// Deleting the plane names its partition, or deletes it too.
let e = s.execute("geometry.datum.delete", &json!({"name": "Mid"})).unwrap_err().to_string();
assert!(e.contains("partition `Half`"), "{e}");
let r = s.execute("geometry.datum.delete", &json!({"name": "Mid", "cascade": true})).unwrap();
assert_eq!(r["partitions"], json!(["Half"]));
assert!(s.model.partitions().is_empty() && s.model.datum("Mid").is_none());
assert_eq!(bodies(&s).len(), 1);
// One undo step brings both back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((s.model.partitions().len(), bodies(&s).len()), (1, 2));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_partition_that_cuts_nothing_changes_nothing() {
let (mut s, dir) = plate();
@@ -383,4 +841,145 @@ pub(crate) mod tests {
assert_eq!(s.journal.len(), journal);
let _ = std::fs::remove_dir_all(&dir);
}
/// A session with the design `commands` (a SolidCraft script) open.
pub(crate) fn scripted(commands: Value) -> (crate::tests::TempDir, Session) {
let bytes = fieldcraft_geometry::script_design(&json!({"commands": commands}).to_string()).unwrap();
let (dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
(dir, s)
}
/// Partition the open design by the planes `x = …` / `y = …` / `z = …` (`(axis, offset)`).
pub(crate) fn cut_at(s: &mut Session, planes: &[(usize, f64)]) {
for (i, &(k, offset)) in planes.iter().enumerate() {
let (name, plane) = (format!("C{i}"), ["yz", "zx", "xy"][k]);
s.execute("geometry.datum", &json!({"name": name, "by": {"type": "offset", "plane": plane, "offset": offset}})).unwrap();
s.execute("geometry.partition", &json!({"name": format!("P{i}"), "datum": name})).unwrap();
}
}
/// A box with a plate-shaped void in its middle that touches no side (#388): the planes
/// round the void leave a centre column whose material lies above and below the void, two
/// pieces that become separate cells only at the last cut.
#[test]
fn pieces_that_do_not_touch_are_separate_cells() {
let (_dir, mut s) = scripted(json!([
{"command": "solid.box", "params": {"length": 106, "width": 76, "height": 20, "corner": [0, 0, 0], "body_name": "Air"}},
{"command": "solid.box", "params": {"length": 85, "width": 56, "height": 2, "corner": [13, 13, 9], "operation": "cut"}},
]));
let whole = s.design.as_ref().unwrap().bodies[0].measure().unwrap().volume;
cut_at(&mut s, &[(0, 22.5), (0, 68.5), (1, 22.5), (1, 59.5)]);
let design = s.design.clone().unwrap();
let shells: Vec<(&str, usize)> = design.bodies.iter().map(|b| (b.name.as_str(), b.shells().unwrap())).collect();
assert!(shells.iter().all(|s| s.1 == 1), "{shells:?}");
// 3 × 3 columns, the centre one in two pieces.
assert_eq!(shells.len(), 10, "{shells:?}");
let volume: f64 = design.bodies.iter().map(|b| b.measure().unwrap().volume).sum();
assert!((volume - whole).abs() < 1e-6 * whole, "{volume} vs {whole}");
let centre: Vec<&str> = shells.iter().map(|s| s.0).filter(|n| n.ends_with('1') || n.ends_with('2')).collect();
assert_eq!(centre.len(), 2, "{centre:?}");
// Numbered by centroid: the piece below the void first.
let z = |n: &str| design.body(n).unwrap().measure().unwrap().centroid[2];
assert!(z(centre[0]) < 9.0 && z(centre[1]) > 11.0, "{centre:?}");
}
/// #385: the cells' meshes go with the cells (deleting, suppressing or replacing their
/// partitions), a body's mesh goes when a partition cuts it, and meshes left over from an
/// earlier cut are listed by model.check and removed by mesh.clear.
#[test]
fn meshes_go_with_the_bodies_partitions_remove() {
let (mut s, dir) = plate();
let whole = s.design.as_ref().unwrap().bodies[0].measure().unwrap().volume;
let volume = |s: &mut Session| s.execute("mesh.quality", &json!({})).unwrap()["volume"].as_f64().unwrap();
// Partitioning a meshed body takes its mesh.
s.execute("mesh.hex.generate", &json!({"size": 2.5})).unwrap();
s.execute("geometry.datum", &json!({"name": "X30", "by": {"type": "offset", "plane": "yz", "offset": 30}})).unwrap();
let r = s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
assert_eq!(r["replaced"][0]["body"], "Body1", "{r}");
assert!(s.model.elements().is_empty());
// Deleting the datum with its partition takes the cells' meshes; the whole body's new
// mesh is the only one.
s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
let r = s.execute("geometry.datum.delete", &json!({"name": "X30", "cascade": true})).unwrap();
let gone: Vec<&str> = r["replaced"].as_array().unwrap().iter().map(|b| b["body"].as_str().unwrap()).collect();
assert_eq!(gone, ["Body1/a", "Body1/b"], "{r}");
assert!(s.model.elements().is_empty());
s.execute("mesh.hex.generate", &json!({"size": 2.5})).unwrap();
let v = volume(&mut s);
assert!((v - whole).abs() < 1e-2 * whole, "{v} vs {whole}");
// Suppressing or deleting a partition does the same.
s.execute("geometry.datum", &json!({"name": "X30", "by": {"type": "offset", "plane": "yz", "offset": 30}})).unwrap();
s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
let r = s.execute("geometry.partition.suppress", &json!({"name": "P"})).unwrap();
assert_eq!(r["replaced"].as_array().map(Vec::len), Some(2), "{r}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.model.elements().is_empty(), "undo brings the cells' meshes back");
let r = s.execute("geometry.partition.delete", &json!({"name": "P"})).unwrap();
assert_eq!(r["replaced"].as_array().map(Vec::len), Some(2), "{r}");
// A mesh left from an earlier cut (a model saved before the cut changed): listed and
// cleared.
s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
s.model.remove_partition("P").unwrap();
let d = s.design.clone().unwrap();
s.design = Some(Arc::new(partitioned(&d, &s.model).unwrap()));
let check = s.execute("model.check", &json!({})).unwrap();
let listed: Vec<&str> =
check["diagnostics"].as_array().unwrap().iter().filter_map(|d| d["subject"].as_str()).filter(|d| d.starts_with("body")).collect();
assert_eq!(listed, ["body `Body1/a`", "body `Body1/b`"], "{check}");
let r = s.execute("mesh.clear", &json!({})).unwrap();
assert_eq!(r["replaced"].as_array().map(Vec::len), Some(2), "{r}");
assert!(s.model.elements().is_empty());
assert!(s.execute("mesh.clear", &json!({"bodies": ["Body1"]})).is_err(), "nothing to clear");
let _ = std::fs::remove_dir_all(&dir);
}
/// The Raspberry Pi 5 enclosure analysis design (base, lid, heat sink, board, chips and the
/// air inside), its SolidCraft recipe.
pub(crate) fn pi5() -> (crate::tests::TempDir, Session) {
scripted(serde_json::from_str(include_str!("../../tests/designs/pi5-enclosure.json")).unwrap())
}
/// #384: cuts stay on their plane (the kernel's own split put them 1.8 µm off it on the air
/// of the enclosure, so the cut faces were not even recognized), and a plane along an
/// existing face or through a hole's axis is a warning naming the plane, the body and where.
#[test]
fn cuts_stay_on_the_plane_and_risky_ones_are_named() {
let (_dir, mut s) = pi5();
let plane = |s: &mut Session, name: &str, x: f64| {
s.execute("geometry.datum", &json!({"name": name, "by": {"type": "offset", "plane": "yz", "offset": x}})).unwrap();
s.execute("geometry.partition", &json!({"name": format!("P{name}"), "datum": name, "bodies": ["Air"]})).unwrap()
};
// Beside the board's mounting holes: clean cells, cut faces on the plane.
let r = plane(&mut s, "X", 16.5);
assert!(r.get("warnings").is_none(), "{r}");
let design = s.design.clone().unwrap();
for cell in ["Air/a", "Air/b"] {
let shape = design.body(cell).unwrap();
let cut: Vec<f64> = shape
.faces()
.iter()
.zip(shape.face_surfaces().unwrap())
.filter(|(f, _)| f.name.starts_with("partition:PX:"))
.filter_map(|(_, srf)| match srf {
Some(fieldcraft_geometry::FaceSurface::Plane { point, .. }) => Some(point[0]),
_ => None,
})
.collect();
assert!(!cut.is_empty() && cut.iter().all(|x| (x - 16.5).abs() < 1e-9), "{cell}: {cut:?}");
}
s.execute("edit.undo", &json!({})).unwrap();
// Along the side of the heat sink's pedestal: named.
let r = plane(&mut s, "Side", 34.0);
let warnings = r["warnings"].to_string();
assert!(warnings.contains("partition `PSide`: the plane lies on face `F45:-x` of `Air`"), "{r}");
s.execute("edit.undo", &json!({})).unwrap();
// Through a standoff's hole: the cell whose boundary breaks at the hole's edge is named.
let r = plane(&mut s, "Axis", 74.5);
let warnings = r["warnings"].to_string();
assert!(warnings.contains("partition `PAxis`: cell `Air/") && warnings.contains("boundary no mesher takes"), "{r}");
}
}
+81 -3
View File
@@ -13,6 +13,9 @@ use fieldcraft_model::{
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use fieldcraft_io::{Item, ItemKind};
use fieldcraft_model::rename::Kind as RenameKind;
use super::{name, opt, req};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
@@ -92,7 +95,7 @@ definition_commands!(
Material,
"material",
"Material",
r#"{"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3} | {"type": "engineering_constants", "young": [E1, E2, E3], "poisson": [ν12, ν13, ν23], "shear": [G12, G13, G23]}, "density": 7.85e-9, "fluid": {"type": "newtonian", "viscosity": 1.0e-9} (dynamic viscosity; a fluid needs a density), "plastic": {…} (see model.material.plasticity), "damage": {…}, "erosion": {…} (see model.material.damage), "hyperelastic": {"type": "neo_hookean"} | {"type": "mooney_rivlin", "c01": 0.1} (C10 = μ/2 − C01) | {"type": "yeoh", "c20": -0.01, "c30": 0.001} (C10 = μ/2) (large strain in nonlinear steps, from the isotropic constants: μ = E/(2(1 + ν)), κ = E/(3(1 − 2ν)); without it an elastic material is St Venant–Kirchhoff there)} — in the model's unit system (model.units), never converted"#,
r#"{"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3} | {"type": "engineering_constants", "young": [E1, E2, E3], "poisson": [ν12, ν13, ν23], "shear": [G12, G13, G23]}, "density": 7.85e-9, "fluid": {"type": "newtonian", "viscosity": 1.0e-9} (dynamic viscosity; a fluid needs a density), "plastic": {…} (see model.material.plasticity), "damage": {…}, "erosion": {…} (see model.material.damage), "hyperelastic": {"type": "neo_hookean"} | {"type": "mooney_rivlin", "c01": 0.1} (C10 = μ/2 − C01) | {"type": "yeoh", "c20": -0.01, "c30": 0.001} (C10 = μ/2) (large strain in nonlinear steps, from the isotropic constants: μ = E/(2(1 + ν)), κ = E/(3(1 − 2ν)); without it an elastic material is St Venant–Kirchhoff there), "thermal": {"conductivity": 0.05 | [kx, ky, kz], "specific_heat": 4.6e8, "expansion": 1.2e-5 | [αx, αy, αz], "reference_temperature": 20 (zero thermal strain; default 0)} (heat transfer and thermal strain; each key optional)} — in the model's unit system (model.units), never converted"#,
super::forms::MATERIAL,
super::forms::MATERIAL_DELETE,
add_material,
@@ -267,7 +270,7 @@ definition_commands!(
Load,
"load",
"Load",
r#"{"name": "push", "type": "force|moment", "target": {"set": "…"} | {"reference_point": "…"}, "vector": [x, y, z], "distribution": "total" (default: the vector is the total, split by area over the set's faces, or equally over its nodes) | "per_node" (at every node: depends on the mesh)} | {"name", "type": "traction", "set", "vector" (per area, on the set's faces)} | {"name", "type": "pressure", "set", "magnitude" (positive pushes in)} | {"name", "type": "gravity", "acceleration": [x, y, z], "set" (optional, default the whole model)} | {"name", "type": "body_force", "set", "vector" (per volume)} | {"name", "type": "centrifugal", "angular_velocity" (rad per time unit), "point": [x, y, z] (on the axis), "axis": [x, y, z], "set" (optional)} — 2D models: in-plane vectors, surface loads on element edges; active in the steps that list it (model.step.activate)"#,
r#"{"name": "push", "type": "force|moment", "target": {"set": "…"} | {"reference_point": "…"}, "vector": [x, y, z], "distribution": "total" (default: the vector is the total, split by area over the set's faces, or equally over its nodes) | "per_node" (at every node: depends on the mesh)} | {"name", "type": "traction", "set", "vector" (per area, on the set's faces)} | {"name", "type": "pressure", "set", "magnitude" (positive pushes in)} | {"name", "type": "gravity", "acceleration": [x, y, z], "set" (optional, default the whole model)} | {"name", "type": "body_force", "set", "vector" (per volume)} | {"name", "type": "centrifugal", "angular_velocity" (rad per time unit), "point": [x, y, z] (on the axis), "axis": [x, y, z], "set" (optional)} | {"name", "type": "surface_flux", "set", "flux" (heat per area into the set's faces)} | {"name", "type": "convection", "set", "film" (film coefficient h), "sink" (surrounding temperature): heat flux h (sink − T) into the set's faces} | {"name", "type": "heat_source", "set", "power" (heat per volume in the set's elements)} | {"name", "type": "temperature", "target": {"set": "…"} | {"reference_point": "…"}, "value" (a temperature that strains the material in stress steps)} — heat loads act in heat transfer and coupled steps; 2D models: in-plane vectors, surface loads on element edges; active in the steps that list it (model.step.activate)"#,
super::forms::LOAD,
super::forms::LOAD_DELETE,
add_load,
@@ -319,7 +322,7 @@ fn fluid_boundary(s: &mut Session, p: &Value) -> Result<Value> {
pub const STEP_CREATE: CommandSpec = CommandSpec {
id: "model.step.create",
label: "New Step",
params: r#"{"name": "Bend", "procedure": {"type": "static"} | {"type": "nonlinear_static", "nonlinear_geometry": true, "initial_increment": 0.1, "min_increment": 1e-5, "max_increment": 1.0 (fractions of the step), "max_increments": 100, "max_iterations": 16 (per increment), "tolerances": {"force": 1e-6, "displacement": 1e-5, "energy": 1e-10}, "line_search": false, "load_path": [[0, 0], [0.5, 1], [1, 0]] (optional: the load factor against the step fraction, piecewise linear from [0, 0] to fraction 1; increments end at its points)} (loads and prescribed displacements are the load factor times their values; it ramps from 0 to 1 without a load path) | {"type": "frequency", "modes": 10, "min_hz": 0, "max_hz": 500} | {"type": "fluid", "domain": "Flow", "end_time": 1.0 | "steps": 1000, "time_step": (default: chosen for Mach 0.087 and τ ≤ 1), "frames": 10, "magic": 0.1875 (the two-relaxation-time Λ)} | {"type": "explicit_dynamic", "end_time": 0.001, "dt_scale": 0.9, "max_increments": 10000000, "output_interval", "history_interval", "history_nodes": "set", "initial_velocities": [{"set", "velocity": [vx, vy, vz]}], "rigid_walls": [{"set", "point", "normal", "friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb; default frictionless)}], "hourglass": {"type": "viscous|stiffness", "coefficient": 0.1}, "bulk_viscosity": {"linear": 0.06, "quadratic": 1.5}, "mass_scaling": {"target_increment": 1e-6, "set": "…" (optional, default every element)} (opt-in: elements below the target increment get the density that reaches it; the added mass is reported)}, "output": ["displacement", "reaction_force", "stress", "strain"] (default by procedure), "boundary_conditions": [names], "loads": [names] (active in this step; nothing carries over between steps), "before": "step" (default: last)}"#,
params: r#"{"name": "Bend", "procedure": {"type": "static"} | {"type": "nonlinear_static", "nonlinear_geometry": true, "initial_increment": 0.1, "min_increment": 1e-5, "max_increment": 1.0 (fractions of the step), "max_increments": 100, "max_iterations": 16 (per increment), "tolerances": {"force": 1e-6, "displacement": 1e-5, "energy": 1e-10}, "line_search": false, "load_path": [[0, 0], [0.5, 1], [1, 0]] (optional: the load factor against the step fraction, piecewise linear from [0, 0] to fraction 1; increments end at its points)} (loads and prescribed displacements are the load factor times their values; it ramps from 0 to 1 without a load path) | {"type": "frequency", "modes": 10, "min_hz": 0, "max_hz": 500} | {"type": "buckle", "modes": 5, "shift"?: 0} | {"type": "heat_transfer", "transient"?: {"end_time": 10, "increment": 0.5, "theta": 1, "initial_temperature": 20}} (steady without `transient`) | {"type": "coupled_temperature_displacement"} (steady heat and the static equilibrium of its thermal strains) | {"type": "fluid", "domain": "Flow", "end_time": 1.0 | "steps": 1000, "time_step": (default: chosen for Mach 0.087 and τ ≤ 1), "frames": 10, "magic": 0.1875 (the two-relaxation-time Λ)} | {"type": "explicit_dynamic", "end_time": 0.001, "dt_scale": 0.9, "max_increments": 10000000, "output_interval", "history_interval", "history_nodes": "set", "initial_velocities": [{"set", "velocity": [vx, vy, vz]}], "rigid_walls": [{"set", "point", "normal", "friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb; default frictionless)}], "hourglass": {"type": "viscous|stiffness", "coefficient": 0.1}, "bulk_viscosity": {"linear": 0.06, "quadratic": 1.5}, "mass_scaling": {"target_increment": 1e-6, "set": "…" (optional, default every element)} (opt-in: elements below the target increment get the density that reaches it; the added mass is reported)}, "output": ["displacement", "reaction_force", "stress", "strain"] (default by procedure), "boundary_conditions": [names], "loads": [names] (active in this step; nothing carries over between steps), "before": "step" (default: last)}"#,
form: Some(super::forms::STEP_CREATE),
kind: CommandKind::Model,
requires: &[],
@@ -356,6 +359,60 @@ pub const STEP_ACTIVATE: CommandSpec = CommandSpec {
run: step_activate,
};
pub const RENAME: CommandSpec = CommandSpec {
id: "model.rename",
label: "Rename",
params: r#"{"kind": "set" | "material" | "section" | "step" | "boundary_condition" | "load" | "reference_point" | "coupling" | "contact" | "tie" | "point_mass" | "spring" | "fluid_domain" | "datum", "from": "end", "to": "Tip"} — renames the definition and every reference to it (sets in sections, couplings, contacts, ties, discrete elements, boundary conditions, loads and explicit steps; materials in sections and fluid domains; reference points; boundary conditions and loads in the steps they are active in; steps in imperfections; fluid domains in fluid steps; datum planes in partitions). A name already taken is refused; the viewport's hidden items follow the new name"#,
form: Some(super::forms::RENAME),
kind: CommandKind::Model,
requires: &[],
run: rename,
};
/// `model.rename`'s kinds, as the command takes them.
pub const RENAME_KINDS: &[(&str, RenameKind)] = &[
("set", RenameKind::Set),
("material", RenameKind::Material),
("section", RenameKind::Section),
("step", RenameKind::Step),
("boundary_condition", RenameKind::BoundaryCondition),
("load", RenameKind::Load),
("reference_point", RenameKind::ReferencePoint),
("coupling", RenameKind::Coupling),
("contact", RenameKind::Contact),
("tie", RenameKind::Tie),
("point_mass", RenameKind::PointMass),
("spring", RenameKind::Spring),
("fluid_domain", RenameKind::FluidDomain),
("datum", RenameKind::Datum),
];
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let kind: &str = req(p, "kind")?;
let from: &str = req(p, "from")?;
let to: &str = req(p, "to")?;
let Some((_, k)) = RENAME_KINDS.iter().find(|(id, _)| *id == kind) else {
let kinds: Vec<&str> = RENAME_KINDS.iter().map(|(id, _)| *id).collect();
return Err(EngineError::Params(format!("`kind` is one of {}", kinds.join(", "))));
};
s.model.rename(*k, from, to)?;
// What the viewport hides follows the new name.
let item = match k {
RenameKind::Datum => Some(ItemKind::Datum),
RenameKind::BoundaryCondition => Some(ItemKind::BoundaryCondition),
RenameKind::Load => Some(ItemKind::Load),
RenameKind::ReferencePoint => Some(ItemKind::ReferencePoint),
RenameKind::Coupling => Some(ItemKind::Coupling),
_ => None,
};
if let Some(kind) = item
&& s.view.hidden.remove(&Item { kind, name: from.to_string() })
{
s.view.hidden.insert(Item { kind, name: to.to_string() });
}
Ok(json!({"kind": kind, "from": from, "name": to}))
}
pub const ACTIVITY: CommandSpec = CommandSpec {
id: "model.activity",
label: "Step Table",
@@ -473,6 +530,27 @@ pub(crate) mod tests {
s.run_script(&script).unwrap();
}
/// A rename rewrites the references, checks clean, is undone in one step, follows the hidden
/// state and refuses a name in use (#290).
#[test]
fn rename_keeps_the_model_whole_and_undoes() {
let mut s = Session::default();
defined_bar(&mut s);
s.execute("view.hide", &json!({"items": [{"kind": "load", "name": "push"}]})).unwrap();
s.execute("model.rename", &json!({"kind": "set", "from": "end", "to": "Tip"})).unwrap();
s.execute("model.rename", &json!({"kind": "load", "from": "push", "to": "Push"})).unwrap();
s.execute("model.rename", &json!({"kind": "step", "from": "Bend", "to": "Load"})).unwrap();
assert!(s.model.sets().get("end").is_none() && !s.model.set_users("Tip").is_empty());
assert!(s.model.step("Load").is_some_and(|st| st.loads.contains("Push")));
assert!(s.view.is_hidden(fieldcraft_io::ItemKind::Load, "Push") && !s.view.is_hidden(fieldcraft_io::ItemKind::Load, "push"));
assert_eq!(s.execute("model.check", &json!({})).unwrap()["ready"], true);
let e = s.execute("model.rename", &json!({"kind": "set", "from": "Tip", "to": "root"})).unwrap_err().to_string();
assert!(e.contains("already exists"), "{e}");
assert!(s.execute("model.rename", &json!({"kind": "partition", "from": "a", "to": "b"})).is_err());
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.model.step("Bend").is_some() && s.model.step("Load").is_none());
}
#[test]
fn a_script_defines_a_model_that_checks_clean() {
let mut s = Session::default();
+198
View File
@@ -0,0 +1,198 @@
//! Crash reports and bug report drafts (docs/crash-reports.md): list and read the reports the
//! desktop app wrote, draft a bug report, and (with `FIELDCRAFT_CRASH_TEST=1`) crash on purpose
//! to check that reporting works.
use std::path::PathBuf;
use fieldcraft_io::roots::Access;
use serde_json::{Value, json};
use super::{file_param, opt, req};
use crate::{CommandKind, CommandSpec, EngineError, Result, Session, bug_report, crash};
pub const CRASH_REPORTS: CommandSpec = CommandSpec {
id: "diagnostics.crash_reports",
label: "Crash Reports",
params: r#"{"limit"?: 20, "dir"?: "…"} — the crash reports the desktop app wrote on this computer, newest first: id, kind (command_panic, recovered_panic, panic, unclean_exit), time, message, command, count, version, path and whether it can be replayed (default folder: FIELDCRAFT_CRASH_DIR, a temporary folder in runs driven by automation, else the per-user data folder)"#,
form: Some(super::forms::CRASH_REPORTS),
kind: CommandKind::Session,
requires: &[],
run: crash_reports,
};
pub const CRASH_REPORT: CommandSpec = CommandSpec {
id: "diagnostics.crash_report",
label: "Crash Report",
params: r#"{"id": "20261014-101500-…", "dir"?: "…"} — one crash report: what happened, where, the backtrace, the command and recent commands, and the paths of its model, replay and log files"#,
form: Some(super::forms::CRASH_REPORT),
kind: CommandKind::Session,
requires: &[],
run: crash_report,
};
pub const CRASH_REPORTS_DELETE: CommandSpec = CommandSpec {
id: "diagnostics.crash_reports.delete",
label: "Delete Crash Reports",
params: r#"{"id": "20261014-101500-…"} or {"all": true}; "dir"?: "…" — deletes one crash report, or all of them, from this computer: how many were deleted"#,
form: Some(super::forms::CRASH_REPORTS_DELETE),
kind: CommandKind::Session,
requires: &[],
run: crash_reports_delete,
};
pub const BUG_REPORT: CommandSpec = CommandSpec {
id: "diagnostics.bug_report",
label: "Report a Bug",
params: r#"{"title"?: "…", "observed"?: "what happened", "crash"?: "<crash report id>", "share_session"?: false, "include_model"?: false} — drafts a GitHub bug report: the issue link (the bug form filled with the version, the OS, what happened and, for a crash, where), and the files to attach. Only with share_session does it carry the model's commands, and only with include_model as well the model file. Nothing is sent: the desktop app's Help › Report a Bug shows the draft and opens the link when the user asks"#,
form: Some(super::forms::BUG_REPORT),
kind: CommandKind::Session,
requires: &[],
run: bug_report_draft,
};
pub const CRASH_TEST: CommandSpec = CommandSpec {
id: "diagnostics.crash_test",
label: "Crash Test",
params: r#"{"mode": "panic|recovered|abort"} — crashes on purpose to check that crash reports work (only with FIELDCRAFT_CRASH_TEST=1): panic, an internal error in this command; recovered, one caught inside it; abort, the app ends at once (reported at its next start)"#,
form: Some(super::forms::CRASH_TEST),
kind: CommandKind::Session,
requires: &[],
run: crash_test,
};
fn crash_dir(s: &Session, p: &Value) -> Result<PathBuf> {
crash_dir_for(s, p, Access::Read)
}
fn crash_dir_for(s: &Session, p: &Value, access: Access) -> Result<PathBuf> {
if p.get("dir").is_some() {
return Ok(PathBuf::from(file_param(s, p, "dir", access)?));
}
crash::default_dir().ok_or_else(|| EngineError::Params("no crash folder: set FIELDCRAFT_CRASH_DIR or give `dir`".into()))
}
fn crash_reports(s: &mut Session, p: &Value) -> Result<Value> {
let dir = crash_dir(s, p)?;
let limit = opt::<usize>(p, "limit")?.unwrap_or(crash::MAX_REPORTS);
let mut reports = crash::list(&dir);
reports.truncate(limit);
Ok(json!({"dir": dir.to_string_lossy(), "reports": reports}))
}
fn crash_report(s: &mut Session, p: &Value) -> Result<Value> {
let dir = crash_dir(s, p)?;
let id = req::<String>(p, "id")?;
crash::read(&dir, &id).map_err(EngineError::Params)
}
fn crash_reports_delete(s: &mut Session, p: &Value) -> Result<Value> {
let id = opt::<String>(p, "id")?;
let all = opt::<bool>(p, "all")?.unwrap_or(false);
let dir = crash_dir_for(s, p, Access::Write)?;
let deleted = match (id.as_deref(), all) {
(Some(id), false) => match crash::clear(&dir, Some(id)) {
0 => return Err(EngineError::Params(format!("no crash report `{}`", crash::limited(id, 64)))),
n => n,
},
(None, true) => crash::clear(&dir, None),
_ => return Err(EngineError::Params("give one of `id` (a crash report) or `all: true`".into())),
};
Ok(json!({"deleted": deleted}))
}
/// The draft input for `p` from the session: its commands and model (when shared), or a crash
/// report's replay and model.
pub fn bug_report_input(s: &Session, p: &Value) -> Result<bug_report::Input> {
let share = opt::<bool>(p, "share_session")?.unwrap_or(false);
let include_model = opt::<bool>(p, "include_model")?.unwrap_or(false);
let mut input = bug_report::Input {
title: opt::<String>(p, "title")?.unwrap_or_default(),
observed: opt::<String>(p, "observed")?.unwrap_or_default(),
share_session: share,
include_model,
..Default::default()
};
match opt::<String>(p, "crash")? {
Some(id) => {
let report = crash::read(&crash_dir(s, p)?, &id).map_err(EngineError::Params)?;
if share {
let read = |k: &str| {
report
.get(k)
.and_then(Value::as_str)
.and_then(|f| fieldcraft_io::fs::read_capped(std::path::Path::new(f), crash::MAX_MODEL_BYTES as u64).ok())
};
let replay: Value = read("replay_path").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(Value::Null);
input.commands = replay.get("commands").and_then(Value::as_array).cloned().unwrap_or_default();
input.model = if include_model { read("model_path") } else { None };
}
input.crash = Some(report);
}
None if share => {
input.commands = s.journal.iter().map(|(command, params)| json!({"command": command, "params": params})).collect();
input.model = if include_model { Some(s.file_bytes(None)?) } else { None };
}
None => {}
}
Ok(input)
}
fn bug_report_draft(s: &mut Session, p: &Value) -> Result<Value> {
let input = bug_report_input(s, p)?;
Ok(bug_report::draft(&input, &crash::Build::current().version_line()).to_json())
}
// The one deliberate panic and abort: they prove that crash reports work, and run only when
// asked for with FIELDCRAFT_CRASH_TEST=1.
#[allow(clippy::panic)]
fn crash_test(_: &mut Session, p: &Value) -> Result<Value> {
let mode = req::<String>(p, "mode")?;
if std::env::var_os("FIELDCRAFT_CRASH_TEST").is_none_or(|v| v != "1") {
return Err(EngineError::Params("the crash test runs only with FIELDCRAFT_CRASH_TEST=1".into()));
}
match mode.as_str() {
"panic" => std::panic::panic_any(String::from("crash test: an internal error in a command")),
"recovered" => {
let caught = std::panic::catch_unwind(|| std::panic::panic_any(String::from("crash test: an internal error caught inside a command")));
Ok(json!({"caught": caught.is_err()}))
}
"abort" => std::process::abort(),
_ => Err(EngineError::invalid("mode", "must be panic, recovered or abort")),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `diagnostics.crash_reports.delete` deletes one report by id, then the rest; an unknown or
/// hostile id and a missing choice are errors that delete nothing.
#[test]
fn crash_reports_are_deleted_one_or_all() {
let dir = std::env::temp_dir().join(format!("fieldcraft-crash-delete-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let ids = ["20261014-101500-0000000000000001", "20261014-101600-0000000000000002", "20261014-101700-0000000000000003"];
for id in ids {
std::fs::create_dir_all(dir.join(id)).unwrap();
std::fs::write(dir.join(id).join("report.json"), r#"{"kind": "panic", "message": "x"}"#).unwrap();
}
let mut s = Session::default();
let d = dir.to_string_lossy().to_string();
let listed = |s: &mut Session| s.execute("diagnostics.crash_reports", &json!({"dir": d})).unwrap()["reports"].as_array().map_or(0, Vec::len);
assert_eq!(listed(&mut s), 3);
for bad in [
json!({"dir": d}),
json!({"dir": d, "id": "../x"}),
json!({"dir": d, "id": "20261014-101500-00000000000000ff"}),
json!({"dir": d, "id": ids[0], "all": true}),
] {
assert!(s.execute("diagnostics.crash_reports.delete", &bad).is_err(), "{bad}");
}
assert_eq!(listed(&mut s), 3);
assert_eq!(s.execute("diagnostics.crash_reports.delete", &json!({"dir": d, "id": ids[1]})).unwrap()["deleted"], 1);
assert_eq!(listed(&mut s), 2);
assert_eq!(s.execute("diagnostics.crash_reports.delete", &json!({"dir": d, "all": true})).unwrap()["deleted"], 2);
assert_eq!(listed(&mut s), 0);
let _ = std::fs::remove_dir_all(&dir);
}
}
+49 -4
View File
@@ -19,6 +19,16 @@ use fieldcraft_io::roots::{Access, Roots};
use super::{file_param, req};
use crate::{CommandKind, CommandSpec, EngineError, Result, Session, next_revision};
pub const NEW: CommandSpec = CommandSpec {
id: "file.new",
label: "New Model",
params: r#"{} — starts an empty model in place of the current one: no design, mesh, definitions, results or journal; unsaved changes are discarded (the window asks first) and the undo history starts empty"#,
form: Some(&[]),
kind: CommandKind::Session,
requires: &[],
run: new_model,
};
pub const OPEN: CommandSpec = CommandSpec {
id: "file.open",
label: "Open Model",
@@ -89,6 +99,15 @@ pub const SAMPLE: CommandSpec = CommandSpec {
run: open_sample,
};
fn new_model(s: &mut Session, _: &Value) -> Result<Value> {
let mut empty = Session::default();
// Nothing to save until a command changes it.
empty.saved_revision = Some(empty.revision);
empty.saved_view = empty.view.clone();
s.replace_with(empty);
Ok(summary(s, &[]))
}
fn open_sample(s: &mut Session, p: &Value) -> Result<Value> {
let name: &str = req(p, "name")?;
let names = || crate::sample::SAMPLES.iter().map(|x| x.name).collect::<Vec<_>>().join(", ");
@@ -105,6 +124,8 @@ fn open_sample(s: &mut Session, p: &Value) -> Result<Value> {
opened.run_script(&script)?;
// A sample just opened has nothing to save: it opens again the same way.
opened.saved_revision = Some(opened.revision);
opened.saved_view = opened.view.clone();
opened.sample = Some(sample.label);
s.replace_with(opened);
let mut reply = summary(s, &[]);
reply["sample"] = json!(sample.name);
@@ -190,7 +211,7 @@ impl Session {
design: self.sources.design.as_ref().map(stored).transpose()?,
meshes: self.sources.meshes.iter().map(stored).collect::<fieldcraft_io::Result<_>>()?,
};
Ok(fieldcraft_io::write(&self.model, &geometry, &self.journal)?)
Ok(fieldcraft_io::write(&self.model, &geometry, &self.journal, &self.view)?)
}
/// A session holding what a file holds, its geometry opened again from the paths it names
@@ -220,17 +241,28 @@ impl Session {
surfaces.extend(opened.into_iter().flatten().map(Arc::new));
sources.meshes.push(source);
}
let session =
Session { model: file.model, design, surfaces, sources, journal: file.journal, revision: next_revision(), ..Session::default() };
let session = Session {
model: file.model,
design,
surfaces,
sources,
journal: file.journal,
revision: next_revision(),
saved_view: file.view.clone(),
view: file.view,
..Session::default()
};
(session, warnings)
}
/// Replace this session with `opened`, keeping its undo memory limit, its work caps and its
/// file access; the history starts empty.
/// file access (and where its commands come from); the history starts empty.
fn replace_with(&mut self, mut opened: Session) {
opened.history = std::mem::take(&mut self.history);
opened.limits = self.limits;
opened.file_access = std::mem::take(&mut self.file_access);
opened.crash_journal = self.crash_journal;
opened.origin = self.origin;
opened.clear_history();
opened.mark_opened();
*self = opened;
@@ -362,6 +394,19 @@ mod tests {
s.execute("model.material.create", &json!({"name": "Steel", "elastic": {"type": "isotropic", "young": 210000.0, "poisson": 0.3}})).unwrap();
}
/// `file.new` empties the model, its journal and its undo history, and has nothing to save.
#[test]
fn new_starts_an_empty_model() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
s.execute("mesh.node.add", &json!({"label": 10_000, "xyz": [0, 0, 0]})).unwrap();
let r = s.execute("file.new", &json!({})).unwrap();
assert_eq!((r["nodes"].as_u64(), r["elements"].as_u64(), r["journal"].as_u64()), (Some(0), Some(0), Some(0)), "{r}");
assert!(s.model.materials().is_empty() && s.model.steps().is_empty() && s.design.is_none() && s.sample.is_none());
assert!(!s.is_dirty(), "an empty model has nothing to save");
assert!(s.execute("edit.undo", &json!({})).is_err(), "the undo history starts empty");
}
#[test]
fn save_and_open_keep_the_model_journal_and_design() {
let d = dir("roundtrip");
+320 -25
View File
@@ -54,8 +54,10 @@ pub const SET: &[Field] = &[
)
.help("Bodies of the design, or their named faces, edges or vertices. Kept by name, so the set survives remeshing.")
.hint("whole bodies, or their faces, edges or vertices"),
json("nodes", "Nodes").help("Mesh node labels, as a JSON list.").hint("[labels]"),
json("elements", "Elements").help("Mesh element labels, as a JSON list.").hint("[labels]"),
labels("nodes", "Nodes", LabelOf::Node).help("Mesh node labels; Use selection takes the picked nodes.").hint("labels: 1, 2, 10-20"),
labels("elements", "Elements", LabelOf::Element)
.help("Mesh element labels; Use selection takes the picked elements.")
.hint("labels: 1, 2, 10-20"),
json("faces", "Element faces").help("Element faces, as a JSON list of element label and local face number.").hint("[{\"element\", \"face\"}]"),
json("edges", "Element edges").help("Element edges, as a JSON list of element label and local edge number.").hint("[{\"element\", \"edge\"}]"),
];
@@ -351,9 +353,9 @@ pub const REFERENCE_POINT: &[Field] = &[
int("label", "Node label", 0, u32::MAX as i64).help("The node label written to decks.").hint("0: the highest free label"),
];
const DOFS: Field = json("dofs", "Degrees of freedom")
const DOFS: Field = multi("dofs", "Degrees of freedom", &[("1", "UX"), ("2", "UY"), ("3", "UZ"), ("4", "URX"), ("5", "URY"), ("6", "URZ")])
.help("Which of the six DOFs to couple (1–3 translations, 4–6 rotations); all when empty.")
.hint("[1, …, 6], default all");
.hint("all");
pub const COUPLING: &[Field] = &[
NAME,
@@ -809,9 +811,20 @@ const PROCEDURE: Field = variants(
)
.help("What the step solves: linear or nonlinear static, buckling, frequencies, explicit dynamics, heat transfer or flow.");
const OUTPUT: Field = json("output", "Output")
.help("Which results to keep, as JSON; by procedure when empty.")
.hint("[\"displacement\", \"stress\", …]; by procedure when empty");
const OUTPUT: Field = multi(
"output",
"Output",
&[
("\"displacement\"", "Displacement"),
("\"reaction_force\"", "Reaction force"),
("\"stress\"", "Stress"),
("\"strain\"", "Strain"),
("\"temperature\"", "Temperature"),
("\"heat_flux\"", "Heat flux"),
],
)
.help("Which results to keep; by procedure when none is ticked.")
.hint("by procedure");
const STEP_BCS: Field =
references("boundary_conditions", "Boundary conditions", C::BoundaryCondition).help("The boundary conditions active in the step.");
const STEP_LOADS: Field = references("loads", "Loads", C::Load).help("The loads active in the step.");
@@ -834,6 +847,43 @@ pub const STEP_ACTIVATE: &[Field] = &[
flag("active", "Active").help("On: they act in the step. Off: they are switched off from it on.").def("true"),
];
pub const DATUM_SUPPRESS: &[Field] = &[
reference("name", "Datum", C::Datum).help("The datum to keep but leave out of the model.").req(),
flag("suppressed", "Suppressed").help("On: left out (its partitions stop cutting). Off: back in the model.").def("true"),
];
pub const PARTITION_SUPPRESS: &[Field] = &[
reference("name", "Partition", C::Partition).help("The partition to keep but leave out: its cells merge back.").req(),
flag("suppressed", "Suppressed").help("On: the design is cut without it. Off: it cuts again.").def("true"),
];
pub const RENAME: &[Field] = &[
choice(
"kind",
"Kind",
&[
("set", "Set"),
("material", "Material"),
("section", "Section"),
("step", "Step"),
("boundary_condition", "Boundary condition"),
("load", "Load"),
("reference_point", "Reference point"),
("coupling", "Coupling"),
("contact", "Contact"),
("tie", "Tie"),
("point_mass", "Point mass"),
("spring", "Spring"),
("fluid_domain", "Fluid domain"),
("datum", "Datum"),
],
)
.help("What kind of definition to rename.")
.req(),
text("from", "Name").help("Its current name.").req(),
text("to", "New name").help("Every definition that refers to it is changed to the new name.").req(),
];
pub const UNITS: &[Field] = &[choice(
"system",
"Unit system",
@@ -1050,10 +1100,22 @@ pub const HEX_BLOCKS: &[Field] = &[
FEATURE_ANGLE,
];
const CELL_METHODS: &[(&str, &str)] = &[
("auto", "Auto (hex, else tet)"),
("hex", "Hex"),
("swept", "Swept"),
("extrude", "Extrude"),
("sweep", "Sweep"),
("revolve", "Revolve"),
("mapped", "Mapped"),
("tet", "Tet"),
];
pub const CELLS: &[Field] = &[
json("methods", "Methods")
.help("The meshing method per cell, as JSON.")
.hint(r#"{"cell": "auto | hex | swept | extrude | sweep | revolve | mapped | tet"}"#),
references("bodies", "Cells", C::Body)
.help("The cells (bodies) to mesh: tick them, or pick them in the viewport (Select: Bodies) and Use selection. Every body of the design when none is ticked.")
.hint("every body of the design"),
ref_choices("methods", "Methods", C::Body, CELL_METHODS).help("A meshing method for single cells; the others take Other cells' method."),
choice(
"default",
"Other cells",
@@ -1062,12 +1124,15 @@ pub const CELLS: &[Field] = &[
.help("The method for cells not listed in Methods. All hex meshes every cell as a mapped block, with the division counts of all cells assigned together so shared faces match (mesh.hex.blocks).")
.notes(&[("blocks", "All hex: every cell must have six sides, each with four edges; leave Methods empty.")])
.def("\"auto\""),
references("bodies", "Cells", C::Body).help("The cells (bodies) to mesh; every body of the design when empty.").hint("every body of the design"),
HEX_SIZE,
HEX_ORDER,
TOLERANCE,
];
pub const CLEAR_MESH: &[Field] = &[references("bodies", "Bodies", C::Body)
.help("The bodies whose meshes go. When none is ticked: the meshes of bodies the open design no longer has because its partitions changed (model.check lists them).")
.hint("the bodies partitions removed")];
pub const MIRROR: &[Field] = &[
json("plane", "Plane")
.help("The mirror plane: a datum plane's name, or a point and normal as JSON.")
@@ -1120,7 +1185,7 @@ pub const BLOCK: &[Field] = &[
.help("The element type of the block.")
.req()
.def("\"hex8\""),
json("corners", "Corners").help("The eight corner points (four for 2D), as JSON.").req().hint("[[x, y, z] × 8] (2D: × 4 at z = 0)"),
points("corners", "Corners", D::Length, 8).help("The eight corner points (four for 2D, at z = 0).").req(),
json("divisions", "Divisions").help("Elements along each edge direction, as JSON.").req().hint("[n12, n14, n15] (2D: [n12, n14])"),
json("bias", "Bias").help("Element size ratio along each direction, as JSON; 1 is uniform.").hint("[1, 1, 1]"),
json("edges", "Curved and named edges").help("Edge curves and names, as JSON."),
@@ -1145,7 +1210,7 @@ pub const PLANAR: &[Field] = &[
];
pub const QUALITY: &[Field] = &[
json("elements", "Elements").help("The elements to measure, as JSON labels; all when empty.").hint("[labels]; all when empty"),
labels("elements", "Elements", LabelOf::Element).help("The elements to measure; all when empty.").hint("all"),
int("bins", "Histogram bins", 1, 1000).help("Number of bars in the quality histogram.").def("10"),
];
@@ -1185,7 +1250,52 @@ pub const ELEMENT_ADD: &[Field] = &[
.help("The element type.")
.req()
.def("\"hex8\""),
json("nodes", "Nodes").help("The element's node labels in order, as JSON.").req().hint("[labels]"),
labels("nodes", "Nodes", LabelOf::Node).help("The element's node labels in order.").req().hint("labels in order: 1, 2, 3, 4"),
];
const MERGE_TOLERANCE: Field =
positive("tolerance", "Tolerance", D::Length).help("Nodes closer than this are one node.").hint("a millionth of the mesh's size");
pub const NODE_MERGE: &[Field] = &[
MERGE_TOLERANCE,
reference("set", "Set", C::Set).help("Merge only the nodes of this set (and of its elements and faces).").hint("every node"),
choice("keep", "Keep", &[("lowest", "Lowest label"), ("highest", "Highest label")]).help("Which node of each group survives.").def("\"lowest\""),
];
pub const CHECK_DUPLICATES: &[Field] = &[MERGE_TOLERANCE];
pub const NODE_RELAX: &[Field] = &[
xyz("center", "Centre", D::Length).help("The centre of the sphere of influence; click the mesh to place it.").hint("click the mesh"),
positive("radius", "Radius", D::Length).help("Nodes closer to the centre than this move; Alt + scroll over the view changes it."),
int("around_element", "Around element", 1, 99_999_999)
.help("Instead of a centre: a sphere round this element (radius default twice its longest edge).")
.hint("none"),
labels("nodes", "Nodes", LabelOf::Node).help("Instead of a sphere: these nodes.").hint("none"),
references("bodies", "Bodies", C::Body).help("Only the nodes of these bodies.").hint("every body"),
int("iterations", "Iterations", 1, 100).help("Sweeps over the nodes.").def("5"),
range("strength", "Strength", D::None, 0.0, 1.0).help("How far each node moves toward its relaxed position, 0 to 1.").def("1"),
choice("falloff", "Falloff", &[("smooth", "Smooth"), ("linear", "Linear"), ("none", "None")])
.help("How the strength falls from the centre to the radius, so the edit blends into the mesh.")
.def("\"smooth\""),
text("field", "Keep as").help("The relaxation field to keep, to apply again after a remesh.").hint("Relax1, Relax2, …"),
flag("reapply", "Reapply after remesh").help("Apply the field again by itself after each remesh.").def("false"),
];
pub const NODE_RELAX_APPLY: &[Field] = &[
text("field", "Field").req().help("The relaxation field kept by Relax Nodes."),
references("bodies", "Bodies", C::Body).help("Only the nodes of these bodies.").hint("the field's bodies"),
range("polish", "Polish", D::None, 0.0, 1.0).help("Strength of one guarded smoothing sweep after the field is applied; 0 for none.").def("0.3"),
];
pub const RENUMBER: &[Field] = &[
choice("what", "Renumber", &[("both", "Nodes and elements"), ("nodes", "Nodes"), ("elements", "Elements")])
.help("Which labels change.")
.def("\"both\""),
choice("by", "Order", &[("compact", "Compact (label order)"), ("bandwidth", "Bandwidth (reverse Cuthill–McKee)"), ("body", "Body by body")])
.help("The order of the new labels.")
.def("\"compact\""),
int("start", "Start", 1, 99_999_999).help("The first new label.").def("1"),
int("offset", "Offset", -99_999_999, 99_999_999).help("Instead of an order and a start: add this to every label.").hint("none"),
];
pub const SEED_EDGE: &[Field] = &[
@@ -1214,7 +1324,7 @@ pub const SEED_EDGE: &[Field] = &[
pub const SEED_CLEAR: &[Field] = &[json("edges", "Edges").help("The edges to clear, as JSON; every seed when empty.").hint("every seed")];
pub const DELAUNAY_POINTS: &[Field] = &[json("points", "Points").help("The points to triangulate, as JSON.").req().hint("[[x, y, z], …]")];
pub const DELAUNAY_POINTS: &[Field] = &[points("points", "Points", D::Length, 20_000).help("The points to triangulate.").req()];
pub const TAG: &[Field] = &[
group(
@@ -1229,10 +1339,10 @@ pub const TAG: &[Field] = &[
)
.help("The geometry the mesh entities are tagged with.")
.req(),
json("elements", "Elements").help("Element labels, as JSON."),
labels("elements", "Elements", LabelOf::Element).help("Element labels."),
json("faces", "Element faces").help("Element faces, as JSON."),
json("edges", "Element edges").help("Element edges, as JSON."),
json("nodes", "Nodes").help("Node labels, as JSON."),
labels("nodes", "Nodes", LabelOf::Node).help("Node labels."),
];
// ---- Geometry and files ----
@@ -1277,6 +1387,25 @@ pub const DATUM_PLANE: &[Field] = &[
xyz("normal", "Normal", D::None).help("The plane's normal direction.").req(),
],
),
variant(
"datum_points",
"Three datum points",
&[
reference("a", "Point A", C::DatumPoint).help("First datum point.").req(),
reference("b", "Point B", C::DatumPoint).help("Second datum point.").req(),
reference("c", "Point C", C::DatumPoint).help("Third datum point.").req(),
],
),
variant(
"normal_to_axis",
"Normal to an axis",
&[
reference("axis", "Axis", C::DatumAxis).help("The datum axis the plane is normal to.").req(),
reference("point", "Through", C::DatumPoint)
.help("A datum point on the plane; the axis's own point when empty.")
.hint("the axis's point"),
],
),
],
)
.help("How the plane is defined.")
@@ -1313,13 +1442,123 @@ pub const DATUM_AXIS: &[Field] = &[
xyz("direction", "Direction", D::None).help("The axis direction.").req(),
],
),
variant(
"datum_points",
"Two datum points",
&[
reference("a", "Point A", C::DatumPoint).help("First datum point on the axis.").req(),
reference("b", "Point B", C::DatumPoint).help("Second datum point on the axis.").req(),
],
),
],
)
.help("How the axis is defined.")
.req()
.def(r#"{"type": "principal"}"#),
];
pub const DATUM_DELETE: &[Field] = existing!("Datum", C::Datum);
pub const RIGID_WALL: &[Field] = &[
reference("step", "Step", C::Step)
.help("The explicit dynamics step the wall acts in; the model's only one when empty.")
.hint("the explicit step"),
reference("set", "Set", C::Set).help("The nodes the wall stops: pick them and Use selection.").req(),
xyz("point", "Point", D::Length).help("A point on the wall.").req().def("[0, 0, 0]"),
xyz("normal", "Normal", D::None).help("The wall's normal, pointing to the side the nodes stay on.").req().def("[0, 0, 1]"),
FRICTION,
];
pub const RIGID_WALL_DELETE: &[Field] = &[
reference("step", "Step", C::Step).help("The explicit dynamics step.").req(),
int("index", "Wall", 0, MAX_ROWS as i64).help("The wall's place in the step's rigid walls, from 0.").req(),
];
pub const CENTRE: &[Field] = &[
rows(
"geometry",
"Geometry",
&[
reference("body", "Body", C::Body).help("A body of the open design.").req(),
text("face", "Face").help("A persistent face name of the body."),
text("edge", "Edge").help("A persistent edge name of the body."),
text("vertex", "Vertex").help("A persistent vertex name of the body."),
],
)
.help("Faces or edges (a hole's faces or rim give its centre), or one vertex."),
labels("nodes", "Nodes", LabelOf::Node).help("Mesh node labels: their mean.").hint("labels: 1, 2, 10-20"),
];
pub const DATUM_POINT: &[Field] = &[
NAME,
variants(
"by",
"Definition",
&[
variant("coordinates", "Coordinates", &[xyz("point", "Point", POINT).help("The point's coordinates.").req()]),
variant(
"vertex",
"Vertex",
&[
reference("body", "Body", C::Body).help("The body the vertex belongs to.").req(),
text("vertex", "Vertex")
.help("The vertex's persistent name: pick it with Select: Vertices and Use selection (geometry.bodies lists every body's vertices).")
.req(),
],
),
variant(
"edge",
"On an edge",
&[
reference("body", "Body", C::Body).help("The body the edge belongs to.").req(),
text("edge", "Edge").help("The edge's persistent name.").req(),
range("fraction", "Fraction", D::None, 0.0, 1.0).help("How far along the edge from its start: 0.5 is its midpoint.").def("0.5"),
],
),
variant(
"face_centre",
"Face centre",
&[
reference("body", "Body", C::Body).help("The body the face belongs to.").req(),
text("face", "Face").help("The face's persistent name.").req(),
],
),
variant(
"axis_plane",
"Axis and plane",
&[
reference("axis", "Axis", C::DatumAxis).help("The datum axis.").req(),
reference("plane", "Plane", C::DatumPlane).help("The datum plane the axis crosses.").req(),
],
),
],
)
.help("How the point is defined.")
.req()
.def(r#"{"type": "coordinates"}"#),
];
pub const VIEW_ITEMS: &[Field] = &[rows(
"items",
"Items",
&[
choice(
"kind",
"Kind",
&[
("body", "Body"),
("surface", "Surface"),
("datum", "Datum"),
("boundary_condition", "Boundary condition"),
("load", "Load"),
("reference_point", "Reference point"),
("coupling", "Coupling"),
],
)
.help("What kind of item it is.")
.req(),
text("name", "Name").help("The item's name.").req(),
],
)
.help("The viewport items.")
.req()];
pub const DATUM_DELETE: &[Field] = &[
reference("name", "Datum", C::Datum).req().help("The Datum to act on, by name."),
flag("cascade", "Delete its partitions").help("Also delete the partitions that cut by it; without it, a datum in use is refused."),
];
pub const PARTITION: &[Field] = &[
NAME,
reference("datum", "Datum plane", C::DatumPlane).help("The plane that divides the bodies.").req(),
@@ -1333,6 +1572,28 @@ pub const FILE_SAVE: &[Field] = &[path("path", "File", true).help("Where to save
pub const FILE_SAVE_AS: &[Field] = &[path("path", "File", true).help("The file to save to.").req()];
pub const RECOVERY_LIST: &[Field] =
&[path("dir", "Folder", false).help("The recovery folder; the default one when empty.").hint("the recovery folder")];
pub const CRASH_REPORTS: &[Field] = &[
int("limit", "Limit", 1, 1000).help("At most this many reports, newest first.").hint("20"),
path("dir", "Folder", false).help("The crash folder; the default one when empty.").hint("the crash folder"),
];
pub const CRASH_REPORT: &[Field] = &[
text("id", "Report").help("The crash report to show.").req(),
path("dir", "Folder", false).help("The crash folder; the default one when empty.").hint("the crash folder"),
];
pub const CRASH_REPORTS_DELETE: &[Field] = &[
text("id", "Report").help("The crash report to delete.").hint("or All"),
flag("all", "All").help("Delete every crash report instead of one."),
path("dir", "Folder", false).help("The crash folder; the default one when empty.").hint("the crash folder"),
];
pub const BUG_REPORT: &[Field] = &[
text("title", "Title").help("The issue's title; one is made up when empty."),
text("observed", "What happened").help("What went wrong; the last error when empty."),
text("crash", "Crash report").help("A crash report to report (its id)."),
flag("share_session", "Share my session").help("Attach the commands that built the model (they can name your files).").def("false"),
flag("include_model", "Include the model").help("Attach the model file too (with Share my session).").def("false"),
];
pub const CRASH_TEST: &[Field] =
&[choice("mode", "Mode", &[("panic", "Panic"), ("recovered", "Recovered panic"), ("abort", "Abort")]).help("How to crash.").req()];
pub const RECOVER: &[Field] = &[
text("id", "Autosave").help("The autosave to recover.").req(),
path("dir", "Folder", false).help("The recovery folder; the default one when empty.").hint("the recovery folder"),
@@ -1349,6 +1610,7 @@ pub const SAMPLE: &[Field] = &[choice(
("cantilever", "Cantilever"),
("impact", "Impact"),
("parts", "Parts"),
("ibeam", "I-beam cantilever"),
("drop-test", "Drop test"),
("rubber-seal", "Rubber seal"),
("flow-past", "Flow past a bracket"),
@@ -1377,8 +1639,9 @@ pub const DECK: &[Field] = &[
const STEP: Field = reference("step", "Step", C::Step).help("The step to solve; the only one when empty.").hint("the only one");
const SOLVED: Field = reference("step", "Step", C::SolvedStep).help("The solved step; the step shown when empty.").hint("the step shown");
const MAX_DOFS: Field = int("max_dofs", "Max DOFs", 1, 6_000_000).help("Cap on the degrees of freedom solved.").hint("6000000");
const MAX_FACTOR: Field =
int("max_factor_entries", "Max factor entries", 1, 400_000_000).help("Cap on the factorised matrix size, which bounds memory.").hint("400000000");
const MAX_FACTOR: Field = int("max_factor_entries", "Max factor entries", 1, super::solve::FACTOR_ENTRY_CEILING as i64)
.help("Cap on factor entries (8 bytes each): 400M by default; raise deliberately up to 2B (16 GB of values alone). Indices, workspace and other solver storage need additional memory.")
.hint("400000000");
const THREADS: Field = int("threads", "Threads", 1, 256).help("Threads to use; the session's setting when empty.").hint("the session's");
pub const SOLVE_STATIC: &[Field] = &[STEP, MAX_DOFS, MAX_FACTOR, THREADS];
@@ -1421,13 +1684,13 @@ pub const SOLVE_FLUID: &[Field] = &[
];
pub const SOLVE_PROBE: &[Field] = &[
SOLVED.req(),
json("nodes", "Nodes").help("Node labels to read, as JSON.").hint("[labels]"),
labels("nodes", "Nodes", LabelOf::Node).help("Node labels to read.").hint("labels: 1, 2, 10-20"),
reference("set", "Set", C::Set).help("A set whose nodes to read."),
json("at", "Points").help("Points to read at the nearest nodes, as JSON.").hint("[[x, y, z], …]: nearest nodes"),
points("at", "Points", D::Length, 10_000).help("Points to read at the nearest nodes."),
int("mode", "Mode", 1, 1_000_000).help("The mode to read, for frequency and buckling steps."),
int("frame", "Frame", 0, 1_000_000_000).help("The frame to read, for explicit and transient steps."),
flag("elements", "Element results").help("Also read element results (stresses) around the nodes."),
json("points", "Fluid points").help("Points in the fluid to read, as JSON.").hint("[[x, y, z], …]"),
points("points", "Fluid points", D::Length, 10_000).help("Points in the fluid to read."),
json("forces", "Fluid walls").help("Walls whose fluid forces to sum, as JSON.").hint("[\"x_min\", \"F2:top\"]"),
];
@@ -1436,7 +1699,7 @@ pub const SOLVE_PROBE: &[Field] = &[
pub const DEFORMED: &[Field] = &[
SOLVED,
flag("show", "Show").help("Show the deformed shape.").def("true"),
json("scale", "Scale").help("Displacement magnification: auto, or a factor (1 is true scale).").def("\"auto\"").hint("\"auto\" or a factor"),
number_or_auto("scale", "Scale", D::None, Some(0.0)).help("Displacement magnification: auto, or a factor (1 is true scale).").def("\"auto\""),
];
pub const CONTOUR: &[Field] = &[
SOLVED,
@@ -1470,6 +1733,15 @@ pub const CONTOUR: &[Field] = &[
.req()
.def("\"von_mises\""),
int("bands", "Bands", 2, 24).help("Number of colour bands.").def("12"),
group(
"range",
"Legend range",
&[
num("min", "Min", D::None).help("Values below it take the lowest colour.").hint("the field's minimum"),
num("max", "Max", D::None).help("Values above it are drawn in the over colour.").hint("the field's maximum"),
],
)
.help("Clamp the legend, e.g. below a singular peak; empty follows the field."),
];
pub const MODES: &[Field] = &[SOLVED, int("mode", "Mode", 1, 1_000_000).help("The mode shape shown.").def("1")];
pub const ANIMATE: &[Field] = &[flag("on", "Animate").help("Play the deformation or the frames.").def("true")];
@@ -1478,6 +1750,18 @@ pub const FRAME: &[Field] = &[
int("frame", "Frame", 0, 1_000_000_000).help("The frame shown."),
positive("time", "Time", D::Time).help("Show the frame nearest this time; the last when empty.").hint("the last frame"),
];
pub const EXPORT_CSV: &[Field] = &[
choice("what", "Export", &[("reactions", "Reaction sums"), ("probe", "Probed nodes")]).help("What to write.").req().def("\"reactions\""),
path("path", "File", true).help("The CSV file to write.").req(),
SOLVED,
references("sets", "Sets", C::Set).help("Reactions: the sets to sum; the step's BC sets when empty.").hint("the step's BC sets"),
xyz("about", "About point", D::Length).help("Reactions: the point moments are taken about."),
labels("nodes", "Nodes", LabelOf::Node).help("Probe: the node labels."),
reference("set", "Set", C::Set).help("Probe: a set whose nodes to read."),
points("at", "Points", D::Length, 10_000).help("Probe: points to read at the nearest nodes."),
int("mode", "Mode", 1, 1_000_000).help("Probe: the mode to read, for frequency and buckling steps."),
int("frame", "Frame", 0, 1_000_000_000).help("Probe: the frame to read, for explicit and transient steps."),
];
pub const REACTIONS: &[Field] = &[
SOLVED,
references("sets", "Sets", C::Set)
@@ -1597,7 +1881,18 @@ mod tests {
}
}
const STATE: &[&str] = &["open a design first", "`boundary_conditions` or `loads`", "give one of", "is not an explicit", "has a result"];
const STATE: &[&str] = &[
"open a design first",
"update checks are off",
"`boundary_conditions` or `loads`",
"give one of",
"is not an explicit",
"has no explicit dynamics step",
"has a result",
"no crash report",
"FIELDCRAFT_CRASH_TEST",
"no relaxation field",
];
/// Fill top-level required names (a fresh one) and references (the first existing item).
fn fill_required(s: &Session, form: &[Field], p: &mut Value) {
+265 -3
View File
@@ -16,7 +16,7 @@ use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const OPEN: CommandSpec = CommandSpec {
id: "geometry.open",
label: "Open Design",
params: r#"{"path": "part.solidcraft", "model"?: "keep"} — rebuilds the SolidCraft design and makes its bodies the geometry. `model`: "keep" (default) keeps the mesh and every definition, so opening the same design again after an edit picks up the change and sets follow their persistent face names; "new" starts a new model with the design (no mesh, sets, materials, sections, BCs, loads or steps; the unit system stays; the model is untitled until saved, and undo restores the previous file). The reply's `related` is false when the model (before the open) refers to bodies (mesh tags, set geometry) and the design has none of them, and `stale` lists what no longer resolves: `mesh_bodies` (bodies the mesh is tagged with that the design lacks) `sets` (sets naming a body or face it lacks) and `seeds` (edge seeds on edges it lacks). One undo step"#,
params: r#"{"path": "part.solidcraft", "model"?: "keep"} — rebuilds the SolidCraft design and makes its bodies the geometry. `model`: "keep" (default) keeps the mesh and every definition, so opening the same design again after an edit picks up the change and sets follow their persistent face names; "new" starts a new model with the design (no mesh, sets, materials, sections, BCs, loads or steps; the unit system stays; the model is untitled until saved, and undo restores the previous file). The reply's `related` is false when the model (before the open) refers to bodies (mesh tags, set geometry) and the design has none of them, and `stale` lists what no longer resolves: `mesh_bodies` (bodies the mesh is tagged with that the design lacks) `sets` (sets naming a body or face it lacks) and `seeds` (edge seeds on edges it lacks). `errors` lists the features that failed to rebuild with the `bodies` each may change, and `warnings` says so in one line each. One undo step"#,
form: Some(super::forms::OPEN_DESIGN),
kind: CommandKind::Model,
requires: &[],
@@ -26,13 +26,23 @@ pub const OPEN: CommandSpec = CommandSpec {
pub const BODIES: CommandSpec = CommandSpec {
id: "geometry.bodies",
label: "Bodies",
params: "{} — the open design's bodies: measures, persistent face names (by face index) and edges (persistent name `<face>|<face>`, `~k` when several separate the same faces, and length)",
params: "{} — the open design's bodies: measures, persistent face names (by face index) and edges (persistent name `<face>|<face>`, `~k` when several separate the same faces, and length) and vertices (persistent name `<face>|<face>|<face>` after the faces that meet there, `~k` when several touch the same faces, and point)",
form: Some(&[]),
kind: CommandKind::Model,
requires: &[], // No design is an answer too: no bodies.
run: bodies,
};
pub const CENTRE: CommandSpec = CommandSpec {
id: "geometry.centre",
label: "Centre of Selection",
params: r#"{"geometry": [{"body": "Body1", "face": "F3:hole"} | {"body", "edge"} | {"body", "vertex"}], "nodes": [labels]} — the point a reference point or datum point goes at for what is picked: a vertex's point; the mean of nodes; the centre of a hole (cylindrical faces on one axis, or circular edges on one circle: the axis point at their mid-depth, the circle's centre); otherwise the area centroid of the faces and the length centroid of the edges. Replies `point` and `from` (`vertex`, `nodes`, `circle`, `centroid`)"#,
form: Some(super::forms::CENTRE),
kind: CommandKind::Model,
requires: &[],
run: centre,
};
pub const TESSELLATE: CommandSpec = CommandSpec {
id: "geometry.tessellate",
label: "Tessellate Body",
@@ -86,7 +96,9 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
let out = json!({
"name": design.name,
"bodies": design.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
"errors": design.errors.iter().map(|e| json!({"feature": e.feature, "message": e.message})).collect::<Vec<_>>(),
"errors": design.errors.iter().map(|e| json!({"feature": e.feature, "message": e.message, "bodies": e.bodies})).collect::<Vec<_>>(),
// Shown with the open: a body that differs from the design is never silent.
"warnings": design.errors.iter().map(|e| e.warning()).collect::<Vec<_>>(),
"model": if new_model { "new" } else { "kept" },
"related": fit.related,
"stale": {"mesh_bodies": fit.mesh_bodies, "sets": fit.sets, "seeds": fit.seeds},
@@ -143,6 +155,7 @@ fn bodies(s: &mut Session, _: &Value) -> Result<Value> {
for b in &design.bodies {
let m = b.measure()?;
let edges: Vec<Value> = b.edges()?.iter().map(|e| json!({"name": e.name, "length": e.length()})).collect();
let vertices: Vec<Value> = b.vertices()?.iter().map(|v| json!({"name": v.name, "point": v.point})).collect();
out.push(json!({
"name": b.name,
"volume": m.volume,
@@ -151,11 +164,193 @@ fn bodies(s: &mut Session, _: &Value) -> Result<Value> {
"bbox": [m.bbox_min, m.bbox_max],
"faces": b.faces().iter().map(|f| json!({"name": f.name, "exact": f.exact})).collect::<Vec<_>>(),
"edges": edges,
"vertices": vertices,
}));
}
Ok(Value::Array(out))
}
/// Most geometry items and nodes `geometry.centre` takes.
const MAX_CENTRE_ITEMS: usize = 10_000;
fn add3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
fn sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn scale3(a: [f64; 3], k: f64) -> [f64; 3] {
a.map(|v| v * k)
}
fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
/// The centre of the circle through three points, `None` when they lie on a line.
fn circumcentre(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Option<[f64; 3]> {
let (u, v) = (sub3(b, a), sub3(c, a));
let n = cross3(u, v);
let nn = dot3(n, n);
if !(nn > 1e-24 * dot3(u, u) * dot3(v, v)) {
return None;
}
let k = add3(scale3(cross3(n, u), dot3(v, v)), scale3(cross3(v, n), dot3(u, u)));
Some(add3(a, scale3(k, 0.5 / nn)))
}
/// The centre of an edge's polyline when it is an arc or circle (every point at one distance
/// from it, within a thousandth), else `None`.
fn circle_centre(points: &[[f64; 3]]) -> Option<[f64; 3]> {
let n = points.len();
if n < 3 {
return None;
}
let closed = points.first().zip(points.last()).is_some_and(|(a, b)| dot3(sub3(*a, *b), sub3(*a, *b)) < 1e-18);
let pick = |f: f64| points.get(((n - 1) as f64 * f).round() as usize).copied();
let (a, b, c) = if closed { (pick(0.0)?, pick(1.0 / 3.0)?, pick(2.0 / 3.0)?) } else { (pick(0.0)?, pick(0.5)?, pick(1.0)?) };
let centre = circumcentre(a, b, c)?;
let r = dot3(sub3(a, centre), sub3(a, centre)).sqrt();
let on = points.iter().all(|p| (dot3(sub3(*p, centre), sub3(*p, centre)).sqrt() - r).abs() <= 1e-3 * r);
on.then_some(centre)
}
/// The length-weighted centre of a polyline and its length.
fn polyline_centroid(points: &[[f64; 3]]) -> ([f64; 3], f64) {
let (mut sum, mut length) = ([0.0; 3], 0.0);
for w in points.windows(2) {
let l = dot3(sub3(w[1], w[0]), sub3(w[1], w[0])).sqrt();
sum = add3(sum, scale3(add3(w[0], w[1]), 0.5 * l));
length += l;
}
(if length > 0.0 { scale3(sum, 1.0 / length) } else { points.first().copied().unwrap_or_default() }, length)
}
fn centre(s: &mut Session, p: &Value) -> Result<Value> {
let geometry: Vec<GeometryRef> = super::opt(p, "geometry")?.unwrap_or_default();
let nodes: Vec<u32> = super::opt(p, "nodes")?.unwrap_or_default();
if geometry.len() + nodes.len() > MAX_CENTRE_ITEMS {
return Err(EngineError::Params(format!("geometry.centre takes at most {MAX_CENTRE_ITEMS} items")));
}
if geometry.is_empty() && nodes.is_empty() {
return Err(EngineError::Params("give one of `geometry` or `nodes`: what to find the centre of".into()));
}
if !geometry.is_empty() && !nodes.is_empty() {
return Err(EngineError::Params("give either `geometry` or `nodes`, not both".into()));
}
if !nodes.is_empty() {
let mut sum = [0.0; 3];
for n in &nodes {
let node = s.model.node(*n).ok_or_else(|| EngineError::Params(format!("no node {n}")))?;
sum = add3(sum, node.xyz);
}
return Ok(json!({"point": scale3(sum, 1.0 / nodes.len() as f64), "from": "nodes"}));
}
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
let shape = |b: &str| design.body(b).ok_or_else(|| EngineError::Params(format!("the design has no body `{b}`")));
if let [g] = geometry.as_slice()
&& let Entity::Vertex(v) = &g.entity
{
let vertex = shape(&g.body)?.vertices()?.into_iter().find(|x| &x.name == v);
let vertex = vertex.ok_or_else(|| EngineError::Params(format!("body `{}` has no vertex `{v}`", g.body)))?;
return Ok(json!({"point": vertex.point, "from": "vertex"}));
}
// Hole centres: every face a cylinder about one axis, or every edge an arc of one circle.
let mut circles: Vec<[f64; 3]> = Vec::new();
let mut axis: Option<([f64; 3], [f64; 3])> = None;
let mut round = true;
// Centroids, weighted by area (faces) or length (edges).
let (mut faces_sum, mut faces_area, mut edges_sum, mut edges_length) = ([0.0; 3], 0.0, [0.0; 3], 0.0);
for g in &geometry {
let body = shape(&g.body)?;
match &g.entity {
Entity::Face(f) => {
let i = body.face_index(f).ok_or_else(|| EngineError::Params(format!("body `{}` has no face `{f}`", g.body)))?;
let c = body.face_centre(f)?;
let mesh = body.tessellate((body.size()? * fieldcraft_geometry::EDGE_TOLERANCE).max(1e-4))?;
let area: f64 = mesh
.triangles
.iter()
.zip(&mesh.tri_face)
.filter(|(_, t)| **t == i)
.filter_map(|(t, _)| {
let q = |k: usize| mesh.positions.get(t[k] as usize).copied();
let (a, b, c) = (q(0)?, q(1)?, q(2)?);
let n = cross3(sub3(b, a), sub3(c, a));
Some(0.5 * dot3(n, n).sqrt())
})
.sum();
faces_sum = add3(faces_sum, scale3(c, area));
faces_area += area;
match body.face_surfaces()?.get(i as usize).copied().flatten() {
Some(fieldcraft_geometry::FaceSurface::Cylinder { origin, axis: d, .. }) => {
let len = dot3(d, d).sqrt();
let d = scale3(d, 1.0 / len.max(1e-300));
// The face centre's foot on the axis.
let foot = add3(origin, scale3(d, dot3(sub3(c, origin), d)));
let same = axis.is_none_or(|(o, a)| {
let off = sub3(foot, o);
let across = sub3(off, scale3(a, dot3(off, a)));
dot3(cross3(a, d), cross3(a, d)) < 1e-12 && dot3(across, across).sqrt() <= 1e-6 * body.size().unwrap_or(1.0).max(1e-9)
});
round &= same;
axis.get_or_insert((foot, d));
circles.push(foot);
}
_ => round = false,
}
}
Entity::Edge(e) => {
let edges = body.edges()?;
let edge = edges.iter().find(|x| &x.name == e).ok_or_else(|| EngineError::Params(format!("body `{}` has no edge `{e}`", g.body)))?;
let (c, l) = polyline_centroid(&edge.points);
edges_sum = add3(edges_sum, scale3(c, l));
edges_length += l;
match circle_centre(&edge.points) {
Some(c) => circles.push(c),
None => round = false,
}
}
Entity::Vertex(_) | Entity::Body => {
return Err(EngineError::Params("geometry.centre takes one vertex, or faces and edges".into()));
}
}
}
// Arcs of one circle share a centre; faces of one axis were checked as they came.
let spread = circles.iter().map(|c| circles.first().map_or(0.0, |f| dot3(sub3(*c, *f), sub3(*c, *f)).sqrt())).fold(0.0f64, f64::max);
let size = geometry.first().and_then(|g| design.body(&g.body)).and_then(|b| b.size().ok()).unwrap_or(1.0).max(1e-9);
let edges_only = geometry.iter().all(|g| matches!(g.entity, Entity::Edge(_)));
if round && !circles.is_empty() && (!edges_only || spread <= 1e-6 * size) {
let point = match axis {
// Cylinder faces: the axis point at the mean of their centres' feet.
Some((_, d)) => {
let mean = scale3(circles.iter().fold([0.0; 3], |a, c| add3(a, *c)), 1.0 / circles.len() as f64);
let o = circles.first().copied().unwrap_or(mean);
add3(o, scale3(d, dot3(sub3(mean, o), d)))
}
None => circles.first().copied().unwrap_or_default(),
};
return Ok(json!({"point": point, "from": "circle"}));
}
let point = if faces_area > 0.0 {
scale3(faces_sum, 1.0 / faces_area)
} else if edges_length > 0.0 {
scale3(edges_sum, 1.0 / edges_length)
} else {
return Err(EngineError::Params("what is picked has no area or length to find a centre of".into()));
};
if !point.iter().all(|v| v.is_finite()) {
return Err(EngineError::Params("the centre is not a finite point".into()));
}
Ok(json!({"point": point, "from": "centroid"}))
}
fn body<'a>(s: &'a Session, p: &Value) -> Result<&'a Shape> {
let name = p.get("body").and_then(Value::as_str).ok_or_else(|| EngineError::param("body", ProblemKind::NotAName))?;
s.design.as_deref().and_then(|d| d.body(name)).ok_or_else(|| EngineError::Params(format!("no body `{name}` (open a design first)")))
@@ -212,6 +407,73 @@ mod tests {
zip.finish().unwrap().into_inner()
}
/// The plate's hole (Ø10 at x = y = 15 through z 0..10): its faces give the axis point at
/// mid-depth, a rim arc its circle's centre, a corner vertex its point, a flat face its
/// centroid; datum points take the design's vertices by name.
#[test]
fn centres_of_holes_vertices_and_faces() {
use fieldcraft_geometry::FaceSurface;
use fieldcraft_geometry::sample::{Plate, plate_design};
let design = Arc::new(open_design(&plate_design(&Plate::default()).unwrap()).unwrap());
let mut s = Session { design: Some(design.clone()), ..Session::default() };
let body = &design.bodies[0];
let near = |v: &Value, p: [f64; 3]| {
let q: [f64; 3] = serde_json::from_value(v["point"].clone()).unwrap();
assert!((0..3).all(|k| (q[k] - p[k]).abs() < 1e-6), "{v} vs {p:?}");
};
let surfaces = body.face_surfaces().unwrap();
let hole: Vec<Value> = body
.faces()
.iter()
.zip(&surfaces)
.filter(|(_, s)| matches!(s, Some(FaceSurface::Cylinder { .. })))
.map(|(f, _)| json!({"body": body.name, "face": f.name}))
.collect();
assert_eq!(hole.len(), 2);
let r = s.execute("geometry.centre", &json!({"geometry": hole})).unwrap();
near(&r, [15.0, 15.0, 5.0]);
assert_eq!(r["from"], "circle");
let r = s.execute("geometry.centre", &json!({"geometry": [hole[0]]})).unwrap();
near(&r, [15.0, 15.0, 5.0]);
// A rim arc on top.
let edges = body.edges().unwrap();
let arc = edges.iter().find(|e| e.points.iter().all(|p| (p[2] - 10.0).abs() < 1e-9) && e.points.len() > 3).unwrap();
let r = s.execute("geometry.centre", &json!({"geometry": [{"body": body.name, "edge": arc.name}]})).unwrap();
near(&r, [15.0, 15.0, 10.0]);
assert_eq!(r["from"], "circle");
// The corner at the origin, and a datum point on it by name.
let corner = body.vertices().unwrap().into_iter().find(|v| v.point == [0.0; 3]).unwrap();
let r = s.execute("geometry.centre", &json!({"geometry": [{"body": body.name, "vertex": corner.name}]})).unwrap();
near(&r, [0.0; 3]);
s.execute("geometry.datum.point", &json!({"name": "P", "by": {"type": "vertex", "body": body.name, "vertex": corner.name}})).unwrap();
assert_eq!(s.model.datum("P").and_then(|d| d.point()), Some([0.0; 3]));
let listed = s.execute("geometry.bodies", &json!({})).unwrap();
assert!(listed[0]["vertices"].as_array().unwrap().iter().any(|v| v["name"] == corner.name.as_str()), "{listed}");
// The bottom face (z = 0): its centroid, off the hole.
let bottom = body
.faces()
.iter()
.zip(&surfaces)
.find(|(_, s)| matches!(s, Some(FaceSurface::Plane { normal, point }) if normal[2].abs() > 0.99 && point[2].abs() < 1e-9))
.unwrap()
.0;
let r = s.execute("geometry.centre", &json!({"geometry": [{"body": body.name, "face": bottom.name}]})).unwrap();
assert_eq!(r["from"], "centroid");
// Nodes, and what is refused.
s.model.set_node(1, [1.0, 2.0, 3.0]).unwrap();
s.model.set_node(2, [3.0, 2.0, 1.0]).unwrap();
near(&s.execute("geometry.centre", &json!({"nodes": [1, 2]})).unwrap(), [2.0, 2.0, 2.0]);
for bad in [
json!({}),
json!({"nodes": [99]}),
json!({"geometry": [{"body": "nope"}]}),
json!({"geometry": [{"body": body.name}]}),
json!({"nodes": "x"}),
] {
assert!(s.execute("geometry.centre", &bad).is_err(), "{bad}");
}
}
#[test]
fn import_adds_tagged_surfaces_and_failures_change_nothing() {
let dir = std::env::temp_dir().join(format!("fieldcraft-import-mesh-{}", std::process::id()));
+31 -20
View File
@@ -16,7 +16,7 @@ use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const HEX_GENERATE: CommandSpec = CommandSpec {
id: "mesh.hex.generate",
label: "Hex Mesh",
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the meshes of the bodies it meshes (as mesh.tet.generate; other bodies keep theirs) with structured hexahedra: multi-level sweeps along a direction or around an axis, one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Edge seeds (mesh.seed.edge) set the counts and spacing of their edges: exact seeds are held, and seeds that cannot all hold (opposite sides of a mapped face, the layers between two levels) are an error naming them. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the meshes of the bodies it meshes (as mesh.tet.generate; other bodies keep theirs) with structured hexahedra: multi-level sweeps along a direction or around an axis (their cross-section cut into mappable blocks automatically: O-grids round holes, triangle primitives, four-sided blocks; nothing is added to the model), one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Edge seeds (mesh.seed.edge) set the counts and spacing of their edges: exact seeds are held, and seeds that cannot all hold (opposite sides of a mapped face, the layers between two levels) are an error naming them. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
form: Some(super::forms::HEX_GENERATE),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
@@ -220,27 +220,15 @@ pub(super) fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
seeds: super::seeds::edge_seeds(s)?,
..HexOptions::default()
};
let cm = hex_mesh_cells(&cells, &UniformSize(h), &options).map_err(|e| EngineError::Params(e.to_string()))?;
let cm = hex_mesh_cells(&cells, &UniformSize(h), &options).map_err(|e| match e {
fieldcraft_mesh::Error::Model(fieldcraft_model::Error::Cancelled) => EngineError::Model(fieldcraft_model::Error::Cancelled),
e => EngineError::Params(e.to_string()),
})?;
let m = &cm.mesh;
// Replace the cells' meshes (replace.rs); other bodies and the definitions stay.
let model = &mut s.model;
let cleared = super::replace::clear(model, inputs.iter().map(|b| b.name.as_str()));
let (first_node, first_element) = super::fresh_labels(model, m.nodes.len(), m.element_count())?;
for (i, xyz) in m.nodes.iter().enumerate() {
model.set_node(first_node + i as u32, *xyz)?;
}
let mut body_tags = Vec::with_capacity(inputs.len());
for b in &inputs {
body_tags.push(model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?);
}
for e in 0..m.element_count() {
let cell = cm.element_cell.get(e).map_or(0, |&c| c as usize);
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
let l = first_element + e as u32;
model.set_element(l, m.kind, nodes)?;
model.tag_element(l, body_tags.get(cell).copied().ok_or_else(|| EngineError::Params("element without a cell".into()))?)?;
}
tag_faces(model, &inputs, |e| cm.element_cell.get(e as usize).map_or(0, |&c| c as usize), &m.boundary, first_element)?;
add_cells(model, &inputs, &cm)?;
let blocks: Vec<Value> =
inputs.iter().zip(&cm.blocks).map(|(b, d)| json!({"body": b.name, "divisions": d, "elements": d.iter().product::<usize>()})).collect();
let reply = json!({
@@ -349,7 +337,30 @@ pub(super) fn hex_body(p: &Value, b: &Input, method: HexMethod, quadratic: bool,
seeds: b.seeds.clone(),
..HexOptions::default()
};
hex_mesh(&surface, &b.surfaces, &UniformSize(h), &options).map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))
hex_mesh(&surface, &b.surfaces, &UniformSize(h), &options).map_err(|e| EngineError::of_body(&b.name, e))
}
/// Add a mesh of several cells (`inputs[c]` is cell `c`) after the model's largest labels, its
/// nodes shared between the cells, tagging each element with its cell's body and the boundary
/// element faces with the cell's B-rep faces.
pub(super) fn add_cells(model: &mut Model, inputs: &[Input], cm: &fieldcraft_mesh::hex::CellsMesh) -> Result<()> {
let m = &cm.mesh;
let (first_node, first_element) = super::fresh_labels(model, m.nodes.len(), m.element_count())?;
for (i, xyz) in m.nodes.iter().enumerate() {
model.set_node(first_node + i as u32, *xyz)?;
}
let mut body_tags = Vec::with_capacity(inputs.len());
for b in inputs {
body_tags.push(model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?);
}
for e in 0..m.element_count() {
let cell = cm.element_cell.get(e).map_or(0, |&c| c as usize);
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
let l = first_element + e as u32;
model.set_element(l, m.kind, nodes)?;
model.tag_element(l, body_tags.get(cell).copied().ok_or_else(|| EngineError::Params("element without a cell".into()))?)?;
}
tag_faces(model, inputs, |e| cm.element_cell.get(e as usize).map_or(0, |&c| c as usize), &m.boundary, first_element)
}
/// Add one body's hex mesh after the model's largest labels, tagging the elements with the body
@@ -523,7 +534,7 @@ mod tests {
let (_dir, mut s) = split_box(true);
let before = s.model.clone();
let e = s.execute("mesh.hex.blocks", &json!({"size": 2.5})).unwrap_err().to_string();
assert!(e.contains("do not conform") && e.contains("`Box`"), "{e}");
assert!(e.contains("do not conform") && e.contains("`Box.1`"), "{e}");
assert_eq!(s.model, before);
for p in [
json!({"size": 0}),
+32 -1
View File
@@ -252,7 +252,9 @@ pub(super) fn mesh_body(
None => s.design.as_deref().and_then(|d| d.body(&input.name)).map(analytic_surfaces).unwrap_or_default(),
Some(_) => Vec::new(),
};
fieldcraft_model::progress::stage(&format!("{}: boundary", input.name), None, "");
let surface = BoundarySurface::new(&input.mesh.positions, &input.mesh.triangles, &input.mesh.tri_face, &surface_options(p, &input.mesh)?)?;
fieldcraft_model::progress::stage(&format!("{}: Delaunay", input.name), None, "");
let tets = tetrahedralize(&surface, cdt)?;
let mesh = if quality {
let options = QualityOptions { seeds: input.seeds.clone(), ..options.clone() };
@@ -269,7 +271,7 @@ pub(super) fn mesh_body(
surface_volume: surface.volume(),
})
};
mesh().map_err(|e| if several { EngineError::Params(format!("body `{}`: {e}", input.name)) } else { e })
mesh().map_err(|e| if several && !e.is_cancelled() { EngineError::Params(format!("body `{}`: {e}", input.name)) } else { e })
}
fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
@@ -894,6 +896,35 @@ mod tests {
assert!(e.starts_with("body `Box"), "{e}");
}
/// Persistent names grow with the design's split history: a tray floor split by joined ribs
/// names every split, past the old 256-character cap. Such a design meshes, and a set on that
/// face resolves by its full name, again after a remesh (#374).
#[test]
fn long_persistent_face_names_mesh_and_resolve() {
let mut commands = vec![
json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0], "body_name": "Case"}}),
json!({"command": "solid.shell", "params": {"faces": [[20, 15, 20]], "thickness": 2, "direction": "inside", "body": "Case"}}),
];
// Ribs across the floor split it into strips, each named by every split before it.
for x in (3..=36).step_by(3) {
commands.push(json!({"command": "solid.box", "params": {"length": 1, "width": 26, "height": 5, "corner": [x, 2, 2], "operation": "join", "targets": ["Case"]}}));
}
let bytes = fieldcraft_geometry::script_design(&json!({"commands": commands}).to_string()).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
let bodies = s.execute("geometry.bodies", &json!({})).unwrap();
let long = bodies[0]["faces"].as_array().unwrap().iter().filter_map(|f| f["name"].as_str()).max_by_key(|n| n.len()).unwrap().to_string();
assert!(long.len() > 256, "the fixture needs a face name past the old cap: {long}");
s.execute("mesh.tet.generate", &json!({"body": "Case"})).unwrap();
s.execute("model.set.create", &json!({"name": "floor", "geometry": [{"body": "Case", "face": long}]})).unwrap();
let first = s.model.resolve_set("floor").unwrap();
assert!(!first.faces.is_empty());
s.execute("mesh.tet.generate", &json!({"body": "Case", "tolerance": 0.5})).unwrap();
let again = s.model.resolve_set("floor").unwrap();
assert!(!again.faces.is_empty(), "the set follows the remesh by the full name");
}
/// The quality report's one-line summary counts the inverted elements.
#[test]
fn quality_summary_counts_invalid_elements() {
+1 -5
View File
@@ -42,11 +42,7 @@ fn not_a_plane() -> EngineError {
/// The plane: a datum plane by name, or a point and a normal.
fn plane(s: &Session, p: &Value) -> Result<([f64; 3], [f64; 3])> {
match p.get("plane") {
Some(Value::String(name)) => s
.model
.datum(name)
.and_then(|d| d.plane())
.ok_or_else(|| EngineError::Params(format!("no datum plane `{}`", name.chars().take(64).collect::<String>()))),
Some(Value::String(name)) => super::datum::datum_plane_of(&s.model, name),
Some(v @ Value::Object(_)) => match (super::xyz(v, "point"), super::xyz(v, "normal")) {
(Ok(point), Ok(normal)) => Ok((point, normal)),
_ => Err(not_a_plane()),
+37
View File
@@ -6,6 +6,7 @@ mod contact;
pub(crate) mod datum;
pub(crate) mod deck;
pub(crate) mod define;
pub mod diagnostics;
mod edit;
pub(crate) mod file;
pub(crate) mod forms;
@@ -13,16 +14,24 @@ mod geometry;
mod hex;
pub(crate) mod mesh;
pub use datum::edit_params as datum_edit_params;
pub use datum::preview as datum_preview;
pub use mesh::analytic_surfaces;
pub use nodes::merge_preview as node_merge_preview;
pub use relax::{Preview as RelaxPreview, preview as relax_preview, sphere as relax_sphere};
mod mirror;
mod model;
pub(crate) mod nodes;
pub(crate) mod octree;
pub(crate) mod relax;
pub mod replace;
mod results;
pub(crate) mod seeds;
pub(crate) mod solve;
mod symmetry;
mod tags;
pub mod update;
pub(crate) mod view;
use crate::schema::ProblemKind;
use fieldcraft_model::MAX_LABEL;
@@ -37,17 +46,29 @@ pub static ALL: &[CommandSpec] = &[
model::INFO,
geometry::OPEN,
geometry::BODIES,
geometry::CENTRE,
geometry::TESSELLATE,
geometry::IMPORT_MESH,
datum::DATUM_PLANE,
datum::DATUM_AXIS,
datum::DATUM_POINT,
datum::DATUM_EDIT,
datum::DATUM_AXIS_EDIT,
datum::DATUM_POINT_EDIT,
datum::DATUM_DELETE,
view::HIDE,
view::SHOW,
view::ISOLATE,
view::SHOW_ALL,
datum::PARTITION,
datum::DATUM_SUPPRESS,
datum::PARTITION_SUPPRESS,
datum::PARTITION_DELETE,
mesh::NODE_ADD,
mesh::NODE_REMOVE,
mesh::ELEMENT_ADD,
mesh::ELEMENT_REMOVE,
replace::CLEAR,
mesh::QUALITY,
mesh::DELAUNAY_POINTS,
mesh::SURFACE_CHECK,
@@ -64,6 +85,11 @@ pub static ALL: &[CommandSpec] = &[
seeds::SEED_CLEAR,
seeds::SEED_LIST,
mirror::MIRROR,
nodes::MERGE,
nodes::DUPLICATES,
nodes::RENUMBER,
relax::RELAX,
relax::APPLY,
tags::TAG,
tags::TAG_CLEAR,
model::UNITS,
@@ -94,6 +120,8 @@ pub static ALL: &[CommandSpec] = &[
contact::TIE,
contact::TIE_EDIT,
contact::TIE_DELETE,
contact::RIGID_WALL,
contact::RIGID_WALL_DELETE,
define::MASS_CREATE,
define::MASS_EDIT,
define::MASS_DELETE,
@@ -115,7 +143,9 @@ pub static ALL: &[CommandSpec] = &[
define::STEP_EDIT,
define::STEP_DELETE,
define::STEP_ACTIVATE,
define::RENAME,
define::ACTIVITY,
file::NEW,
file::OPEN,
file::SAVE,
file::SAVE_AS,
@@ -142,7 +172,14 @@ pub static ALL: &[CommandSpec] = &[
results::ANIMATE,
results::FRAME,
results::REACTIONS,
results::EXPORT_CSV,
results::CLEAR,
diagnostics::CRASH_REPORTS,
diagnostics::CRASH_REPORT,
diagnostics::CRASH_REPORTS_DELETE,
diagnostics::BUG_REPORT,
diagnostics::CRASH_TEST,
update::CHECK,
];
/// The problem with required parameter `key`: [`ProblemKind::Required`] when it is left out,
+15 -1
View File
@@ -55,7 +55,21 @@ fn units(s: &mut Session, p: &Value) -> Result<Value> {
}
fn check(s: &mut Session, _: &Value) -> Result<Value> {
let diagnostics = s.model.check();
let mut diagnostics = s.model.check();
if let Some(design) = s.design.as_deref() {
for (body, n) in super::replace::stale(&s.model, design) {
diagnostics.push(fieldcraft_model::Diagnostic {
severity: Severity::Warning,
subject: format!("body `{body}`"),
message: format!(
"{n} elements mesh a body the open design no longer has (its partitions changed since it was meshed); mesh.clear removes them"
),
});
}
}
if let Some(why) = s.mesh_outdated() {
diagnostics.push(fieldcraft_model::Diagnostic { severity: Severity::Warning, subject: "mesh".into(), message: why });
}
let errors = diagnostics.iter().filter(|d| d.severity == Severity::Error).count();
let first_error = diagnostics.iter().find(|d| d.severity == Severity::Error).map(ToString::to_string);
let progress = crate::progress::to_json(&s.progress_given(first_error));
+385
View File
@@ -0,0 +1,385 @@
//! Node tools (#234): `mesh.node.merge` equivalences coincident nodes, `mesh.check.duplicates`
//! finds what is not merged or does not join (coincident nodes, repeated elements, free faces and
//! edges, cracks), and `mesh.renumber` gives nodes and elements new labels. Merging and
//! renumbering move every reference with the labels (connectivity, sets, geometry tags, a step's
//! displacement limit), so boundary conditions and loads, which act on sets, stay on the same
//! entities; deck writers write the labels as they are. Both are one undo step; results solved
//! before go stale, as after any mesh edit.
use std::collections::{BTreeMap, BTreeSet};
use fieldcraft_mesh::nodes::{Keep, bandwidth, duplicates, merge_plan, reverse_cuthill_mckee};
use fieldcraft_model::geometry::Entity;
use fieldcraft_model::{MAX_LABEL, Model};
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::schema::ProblemKind;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const MERGE: CommandSpec = CommandSpec {
id: "mesh.node.merge",
label: "Merge Nodes",
params: r#"{"tolerance"?: mm (default a millionth of the mesh's bounding-box diagonal), "set"?: "Name" (only the set's nodes and those of its elements and faces), "keep"?: "lowest" (default) | "highest"} — equivalences coincident nodes: every node within the distance of another becomes that one (the lowest or highest label of each group survives, keeping its position) in every element, set and geometry tag, and is removed. A merge that would put two nodes of one element together (collapsing it) is left out and listed under `refused`; the rest are made. Reports `merged`, the `pairs` [node, survivor] (the first 1000) and `refused`"#,
form: Some(super::forms::NODE_MERGE),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: merge,
};
pub const DUPLICATES: CommandSpec = CommandSpec {
id: "mesh.check.duplicates",
label: "Check Duplicates",
params: r#"{"tolerance"?: mm (default a millionth of the mesh's bounding-box diagonal)} — checks the mesh for what was not merged or does not join, changing nothing: `coincident` nodes within the distance of another ([node, other, distance]), `duplicate_elements` (groups on the same nodes), `free_faces` (faces of solid elements no other element shares: the skin), `cracks` (free faces lying on another free face: parts that touch without sharing nodes) and `free_edges` (edges of the skin and of 2D elements on one facet only: open borders). Lists hold the first 1000; `counts` has the totals"#,
form: Some(super::forms::CHECK_DUPLICATES),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: check_duplicates,
};
pub const RENUMBER: CommandSpec = CommandSpec {
id: "mesh.renumber",
label: "Renumber",
params: r#"{"what"?: "both" (default) | "nodes" | "elements", "by"?: "compact" (default: in label order) | "bandwidth" (nodes in reverse Cuthill–McKee order, elements by their lowest new node label) | "body" (body by body, by name; within a body in label order), "start"?: 1, "offset"?: n (instead of `by` and `start`: add n to every label)} — gives nodes and elements new labels from `start` up (or shifted by `offset`), every set, geometry tag and step following, so boundary conditions and loads stay on the same entities and decks write the new labels. Refused, changing nothing, when a label would leave 1..=99999999 or a node would take a reference point's label. Reports the counts renumbered, the label ranges and the bandwidth before and after"#,
form: Some(super::forms::RENUMBER),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: renumber,
};
/// Most items a reply lists.
const MAX_LISTED: usize = 1000;
/// The merge distance: `tolerance`, or a millionth of the mesh's bounding-box diagonal.
pub(crate) fn tolerance(model: &Model, p: &Value) -> Result<f64> {
match p.get("tolerance") {
Some(v) => v.as_f64().filter(|t| *t > 0.0 && t.is_finite()).ok_or_else(|| EngineError::param("tolerance", ProblemKind::NotPositive)),
None => {
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for n in model.nodes().values() {
for k in 0..3 {
lo[k] = lo[k].min(n.xyz[k]);
hi[k] = hi[k].max(n.xyz[k]);
}
}
let diagonal = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::<f64>().sqrt();
Ok(if diagonal > 0.0 && diagonal.is_finite() { 1e-6 * diagonal } else { 1e-9 })
}
}
}
/// The merge's candidates: the nodes of `set` (its own, and those of its elements and faces).
fn candidates(model: &Model, p: &Value) -> Result<Option<BTreeSet<u32>>> {
let Some(name) = super::opt::<String>(p, "set")? else { return Ok(None) };
let set = model.resolve_set(&name)?;
let mut nodes: BTreeSet<u32> = set.nodes.into_iter().collect();
for e in set.elements.iter().chain(set.faces.iter().map(|f| &f.element)) {
if let Some(el) = model.element(*e) {
nodes.extend(el.nodes.iter().copied());
}
}
Ok(Some(nodes))
}
fn keep(p: &Value) -> Result<Keep> {
match super::opt::<String>(p, "keep")?.as_deref() {
None | Some("lowest") => Ok(Keep::Lowest),
Some("highest") => Ok(Keep::Highest),
Some(_) => Err(EngineError::param("keep", ProblemKind::NotAChoice)),
}
}
/// The merges `mesh.node.merge` with `params` would make, as [node, survivor] pairs: what its
/// form previews. `None` when the parameters are not (yet) valid.
pub fn merge_preview(s: &Session, params: &Value) -> Option<Vec<[u32; 2]>> {
let tol = tolerance(&s.model, params).ok()?;
let only = candidates(&s.model, params).ok()?;
let plan = merge_plan(&s.model, only.as_ref(), tol, keep(params).ok()?).ok()?;
Some(plan.map.into_iter().map(|(a, b)| [a, b]).collect())
}
fn merge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = tolerance(&s.model, p)?;
let only = candidates(&s.model, p)?;
let plan = merge_plan(&s.model, only.as_ref(), tol, keep(p)?)?;
if !plan.map.is_empty() {
s.model.merge_nodes(&plan.map)?;
}
let pairs: Vec<[u32; 2]> = plan.map.iter().take(MAX_LISTED).map(|(&a, &b)| [a, b]).collect();
let refused: Vec<Value> =
plan.refused.iter().take(MAX_LISTED).map(|r| json!({"node": r.node, "survivor": r.survivor, "element": r.element})).collect();
let mut summary = format!("merged {} node{} within {tol:.3e}", plan.map.len(), if plan.map.len() == 1 { "" } else { "s" });
if !plan.refused.is_empty() {
summary.push_str(&format!("; {} left apart (they would collapse an element)", plan.refused.len()));
}
Ok(json!({
"merged": plan.map.len(),
"pairs": pairs,
"refused": refused,
"tolerance": tol,
"nodes": s.model.nodes().len(),
"summary": summary,
}))
}
fn check_duplicates(s: &mut Session, p: &Value) -> Result<Value> {
let tol = tolerance(&s.model, p)?;
let d = duplicates(&s.model, tol)?;
let coincident: Vec<Value> = d.coincident.iter().take(MAX_LISTED).map(|&(a, b, dist)| json!([a, b, dist])).collect();
let summary = format!(
"{} coincident node{}, {} duplicate element group{}, {} crack face{}, {} free edge{} ({} free faces)",
d.coincident.len(),
plural(d.coincident.len()),
d.elements.len(),
plural(d.elements.len()),
d.cracks.len(),
plural(d.cracks.len()),
d.free_edges.len(),
plural(d.free_edges.len()),
d.free_faces,
);
Ok(json!({
"tolerance": tol,
"coincident": coincident,
"duplicate_elements": d.elements.iter().take(MAX_LISTED).collect::<Vec<_>>(),
"free_faces": d.free_faces,
"cracks": d.cracks.iter().take(MAX_LISTED).collect::<Vec<_>>(),
"free_edges": d.free_edges.iter().take(MAX_LISTED).collect::<Vec<_>>(),
"counts": {
"coincident": d.coincident.len(),
"duplicate_elements": d.elements.len(),
"cracks": d.cracks.len(),
"free_edges": d.free_edges.len(),
},
"summary": summary,
}))
}
fn plural(n: usize) -> &'static str {
if n == 1 { "" } else { "s" }
}
/// The body name of each element tagged with one.
fn element_bodies(model: &Model) -> BTreeMap<u32, String> {
let c = model.classification();
c.elements()
.iter()
.filter_map(|(&e, t)| {
let r = c.entity(t.region?)?;
(r.entity == Entity::Body).then(|| (e, r.body.clone()))
})
.collect()
}
/// New labels for `order` from `start` up; `None` when they would leave the label range.
fn from_start(order: &[u32], start: u32) -> Option<BTreeMap<u32, u32>> {
order
.iter()
.enumerate()
.map(|(i, &l)| Some((l, start.checked_add(u32::try_from(i).ok()?).filter(|x| *x <= MAX_LABEL)?)))
.filter(|x| x.as_ref().is_none_or(|(a, b)| a != b))
.collect()
}
fn renumber(s: &mut Session, p: &Value) -> Result<Value> {
let (nodes_too, elements_too) = match super::opt::<String>(p, "what")?.as_deref() {
None | Some("both") => (true, true),
Some("nodes") => (true, false),
Some("elements") => (false, true),
Some(_) => return Err(EngineError::param("what", ProblemKind::NotAChoice)),
};
let model = &s.model;
let out_of_range = || EngineError::Params(format!("the new labels would leave 1..={MAX_LABEL}"));
let (node_map, element_map) = if let Some(v) = p.get("offset") {
if p.get("by").is_some() || p.get("start").is_some() {
return Err(EngineError::Params("give `offset`, or `by` and `start`, not both".into()));
}
let offset = v
.as_i64()
.ok_or_else(|| EngineError::param("offset", ProblemKind::NotAWholeNumber { min: -i64::from(MAX_LABEL), max: i64::from(MAX_LABEL) }))?;
let shift = |labels: &mut dyn Iterator<Item = u32>| -> Result<BTreeMap<u32, u32>> {
labels
.filter(|_| offset != 0)
.map(|l| u32::try_from(i64::from(l) + offset).ok().filter(|x| (1..=MAX_LABEL).contains(x)).map(|n| (l, n)).ok_or_else(out_of_range))
.collect()
};
let n = if nodes_too { shift(&mut model.nodes().keys().copied())? } else { BTreeMap::new() };
let e = if elements_too { shift(&mut model.elements().keys().copied())? } else { BTreeMap::new() };
(n, e)
} else {
let start = match p.get("start") {
None => 1,
Some(v) => v
.as_u64()
.and_then(|x| u32::try_from(x).ok())
.filter(|x| (1..=MAX_LABEL).contains(x))
.ok_or_else(|| EngineError::param("start", ProblemKind::NotAWholeNumber { min: 1, max: i64::from(MAX_LABEL) }))?,
};
let (node_order, element_order): (Vec<u32>, Vec<u32>) = match super::opt::<String>(p, "by")?.as_deref() {
None | Some("compact") => (model.nodes().keys().copied().collect(), model.elements().keys().copied().collect()),
Some("bandwidth") => {
let nodes = reverse_cuthill_mckee(model);
let rank: BTreeMap<u32, usize> = nodes.iter().enumerate().map(|(i, &l)| (l, i)).collect();
let mut elements: Vec<(usize, u32)> = model
.elements()
.iter()
.map(|(&l, e)| (e.nodes.iter().filter_map(|n| rank.get(n).copied()).min().unwrap_or(usize::MAX), l))
.collect();
elements.sort_unstable();
(nodes, elements.into_iter().map(|(_, l)| l).collect())
}
Some("body") => {
let bodies = element_bodies(model);
// Elements by body name (untagged last), then label; nodes as their first
// element in that order meets them, then the nodes no element uses.
let mut elements: Vec<(Option<&String>, u32)> = model.elements().keys().map(|&l| (bodies.get(&l), l)).collect();
elements.sort_by(|a, b| (a.0.is_none(), a.0, a.1).cmp(&(b.0.is_none(), b.0, b.1)));
let elements: Vec<u32> = elements.into_iter().map(|(_, l)| l).collect();
let mut seen = BTreeSet::new();
let mut nodes: Vec<u32> = Vec::with_capacity(model.nodes().len());
for e in &elements {
for &n in model.element(*e).map(|x| x.nodes.as_slice()).unwrap_or(&[]) {
if seen.insert(n) {
nodes.push(n);
}
}
}
let mut free: Vec<u32> = model.nodes().keys().copied().filter(|n| !seen.contains(n)).collect();
free.sort_unstable();
nodes.extend(free);
(nodes, elements)
}
Some(_) => return Err(EngineError::param("by", ProblemKind::NotAChoice)),
};
let n = if nodes_too { from_start(&node_order, start).ok_or_else(out_of_range)? } else { BTreeMap::new() };
let e = if elements_too { from_start(&element_order, start).ok_or_else(out_of_range)? } else { BTreeMap::new() };
(n, e)
};
let before = bandwidth(model, &|l| l);
s.model.renumber(&node_map, &element_map)?;
let after = bandwidth(&s.model, &|l| l);
let range = |labels: &mut dyn Iterator<Item = u32>| -> Value {
let (lo, hi) = labels.fold((u32::MAX, 0), |(lo, hi), l| (lo.min(l), hi.max(l)));
if hi == 0 { Value::Null } else { json!([lo, hi]) }
};
Ok(json!({
"nodes": node_map.len(),
"elements": element_map.len(),
"node_labels": range(&mut s.model.nodes().keys().copied()),
"element_labels": range(&mut s.model.elements().keys().copied()),
"bandwidth": [before, after],
"summary": format!("renumbered {} nodes and {} elements; bandwidth {before} → {after}", node_map.len(), element_map.len()),
}))
}
#[cfg(test)]
mod tests {
use super::*;
/// A 2 × 1 × 1 bar of hex8 blocks: whole, or as two halves that do not share their nodes
/// on x = 1.
fn bar(halves: bool) -> Session {
let mut s = Session::default();
let block = |body: &str, x0: f64, x1: f64, n: u32| {
let c = [[x0, 0., 0.], [x1, 0., 0.], [x1, 1., 0.], [x0, 1., 0.], [x0, 0., 1.], [x1, 0., 1.], [x1, 1., 1.], [x0, 1., 1.]];
json!({"body": body, "kind": "hex8", "corners": c, "divisions": [n, 2, 2], "merge": 0})
};
if halves {
s.execute("mesh.block", &block("A", 0.0, 1.0, 2)).unwrap();
s.execute("mesh.block", &block("B", 1.0, 2.0, 2)).unwrap();
} else {
s.execute("mesh.block", &block("A", 0.0, 2.0, 4)).unwrap();
}
s
}
fn positions(s: &Session) -> Vec<[u64; 3]> {
let mut p: Vec<[u64; 3]> = s.model.nodes().values().map(|n| n.xyz.map(|x| (x + 0.0).to_bits())).collect();
p.sort_unstable();
p
}
/// Two halves meshed apart are found coincident and cracked, and merging them gives the
/// whole bar's nodes: no crack left, and undo brings the halves back.
#[test]
fn merging_two_halves_gives_the_whole() {
let whole = bar(false);
let mut s = bar(true);
s.execute(
"model.set.create",
&json!({"name": "seam", "nodes": s.model.nodes().iter().filter(|(_, n)| n.xyz[0] == 1.0).map(|(l, _)| *l).collect::<Vec<_>>()}),
)
.unwrap();
let d = s.execute("mesh.check.duplicates", &json!({})).unwrap();
assert_eq!(d["counts"]["coincident"], 9, "{d}");
assert_eq!(d["counts"]["cracks"], 8, "{d}");
assert_eq!(d["counts"]["free_edges"], 0, "{d}");
assert_eq!(s.model.nodes().len(), whole.model.nodes().len() + 9);
let r = s.execute("mesh.node.merge", &json!({})).unwrap();
assert_eq!(r["merged"], 9, "{r}");
assert_eq!(positions(&s), positions(&whole));
// The seam set keeps its nine positions, on the survivors.
assert_eq!(s.model.set("seam").unwrap().nodes.len(), 9);
let d = s.execute("mesh.check.duplicates", &json!({})).unwrap();
assert_eq!((d["counts"]["coincident"].as_u64(), d["counts"]["cracks"].as_u64()), (Some(0), Some(0)), "{d}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.model.nodes().len(), whole.model.nodes().len() + 9);
// Keeping the highest labels; only a set's nodes; hostile parameters change nothing.
let r = s.execute("mesh.node.merge", &json!({"keep": "highest", "set": "seam"})).unwrap();
assert!(r["pairs"].as_array().unwrap().iter().all(|p| p[0].as_u64() < p[1].as_u64()), "{r}");
s.execute("edit.undo", &json!({})).unwrap();
for bad in [json!({"tolerance": -1}), json!({"tolerance": "x"}), json!({"keep": "middle"}), json!({"set": "nope"})] {
assert!(s.execute("mesh.node.merge", &bad).is_err(), "{bad}");
}
assert!(merge_preview(&s, &json!({})).is_some_and(|p| p.len() == 9));
}
/// Renumbering keeps the analysis: the cantilever solves to the same displacements, point
/// for point, after its nodes take the bandwidth order from 1000 and its elements are
/// shifted; the deck writes the new labels.
#[test]
fn renumbering_keeps_the_solution() {
let mut s = Session::default();
s.run_script(&crate::sample::cantilever()).unwrap();
let at = json!([[100.0, 10.0, 10.0], [50.0, 0.0, 20.0], [25.0, 20.0, 0.0]]);
let probe = |s: &mut Session| {
s.execute("solve.static", &json!({})).unwrap();
s.execute("solve.probe", &json!({"step": "Load", "at": at})).unwrap()["nodes"].clone()
};
let before = probe(&mut s);
let bw = bandwidth(&s.model, &|l| l);
let r = s.execute("mesh.renumber", &json!({"what": "nodes", "by": "bandwidth", "start": 1000})).unwrap();
assert_eq!(r["node_labels"][0], 1000, "{r}");
assert!(r["bandwidth"][1].as_u64().unwrap() <= u64::from(bw), "{r}");
s.execute("mesh.renumber", &json!({"what": "elements", "offset": 500})).unwrap();
assert_eq!(s.model.elements().keys().next().copied(), Some(501));
let after = probe(&mut s);
for (a, b) in before.as_array().unwrap().iter().zip(after.as_array().unwrap()) {
for k in 0..3 {
let (x, y) = (a["displacement"][k].as_f64().unwrap(), b["displacement"][k].as_f64().unwrap());
// Equal to roundoff of the tip deflection (0.24 mm).
assert!((x - y).abs() <= 1e-9, "{a} vs {b}");
}
}
let deck = fieldcraft_decks::abaqus::write(&s.model).unwrap();
assert!(deck.lines().any(|l| l.starts_with("1000,")) && deck.lines().any(|l| l.starts_with("501,")), "{deck}");
// Body by body and compact, then refusals that change nothing.
s.execute("mesh.renumber", &json!({"by": "body"})).unwrap();
s.execute("mesh.renumber", &json!({})).unwrap();
assert_eq!(s.model.nodes().keys().next().copied(), Some(1));
let model = s.model.clone();
for bad in [
json!({"offset": -1}),
json!({"start": 99_999_999}),
json!({"start": 0}),
json!({"by": "random"}),
json!({"what": "faces"}),
json!({"offset": 1, "start": 3}),
] {
assert!(s.execute("mesh.renumber", &bad).is_err(), "{bad}");
}
assert_eq!(s.model, model);
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ fn hex_octree(s: &mut Session, p: &Value) -> Result<Value> {
let surface = BoundarySurface::new(&b.mesh.positions, &b.mesh.triangles, &b.mesh.tri_face, &surface_options)
.map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
let left = OctreeOptions { max_elements: options.max_elements.saturating_sub(total).max(1), ..options.clone() };
let mesh = octree_hex_mesh(&surface, &UniformSize(h), &left).map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
let mesh = octree_hex_mesh(&surface, &UniformSize(h), &left).map_err(|e| EngineError::of_body(&b.name, e))?;
total += mesh.hexes.len();
meshes.push((b, mesh));
}
+542
View File
@@ -0,0 +1,542 @@
//! Node relaxation (#398): `mesh.node.relax` moves the nodes inside a sphere of influence (or
//! listed nodes, elements or a set) to fix the worst elements there, nodes on the geometry
//! staying on it ([`fieldcraft_mesh::relax`]), and keeps what it did as a relaxation field of the
//! model; `mesh.node.relax.apply` does a field again on the current mesh (after a remesh), and a
//! field marked `reapply` is applied by itself after every remesh of its bodies.
//!
//! **Where a node may go** comes from the mesh's geometry tags: a node on one B-rep face slides
//! in that face's parameters, a node where two faces meet slides along their edge, a node on a
//! geometry vertex or on three or more faces stays. Faces of the same surface (the two halves a
//! kernel splits a cylinder into, or one face as cut into cells) count once. Partition cut faces
//! (`partition:<name>:a` and `:b`) are not geometry: a node on one moves freely, and the cells on
//! both sides share it, so the mesh stays conforming across the cut. A node on the skin whose
//! geometry is unknown (an imported mesh) stays.
use std::collections::{BTreeMap, BTreeSet};
use fieldcraft_mesh::relax::{self, Constraints, Falloff, Freedom, RegionQuality, Relaxed};
use fieldcraft_mesh::surface::{BoundarySurface, SurfaceOptions};
use fieldcraft_mesh::tet::geometry::{AnalyticSurface, Tessellation};
use fieldcraft_model::geometry::Entity;
use fieldcraft_model::{Model, Relaxation};
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::schema::ProblemKind;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const RELAX: CommandSpec = CommandSpec {
id: "mesh.node.relax",
label: "Relax Nodes",
params: r#"{"center": [x, y, z], "radius": mm (the sphere of influence) | "around_element": label (a sphere round that element; radius default twice its longest edge) | "nodes": [labels] | "elements": [labels] | "set": "Name", "bodies"?: ["Body1"] (only their nodes), "iterations"?: 5 (1..=100), "strength"?: 1 (0..1], "falloff"?: "smooth" (default: weight 1 at the centre to 0 at the radius) | "linear" | "none", "field"?: "Name" (the relaxation field to keep; default Relax1, Relax2, …), "reapply"?: false (apply the field again after each remesh of these bodies)} — moves the nodes to improve the worst elements around them (smart Laplacian, then optimization of the worst element; a move is kept only when the worst element around the node does not get worse, and never inverts one). Nodes on a B-rep face slide in its UV parameters and stay on it, nodes on a B-rep edge slide along it, nodes on vertices stay; nodes on partition cut faces move freely (shared by both cells); mid-side nodes follow, on the geometry. Reports the nodes moved, the largest displacement, the region's smallest scaled Jacobian, largest edge ratio and worst elements before and after, and the field kept. One undo step"#,
form: Some(super::forms::NODE_RELAX),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: relax_nodes,
};
pub const APPLY: CommandSpec = CommandSpec {
id: "mesh.node.relax.apply",
label: "Apply Relaxation",
params: r#"{"field": "Name", "bodies"?: ["Body1"] (default the field's), "polish"?: 0.3 (strength of one guarded smoothing sweep after; 0 for none)} — applies a relaxation field kept by mesh.node.relax to the current mesh (typically after a remesh): each node inside the relaxed region takes the displacement interpolated from the field at its parametric coordinates in the old cells, on its face or edge as mesh.node.relax moves it; a move that would invert an element is undone; then one guarded smoothing sweep. Reports the nodes moved and the largest displacement"#,
form: Some(super::forms::NODE_RELAX_APPLY),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: apply,
};
/// The commands after which `reapply` fields are applied again.
const REMESH: &[&str] = &[
"mesh.tet.generate",
"mesh.hex.generate",
"mesh.hex.sweep",
"mesh.hex.mapped",
"mesh.hex.blocks",
"mesh.hex.octree",
"mesh.cells",
"mesh.block",
];
const DEFAULT_ITERATIONS: usize = 5;
/// The region's quality as JSON.
fn quality_json(q: &RegionQuality) -> Value {
json!({
"elements": q.elements,
"min_scaled_jacobian": q.min_quality,
"max_edge_ratio": if q.max_edge_ratio.is_finite() { json!(q.max_edge_ratio) } else { Value::Null },
"invalid": q.invalid,
"worst": q.worst.iter().map(|(e, v)| json!({"element": e, "quality": v})).collect::<Vec<_>>(),
})
}
/// Faces a node lies on (geometry references), from the element faces, shells and vertex tags.
struct NodeTags {
faces: BTreeMap<u32, BTreeSet<(String, String)>>,
vertex: BTreeSet<u32>,
/// Nodes on a partition cut face.
cut: BTreeSet<u32>,
}
fn node_tags(model: &Model, nodes: &BTreeSet<u32>) -> NodeTags {
let c = model.classification();
let mut t = NodeTags { faces: BTreeMap::new(), vertex: BTreeSet::new(), cut: BTreeSet::new() };
let note = |n: u32, tag: u32, t: &mut NodeTags| {
let Some(g) = c.entity(tag) else { return };
if let Entity::Face(name) = &g.entity {
if name.starts_with("partition:") {
t.cut.insert(n);
} else {
t.faces.entry(n).or_default().insert((g.body.clone(), name.clone()));
}
}
};
for (&label, tags) in c.elements() {
let Some(e) = model.element(label) else { continue };
if !e.nodes.iter().any(|n| nodes.contains(n)) {
continue;
}
if e.kind.dimension() == 2
&& let Some(r) = tags.region
{
for &n in &e.nodes {
note(n, r, &mut t);
}
}
for (&face, &tag) in &tags.faces {
let Some(local) = e.kind.faces().get(usize::from(face).wrapping_sub(1)) else { continue };
for &i in local.iter() {
if let Some(&n) = e.nodes.get(i) {
note(n, tag, &mut t);
}
}
}
}
for (&n, &tag) in c.nodes() {
if nodes.contains(&n) && c.entity(tag).is_some_and(|g| matches!(g.entity, Entity::Vertex(_))) {
t.vertex.insert(n);
}
}
t
}
/// Whether two exact surfaces are the same surface.
fn same_surface(a: &AnalyticSurface, b: &AnalyticSurface, tol: f64) -> bool {
use AnalyticSurface as S;
let sub = |x: [f64; 3], y: [f64; 3]| [x[0] - y[0], x[1] - y[1], x[2] - y[2]];
let dot = |x: [f64; 3], y: [f64; 3]| x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
let len = |x: [f64; 3]| dot(x, x).sqrt();
let unit = |x: [f64; 3]| {
let l = len(x);
if l > 0.0 { [x[0] / l, x[1] / l, x[2] / l] } else { x }
};
let parallel = |x: [f64; 3], y: [f64; 3]| (dot(unit(x), unit(y)).abs() - 1.0).abs() < 1e-9;
let on_axis = |p: [f64; 3], o: [f64; 3], a: [f64; 3]| {
let d = sub(p, o);
let a = unit(a);
let along = dot(d, a);
len([d[0] - a[0] * along, d[1] - a[1] * along, d[2] - a[2] * along]) <= tol
};
match (*a, *b) {
(S::Plane { normal: n1, point: p1 }, S::Plane { normal: n2, point: p2 }) => parallel(n1, n2) && dot(sub(p2, p1), unit(n1)).abs() <= tol,
(S::Cylinder { origin: o1, axis: a1, radius: r1 }, S::Cylinder { origin: o2, axis: a2, radius: r2 }) => {
(r1 - r2).abs() <= tol && parallel(a1, a2) && on_axis(o2, o1, a1)
}
(S::Sphere { center: c1, radius: r1 }, S::Sphere { center: c2, radius: r2 }) => len(sub(c1, c2)) <= tol && (r1 - r2).abs() <= tol,
(S::Cone { apex: p1, axis: a1, half_angle: h1 }, S::Cone { apex: p2, axis: a2, half_angle: h2 }) => {
len(sub(p1, p2)) <= tol && dot(unit(a1), unit(a2)) > 1.0 - 1e-9 && (h1 - h2).abs() <= 1e-9
}
(S::Torus { center: c1, axis: a1, major: m1, minor: n1 }, S::Torus { center: c2, axis: a2, major: m2, minor: n2 }) => {
len(sub(c1, c2)) <= tol && parallel(a1, a2) && (m1 - m2).abs() <= tol && (n1 - n2).abs() <= tol
}
_ => false,
}
}
/// The design's geometry as relaxation constraints.
struct DesignGeometry {
/// Per body: its tessellation with exact surfaces.
bodies: Vec<Tessellation>,
/// Face ids: (body, B-rep face).
faces: Vec<(usize, u32)>,
/// Curve ids: (body, the two B-rep faces).
curves: Vec<(usize, [u32; 2])>,
freedom: BTreeMap<u32, Freedom>,
}
impl Constraints for DesignGeometry {
fn freedom(&self, node: u32) -> Option<Freedom> {
self.freedom.get(&node).copied()
}
fn slide_face(&self, face: u32, p: [f64; 3], d: [f64; 3]) -> Option<[f64; 3]> {
let &(b, f) = self.faces.get(face as usize)?;
self.bodies.get(b)?.slide_face(f, p, d)
}
fn slide_curve(&self, curve: u32, p: [f64; 3], d: [f64; 3]) -> Option<[f64; 3]> {
let &(b, f) = self.curves.get(curve as usize)?;
self.bodies.get(b)?.slide_curve(f, p, d)
}
}
/// The constraints of `nodes` from the mesh's tags and the open design.
fn design_geometry(s: &Session, nodes: &BTreeSet<u32>) -> Result<DesignGeometry> {
let tags = node_tags(&s.model, nodes);
let mut g = DesignGeometry { bodies: Vec::new(), faces: Vec::new(), curves: Vec::new(), freedom: BTreeMap::new() };
// Body name → (index into `g.bodies`, its exact surfaces), built when first needed.
let mut loaded: BTreeMap<String, Option<(usize, Vec<Option<AnalyticSurface>>)>> = BTreeMap::new();
let mut load = |name: &str, g: &mut DesignGeometry| -> Result<Option<(usize, Vec<Option<AnalyticSurface>>)>> {
if let Some(l) = loaded.get(name) {
return Ok(l.clone());
}
let shape = s.design.as_deref().and_then(|d| d.body(name));
let entry = match shape {
None => None,
Some(shape) => {
let tol = (shape.size()? * 1e-3).max(1e-6);
let mesh = shape.tessellate(tol)?;
let surface = BoundarySurface::new(
&mesh.positions,
&mesh.triangles,
&mesh.tri_face,
&SurfaceOptions { weld_distance: mesh.weld_distance, ..SurfaceOptions::default() },
)?;
let analytic = super::mesh::analytic_surfaces(shape);
g.bodies.push(Tessellation::new(&surface, analytic.clone()));
Some((g.bodies.len() - 1, analytic))
}
};
loaded.insert(name.to_string(), entry.clone());
Ok(entry)
};
let tol = 1e-6 * s.model.nodes().values().fold(0.0f64, |m, n| m.max(n.xyz.iter().fold(0.0f64, |a, x| a.max(x.abs())))).max(1.0);
let mut face_ids: BTreeMap<(usize, u32), u32> = BTreeMap::new();
let mut curve_ids: BTreeMap<(usize, [u32; 2]), u32> = BTreeMap::new();
for &n in nodes {
if tags.vertex.contains(&n) {
g.freedom.insert(n, Freedom::Fixed);
continue;
}
let Some(refs) = tags.faces.get(&n) else {
if tags.cut.contains(&n) {
g.freedom.insert(n, Freedom::Free);
}
continue;
};
// Resolve each face; group those on one surface.
let mut groups: Vec<Vec<(usize, u32, Option<AnalyticSurface>)>> = Vec::new();
let mut unknown = false;
for (body, face) in refs {
let Some((b, analytic)) = load(body, &mut g)? else {
unknown = true;
continue;
};
let Some(f) = s.design.as_deref().and_then(|d| d.body(body)).and_then(|sh| sh.face_index(face)) else {
unknown = true;
continue;
};
let surface = analytic.get(f as usize).copied().flatten();
let group = groups.iter_mut().find(|grp| {
grp.iter().any(|(gb, gf, gs)| (*gb == b && *gf == f) || matches!((gs, surface), (Some(x), Some(y)) if same_surface(x, &y, tol)))
});
match group {
Some(grp) => grp.push((b, f, surface)),
None => groups.push(vec![(b, f, surface)]),
}
}
let freedom = match groups.as_slice() {
_ if unknown => Freedom::Fixed,
[one] => {
let Some(&(b, f, _)) = one.first() else { continue };
let next = g.faces.len() as u32;
let id = *face_ids.entry((b, f)).or_insert(next);
if id == next {
g.faces.push((b, f));
}
Freedom::Face(id)
}
[x, y] => {
// A body with a face of each surface carries their edge.
let pair = x.iter().find_map(|&(bx, fx, _)| y.iter().find(|(by, _, _)| *by == bx).map(|&(_, fy, _)| (bx, [fx.min(fy), fx.max(fy)])));
match pair {
Some(key) => {
let next = g.curves.len() as u32;
let id = *curve_ids.entry(key).or_insert(next);
if id == next {
g.curves.push(key);
}
Freedom::Curve(id)
}
None => Freedom::Fixed,
}
}
_ => Freedom::Fixed,
};
g.freedom.insert(n, freedom);
}
Ok(g)
}
/// The nodes of `bodies`' elements, when given.
fn body_nodes(model: &Model, p: &Value) -> Result<Option<(Vec<String>, BTreeSet<u32>)>> {
let Some(bodies) = super::opt::<Vec<String>>(p, "bodies")? else { return Ok(None) };
let mut nodes = BTreeSet::new();
for b in &bodies {
let elements = model.body_elements(b);
if elements.is_empty() {
return Err(EngineError::Params(format!("body `{}` has no mesh", b.chars().take(80).collect::<String>())));
}
for e in elements {
if let Some(el) = model.element(e) {
nodes.extend(el.nodes.iter().copied());
}
}
}
Ok(Some((bodies, nodes)))
}
fn point(p: &Value, key: &str) -> Result<Option<[f64; 3]>> {
match super::opt::<[f64; 3]>(p, key)? {
Some(c) if c.iter().all(|x| x.is_finite()) => Ok(Some(c)),
Some(_) => Err(EngineError::param(key, ProblemKind::NotANumber)),
None => Ok(None),
}
}
/// The sphere around element `label`: its centroid, and twice its longest corner edge.
fn around_element(model: &Model, label: u32) -> Result<([f64; 3], f64)> {
let e = model.element(label).ok_or_else(|| EngineError::Params(format!("no element {label}")))?;
let x: Vec<[f64; 3]> = e.nodes.iter().take(e.kind.corner_count()).filter_map(|n| model.node(*n).map(|p| p.xyz)).collect();
if x.is_empty() {
return Err(EngineError::Params(format!("element {label} has no nodes")));
}
let c = x.iter().fold([0.0; 3], |s, p| [s[0] + p[0], s[1] + p[1], s[2] + p[2]]).map(|v| v / x.len() as f64);
let mut longest = 0.0f64;
for edge in e.kind.edges() {
let at = |i: usize| edge.get(i).and_then(|&k| x.get(k)).copied();
if let (Some(a), Some(b)) = (at(0), at(1)) {
longest = longest.max(((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt());
}
}
Ok((c, 2.0 * longest))
}
/// The nodes to move and their weights, and the sphere when there is one.
pub(crate) fn weights(model: &Model, p: &Value) -> Result<(BTreeMap<u32, f64>, Option<([f64; 3], f64)>)> {
let strength = super::optional_number(p, "strength", 1.0)?;
if !(strength > 0.0 && strength <= 1.0) {
return Err(EngineError::param("strength", ProblemKind::NotInRange { min: 0.0, max: 1.0 }));
}
let falloff = match super::opt::<String>(p, "falloff")? {
None => Falloff::Smooth,
Some(f) => Falloff::from_name(&f).ok_or_else(|| EngineError::param("falloff", ProblemKind::NotAChoice))?,
};
let only = body_nodes(model, p)?.map(|(_, n)| n);
let around = match super::opt::<u32>(p, "around_element")? {
Some(e) => Some(around_element(model, e)?),
None => None,
};
let center = point(p, "center")?.or(around.map(|a| a.0));
let radius = match p.get("radius") {
Some(_) => Some(super::optional_number(p, "radius", 0.0)?)
.filter(|r| *r > 0.0 && r.is_finite())
.ok_or_else(|| EngineError::param("radius", ProblemKind::NotPositive))
.map(Some)?,
None => around.map(|a| a.1),
};
let listed = ["nodes", "elements", "set"].iter().filter(|k| p.get(**k).is_some()).count();
if let (Some(c), Some(r)) = (center, radius) {
if listed > 0 {
return Err(EngineError::Params(
"give a sphere (`center` and `radius`, or `around_element`) or `nodes`, `elements` or `set`, not both".into(),
));
}
return Ok((relax::sphere_weights(model, c, r, strength, falloff, only.as_ref())?, Some((c, r))));
}
if center.is_some() != radius.is_some() {
return Err(EngineError::Params("a sphere of influence needs both `center` and `radius`".into()));
}
let mut nodes: BTreeSet<u32> = BTreeSet::new();
if p.get("nodes").is_some() {
nodes.extend(super::labels(p, "nodes", fieldcraft_model::MAX_NODES)?);
}
let mut elements: Vec<u32> = Vec::new();
if p.get("elements").is_some() {
elements.extend(super::labels(p, "elements", fieldcraft_model::MAX_ELEMENTS)?);
}
if let Some(name) = super::opt::<String>(p, "set")? {
let set = model.resolve_set(&name)?;
nodes.extend(set.nodes.iter().copied());
elements.extend(set.elements.iter().copied());
elements.extend(set.faces.iter().map(|f| f.element));
}
for e in elements {
let el = model.element(e).ok_or_else(|| EngineError::Params(format!("no element {e}")))?;
nodes.extend(el.nodes.iter().copied());
}
if listed == 0 {
return Err(EngineError::Params(
"say which nodes to relax: give one of `center` and `radius`, `around_element`, `nodes`, `elements` or `set`".into(),
));
}
if let Some(only) = &only {
nodes.retain(|n| only.contains(n));
}
Ok((relax::uniform_weights(model, &nodes, strength)?, None))
}
fn iterations(p: &Value) -> Result<usize> {
match p.get("iterations") {
None => Ok(DEFAULT_ITERATIONS),
Some(v) => v
.as_u64()
.and_then(|i| usize::try_from(i).ok())
.filter(|i| (1..=relax::MAX_ITERATIONS).contains(i))
.ok_or_else(|| EngineError::param("iterations", ProblemKind::NotInRange { min: 1.0, max: relax::MAX_ITERATIONS as f64 })),
}
}
/// The nodes the relaxation may touch: the weighted ones and their elements' nodes.
fn touched(model: &Model, weights: &BTreeMap<u32, f64>) -> BTreeSet<u32> {
let mut out: BTreeSet<u32> = weights.keys().copied().collect();
for e in model.elements().values() {
if e.nodes.iter().any(|n| weights.contains_key(n)) {
out.extend(e.nodes.iter().copied());
}
}
out
}
/// What `mesh.node.relax` with `params` would do, without doing it: the open form's preview.
pub struct Preview {
pub sphere: Option<([f64; 3], f64)>,
pub relaxed: Relaxed,
}
pub fn preview(s: &Session, params: &Value) -> Option<Preview> {
let (w, sphere) = weights(&s.model, params).ok()?;
let g = design_geometry(s, &touched(&s.model, &w)).ok()?;
let relaxed = relax::relax(&s.model, &w, iterations(params).ok()?, &g).ok()?;
Some(Preview { sphere, relaxed })
}
/// The sphere `params` describe, for the form's gizmo before the rest is valid.
pub fn sphere(s: &Session, params: &Value) -> Option<([f64; 3], f64)> {
let around = params.get("around_element").and_then(Value::as_u64).and_then(|e| around_element(&s.model, u32::try_from(e).ok()?).ok());
let c = point(params, "center").ok().flatten().or(around.map(|a| a.0))?;
let r = params.get("radius").and_then(Value::as_f64).filter(|r| *r > 0.0 && r.is_finite()).or(around.map(|a| a.1))?;
Some((c, r))
}
fn relax_nodes(s: &mut Session, p: &Value) -> Result<Value> {
let (w, sphere) = weights(&s.model, p)?;
if w.is_empty() {
return Err(EngineError::Params("no mesh nodes in the region to relax".into()));
}
let iterations = iterations(p)?;
let g = design_geometry(s, &touched(&s.model, &w))?;
let r = relax::relax(&s.model, &w, iterations, &g)?;
let field_name = match super::opt::<String>(p, "field")? {
Some(n) => n,
None => (1..).map(|i| format!("Relax{i}")).find(|n| s.model.relaxation(n).is_none()).unwrap_or_else(|| "Relax".into()),
};
let bodies = match body_nodes(&s.model, p)? {
Some((b, _)) => b,
None => Vec::new(),
};
let reapply = super::opt::<bool>(p, "reapply")?.unwrap_or(false);
if !r.positions.is_empty() {
let cells = relax::field_cells(&s.model, &r);
s.model.set_relaxation(&field_name, Relaxation { bodies, cells, reapply })?;
}
for (n, x) in &r.positions {
s.model.set_node(*n, *x)?;
}
let summary = format!(
"moved {} node{} (largest {:.3e}); scaled Jacobian min from {:.3} to {:.3}{}",
r.moved,
if r.moved == 1 { "" } else { "s" },
r.max_displacement,
r.before.min_quality,
r.after.min_quality,
if r.positions.is_empty() { String::new() } else { format!("; kept as field {field_name}") }
);
Ok(json!({
"moved": r.moved,
"nodes_changed": r.positions.len(),
"max_displacement": r.max_displacement,
"iterations": r.iterations,
"sphere": sphere.map(|(c, r)| json!({"center": c, "radius": r})),
"before": quality_json(&r.before),
"after": quality_json(&r.after),
"field": (!r.positions.is_empty()).then_some(field_name),
"summary": summary,
}))
}
/// Apply field `name` to the nodes of `bodies` (or of the whole mesh).
fn apply_field(s: &mut Session, name: &str, bodies: &[String], polish: f64) -> Result<Relaxed> {
let field = s
.model
.relaxation(name)
.cloned()
.ok_or_else(|| EngineError::Params(format!("no relaxation field `{}`", name.chars().take(80).collect::<String>())))?;
let mut nodes = BTreeSet::new();
let bodies = if bodies.is_empty() { &field.bodies[..] } else { bodies };
if bodies.is_empty() {
nodes.extend(s.model.nodes().keys().copied());
} else {
for b in bodies {
for e in s.model.body_elements(b) {
if let Some(el) = s.model.element(e) {
nodes.extend(el.nodes.iter().copied());
}
}
}
}
// Only nodes the field reaches need constraints.
nodes.retain(|n| s.model.node(*n).is_some_and(|p| relax::field_displacement(&field.cells, p.xyz).is_some()));
let g = design_geometry(s, &nodes)?;
let r = relax::apply_field(&s.model, &field.cells, Some(&nodes), &g, polish)?;
for (n, x) in &r.positions {
s.model.set_node(*n, *x)?;
}
Ok(r)
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let name: String = super::req(p, "field")?;
let bodies = super::opt::<Vec<String>>(p, "bodies")?.unwrap_or_default();
let polish = super::optional_number(p, "polish", 0.3)?;
if !(0.0..=1.0).contains(&polish) {
return Err(EngineError::param("polish", ProblemKind::NotInRange { min: 0.0, max: 1.0 }));
}
let r = apply_field(s, &name, &bodies, polish)?;
Ok(json!({
"moved": r.moved,
"nodes_changed": r.positions.len(),
"max_displacement": r.max_displacement,
"summary": format!("applied field {name}: moved {} node{} (largest {:.3e})", r.moved, if r.moved == 1 { "" } else { "s" }, r.max_displacement),
}))
}
/// After a remesh (`id`), apply again every field marked `reapply`; its reply lists them.
pub(crate) fn after_remesh(s: &mut Session, id: &str, mut reply: Value) -> Result<Value> {
if !REMESH.contains(&id) {
return Ok(reply);
}
let fields: Vec<String> = s.model.relaxations().iter().filter(|(_, f)| f.reapply).map(|(n, _)| n.clone()).collect();
let mut applied = Vec::new();
for name in fields {
let r = apply_field(s, &name, &[], 0.3)?;
applied.push(json!({"field": name, "moved": r.moved}));
}
if !applied.is_empty()
&& let Some(o) = reply.as_object_mut()
{
o.insert("relaxations_applied".into(), Value::Array(applied));
}
Ok(reply)
}
#[cfg(test)]
mod tests;
+194
View File
@@ -0,0 +1,194 @@
use super::*;
/// The plate (40 × 30 × 10) with its Ø10 hole round (15, 15): a point on the hole's wall.
const ON_HOLE: [f64; 3] = [20.0, 15.0, 5.0];
const HOLE: ([f64; 2], f64) = ([15.0, 15.0], 5.0);
fn plate() -> Session {
super::super::datum::tests::plate().0
}
fn hole_radius(p: [f64; 3]) -> f64 {
((p[0] - HOLE.0[0]).powi(2) + (p[1] - HOLE.0[1]).powi(2)).sqrt()
}
/// Which analytic face a node of the plate lies on, if any.
fn on_faces(p: [f64; 3]) -> Vec<&'static str> {
let mut f = Vec::new();
if (hole_radius(p) - HOLE.1).abs() < 1e-6 {
f.push("hole");
}
if p[2].abs() < 1e-6 || (p[2] - 10.0).abs() < 1e-6 {
f.push("cap");
}
f
}
/// Spikes near the hole: interior nodes pushed about; nodes on the hole turned round it and
/// moved along its axis (still on the cylinder), nodes on the caps moved in their plane.
fn perturb(s: &mut Session, centre: [f64; 3], radius: f64, amount: f64) {
let nodes: Vec<(u32, [f64; 3])> = s.model.nodes().iter().map(|(n, p)| (*n, p.xyz)).collect();
for (k, (n, p)) in nodes.into_iter().enumerate() {
let d2: f64 = (0..3).map(|i| (p[i] - centre[i]).powi(2)).sum();
if d2 > radius * radius {
continue;
}
let wiggle = |m: usize| amount * ((k * m % 7) as f64 - 3.0) / 3.0;
let faces = on_faces(p);
let q = match faces.as_slice() {
[] => [p[0] + wiggle(3), p[1] + wiggle(5), p[2] + wiggle(11)],
["hole"] => {
let a = wiggle(3) / HOLE.1;
let (x, y) = (p[0] - HOLE.0[0], p[1] - HOLE.0[1]);
[HOLE.0[0] + x * a.cos() - y * a.sin(), HOLE.0[1] + x * a.sin() + y * a.cos(), p[2] + wiggle(5)]
}
["cap"] if hole_radius(p) > HOLE.1 + 1e-6 => [p[0] + wiggle(3), p[1] + wiggle(5), p[2]],
_ => continue,
};
s.model.set_node(n, q).unwrap();
}
}
fn check_on_geometry(before: &Model, after: &Model) {
for (n, p) in after.nodes() {
let old = before.node(*n).unwrap().xyz;
for f in on_faces(old) {
match f {
"hole" => assert!((hole_radius(p.xyz) - HOLE.1).abs() < 1e-6, "node {n} left the hole: r = {}", hole_radius(p.xyz)),
_ => assert!((p.xyz[2] - old[2]).abs() < 1e-6, "node {n} left its cap"),
}
}
}
}
fn invalid(s: &mut Session) -> u64 {
s.execute("mesh.quality", &json!({})).unwrap()["invalid"]["count"].as_u64().unwrap_or(0)
}
/// The issue's hex test on a design: spikes near the hole relax, every surface node stays on its
/// face (the hole's cylinder exactly), quality rises, nothing inverts, nothing outside the sphere
/// moves; one undo step; the field is kept and saved with the model.
#[test]
fn hex_spikes_near_a_hole_relax_on_the_geometry() {
let mut s = plate();
s.execute("mesh.hex.generate", &json!({"size": 2.0})).unwrap();
perturb(&mut s, ON_HOLE, 3.0, 0.35);
let perturbed = s.model.clone();
let r = s.execute("mesh.node.relax", &json!({"center": ON_HOLE, "radius": 4.0, "iterations": 10})).unwrap();
let (before, after) = (r["before"]["min_scaled_jacobian"].as_f64().unwrap(), r["after"]["min_scaled_jacobian"].as_f64().unwrap());
assert!(after > before + 0.05, "{r}");
assert_eq!(r["after"]["invalid"], 0, "{r}");
assert!(r["moved"].as_u64().unwrap() > 0 && r["field"] == "Relax1", "{r}");
check_on_geometry(&perturbed, &s.model);
for (n, p) in s.model.nodes() {
let old = perturbed.node(*n).unwrap().xyz;
if old != p.xyz {
let d2: f64 = (0..3).map(|i| (old[i] - ON_HOLE[i]).powi(2)).sum();
assert!(d2 < 16.0, "node {n} outside the sphere moved");
}
}
assert_eq!(invalid(&mut s), 0);
// The field is saved with the model.
let text = serde_json::to_string(&s.model).unwrap();
let back: Model = serde_json::from_str(&text).unwrap();
assert_eq!(back.relaxation("Relax1"), s.model.relaxation("Relax1"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.model, perturbed);
}
/// The same on tet10 with curved mid-side nodes on the hole: they stay on the cylinder.
#[test]
fn tet10_relaxes_with_curved_mid_side_nodes_on_the_hole() {
let mut s = plate();
s.execute("mesh.tet.generate", &json!({"size": 2.5, "order": "quadratic"})).unwrap();
perturb(&mut s, ON_HOLE, 3.0, 0.2);
// Put the mid-side nodes back on their edges' middles, on the hole where the edge is.
let mids: Vec<(u32, u32, u32)> = s
.model
.elements()
.values()
.flat_map(|e| e.kind.edges().iter().map(|ed| (e.nodes[ed[0]], e.nodes[ed[1]], e.nodes[ed[2]])).collect::<Vec<_>>())
.collect();
let original = s.model.clone();
for (a, b, m) in mids {
let (pa, pb, pm) = (original.node(a).unwrap().xyz, original.node(b).unwrap().xyz, original.node(m).unwrap().xyz);
let mut q = [(pa[0] + pb[0]) / 2.0, (pa[1] + pb[1]) / 2.0, (pa[2] + pb[2]) / 2.0];
if on_faces(pm).contains(&"hole") {
let r = hole_radius(q);
q = [HOLE.0[0] + (q[0] - HOLE.0[0]) * HOLE.1 / r, HOLE.0[1] + (q[1] - HOLE.0[1]) * HOLE.1 / r, q[2]];
}
s.model.set_node(m, q).unwrap();
}
let perturbed = s.model.clone();
let r = s.execute("mesh.node.relax", &json!({"center": ON_HOLE, "radius": 4.0, "iterations": 8})).unwrap();
assert!(r["after"]["min_scaled_jacobian"].as_f64().unwrap() >= r["before"]["min_scaled_jacobian"].as_f64().unwrap(), "{r}");
assert_eq!(r["after"]["invalid"], 0, "{r}");
check_on_geometry(&perturbed, &s.model);
}
/// A partition cut is not geometry: nodes on it move freely, shared by the cells on both sides.
#[test]
fn nodes_on_a_partition_cut_move_freely() {
let mut s = plate();
s.execute("geometry.datum", &json!({"name": "Cut", "by": {"type": "offset", "plane": "yz", "offset": 27}})).unwrap();
s.execute("geometry.partition", &json!({"name": "P", "datum": "Cut"})).unwrap();
s.execute("mesh.cells", &json!({"size": 2.0, "default": "hex"})).unwrap();
let centre = [27.0, 15.0, 5.0];
perturb(&mut s, centre, 2.5, 0.3);
let before = s.model.clone();
s.execute("mesh.node.relax", &json!({"center": centre, "radius": 3.5, "iterations": 10})).unwrap();
let moved_off = s
.model
.nodes()
.iter()
.filter(|(n, p)| {
let old = before.node(**n).unwrap().xyz;
(old[0] - 27.0).abs() < 1e-6 && on_faces(old).is_empty() && (p.xyz[0] - 27.0).abs() > 1e-6
})
.count();
assert!(moved_off > 0, "nodes on the cut are free");
assert_eq!(invalid(&mut s), 0);
}
/// A field marked `reapply` is applied again after a remesh; `mesh.node.relax.apply` applies it
/// on demand; around the worst element works.
#[test]
fn a_kept_field_is_applied_again_after_a_remesh() {
let mut s = plate();
s.execute("mesh.hex.generate", &json!({"size": 3.0})).unwrap();
perturb(&mut s, ON_HOLE, 4.0, 0.3);
let r = s.execute("mesh.node.relax", &json!({"center": ON_HOLE, "radius": 5.0, "field": "Spike", "reapply": true})).unwrap();
assert_eq!(r["field"], "Spike");
let r = s.execute("mesh.hex.generate", &json!({"size": 1.5})).unwrap();
assert_eq!(r["relaxations_applied"][0]["field"], "Spike", "{r}");
assert_eq!(invalid(&mut s), 0);
let r = s.execute("mesh.node.relax.apply", &json!({"field": "Spike"})).unwrap();
assert!(r["summary"].as_str().unwrap().contains("Spike"));
let worst = s.execute("mesh.quality", &json!({})).unwrap()["metrics"]["scaled_jacobian"]["worst"].as_u64().unwrap();
let r = s.execute("mesh.node.relax", &json!({"around_element": worst})).unwrap();
assert!(r["after"]["min_scaled_jacobian"].as_f64() >= r["before"]["min_scaled_jacobian"].as_f64(), "{r}");
}
#[test]
fn hostile_parameters_never_panic() {
let mut s = plate();
s.execute("mesh.hex.generate", &json!({"size": 4.0})).unwrap();
for p in [
json!({}),
json!({"center": [0, 0, 0]}),
json!({"center": [1e300, 0, 0], "radius": 1}),
json!({"center": [0, 0, 0], "radius": -1}),
json!({"center": [0, 0, 0], "radius": 1, "nodes": [1]}),
json!({"nodes": [1], "strength": 2}),
json!({"nodes": [1], "iterations": 0}),
json!({"nodes": [1], "iterations": 1000}),
json!({"nodes": [1], "falloff": "cubic"}),
json!({"around_element": 99999999}),
json!({"set": "nope"}),
json!({"nodes": [1], "bodies": ["nope"]}),
] {
assert!(s.execute("mesh.node.relax", &p).is_err(), "{p}");
}
assert!(s.execute("mesh.node.relax.apply", &json!({"field": "nope"})).is_err());
assert!(s.execute("mesh.node.relax.apply", &json!({})).is_err());
}
+119 -24
View File
@@ -46,6 +46,11 @@ pub(super) fn clear<'a>(model: &mut Model, bodies: impl IntoIterator<Item = &'a
}
impl Cleared {
/// [`Cleared::report`] when anything was removed; `reply` as it is otherwise.
pub(super) fn report_if_any(self, s: &Session, reply: Value) -> Value {
if self.bodies.is_empty() { reply } else { self.report(s, reply) }
}
/// Add `replaced`, `stale_sets` and `results_cleared` to a command's reply (an object).
pub(super) fn report(self, s: &Session, mut reply: Value) -> Value {
if let Some(o) = reply.as_object_mut() {
@@ -63,6 +68,55 @@ impl Cleared {
}
}
pub const CLEAR: crate::CommandSpec = crate::CommandSpec {
id: "mesh.clear",
label: "Clear Mesh",
params: r#"{"bodies"?: ["Body1/a"]} — removes the meshes of the bodies (their elements and the nodes only they use; sets that listed them are named as `stale_sets`, results solved on them are cleared); without `bodies`, of every body the open design no longer has because its partitions changed since it was meshed (model.check lists them; none: nothing changes). Reports what went as `replaced`"#,
form: Some(super::forms::CLEAR_MESH),
kind: crate::CommandKind::Model,
requires: &[crate::requirement::Requirement::Mesh],
run: clear_meshes,
};
fn clear_meshes(s: &mut Session, p: &Value) -> Result<Value> {
let bodies: Vec<String> = match p.get("bodies") {
Some(_) => super::req(p, "bodies")?,
None => s.design.as_deref().map(|d| stale(&s.model, d).into_iter().map(|(b, _)| b).collect()).unwrap_or_default(),
};
for b in &bodies {
if s.model.body_elements(b).is_empty() {
return Err(EngineError::Params(format!("body `{}` has no mesh", b.chars().take(64).collect::<String>())));
}
}
let cleared = clear(&mut s.model, bodies.iter().map(String::as_str));
let (nodes, elements) = (s.model.nodes().len(), s.model.elements().len());
Ok(cleared.report(s, json!({"nodes": nodes, "elements": elements})))
}
/// The meshed bodies the open design no longer has because its partitions changed (#385): cells
/// of a partition that is gone (`Base/a/b`), or a body partitions now cut (`Base`), each with
/// its element count. Other bodies the design lacks (mirror images, imported surfaces, blocks)
/// are not stale.
pub(crate) fn stale(model: &Model, design: &fieldcraft_geometry::Design) -> Vec<(String, usize)> {
let cell = |name: &str| -> bool {
let Some(source) = design.source_of(name) else { return false };
let rest = name.get(source.len()..).unwrap_or_default();
rest.split('/').skip(1).all(|seg| seg.strip_prefix(['a', 'b']).is_some_and(|k| k.bytes().all(|c| c.is_ascii_digit())))
};
model
.classification()
.entities()
.iter()
.filter(|g| matches!(g.entity, fieldcraft_model::geometry::Entity::Body))
.map(|g| g.body.as_str())
.filter(|b| design.body(b).is_none() && cell(b))
.filter_map(|b| {
let n = model.body_elements(b).len();
(n > 0).then(|| (b.to_string(), n))
})
.collect()
}
/// The bodies a meshing command fills, from its parameters, without meshing anything.
pub type Targets = fn(&Session, &Value) -> Result<Vec<String>>;
@@ -102,6 +156,28 @@ fn design_bodies(s: &Session) -> Result<Vec<String>> {
Ok(design.bodies.iter().map(|b| b.name.clone()).collect())
}
/// Tetrahedra and hexahedra of either order: the kinds an order change swaps.
fn family(k: ElementKind) -> Option<u8> {
match k {
ElementKind::Tet4 | ElementKind::Tet10 => Some(0),
ElementKind::Hex8 | ElementKind::Hex20 => Some(1),
_ => None,
}
}
/// The solid element type `command` makes with `params`, when it makes one type.
fn made_kind(command: &str, params: &Value) -> Option<ElementKind> {
match command {
"mesh.tet.generate" => {
Some(if params.get("order").and_then(Value::as_str) == Some("quadratic") { ElementKind::Tet10 } else { ElementKind::Tet4 })
}
"mesh.hex.generate" | "mesh.hex.sweep" | "mesh.hex.mapped" | "mesh.hex.blocks" => {
Some(if params.get("order").and_then(Value::as_i64) == Some(2) { ElementKind::Hex20 } else { ElementKind::Hex8 })
}
_ => None,
}
}
/// What running a meshing command would replace, for a confirmation before it runs.
#[derive(Debug, Clone, PartialEq)]
pub struct Replacement {
@@ -141,6 +217,14 @@ pub fn replacement(s: &Session, command: &str, params: &Value) -> Option<Replace
}
};
let mut warnings = Vec::new();
// The element type changing (tet10 → tet4 when the order is left out) is easy to miss.
if let Some(new) = made_kind(command, params) {
let old: BTreeSet<ElementKind> = removed.elements.iter().filter_map(|l| s.model.element(*l)).map(|e| e.kind).collect();
let changed: Vec<&str> = old.iter().filter(|k| **k != new && family(**k) == family(new)).map(|k| k.name()).collect();
if !changed.is_empty() {
warnings.push(format!("The element type changes: {} → {}.", changed.join(", "), new.name()));
}
}
let stale = s.model.sets_using(&removed);
if !stale.is_empty() {
warnings.push(format!("Sets that list its nodes or elements by label ({}) will name labels of the old mesh.", stale.join(", ")));
@@ -153,7 +237,7 @@ pub fn replacement(s: &Session, command: &str, params: &Value) -> Option<Replace
}
/// `n` with thousands separators: 7274 → "7,274".
fn thousands(n: usize) -> String {
pub fn thousands(n: usize) -> String {
let digits = n.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, c) in digits.chars().enumerate() {
@@ -181,7 +265,7 @@ mod tests {
assert_eq!(thousands(1_000_000), "1,000,000");
}
/// A 20 × 10 × 10 box split at x = 10 into `Box` (x < 10) and `Box (1)`.
/// A 20 × 10 × 10 box split at x = 10, opened as `Box.1` (x < 10) and `Box.2`.
fn two_boxes() -> (crate::tests::TempDir, Session) {
let commands = json!({"commands": [
{"command": "solid.box", "params": {"length": 20, "width": 10, "height": 10, "body_name": "Box"}},
@@ -194,6 +278,17 @@ mod tests {
(dir, s)
}
/// Remeshing without the order would turn tet10 into tet4: the question says so (#343).
#[test]
fn an_element_type_change_is_named() {
let (_dir, mut s) = two_boxes();
s.execute("mesh.tet.generate", &json!({"body": "Box.1", "size": 5, "order": "quadratic"})).unwrap();
let r = replacement(&s, "mesh.tet.generate", &json!({"body": "Box.1", "size": 4})).unwrap();
assert!(r.warnings.iter().any(|w| w == "The element type changes: tet10 → tet4."), "{r:?}");
let same = replacement(&s, "mesh.tet.generate", &json!({"body": "Box.1", "order": "quadratic"})).unwrap();
assert!(same.warnings.iter().all(|w| !w.contains("element type")), "{same:?}");
}
/// A body's elements, by label.
fn elements_of(s: &Session, body: &str) -> BTreeMap<u32, Element> {
s.model.body_elements(body).into_iter().filter_map(|l| Some((l, s.model.element(l)?.clone()))).collect()
@@ -204,25 +299,25 @@ mod tests {
/// was, names the set that listed the old labels, and one undo brings the first mesh back.
#[test]
fn every_mesher_replaces_the_mesh_of_its_body_only() {
let tet_other = json!({"command": "mesh.tet.generate", "params": {"body": "Box (1)", "size": 5}});
let hex_box = json!({"command": "mesh.hex.generate", "params": {"body": "Box", "size": 2.5}});
let tet_other = json!({"command": "mesh.tet.generate", "params": {"body": "Box.2", "size": 5}});
let hex_box = json!({"command": "mesh.hex.generate", "params": {"body": "Box.1", "size": 2.5}});
let square = json!([[0, 0], [10, 0], [10, 10], [0, 10]]);
let cases: Vec<(&str, Vec<Value>, Value, &str, &str)> = vec![
("mesh.tet.generate", vec![tet_other.clone()], json!({"body": "Box", "size": 4}), "Box", "Box (1)"),
("mesh.hex.generate", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.sweep", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.mapped", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.octree", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.blocks", vec![tet_other.clone()], json!({"bodies": ["Box"], "size": 2.5}), "Box", "Box (1)"),
("mesh.cells", vec![tet_other.clone()], json!({"bodies": ["Box"], "size": 2.5, "default": "hex"}), "Box", "Box (1)"),
("mesh.planar", vec![tet_other.clone()], json!({"polygon": square, "size": 2.5, "name": "Box"}), "Box", "Box (1)"),
("mesh.tet.generate", vec![tet_other.clone()], json!({"body": "Box.1", "size": 4}), "Box.1", "Box.2"),
("mesh.hex.generate", vec![tet_other.clone()], json!({"body": "Box.1", "size": 2.5}), "Box.1", "Box.2"),
("mesh.hex.sweep", vec![tet_other.clone()], json!({"body": "Box.1", "size": 2.5}), "Box.1", "Box.2"),
("mesh.hex.mapped", vec![tet_other.clone()], json!({"body": "Box.1", "size": 2.5}), "Box.1", "Box.2"),
("mesh.hex.octree", vec![tet_other.clone()], json!({"body": "Box.1", "size": 2.5}), "Box.1", "Box.2"),
("mesh.hex.blocks", vec![tet_other.clone()], json!({"bodies": ["Box.1"], "size": 2.5}), "Box.1", "Box.2"),
("mesh.cells", vec![tet_other.clone()], json!({"bodies": ["Box.1"], "size": 2.5, "default": "hex"}), "Box.1", "Box.2"),
("mesh.planar", vec![tet_other.clone()], json!({"polygon": square, "size": 2.5, "name": "Box.1"}), "Box.1", "Box.2"),
// The image's tets (meshed before) are replaced by the mirrored hexahedra.
(
"mesh.mirror",
vec![hex_box, tet_other],
json!({"plane": {"point": [10, 0, 0], "normal": [1, 0, 0]}, "bodies": ["Box"]}),
"Box (1)",
"Box",
json!({"plane": {"point": [10, 0, 0], "normal": [1, 0, 0]}, "bodies": ["Box.1"]}),
"Box.2",
"Box.1",
),
];
let covered: BTreeSet<&str> = cases.iter().map(|c| c.0).collect();
@@ -272,16 +367,16 @@ mod tests {
fn tets_over_hexahedra_leave_only_tets() {
let (_dir, mut s) = two_boxes();
s.execute("mesh.hex.generate", &json!({"size": 2.5})).unwrap();
let hexes = elements_of(&s, "Box").len();
let other = elements_of(&s, "Box (1)");
let r = s.execute("mesh.tet.generate", &json!({"body": "Box", "size": 4})).unwrap();
let hexes = elements_of(&s, "Box.1").len();
let other = elements_of(&s, "Box.2");
let r = s.execute("mesh.tet.generate", &json!({"body": "Box.1", "size": 4})).unwrap();
assert_eq!(r["replaced"][0]["elements"], hexes, "{r}");
assert!(elements_of(&s, "Box").values().all(|e| e.kind == ElementKind::Tet4));
assert_eq!(elements_of(&s, "Box (1)"), other);
assert!(elements_of(&s, "Box.1").values().all(|e| e.kind == ElementKind::Tet4));
assert_eq!(elements_of(&s, "Box.2"), other);
let tets = s.model.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(elements_of(&s, "Box").len(), hexes, "one undo brings the hexahedra back");
assert!(elements_of(&s, "Box").values().all(|e| e.kind == ElementKind::Hex8));
assert_eq!(elements_of(&s, "Box.1").len(), hexes, "one undo brings the hexahedra back");
assert!(elements_of(&s, "Box.1").values().all(|e| e.kind == ElementKind::Hex8));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.model, tets);
// Meshing every body replaces both.
@@ -290,8 +385,8 @@ mod tests {
assert!(s.model.elements().values().all(|e| e.kind == ElementKind::Tet4));
// A body without a mesh asks nothing.
let (_dir2, s2) = two_boxes();
assert_eq!(replacement(&s2, "mesh.tet.generate", &json!({"body": "Box"})), None);
assert_eq!(replacement(&s, "mesh.block", &json!({"body": "Box"})), None, "not a mesher");
assert_eq!(replacement(&s2, "mesh.tet.generate", &json!({"body": "Box.1"})), None);
assert_eq!(replacement(&s, "mesh.block", &json!({"body": "Box.1"})), None, "not a mesher");
}
#[test]
+334 -3
View File
@@ -23,7 +23,7 @@ pub const DEFORMED: CommandSpec = CommandSpec {
pub const CONTOUR: CommandSpec = CommandSpec {
id: "results.contour",
label: "Contours",
params: r#"{"step": "Load", "field": "von_mises", "bands": 12} — contours of a nodal field: displacement, displacement_x/y/z, von_mises, max/mid/min_principal, stress_xx/yy/zz/xy/xz/yz (stresses for static steps), contact_pressure, contact_gap, contact_status (0 open, 1 closed or stick, 2 slip), contact_shear, contact_slip (friction; nonlinear static steps with contact, at the contacts' secondary surfaces); "none" turns them off; 2 to 24 bands"#,
params: r#"{"step": "Load", "field": "von_mises", "bands": 12, "range"?: {"min"?: 0, "max"?: 80} | "auto"} — contours of a nodal field: displacement, displacement_x/y/z, von_mises, max/mid/min_principal, stress_xx/yy/zz/xy/xz/yz (stresses for static steps), contact_pressure, contact_gap, contact_status (0 open, 1 closed or stick, 2 slip), contact_shear, contact_slip (friction; nonlinear static steps with contact, at the contacts' secondary surfaces); "none" turns them off; 2 to 24 bands; `range` clamps the legend (a bound left out, null or "auto" follows the field; values above `max` are drawn in the over colour), kept until the field changes"#,
form: Some(super::forms::CONTOUR),
kind: CommandKind::Session,
requires: &[Requirement::Result],
@@ -63,13 +63,23 @@ pub const FRAME: CommandSpec = CommandSpec {
pub const REACTIONS: CommandSpec = CommandSpec {
id: "results.reactions",
label: "Reaction Sums",
params: r#"{"step": "Load", "sets": ["root"], "about": [0, 0, 0]} — reaction force and moment (about the point) summed over each node set, and over the whole model; `sets` defaults to the sets the step's boundary conditions hold"#,
params: r#"{"step": "Load", "sets": ["root"], "about": [0, 0, 0]} — reaction force and moment (about the point) summed over each node set, and over the whole model; `sets` (none or empty) defaults to the sets the step's boundary conditions hold"#,
form: Some(super::forms::REACTIONS),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: reactions,
};
pub const EXPORT_CSV: CommandSpec = CommandSpec {
id: "results.export.csv",
label: "Export Results (CSV)",
params: r#"{"what": "probe" | "reactions", "path": "tip.csv", "step": "Load", …} — writes probe or reaction results as a CSV file (RFC 4180, a header line, numbers in shortest round-trip form); the other parameters are solve.probe's (`nodes`, `at` or `set`, `mode`, `frame`) or results.reactions' (`sets`, `about`). Probe: a row per node with node, x, y, z and the quantities the step has; reactions: a row per set, a total row and an applied row. Replies with the path, rows, columns, step and units"#,
form: Some(super::forms::EXPORT_CSV),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: export_csv,
};
pub const CLEAR: CommandSpec = CommandSpec {
id: "results.clear",
label: "Hide Results",
@@ -196,14 +206,52 @@ fn contour(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(EngineError::Params(format!("{} is not available for step `{step}` (mode shapes have no stress scale)", f.label())));
}
let range = match p.get("range") {
None => None,
Some(r) => Some(legend_range(r)?),
};
let v = view_of(s, &step)?;
if v.contour != field {
(v.range_min, v.range_max) = (None, None);
}
v.contour = field;
if let Some(b) = bands {
v.bands = b;
}
if let Some((lo, hi)) = range {
(v.range_min, v.range_max) = (lo, hi);
}
Ok(s.results_report())
}
/// `results.contour`'s `range`: `"auto"` or null (follow the field), or `{min?, max?}`, each a
/// finite number, null or `"auto"`; `min` below `max`.
fn legend_range(r: &Value) -> Result<(Option<f64>, Option<f64>)> {
let bound = |k: &str| -> Result<Option<f64>> {
match r.get(k) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(a)) if a == "auto" => Ok(None),
Some(v) => {
v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| EngineError::Params(format!("`range.{k}` must be a number or \"auto\"")))
}
}
};
match r {
Value::Null => Ok((None, None)),
Value::String(a) if a == "auto" => Ok((None, None)),
Value::Object(_) => {
let (lo, hi) = (bound("min")?, bound("max")?);
if let (Some(a), Some(b)) = (lo, hi)
&& a >= b
{
return Err(EngineError::Params(format!("`range.min` ({a}) must be below `range.max` ({b})")));
}
Ok((lo, hi))
}
_ => Err(EngineError::Params("`range` must be {\"min\"?, \"max\"?} or \"auto\"".into())),
}
}
fn modes(s: &mut Session, p: &Value) -> Result<Value> {
let step = step_for(s, p, Want::Frequency)?;
let count = match s.latest_result(&step).map(|(r, _)| r.kind()) {
@@ -281,7 +329,8 @@ fn reactions(s: &mut Session, p: &Value) -> Result<Value> {
"step `{step}` is not a static step: reactions are kept for static steps (explicit steps keep the constraint force history, solve.history)"
)));
};
let sets: Vec<String> = match p.get("sets") {
// No sets (or an empty list, a form with none ticked): the step's boundary-condition sets.
let sets: Vec<String> = match p.get("sets").filter(|v| v.as_array().is_none_or(|a| !a.is_empty())) {
Some(v) => {
let list = v
.as_array()
@@ -330,6 +379,171 @@ fn reactions(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"step": step, "stale": !current, "about": about, "sets": per_set, "total": total, "applied": r.applied_total}))
}
fn export_csv(s: &mut Session, p: &Value) -> Result<Value> {
let what: String = super::req(p, "what")?;
let path = super::file_param(s, p, "path", fieldcraft_io::roots::Access::Write)?;
let (step, table) = match what.as_str() {
"probe" => {
let r = super::solve::probe(s, p)?;
(r.get("step").cloned().unwrap_or(Value::Null), probe_table(&r, &|label| s.model.node(label).map(|n| n.xyz))?)
}
"reactions" => {
let r = reactions(s, p)?;
if r.get("stale").and_then(Value::as_bool).unwrap_or(false) {
let step = r.get("step").and_then(Value::as_str).unwrap_or_default();
return Err(EngineError::Params(format!(
"the result of step `{step}` is stale (the model changed since it was solved); solve it again"
)));
}
(r.get("step").cloned().unwrap_or(Value::Null), reactions_table(&r))
}
_ => return Err(EngineError::Params("`what` must be \"probe\" or \"reactions\"".into())),
};
let text = table.csv();
fieldcraft_io::fs::write_atomic(std::path::Path::new(&path), text.as_bytes(), false)?;
Ok(json!({"path": path, "rows": table.rows.len(), "columns": table.header, "step": step, "units": s.model.units()}))
}
/// A table of cells (a number, text, or empty) under a header, written as CSV.
struct Table {
header: Vec<String>,
rows: Vec<Vec<Cell>>,
}
#[derive(Clone, Debug, PartialEq)]
enum Cell {
Number(f64),
Text(String),
Empty,
}
impl Table {
/// RFC 4180: comma-separated, CRLF line ends, a field with a comma, quote or line break in
/// quotes (its quotes doubled); numbers in Rust's shortest round-trip form.
fn csv(&self) -> String {
let field = |s: &str| if s.contains([',', '"', '\r', '\n']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() };
let mut out = String::new();
let line = |cells: Vec<String>, out: &mut String| {
out.push_str(&cells.join(","));
out.push_str("\r\n");
};
line(self.header.iter().map(|h| field(h)).collect(), &mut out);
for row in &self.rows {
let cells = row
.iter()
.map(|c| match c {
Cell::Number(v) => format!("{v}"),
Cell::Text(t) => field(t),
Cell::Empty => String::new(),
})
.collect();
line(cells, &mut out);
}
out
}
/// Rows of named cells into a table whose columns are every name that has a value, in the
/// order first met; a column no row has a value in is left out.
fn from_named(rows: Vec<Vec<(String, Cell)>>) -> Table {
let mut header: Vec<String> = Vec::new();
for row in &rows {
for (name, c) in row {
if *c != Cell::Empty && !header.contains(name) {
header.push(name.clone());
}
}
}
let rows = rows
.into_iter()
.map(|row| header.iter().map(|h| row.iter().find(|(n, _)| n == h).map_or(Cell::Empty, |(_, c)| c.clone())).collect())
.collect();
Table { header, rows }
}
}
/// The CSV columns of a quantity of a probe's node entry: a vector's components (and a
/// displacement's magnitude), a stress tensor's six components, a scalar under its own name.
fn quantity_cells(key: &str, v: &Value, out: &mut Vec<(String, Cell)>) {
const VECTORS: [(&str, &[&str]); 7] = [
("displacement", &["ux", "uy", "uz"]),
("rotation", &["rx", "ry", "rz"]),
("reaction", &["rfx", "rfy", "rfz"]),
("reaction_moment", &["rmx", "rmy", "rmz"]),
("velocity", &["vx", "vy", "vz"]),
("shape", &["ux", "uy", "uz", "rx", "ry", "rz"]),
("stress", &["s_xx", "s_yy", "s_zz", "s_xy", "s_xz", "s_yz"]),
];
match v {
Value::Number(n) => out.push((key.to_string(), n.as_f64().map_or(Cell::Empty, Cell::Number))),
Value::Array(items) if items.iter().all(Value::is_number) => {
let nums: Vec<f64> = items.iter().filter_map(Value::as_f64).collect();
let names: Vec<String> = match VECTORS.iter().find(|(k, _)| *k == key) {
Some((_, n)) if n.len() == nums.len() => n.iter().map(|s| (*s).to_string()).collect(),
_ => (1..=nums.len()).map(|i| format!("{key}_{i}")).collect(),
};
out.extend(names.into_iter().zip(nums.iter().map(|&x| Cell::Number(x))));
if key == "displacement" && nums.len() == 3 {
out.push(("u_mag".into(), Cell::Number(nums.iter().map(|x| x * x).sum::<f64>().sqrt())));
}
}
_ => {}
}
}
/// `solve.probe`'s reply as a table: a row per node with its label, undeformed position and
/// the quantities the step has.
fn probe_table(r: &Value, position: &dyn Fn(u32) -> Option<[f64; 3]>) -> Result<Table> {
let nodes = r.get("nodes").and_then(Value::as_array).ok_or_else(|| EngineError::Params("the probe has no node results to export".into()))?;
let rows = nodes
.iter()
.map(|e| {
let label = e.get("node").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
let mut row = vec![("node".to_string(), label.map_or(Cell::Empty, |l| Cell::Number(f64::from(l))))];
if let Some(name) = e.get("reference_point").and_then(Value::as_str) {
row.push(("reference_point".into(), Cell::Text(name.to_string())));
}
let xyz = label.and_then(position);
for (k, axis) in ["x", "y", "z"].iter().enumerate() {
row.push(((*axis).to_string(), xyz.and_then(|p| p.get(k).copied()).map_or(Cell::Empty, Cell::Number)));
}
if let Some(o) = e.as_object() {
for (k, v) in o.iter().filter(|(k, _)| !matches!(k.as_str(), "node" | "reference_point" | "xyz" | "distance")) {
quantity_cells(k, v, &mut row);
}
}
row
})
.collect();
Ok(Table::from_named(rows))
}
/// `results.reactions`' reply as a table: a row per set, the total and the applied load.
fn reactions_table(r: &Value) -> Table {
let row = |name: &str, e: &Value| {
let mut row = vec![("set".to_string(), Cell::Text(name.to_string()))];
row.push(("nodes".into(), e.get("nodes").and_then(Value::as_f64).map_or(Cell::Empty, Cell::Number)));
for (key, names) in [("force", ["fx", "fy", "fz"]), ("moment", ["mx", "my", "mz"])] {
let v = e.get(key).and_then(Value::as_array);
for (k, n) in names.iter().enumerate() {
row.push(((*n).to_string(), v.and_then(|a| a.get(k)).and_then(Value::as_f64).map_or(Cell::Empty, Cell::Number)));
}
}
row
};
let mut rows: Vec<Vec<(String, Cell)>> = r
.get("sets")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|e| row(e.get("set").and_then(Value::as_str).unwrap_or_default(), e))
.collect();
rows.push(row("total", r.get("total").unwrap_or(&Value::Null)));
if let Some(applied) = r.get("applied").filter(|a| a.is_array()) {
rows.push(row("applied", &json!({"force": applied})));
}
Table::from_named(rows)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -343,6 +557,103 @@ mod tests {
s
}
/// `range` clamps the legend (#191): kept with the field, cleared by "auto" or another
/// field, reported in the reply; the true range is still there.
/// A CSV reader (RFC 4180) for the tests: rows of fields, quotes undone.
fn read_csv(text: &str) -> Vec<Vec<String>> {
let (mut rows, mut row, mut field, mut quoted, mut chars) = (Vec::new(), Vec::new(), String::new(), false, text.chars().peekable());
while let Some(c) = chars.next() {
match (quoted, c) {
(true, '"') if chars.peek() == Some(&'"') => {
chars.next();
field.push('"');
}
(true, '"') => quoted = false,
(true, c) => field.push(c),
(false, '"') => quoted = true,
(false, ',') => row.push(std::mem::take(&mut field)),
(false, '\r') => {}
(false, '\n') => {
row.push(std::mem::take(&mut field));
rows.push(std::mem::take(&mut row));
}
(false, c) => field.push(c),
}
}
rows
}
fn temp_csv(tag: &str) -> String {
std::env::temp_dir().join(format!("fieldcraft-csv-{tag}-{}.csv", std::process::id())).to_string_lossy().into_owned()
}
/// `results.export.csv` writes what results.reactions and solve.probe reply, bit for bit
/// after parsing; a set name with a comma and a quote round-trips (#92).
#[test]
fn results_export_as_csv() {
let mut s = solved();
let path = temp_csv("reactions");
let sets = json!(["root", "tip"]);
let reply = s.execute("results.export.csv", &json!({"what": "reactions", "path": path, "step": "Bend", "sets": sets})).unwrap();
let sums = s.execute("results.reactions", &json!({"step": "Bend", "sets": sets})).unwrap();
let rows = read_csv(&std::fs::read_to_string(&path).unwrap());
assert_eq!(rows[0], ["set", "nodes", "fx", "fy", "fz", "mx", "my", "mz"]);
assert_eq!((reply["rows"].as_u64(), reply["step"].as_str()), (Some(4), Some("Bend")), "{reply}");
// A name with a comma and a quote round-trips through a CSV reader.
let named =
Table { header: vec!["set".into(), "fx".into()], rows: vec![vec![Cell::Text("the \"root\", clamped".into()), Cell::Number(0.1)]] };
assert_eq!(read_csv(&named.csv()), [vec!["set", "fx"], vec!["the \"root\", clamped", "0.1"]]);
let total = rows.iter().find(|r| r[0] == "total").unwrap();
assert_eq!(total[4].parse::<f64>().unwrap(), sums["total"]["force"][2].as_f64().unwrap(), "bit for bit");
let applied = rows.iter().find(|r| r[0] == "applied").unwrap();
assert_eq!((applied[1].as_str(), applied[5].as_str()), ("", ""), "the applied load has no nodes or moments");
let path = temp_csv("probe");
s.execute("results.export.csv", &json!({"what": "probe", "path": path, "step": "Bend", "nodes": [1, 2, 3]})).unwrap();
let probe = s.execute("solve.probe", &json!({"step": "Bend", "nodes": [1, 2, 3]})).unwrap();
let rows = read_csv(&std::fs::read_to_string(&path).unwrap());
assert_eq!(rows.len(), 4);
let col = |name: &str| rows[0].iter().position(|h| h == name).unwrap_or_else(|| panic!("no {name}: {:?}", rows[0]));
for (i, node) in probe["nodes"].as_array().unwrap().iter().enumerate() {
assert_eq!(rows[i + 1][col("node")], node["node"].to_string());
assert_eq!(rows[i + 1][col("uz")].parse::<f64>().unwrap(), node["displacement"][2].as_f64().unwrap());
assert_eq!(rows[i + 1][col("s_yz")].parse::<f64>().unwrap(), node["stress"][5].as_f64().unwrap());
assert_eq!(rows[i + 1][col("von_mises")].parse::<f64>().unwrap(), node["von_mises"].as_f64().unwrap());
}
assert!(!rows[0].iter().any(|h| h == "temperature"), "columns the step does not have are left out: {:?}", rows[0]);
// A stale result is refused.
// Every parameter the description names is taken: a set's nodes, points, a moment point.
let set = s.execute("results.export.csv", &json!({"what": "probe", "path": path, "step": "Bend", "set": "tip"})).unwrap();
assert!(set["rows"].as_u64().unwrap_or(0) > 0, "{set}");
s.execute("results.export.csv", &json!({"what": "probe", "path": path, "step": "Bend", "at": [[0, 0, 0]]})).unwrap();
s.execute("results.export.csv", &json!({"what": "reactions", "path": path, "step": "Bend", "about": [1, 0, 0]})).unwrap();
s.execute("mesh.node.add", &json!({"label": 99_999, "xyz": [0, 0, 0]})).unwrap();
assert!(s.execute("results.export.csv", &json!({"what": "reactions", "path": temp_csv("stale"), "step": "Bend"})).is_err());
for p in ["reactions", "probe"] {
let _ = std::fs::remove_file(temp_csv(p));
}
}
#[test]
fn the_legend_range_can_be_clamped() {
let mut s = solved();
let r = s.execute("results.contour", &json!({"field": "von_mises", "range": {"max": 10}})).unwrap();
let top = r["contour"]["range"]["max"]["value"].as_f64().unwrap();
assert!(top > 10.0, "{r}");
assert_eq!(r["contour"]["legend"], json!({"min": null, "max": 10.0}), "{r}");
let v = s.results_view.clone().unwrap();
let b = v.bands(0.0, top);
assert!(b.over && b.max == 10.0 && b.band(top) == Some(b.count));
s.execute("results.contour", &json!({"field": "von_mises", "bands": 6})).unwrap();
assert_eq!(s.results_view.as_ref().unwrap().range_max, Some(10.0), "kept with the field");
s.execute("results.contour", &json!({"field": "von_mises", "range": {"max": "auto", "min": 2}})).unwrap();
assert_eq!(s.results_view.as_ref().map(|v| (v.range_min, v.range_max)), Some((Some(2.0), None)));
s.execute("results.contour", &json!({"field": "displacement"})).unwrap();
assert_eq!(s.results_view.as_ref().map(|v| (v.range_min, v.range_max)), Some((None, None)), "another field follows its own range");
s.execute("results.contour", &json!({"field": "displacement", "range": {"max": 1e-3}})).unwrap();
let r = s.execute("results.contour", &json!({"field": "displacement", "range": "auto"})).unwrap();
assert!(r["contour"].get("legend").is_none(), "{r}");
}
#[test]
fn the_display_follows_the_commands_and_is_not_an_edit() {
let mut s = solved();
@@ -369,6 +680,13 @@ mod tests {
assert!(s.execute("results.contour", &json!({"field": "von_mises"})).is_err());
s.execute("results.contour", &json!({"field": "displacement", "bands": 6})).unwrap();
s.execute("results.animate", &json!({})).unwrap();
// Changing the field keeps the deformation, its scale and the animation (#332).
s.execute("results.deformed", &json!({"scale": 3})).unwrap();
let r = s.execute("results.contour", &json!({"step": "Modes", "field": "displacement_z"})).unwrap();
assert_eq!(
(r["view"]["deformed"].as_bool(), r["view"]["scale"].as_f64(), r["view"]["animate"].as_bool()),
(Some(true), Some(3.0), Some(true))
);
assert!(s.results_view.as_ref().is_some_and(|v| v.animate && v.bands == 6));
s.execute("results.animate", &json!({"on": false})).unwrap();
assert!(s.results_view.as_ref().is_some_and(|v| !v.animate));
@@ -398,6 +716,8 @@ mod tests {
let r = s.execute("results.reactions", &json!({"sets": ["root", "tip"], "about": [10, 0, 0]})).unwrap();
assert!(r["sets"][0]["moment"][1].as_f64().unwrap().abs() < 1e-6, "{r}");
assert_eq!(r["sets"][1]["force"][2].as_f64(), Some(0.0));
let empty = s.execute("results.reactions", &json!({"sets": []})).unwrap();
assert_eq!(empty["sets"][0]["set"], "root", "an empty list sums the step's boundary-condition sets: {empty}");
assert!(s.execute("results.reactions", &json!({"step": "Modes"})).is_err());
assert!(s.execute("results.reactions", &json!({"sets": ["nope"]})).is_err());
}
@@ -440,6 +760,17 @@ mod tests {
json!({"field": 3, "bands": 1e300}),
json!({"field": "von_mises", "bands": 0}),
json!({"field": "von_mises", "bands": 25}),
json!({"field": "von_mises", "range": {"max": "high"}}),
json!({"field": "von_mises", "range": {"min": 5, "max": 5}}),
json!({"field": "von_mises", "range": {"min": 1e308, "max": -1e308}}),
json!({"field": "von_mises", "range": 7}),
json!({"what": 7, "path": "x.csv"}),
json!({"what": "probe"}),
json!({"what": "probe", "path": "", "nodes": [1]}),
json!({"what": "probe", "path": "/no/such/dir/x.csv", "nodes": [1]}),
json!({"what": "probe", "path": "x.csv", "nodes": vec![1; 1_000_000]}),
json!({"what": "reactions", "path": "x.csv", "step": "Modes"}),
json!({"what": "reactions", "path": "x.csv", "step": "Nope"}),
json!({"scale": -1}),
json!({"scale": -0.0001}),
json!({"scale": 1e300}),
+234 -22
View File
@@ -30,7 +30,7 @@ pub const RUN: CommandSpec = CommandSpec {
pub const STATIC: CommandSpec = CommandSpec {
id: "solve.static",
label: "Solve Static Step",
params: r#"{"step": "Load", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — solves a linear static or coupled temperature–displacement step (the only one when `step` is left out) and keeps the result in the session; the caps may only be lowered; `threads` (1 to 256, by default the session's: `FIELDCRAFT_THREADS` or the cores) changes only the time, never the result"#,
params: r#"{"step": "Load", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — solves a linear static or coupled temperature–displacement step (the only one when `step` is left out) and keeps the result in the session; `max_dofs` may only be lowered; `max_factor_entries` defaults to 400000000 and may be deliberately raised up to 2000000000 (8 bytes per factor value; indices and workspace are additional); `threads` (1 to 256, by default the session's: `FIELDCRAFT_THREADS` or the cores) changes only the time, never the result"#,
form: Some(super::forms::SOLVE_STATIC),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
@@ -40,7 +40,7 @@ pub const STATIC: CommandSpec = CommandSpec {
pub const NONLINEAR: CommandSpec = CommandSpec {
id: "solve.nonlinear",
label: "Solve Nonlinear Static Step",
params: r#"{"step": "Inflate", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_newton_iterations": 100000, "threads": 8} — solves a nonlinear static step (the only one when `step` is left out) in load increments with Newton–Raphson iterations and keeps the result in the session: the final displacements, reactions, Cauchy stresses and logarithmic strains (small strains without nonlinear geometry), the equivalent plastic strain of plastic materials (the largest in the summary), every increment's load factor, iterations and residuals (force, displacement and energy, relative to their tolerances' scales), and a displacement frame per converged increment, and with contact pairs (interaction.contact.pair: mortar contact by augmented Lagrangian, Coulomb friction by a return map) each contact's force, normal force, largest pressure, closed and slipping nodes, deepest penetration and augmentations (solve.probe gives each secondary node's pressure, gap and status, and with friction its shear traction and slip); the caps may only be lowered (`max_newton_iterations` over the whole step); `threads` as for solve.static"#,
params: r#"{"step": "Inflate", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_newton_iterations": 100000, "threads": 8} — solves a nonlinear static step (the only one when `step` is left out) in load increments with Newton–Raphson iterations and keeps the result in the session: the final displacements, reactions, Cauchy stresses and logarithmic strains (small strains without nonlinear geometry), the equivalent plastic strain of plastic materials (the largest in the summary), every increment's load factor, iterations and residuals (force, displacement and energy, relative to their tolerances' scales), and a displacement frame per converged increment, and with contact pairs (interaction.contact.pair: mortar contact by augmented Lagrangian, Coulomb friction by a return map) each contact's force, normal force, largest pressure, closed and slipping nodes, deepest penetration and augmentations (solve.probe gives each secondary node's pressure, gap and status, and with friction its shear traction and slip); `max_dofs` and `max_newton_iterations` may only be lowered (the latter over the whole step); `max_factor_entries` and `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_NONLINEAR),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
@@ -50,7 +50,7 @@ pub const NONLINEAR: CommandSpec = CommandSpec {
pub const HEAT: CommandSpec = CommandSpec {
id: "solve.heat",
label: "Solve Heat Transfer Step",
params: r#"{"step": "Heat", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — steady or transient heat conduction of a heat transfer step (the only one when `step` is left out): temperatures, heat flux and the heat flow at prescribed temperatures, kept in the session; the caps may only be lowered; `threads` as for solve.static"#,
params: r#"{"step": "Heat", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — steady or transient heat conduction of a heat transfer step (the only one when `step` is left out): temperatures, heat flux and the heat flow at prescribed temperatures, kept in the session; `max_dofs` may only be lowered; `max_factor_entries` and `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_STATIC),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
@@ -60,7 +60,7 @@ pub const HEAT: CommandSpec = CommandSpec {
pub const FREQUENCY: CommandSpec = CommandSpec {
id: "solve.frequency",
label: "Solve Frequency Step",
params: r#"{"step": "Modes", "mass": "consistent|lumped", "shift": 0.0, "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — natural frequencies and mode shapes of a frequency step (its modes and range); `max_iterations` caps the Lanczos vectors; the result stays in the session; `threads` as for solve.static"#,
params: r#"{"step": "Modes", "mass": "consistent|lumped", "shift": 0.0, "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — natural frequencies and mode shapes of a frequency step (its modes and range); `max_iterations` caps the Lanczos vectors; the result stays in the session; `max_factor_entries` and `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_FREQUENCY),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
@@ -70,7 +70,7 @@ pub const FREQUENCY: CommandSpec = CommandSpec {
pub const BUCKLE: CommandSpec = CommandSpec {
id: "solve.buckle",
label: "Solve Buckling Step",
params: r#"{"step": "Buckle", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — linear buckling of a buckling step (the only one when `step` is left out): the step's loads as a linear preload, then the lowest load factors λ with (K + λ K_σ) φ = 0 and their mode shapes (largest component 1), or those above the step's shift (whose LDLᵀ factor counts the load factors below it); negative load factors found are reported; the result stays in the session and its modes display like frequency modes; `threads` as for solve.static"#,
params: r#"{"step": "Buckle", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — linear buckling of a buckling step (the only one when `step` is left out): the step's loads as a linear preload, then the lowest load factors λ with (K + λ K_σ) φ = 0 and their mode shapes (largest component 1), or those above the step's shift (whose LDLᵀ factor counts the load factors below it); negative load factors found are reported; the result stays in the session and its modes display like frequency modes; `max_factor_entries` and `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_BUCKLE),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
@@ -117,6 +117,9 @@ pub const PROBE: CommandSpec = CommandSpec {
run: probe,
};
/// Largest explicit factor cap accepted by solve commands; the default remains 400M entries.
pub(super) const FACTOR_ENTRY_CEILING: usize = 2_000_000_000;
/// Most nodes one probe lists.
const MAX_PROBE: usize = 10_000;
@@ -154,7 +157,11 @@ fn threads(s: &Session, p: &Value) -> Result<usize> {
fn limits(p: &Value) -> Result<Limits> {
Ok(Limits {
max_dofs: cap(p, "max_dofs", Limits::MAX_DOFS)?,
max_factor_entries: cap(p, "max_factor_entries", Limits::MAX_FACTOR_ENTRIES)?,
max_factor_entries: if p.get("max_factor_entries").is_none() {
Limits::MAX_FACTOR_ENTRIES
} else {
cap(p, "max_factor_entries", FACTOR_ENTRY_CEILING)?
},
max_lanczos_vectors: cap(p, "max_iterations", Limits::MAX_LANCZOS_VECTORS)?,
max_newton_iterations: cap(p, "max_newton_iterations", Limits::MAX_NEWTON_ITERATIONS)?,
})
@@ -168,6 +175,12 @@ fn extreme(values: impl Iterator<Item = (u32, f64)>, better: fn(f64, f64) -> boo
}
}
/// [`parallel::with_threads`], the caller's progress reporter carried onto the pool's thread.
fn with_threads<R: Send>(threads: usize, f: impl FnOnce() -> R + Send) -> R {
let progress = fieldcraft_model::progress::current();
parallel::with_threads(threads, move || fieldcraft_model::progress::scoped(progress, f))
}
fn run_all(s: &mut Session, _: &Value) -> Result<Value> {
use fieldcraft_model::Procedure;
type Solve = fn(&mut Session, &Value) -> Result<Value>;
@@ -192,13 +205,30 @@ fn run_all(s: &mut Session, _: &Value) -> Result<Value> {
return Err(EngineError::Params("the model has no steps to solve: add one (model.step.create)".into()));
}
let mut done = Vec::new();
for (name, procedure, solve) in steps {
let summary = solve(s, &json!({"step": name})).map_err(|e| EngineError::Params(format!("step `{name}`: {e}")))?;
let count = steps.len();
for (index, (name, procedure, solve)) in steps.into_iter().enumerate() {
fieldcraft_model::progress::step(&name, index + 1, count);
fieldcraft_model::progress::check()?;
let summary =
solve(s, &json!({"step": name})).map_err(|e| if e.is_cancelled() { e } else { EngineError::Params(format!("step `{name}`: {e}")) })?;
done.push(json!({"step": name, "procedure": procedure, "summary": summary}));
}
Ok(json!({"steps": done}))
}
/// A sum of nodal values with its round-off set to 0: a component below a billionth of the sum
/// of the terms' magnitudes is what cancelling left (a balanced load sums to ~1e-11, not 0).
fn settled(total: [f64; 3], terms: &[[f64; 3]]) -> [f64; 3] {
let mut out = total;
for (k, c) in out.iter_mut().enumerate() {
let scale: f64 = terms.iter().filter_map(|t| t.get(k)).map(|x| x.abs()).filter(|x| x.is_finite()).sum();
if c.abs() <= 1e-9 * scale {
*c = 0.0;
}
}
out
}
fn largest(values: impl Iterator<Item = (u32, f64)>) -> Value {
extreme(values, |v, b| v > b)
}
@@ -211,7 +241,7 @@ fn run_static(s: &mut Session, p: &Value) -> Result<Value> {
let limits = limits(p)?;
let step = opt::<String>(p, "step")?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || solve_static(model, step.as_deref(), &limits))?;
let r = with_threads(threads(s, p)?, || solve_static(model, step.as_deref(), &limits))?;
let summary = json!({
"step": r.step,
@@ -220,8 +250,8 @@ fn run_static(s: &mut Session, p: &Value) -> Result<Value> {
"factor_entries": r.stats.factor_entries,
"max_displacement": largest(r.nodes.iter().zip(&r.displacement).map(|(l, u)| (*l, crate::results::magnitude(*u)))),
"max_von_mises": largest(r.nodes.iter().zip(&r.von_mises).map(|(l, v)| (*l, *v))),
"applied_total": r.applied_total,
"reaction_total": r.reaction_total,
"applied_total": settled(r.applied_total, &r.reaction),
"reaction_total": settled(r.reaction_total, &r.reaction),
"reference_points": r.reference_points.iter().map(|p| json!({
"name": p.name,
"label": p.label,
@@ -239,7 +269,7 @@ fn run_nonlinear(s: &mut Session, p: &Value) -> Result<Value> {
let limits = limits(p)?;
let step = opt::<String>(p, "step")?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || solve_nonlinear(model, step.as_deref(), &limits))?;
let r = with_threads(threads(s, p)?, || solve_nonlinear(model, step.as_deref(), &limits))?;
let history = r.nonlinear.as_ref();
let summary = json!({
"step": r.step,
@@ -264,8 +294,8 @@ fn run_nonlinear(s: &mut Session, p: &Value) -> Result<Value> {
"max_displacement": largest(r.nodes.iter().zip(&r.displacement).map(|(l, u)| (*l, crate::results::magnitude(*u)))),
"max_von_mises": largest(r.nodes.iter().zip(&r.von_mises).map(|(l, v)| (*l, *v))),
"max_plastic_strain": largest(r.elements.iter().flat_map(|e| e.plastic_strain.iter().map(|v| (e.label, *v)))),
"applied_total": r.applied_total,
"reaction_total": r.reaction_total,
"applied_total": settled(r.applied_total, &r.reaction),
"reaction_total": settled(r.reaction_total, &r.reaction),
"reference_points": r.reference_points.iter().map(|p| json!({
"name": p.name,
"label": p.label,
@@ -282,7 +312,7 @@ fn run_heat(s: &mut Session, p: &Value) -> Result<Value> {
let limits = limits(p)?;
let step = opt::<String>(p, "step")?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || solve_heat(model, step.as_deref(), &limits))?;
let r = with_threads(threads(s, p)?, || solve_heat(model, step.as_deref(), &limits))?;
let t = r.temperature();
let summary = json!({
"step": r.step,
@@ -295,6 +325,7 @@ fn run_heat(s: &mut Session, p: &Value) -> Result<Value> {
"max_temperature": largest(r.nodes.iter().copied().zip(t.iter().copied())),
"heat_supplied": r.applied_total,
"heat_removed": r.reaction_total,
"heat_flows": crate::results::heat_flows(&r),
"warnings": r.warnings,
});
s.store_result(StepResult::Implicit(ImplicitResult::Heat(r)));
@@ -307,7 +338,7 @@ fn run_frequency(s: &mut Session, p: &Value) -> Result<Value> {
let mass = opt::<MassKind>(p, "mass")?.unwrap_or_default();
let shift = opt::<f64>(p, "shift")?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || solve_frequency(model, step.as_deref(), &FrequencyOptions { mass, shift }, &limits))?;
let r = with_threads(threads(s, p)?, || solve_frequency(model, step.as_deref(), &FrequencyOptions { mass, shift }, &limits))?;
let summary = json!({
"step": r.step,
"dofs": r.stats.dofs,
@@ -330,7 +361,7 @@ fn run_buckle(s: &mut Session, p: &Value) -> Result<Value> {
let limits = limits(p)?;
let step = opt::<String>(p, "step")?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || solve_buckle(model, step.as_deref(), &limits))?;
let r = with_threads(threads(s, p)?, || solve_buckle(model, step.as_deref(), &limits))?;
let summary = json!({
"step": r.step,
"dofs": r.stats.dofs,
@@ -354,7 +385,7 @@ fn run_explicit(s: &mut Session, p: &Value) -> Result<Value> {
};
let step = opt::<String>(p, "step")?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || solve_explicit(model, step.as_deref(), &limits))?;
let r = with_threads(threads(s, p)?, || solve_explicit(model, step.as_deref(), &limits))?;
let summary = explicit_summary(&r);
s.store_result(StepResult::Explicit(r));
Ok(summary)
@@ -459,7 +490,7 @@ fn run_fluid(s: &mut Session, p: &Value) -> Result<Value> {
let (_, domain) = fieldcraft_lbm::fluid_step(&s.model, step.as_deref())?;
let obstacles = obstacles(s, domain)?;
let model = &s.model;
let r = parallel::with_threads(threads(s, p)?, || fieldcraft_lbm::solve_fluid(model, step.as_deref(), &obstacles, &limits))?;
let r = with_threads(threads(s, p)?, || fieldcraft_lbm::solve_fluid(model, step.as_deref(), &obstacles, &limits))?;
let summary = fluid_summary(&r);
s.store_result(StepResult::Fluid(r));
Ok(summary)
@@ -541,7 +572,7 @@ fn probe_fluid(r: &FluidResult, p: &Value) -> Result<Value> {
Ok(json!({"step": r.step, "frame": frame, "time": time, "points": out}))
}
fn probe(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn probe(s: &mut Session, p: &Value) -> Result<Value> {
let step = opt::<String>(p, "step")?.ok_or_else(|| EngineError::param("step", ProblemKind::Required))?;
let result = s.result(&step).ok_or_else(|| {
EngineError::Params(if s.latest_result(&step).is_some() {
@@ -897,6 +928,76 @@ pub(crate) mod tests {
assert!(e.contains("stale"), "{e}");
}
#[test]
fn factor_cap_can_be_raised_deliberately_to_a_finite_ceiling() {
assert_eq!(limits(&json!({})).unwrap(), Limits::default());
for entries in [1, 400_000_000, 400_000_001, 467_000_000, 2_000_000_000] {
assert_eq!(limits(&json!({"max_factor_entries": entries})).unwrap().max_factor_entries, entries);
}
for entries in
[json!(null), json!(true), json!("467000000"), json!(-1), json!(0), json!(2.5), json!(2_000_000_001u64), json!(u64::MAX), json!(1e300)]
{
assert!(limits(&json!({"max_factor_entries": entries})).is_err(), "{entries}");
}
for params in [
json!({"max_dofs": Limits::MAX_DOFS + 1}),
json!({"max_iterations": Limits::MAX_LANCZOS_VECTORS + 1}),
json!({"max_newton_iterations": Limits::MAX_NEWTON_ITERATIONS + 1}),
] {
assert!(limits(&params).is_err(), "{params}");
}
for id in ["solve.static", "solve.nonlinear", "solve.heat", "solve.frequency", "solve.buckle"] {
let schema = crate::schema::json_schema(crate::find_command(id).unwrap().form.unwrap());
let factor = &schema["properties"]["max_factor_entries"];
assert_eq!(factor["minimum"], 1, "{id}: {factor}");
assert_eq!(factor["maximum"], 2_000_000_000u64, "{id}: {factor}");
}
}
#[test]
fn raised_factor_caps_solve_small_models_and_failures_keep_results() {
let mut s = Session::default();
cantilever(&mut s);
s.run_script(&json!([
{"command": "model.section.edit", "params": {"name": "bar", "set": "all", "material": "Mat", "kind": {"type": "solid"}, "formulation": {}}},
{"command": "model.step.create", "params": {"name": "Nonlinear", "procedure": {"type": "nonlinear_static", "nonlinear_geometry": false}, "boundary_conditions": ["clamp"], "loads": ["push"]}},
{"command": "model.load.create", "params": {"name": "compress", "type": "force", "target": {"set": "tip"}, "vector": [-1, 0, 0]}},
{"command": "model.step.create", "params": {"name": "Buckle", "procedure": {"type": "buckle", "modes": 1}, "boundary_conditions": ["clamp"], "loads": ["compress"]}},
{"command": "model.material.edit", "params": {"name": "Mat", "elastic": {"type": "isotropic", "young": 1000, "poisson": 0}, "density": 1, "thermal": {"conductivity": 2}}},
{"command": "model.boundary_condition.create", "params": {"name": "cold", "type": "temperature", "target": {"set": "root"}, "value": 0}},
{"command": "model.boundary_condition.create", "params": {"name": "hot", "type": "temperature", "target": {"set": "tip"}, "value": 100}},
{"command": "model.step.create", "params": {"name": "Heat", "procedure": {"type": "heat_transfer"}, "boundary_conditions": ["cold", "hot"]}},
])).unwrap();
for (command, step) in [
("solve.static", "Bend"),
("solve.nonlinear", "Nonlinear"),
("solve.heat", "Heat"),
("solve.frequency", "Modes"),
("solve.buckle", "Buckle"),
] {
let expected = s.execute(command, &json!({"step": step})).unwrap();
let probe_params = json!({"step": step, "nodes": [6]});
let probe = s.execute("solve.probe", &probe_params).unwrap();
for entries in [400_000_001, 467_000_000, 2_000_000_000] {
assert_eq!(s.execute(command, &json!({"step": step, "max_factor_entries": entries})).unwrap(), expected);
assert_eq!(s.execute("solve.probe", &probe_params).unwrap(), probe);
}
let before = s.model.clone();
let results = s.solved_steps().count();
let journal = s.journal.len();
for entries in [json!(1), json!(0), json!(-1), json!(2.5), json!(null), json!(2_000_000_001u64), json!(u64::MAX)] {
let e = s.execute(command, &json!({"step": step, "max_factor_entries": entries})).unwrap_err().to_string();
if entries == 1 {
assert!(e.contains("bytes of factor values alone") && e.contains("limit is 1 entries"), "{command}: {e}");
}
assert_eq!(s.model, before, "{command}: {entries}");
assert_eq!(s.solved_steps().count(), results);
assert_eq!(s.journal.len(), journal);
assert_eq!(s.execute("solve.probe", &probe_params).unwrap(), probe);
}
}
}
#[test]
fn solve_hostile_params_never_panic() {
let mut s = Session::default();
@@ -1388,8 +1489,8 @@ pub(crate) mod tests {
s.execute("model.step.create", &json!({"name": "Long", "procedure": long})).unwrap();
assert!(s.execute("solve.explicit", &json!({"step": "Long"})).unwrap_err().to_string().contains("increments"));
assert!(s.execute("model.set.delete", &json!({"name": "all_nodes"})).unwrap_err().to_string().contains("step `Impact`"));
// Defining steps edited the model, so the impact result is stale.
assert_eq!(s.solved_steps().count(), 0);
// Defining other steps left what the impact step reads alone: its result is current.
assert_eq!(s.solved_steps().collect::<Vec<_>>(), ["Impact"]);
}
/// A mass on a spring and a dashpot, defined, solved and written through commands; editing
@@ -1469,6 +1570,30 @@ pub(crate) mod tests {
}
}
/// A heat balance per load: the convection `Air` carries away what the heater's prescribed
/// temperature supplies (#362).
#[test]
fn heat_flows_balance_per_load() {
let mut s = Session::default();
cantilever(&mut s);
let script = json!([
{"command": "model.material.edit", "params": {"name": "Mat", "elastic": {"type": "isotropic", "young": 1000, "poisson": 0}, "density": 1, "thermal": {"conductivity": 2}}},
{"command": "model.boundary_condition.create", "params": {"name": "Heater", "type": "temperature", "target": {"set": "root"}, "value": 100}},
{"command": "model.set.create", "params": {"name": "skin", "faces": (1..=6).map(|f| json!({"element": 10, "face": f})).collect::<Vec<_>>()}},
{"command": "model.load.create", "params": {"name": "Air", "type": "convection", "set": "skin", "film": 0.5, "sink": 20}},
{"command": "model.step.create", "params": {"name": "Therm", "procedure": {"type": "heat_transfer"}, "boundary_conditions": ["Heater"], "loads": ["Air"]}},
]);
s.run_script(&script).unwrap();
let r = s.execute("solve.heat", &json!({"step": "Therm"})).unwrap();
let flows = &r["heat_flows"];
let air = flows["loads"].as_array().unwrap().iter().find(|l| l["name"] == "Air").unwrap();
assert_eq!(air["type"], "convection");
let (out, supplied) = (air["heat"].as_f64().unwrap(), flows["reactions"].as_f64().unwrap());
assert!(out < 0.0 && supplied > 0.0, "{flows}");
assert!(flows["imbalance"].as_f64().unwrap().abs() < 1e-6 * supplied, "{flows}");
assert_eq!(s.results_report()["heat_flows"], *flows);
}
#[test]
fn solve_heat_and_probe_temperatures() {
// The cantilever bar as a conductor: 0 at the root, 100 at the tip, linear between.
@@ -1633,4 +1758,91 @@ pub(crate) mod tests {
let v = s.execute("results.contour", &json!({"step": "Squeeze", "field": "contact_shear"})).unwrap();
assert!(v["contour"]["range"]["max"]["value"].as_f64().unwrap() > 1.0, "{v}");
}
/// A chip with a pad on it, both in a pocket of air (tet4), the chip and pad hex8 at other
/// sizes: tie `air` holds the chip's and the pad's sides on the air, tie `chip` the pad's
/// underside on the chip. The pad's bottom edge is on both ties' secondary surfaces, and the
/// chip's top edge, the main nodes there, follows the air: two constraints per edge node that
/// nearly repeat each other.
fn chip_pad_air(s: &mut Session) {
let (_dir, opened) = super::super::datum::tests::scripted(json!([
{"command": "solid.box", "params": {"length": 20, "width": 20, "height": 6, "corner": [0, 0, 0], "body_name": "Air"}},
{"command": "solid.box", "params": {"length": 8, "width": 8, "height": 3, "corner": [6, 6, 0], "operation": "cut"}},
{"command": "solid.box", "params": {"length": 8, "width": 8, "height": 2, "corner": [6, 6, 0], "operation": "new_body", "body_name": "Chip"}},
{"command": "solid.box", "params": {"length": 8, "width": 8, "height": 1, "corner": [6, 6, 2], "operation": "new_body", "body_name": "Pad"}},
]));
*s = opened;
std::mem::forget(_dir);
s.execute("mesh.tet.generate", &json!({"body": "Air", "size": 2.0})).unwrap();
s.execute("mesh.hex.generate", &json!({"body": "Chip", "size": 0.8})).unwrap();
s.execute("mesh.hex.generate", &json!({"body": "Pad", "size": 0.45})).unwrap();
let m = &s.model;
// Element faces of a body all of whose nodes satisfy `on`.
let faces = |body: &str, on: &dyn Fn([f64; 3]) -> bool| -> Vec<Value> {
m.body_elements(body)
.into_iter()
.flat_map(|e| (1..=m.element(e).unwrap().kind.faces().len() as u8).map(move |f| (e, f)))
.filter(|&(e, f)| {
let ns = m.face_nodes(fieldcraft_model::ElementFace { element: e, face: f }).unwrap();
ns.iter().all(|n| on(m.node(*n).unwrap().xyz))
})
.map(|(e, f)| json!({"element": e, "face": f}))
.collect()
};
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
let side = |p: [f64; 3]| near(p[0], 6.0) || near(p[0], 14.0) || near(p[1], 6.0) || near(p[1], 14.0);
let pocket = |p: [f64; 3]| {
(side(p) && p[2] < 3.0 + 1e-6 && (6.0 - 1e-6..=14.0 + 1e-6).contains(&p[0]) && (6.0 - 1e-6..=14.0 + 1e-6).contains(&p[1]))
|| (near(p[2], 3.0) && (6.0 - 1e-6..=14.0 + 1e-6).contains(&p[0]) && (6.0 - 1e-6..=14.0 + 1e-6).contains(&p[1]))
};
let outer = |p: [f64; 3]| near(p[0], 0.0) || near(p[0], 20.0) || near(p[1], 0.0) || near(p[1], 20.0) || near(p[2], 6.0);
let mut sides = faces("Chip", &|p| side(p));
sides.extend(faces("Pad", &|p| side(p)));
let script = json!([
{"command": "model.set.create", "params": {"name": "all", "elements": m.elements().keys().collect::<Vec<_>>()}},
{"command": "model.set.create", "params": {"name": "chip", "elements": m.body_elements("Chip")}},
{"command": "model.set.create", "params": {"name": "pocket", "faces": faces("Air", &pocket)}},
{"command": "model.set.create", "params": {"name": "sides", "faces": sides}},
{"command": "model.set.create", "params": {"name": "chip_top", "faces": faces("Chip", &|p| near(p[2], 2.0))}},
{"command": "model.set.create", "params": {"name": "pad_bottom", "faces": faces("Pad", &|p| near(p[2], 2.0))}},
{"command": "model.set.create", "params": {"name": "outside", "faces": faces("Air", &outer)}},
{"command": "model.material.create", "params": {"name": "M", "elastic": {"type": "isotropic", "young": 1000, "poisson": 0.3}, "thermal": {"conductivity": 0.5}}},
{"command": "model.section.create", "params": {"name": "S", "set": "all", "material": "M", "kind": {"type": "solid"}}},
{"command": "interaction.tie", "params": {"name": "air", "main": "pocket", "secondary": "sides", "position_tolerance": 0.1}},
{"command": "interaction.tie", "params": {"name": "chip", "main": "chip_top", "secondary": "pad_bottom", "position_tolerance": 0.1}},
{"command": "model.load.create", "params": {"name": "Q", "type": "heat_source", "set": "chip", "power": 1}},
{"command": "model.load.create", "params": {"name": "Room", "type": "convection", "set": "outside", "film": 0.01, "sink": 25}},
{"command": "model.step.create", "params": {"name": "Steady", "procedure": {"type": "heat_transfer"}, "loads": ["Q", "Room"]}},
]);
s.run_script(&script).unwrap();
}
/// #389: a node on the secondary surfaces of two ties follows their main surfaces together,
/// so the heat balances to round-off and no temperature drops below the surroundings'. (With
/// a constraint per tie, this model put 335 W more in than the 128 W supplied, and some
/// temperatures below 0.)
#[test]
fn nodes_in_two_ties_keep_the_heat_balance() {
let mut s = Session::default();
chip_pad_air(&mut s);
let r = s.execute("solve.heat", &json!({"step": "Steady"})).unwrap();
let flows = &r["heat_flows"];
let supplied = flows["loads"].as_array().unwrap().iter().find(|l| l["name"] == "Q").unwrap()["heat"].as_f64().unwrap();
assert!((supplied - 128.0).abs() < 1e-9, "{flows}");
assert!(flows["imbalance"].as_f64().unwrap().abs() < 1e-9 * supplied, "{flows}");
assert!(r["min_temperature"]["value"].as_f64().unwrap() > 25.0, "{r}");
let warnings = r["warnings"].to_string();
assert!(warnings.contains("ties `air`, `chip`"), "{warnings}");
}
/// Two ties on one interface in opposite directions hold every node there twice: an error
/// naming both, not a field.
#[test]
fn ties_both_ways_on_one_interface_are_an_error_naming_them() {
let mut s = Session::default();
chip_pad_air(&mut s);
s.execute("interaction.tie", &json!({"name": "back", "main": "pad_bottom", "secondary": "chip_top", "position_tolerance": 0.1})).unwrap();
let e = s.execute("solve.heat", &json!({"step": "Steady"})).unwrap_err().to_string();
assert!(e.contains("tie `back`") && e.contains("tie `chip`"), "{e}");
}
}
+1 -5
View File
@@ -29,11 +29,7 @@ const ON_PLANE: f64 = 1e-6;
fn symmetry(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?.to_string();
let datum: String = super::req(p, "datum")?;
let (point, normal) = s
.model
.datum(&datum)
.and_then(|d| d.plane())
.ok_or_else(|| EngineError::Params(format!("no datum plane `{}`", datum.chars().take(64).collect::<String>())))?;
let (point, normal) = super::datum::datum_plane_of(&s.model, &datum)?;
let axis = (0..3).find(|&k| (normal[k].abs() - 1.0).abs() < 1e-9).ok_or_else(|| {
EngineError::Params(format!("not supported yet: symmetry about a plane not normal to X, Y or Z (datum `{datum}` has normal {normal:?})"))
})?;
+59
View File
@@ -0,0 +1,59 @@
//! `app.update.check`: is a newer FieldCraft published? The same check as the desktop app's
//! Help › Check for Updates and `fieldcraft-cli update --check` (docs/updates.md). It only
//! reports: nothing is downloaded or installed, and no dialog opens.
//!
//! Checking reaches the network, so it is switched on only by the programs that may
//! ([`enable_checks`]: the desktop app and the CLI); everywhere else (tests, scratch sessions,
//! the browser) the command refuses without asking anything.
use std::sync::atomic::{AtomicBool, Ordering};
use serde_json::Value;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const CHECK: CommandSpec = CommandSpec {
id: "app.update.check",
label: "Check for Updates",
params: r#"{} — asks GitHub Releases for the latest published FieldCraft release and compares it with this version: current, latest, newer, url (its page and release notes), published, signed (whether it can be verified and installed from the app) and asset (the file this install would download; null when it cannot update itself). Reports only: nothing is downloaded or installed. Desktop app and fieldcraft-cli only"#,
form: Some(&[]),
kind: CommandKind::Session,
requires: &[],
run: check,
};
static ENABLED: AtomicBool = AtomicBool::new(false);
/// Let `app.update.check` reach the release server (the desktop app and the CLI do).
pub fn enable_checks(on: bool) {
ENABLED.store(on, Ordering::SeqCst);
}
#[cfg(target_arch = "wasm32")]
fn check(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Params("not in the browser: the web app offers Reload to update when a new version is deployed".into()))
}
#[cfg(not(target_arch = "wasm32"))]
fn check(_: &mut Session, _: &Value) -> Result<Value> {
if !ENABLED.load(Ordering::SeqCst) {
return Err(EngineError::Params("update checks are off in this session (the desktop app and fieldcraft-cli check for updates)".into()));
}
let check = fieldcraft_update::net::Client::from_env().check().map_err(|e| EngineError::Params(e.to_string()))?;
let asset = fieldcraft_update::install::here().asset_name(&check.latest.version, std::env::consts::ARCH);
Ok(check.to_json(asset.as_deref()))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
/// Off unless a program switches it on: tests and scratch sessions never reach the network.
#[test]
fn checks_are_off_unless_enabled() {
let e = Session::default().execute("app.update.check", &json!({})).unwrap_err();
assert!(e.to_string().contains("update checks are off"), "{e}");
}
}
+239
View File
@@ -0,0 +1,239 @@
//! What the viewport hides: `view.hide`, `view.show`, `view.isolate` and `view.show_all`.
//!
//! The hidden items (bodies, imported surfaces, datums, boundary conditions, loads, reference
//! points, couplings) are view state ([`fieldcraft_io::View`]): saved with the model and marking
//! it unsaved, but not a definition, so they are neither journalled nor undone and they leave
//! results current. A hidden item is not drawn, so it cannot be picked either. An item that goes
//! away (deleted, or a body cut into cells) is forgotten.
use std::collections::BTreeSet;
use fieldcraft_io::{Item, ItemKind, MAX_HIDDEN};
use serde_json::Value;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const HIDE: CommandSpec = CommandSpec {
id: "view.hide",
label: "Hide",
params: concat!(
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
" — hides the items in the viewport (and from picking); view state, saved with the model"
),
form: Some(super::forms::VIEW_ITEMS),
kind: CommandKind::Session,
requires: &[],
run: |s, p| change(s, p, Change::Hide),
};
pub const SHOW: CommandSpec = CommandSpec {
id: "view.show",
label: "Show",
params: concat!(
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
" — shows hidden items again"
),
form: Some(super::forms::VIEW_ITEMS),
kind: CommandKind::Session,
requires: &[],
run: |s, p| change(s, p, Change::Show),
};
pub const ISOLATE: CommandSpec = CommandSpec {
id: "view.isolate",
label: "Isolate",
params: concat!(
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
" — shows only these items: every other one is hidden (view.show_all brings them back)"
),
form: Some(super::forms::VIEW_ITEMS),
kind: CommandKind::Session,
requires: &[],
run: |s, p| change(s, p, Change::Isolate),
};
pub const SHOW_ALL: CommandSpec = CommandSpec {
id: "view.show_all",
label: "Show All",
params: "{}",
form: Some(&[]),
kind: CommandKind::Session,
requires: &[],
run: |s, _| {
s.view.hidden.clear();
Ok(Value::Null)
},
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Change {
Hide,
Show,
Isolate,
}
/// Every item of `kind` the session has, by name.
pub(crate) fn names(s: &Session, kind: ItemKind) -> Vec<String> {
let m = &s.model;
match kind {
ItemKind::Body => s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect(),
ItemKind::Surface => s.surfaces.iter().map(|x| x.name.clone()).collect(),
ItemKind::Datum => m.datums().keys().cloned().collect(),
ItemKind::BoundaryCondition => m.boundary_conditions().keys().cloned().collect(),
ItemKind::Load => m.loads().keys().cloned().collect(),
ItemKind::ReferencePoint => m.reference_points().keys().cloned().collect(),
ItemKind::Coupling => m.couplings().keys().cloned().collect(),
}
}
fn exists(s: &Session, item: &Item) -> bool {
let m = &s.model;
match item.kind {
ItemKind::Body => s.design.as_ref().is_some_and(|d| d.body(&item.name).is_some()),
ItemKind::Surface => s.surfaces.iter().any(|x| x.name == item.name),
ItemKind::Datum => m.datum(&item.name).is_some(),
ItemKind::BoundaryCondition => m.boundary_conditions().contains_key(&item.name),
ItemKind::Load => m.loads().contains_key(&item.name),
ItemKind::ReferencePoint => m.reference_points().contains_key(&item.name),
ItemKind::Coupling => m.couplings().contains_key(&item.name),
}
}
/// Forget hidden items the session no longer has.
pub(crate) fn forget_missing(s: &mut Session) {
if s.view.hidden.is_empty() {
return;
}
let gone: Vec<Item> = s.view.hidden.iter().filter(|i| !exists(s, i)).cloned().collect();
for i in gone {
s.view.hidden.remove(&i);
}
}
impl Session {
/// The analysis setup's symbols, without the definitions the view hides.
pub fn glyphs(&self) -> fieldcraft_render::glyphs::Glyphs {
self.glyphs_of(None)
}
/// The symbols of what solved step `step` used, over its results: its own boundary
/// conditions and loads (none for a frequency step, which has no loads) and its own initial
/// velocities and rigid walls; the interactions as always. Without the view's hidden items.
pub fn step_glyphs(&self, step: &str) -> fieldcraft_render::glyphs::Glyphs {
self.glyphs_of(Some(step))
}
fn glyphs_of(&self, step: Option<&str>) -> fieldcraft_render::glyphs::Glyphs {
use fieldcraft_model::Procedure;
use fieldcraft_render::glyphs::Definition;
let step = step.map(|name| self.model.step(name));
let frequency = matches!(step, Some(Some(s)) if matches!(s.procedure, Procedure::Frequency { .. }));
fieldcraft_render::glyphs::Glyphs::from_model_hiding(&self.model, &|definition, name| {
let (kind, used) = match definition {
Definition::BoundaryCondition => (ItemKind::BoundaryCondition, step.map(|s| s.is_some_and(|s| s.boundary_conditions.contains(name)))),
Definition::Load => (ItemKind::Load, step.map(|s| !frequency && s.is_some_and(|s| s.loads.contains(name)))),
Definition::ReferencePoint => (ItemKind::ReferencePoint, None),
Definition::Coupling => (ItemKind::Coupling, None),
Definition::Step => return step.is_some_and(|s| s.is_none_or(|s| s.name != name)),
Definition::Contact | Definition::Tie => return false,
};
used == Some(false) || self.view.is_hidden(kind, name)
})
}
/// The elements of the bodies the view hides: hiding a body hides its mesh and its results.
pub fn hidden_elements(&self) -> std::collections::BTreeSet<u32> {
self.view.hidden.iter().filter(|i| i.kind == ItemKind::Body).flat_map(|i| self.model.body_elements(&i.name)).collect()
}
/// Whether the view shows item `name` of `kind`.
pub fn shows(&self, kind: ItemKind, name: &str) -> bool {
!self.view.is_hidden(kind, name)
}
}
fn change(s: &mut Session, p: &Value, how: Change) -> Result<Value> {
let items: Vec<Item> = super::req(p, "items")?;
if items.len() > MAX_HIDDEN {
return Err(EngineError::Params(format!("at most {MAX_HIDDEN} items")));
}
if let Some(i) = items.iter().find(|i| !exists(s, i)) {
let kind = serde_json::to_value(i.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
return Err(EngineError::Params(format!("no {} `{}`", kind.replace('_', " "), i.name.chars().take(100).collect::<String>())));
}
match how {
Change::Hide => s.view.hidden.extend(items),
Change::Show => {
for i in &items {
s.view.hidden.remove(i);
}
}
Change::Isolate => {
let keep: BTreeSet<Item> = items.into_iter().collect();
let all = ItemKind::ALL.into_iter().flat_map(|kind| names(s, kind).into_iter().map(move |name| Item { kind, name }));
let rest: BTreeSet<Item> = all.filter(|i| !keep.contains(i)).take(MAX_HIDDEN).collect();
s.view.hidden = rest;
}
}
Ok(Value::Null)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::cmd::datum::tests::plate;
fn item(kind: ItemKind, name: &str) -> Value {
json!({"kind": kind, "name": name})
}
#[test]
fn hiding_is_saved_view_state_not_an_edit() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Sym", "by": {"type": "offset", "plane": "zx"}})).unwrap();
s.execute("geometry.datum.point", &json!({"name": "P", "by": {"type": "coordinates", "point": [1, 2, 3]}})).unwrap();
let file = dir.join("hide.fieldcraft");
s.execute("file.save_as", &json!({"path": file.to_str().unwrap()})).unwrap();
let (journal, revision) = (s.journal.len(), s.revision());
assert!(!s.is_dirty());
s.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
assert_eq!(s.view.hidden.iter().collect::<Vec<_>>(), [&Item { kind: ItemKind::Datum, name: "Sym".into() }]);
// Unsaved, but no edit: nothing journalled, the revision (and so any result) unchanged.
assert!(s.is_dirty());
assert_eq!((s.journal.len(), s.revision()), (journal, revision));
// Showing it again is back to the saved state.
s.execute("view.show", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
assert!(!s.is_dirty());
// Hidden state survives save and open.
s.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
s.execute("file.save", &json!({})).unwrap();
let mut t = Session::default();
t.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
assert!(t.view.is_hidden(ItemKind::Datum, "Sym") && !t.view.is_hidden(ItemKind::Datum, "P"));
assert!(!t.is_dirty());
// Isolate hides every other item; show_all brings them back.
let body = names(&t, ItemKind::Body).remove(0);
t.execute("view.isolate", &json!({"items": [item(ItemKind::Datum, "P")]})).unwrap();
assert!(t.view.is_hidden(ItemKind::Body, &body) && t.view.is_hidden(ItemKind::Datum, "Sym") && !t.view.is_hidden(ItemKind::Datum, "P"));
t.execute("view.show_all", &json!({})).unwrap();
assert!(t.view.is_empty());
// An item deleted is forgotten.
t.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "P")]})).unwrap();
t.execute("geometry.datum.delete", &json!({"name": "P"})).unwrap();
assert!(t.view.is_empty());
// Unknown items and hostile parameters change nothing.
for p in [json!({}), json!({"items": "x"}), json!({"items": [item(ItemKind::Load, "Nope")]}), json!({"items": [{"kind": "x", "name": "A"}]})]
{
assert!(t.execute("view.hide", &p).is_err(), "{p}");
}
assert!(t.view.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}
File diff suppressed because it is too large. Load diff
+277
View File
@@ -0,0 +1,277 @@
use super::*;
use crate::Session;
fn fresh_dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("fieldcraft-crash-test-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
d
}
fn build() -> Build {
Build { version: "9.9.9", commit: "abc1234" }
}
fn node(label: u32) -> Value {
json!({"label": label, "xyz": [f64::from(label), 0.0, 0.0]})
}
/// The child half of the process tests: does nothing unless a parent asks, then installs the
/// hook and crashes the way `FIELDCRAFT_CRASH_CHILD` says.
#[test]
fn child() {
let (Some(dir), Ok(mode)) = (std::env::var_os("FIELDCRAFT_CRASH_CHILD_DIR"), std::env::var("FIELDCRAFT_CRASH_CHILD")) else {
return;
};
let dir = PathBuf::from(dir);
if mode == "replay" {
// Replay the one report (in a process of its own: the replay replaces the panic hook).
let id = list(&dir)[0].id.clone();
let r = replay(&read(&dir, &id).unwrap(), &std::env::temp_dir()).unwrap();
let steps: Vec<_> = r.steps.iter().map(|(c, r)| json!({"command": c, "ok": r.is_ok()})).collect();
println!("REPLAY {}", json!({"reproduced": r.reproduced, "nodes": r.session.model.nodes().len(), "steps": steps}));
return;
}
let fresh = install(dir.clone(), build());
println!("FRESH {}", serde_json::to_string(&fresh).unwrap());
if mode == "idle" {
end_session();
return;
}
let mut s = Session { crash_journal: true, ..Default::default() };
s.execute("mesh.node.add", &node(1)).unwrap();
s.execute("mesh.node.add", &node(2)).unwrap();
// Commands that only read are not kept.
for _ in 0..50 {
s.execute("model.info", &json!({})).unwrap();
}
match mode.as_str() {
"command" => {
for _ in 0..3 {
let r = s.execute("diagnostics.crash_test", &json!({"mode": "panic"}));
assert!(matches!(r, Err(crate::EngineError::Internal { .. })), "{r:?}");
}
assert_eq!(s.model.nodes().len(), 2, "the model is unchanged");
}
"recovered" => {
assert_eq!(s.execute("diagnostics.crash_test", &json!({"mode": "recovered"})).unwrap()["caught"], true);
}
"thread" => {
let r = std::thread::Builder::new()
.name("worker".into())
.spawn(|| std::panic::panic_any(String::from("worker thread 42 failed")))
.unwrap()
.join();
assert!(r.is_err());
}
"abort" => {
activity("control ui.capture");
let _ = s.execute("diagnostics.crash_test", &json!({"mode": "abort"}));
}
"autosave" => {
// The journal starts again from each autosave.
let mut a = crate::autosave::Autosaver::new(&dir.join("recovery")).unwrap();
assert!(a.save(&s).unwrap());
s.execute("mesh.node.add", &node(3)).unwrap();
activity("control ui.capture");
std::process::abort();
}
_ => {}
}
end_session();
}
/// Run [`child`] in a new process; returns its stdout and whether it succeeded.
fn run_child(dir: &Path, mode: &str) -> (String, bool) {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "crash::tests::child", "--test-threads=1", "--nocapture"])
.env("FIELDCRAFT_CRASH_CHILD_DIR", dir)
.env("FIELDCRAFT_CRASH_CHILD", mode)
.env("FIELDCRAFT_CRASH_TEST", "1")
.env("RUST_BACKTRACE", "0")
.output()
.unwrap();
(String::from_utf8_lossy(&out.stdout).into_owned(), out.status.success())
}
fn printed(out: &str, tag: &str) -> Value {
let line = out.lines().find_map(|l| l.split_once(tag).map(|(_, rest)| rest)).unwrap_or_else(|| panic!("no {tag} in {out}"));
serde_json::from_str(line.trim()).unwrap()
}
fn only_report(dir: &Path) -> (Summary, Value) {
let all = list(dir);
assert_eq!(all.len(), 1, "{all:?}");
let s = all.into_iter().next().unwrap();
let v = read(dir, &s.id).unwrap();
(s, v)
}
fn nodes_in(model: &str) -> usize {
let mut s = Session::default();
s.execute("file.open", &json!({"path": model})).unwrap();
s.model.nodes().len()
}
#[test]
fn a_command_panic_is_reported_once_with_the_model_and_the_command_and_replays() {
let d = fresh_dir("command");
let (_, ok) = run_child(&d, "command");
assert!(ok, "the panics were caught");
let (s, v) = only_report(&d);
assert_eq!(s.kind, "command_panic");
assert_eq!(s.count, 3, "repeats are counted, not written again");
assert_eq!(s.command.as_deref(), Some("diagnostics.crash_test"));
assert!(s.replayable);
assert_eq!(v["format"], FORMAT);
assert_eq!(v["app"]["version"], "9.9.9");
assert_eq!(v["system"]["os"], std::env::consts::OS);
assert!(v["message"].as_str().unwrap().contains("an internal error in a command"), "{v}");
assert!(v["location"].as_str().unwrap().contains("diagnostics.rs"), "{v}");
let bt = v["backtrace"].as_array().unwrap();
assert!(bt.iter().any(|f| f.as_str().unwrap().contains("crash_test")), "{bt:?}");
assert!(!bt.iter().any(|f| f.as_str().unwrap().contains("crash::hook")), "the hook's own frames are dropped: {bt:?}");
assert_eq!(v["recent_commands"][0]["command"], "mesh.node.add");
assert_eq!(v["recent_commands"].as_array().unwrap().len(), 3, "read-only commands are not kept: {v}");
assert_eq!(v["recent_commands"][2]["ok"], false);
// The model from before the command, and the command: together they reproduce the crash.
assert_eq!(nodes_in(v["model_path"].as_str().unwrap()), 2);
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(replay["commands"], json!([{"command": "diagnostics.crash_test", "params": {"mode": "panic"}}]));
assert_eq!(v["reproduce"], format!("fieldcraft-cli crashes replay {}", s.id));
assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "a clean exit leaves no journal");
// The replay reaches the same internal error, from the same model.
let (out, ok) = run_child(&d, "replay");
assert!(ok, "{out}");
let r = printed(&out, "REPLAY ");
assert_eq!(r["reproduced"], true, "{r}");
assert_eq!(r["nodes"], 2, "the replay ends in the state the crash left: {r}");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn a_panic_caught_inside_a_command_is_reported_as_recovered() {
let d = fresh_dir("recovered");
let (_, ok) = run_child(&d, "recovered");
assert!(ok);
let (s, v) = only_report(&d);
assert_eq!(s.kind, "recovered_panic");
assert!(!s.replayable, "the command did not fail");
assert!(v["message"].as_str().unwrap().contains("caught inside"), "{v}");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn a_panic_outside_commands_is_reported_from_the_journal() {
let d = fresh_dir("thread");
let (_, ok) = run_child(&d, "thread");
assert!(ok);
let (s, v) = only_report(&d);
assert_eq!(s.kind, "panic");
assert_eq!(v["thread"], "worker");
assert!(s.message.contains("worker thread 42 failed"));
// The journal's commands from a new model rebuild it.
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(replay["commands"].as_array().unwrap().len(), 2, "{replay}");
// A panic the hook reported is no unclean exit at the next start.
let (out, _) = run_child(&d, "abort");
let fresh = printed(&out, "FRESH ");
assert_eq!(fresh.as_array().unwrap().len(), 1, "the earlier report, seen once: {fresh}");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn an_unclean_exit_is_found_at_the_next_start_with_its_commands() {
let d = fresh_dir("abort");
let (_, ok) = run_child(&d, "abort");
assert!(!ok, "the child aborted");
assert!(list(&d).is_empty(), "nothing wrote a report while it died");
assert_eq!(fs::read_dir(d.join("sessions")).unwrap().count(), 1, "its journal is left behind");
let (out, ok) = run_child(&d, "idle");
assert!(ok);
let fresh = printed(&out, "FRESH ");
assert_eq!(fresh[0]["kind"], "unclean_exit", "{fresh}");
let (s, v) = only_report(&d);
assert_eq!(s.command.as_deref(), Some("diagnostics.crash_test"), "the command in flight");
assert!(s.message.contains("ended without a clean exit while running `diagnostics.crash_test`"), "{}", s.message);
assert_eq!(v["last_activity"], "control ui.capture");
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
let ids: Vec<&str> = replay["commands"].as_array().unwrap().iter().map(|c| c["command"].as_str().unwrap()).collect();
assert_eq!(ids, ["mesh.node.add", "mesh.node.add", "diagnostics.crash_test"]);
assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "the dead journal is gone");
// Told once: the next start offers nothing new.
let (out, _) = run_child(&d, "idle");
assert_eq!(printed(&out, "FRESH "), json!([]));
let _ = fs::remove_dir_all(&d);
}
#[test]
fn an_unclean_exit_after_an_autosave_starts_from_the_autosave() {
let d = fresh_dir("autosave");
let (_, ok) = run_child(&d, "autosave");
assert!(!ok);
run_child(&d, "idle");
let (s, v) = only_report(&d);
assert_eq!(s.kind, "unclean_exit");
assert!(s.message.contains("between commands (last: control ui.capture)"), "{}", s.message);
assert_eq!(nodes_in(v["model_path"].as_str().unwrap()), 2, "the autosaved model");
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(replay["commands"], json!([{"command": "mesh.node.add", "params": node(3)}]), "only what came after the autosave");
let (out, ok) = run_child(&d, "replay");
assert!(ok, "{out}");
assert_eq!(printed(&out, "REPLAY ")["nodes"], 3, "the replay rebuilds the model the app had");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn journals_parse_and_hostile_ids_are_refused() {
let text = [
r#"{"start":"x","pid":1,"version":"1"}"#,
r#"{"base":"new"}"#,
r#"{"run":"a","params":{}}"#,
r#"{"ok":true}"#,
r#"{"activity":"control ui.capture"}"#,
r#"{"run":"b","params":{"x":1}}"#,
r#"{"ok":false,"error":"no"}"#,
"not json",
r#"{"run":"c","params":{}}"#,
]
.join("\n");
let j = parse_journal(&text);
assert_eq!(j.replay, vec![json!({"command": "a", "params": {}})]);
assert_eq!(j.recent.len(), 2);
assert_eq!(j.in_flight, Some(json!({"command": "c", "params": {}})));
assert_eq!(j.activity.as_deref(), Some("control ui.capture"));
assert!(j.complete && !j.reported);
let d = fresh_dir("hostile");
fs::create_dir_all(&d).unwrap();
for id in ["", "../x", "a/b", &"f".repeat(65)] {
assert!(read(&d, id).is_err(), "{id}");
assert_eq!(clear(&d, Some(id)), 0);
}
let _ = fs::remove_dir_all(&d);
}
#[test]
fn signatures_ignore_numbers() {
assert_eq!(signature("a.rs:1", "node 12 of 400"), signature("a.rs:1", "node 7 of 3"));
assert_ne!(signature("a.rs:1", "node 12"), signature("a.rs:2", "node 12"));
assert_eq!(utc(0), "1970-01-01T00:00:00Z");
assert_eq!(stamp(1_760_436_000), "20251014-100000");
}
#[test]
fn reports_are_pruned_to_the_limits() {
let d = fresh_dir("prune");
for i in 0..(MAX_REPORTS + 5) {
let id = format!("20261014-1000{:02}-{:016x}", i % 60, i + 1);
fs::create_dir_all(d.join(&id)).unwrap();
let kind = if i == MAX_REPORTS + 4 { "recovered_panic" } else { "panic" };
fs::write(d.join(&id).join("report.json"), json!({"kind": kind, "message": "m"}).to_string()).unwrap();
}
prune(&d, now());
let left = list(&d);
assert_eq!(left.len(), MAX_REPORTS);
assert!(left.iter().all(|r| r.kind == "panic"), "recovered ones go first");
assert_eq!(clear(&d, None), MAX_REPORTS);
let _ = fs::remove_dir_all(&d);
}
+114 -5
View File
@@ -13,17 +13,23 @@
#![forbid(unsafe_code)]
pub mod autosave;
pub mod bug_report;
pub mod catalogue;
pub mod cmd;
pub mod crash;
pub mod logfile;
pub use cmd::analytic_surfaces;
pub use cmd::replace::{MESHERS, Replacement, replacement};
pub use cmd::replace::{MESHERS, Replacement, replacement, thousands};
pub use cmd::update::enable_checks as enable_update_checks;
pub use fieldcraft_io::{Item as ViewItem, ItemKind};
pub mod history;
pub mod progress;
pub mod requirement;
pub mod results;
pub mod sample;
pub mod schema;
pub mod usage;
pub mod view;
use std::collections::BTreeMap;
@@ -73,6 +79,29 @@ pub enum EngineError {
}
impl EngineError {
/// Whether the command stopped because it was cancelled
/// ([`fieldcraft_model::progress::Progress::cancel`]).
pub fn is_cancelled(&self) -> bool {
use fieldcraft_model::Error::Cancelled;
matches!(
self,
EngineError::Model(Cancelled)
| EngineError::Mesh(fieldcraft_mesh::Error::Model(Cancelled))
| EngineError::Solver(fieldcraft_solver::Error::Model(Cancelled))
| EngineError::Explicit(fieldcraft_explicit::Error::Model(Cancelled))
| EngineError::Fluid(fieldcraft_lbm::Error::Model(Cancelled) | fieldcraft_lbm::Error::Mesh(fieldcraft_mesh::Error::Model(Cancelled)))
)
}
/// A body's mesher failure as a parameter problem naming the body, or the cancellation as
/// it is.
pub(crate) fn of_body(body: &str, e: fieldcraft_mesh::Error) -> Self {
match e {
fieldcraft_mesh::Error::Model(fieldcraft_model::Error::Cancelled) => EngineError::Model(fieldcraft_model::Error::Cancelled),
e => EngineError::Params(format!("body `{body}`: {e}")),
}
}
/// A problem with the parameter at `path` (`elastic/young`).
pub fn param(path: impl Into<String>, kind: schema::ProblemKind) -> Self {
Self::Param(schema::Problem::at(path, kind))
@@ -165,6 +194,16 @@ pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
commands().iter().find(|c| c.id == id)
}
/// Refuse a parameter the command does not take, naming the ones it does: a script that sets
/// `deformed` on `results.contour` learns it belongs elsewhere instead of being ignored.
fn check_keys(spec: &CommandSpec, params: &Value) -> Result<()> {
match spec.form.and_then(|form| schema::unknown_key(form, params)) {
Some((key, accepted)) if accepted.is_empty() => Err(EngineError::Params(format!("{} takes no parameters (got `{key}`)", spec.id))),
Some((key, accepted)) => Err(EngineError::Params(format!("{} has no parameter `{key}`; it takes {}", spec.id, accepted.join(", ")))),
None => Ok(()),
}
}
/// A new revision number, unique in the process: every state of every session has its own.
pub(crate) fn next_revision() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -218,6 +257,9 @@ pub struct Session {
pub journal: Vec<(String, Value)>,
/// The `.fieldcraft` file the session was opened from or last saved to.
pub path: Option<String>,
/// The sample the session was opened as (`file.sample`), by its label; the document is named
/// after it until it is saved under a name of its own.
pub sample: Option<&'static str>,
history: History,
/// Identifies the current state: it changes with every edit, undo and redo, and comes back
/// when an undo returns to an earlier state.
@@ -228,6 +270,9 @@ pub struct Session {
/// The latest result of each solved step, by step name, with the revision it was solved at;
/// [`Session::result`] hands out only those that describe the current state.
results: BTreeMap<String, (u64, Arc<StepResult>)>,
/// What each solved step read ([`results::inputs_fingerprint`]): an edit that leaves it the
/// same keeps the step's result current.
result_inputs: BTreeMap<String, u64>,
/// What the results display shows (`results.*`); `None` shows the model.
pub results_view: Option<results::ResultsView>,
/// The default work caps of commands; a file replacing the session keeps them.
@@ -238,6 +283,18 @@ pub struct Session {
/// Identifies the open document: it changes when another model, sample or design is opened
/// in place of the current one, never with an edit (see [`Session::opened`]).
opened: u64,
/// What the viewport hides (`view.*`): saved with the model, but no edit of it, so it is
/// neither journalled nor undone, and it leaves results current.
pub view: fieldcraft_io::View,
/// The view as last saved (or opened): a change to it is unsaved too.
saved_view: fieldcraft_io::View,
/// This is the app's own model: its top-level commands go into the crash journal
/// ([`crash`]), so an unclean exit can be replayed. Off for scratch sessions and tests.
pub crash_journal: bool,
/// Where this session's commands come from, for the usage analytics ([`usage`]): the app
/// sets it on its own model (and the control channel and the command search while they
/// run); `None` (scratch sessions, the CLI, tests) counts nothing.
pub origin: Option<usage::Origin>,
}
impl Session {
@@ -246,11 +303,33 @@ impl Session {
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
// An id from hostile input is not echoed in full.
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.chars().take(100).collect()))?;
self.availability(spec).map_err(EngineError::Unavailable)?;
let timer = usage::Timer::start(self.origin);
let elements = self.model.elements().len();
let result = self
.availability(spec)
.map_err(EngineError::Unavailable)
.and_then(|()| check_keys(spec, params))
.and_then(|()| self.run_command(spec, params));
if timer.counting() {
let milestone = usage::milestone(spec.id, (elements, self.model.elements().len()));
let sample =
(spec.id == "file.sample").then(|| params.get("name").and_then(Value::as_str).and_then(sample::find)).flatten().map(|s| s.name);
timer.done(spec.id, spec.kind, result.as_ref().err(), milestone, sample);
}
result
}
/// [`Session::execute`] once the command is found and can run.
fn run_command(&mut self, spec: &'static CommandSpec, params: &Value) -> Result<Value> {
let id = spec.id;
// Session commands (open, save, undo, redo) change the session only in their last step,
// after everything that can fail, so they need no copy of the model to restore.
let before = (spec.kind == CommandKind::Model).then(|| (self.snapshot(), self.document()));
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (spec.run)(self, params)));
let scope = crash::Scope::enter();
let journaled = crash::command_begin(&scope, self, id, params);
let (revision, opened) = (self.revision, self.opened);
let outcome =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (spec.run)(self, params).and_then(|v| cmd::relax::after_remesh(self, id, v))));
let result = match outcome {
Ok(Err(EngineError::Param(p))) => Err(EngineError::Param(match spec.form {
Some(form) => schema::refine(form, params, p),
@@ -275,8 +354,15 @@ impl Session {
self.journal.push((id.to_string(), params.clone()));
self.revision = next_revision();
self.record_undo(before);
// An item deleted (or a body cut into cells) is no longer hidden.
cmd::view::forget_missing(self);
}
}
if self.revision != revision {
self.refresh_results();
}
drop(scope);
crash::command_done(self, journaled, self.revision != revision || self.opened != opened, id, params, &result);
result
}
@@ -315,7 +401,7 @@ impl Session {
/// Whether the session has changes its file does not hold. Undoing back to the saved state
/// makes it clean again.
pub fn is_dirty(&self) -> bool {
self.saved_revision.unwrap_or(0) != self.revision
self.saved_revision.unwrap_or(0) != self.revision || self.view != self.saved_view
}
/// The stored result of a step, if it was solved in the current state (an edit makes it stale;
@@ -340,7 +426,25 @@ impl Session {
}
Some(_) => {}
}
self.results.insert(result.step().to_string(), (self.revision, Arc::new(result)));
let step = result.step().to_string();
match results::inputs_fingerprint(&self.model, &step) {
Some(f) => self.result_inputs.insert(step.clone(), f),
None => self.result_inputs.remove(&step),
};
self.results.insert(step, (self.revision, Arc::new(result)));
}
/// After the state changed (an edit, undo or redo): a result whose step reads what it read
/// when it was solved describes the new state too, so it stays (or is again) current; the
/// others go stale.
fn refresh_results(&mut self) {
let revision = self.revision;
for (step, (solved, _)) in self.results.iter_mut().filter(|(_, (r, _))| *r != revision) {
let read = self.result_inputs.get(step).copied();
if read.is_some() && read == results::inputs_fingerprint(&self.model, step) {
*solved = revision;
}
}
}
/// The path to use for `access` to the file at `path`, checked against [`Session::file_access`].
@@ -356,9 +460,13 @@ impl Session {
pub(crate) fn mark_saved(&mut self, path: String) {
self.path = Some(path);
self.saved_revision = Some(self.revision);
self.saved_view = self.view.clone();
}
}
#[cfg(test)]
mod cancel_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -677,6 +785,7 @@ mod tests {
let opened = s.execute("geometry.open", &json!({"path": path})).unwrap();
assert_eq!(opened["bodies"], json!(["Body1"]));
assert_eq!(opened["errors"], json!([]));
assert_eq!(opened["warnings"], json!([]));
assert_eq!(s.journal.len(), 1);
let bodies = s.execute("geometry.bodies", &json!({})).unwrap();
+180
View File
@@ -0,0 +1,180 @@
//! The log file: what the desktop app logs (through the `log` facade) goes to
//! `<data folder>/logs/fieldcraft.log`, one line per record:
//! `2026-10-14T10:03:22Z WARN [4242] fieldcraft_engine: message`. Warnings and errors also go to
//! the standard error stream.
//!
//! Bounded: past [`MAX_BYTES`] the file becomes `fieldcraft.log.1` (replacing the one before) and
//! a new one starts, so the logs never take more than twice that. A record is cut at
//! [`MAX_LINE`] bytes. The process id on every line lets a crash report take only the lines of
//! the run that crashed ([`tail`]), even when two apps share the file.
//!
//! Nothing is installed in tests, the CLI or the web build (which logs to the browser console).
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
/// The log file's name.
pub const FILE_NAME: &str = "fieldcraft.log";
/// The log file's size limit.
pub const MAX_BYTES: u64 = 2 << 20;
/// A record's size limit.
pub const MAX_LINE: usize = 4 << 10;
struct FileLogger {
path: PathBuf,
level: log::LevelFilter,
out: Mutex<Out>,
}
struct Out {
file: Option<File>,
bytes: u64,
}
static LOGGER: OnceLock<FileLogger> = OnceLock::new();
/// Send the `log` records at `level` and above to the log file in `dir` (created if needed).
/// Returns the file's path. Call once; later calls change nothing.
pub fn install(dir: &Path, level: log::LevelFilter) -> Result<PathBuf, String> {
fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let path = dir.join(FILE_NAME);
let file = open(&path).map_err(|e| format!("{}: {e}", path.display()))?;
let bytes = file.metadata().map_or(0, |m| m.len());
let logger = FileLogger { path: path.clone(), level, out: Mutex::new(Out { file: Some(file), bytes }) };
if LOGGER.set(logger).is_err() {
return Err("a log file is already installed".into());
}
if let Some(l) = LOGGER.get() {
log::set_logger(l).map_err(|e| e.to_string())?;
log::set_max_level(level);
}
Ok(path)
}
fn open(path: &Path) -> std::io::Result<File> {
OpenOptions::new().create(true).append(true).open(path)
}
/// The log file, once [`install`]ed.
pub fn path() -> Option<&'static Path> {
LOGGER.get().map(|l| l.path.as_path())
}
/// The last `max` bytes of the log file's lines written by process `pid` (every line when
/// `None`), from the rotated file too when the current one is short. `None` without a log file.
pub fn tail(pid: Option<u32>, max: usize) -> Option<String> {
let path = path().map(Path::to_path_buf).or_else(default_path)?;
Some(tail_of(&path, pid, max))
}
/// [`tail`] of the log file at `path`.
fn tail_of(path: &Path, pid: Option<u32>, max: usize) -> String {
let mut text = String::new();
for p in [rotated(path), path.to_path_buf()] {
// The whole file (it is bounded): another process's lines may come between.
text.push_str(&read_end(&p, MAX_BYTES));
}
let mark = pid.map(|p| format!(" [{p}] "));
let mut lines: Vec<&str> = text.lines().filter(|l| mark.as_deref().is_none_or(|m| l.contains(m))).collect();
let mut total = 0;
let mut keep = lines.len();
for (i, l) in lines.iter().enumerate().rev() {
total += l.len() + 1;
if total > max {
break;
}
keep = i;
}
lines.drain(..keep);
lines.join("\n")
}
/// The log file of this computer's app (for a crash report written before [`install`]).
fn default_path() -> Option<PathBuf> {
fieldcraft_io::recovery::data_dir().map(|d| d.join("logs").join(FILE_NAME))
}
/// The file the log rotates into.
pub fn rotated(path: &Path) -> PathBuf {
let mut s = path.as_os_str().to_owned();
s.push(".1");
PathBuf::from(s)
}
/// The last `max` bytes of a file, from the start of a line.
fn read_end(path: &Path, max: u64) -> String {
let Ok(mut f) = File::open(path) else { return String::new() };
let len = f.metadata().map_or(0, |m| m.len());
let from = len.saturating_sub(max);
let mut buf = Vec::new();
if f.seek(SeekFrom::Start(from)).is_err() || f.take(max).read_to_end(&mut buf).is_err() {
return String::new();
}
let text = String::from_utf8_lossy(&buf).into_owned();
match (from > 0, text.find('\n')) {
(true, Some(i)) => text.get(i + 1..).unwrap_or_default().to_string(),
_ => text,
}
}
impl log::Log for FileLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
metadata.level() <= self.level
}
fn log(&self, record: &log::Record<'_>) {
if !self.enabled(record.metadata()) {
return;
}
let message = crate::crash::limited(&record.args().to_string(), MAX_LINE).replace('\n', "\n ");
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let line = format!("{} {:<5} [{}] {}: {message}\n", crate::crash::utc(now), record.level(), std::process::id(), record.target());
if record.level() <= log::Level::Warn {
eprint!("{line}");
}
let Ok(mut out) = self.out.lock() else { return };
if out.bytes + line.len() as u64 > MAX_BYTES {
out.file = None;
let _ = fs::rename(&self.path, rotated(&self.path));
out.file = open(&self.path).ok();
out.bytes = 0;
}
if let Some(f) = &mut out.file
&& f.write_all(line.as_bytes()).is_err()
{
out.file = None;
}
out.bytes += line.len() as u64;
}
fn flush(&self) {
if let Ok(mut out) = self.out.lock()
&& let Some(f) = &mut out.file
{
let _ = f.flush();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tail_keeps_one_process_and_the_end() {
let d = std::env::temp_dir().join(format!("fieldcraft-logtail-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
let p = d.join(FILE_NAME);
fs::write(rotated(&p), "t INFO [7] a: old seven\nt INFO [8] a: old eight\n").unwrap();
fs::write(&p, "t INFO [7] a: one\nt WARN [8] a: other\nt INFO [7] a: two\n").unwrap();
assert_eq!(tail_of(&p, Some(7), 1000), "t INFO [7] a: old seven\nt INFO [7] a: one\nt INFO [7] a: two");
assert_eq!(tail_of(&p, Some(7), 40), "t INFO [7] a: one\nt INFO [7] a: two");
assert_eq!(tail_of(&p, None, 1000).lines().count(), 5);
// From the middle of a line, the partial line is dropped.
assert_eq!(read_end(&p, 20), "t INFO [7] a: two\n");
let _ = fs::remove_dir_all(&d);
}
}
+85 -2
View File
@@ -97,6 +97,9 @@ pub enum Status {
Blocked,
/// Not done, and not needed for this model.
Optional,
/// Done, but what it was made from changed since (`detail` says what): a mesh made before
/// its seeds or partitions changed.
Outdated,
}
/// One row of the checklist.
@@ -128,6 +131,11 @@ impl Session {
// Models without elements (point masses, fluid domains) need no material or section.
let elementless = analysable && m.elements().is_empty();
let modal_only = !m.steps().is_empty() && m.steps().iter().all(|st| matches!(st.procedure, Procedure::Frequency { .. }));
// Transient dynamics may leave a body free and unloaded (a drop, a flight onto a wall: initial
// velocities drive it): no support or load needed.
let dynamic_only = !m.steps().is_empty() && m.steps().iter().all(|st| st.procedure.is_dynamic());
// A model driven by a prescribed displacement or temperature needs no load either.
let driven = m.boundary_conditions().values().any(|bc| bc.drives());
let mut next_given = false;
Stage::ALL
.into_iter()
@@ -137,7 +145,8 @@ impl Session {
let optional = match stage {
Stage::Prepare => true,
Stage::Material | Stage::Section => elementless,
Stage::Loads => modal_only,
Stage::BoundaryConditions => dynamic_only,
Stage::Loads => modal_only || driven || dynamic_only,
_ => false,
};
let command = r.provider();
@@ -146,7 +155,10 @@ impl Session {
_ if stage == Stage::Solve => first_error.clone(),
_ => None,
};
let (status, detail) = if done {
let outdated = if done && stage == Stage::Mesh { self.mesh_outdated() } else { None };
let (status, detail) = if let Some(why) = outdated {
(Status::Outdated, Some(why))
} else if done {
(Status::Done, None)
} else if optional {
(Status::Optional, None)
@@ -165,6 +177,35 @@ impl Session {
}
}
impl Session {
/// Why the mesh no longer matches what steers it: seeds, partitions or the datums they cut
/// by changed after the last mesher ran (the journal says what ran when). `None` when it
/// matches, or no mesher made it.
pub fn mesh_outdated(&self) -> Option<String> {
let mesher = self.journal.iter().rposition(|(c, _)| crate::MESHERS.iter().any(|(m, _)| m == c))?;
let (command, _) = self.journal.get(mesher)?;
let mut changed = Vec::new();
for (c, _) in self.journal.get(mesher + 1..).unwrap_or_default() {
let what = match c.as_str() {
"mesh.seed.edge" | "mesh.seed.clear" => "Seeds",
"geometry.partition" | "geometry.partition.delete" | "geometry.partition.suppress" => "Partitions",
"geometry.datum.edit" | "geometry.datum.suppress" => "Datum planes",
_ => continue,
};
if !changed.contains(&what) {
changed.push(what);
}
}
let place = crate::catalogue::entry_of(command).map_or_else(|| command.clone(), |e| format!("{} › {}", e.tab.label(), e.label));
let what = match changed.as_slice() {
[] => return None,
[one] => one.to_string(),
[first @ .., last] => format!("{} and {}", first.join(", "), last.to_lowercase()),
};
Some(format!("{what} changed since this mesh was made — {place} to remesh"))
}
}
/// The checklist as JSON, with the next stage's command first for agents:
/// `{"next": {"stage", "command"} | null, "stages": [...]}`.
pub fn to_json(stages: &[StageState]) -> Value {
@@ -234,6 +275,48 @@ mod tests {
assert_eq!((status(&s, Stage::Results), to_json(&s.progress())["next"]["command"].clone()), (Next, json!("results.contour")));
}
/// A model driven by a prescribed displacement (rubber-seal) needs no load: the checklist
/// agrees with the model check and offers the solve next.
#[test]
fn a_displacement_driven_model_needs_no_load() {
let mut s = Session::default();
s.run_script(&crate::sample::rubber_seal()).unwrap();
assert!(s.model.loads().is_empty());
assert_eq!(status(&s, Stage::Loads), Optional);
assert_eq!(status(&s, Stage::Solve), Next, "{:?}", s.progress());
}
/// A free body in transient dynamics (drop-test: no support, only gravity and the floor)
/// needs no boundary condition, nor a load (impact): the checklist offers the solve next.
#[test]
fn a_free_body_in_explicit_dynamics_needs_no_boundary_condition() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "drop-test"})).unwrap();
assert!(s.model.boundary_conditions().is_empty());
assert_eq!(status(&s, Stage::BoundaryConditions), Optional);
assert_eq!(status(&s, Stage::Solve), Next, "{:?}", s.progress());
// impact: no support and no load, only an initial velocity onto a rigid wall.
s.execute("file.sample", &json!({"name": "impact"})).unwrap();
assert!(s.model.loads().is_empty() && s.model.boundary_conditions().is_empty());
assert_eq!((status(&s, Stage::BoundaryConditions), status(&s, Stage::Loads)), (Optional, Optional));
assert_eq!(status(&s, Stage::Solve), Next, "{:?}", s.progress());
}
/// A seed added after meshing marks the mesh out of date, until a remesh (#342).
#[test]
fn a_seed_after_the_mesh_marks_it_outdated() {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": "bracket-hex"})).unwrap();
assert_eq!(status(&s, Stage::Mesh), Done);
let edge = json!({"body": "Bracket.17", "edge": "F17:face:5|F2:side:l1"});
s.execute("mesh.seed.edge", &json!({"edges": [edge], "count": 6})).unwrap();
assert_eq!(status(&s, Stage::Mesh), Outdated);
let why = s.mesh_outdated().unwrap();
assert!(why.starts_with("Seeds changed since this mesh was made — Mesh › "), "{why}");
let v = s.execute("model.check", &json!({})).unwrap();
assert!(v.to_string().contains("Seeds changed since this mesh was made"), "{v}");
}
#[test]
fn model_check_returns_the_checklist() {
let mut s = Session::default();
+14 -2
View File
@@ -24,10 +24,12 @@ pub enum Requirement {
Design,
/// Geometry to mesh: an open design or an imported surface.
Geometry,
/// A datum plane or axis.
/// A datum plane, axis or point.
Datum,
/// A datum plane (what a partition cuts by).
DatumPlane,
DatumAxis,
DatumPoint,
/// A partition of the design.
Partition,
/// An edge seed.
@@ -74,6 +76,8 @@ impl Requirement {
Requirement::Geometry => s.design.is_some() || !s.surfaces.is_empty(),
Requirement::Datum => !m.datums().is_empty(),
Requirement::DatumPlane => m.datums().values().any(|d| d.plane().is_some()),
Requirement::DatumAxis => m.datums().values().any(|d| d.axis().is_some()),
Requirement::DatumPoint => m.datums().values().any(|d| d.point().is_some()),
Requirement::Partition => !m.partitions().is_empty(),
Requirement::Seed => !m.seeds().is_empty(),
Requirement::Nodes => !m.nodes().is_empty(),
@@ -110,8 +114,10 @@ impl Requirement {
match self {
Requirement::Design => "an open design",
Requirement::Geometry => "geometry (an open design or an imported surface)",
Requirement::Datum => "a datum plane or axis",
Requirement::Datum => "a datum",
Requirement::DatumPlane => "a datum plane",
Requirement::DatumAxis => "a datum axis",
Requirement::DatumPoint => "a datum point",
Requirement::Partition => "a partition",
Requirement::Seed => "an edge seed",
Requirement::Nodes => "mesh nodes",
@@ -140,6 +146,8 @@ impl Requirement {
match self {
Requirement::Design | Requirement::Geometry => "geometry.open",
Requirement::Datum | Requirement::DatumPlane => "geometry.datum",
Requirement::DatumAxis => "geometry.datum.axis",
Requirement::DatumPoint => "geometry.datum.point",
Requirement::Partition => "geometry.partition",
Requirement::Seed => "mesh.seed.edge",
Requirement::Nodes => "mesh.node.add",
@@ -195,6 +203,8 @@ impl crate::schema::Collection {
C::Body => Requirement::Design,
C::Datum => Requirement::Datum,
C::DatumPlane => Requirement::DatumPlane,
C::DatumAxis => Requirement::DatumAxis,
C::DatumPoint => Requirement::DatumPoint,
C::Partition => Requirement::Partition,
}
}
@@ -333,6 +343,8 @@ mod tests {
C::Body,
C::Datum,
C::DatumPlane,
C::DatumAxis,
C::DatumPoint,
C::Partition,
];
let empty = Session::default();
+257 -10
View File
@@ -8,11 +8,12 @@
//! earlier revision is still shown, marked stale ([`Session::latest_result`]).
use fieldcraft_explicit::{ExplicitResult, Frame};
use fieldcraft_model::Model;
use fieldcraft_model::{Model, UnitSystem};
use fieldcraft_solver::{FrequencyResult, HeatResult, StaticResult};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::schema::Dim;
use crate::{EngineError, Result, Session, StepResult};
/// A result by its procedure.
@@ -182,6 +183,49 @@ impl Field {
}
}
/// What it measures.
pub fn quantity(self) -> Quantity {
match self {
Field::Displacement | Field::DisplacementX | Field::DisplacementY | Field::DisplacementZ | Field::ContactSlip => Quantity::Length,
Field::Velocity => Quantity::Velocity,
Field::Temperature => Quantity::Temperature,
Field::HeatFlux => Quantity::HeatFlux,
Field::ContactGap | Field::ContactStatus => Quantity::None,
Field::ContactPressure
| Field::ContactShear
| Field::VonMises
| Field::MaxPrincipal
| Field::MidPrincipal
| Field::MinPrincipal
| Field::StressXx
| Field::StressYy
| Field::StressZz
| Field::StressXy
| Field::StressXz
| Field::StressYz => Quantity::Stress,
}
}
/// Whether `r` holds it as a mode shape: normalised, with no unit.
pub fn is_mode_shape(self, r: &StepResult) -> bool {
matches!(r.kind(), Kind::Frequency(_)) && self.quantity() == Quantity::Length
}
/// Its unit for result `r` in `system`: none for a mode shape (it is normalised).
pub fn unit(self, r: &StepResult, system: UnitSystem) -> Option<String> {
if self.is_mode_shape(r) { None } else { self.quantity().unit(system) }
}
/// Its title over result `r`: the label with its unit (`Von Mises stress [MPa]`), or, for
/// a mode shape, saying it is normalised.
pub fn title(self, r: &StepResult, system: UnitSystem) -> String {
if self.is_mode_shape(r) {
let label = self.label().trim_end_matches(" magnitude");
return format!("{label} (mode shape, normalised)");
}
with_unit(self.label(), self.unit(r, system).as_deref())
}
pub fn parse(id: &str) -> Option<Field> {
Field::ALL.into_iter().find(|f| f.id() == id)
}
@@ -238,6 +282,76 @@ impl Field {
}
}
/// What a number the results show measures: its unit follows the model's unit system
/// ([`Quantity::unit`]). The legend, the probe, the reaction sums and the solve summary all name
/// their units through it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Quantity {
/// No unit (a ratio, a code, a normalised value).
None,
Length,
Stress,
Force,
Moment,
Mass,
Time,
Velocity,
Temperature,
/// Energy (work): force × length.
Energy,
/// Heat flow (power): energy per time.
HeatFlow,
/// Heat flux: heat flow per area.
HeatFlux,
}
impl Quantity {
/// Its unit in `system` (`mm`, `MPa`, `N·mm`, `mW`…), or `None` (no unit, or the system is
/// unspecified). The model never converts, so this only names the system's own unit; a
/// temperature is in whatever scale its values were entered in.
pub fn unit(self, system: UnitSystem) -> Option<String> {
let dim = match self {
Quantity::None => return None,
Quantity::Length => Dim::Length,
Quantity::Stress => Dim::Stress,
Quantity::Force => Dim::Force,
Quantity::Moment => Dim::Moment,
Quantity::Mass => Dim::Mass,
Quantity::Time => Dim::Time,
Quantity::Velocity => Dim::Velocity,
Quantity::Temperature | Quantity::Energy | Quantity::HeatFlow | Quantity::HeatFlux => {
// Named units where the system's force × length (per time) has one.
let (energy, power, flux) = match system {
UnitSystem::Unspecified => return None,
UnitSystem::MKgS => ("J", "W", "W/m²"),
UnitSystem::MmTonneS => ("mJ", "mW", "mW/mm²"),
UnitSystem::MmKgMs => ("J", "kW", "kW/mm²"),
UnitSystem::MmGMs => ("mJ", "W", "W/mm²"),
UnitSystem::InLbfS => ("lbf·in", "lbf·in/s", "lbf/(in·s)"),
};
return Some(
match self {
Quantity::Energy => energy,
Quantity::HeatFlow => power,
Quantity::HeatFlux => flux,
_ => "°C or K",
}
.into(),
);
}
};
dim.unit(system)
}
}
/// `label` with `unit` in brackets when there is one: `Von Mises stress [MPa]`.
pub fn with_unit(label: &str, unit: Option<&str>) -> String {
match unit {
Some(u) => format!("{label} [{u}]"),
None => label.to_string(),
}
}
/// Most contour bands.
pub const MAX_BANDS: u32 = 24;
/// Fewest contour bands.
@@ -258,6 +372,12 @@ pub struct ResultsView {
/// Contours of this field; `None` draws the deformed shape in element colours.
pub contour: Option<Field>,
pub bands: u32,
/// The legend's range, clamped below the field's smallest or above its largest value (each
/// `None` follows the field): a singular peak no longer squeezes the field into one band.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub range_min: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub range_max: Option<f64>,
/// The mode shown, from 1 (frequency steps).
pub mode: usize,
/// The field frame shown (explicit steps); `None` is the last.
@@ -268,11 +388,12 @@ pub struct ResultsView {
}
impl ResultsView {
/// How a step's result is shown first: a static step undeformed with von Mises contours, so
/// they are read on the true geometry (`results.deformed` shows the deformed shape, at the
/// automatic scale); a frequency step's first mode deformed with displacement contours (a
/// mode shape is a deformation); an explicit step at its last frame, deformed to true scale
/// (with von Mises contours when it kept stresses); a heat step undeformed.
/// How a step's result is shown first: a linear static step undeformed with von Mises
/// contours, so they are read on the true geometry (`results.deformed` shows the deformed
/// shape, at the automatic scale); a frequency step's first mode deformed with displacement
/// contours (a mode shape is a deformation); an explicit step at its last frame and a
/// nonlinear static step at its last increment, deformed to true scale ([`true_scale`];
/// with von Mises contours when they kept stresses); a heat step undeformed.
pub fn for_result(r: &StepResult) -> ResultsView {
let heat = matches!(r.kind(), Kind::Heat(_));
let contour = if heat {
@@ -282,13 +403,15 @@ impl ResultsView {
} else {
Field::Displacement
};
let scale = matches!(r.kind(), Kind::Explicit(_)).then_some(1.0);
let true_scale = true_scale(r);
ResultsView {
step: r.step().to_string(),
deformed: matches!(r.kind(), Kind::Frequency(_) | Kind::Explicit(_)),
scale,
deformed: true_scale || matches!(r.kind(), Kind::Frequency(_)),
scale: true_scale.then_some(1.0),
contour: Some(contour),
bands: DEFAULT_BANDS,
range_min: None,
range_max: None,
mode: 1,
frame: None,
animate: false,
@@ -298,6 +421,38 @@ impl ResultsView {
pub fn pick(&self) -> Pick {
Pick { mode: self.mode, frame: self.frame }
}
/// The contour bands for a field ranging from `min` to `max`, clamped to the view's range.
pub fn bands(&self, min: f64, max: f64) -> fieldcraft_render::contour::Bands {
fieldcraft_render::contour::Bands::clamped(min, max, self.range_min, self.range_max, self.bands)
}
}
/// The automatic deformation scale draws the largest displacement this fraction of the model's
/// size.
pub const AUTO_FRACTION: f64 = 0.1;
/// Whether a result's deformation is drawn at true scale even when the scale is automatic: an
/// explicit step's and a nonlinear static step's displacements are already large (finite strain,
/// contact), and magnifying them draws the part crushed through its neighbours. Linear static,
/// frequency and buckling results are magnified.
pub fn true_scale(r: &StepResult) -> bool {
match r.kind() {
Kind::Explicit(_) => true,
Kind::Static(s) => s.nonlinear.is_some(),
Kind::Frequency(_) | Kind::Fluid(_) | Kind::Heat(_) => false,
}
}
/// The automatic deformation scale of `r` at `pick` on a model `size` across (its bounding box
/// diagonal): 1 for a [`true_scale`] result, else the factor that draws the largest
/// displacement [`AUTO_FRACTION`] of the size; 0 when nothing moves.
pub fn auto_scale(r: &StepResult, pick: Pick, size: f64) -> f64 {
if true_scale(r) {
return 1.0;
}
let largest = displacements(r, pick).map_or(0.0, |u| u.iter().map(|v| magnitude(*v)).filter(|m| m.is_finite()).fold(0.0, f64::max));
if largest > 0.0 && size.is_finite() && size > 0.0 { AUTO_FRACTION * size / largest } else { 0.0 }
}
/// The nodal displacements a result's deformed shape uses: the static displacement, the shape
@@ -458,6 +613,32 @@ pub fn range(labels: &[u32], values: &[f64]) -> Option<((u32, f64), (u32, f64))>
out
}
/// A fingerprint of what solving step `step` of `model` reads ([`Model::step_inputs`]), or
/// `None` when there is no such step.
pub(crate) fn inputs_fingerprint(model: &Model, step: &str) -> Option<u64> {
use std::hash::Hasher;
/// Hashes what is written to it.
struct HashWriter(std::hash::DefaultHasher);
impl std::io::Write for HashWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.write(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let inputs = model.step_inputs(step)?;
let mut h = HashWriter(std::hash::DefaultHasher::new());
serde_json::to_writer(&mut h, &inputs).ok()?;
Some(h.0.finish())
}
/// The principal values of a stress (xx, yy, zz, xy, xz, yz), largest first.
pub fn principal(t: &[f64; 6]) -> [f64; 3] {
fieldcraft_fem::principal(t)
}
pub fn magnitude(v: [f64; 3]) -> f64 {
(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}
@@ -481,7 +662,10 @@ impl Session {
{
let ends =
range(r.nodes(), &values).map(|((ln, lv), (hn, hv))| json!({"min": {"node": ln, "value": lv}, "max": {"node": hn, "value": hv}}));
out["contour"] = json!({"field": f, "label": f.label(), "range": ends});
out["contour"] = json!({"field": f, "label": f.label(), "unit": f.unit(r, self.model.units()), "range": ends});
if v.range_min.is_some() || v.range_max.is_some() {
out["contour"]["legend"] = json!({"min": v.range_min, "max": v.range_max});
}
}
match r.kind() {
Kind::Frequency(fr) => {
@@ -497,6 +681,7 @@ impl Session {
out["frames"] = f.frames.iter().map(|f| f.time).collect();
}
Kind::Heat(h) => {
out["heat_flows"] = heat_flows(h);
out["frames"] = json!(h.times);
if let Ok((t, _)) = heat_frame(h, v.pick()) {
out["time"] = json!(t);
@@ -519,6 +704,16 @@ impl Session {
}
}
/// The heat balance of a heat transfer result: each heat load's flow into the body (`loads`:
/// `{name, type, heat}`, negative out of it), the prescribed temperatures' total (`reactions`),
/// and `imbalance`, their sum: about 0 in a steady state, the heat stored per time in a
/// transient one.
pub fn heat_flows(h: &HeatResult) -> Value {
let loads: Vec<Value> = h.loads.iter().map(|l| json!({"name": l.name, "type": l.kind, "heat": l.heat})).collect();
let applied: f64 = h.loads.iter().map(|l| l.heat).sum();
json!({"loads": loads, "reactions": h.reaction_total, "imbalance": applied + h.reaction_total})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -563,6 +758,58 @@ mod tests {
assert_eq!(s.result_steps().collect::<Vec<_>>(), vec![("Bend", false), ("Modes", false)]);
}
/// A step's result goes stale only when something it reads changes (#318); undoing the
/// change makes it current again.
#[test]
fn unrelated_edits_keep_results_current() {
let mut s = Session::default();
cantilever(&mut s);
s.execute("solve.static", &json!({})).unwrap();
s.execute("solve.frequency", &json!({})).unwrap();
// A set, a boundary condition and a step that neither solved step uses.
s.execute("model.set.create", &json!({"name": "extra", "nodes": [1]})).unwrap();
s.execute("model.boundary_condition.create", &json!({"name": "X", "type": "fixed", "target": {"set": "extra"}})).unwrap();
s.execute("model.step.create", &json!({"name": "Other", "procedure": {"type": "static"}, "boundary_conditions": ["X"]})).unwrap();
assert_eq!(s.result_steps().collect::<Vec<_>>(), vec![("Bend", true), ("Modes", true)]);
// The load only Bend lists: Bend goes stale, Modes (no loads) stays current.
s.execute("model.load.edit", &json!({"name": "push", "type": "force", "target": {"set": "tip"}, "vector": [0, 0, -2]})).unwrap();
assert_eq!(s.result_steps().collect::<Vec<_>>(), vec![("Bend", false), ("Modes", true)]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.result_steps().collect::<Vec<_>>(), vec![("Bend", true), ("Modes", true)]);
// The clamp's set, which both use.
s.execute("model.set.edit", &json!({"name": "root", "nodes": [1, 12]})).unwrap();
assert_eq!(s.result_steps().collect::<Vec<_>>(), vec![("Bend", false), ("Modes", false)]);
s.execute("edit.undo", &json!({})).unwrap();
// A step's own definition.
s.execute("model.step.edit", &json!({"name": "Modes", "procedure": {"type": "frequency", "modes": 3}, "boundary_conditions": ["clamp"]}))
.unwrap();
assert_eq!(s.result_steps().collect::<Vec<_>>(), vec![("Bend", true), ("Modes", false)]);
}
#[test]
fn units_follow_the_unit_system() {
let mut s = Session::default();
cantilever(&mut s);
s.execute("solve.static", &json!({})).unwrap();
s.execute("solve.frequency", &json!({})).unwrap();
let mm = UnitSystem::MmTonneS;
let (bend, _) = s.latest_result("Bend").unwrap();
let (modes, _) = s.latest_result("Modes").unwrap();
assert_eq!(Field::VonMises.title(bend, mm), "Von Mises stress [MPa]");
assert_eq!(Field::Displacement.title(bend, mm), "Displacement magnitude [mm]");
assert_eq!(Field::Displacement.title(modes, mm), "Displacement (mode shape, normalised)");
assert_eq!(Field::DisplacementZ.title(modes, mm), "Displacement Z (mode shape, normalised)");
assert_eq!(Field::VonMises.title(bend, UnitSystem::Unspecified), "Von Mises stress");
assert_eq!(Field::ContactStatus.unit(bend, mm), None);
let unit = |q: Quantity, u: UnitSystem| q.unit(u);
assert_eq!(unit(Quantity::HeatFlow, mm).as_deref(), Some("mW"));
assert_eq!(unit(Quantity::Energy, mm).as_deref(), Some("mJ"));
assert_eq!(unit(Quantity::Moment, mm).as_deref(), Some("N·mm"));
assert_eq!(unit(Quantity::Energy, UnitSystem::MKgS).as_deref(), Some("J"));
assert_eq!(unit(Quantity::Temperature, UnitSystem::Unspecified), None);
assert_eq!(unit(Quantity::None, mm), None);
}
#[test]
fn field_ids_round_trip() {
for f in Field::ALL {
+154 -95
View File
@@ -11,7 +11,7 @@
//! explicit dynamic step.
//!
//! The examples gallery (docs/examples.md), each ready to solve with `solve.run`:
//! [`drop_test`], [`rubber_seal`], [`flow_past`], [`heated_bracket`], [`bracket_hex`] and [`crank_arm`]. Their
//! [`ibeam`], [`drop_test`], [`rubber_seal`], [`flow_past`], [`heated_bracket`], [`bracket_hex`] and [`crank_arm`]. Their
//! geometry is a SolidCraft script run when the sample opens ([`Sample::design`]): a corpus
//! recipe (`tests/corpus`) or [`UPRIGHT_BRACKET`].
@@ -60,6 +60,14 @@ pub const SAMPLES: &[Sample] = &[
prepare: None,
script: |_| impact(),
},
Sample {
name: "ibeam",
label: "I-Beam Cantilever",
about: "A 200 mm steel I-beam swept all-hex, clamped at one end with 1 kN on the other through a coupling: static, ready to solve",
design: Some(CANTILEVER_I_BEAM),
prepare: None,
script: |_| ibeam(),
},
Sample {
name: "drop-test",
label: "Drop Test",
@@ -290,6 +298,36 @@ pub fn impact() -> Value {
Value::Array(steps)
}
/// The 200 mm I-beam lying along x, web upright (`tests/corpus/cantilever-i-beam`): 40 × 40 mm,
/// 3 mm flanges, a 2 mm web. Body `Beam`; its end faces are `F2:start` (x = 0) and `F2:top`
/// (x = 200).
pub const CANTILEVER_I_BEAM: &str = include_str!("../../../tests/corpus/cantilever-i-beam/recipe.json");
/// The I-beam's tip load (N).
pub const IBEAM_LOAD: f64 = 1000.0;
/// [`CANTILEVER_I_BEAM`] swept all-hex (hex8 of 4 mm, incompatible modes) in steel, clamped at
/// x = 0 (set `root`), [`IBEAM_LOAD`] down (−z) on a reference point on the beam's axis at the
/// free end, kinematically coupled to the end face (set `tip`) so the section stays plane. Step
/// `Load` (linear static). The README demo's model (tools/demo-video).
pub fn ibeam() -> Value {
let face = |f: &str| json!([{"body": "Beam", "face": f}]);
json!([
{"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}},
{"command": "mesh.hex.sweep", "params": {"body": "Beam", "size": 4}},
{"command": "model.set.create", "params": {"name": "beam", "geometry": [{"body": "Beam"}]}},
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}, "density": 7.85e-9}},
{"command": "model.section.create", "params": {"name": "Beam", "set": "beam", "material": "Steel", "kind": {"type": "solid"}, "formulation": {"incompatible_modes": true}}},
{"command": "model.set.create", "params": {"name": "root", "geometry": face("F2:start")}},
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
{"command": "model.set.create", "params": {"name": "tip", "geometry": face("F2:top")}},
{"command": "model.reference_point.create", "params": {"name": "End", "xyz": [200, 0, 20]}},
{"command": "model.coupling.create", "params": {"name": "EndPlate", "reference_point": "End", "set": "tip", "kind": "kinematic"}},
{"command": "model.load.create", "params": {"name": "Push", "type": "force", "target": {"reference_point": "End"}, "vector": [0, 0, -IBEAM_LOAD]}},
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["Clamp"], "loads": ["Push"]}},
])
}
/// An L-bracket standing on its foot, Z up, as a SolidCraft script: a 60 × 40 mm foot and a 50 mm
/// upright, both 8 mm thick, with an R6 fillet inside the bend (the corpus `filleted-bracket`'s
/// profile without its holes, sketched on XZ so it sweeps along y). Body `Bracket`; its faces
@@ -497,101 +535,36 @@ pub const CRANK_ARM: &str = include_str!("../samples/crank-arm.json");
/// The crank arm's pedal load (N): a standing rider's weight on one pedal.
pub const PEDAL_LOAD: f64 = 1500.0;
/// The cells of the half `CrankArm/a` (y < 0) after [`crank_prepare`], from the spindle to the
/// pedal: the spindle boss and the arm's root (`X30`), the pocket's spindle end below the
/// diagonal `D1`, the arm between `D1` and `X60`, the middle of the arm (`X60` to `X110`), the arm
/// between `X110` and `D2`, the pocket's pedal end beyond `D2`, and the pedal boss (`X148`).
pub const CRANK_CELLS: [&str; 7] = [
"CrankArm/a/a",
"CrankArm/a/b/a",
"CrankArm/a/b/b/a",
"CrankArm/a/b/b/b/a",
"CrankArm/a/b/b/b/b/a",
"CrankArm/a/b/b/b/b/b/a",
"CrankArm/a/b/b/b/b/b/b",
];
/// The half of the crank [`crank_prepare`] cuts off on the symmetry plane (y < 0), the one
/// meshed; its mirror image is `CrankArm/b`.
pub const CRANK_HALF: &str = "CrankArm/a";
/// The diagonals' angles from the arm's axis (degrees): `D1` through the centre of the pocket's
/// spindle-end corner fillet (53, −2), `D2` through the pedal-end one (125, −2), each radial to
/// its fillet so it meets the pocket wall square. Steeper than 45° from the pocket's floor edge
/// (y = 0) on its inner side and shallower than 45° from the arm's edge on its outer side, so the
/// pocket's middle keeps its corners there and the cells beyond it do not gain one.
const CRANK_DIAGONALS: [f64; 2] = [40.0, 32.0];
/// [`CRANK_ARM`] meshed structured all-hex (hex20 of 3 mm) from a partitioned half and mirrored,
/// in 6061-T6 aluminium: the square bore's faces and corner fillets (set `spindle`) fixed,
/// [`CRANK_ARM`] meshed structured all-hex (hex20 of 3 mm) from its half and mirrored, in
/// 6061-T6 aluminium: the square bore's faces and corner fillets (set `spindle`) fixed,
/// [`PEDAL_LOAD`] on the pedal hole (set `pedal`), in the crank's plane and across the arm (−y).
/// Step `Pedal` (linear static). The faces are picked by their surfaces, not their names: the
/// square bore's are the vertical planes 6.35 mm from the spindle axis and the R1.5 cylinders
/// beside it, the pedal hole is the Ø14 cylinder on the pedal axis.
///
/// The mesh: [`crank_prepare`] cuts the crank on its symmetry plane and the half `CrankArm/a`
/// into the seven [`CRANK_CELLS`], each a stack of extrusions whose cross-section splits into
/// regions that map: four-sided regions (transfinite), the half ring round each bore, and the
/// pocket's four corners cut off by the partitions, three-sided (the triangle primitive). Exact
/// edge seeds give each cut the same divisions in the two cells it divides, so `mesh.cells`
/// sweeps every cell (`extrude`) and merges them node for node; `mesh.mirror` reflects the half
/// onto `CrankArm/b`, joined on the plane.
/// The mesh: [`crank_prepare`] cuts the crank on its symmetry plane only; `mesh.hex.generate`
/// extrudes the half [`CRANK_HALF`], decomposing its cross-section into blocks itself (half
/// rings round both bores, the pocket's corners as triangle primitives, four-sided blocks along
/// the arm), with no seeds; `mesh.mirror` reflects it onto `CrankArm/b`, joined on the plane.
pub fn crank_arm(bodies: &[Shape]) -> Value {
let cells = CRANK_CELLS;
let mut mesh = crank_seeds();
mesh.push(json!({"command": "mesh.cells", "params": {"bodies": cells, "default": "extrude", "size": 3, "order": 2}}));
// Each cell's image is part of the uncut half.
let images: serde_json::Map<String, Value> = cells.iter().map(|c| (c.to_string(), json!("CrankArm/b"))).collect();
mesh.push(json!({"command": "mesh.mirror", "params": {"plane": "Sym", "bodies": cells, "as": images}}));
let mesh = vec![
json!({"command": "mesh.hex.generate", "params": {"body": CRANK_HALF, "method": "extrude", "size": 3, "order": 2}}),
json!({"command": "mesh.mirror", "params": {"plane": "Sym", "bodies": [CRANK_HALF], "as": {CRANK_HALF: "CrankArm/b"}}}),
];
crank_model(bodies, mesh)
}
/// The edge seeds that make every cut's divisions alike on its two sides: each cut's line in
/// the arm's cross-section (its bottom edge, z = 0) and, for the diagonals and the cuts across the
/// pocket, its line on the pocket's floor (z = 8); and the 16 mm walls of the end cells on their
/// cuts, in six layers as the pocket's floor level splits the cells between them (3 + 3). The
/// counts are those the cells' mapped regions need: the cut `X30` faces the spindle boss's arc
/// across the root (7), the arm between the diagonals is one block of five rows.
fn crank_seeds() -> Vec<Value> {
let [c1, c2, c3, c4, c5, c6, c7] = CRANK_CELLS;
let cut = |name: &str, a: &str, b: &str, face: &str, count: u32| {
json!({"command": "mesh.seed.edge", "params": {"edges": [
{"body": a, "edge": format!("{face}|partition:{name}:a")},
{"body": b, "edge": format!("{face}|partition:{name}:b")},
], "count": count}})
};
let mut seeds = vec![cut("X30", c1, c2, "F2:start", 7), cut("X148", c6, c7, "F2:start", 5)];
for (name, a, b) in [("D1", c2, c3), ("X60", c3, c4), ("X110", c4, c5), ("D2", c5, c6)] {
seeds.push(cut(name, a, b, "F2:start", 5));
seeds.push(cut(name, a, b, "F6:top", 3));
}
seeds.push(json!({"command": "mesh.seed.edge", "params": {"edges": [
{"body": c1, "edge": "F2:side:lo|partition:X30:a"},
{"body": c7, "edge": "F2:side:lo|partition:X148:b"},
], "count": 6}}));
seeds
}
/// The crank arm's symmetry plane (`Sym`, y = 0) and the partition by it (`Half`), then the
/// half `CrankArm/a` cut into [`CRANK_CELLS`]: across the arm at x = 30 (the root, beyond the
/// spindle boss), 60 and 110 (the pocket's straight middle) and 148 (before the pedal boss), and
/// on the diagonals of [`CRANK_DIAGONALS`]. Each cut names the one cell it divides.
/// The crank arm's symmetry plane (`Sym`, y = 0) and the partition by it (`Half`): the one datum
/// the structured mesh needs.
fn crank_prepare() -> Value {
let [d1, d2] = CRANK_DIAGONALS.map(f64::to_radians);
let across = |x: f64| json!({"type": "offset", "plane": "yz", "offset": x});
let cuts = [
("X30", across(30.0), "CrankArm/a"),
("D1", json!({"type": "point_normal", "point": [53, -2, 0], "normal": [d1.sin(), -d1.cos(), 0]}), "CrankArm/a/b"),
("X60", across(60.0), "CrankArm/a/b/b"),
("X110", across(110.0), "CrankArm/a/b/b/b"),
("D2", json!({"type": "point_normal", "point": [125, -2, 0], "normal": [d2.sin(), d2.cos(), 0]}), "CrankArm/a/b/b/b/b"),
("X148", across(148.0), "CrankArm/a/b/b/b/b/b"),
];
let mut script = vec![
json!({"command": "geometry.datum", "params": {"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}}}),
json!({"command": "geometry.partition", "params": {"name": "Half", "datum": "Sym"}}),
];
for (name, by, body) in cuts {
script.push(json!({"command": "geometry.datum", "params": {"name": name, "by": by}}));
script.push(json!({"command": "geometry.partition", "params": {"name": name, "datum": name, "bodies": [body]}}));
}
Value::Array(script)
json!([
{"command": "geometry.datum", "params": {"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}}},
{"command": "geometry.partition", "params": {"name": "Half", "datum": "Sym"}},
])
}
/// The crank's model after the `mesh` commands: material, the spindle fixed, the rider on the
@@ -711,6 +684,21 @@ mod tests {
assert_eq!(f["modes"].as_array().map(Vec::len), Some(6));
}
/// The I-beam opens swept all-hex and ready; solved, its tip deflection is the beam theory's
/// bending plus shear (P L³ / 3 E I + P L / G A_web: 0.149 + 0.035 mm) within 5 %.
#[test]
fn the_ibeam_bends_as_beam_theory() {
let mut s = open("ibeam");
assert!(s.model.elements().values().all(|e| e.kind == fieldcraft_model::ElementKind::Hex8));
s.execute("solve.static", &json!({})).unwrap();
let p = s.execute("solve.probe", &json!({"step": "Load", "at": [[200.0, 0.0, 20.0]]})).unwrap();
let tip = -p["nodes"][0]["displacement"][2].as_f64().unwrap();
let (e, g) = (210000.0, 210000.0 / 2.6);
let i = (40.0 * 40.0f64.powi(3) - 38.0 * 34.0f64.powi(3)) / 12.0;
let theory = IBEAM_LOAD * 200.0f64.powi(3) / (3.0 * e * i) + IBEAM_LOAD * 200.0 / (g * 2.0 * 37.0);
assert!((tip - theory).abs() < 0.05 * theory, "{tip} against {theory}");
}
#[test]
fn the_impact_runs_and_keeps_frames_with_stresses() {
let mut s = Session::default();
@@ -720,6 +708,64 @@ mod tests {
assert!(r["energy_balance"].as_f64().unwrap() < 0.05, "{r}");
}
/// Hex20 extrudes the crank with its root arcs tangent to the spindle boss (#197), at the
/// sizes where it once failed the validity gate with inverted elements and hex8 did not: the
/// sample moves the root arcs off tangent, so this builds the tangent variant (root arcs of
/// R10 whose centres lie 33 mm from the spindle axis, R23 + R10). The elements at the cusp,
/// whose two curved sides meet tangentially, stay valid.
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn hex20_extrudes_the_crank_with_tangent_root_arcs() {
let mut script = CRANK_ARM.to_string();
for (from, to) in [
("15.883151316213851, 28.354461805265395", "16.9566899202338, 28.310257274511628"),
("15.883151316213851, -28.354461805265395", "16.9566899202338, -28.310257274511628"),
("15.471735240951828, 18.362928548901984", "16.545273844971774, 18.31872401814822"),
("15.471735240951828, -18.362928548901984", "16.545273844971774, -18.31872401814822"),
("13.455063072993756, 18.65372021077189", "11.818299035314467, 19.731391433750527"),
("13.455063072993756, -18.65372021077189", "11.818299035314467, -19.731391433750527"),
] {
assert!(script.contains(from), "{from}");
script = script.replace(from, to);
}
let bytes = fieldcraft_geometry::script_design(&script).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
for size in [2.5, 3.0, 5.0] {
let r = s.execute("mesh.hex.generate", &json!({"body": "CrankArm", "size": size, "order": 2, "method": "extrude"})).unwrap();
let body = &r["bodies"][0];
assert_eq!(body["kind"], "hex20", "{r}");
assert!(body["quality"]["min_scaled_jacobian"].as_f64().unwrap() > 0.0, "{size}: {r}");
}
}
/// A partition the kernel fails to make is reported as the kernel's failure, never as a plane
/// that does not divide the body (#283): x = 148 plainly crosses the crank's half y > 0, whose
/// cut fails in the kernel's boolean, and the same plane cuts the half y < 0.
#[test]
fn a_kernel_failure_to_partition_is_reported_as_such() {
use fieldcraft_geometry::Cut;
let design = fieldcraft_geometry::open_design(&fieldcraft_geometry::script_design(CRANK_ARM).unwrap()).unwrap();
let cut = |name: &str, point: [f64; 3], normal: [f64; 3], bodies: &[&str]| Cut {
name: name.into(),
point,
normal,
bodies: bodies.iter().map(|b| b.to_string()).collect(),
};
let half = cut("Half", [0.0; 3], [0.0, 1.0, 0.0], &[]);
let p = design.partitioned(&[half.clone(), cut("X148", [148.0, 0.0, 0.0], [1.0, 0.0, 0.0], &[CRANK_HALF])]).unwrap();
assert!(p.errors.is_empty(), "{:?}", p.errors);
let p = design.partitioned(&[half, cut("X148", [148.0, 0.0, 0.0], [1.0, 0.0, 0.0], &["CrankArm/b"])]).unwrap();
// Should the kernel learn to make this cut, the cut is all there is to check.
if p.cuts[1].split.is_empty() {
let errors: Vec<&str> = p.errors.iter().filter(|e| e.feature == "partition X148").map(|e| e.message.as_str()).collect();
assert!(matches!(errors.as_slice(), [m] if m.starts_with("the kernel could not cut `CrankArm/b`")), "{errors:?}");
} else {
assert_eq!(p.cuts[1].split, ["CrankArm/b"]);
}
}
/// `file.sample NAME`, checked clean: ready, no errors or warnings.
fn open(name: &str) -> Session {
let mut s = Session::default();
@@ -806,6 +852,18 @@ mod tests {
assert!(r["mass"]["relative_change"].as_f64().unwrap().abs() < 0.01, "{r}");
}
/// The heated bracket's 4 mm tet mesh stays near its 23 000 elements. #303: refinement piled
/// face vertices against a feature curve, and the improvement then grew the mesh to 29 257
/// elements in about two minutes. The element count is the check: wall time depends on the
/// machine and the build profile (about 5 s in a release build, far longer on CI).
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_heated_bracket_opens_with_its_usual_mesh() {
let s = open("heated-bracket");
let elements = s.model.elements().len();
assert!((20_000..=26_000).contains(&elements), "{elements} elements");
}
/// The heated bracket's temperatures lie between the air's and the heater's, falling along
/// the bracket away from the heater. Its thermal expansion: with the air at the heater's
/// temperature the bracket warms evenly by ΔT, and held at the foot's hole alone (at x = 40)
@@ -859,11 +917,11 @@ mod tests {
assert!(r["max_von_mises"]["value"].as_f64().unwrap() > 200.0, "{r}");
}
/// The crank opens as one conforming structured hex20 mesh: the
/// half's seven cells, every cut merged node for node (no ties), the half and its mirror
/// The crank opens as one conforming structured hex20 mesh: the half meshed in blocks
/// without partitions or seeds, no ties, the half and its mirror
/// image alike and joined on the symmetry plane, the spindle and pedal faces found on both
/// halves (the image's faces carry the names of the half they are the image of), and the
/// quality floor: scaled Jacobian at least 0.3, edge ratio at most 10.
/// quality floor: scaled Jacobian at least 0.37, edge ratio at most 10.
#[test]
fn the_crank_opens_as_one_structured_mesh_of_two_alike_halves() {
let (arm, mirror) = (find("crank-arm").unwrap(), find("crank-mirror").unwrap());
@@ -876,10 +934,11 @@ mod tests {
let name = "crank-arm";
let mut s = open(name);
let bodies: Vec<String> = s.design.as_ref().unwrap().bodies.iter().map(|b| b.name.clone()).collect();
let mut cells: Vec<String> = CRANK_CELLS.iter().map(|c| c.to_string()).collect();
cells.push("CrankArm/b".into());
assert_eq!(bodies, cells);
assert!(s.model.ties().is_empty(), "every cut merged");
assert_eq!(bodies, [CRANK_HALF, "CrankArm/b"]);
// One datum, the symmetry plane, hidden.
assert!(s.model.datums().len() == 1 && s.model.datums().keys().all(|d| !s.shows(crate::ItemKind::Datum, d)), "datums shown");
assert!(!s.is_dirty(), "a sample just opened has nothing to save");
assert!(s.model.ties().is_empty(), "no ties");
let elements = s.model.elements().values().filter(|e| e.kind == fieldcraft_model::ElementKind::Hex20).count();
assert_eq!(elements, s.model.elements().len());
let mut set = |name: &str, bodies: &[&str]| {
@@ -887,7 +946,7 @@ mod tests {
.unwrap();
s.model.resolve_set(name).unwrap()
};
let (a, b) = (set("half_a", &CRANK_CELLS), set("half_b", &["CrankArm/b"]));
let (a, b) = (set("half_a", &[CRANK_HALF]), set("half_b", &["CrankArm/b"]));
assert_eq!(a.elements.len(), b.elements.len());
assert_eq!(a.elements.len() + b.elements.len(), elements);
assert_eq!(a.faces.len(), b.faces.len(), "the halves' skins are alike");
@@ -897,12 +956,12 @@ mod tests {
let q = s.execute("mesh.quality", &json!({})).unwrap();
assert_eq!(q["valid"].as_u64().unwrap() as usize, elements, "{q}");
let metric = |m: &str, k: &str| q["metrics"][m][k].as_f64().unwrap();
assert!(metric("scaled_jacobian", "min") >= 0.3, "{q}");
assert!(metric("scaled_jacobian", "min") >= 0.37, "{q}");
assert!(metric("edge_ratio", "max") <= 10.0, "{q}");
let members = |set: &str| s.model.sets().get(set).map_or(Vec::new(), |x| x.geometry.iter().map(|g| g.body.clone()).collect::<Vec<_>>());
for set in ["spindle", "pedal"] {
let bodies = members(set);
assert!(bodies.iter().any(|b| b.starts_with("CrankArm/a/")) && bodies.iter().any(|b| b == "CrankArm/b"), "{set}: {bodies:?}");
assert!(bodies.iter().any(|b| b == CRANK_HALF) && bodies.iter().any(|b| b == "CrankArm/b"), "{set}: {bodies:?}");
assert!(!s.model.resolve_set(set).unwrap().faces.is_empty(), "{set}");
}
let faces = |set: &str| s.model.sets().get(set).map_or(0, |x| x.geometry.len());
+218 -3
View File
@@ -74,6 +74,9 @@ pub enum Kind {
Ref(Collection),
/// A list of such names.
RefList(Collection),
/// A choice per item: an object from the names of a collection's items to one of these
/// strings (value, label); an item left out takes the command's default.
RefChoices(Collection, &'static [(&'static str, &'static str)]),
/// A nested object.
Group(&'static [Field]),
/// A nested object (or, with an empty key, the parent object) tagged by `tag`: the tag's value
@@ -92,10 +95,44 @@ pub enum Kind {
fields: &'static [Field],
max: usize,
},
/// A list of mesh labels, nodes or elements (at most [`MAX_LABELS`]).
Labels(LabelOf),
/// A list of points `[x, y, z]`, at most `max`.
Points {
dim: Dim,
max: usize,
},
/// Any of these values, as a list: (the value as JSON text, label), e.g. `("1", "UX")` or
/// `("\"stress\"", "Stress")`.
Multi(&'static [(&'static str, &'static str)]),
/// A number at least `min`, or the string `"auto"`.
NumberOrAuto {
dim: Dim,
min: Option<f64>,
},
/// Any JSON: what the schema does not describe.
Json,
}
/// What a [`Kind::Labels`] list labels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelOf {
Node,
Element,
}
impl LabelOf {
pub fn label(self) -> &'static str {
match self {
LabelOf::Node => "node",
LabelOf::Element => "element",
}
}
}
/// Most labels a [`Kind::Labels`] list holds.
pub const MAX_LABELS: usize = 1_000_000;
/// One variant of [`Kind::Variants`].
#[derive(Debug, Clone, Copy)]
pub struct Variant {
@@ -124,10 +161,14 @@ pub enum Collection {
SolvedStep,
/// A body of the open design.
Body,
/// A datum plane or axis.
/// A datum plane, axis or point.
Datum,
/// A datum plane.
DatumPlane,
/// A datum axis.
DatumAxis,
/// A datum point.
DatumPoint,
Partition,
}
@@ -151,6 +192,8 @@ impl Collection {
Collection::Body => "body",
Collection::Datum => "datum",
Collection::DatumPlane => "datum plane",
Collection::DatumAxis => "datum axis",
Collection::DatumPoint => "datum point",
Collection::Partition => "partition",
}
}
@@ -178,6 +221,8 @@ impl Session {
Collection::Body => Box::new(self.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.as_str()))),
Collection::Datum => Box::new(m.datums().keys().map(String::as_str)),
Collection::DatumPlane => Box::new(m.datums().iter().filter(|(_, d)| d.plane().is_some()).map(|(n, _)| n.as_str())),
Collection::DatumAxis => Box::new(m.datums().iter().filter(|(_, d)| d.axis().is_some()).map(|(n, _)| n.as_str())),
Collection::DatumPoint => Box::new(m.datums().iter().filter(|(_, d)| d.point().is_some()).map(|(n, _)| n.as_str())),
Collection::Partition => Box::new(m.partitions().iter().map(|p| p.name.as_str())),
};
names.take(MAX_NAMES).map(str::to_string).collect()
@@ -343,7 +388,7 @@ impl Field {
/// Its physical dimension, for a number or a vector of numbers.
pub fn dim(&self) -> Option<Dim> {
match self.kind {
Kind::Number { dim, .. } | Kind::Vector { dim, .. } => Some(dim),
Kind::Number { dim, .. } | Kind::Vector { dim, .. } | Kind::Points { dim, .. } | Kind::NumberOrAuto { dim, .. } => Some(dim),
_ => None,
}
}
@@ -421,6 +466,10 @@ pub const fn reference(key: &'static str, label: &'static str, c: Collection) ->
pub const fn references(key: &'static str, label: &'static str, c: Collection) -> Field {
field(key, label, Kind::RefList(c))
}
pub const fn ref_choices(key: &'static str, label: &'static str, c: Collection, options: &'static [(&'static str, &'static str)]) -> Field {
field(key, label, Kind::RefChoices(c, options))
}
pub const fn group(key: &'static str, label: &'static str, fields: &'static [Field]) -> Field {
field(key, label, Kind::Group(fields))
}
@@ -436,6 +485,22 @@ pub const fn unit(key: &'static str, label: &'static str) -> Field {
pub const fn rows(key: &'static str, label: &'static str, fields: &'static [Field]) -> Field {
field(key, label, Kind::Rows { fields, max: MAX_ROWS })
}
/// A list of node or element labels.
pub const fn labels(key: &'static str, label: &'static str, of: LabelOf) -> Field {
field(key, label, Kind::Labels(of))
}
/// A list of points `[x, y, z]`.
pub const fn points(key: &'static str, label: &'static str, dim: Dim, max: usize) -> Field {
field(key, label, Kind::Points { dim, max })
}
/// Any of `options` (each a value as JSON text, and a label), as a list.
pub const fn multi(key: &'static str, label: &'static str, options: &'static [(&'static str, &'static str)]) -> Field {
field(key, label, Kind::Multi(options))
}
/// A number at least `min`, or "auto".
pub const fn number_or_auto(key: &'static str, label: &'static str, dim: Dim, min: Option<f64>) -> Field {
field(key, label, Kind::NumberOrAuto { dim, min })
}
pub const fn json(key: &'static str, label: &'static str) -> Field {
field(key, label, Kind::Json)
}
@@ -446,6 +511,11 @@ pub const fn variant(tag: &'static str, label: &'static str, fields: &'static [F
/// The `name` of a new or edited definition.
pub const NAME: Field = text("name", "Name").req().help("A name for it, unique among its kind; other definitions refer to it by this name.");
/// A [`Kind::Multi`] option's value: its JSON text parsed (text that is not JSON is a string).
pub fn multi_value(option: &str) -> Value {
serde_json::from_str(option).unwrap_or_else(|_| Value::String(option.to_string()))
}
impl Kind {
/// The variant of `tag`, for [`Kind::Variants`].
pub fn variant(&self, tag: &str) -> Option<&'static Variant> {
@@ -651,8 +721,11 @@ impl Problem {
ProblemKind::NotText => "text".into(),
ProblemKind::NotABool => "true or false".into(),
ProblemKind::NotAChoice => match f.map(|f| f.kind) {
Some(Kind::Choice(options)) => format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", ")),
Some(Kind::Choice(options) | Kind::RefChoices(_, options)) => {
format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", "))
}
Some(Kind::Either(options)) => format!("one of {}", options.iter().map(|o| o.key).collect::<Vec<_>>().join(", ")),
Some(Kind::Multi(options)) => format!("a list of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", ")),
_ => "one of the choices".into(),
},
ProblemKind::NotAVector { len } => format!("{len} numbers"),
@@ -769,6 +842,38 @@ pub fn object_problems(fields: &'static [Field], obj: &Map<String, Value>) -> Ve
out
}
/// The top-level keys `params` may hold for these fields: each field's key, and for a flattened
/// one-of (a load's `type`) its tag and the fields of the variant `params` picks (of every
/// variant when it picks none).
pub fn accepted_keys(fields: &[Field], params: &Value) -> Vec<&'static str> {
let mut keys = Vec::new();
for f in fields {
match f.kind {
Kind::Variants { tag, variants } if f.key.is_empty() => {
keys.push(tag);
let picked = params.get(tag).and_then(Value::as_str).and_then(|t| variants.iter().find(|v| v.tag == t));
for v in variants.iter().filter(|v| picked.is_none_or(|p| p.tag == v.tag)) {
for key in accepted_keys(v.fields, params) {
if !keys.contains(&key) {
keys.push(key);
}
}
}
}
_ => keys.push(f.key),
}
}
keys
}
/// The first top-level key of `params` that `fields` do not describe, with the keys they do:
/// a misspelt or misplaced parameter is refused rather than silently ignored.
pub fn unknown_key(fields: &[Field], params: &Value) -> Option<(String, Vec<&'static str>)> {
let obj = params.as_object()?;
let accepted = accepted_keys(fields, params);
obj.keys().find(|k| !accepted.contains(&k.as_str())).map(|k| (k.chars().take(64).collect(), accepted))
}
/// The path of field `key` inside `prefix` (`elastic/young`).
pub fn join(prefix: &str, key: &str) -> String {
if prefix.is_empty() {
@@ -874,6 +979,11 @@ fn value_problem(f: &'static Field, v: &Value, path: &str, out: &mut Vec<Problem
_ => Some(ProblemKind::NotAVector { len: labels.len() }),
},
Kind::RefList(_) => (!v.as_array().is_some_and(|a| a.iter().all(Value::is_string))).then_some(ProblemKind::NotNames),
Kind::RefChoices(_, options) => match v.as_object() {
Some(o) if o.values().all(|x| x.as_str().is_some_and(|s| options.iter().any(|(opt, _)| *opt == s))) => None,
Some(_) => Some(ProblemKind::NotAChoice),
None => Some(ProblemKind::NotAnObject),
},
Kind::Group(fields) => match v.as_object() {
Some(o) => {
check(fields, o, path, out, depth + 1);
@@ -902,6 +1012,29 @@ fn value_problem(f: &'static Field, v: &Value, path: &str, out: &mut Vec<Problem
(!ok).then_some(ProblemKind::NotAChoice)
}
Kind::Unit | Kind::Json => None,
Kind::Labels(_) => match v.as_array() {
Some(a) if a.len() <= MAX_LABELS && a.iter().all(|x| x.as_u64().is_some_and(|n| n >= 1 && n <= u64::from(u32::MAX))) => None,
_ => Some(ProblemKind::NotAList { max: MAX_LABELS, what: "labels" }),
},
Kind::Points { max, .. } => match v.as_array() {
Some(a)
if a.len() <= max
&& a.iter().all(|p| p.as_array().is_some_and(|c| c.len() == 3 && c.iter().all(|x| x.as_f64().is_some_and(f64::is_finite)))) =>
{
None
}
_ => Some(ProblemKind::NotAList { max, what: "points [x, y, z]" }),
},
Kind::Multi(options) => match v.as_array() {
Some(a) if a.iter().all(|x| options.iter().any(|(o, _)| multi_value(o) == *x)) => None,
_ => Some(ProblemKind::NotAChoice),
},
Kind::NumberOrAuto { min, .. } => match (v, v.as_f64().filter(|x| x.is_finite())) {
(Value::String(s), _) if s == "auto" => None,
(_, Some(x)) if min.is_none_or(|lo| x >= lo) => None,
(_, Some(_)) => Some(ProblemKind::Below(min.unwrap_or(0.0))),
_ => Some(ProblemKind::Invalid("a number or \"auto\"".into())),
},
Kind::Rows { fields, max } => match v.as_array() {
Some(a) if a.len() <= max => {
for (i, row) in a.iter().enumerate() {
@@ -995,6 +1128,11 @@ fn field_schema(f: &Field, depth: usize) -> Value {
}
Kind::Ref(c) => json!({"type": "string", "x-references": c.label()}),
Kind::RefList(c) => json!({"type": "array", "items": {"type": "string", "x-references": c.label()}}),
Kind::RefChoices(c, options) => json!({
"type": "object",
"x-references": c.label(),
"additionalProperties": {"enum": options.iter().map(|(o, _)| *o).collect::<Vec<_>>()},
}),
Kind::Group(fields) if depth <= MAX_DEPTH => object_schema(fields, depth + 1),
Kind::Variants { tag, variants } if depth <= MAX_DEPTH => json!({"oneOf": variant_schemas(tag, variants, depth + 1)}),
Kind::Either(options) if depth <= MAX_DEPTH => json!({"oneOf": options.iter().map(|o| match o.kind {
@@ -1003,6 +1141,26 @@ fn field_schema(f: &Field, depth: usize) -> Value {
}).collect::<Vec<_>>()}),
Kind::Rows { fields, max } if depth <= MAX_DEPTH => json!({"type": "array", "items": object_schema(fields, depth + 1), "maxItems": max}),
Kind::Unit => json!({"const": f.key}),
Kind::Labels(of) => {
json!({"type": "array", "items": {"type": "integer", "minimum": 1, "maximum": u32::MAX}, "maxItems": MAX_LABELS, "x-labels": of.label()})
}
Kind::Points { dim, max } => {
let mut item = json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3});
if dim != Dim::None {
item["x-dimension"] = json!(format!("{dim:?}").to_lowercase());
}
json!({"type": "array", "items": item, "maxItems": max})
}
Kind::Multi(options) => {
json!({"type": "array", "items": {"enum": options.iter().map(|(o, _)| multi_value(o)).collect::<Vec<_>>()}, "uniqueItems": true})
}
Kind::NumberOrAuto { min, .. } => {
let mut n = json!({"type": "number"});
if let Some(lo) = min {
n["minimum"] = json!(lo);
}
json!({"oneOf": [n, {"const": "auto"}]})
}
_ => json!({}),
};
s["title"] = json!(f.label);
@@ -1054,6 +1212,40 @@ mod tests {
.def("\"force\""),
];
/// The typed lists check their values and describe themselves in JSON Schema (#169).
#[test]
fn labels_points_multi_and_auto_check() {
const F: &[Field] = &[
labels("nodes", "Nodes", LabelOf::Node),
points("at", "Points", Dim::Length, 2),
multi("dofs", "DOFs", &[("1", "UX"), ("2", "UY")]),
multi("output", "Output", &[("\"stress\"", "Stress")]),
number_or_auto("scale", "Scale", Dim::None, Some(0.0)),
];
assert!(problems(F, &json!({"nodes": [1, 5], "at": [[0, 0, 1e3]], "dofs": [2], "output": ["stress"], "scale": "auto"})).is_empty());
assert!(problems(F, &json!({"scale": 2.5})).is_empty());
for bad in [
json!({"nodes": [0]}),
json!({"nodes": [1.5]}),
json!({"nodes": [u64::from(u32::MAX) + 1]}),
json!({"at": [[0, 0]]}),
json!({"at": [[0, 0, 0], [0, 0, 0], [0, 0, 0]]}),
json!({"at": [[0, 0, "x"]]}),
json!({"dofs": [3]}),
json!({"dofs": ["1"]}),
json!({"output": ["strain"]}),
json!({"scale": -1}),
json!({"scale": "big"}),
] {
assert_eq!(problems(F, &bad).len(), 1, "{bad}");
}
let s = json_schema(F);
assert_eq!(s["properties"]["dofs"]["items"]["enum"], json!([1, 2]));
assert_eq!(s["properties"]["output"]["items"]["enum"], json!(["stress"]));
assert_eq!(s["properties"]["at"]["maxItems"], 2);
assert_eq!(s["properties"]["scale"]["oneOf"][1]["const"], "auto");
}
#[test]
fn prefill_switch_and_check() {
let p = prefill(LOADISH, &json!({}));
@@ -1098,4 +1290,27 @@ mod tests {
assert_eq!(s["oneOf"][1]["properties"]["type"]["const"], "pressure");
assert_eq!(s["oneOf"][1]["required"], json!(["magnitude", "set", "type"]));
}
#[test]
fn unknown_keys_are_found_per_variant() {
assert_eq!(unknown_key(LOADISH, &json!({"name": "P", "type": "pressure", "magnitude": 1})), None);
let (key, accepted) = unknown_key(LOADISH, &json!({"name": "P", "type": "pressure", "magnitud": 1})).unwrap();
assert_eq!(key, "magnitud");
assert!(accepted.contains(&"magnitude") && accepted.contains(&"name"));
}
#[test]
fn every_command_refuses_an_unknown_parameter() {
for spec in crate::commands() {
let mut s = Session::default();
let e = s.execute(spec.id, &json!({"bogus_param": 1})).unwrap_err().to_string();
// A command that cannot run yet says so first; otherwise the key is named.
assert!(e.contains("bogus_param") || s.availability(spec).is_err(), "{}: {e}", spec.id);
}
let mut s = Session::default();
crate::cmd::solve::tests::cantilever(&mut s);
s.execute("solve.run", &json!({})).unwrap();
let e = s.execute("results.contour", &json!({"field": "displacement", "deformed": true})).unwrap_err().to_string();
assert!(e.contains("`deformed`") && e.contains("field"), "{e}");
}
}
+593
View File
@@ -0,0 +1,593 @@
//! Anonymous usage analytics, off until the user agrees (docs/privacy.md).
//!
//! The app records [`Event`]s here; a host (the desktop app's sender thread, the web page's
//! `fetch`) takes them in batches ([`take_batch`]) and posts [`Batch::body`] to PostHog's batch
//! API. Nothing here touches the network.
//!
//! What an event can hold is fixed by its type: command ids, sample names and requirements come
//! from the registries (`&'static str`), never from parameters, paths, file names or messages.
//! Recording does nothing until [`enable`] (the user agreed, and the host may send); [`disable`]
//! drops what is queued. The queue is bounded ([`MAX_QUEUED`]): when full, new events are dropped.
//!
//! [`Session::execute`](crate::Session::execute) counts every top-level command of a session
//! whose [`Session::origin`](crate::Session::origin) is set (the app's own model): its id, kind,
//! duration, whether it failed and how, and where it came from ([`Origin`]); the funnel's
//! [`Milestone`]s and [`Event::SampleOpened`] follow from the same commands.
use std::cell::Cell;
use std::collections::VecDeque;
use std::sync::Mutex;
use serde_json::{Map, Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, EngineError};
/// PostHog Cloud's EU ingestion host.
pub const DEFAULT_HOST: &str = "https://eu.i.posthog.com";
/// Events kept waiting to be sent; more are dropped.
pub const MAX_QUEUED: usize = 1000;
/// Events in one request.
pub const MAX_BATCH: usize = 100;
/// Where a command came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Origin {
/// A click: the ribbon, a menu, a form, the browser.
Ui,
/// The command search or the command line.
Palette,
/// A script or the control channel.
Script,
/// An AI agent through the MCP server.
Mcp,
}
impl Origin {
pub fn as_str(self) -> &'static str {
match self {
Origin::Ui => "ui",
Origin::Palette => "palette",
Origin::Script => "script",
Origin::Mcp => "mcp",
}
}
/// Scripts and agents, which the user can leave out on their own.
pub fn automated(self) -> bool {
matches!(self, Origin::Script | Origin::Mcp)
}
}
/// A step of the way from a design to results, counted once per run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Milestone {
DesignOpened,
Meshed,
Solved,
ResultsViewed,
}
impl Milestone {
pub fn as_str(self) -> &'static str {
match self {
Milestone::DesignOpened => "design_opened",
Milestone::Meshed => "meshed",
Milestone::Solved => "solved",
Milestone::ResultsViewed => "results_viewed",
}
}
fn bit(self) -> u8 {
1 << self as u8
}
}
/// Something that happened, with only what docs/privacy.md lists.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
AppStarted,
/// The window closed after `seconds`.
AppClosed {
seconds: u64,
},
CommandRun {
command: &'static str,
kind: CommandKind,
duration_ms: u64,
error: Option<&'static str>,
from: Origin,
},
Milestone(Milestone),
SampleOpened {
name: &'static str,
},
/// A command's form closed without running it.
FormCancelled {
command: &'static str,
},
/// A command clicked before the model had what it needs.
UnavailableClicked {
command: &'static str,
missing: Vec<Requirement>,
},
}
impl Event {
pub fn name(&self) -> &'static str {
match self {
Event::AppStarted => "app_started",
Event::AppClosed { .. } => "app_closed",
Event::CommandRun { .. } => "command_run",
Event::Milestone(_) => "milestone",
Event::SampleOpened { .. } => "sample_opened",
Event::FormCancelled { .. } => "form_cancelled",
Event::UnavailableClicked { .. } => "unavailable_clicked",
}
}
/// The event's own properties.
pub fn properties(&self) -> Map<String, Value> {
let v = match self {
Event::AppStarted => json!({}),
Event::AppClosed { seconds } => json!({"duration_s": seconds}),
Event::CommandRun { command, kind, duration_ms, error, from } => {
let kind = match kind {
CommandKind::Model => "model",
CommandKind::Session => "session",
};
let mut v = json!({"command": command, "kind": kind, "duration_ms": duration_ms, "ok": error.is_none(), "from": from.as_str()});
if let Some(e) = error {
v["error"] = json!(e);
}
v
}
Event::Milestone(m) => json!({"name": m.as_str()}),
Event::SampleOpened { name } => json!({"name": name}),
Event::FormCancelled { command } => json!({"command": command}),
Event::UnavailableClicked { command, missing } => json!({"command": command, "missing": missing}),
};
match v {
Value::Object(m) => m,
_ => Map::new(),
}
}
}
/// The class of an error, without its message (which can name the user's files and values).
pub fn error_class(e: &EngineError) -> &'static str {
match e {
EngineError::UnknownCommand(_) => "unknown_command",
EngineError::Params(_) | EngineError::Param(_) => "params",
EngineError::Model(_) => "model",
EngineError::Geometry(_) => "geometry",
EngineError::Mesh(_) => "mesh",
EngineError::File(_) => "file",
EngineError::Deck(_) => "deck",
EngineError::Solver(_) => "solver",
EngineError::Explicit(_) => "explicit",
EngineError::Fluid(_) => "fluid",
EngineError::Unavailable(_) => "unavailable",
EngineError::Internal { .. } => "internal",
}
}
/// Who is sending: the anonymous install and the build. The same for every event of a run.
#[derive(Clone, Debug, PartialEq)]
pub struct Identity {
/// A random id made for this install (not derived from the machine or the user).
pub install_id: String,
/// `desktop` or `web`.
pub platform: &'static str,
/// The operating system (`macos`, `linux`, `windows`; `web` in a browser).
pub os: &'static str,
pub arch: &'static str,
pub app_version: &'static str,
}
/// What [`take_batch`] hands the sender.
#[derive(Clone, Debug, PartialEq)]
pub struct Batch {
pub identity: Identity,
pub events: Vec<Event>,
}
impl Batch {
/// The body of a POST to PostHog's `/batch/` endpoint with the project's API key: each event
/// with the anonymous install id, the build, no person profile and no IP-based location.
pub fn body(&self, api_key: &str) -> String {
let id = &self.identity;
let batch: Vec<Value> = self
.events
.iter()
.map(|e| {
let mut p = e.properties();
p.insert("app_version".into(), json!(id.app_version));
p.insert("platform".into(), json!(id.platform));
p.insert("os".into(), json!(id.os));
p.insert("arch".into(), json!(id.arch));
p.insert("$process_person_profile".into(), json!(false));
p.insert("$geoip_disable".into(), json!(true));
json!({"event": e.name(), "distinct_id": id.install_id, "properties": p})
})
.collect();
json!({"api_key": api_key, "batch": batch}).to_string()
}
}
/// Whether this run may record at all, before asking the user: the build has a project key,
/// `FIELDCRAFT_TELEMETRY` (`telemetry`) is not `0`, and a run driven by automation (`--control`)
/// or CI records only when `FIELDCRAFT_TELEMETRY=1` says so.
pub fn allowed(has_key: bool, telemetry: Option<&str>, automation: bool, ci: bool) -> bool {
let set = telemetry.map(|v| v.trim().to_ascii_lowercase());
match set.as_deref() {
Some("0" | "false" | "off" | "no") => false,
Some("1" | "true" | "on" | "yes") => has_key,
_ => has_key && !automation && !ci,
}
}
struct State {
identity: Identity,
/// Count scripts and MCP runs too.
automation: bool,
queue: VecDeque<Event>,
/// Milestones already sent this run.
reached: u8,
/// When recording started ([`now_ms`]), for the session's length.
started: Option<f64>,
}
static STATE: Mutex<Option<State>> = Mutex::new(None);
fn with_state<R>(f: impl FnOnce(&mut Option<State>) -> R) -> R {
// A poisoned lock still holds a usable queue.
let mut g = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
f(&mut g)
}
/// Start recording, as `identity`, with [`Event::AppStarted`]; `automation` counts scripts and
/// MCP runs too. Already recording, only the settings change.
pub fn enable(identity: Identity, automation: bool) {
let now = now_ms();
with_state(|s| match s {
Some(s) => {
s.identity = identity;
s.automation = automation;
}
None => *s = Some(State { identity, automation, queue: VecDeque::from([Event::AppStarted]), reached: 0, started: now }),
});
}
/// The app is closing: [`Event::AppClosed`] with how long it recorded.
pub fn closing() {
let now = now_ms();
let started = with_state(|s| s.as_ref().map(|s| s.started));
if let Some(started) = started {
let seconds = match (started, now) {
(Some(a), Some(b)) if b >= a => ((b - a) / 1000.0).round() as u64,
_ => 0,
};
record(Event::AppClosed { seconds });
}
}
/// Stop recording and drop everything queued.
pub fn disable() {
with_state(|s| *s = None);
}
pub fn enabled() -> bool {
with_state(|s| s.is_some())
}
/// Queue an event, when recording (and when it is no script or MCP run the user left out).
pub fn record(event: Event) {
with_state(|s| {
let Some(s) = s else { return };
match &event {
Event::CommandRun { from, .. } if from.automated() && !s.automation => return,
Event::Milestone(m) if s.reached & m.bit() != 0 => return,
Event::Milestone(m) => s.reached |= m.bit(),
_ => {}
}
if s.queue.len() < MAX_QUEUED {
s.queue.push_back(event);
}
});
}
/// Up to [`MAX_BATCH`] queued events to send, oldest first; `None` when there are none.
pub fn take_batch() -> Option<Batch> {
with_state(|s| {
let s = s.as_mut()?;
if s.queue.is_empty() {
return None;
}
let n = s.queue.len().min(MAX_BATCH);
Some(Batch { identity: s.identity.clone(), events: s.queue.drain(..n).collect() })
})
}
/// Events waiting to be sent.
pub fn queued() -> usize {
with_state(|s| s.as_ref().map_or(0, |s| s.queue.len()))
}
/// A clock in milliseconds for command durations. The plain wasm target has none: the web page
/// sets one ([`set_clock`]).
static CLOCK: Mutex<Option<fn() -> f64>> = Mutex::new(None);
/// Use `clock` (milliseconds, any origin) for command durations.
pub fn set_clock(clock: fn() -> f64) {
*CLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(clock);
}
fn now_ms() -> Option<f64> {
if let Some(c) = *CLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
return Some(c());
}
#[cfg(not(target_arch = "wasm32"))]
{
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
Some(START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0)
}
#[cfg(target_arch = "wasm32")]
None
}
thread_local! {
/// Commands running on this thread: only the outermost is counted.
static DEPTH: Cell<u32> = const { Cell::new(0) };
}
/// A command being counted, from [`Session::execute`](crate::Session::execute): `None` when it
/// is not (not recording, no origin, or a command inside another).
pub(crate) struct Timer {
started: Option<f64>,
from: Option<Origin>,
}
impl Timer {
pub(crate) fn start(from: Option<Origin>) -> Timer {
let outer = DEPTH.with(|d| {
d.set(d.get() + 1);
d.get() == 1
});
let from = from.filter(|_| outer && enabled());
Timer { started: from.and_then(|_| now_ms()), from }
}
/// Whether this command is counted.
pub(crate) fn counting(&self) -> bool {
self.from.is_some()
}
/// The command ended: count it, and the milestone it reached.
pub(crate) fn done(
&self,
command: &'static str,
kind: CommandKind,
error: Option<&EngineError>,
milestone: Option<Milestone>,
sample: Option<&'static str>,
) {
let Some(from) = self.from else { return };
let duration_ms = match (self.started, now_ms()) {
(Some(a), Some(b)) if b >= a => (b - a).round() as u64,
_ => 0,
};
record(Event::CommandRun { command, kind, duration_ms, error: error.map(error_class), from });
if error.is_none() {
if let Some(m) = milestone {
record(Event::Milestone(m));
}
if let Some(name) = sample {
record(Event::SampleOpened { name });
}
}
}
}
impl Drop for Timer {
fn drop(&mut self) {
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
/// The milestone a successful `command` reaches; `elements` is the element count before and
/// after it.
pub(crate) fn milestone(command: &str, elements: (usize, usize)) -> Option<Milestone> {
match command {
"geometry.open" | "geometry.import.mesh" | "file.open" => Some(Milestone::DesignOpened),
c if c.starts_with("mesh.") && elements.1 > elements.0 => Some(Milestone::Meshed),
// Solvers, not the queries on a solved step.
c if c.starts_with("solve.") && !matches!(c, "solve.probe" | "solve.history") => Some(Milestone::Solved),
c if c.starts_with("results.") && !matches!(c, "results.reactions" | "results.clear") => Some(Milestone::ResultsViewed),
_ => None,
}
}
/// Serialises the tests (and other code) that turn the process-wide recording on.
#[doc(hidden)]
pub static TEST_LOCK: Mutex<()> = Mutex::new(());
#[cfg(test)]
mod tests {
use super::*;
use crate::Session;
fn identity() -> Identity {
Identity { install_id: "00000000-0000-4000-8000-000000000000".into(), platform: "desktop", os: "test", arch: "test", app_version: "0.0.0" }
}
fn take_all() -> Vec<Event> {
std::iter::from_fn(take_batch).flat_map(|b| b.events).collect()
}
/// Every string in a payload is a key, a registry name or the identity, and every number a
/// duration: no path, file name, parameter value or message can be in it.
pub(crate) fn assert_clean(body: &str) {
let v: Value = serde_json::from_str(body).unwrap();
let mut allowed: Vec<String> = crate::commands().iter().map(|c| c.id.to_string()).collect();
allowed.extend(crate::sample::SAMPLES.iter().map(|s| s.name.to_string()));
for e in [
"app_started",
"app_closed",
"command_run",
"milestone",
"sample_opened",
"form_cancelled",
"unavailable_clicked",
"model",
"session",
"ui",
"palette",
"script",
"mcp",
"design_opened",
"meshed",
"solved",
"results_viewed",
"unknown_command",
"params",
"geometry",
"mesh",
"file",
"deck",
"solver",
"explicit",
"fluid",
"unavailable",
"internal",
"KEY",
] {
allowed.push(e.into());
}
let id = identity();
allowed.extend([id.install_id, id.platform.into(), id.os.into(), id.arch.into(), id.app_version.into()]);
fn walk(key: &str, v: &Value, allowed: &[String]) {
match v {
Value::String(s) => {
// A requirement's snake_case name.
let requirement = key == "missing" && s.chars().all(|c| c.is_ascii_lowercase() || c == '_');
assert!(allowed.contains(s) || requirement, "`{key}`: `{s}` is not a name FieldCraft defines");
}
Value::Number(_) => assert!(["duration_ms", "duration_s"].contains(&key), "`{key}`: a number that is not a duration"),
Value::Array(a) => a.iter().for_each(|x| walk(key, x, allowed)),
Value::Object(m) => m.iter().for_each(|(k, x)| walk(k, x, allowed)),
Value::Bool(_) | Value::Null => {}
}
}
walk("", &v, &allowed);
}
#[test]
fn nothing_is_queued_without_consent() {
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
disable();
let mut s = Session { origin: Some(Origin::Ui), ..Default::default() };
s.run_script(&crate::sample::cantilever()).unwrap();
record(Event::AppStarted);
assert_eq!(queued(), 0);
assert!(take_batch().is_none());
}
#[test]
fn a_scripted_session_sends_only_names_and_durations() {
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
disable();
enable(identity(), true);
let dir = std::env::temp_dir().join(format!("fieldcraft-usage-secret-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let design = dir.join("my-secret-bracket.solidcraft");
std::fs::write(&design, fieldcraft_geometry::sample::plate_design(&fieldcraft_geometry::sample::Plate::default()).unwrap()).unwrap();
let mut s = Session { origin: Some(Origin::Script), ..Default::default() };
s.execute("geometry.open", &json!({"path": design.to_string_lossy()})).unwrap();
s.run_script(&crate::sample::cantilever()).unwrap();
s.execute("model.material.create", &json!({"name": "Secret alloy 7", "elastic": {"young": 123456.75, "poisson": 0.3125}})).ok();
s.execute("solve.run", &json!({})).unwrap();
s.execute("results.contour", &json!({"field": "von_mises"})).unwrap();
// A failure whose message names a path, and a sample.
assert!(s.execute("file.open", &json!({"path": dir.join("missing-secret.fieldcraft").to_string_lossy()})).is_err());
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
// An unknown id is user text: not counted.
assert!(s.execute("secret.command", &json!({})).is_err());
let events = take_all();
let body = Batch { identity: identity(), events: events.clone() }.body("KEY");
assert_clean(&body);
for secret in ["secret", "Secret", "123456", "0.3125", "1000", dir.to_string_lossy().as_ref()] {
assert!(!body.contains(secret), "{secret} in {body}");
}
let names: Vec<&str> = events.iter().map(Event::name).collect();
assert!(names.contains(&"command_run") && names.contains(&"sample_opened"), "{names:?}");
// Inner commands (the script's steps run by execute, a sample's own script) count once.
let runs = events.iter().filter(|e| matches!(e, Event::CommandRun { command: "file.sample", .. })).count();
assert_eq!(runs, 1);
let reached: Vec<_> = events.iter().filter_map(|e| if let Event::Milestone(m) = e { Some(*m) } else { None }).collect();
for m in [Milestone::DesignOpened, Milestone::Meshed, Milestone::Solved, Milestone::ResultsViewed] {
assert_eq!(reached.iter().filter(|r| **r == m).count(), 1, "{m:?} once: {reached:?}");
}
assert!(
events.iter().any(|e| matches!(e, Event::CommandRun { command: "file.open", error: Some("file"), from: Origin::Script, .. })),
"{events:?}"
);
disable();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn scripts_and_agents_can_be_left_out_and_the_queue_is_bounded() {
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
disable();
enable(identity(), false);
let run = |from| Event::CommandRun { command: "model.info", kind: CommandKind::Model, duration_ms: 1, error: None, from };
record(run(Origin::Mcp));
record(run(Origin::Script));
record(run(Origin::Palette));
assert_eq!(take_all(), [Event::AppStarted, run(Origin::Palette)]);
for _ in 0..MAX_QUEUED + 50 {
record(Event::AppStarted);
}
assert_eq!(queued(), MAX_QUEUED);
let first = take_batch().unwrap();
assert_eq!(first.events.len(), MAX_BATCH);
assert_eq!(queued(), MAX_QUEUED - MAX_BATCH);
// Turning it off drops what waits.
disable();
assert_eq!(queued(), 0);
enable(identity(), true);
closing();
assert!(matches!(take_all()[..], [Event::AppStarted, Event::AppClosed { .. }]));
disable();
}
#[test]
fn the_body_is_a_posthog_batch() {
let b = Batch {
identity: identity(),
events: vec![Event::UnavailableClicked { command: "solve.run", missing: vec![Requirement::Step, Requirement::Material] }],
};
let v: Value = serde_json::from_str(&b.body("phc_test")).unwrap();
assert_eq!(v["api_key"], "phc_test");
let e = &v["batch"][0];
assert_eq!((e["event"].as_str(), e["distinct_id"].as_str()), (Some("unavailable_clicked"), Some(identity().install_id.as_str())));
assert_eq!(e["properties"]["missing"], json!(["step", "material"]));
assert_eq!(e["properties"]["$process_person_profile"], false);
assert_eq!(e["properties"]["$geoip_disable"], true);
assert_clean(&b.body("KEY"));
}
#[test]
fn telemetry_is_off_without_a_key_in_automation_and_ci_and_when_turned_off() {
assert!(allowed(true, None, false, false));
assert!(!allowed(false, None, false, false));
assert!(!allowed(false, Some("1"), false, false));
assert!(!allowed(true, Some("0"), false, false));
assert!(!allowed(true, Some(" off "), false, false));
assert!(!allowed(true, None, true, false));
assert!(!allowed(true, None, false, true));
assert!(!allowed(true, Some(""), true, false));
assert!(allowed(true, Some("1"), true, true));
}
}
+29 -26
View File
@@ -8,15 +8,16 @@
//! deformed shape (automatic or chosen scale) with its contour bands. Animation is not drawn: a
//! picture shows the full deformation (a mode at its positive shape). The analysis setup's
//! symbols ([`fieldcraft_render::glyphs`]) are drawn over the model as the viewport draws them,
//! muted over a results plot, at their default size on screen once the camera is known.
//! muted over a results plot (and only those its step used), at their default size on screen
//! once the camera is known.
use fieldcraft_model::ElementKind;
use fieldcraft_render::contour::{Bands, band_color, split_triangle};
use fieldcraft_render::contour::{bands_color, split_triangle};
use fieldcraft_render::glyphs::{self, GlyphColors, GlyphShow, GlyphView, Glyphs};
use fieldcraft_render::{Aabb3, Camera, DisplayMesh, Orientation, Rgb, Scene, SceneLine, SceneTri, Vec3};
use serde_json::Value;
use crate::results::{displacements, field_values, magnitude, range};
use crate::results::{auto_scale, displacements, field_values, range};
use crate::{EngineError, Result, Session};
/// The colours of a picture.
@@ -38,10 +39,15 @@ pub struct Palette {
pub no_result: Rgb,
/// The contour colour scale, low to high.
pub contour: [Rgb; 5],
/// Values above a clamped legend's maximum.
pub contour_over: Rgb,
/// The analysis setup's symbols.
pub glyphs: GlyphColors,
}
/// Values above a clamped legend's maximum (both themes): a deep purple apart from the scale's red.
pub const CONTOUR_OVER: Rgb = Rgb(0x6e, 0x2c, 0x80);
impl Palette {
/// The desktop app's light theme.
pub const LIGHT: Palette = Palette {
@@ -66,6 +72,7 @@ impl Palette {
],
no_result: Rgb(0x9a, 0xa0, 0xaa),
contour: [Rgb(0x2b, 0x4f, 0xd8), Rgb(0x2f, 0xb8, 0xe0), Rgb(0x3c, 0xc8, 0x64), Rgb(0xf0, 0xd2, 0x3c), Rgb(0xe0, 0x40, 0x2e)],
contour_over: CONTOUR_OVER,
glyphs: GlyphColors {
constraint: Rgb(0x00, 0x8a, 0xa8),
load: Rgb(0xd0, 0x24, 0x24),
@@ -93,8 +100,6 @@ impl Palette {
const EDGE_WIDTH: f64 = 1.0;
const GEOMETRY_EDGE_WIDTH: f64 = 1.5;
const LINE_ELEMENT_WIDTH: f64 = 3.0;
/// The automatic scale draws the largest displacement this fraction of the model's size.
const AUTO_FRACTION: f64 = 0.1;
/// The chordal tolerance geometry is tessellated with for display: a thousandth of its size.
fn display_tolerance(b: &Aabb3) -> f64 {
@@ -119,16 +124,16 @@ pub struct Shown {
/// The model's display data with the open design's bodies and the imported surfaces.
pub fn display(s: &Session) -> (DisplayMesh, Vec<String>) {
let mut d = DisplayMesh::from_model(&s.model);
let mut d = DisplayMesh::from_model_hiding(&s.model, &s.hidden_elements());
let mut failed = Vec::new();
for body in s.design.iter().flat_map(|d| &d.bodies) {
for body in s.design.iter().flat_map(|d| &d.bodies).filter(|b| s.shows(fieldcraft_io::ItemKind::Body, &b.name)) {
let mesh = body.measure().and_then(|m| body.tessellate(display_tolerance(&Aabb3 { min: m.bbox_min.into(), max: m.bbox_max.into() })));
match mesh {
Ok(m) => d.add_surface(&m.positions, &m.triangles, &m.tri_face),
Err(e) => failed.push(format!("{}: {e}", body.name)),
}
}
for surface in &s.surfaces {
for surface in s.surfaces.iter().filter(|x| s.shows(fieldcraft_io::ItemKind::Surface, &x.name)) {
d.add_surface(&surface.mesh.positions, &surface.mesh.triangles, &surface.mesh.tri_face);
}
(d, failed)
@@ -164,6 +169,8 @@ struct Picture {
shown: Shown,
glyphs: Glyphs,
colors: GlyphColors,
/// The box around the datums drawn: inside the clipping radius, never framed (#295).
datums: Aabb3,
}
impl Picture {
@@ -180,28 +187,22 @@ impl Picture {
fn picture(s: &Session, p: &Palette) -> Picture {
let (base, failed) = display(s);
let glyphs = Glyphs::from_model(&s.model);
let mut shown = Shown { failed, ..Shown::default() };
let plot = s.results_view.as_ref().and_then(|v| s.latest_result(&v.step).map(|(r, _)| (v, r)));
// Over a results plot, the symbols of what its step used.
let glyphs = plot.map_or_else(|| s.glyphs(), |(v, _)| s.step_glyphs(&v.step));
let Some((view, result)) = plot else {
let mut scene = model_scene(&base, p);
let mut bounds = base.bounds;
bounds.union(fieldcraft_render::glyphs::datums(&s.model, &base.bounds, &p.glyphs, &mut scene));
return Picture { scene, drawn: base, bounds, shown, glyphs, colors: p.glyphs };
let bounds = base.bounds;
let shows = |n: &str| s.shows(fieldcraft_io::ItemKind::Datum, n);
let datums = fieldcraft_render::glyphs::datums(&s.model, &base.bounds, &shows, None, &p.glyphs, &mut scene);
return Picture { scene, drawn: base, bounds, shown, glyphs, colors: p.glyphs, datums };
};
shown.step = Some(view.step.clone());
let pick = view.pick();
let nodes = result.nodes();
let u = displacements(result, pick).unwrap_or(&[]);
let scale = if !view.deformed {
0.0
} else if let Some(k) = view.scale {
k
} else {
let largest = u.iter().map(|v| magnitude(*v)).filter(|m| m.is_finite()).fold(0.0, f64::max);
let size = base.bounds.diagonal();
if largest > 0.0 && size.is_finite() && size > 0.0 { AUTO_FRACTION * size / largest } else { 0.0 }
};
let scale = if !view.deformed { 0.0 } else { view.scale.unwrap_or_else(|| auto_scale(result, pick, base.bounds.diagonal())) };
shown.scale = scale;
let drawn = base.displaced(|label| {
let i = nodes.binary_search(&label).ok()?;
@@ -215,12 +216,12 @@ fn picture(s: &Session, p: &Palette) -> Picture {
});
if let Some((field, min, max, values)) = contour {
shown.contour = Some((field.id().to_string(), min, max));
let bands = Bands::new(min.1, max.1, view.bands);
let bands = view.bands(min.1, max.1);
let at = |label: u32| nodes.binary_search(&label).ok().and_then(|i| values.get(i).copied()).unwrap_or(f64::NAN);
scene.tris.clear();
for tri in &drawn.tris {
split_triangle(tri.p, tri.nodes.map(at), &bands, &mut |piece, band| {
let color = band.map_or(p.no_result, |k| band_color(&p.contour, k, bands.count));
let color = band.map_or(p.no_result, |k| bands_color(&p.contour, p.contour_over, &bands, k));
for k in 1..piece.len().saturating_sub(1) {
if let (Some(&a), Some(&b), Some(&c)) = (piece.first(), piece.get(k), piece.get(k + 1)) {
scene.tris.push(SceneTri { p: [a, b, c], normal: tri.normal, color });
@@ -231,7 +232,7 @@ fn picture(s: &Session, p: &Palette) -> Picture {
}
let mut bounds = base.bounds;
bounds.union(drawn.bounds);
Picture { scene, drawn, bounds, shown, glyphs, colors: p.glyphs.over_results(p.background.1) }
Picture { scene, drawn, bounds, shown, glyphs, colors: p.glyphs.over_results(p.background.1), datums: Aabb3::EMPTY }
}
/// The scene of the session (the model, or the results view's plot) with the setup's symbols
@@ -263,14 +264,15 @@ pub fn orientation(p: &Value) -> Result<Orientation> {
Orientation::checked(yaw, pitch, distance).ok_or_else(|| bad("`yaw` and `pitch` must be finite and `distance` finite and above 0"))
}
/// A PNG of the session seen from `at`, `w` × `h` pixels: framing everything drawn, or from
/// A PNG of the session seen from `at`, `w` × `h` pixels: framing everything drawn but the
/// datums (they are drawn at the model's extent, and framing them would only add margin), or from
/// `at`'s distance when it has one. The symbols are drawn at their default size on screen
/// ([`glyphs::DEFAULT_SIZE`] pixels) for that camera.
pub fn render_png(s: &Session, at: &Orientation, w: usize, h: usize, p: &Palette) -> Result<(Vec<u8>, Shown)> {
let mut pic = picture(s, p);
let mut cam = Camera::default();
let aspect = w as f64 / h.max(1) as f64;
let unit = |cam: &Camera| cam.length_per_pixel(h as f64).and_then(|l| glyphs::symbol_unit(l, glyphs::DEFAULT_SIZE)).unwrap_or(f64::NAN);
let unit = |cam: &Camera| glyphs::unit_for(cam, h as f64, glyphs::DEFAULT_SIZE, 1.0).unwrap_or(f64::NAN);
// Framed on the model, then again with its symbols at that camera's size, which reach a
// little beyond it.
cam.orient(&Orientation { distance: None, ..*at });
@@ -283,6 +285,7 @@ pub fn render_png(s: &Session, at: &Orientation, w: usize, h: usize, p: &Palette
symbols = Scene::default();
let mut bounds = pic.bounds;
bounds.union(pic.symbols(unit(&cam), &mut symbols));
bounds.union(pic.datums);
pic.scene.radius = if bounds.is_empty() { 1.0 } else { (cam.target.dist(bounds.center()) + bounds.diagonal() * 0.5).max(1e-3) };
let png = fieldcraft_render::render_layers_png(&pic.scene, &[&symbols], &cam, w, h).map_err(|e| EngineError::Params(format!("render: {e}")))?;
Ok((png, pic.shown))
@@ -0,0 +1 @@
[{"command": "solid.box", "params": {"length": 112, "width": 82, "height": 36, "corner": [0, 0, 0], "body_name": "Base"}}, {"command": "solid.fillet", "params": {"edges": [[0, 0, 18.0], [112, 0, 18.0], [0, 82, 18.0], [112, 82, 18.0]], "radius": 5}}, {"command": "solid.shell", "params": {"faces": [[56.0, 41.0, 36]], "thickness": 3, "direction": "inside", "body": "Base"}}, {"command": "solid.cylinder", "params": {"diameter": 13, "height": 36, "base": [-1, -1, 0], "operation": "join", "targets": ["Base"]}}, {"command": "solid.cylinder", "params": {"diameter": 13, "height": 36, "base": [113, -1, 0], "operation": "join", "targets": ["Base"]}}, {"command": "solid.cylinder", "params": {"diameter": 13, "height": 36, "base": [-1, 83, 0], "operation": "join", "targets": ["Base"]}}, {"command": "solid.cylinder", "params": {"diameter": 13, "height": 36, "base": [113, 83, 0], "operation": "join", "targets": ["Base"]}}, {"command": "solid.hole", "params": {"position": [-1, -1, 36], "diameter": 3.3, "depth": 20}}, {"command": "solid.hole", "params": {"position": [113, -1, 36], "diameter": 3.3, "depth": 20}}, {"command": "solid.hole", "params": {"position": [-1, 83, 36], "diameter": 3.3, "depth": 20}}, {"command": "solid.hole", "params": {"position": [113, 83, 36], "diameter": 3.3, "depth": 20}}, {"command": "solid.cylinder", "params": {"diameter": 6, "height": 6, "base": [16.5, 16.5, 3], "operation": "join", "targets": ["Base"]}}, {"command": "solid.cylinder", "params": {"diameter": 6, "height": 6, "base": [74.5, 16.5, 3], "operation": "join", "targets": ["Base"]}}, {"command": "solid.cylinder", "params": {"diameter": 6, "height": 6, "base": [16.5, 65.5, 3], "operation": "join", "targets": ["Base"]}}, {"command": "solid.cylinder", "params": {"diameter": 6, "height": 6, "base": [74.5, 65.5, 3], "operation": "join", "targets": ["Base"]}}, {"command": "sketch.create", "params": {"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Nut1"}}, {"command": "sketch.polygon.inscribed", "params": {"center": [34, 17], "radius": 11, "sides": 6, "angle": 0}}, {"command": "sketch.finish", "params": {}}, {"command": "solid.extrude", "params": {"sketch": "Nut1", "profiles": "all", "distance": 6, "operation": "new", "body_name": "Gland1"}}, {"command": "solid.cylinder", "params": {"diameter": 17, "height": 8, "base": [34, -6, 17], "axis": [0, -1, 0], "operation": "join", "targets": ["Gland1"]}}, {"command": "solid.cylinder", "params": {"diameter": 14, "height": 6, "base": [34, -14, 17], "axis": [0, -1, 0], "operation": "join", "targets": ["Gland1"]}}, {"command": "solid.fillet", "params": {"edges": [[34, -20, 24]], "radius": 2.5, "body": "Gland1"}}, {"command": "solid.cylinder", "params": {"diameter": 6.5, "height": 30, "base": [34, -20, 17], "axis": [0, -1, 0], "operation": "new", "body_name": "Cable1"}}, {"command": "sketch.create", "params": {"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Nut2"}}, {"command": "sketch.polygon.inscribed", "params": {"center": [66, 17], "radius": 11, "sides": 6, "angle": 0}}, {"command": "sketch.finish", "params": {}}, {"command": "solid.extrude", "params": {"sketch": "Nut2", "profiles": "all", "distance": 6, "operation": "new", "body_name": "Gland2"}}, {"command": "solid.cylinder", "params": {"diameter": 17, "height": 8, "base": [66, -6, 17], "axis": [0, -1, 0], "operation": "join", "targets": ["Gland2"]}}, {"command": "solid.cylinder", "params": {"diameter": 14, "height": 6, "base": [66, -14, 17], "axis": [0, -1, 0], "operation": "join", "targets": ["Gland2"]}}, {"command": "solid.fillet", "params": {"edges": [[66, -20, 24]], "radius": 2.5, "body": "Gland2"}}, {"command": "solid.cylinder", "params": {"diameter": 6.5, "height": 30, "base": [66, -20, 17], "axis": [0, -1, 0], "operation": "new", "body_name": "Cable2"}}, {"command": "sketch.create", "params": {"plane": {"origin": [112, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Nut3"}}, {"command": "sketch.polygon.inscribed", "params": {"center": [41.0, 18], "radius": 14, "sides": 6, "angle": 0}}, {"command": "sketch.finish", "params": {}}, {"command": "solid.extrude", "params": {"sketch": "Nut3", "profiles": "all", "distance": 5, "operation": "new", "body_name": "Gland3"}}, {"command": "solid.cylinder", "params": {"diameter": 24, "height": 17, "base": [117, 41.0, 18], "axis": [1, 0, 0], "operation": "join", "targets": ["Gland3"]}}, {"command": "solid.hole", "params": {"position": [134, 41.0, 18], "diameter": 14, "depth": 15}}, {"command": "solid.fillet", "params": {"edges": [[134, 41.0, 30]], "radius": 2, "body": "Gland3"}}, {"command": "solid.box", "params": {"length": 110.8, "width": 80.8, "height": 1.6, "corner": [0.6, 0.6, 36], "operation": "new", "body_name": "ORing"}}, {"command": "solid.box", "params": {"length": 107.2, "width": 77.2, "height": 1.6, "corner": [2.4, 2.4, 36], "operation": "cut", "targets": ["ORing"]}}, {"command": "solid.box", "params": {"length": 128, "widthLine truncated
+8
View File
@@ -23,6 +23,9 @@
//! The run starts from u = 0 and the initial velocities with the half increment
//! v^{½} = v^0 + ½Δt^{½} a^0.
/// Increments between progress reports (each takes a lock).
const PROGRESS_EVERY: u64 = 64;
use fieldcraft_model::{ExplicitDynamic, Model, OutputVariable, Procedure, Step};
use crate::contact::{Evaluation, Interface};
@@ -356,7 +359,12 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
let mut v_now = v0;
let mut completed = true;
let mut v_new = vec![0.0; n];
fieldcraft_model::progress::stage("Time", Some(end), "");
loop {
if increments.is_multiple_of(PROGRESS_EVERY) {
fieldcraft_model::progress::count(t);
fieldcraft_model::progress::check()?;
}
if increments >= max_increments {
completed = false;
warnings.push(format!("stopped at time {t:.6e} after {increments} increments (the cap); the step ends at {end:.6e}"));
+2 -2
View File
@@ -18,9 +18,9 @@ thiserror = { workspace = true }
zip = { workspace = true }
quick-xml = { workspace = true }
solidcraft-engine = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
serde_json = { workspace = true }
[features]
# Build designs from SolidCraft command scripts (`script_design`): the test corpus and tooling.
# Off by default; the library itself only opens designs.
scripts = ["dep:solidcraft-engine", "dep:serde_json"]
scripts = ["dep:solidcraft-engine"]
+159 -6
View File
@@ -34,12 +34,58 @@ pub struct Design {
pub struct FeatureError {
pub feature: String,
pub message: String,
/// The bodies that may differ from the design as SolidCraft builds it: those the feature
/// names, or every body when it names none of them.
pub bodies: Vec<String>,
}
impl FeatureError {
/// One line for the person opening the design, naming the bodies it may change.
pub fn warning(&self) -> String {
format!("{} failed to build, so {} may differ from the design: {}", self.feature, quoted(&self.bodies), self.message)
}
}
fn quoted(bodies: &[String]) -> String {
match bodies {
[] => "the design".into(),
[b] => format!("body \"{b}\""),
_ => format!("bodies {}", bodies.iter().map(|b| format!("\"{b}\"")).collect::<Vec<_>>().join(", ")),
}
}
/// The bodies of `bodies` that `feature` names anywhere in its saved form (targets, tools,
/// selections); all of them when it names none.
fn bodies_of(feature: Option<&solidcraft_doc::Feature>, bodies: &[Shape]) -> Vec<String> {
fn strings<'a>(v: &'a serde_json::Value, out: &mut Vec<&'a str>) {
match v {
serde_json::Value::String(s) => out.push(s),
serde_json::Value::Array(a) => a.iter().for_each(|v| strings(v, out)),
serde_json::Value::Object(o) => o.values().for_each(|v| strings(v, out)),
_ => {}
}
}
let value = feature.and_then(|f| serde_json::to_value(f).ok()).unwrap_or_default();
let mut named = Vec::new();
strings(&value, &mut named);
let hit: Vec<String> = bodies.iter().filter(|b| named.contains(&b.name.as_str())).map(|b| b.name.clone()).collect();
if hit.is_empty() { bodies.iter().map(|b| b.name.clone()).collect() } else { hit }
}
impl Design {
pub fn body(&self, name: &str) -> Option<&Shape> {
self.bodies.iter().find(|b| b.name == name)
}
/// The body of the design as opened that `name` is, or that partitions cut it from
/// (`Base` for `Base/a/b1`).
pub fn source_of(&self, name: &str) -> Option<&str> {
self.source
.iter()
.map(|b| b.name.as_str())
.filter(|s| name == *s || name.strip_prefix(s).is_some_and(|rest| rest.starts_with('/')))
.max_by_key(|s| s.len())
}
}
/// Open a design from its file bytes (a `.solidcraft` container or a JSON design) and rebuild it.
@@ -55,12 +101,6 @@ pub(crate) fn rebuild(doc: &Document) -> Result<Design> {
m.evaluate(doc);
Ok(m)
})?;
let errors = model
.results
.iter()
.filter(|r| !r.skipped)
.filter_map(|r| r.error.as_ref().map(|e| FeatureError { feature: r.name.clone(), message: e.clone() }))
.collect();
// Placed in the world: a component's bodies through every occurrence of it (an instance is a
// body of its own, named after its occurrence path), as SolidCraft displays and exports them.
let state = guard("place components", || Ok(solidcraft_doc::world_state(doc, &model.state())))?;
@@ -72,12 +112,125 @@ pub(crate) fn rebuild(doc: &Document) -> Result<Design> {
})?;
bodies.push(Shape { name: b.name.clone(), body: b.body.clone(), faces });
}
// A feature that failed leaves a different solid than SolidCraft's: each one names the bodies
// it would have changed, so opening never hands back a silently different solid.
let errors: Vec<FeatureError> = model
.results
.iter()
.filter(|r| !r.skipped)
.filter_map(|r| {
let message = r.error.clone()?;
let bodies = bodies_of(doc.features.iter().find(|f| f.id == r.id), &bodies);
Some(FeatureError { feature: r.name.clone(), message, bodies })
})
.collect();
// The errors name the bodies as SolidCraft does; they follow the pieces' new names.
let renamed = number_split_bodies(&mut bodies);
let errors = errors
.into_iter()
.map(|mut e| {
for b in &mut e.bodies {
if let Some((_, new)) = renamed.iter().find(|(old, _)| old == b) {
*b = new.clone();
}
}
e
})
.collect();
Ok(Design { name: doc.name.clone(), source: std::sync::Arc::new(bodies.clone()), bodies, errors, cuts: Vec::new() })
}
/// A body name without the suffixes SolidCraft gives the pieces of a split body: ` (1)` for the
/// new piece and `'` for a piece kept under its old name, any number of times
/// (`Bracket (1) (1)' (1)` → `Bracket`).
fn split_base(name: &str) -> &str {
let mut s = name;
loop {
let t = s.trim_end_matches('\'');
let t = match t.strip_suffix(')').and_then(|r| r.rsplit_once(" (")) {
Some((head, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => head,
_ => t,
};
if t.len() == s.len() || t.is_empty() {
return s;
}
s = t;
}
}
/// Name the pieces of a body split in the design `<body>.1`, `<body>.2`, … by position, instead
/// of the suffixes the splits stacked up (`Bracket (1) (1)' (1)`), which say nothing about where
/// a piece is. Pieces are ordered by centroid, x first, then y, then z, on a grid of a millionth
/// of their spread, so the names follow the geometry, not the order of the design's timeline. A
/// group is left as it is when one of the new names is a body's name already. The pieces keep
/// the group's places in the list of bodies, in the order of their numbers. Returns each
/// renamed body's (old, new) name.
fn number_split_bodies(bodies: &mut [Shape]) -> Vec<(String, String)> {
let mut renamed = Vec::new();
let mut groups: std::collections::BTreeMap<String, Vec<usize>> = std::collections::BTreeMap::new();
for (i, b) in bodies.iter().enumerate() {
groups.entry(split_base(&b.name).to_string()).or_default().push(i);
}
for (base, mut members) in groups {
if members.len() < 2 || members.iter().all(|&i| bodies.get(i).is_none_or(|b| b.name == base)) {
continue;
}
let names: Vec<String> = (1..=members.len()).map(|k| format!("{base}.{k}")).collect();
if bodies.iter().any(|b| names.contains(&b.name)) {
continue;
}
let centroid = |i: usize| bodies.get(i).and_then(|b| b.measure().ok()).map_or([0.0; 3], |m| m.centroid);
let centres: Vec<[f64; 3]> = members.iter().map(|&i| centroid(i)).collect();
let spread = (0..3)
.map(|k| {
let (lo, hi) = centres.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), c| (lo.min(c[k]), hi.max(c[k])));
hi - lo
})
.fold(0.0f64, f64::max);
let grid = if spread.is_finite() && spread > 0.0 { spread * 1e-6 } else { 1.0 };
let key = |j: usize| centres.get(j).map_or([0; 3], |c| c.map(|v| (v / grid).round() as i64));
let mut order: Vec<usize> = (0..members.len()).collect();
order.sort_by_key(|&j| (key(j), j));
// The group keeps its places in the list, now in the order of the numbers.
let ordered: Vec<Shape> = order.into_iter().filter_map(|j| members.get(j).and_then(|&i| bodies.get(i)).cloned()).collect();
members.sort_unstable();
for ((slot, mut shape), name) in members.into_iter().zip(ordered).zip(names) {
renamed.push((std::mem::replace(&mut shape.name, name.clone()), name));
if let Some(b) = bodies.get_mut(slot) {
*b = shape;
}
}
}
renamed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_suffixes_are_stripped() {
assert_eq!(split_base("Bracket (1) (1)' (1)"), "Bracket");
assert_eq!(split_base("Bracket (1)'''"), "Bracket");
assert_eq!(split_base("Bracket"), "Bracket");
assert_eq!(split_base("Part (a)"), "Part (a)");
assert_eq!(split_base("(1)"), "(1)");
assert_eq!(split_base("'''"), "'''");
}
#[cfg(feature = "scripts")]
/// The corpus bracket, split 29 times in the design, opens as `Bracket.1` … `Bracket.30`,
/// numbered by position.
#[test]
fn pieces_of_a_split_body_are_numbered_by_position() {
let script = include_str!("../../../tests/corpus/filleted-bracket-blocks/recipe.json");
let d = open_design(&crate::script_design(script).unwrap()).unwrap();
let names: Vec<&str> = d.bodies.iter().map(|b| b.name.as_str()).collect();
let expected: Vec<String> = (1..=30).map(|k| format!("Bracket.{k}")).collect();
assert_eq!(names, expected.iter().map(String::as_str).collect::<Vec<_>>(), "listed in the order of their numbers");
let x = |n: &str| d.body(n).unwrap().measure().unwrap().centroid[0];
assert!(x("Bracket.1") <= x("Bracket.30"));
}
use crate::sample::{self, Plate};
fn face_areas(shape: &Shape) -> Vec<f64> {
+109
View File
@@ -9,6 +9,10 @@
//! edge keeps its name through an edit of the design that keeps its faces' names, and the cut
//! edges of a partition are named after the `partition:<name>:a|b` faces.
//!
//! A vertex is named the same way after the faces that meet there (the faces of the edges that
//! end at it): `F1:top|F2:side:l1|F2:side:l2`, numbered `~0`, `~1`, … where several vertices
//! touch the same faces.
//!
//! A shape built in code has no face names; its edges are named after the face indices.
use crate::{Result, Shape, SurfaceMesh};
@@ -33,12 +37,41 @@ impl Edge {
pub fn length(&self) -> f64 {
self.points.windows(2).map(|w| distance(w[0], w[1])).sum()
}
/// The point `fraction` of its length along it from its start (0: the start, 1: the end);
/// `None` for a fraction outside 0..=1 or an edge without points.
pub fn point_at(&self, fraction: f64) -> Option<[f64; 3]> {
if !(0.0..=1.0).contains(&fraction) {
return None;
}
let mut left = fraction * self.length();
for w in self.points.windows(2) {
let l = distance(w[0], w[1]);
if left <= l && l > 0.0 {
let t = left / l;
return Some([0, 1, 2].map(|k| w[0][k] + t * (w[1][k] - w[0][k])));
}
left -= l;
}
self.points.last().copied()
}
}
fn distance(a: [f64; 3], b: [f64; 3]) -> f64 {
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
}
/// A B-rep vertex of a body: where edges end.
#[derive(Debug, Clone, PartialEq)]
pub struct Vertex {
/// The persistent name (see the module docs).
pub name: String,
pub point: [f64; 3],
}
/// Most edge ends looked at for vertices (each against the vertices found so far).
const MAX_EDGE_ENDS: usize = 20_000;
/// The length-weighted centre of a polyline (its first point when it has no length).
fn centre(points: &[[f64; 3]]) -> [f64; 3] {
let mut sum = [0.0; 3];
@@ -119,6 +152,48 @@ impl Shape {
names
}
/// The vertices of `mesh` (a tessellation of this shape) with their persistent names: the
/// ends of its edges, those within the tessellation's weld distance being one vertex. A
/// closed edge with no other edge on it (a full circle) has no vertex. Empty for a shape with
/// more than [`MAX_EDGE_ENDS`] edge ends.
pub fn vertex_names(&self, mesh: &SurfaceMesh) -> Vec<Vertex> {
let ends = mesh.edges.iter().enumerate().flat_map(|(i, e)| [e.first(), e.last()].into_iter().flatten().map(move |p| (i, *p)));
if mesh.edges.len().saturating_mul(2) > MAX_EDGE_ENDS {
return Vec::new();
}
let close = (2.0 * mesh.weld_distance).max(1e-9);
// Per vertex: its point and the edges that end at it.
let mut found: Vec<([f64; 3], Vec<usize>)> = Vec::new();
for (edge, p) in ends {
match found.iter_mut().find(|(q, _)| distance(*q, p) <= close) {
Some((_, edges)) => edges.push(edge),
None => found.push((p, vec![edge])),
}
}
// A closed edge alone (its two ends one vertex, no other edge there) has no corner.
found.retain(|(_, edges)| edges.windows(2).any(|w| w[0] != w[1]) || edges.len() > 2);
let mut names: Vec<String> = found
.iter()
.map(|(_, edges)| {
let mut faces: Vec<u32> = edges.iter().filter_map(|e| mesh.edge_faces.get(*e)).flatten().copied().collect();
faces.sort_unstable();
faces.dedup();
let mut n: Vec<String> = faces.into_iter().map(|f| self.face_label(f)).collect();
n.sort();
n.join("|")
})
.collect();
let points: Vec<[f64; 3]> = found.iter().map(|(p, _)| *p).collect();
number_repeats(&mut names, &points);
names.into_iter().zip(points).map(|(name, point)| Vertex { name, point }).collect()
}
/// The body's vertices with their persistent names.
pub fn vertices(&self) -> Result<Vec<Vertex>> {
let mesh = self.tessellate((self.size()? * EDGE_TOLERANCE).max(1e-4))?;
Ok(self.vertex_names(&mesh))
}
/// The body's edges with their persistent names, from a tessellation fine enough to place them.
pub fn edges(&self) -> Result<Vec<Edge>> {
let mesh = self.tessellate((self.size()? * EDGE_TOLERANCE).max(1e-4))?;
@@ -186,6 +261,40 @@ mod tests {
assert_eq!(n, names(&ea));
}
#[test]
fn every_corner_of_the_plate_has_its_own_name_from_its_faces() {
let d = open_design(&sample::plate_design(&Plate::default()).unwrap()).unwrap();
let body = &d.bodies[0];
let vertices = body.vertices().unwrap();
// The box's 8 corners and the ends of the hole's two seams (2 × 2).
assert_eq!(vertices.len(), 12, "{vertices:?}");
let mut unique: Vec<&str> = vertices.iter().map(|v| v.name.as_str()).collect();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), vertices.len(), "{unique:?}");
// A box corner is where three faces meet.
let corner = vertices.iter().find(|v| v.point == [0.0, 0.0, 0.0]).unwrap();
assert_eq!(corner.name.split('|').count(), 3, "{}", corner.name);
// The names survive an edit that keeps the faces.
let b = open_design(&sample::plate_design(&Plate { width: 70.0, ..Plate::default() }).unwrap()).unwrap();
let mut other: Vec<String> = b.bodies[0].vertices().unwrap().into_iter().map(|v| v.name).collect();
other.sort_unstable();
assert_eq!(other, unique);
}
#[test]
fn points_along_an_edge() {
let e = super::Edge { name: "e".into(), faces: vec![], points: vec![[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 2.0, 0.0]] };
assert_eq!(e.point_at(0.0), Some([0.0, 0.0, 0.0]));
assert_eq!(e.point_at(0.5), Some([2.0, 0.0, 0.0]));
assert_eq!(e.point_at(0.75), Some([2.0, 1.0, 0.0]));
assert_eq!(e.point_at(1.0), Some([2.0, 2.0, 0.0]));
for bad in [-0.1, 1.5, f64::NAN] {
assert_eq!(e.point_at(bad), None);
}
assert_eq!(super::Edge { points: vec![], ..e }.point_at(0.5), None);
}
#[test]
fn partition_cut_edges_are_named_after_the_cut_faces() {
let d = open_design(&sample::plate_design(&Plate::default()).unwrap()).unwrap();
+46 -1
View File
@@ -25,7 +25,7 @@ pub mod sample;
mod script;
pub use design::{Design, FeatureError, MAX_DESIGN_BYTES, open_design};
pub use edges::{EDGE_TOLERANCE, Edge};
pub use edges::{EDGE_TOLERANCE, Edge, Vertex};
pub use partition::{Cut, CutReport};
pub mod tagged_mesh;
#[cfg(feature = "scripts")]
@@ -160,6 +160,30 @@ impl Shape {
self.faces.iter().position(|f| f.name == name).and_then(|i| u32::try_from(i).ok())
}
/// The area centroid of the face with this persistent name, from a tessellation fine enough
/// to place it (on a curved face the centroid lies off the surface, inside its curvature).
pub fn face_centre(&self, name: &str) -> Result<[f64; 3]> {
let face = self.face_index(name).ok_or_else(|| Error::Invalid(format!("body `{}` has no face `{name}`", self.name)))?;
let mesh = self.tessellate((self.size()? * edges::EDGE_TOLERANCE).max(1e-4))?;
let (mut sum, mut area) = ([0.0; 3], 0.0);
for (t, _) in mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, f)| **f == face) {
let corner = |i: u32| mesh.positions.get(i as usize).copied();
let (Some(a), Some(b), Some(c)) = (corner(t[0]), corner(t[1]), corner(t[2])) else { continue };
let (u, v) = ([0, 1, 2].map(|k| b[k] - a[k]), [0, 1, 2].map(|k| c[k] - a[k]));
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let w = 0.5 * (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
for (k, s) in sum.iter_mut().enumerate() {
*s += w * (a[k] + b[k] + c[k]) / 3.0;
}
area += w;
}
if area > 0.0 && area.is_finite() {
Ok(sum.map(|s| s / area))
} else {
Err(Error::Failed(format!("face `{name}` of body `{}` has no area", self.name)))
}
}
/// The analytic surface of each B-rep face, by face index (the [`SurfaceMesh::tri_face`]
/// tags): `None` for a free-form face. Meshers project nodes onto these surfaces.
pub fn face_surfaces(&self) -> Result<Vec<Option<FaceSurface>>> {
@@ -191,6 +215,11 @@ impl Shape {
Ok(guard("size", || Ok(self.body.size()))?)
}
/// The boundary shells of the body: one for a solid in one piece without voids.
pub fn shells(&self) -> Result<usize> {
Ok(guard("shells", || Ok(self.body.shell_count()))?)
}
pub fn measure(&self) -> Result<Measure> {
let m = guard("measure", || solidcraft_kernel::measure(&self.body))?;
Ok(Measure {
@@ -241,6 +270,22 @@ impl SurfaceMesh {
mod tests {
use super::*;
/// The plate's side face at x = 0 (40 × 30 × 10, the hole well inside) has its centre in its
/// middle; an unknown face is an error.
#[test]
fn a_face_centre_is_its_area_centroid() {
let d = open_design(&sample::plate_design(&sample::Plate::default()).unwrap()).unwrap();
let body = &d.bodies[0];
let surfaces = body.face_surfaces().unwrap();
let side = surfaces
.iter()
.position(|s| matches!(s, Some(FaceSurface::Plane { normal, point }) if normal[0] < -0.5 && point[0].abs() < 1e-9))
.unwrap();
let c = body.face_centre(&body.faces()[side].name).unwrap();
assert!((c[0]).abs() < 1e-9 && (c[1] - 15.0).abs() < 1e-6 && (c[2] - 5.0).abs() < 1e-6, "{c:?}");
assert!(body.face_centre("nope").is_err());
}
#[test]
fn block_measures() {
let m = block([0., 0., 0.], [10., 20., 30.]).unwrap().measure().unwrap();
+107 -18
View File
@@ -1,8 +1,8 @@
//! Partitions: a design's bodies cut into cells by planes, for meshing cell by cell.
//!
//! A partition cuts bodies of the open design by a plane with SolidCraft's kernel
//! (`split_by_plane`, the operation behind SolidCraft's split body), in memory: the design file is
//! never changed. The partitions live in the FieldCraft model and are applied again, in order,
//! A partition cuts bodies of the open design by a plane with SolidCraft's kernel (the body's
//! intersections with a box on each side of the plane, as SolidCraft's split body does), in
//! memory: the design file is never changed. The partitions live in the FieldCraft model and are applied again, in order,
//! whenever the design is opened, so an edit of the design followed by a re-open replays them.
//!
//! Names are FieldCraft's own, so they do not depend on the order of the design's timeline:
@@ -52,6 +52,8 @@ pub struct CutReport {
pub split: Vec<String>,
/// How many cut faces it named.
pub faces: usize,
/// What may make its cells hard to mesh: the plane lying on a face of a body it cut.
pub warnings: Vec<String>,
}
fn vec3(p: [f64; 3]) -> Vec3 {
@@ -89,8 +91,8 @@ fn plane_of(cut: &Cut) -> Result<(Plane, [f64; 3])> {
impl Design {
/// The design as opened, cut by `cuts` in order (the partitions replace any applied before).
/// A cut that names a body the design does not have, or that does not divide a body it
/// names, is listed in [`Design::errors`] (feature `partition <name>`), as a feature of the
/// A cut that names a body the design does not have, that does not divide a body it names,
/// or that the kernel fails to make on any body it applies to, is listed in [`Design::errors`] (feature `partition <name>`), as a feature of the
/// design that failed to rebuild; the rest still apply.
pub fn partitioned(&self, cuts: &[Cut]) -> Result<Design> {
if cuts.len() > MAX_CUTS {
@@ -104,10 +106,10 @@ impl Design {
let feature = format!("partition {}", cut.name);
for b in &cut.bodies {
if !bodies.iter().any(|x| &x.name == b) {
errors.push(FeatureError { feature: feature.clone(), message: format!("no body `{b}` to cut") });
errors.push(FeatureError { feature: feature.clone(), message: format!("no body `{b}` to cut"), bodies: vec![b.clone()] });
}
}
let mut report = CutReport { name: cut.name.clone(), split: Vec::new(), faces: 0 };
let mut report = CutReport { name: cut.name.clone(), split: Vec::new(), faces: 0, warnings: Vec::new() };
let mut next = Vec::with_capacity(bodies.len() + 1);
for body in bodies {
let listed = cut.bodies.iter().any(|b| b == &body.name);
@@ -116,17 +118,32 @@ impl Design {
continue;
}
match split(&body, plane, *n, cut)? {
Some((cells, faces)) => {
Split::Cells(cells, faces, warnings) => {
report.split.push(body.name.clone());
report.faces += faces;
report.warnings.extend(warnings);
next.extend(cells);
}
None => {
Split::Misses => {
if listed {
errors.push(FeatureError { feature: feature.clone(), message: format!("the plane does not divide `{}`", body.name) });
errors.push(FeatureError {
feature: feature.clone(),
message: format!("the plane does not divide `{}`", body.name),
bodies: vec![body.name.clone()],
});
}
next.push(body);
}
// Listed or not: the plane may well divide the body, and a cut that silently
// leaves it whole would be mistaken for one that does not reach it (#283).
Split::Failed(e) => {
errors.push(FeatureError {
feature: feature.clone(),
message: format!("the kernel could not cut `{}` ({e})", body.name),
bodies: vec![body.name.clone()],
});
next.push(body);
}
}
if next.len() > MAX_CELLS {
return Err(Error::Invalid(format!("the partitions make at most {MAX_CELLS} cells")));
@@ -139,13 +156,85 @@ impl Design {
}
}
/// Cut one body: its cells, named, and how many cut faces they have; `None` when the plane does
/// not divide it.
fn split(body: &Shape, plane: &Plane, n: [f64; 3], cut: &Cut) -> Result<Option<(Vec<Shape>, usize)>> {
let parts = match guard("partition", || solidcraft_kernel::split_by_plane(&body.body, plane)) {
Ok(p) if p.len() >= 2 => p,
_ => return Ok(None),
/// The parts of `body` on either side of `plane` (only the non-empty ones): its intersections
/// with two boxes, one on each side, whose faces in the plane are squares as wide as the body's
/// bounding-box diagonal and that reach that far from it. SolidCraft's `split_by_plane` uses boxes
/// several times the body's size, and its boolean then puts the cut up to a few micrometres off
/// the plane (1.8 µm on a 140 mm body), off the faces it should meet (#384); boxes of the body's own
/// size keep the cut on the plane.
fn halves(body: &Shape, plane: &Plane) -> solidcraft_kernel::Result<Vec<solidcraft_kernel::Body>> {
let bbox = solidcraft_kernel::measure(&body.body)?.bbox;
let reach = bbox.diagonal().max(LINEAR_REACH);
let c = plane.to_local(bbox.center());
let square = solidcraft_geom::Region2 {
outer: solidcraft_geom::Loop2::polygon(&[
solidcraft_geom::Vec2::new(c.x - reach, c.y - reach),
solidcraft_geom::Vec2::new(c.x + reach, c.y - reach),
solidcraft_geom::Vec2::new(c.x + reach, c.y + reach),
solidcraft_geom::Vec2::new(c.x - reach, c.y + reach),
]),
holes: vec![],
};
let mut out = Vec::with_capacity(2);
for (lo, hi) in [(0.0, reach), (-reach, 0.0)] {
let Some(side) = solidcraft_kernel::extrude(plane, std::slice::from_ref(&square), lo, hi)?.pop() else { continue };
out.extend(solidcraft_kernel::boolean(&body.body, &side, solidcraft_kernel::BoolOp::Intersect)?);
}
Ok(out)
}
/// Planar faces of `body` the cut's plane lies on (within [`COINCIDENT`] of the body's size),
/// as warnings: the kernel may leave micrometre slivers where a cut runs along a face (#384).
fn coincident(body: &Shape, parent: &Faces, cut: &Cut, n: [f64; 3], size: f64) -> Vec<String> {
let reach = COINCIDENT * size.max(1.0);
let mut out = Vec::new();
for (i, surface) in parent.surfaces.iter().enumerate() {
let Some(FaceSurface::Plane { normal, point }) = surface else { continue };
let along = dot(*normal, n).abs();
let distance = dot(sub(*point, cut.point), n).abs();
if (along - 1.0).abs() < 1e-9 && distance <= reach {
let name = parent.names.get(i).map_or_else(|| i.to_string(), |f| f.name.clone());
out.push(format!(
"partition `{}`: the plane lies on face `{name}` of `{}` ({distance:.2e} mm from it); a cut along an existing face can leave micrometre slivers that no mesher takes: move the plane off the face (by a fraction of the element size)",
cut.name, body.name
));
}
}
out
}
/// A plane within this fraction of a body's size of one of its faces lies on it.
const COINCIDENT: f64 = 1e-5;
/// The least reach of the boxes [`halves`] cuts with (mm), for bodies with no extent.
const LINEAR_REACH: f64 = 1.0;
/// What cutting one body gave.
enum Split {
/// Its cells, named, how many cut faces they have, and warnings.
Cells(Vec<Shape>, usize, Vec<String>),
/// The plane does not divide it.
Misses,
/// The kernel failed to cut it: its message.
Failed(String),
}
/// Cut one body.
fn split(body: &Shape, plane: &Plane, n: [f64; 3], cut: &Cut) -> Result<Split> {
let sides = match guard("partition", || halves(body, plane)) {
Ok(p) if p.len() >= 2 => p,
Ok(_) => return Ok(Split::Misses),
Err(e) => return Ok(Split::Failed(e.to_string())),
};
// Each side may fall apart into pieces that do not touch (#388): every piece is a cell.
let mut parts = Vec::with_capacity(sides.len());
for side in sides {
match guard("partition", || side.lumps()) {
Ok(pieces) if !pieces.is_empty() => parts.extend(pieces),
Ok(_) => parts.push(side),
Err(e) => return Ok(Split::Failed(e.to_string())),
}
}
let size = body.size()?;
let tol = (MATCH_TOLERANCE * size).max(1e-4);
let parent = Faces::of(body, tol)?;
@@ -176,7 +265,7 @@ fn split(body: &Shape, plane: &Plane, n: [f64; 3], cut: &Cut) -> Result<Option<(
faces += name_faces(&mut shape, &parent, cut, n, size, tol)?;
out.push(shape);
}
Ok(Some((out, faces)))
Ok(Split::Cells(out, faces, coincident(body, &parent, cut, n, size)))
}
/// A body's faces as matching needs them: each face's analytic surface, name and triangles.
@@ -404,7 +493,7 @@ mod tests {
assert_eq!(p.bodies.len(), 2, "{:?}", p.bodies.iter().map(|b| &b.name).collect::<Vec<_>>());
let volume: f64 = p.bodies.iter().map(|b| b.measure().unwrap().volume).sum();
assert!((volume - whole).abs() < 1e-6 * whole, "{volume} vs {whole}");
assert_eq!(p.cuts, vec![CutReport { name: "Mid".into(), split: vec![d.bodies[0].name.clone()], faces: 4 }]);
assert_eq!(p.cuts, vec![CutReport { name: "Mid".into(), split: vec![d.bodies[0].name.clone()], faces: 4, warnings: Vec::new() }]);
let mut sides = Vec::new();
for b in &p.bodies {
let m = b.measure().unwrap();
+14 -14
View File
@@ -35,7 +35,7 @@ use fieldcraft_model::MAX_COORD;
/// flattens the object (relative, so a uniform scale is never refused).
const MIN_RELATIVE_DET: f64 = 1e-12;
const CORE_NS: &[u8] = b"http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
const CORE_NS: &str = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
/// SolidCraft's face-tag namespace, version 1.
pub const FACE_TAGS_NS: &str = "https://github.com/bherbruck/solidcraft/formats/3mf-face-tags/2026/10";
@@ -58,8 +58,8 @@ fn bad<T>(msg: impl std::fmt::Display) -> Result<T> {
fn read_part(zip: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str) -> Result<Option<Vec<u8>>> {
let want = name.trim_start_matches('/').to_ascii_lowercase();
let Some(idx) =
(0..zip.len()).find(|i| zip.name_for_index(*i).is_some_and(|n| n.replace('\\', "/").trim_start_matches('/').to_ascii_lowercase() == want))
let Some(idx) = (0..zip.len())
.find(|i| zip.name_for_index(*i).is_some_and(|n| n.is_ok_and(|n| n.replace('\\', "/").trim_start_matches('/').to_ascii_lowercase() == want)))
else {
return Ok(None);
};
@@ -85,7 +85,7 @@ enum Ns {
fn ns_of(r: &ResolveResult) -> Ns {
match r {
ResolveResult::Bound(n) if n.as_ref() == CORE_NS => Ns::Core,
ResolveResult::Bound(n) if n.as_ref() == FACE_TAGS_NS.as_bytes() => Ns::FaceTags,
ResolveResult::Bound(n) if n.as_ref() == FACE_TAGS_NS => Ns::FaceTags,
ResolveResult::Unbound => Ns::Core,
_ => Ns::Other,
}
@@ -93,7 +93,7 @@ fn ns_of(r: &ResolveResult) -> Ns {
/// An element's attributes as (namespace, local name, value), borrowed from the event (values
/// are copied only when they hold entity references). Unprefixed attributes are Core.
type Attrs<'a> = Vec<(Ns, &'a [u8], Cow<'a, str>)>;
type Attrs<'a> = Vec<(Ns, &'a str, Cow<'a, str>)>;
fn attrs<'a, R>(rd: &NsReader<R>, e: &'a BytesStart) -> Result<Attrs<'a>> {
let mut out = Vec::with_capacity(4);
@@ -107,7 +107,7 @@ fn attrs<'a, R>(rd: &NsReader<R>, e: &'a BytesStart) -> Result<Attrs<'a>> {
}
fn get<'s>(a: &'s Attrs, ns: Ns, key: &str) -> Option<&'s str> {
a.iter().find(|(n, k, _)| *n == ns && *k == key.as_bytes()).map(|(_, _, v)| v.as_ref())
a.iter().find(|(n, k, _)| *n == ns && *k == key).map(|(_, _, v)| v.as_ref())
}
fn int(a: &Attrs, ns: Ns, key: &str, what: &str) -> Result<Option<u32>> {
@@ -216,7 +216,7 @@ fn parse_model(xml: &[u8]) -> Result<Model> {
Event::End(end) => {
depth = depth.saturating_sub(1);
if ns == Ns::Core
&& end.local_name().as_ref() == b"object"
&& end.local_name().as_ref() == "object"
&& let Some((id, o)) = cur.take()
{
m.add(id, o)?;
@@ -237,13 +237,13 @@ fn parse_model(xml: &[u8]) -> Result<Model> {
}
let a = attrs(&rd, &e)?;
match e.local_name().as_ref() {
b"model" => {
"model" => {
seen_model = true;
if let Some(u) = get(&a, Ns::Core, "unit") {
m.unit = unit_mm(u).ok_or_else(|| invalid(format!("unknown unit `{u}`")))?;
}
}
b"object" => {
"object" => {
if cur.is_some() {
return bad("an object inside an object");
}
@@ -262,7 +262,7 @@ fn parse_model(xml: &[u8]) -> Result<Model> {
cur = Some((id, o));
}
}
b"vertex" => {
"vertex" => {
let Some((_, o)) = cur.as_mut() else { return bad("vertex outside an object") };
vertices += 1;
if vertices > MAX_ELEMENTS {
@@ -270,7 +270,7 @@ fn parse_model(xml: &[u8]) -> Result<Model> {
}
o.positions.push([coord(&a, "x")?, coord(&a, "y")?, coord(&a, "z")?]);
}
b"triangle" => {
"triangle" => {
let Some((id, o)) = cur.as_mut() else { return bad("triangle outside an object") };
triangles += 1;
if triangles > MAX_ELEMENTS {
@@ -288,11 +288,11 @@ fn parse_model(xml: &[u8]) -> Result<Model> {
}
o.triangles.push(t);
}
b"component" => {
"component" => {
let Some((_, o)) = cur.as_mut() else { return bad("component outside an object") };
o.components = true;
}
b"item" => {
"item" => {
if m.build.len() >= MAX_BUILD_ITEMS {
return bad(format!("more than {MAX_BUILD_ITEMS} build items"));
}
@@ -364,7 +364,7 @@ pub fn read_3mf(bytes: &[u8]) -> Result<Vec<TaggedSurface>> {
let mut buf = Vec::new();
loop {
match rd.read_event_into(&mut buf) {
Ok(Event::Start(e)) | Ok(Event::Empty(e)) if e.local_name().as_ref() == b"Relationship" => {
Ok(Event::Start(e)) | Ok(Event::Empty(e)) if e.local_name().as_ref() == "Relationship" => {
let a = attrs(&rd, &e)?;
if get(&a, Ns::Core, "Type").is_some_and(|t| t.ends_with("/3dmodel"))
&& let Some(t) = get(&a, Ns::Core, "Target")
Loaded 100 of 256 files, more files were not shown because too many files have changed in this diff. Show more