Files
makeCAD/crates/engine/src/tests.rs
T
jyviko ea772a0438 Merge develop into main: SolidCraft on the SMLib kernel (v1.1.0-alpha) (#11351)
* UI: rim and wall picking tests for a circle of arcs that is one wall

A circle drawn as two half arcs now extrudes to one full-turn wall with its
seam edge, and each rim is one closed edge (tangency-labs/smlib#67). The tests
keep their intent on that body: a rim clicked once is one item, measured and
highlighted whole and picked from either side; a wall picked either side of
its seam is the same surface, lit whole, and toggles off from the other side;
every face is its own patch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillets: a later round at a corner where earlier rounds meet blends them again with it

The owner's ruling of 2026-10-30: a later fillet on an edge at a vertex where earlier
rounds already meet in a mitre makes the corner rounding all of them at once makes, one
smooth patch, the mitre gone. A body made by constant-radius rounds keeps what they were
made on and which edges they rounded at which radius; a later round reaching such a corner
blends the earlier rounds' edges (from the earliest of those meeting there on) with the new
edges in one SMLib blend of the body before them. The result's history is put over the body
the later round was given: an earlier round's face is that face trimmed anew (its name
kept), the corner patch and the new rounds are the later fillet's. A picked mitre seam has
no round of its own: it is refused unless a new edge of its radius meets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a later r3 round at an r2 mitre, through the Fillet feature, makes the all-at-once corner

Two box edges rounded r2 in one fillet, then the upright edge at their mitre r3 in a second
fillet (tangent chain on, so the seam comes with it): 10 faces, 7928.743041 mm³ as
fillet_radii of the box gives, the r2 rounds' names kept, the r3 round and the corner patch
the second fillet's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel: a body's record of rounds goes with its history, and can be read back

The rounds that made a body are over the body its history is over: a new history (an
operation carrying a step's result back to its own operands) leaves the record out, so a
later round never reads one history against another body. Body::rounds gives the record and
Body::with_rounds_of takes one back, checked (edges of the body before them, a fillet's
radii, the body's history over that body), for a saved model to keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Model cache: a body made by rounds keeps them, so a later round blends them the same after opening

A design gave another body when opened from its model cache: the rounds a body was made of
lived only in memory, so a later round at their mitre was built sequentially (or refused, as
too large) after opening and blended with them when evaluated anew. The saved model now
records, per kernel body made by rounds, the body they were made on (a place in the bodies,
stored once though no state holds it) and the edges with their radii; reading it attaches
them back down each chain, and a thinned model keeps those bodies with the bodies made from
them. Model cache format 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a corner patch of rounds 2/3/4 takes no more than the strips leave in its block

three_rounds_at_a_corner bounded the patch's extra cut at 3 mm³ beyond the strips, a figure
with no derivation; SMLib's all-at-once body at radii 2, 3, 4 takes 3.099 (V 7878.579574
against strips 7881.678). That body is the strips' outside the block its patch lies in: its
rounds are the strips' cylinders ending at a's section y = rc, b's x = 20 − rc and c's rails
where they meet a's and b's (the patch's four corners, now asserted), so the patch takes at
most what the strips leave in that block (11.86 at 2/2/3, 32.69 at 2/3/4). The lower bound is
that block; the upper one, at most the strips' volume, stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the io crate's hand-built saved models list their rounds, as format 7 records do

Model cache format 7 (f3cf0c4f3) records a `rounds` list in every saved model, and reading one
without it is refused ("saved model: rounds"), as is a model without any of its other lists:
the states, the preview and the thinned model all came back empty. The io tests' saved_model
and timeline_model wrote format-6 records, so six tests (the round trip, the repeated part
stored once, and the four too-big-for-the-file cases) read nothing. Their bodies are none made
by rounds: the list is empty, and every expectation stays as it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin eaa998a (tangency-labs/smlib#68, #69, #70)

Batch 4: drafts and loops, mitre corners, rim chamfers, rulings, tight box, stitch, point
classification, eased corners. Batch 5: a face's tight box divides its cells at the surface's
knots (thread boxes exact); a cylinder, cone, sphere or torus is extended along its own circles.
Batch 6: a revolution's extension closes its turn; a dropped point's foot is the converged one.
The C API is ABI 5 (smlib_blend_dropping and smlib_brep_classify_point are new; nothing existing
changed), so the binding expects 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a strip's tangent and curvature run-offs are the distance long across the surface

SMLib measures an extension's distance across the surface (smlib_extend_sheet corrects
CreateExtendedSurface until the parameter line through the side's middle is that long), so each
run-off of the cylinder strip, swept 20 along z, adds 5 x 20: 10 pi/2 20 + 100 = 414.159 for
both. The parabola-length formula (418.18) was truck's.

Ruling d2 (2026-10-30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: one smooth angle, and a round too small to change the part is refused

The blend's tangent angle is the shaded view's half degree (smooth_edges::ANGLE), one value
for smooth. A constant round lies r (sec(d/2) - 1) inside the crease it replaces (about
r d^2/8); below the edge's tolerance it changes nothing and is refused before SMLib (which
answered SM_ERR_INVALID_INPUT), naming the smallest radius that rounds,
tolerance / (sec(d/2) - 1). d is the least turn along the edge
(tangent_edge::least_angle_along, at tangent_all_along's stations).

Ruling d3 (2026-10-30). The block's tolerance is 2e-5 mm, not 0.1 um: at 1 deg the smallest
radius is 0.526 mm, so R2 and R20 reach SMLib, which still calls an edge within 2 deg smooth
(SmEdge::GetBlendEdgeuse); that test is ignored until SMLib uses 0.5 deg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: the knife-edge chamfers name SMLib's cause, a cusp's ball radius of 0

smlib_chamfer turns the distance into a ball radius d sqrt((1 - c)/(1 + c)), c the faces'
binormals' dot (capi chamfer_radius); at #851's cusp the binormals agree, the radius is 0 and
the call is SM_ERR_INVALID_INPUT before the fillet executive runs (gdb: chamfer_edges sees
radius 0; the dump's why is empty). SolidCraft hands every chamfer to SMLib, so the
ball-contact chord (the ball of radius d: 3.822 wide at d = 2, 159.2365 removed) is SMLib's to
build.

Ruling d4 (2026-10-30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel tests: a corner round wider than its faces overflows and takes the corner's other edges

R21 on a 20 mm cube's edge builds (6107.529370, closed form, to 2e-12). With R5 on the
corner's other edges the R21 takes the faces they lie on, so the body is R21's alone; SMLib
fails that blend (status 1001, fillet error 4, Unable to Trim Rail Curve) and the test is
ignored until it builds. It replaces the refusal test that expected TooLarge.

Ruling d8 (2026-10-30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a 1 degree crease rounds, and the knife edge's chamfers build, on SMLib smlib-batch-4-rulings

With SMLib's smooth limit at half a degree (422e6f1) the 1 degree crease rounds R2 and R20
(the test is no longer ignored), and with a cusp's chamfer the ball of radius d (d231547) the
The 0.5 one stays, for its own cause (the chamfer face left apart from the body). Two corner
cases the same SMLib (replay/1.0.1 and those commits) builds come off too.

Needs SMLIB_REV at that SMLib once it is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel, doc: an overflowing round goes first; an edge it removes is gone, and the fillet says so

SMLib (smlib-batch-4-rulings 0e83cca, SMLIB_ABI_VERSION 5) rounds the edges whose rounds overflow
their faces first and then what is left of the others; smlib_blend_dropping says which picks'
edges the overflow removed whole. The smlib crate binds it (Brep::blend_dropping), the kernel
returns those picks (fillet_removing), and a fillet notes them as its warning: "the edge at
(0, 0, 10) was removed by the larger round, so it is not rounded" (a 50 x 50 x 20 block, R21 on
its bottom front edge with the front left upright: the block is R21's alone, in closed form).

Ruling d8: [21, 5, 5] on a 20 cube builds as R21 alone (6107.529370); the test is no longer
ignored. R25 with R2 at a corner (blend_corner) builds the same way, R25's alone in closed form,
where it was refused. The rig's 1080 notched block outline at R8 builds now and comes off the
known-failing list.

Needs SMLIB_REV at that SMLib once it is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: the knife edge's 0.5 chamfer builds

SMLib's trim took a fillet meeting its face at more than 78 degrees for one with no side
(smlib-batch-4-rulings 971e567); the chord of the knife edge's 0.5 chamfer meets the flat face at
81 degrees. The case comes off the known-failing list.

Needs SMLIB_REV at that SMLib once it is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a 15° tapered text builds, every letter grown, exact where its outline gives it

Owner ruling d6: the letter t of "tres long" was drafted inward by SMLib (its
loop's normal, summed from the cross products of its chords, pointed down;
fixed in SMLib). With the fix every letter grows, and the join builds at 3°
and 15° by the Round rule and by the default rule (tangent for spline
outlines), where before 15° was expected to be refused.

Exact where the outline derives it: a letter's section at height z is its
outline offset by e = z tan a, by the Round rule of area A + P e + C e² while
the offset trims nothing (Steiner; C half each loop's turning less
tan(t/2) - t/2 at each reflex corner), so the letter is
A h + P k h²/2 + C k² h³/3. Each extruded alone, the t at 3° and s, l and o
at 3° and 15° are checked to 1e-6 (SMLib measures them within 1.3e-9; its
mass properties integrate to 1e-8). The concave joins of r, n, g and e are
tighter than e already at 3° (their swallowtails trimmed: r 1.1e-3 under the
formula), the t's by 15° (9.9e-5 over), and on the block the letters grow
into each other, so the whole word is checked for what holds exactly: one
closed body with the block, and half-way up every point of each straight
letter's outline inside the solid (the t drafted inward failed that).

With SMLib's fix (smlib-batch-4-text-loops 82133b2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: a sloped basin's mitred rim rounds are checked tangent along their contact lines

1080-fillet-sloped-basin-1-mm-rim-r0-5-4-edges asked G1 at every blend seam. Its front wall
leans 19 over 20 and the others 10 over 20, so at each rim corner the two mitred rounds meet the
sloped corner edge at different heights (0.155625 and 0.276393 below the top): the deeper round
runs on past the corner edge and is cut by the plane of the other's wall, a crease by
construction, the gap below the shallower round filled on that plane. The check now measures
the rounds' contact seams, on the top and on each wall, where the rounds are tangent. The
volume is unchanged.

With SMLib smlib-batch-4-mitre (1c15364): the case passes (V 144530.427946 against
144530.427909, 15 faces, sound); before it, only the four corner creases failed the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* smlib: Brep::classify_point says exactly where a point lies against a body

Binds the fork's smlib_brep_classify_point (SmBrep::Point3DClassify at the body's own zone
tolerance): inside, outside, or on the boundary within that tolerance of a face, an edge or a
vertex. A box and a cylinder just off its curved wall in measure's tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* kernel: Body::classify_point decides inside, outside or on the boundary exactly

SMLib's point classification at the body's own tolerance, on the exact faces and edges, in
place of a mesh at a chord of 2e-3 of the body's size (about 0.4 mm on a 200 mm part). A point
within the tolerance of a face, edge or vertex is OnBoundary, never decided by a ray. A mesh
body's triangles are its exact shape: on them within the record's tolerance, else by ray
crossings. The kernel's own probes move to it; Body::contains goes once its last callers have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* doc: a hole decides whether it exits at its drill point's shoulder exactly

Material past the depth needs a body with the point inside, air before it needs every body to
have it outside; a point within a body's tolerance of the exit face is neither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* engine tests: probes ask for the exact point class

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* ui, cli tests: probes ask for the exact point class

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* kernel: Body::contains, the mesh test, is gone

Every caller asks Body::classify_point now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* kernel tests: the rim chamfers running off their rims build, on SMLib 737c392

chamfer_wider_than_sloped_basin_rim_builds and a_rim_loop_chamfer_running_off_its_rim_builds
waited for SMLib to build the cliff overflow (CloseRemovalRegion refused it,
SM_FILERR_NO_ROOM). The pinned SMLib builds it (eddf0ede4, bba9914b6): both pass on aarch64
Linux and are no longer ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: the cases SMLib 737c392 builds come off the known-failing list

The gate on aarch64 Linux reports 16 fillet cases FIXED with the pinned SMLib: the sloped and
equal-slope basin rim chamfers and rounds past their rims (1080-*, 5835-*), the pocket rim
chamfer past the floor, and the three pocket rim rounds now mitred at the pocket's corners
(every-pocket-*). No other area's gate reports a case fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: the re-blend's removed picks formatted as rustfmt lays them out

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: blend_smlib laid out by the 2024 edition's rustfmt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Skills: the tests skill's unit-test example stays under the 3600-character limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet: the radius-too-large choice in plain nouns

"If too large: Stop and say so / Largest that fits / Narrow where needed"
becomes "Face limits: Exact radius / Largest radius / Narrowed radius", in
every language of the catalog, with the error and the tip that name them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: a round that would cut through its wall into a hollow is refused

The owner's rule of 2026-10-30: a round running past a rim of its faces
into open air builds; one whose section would remove material through to
a hollow behind its edge (a slit into the hollow, a cut through the part)
is refused as too large, so the fillet names the largest radius that fits.

Decided exactly in the section of a straight convex edge between planar
faces: the round's centre is at depth r below both planes, and it opens
where its arc uncovers a boundary point strictly inside the wedge with no
material beyond it toward the centre (the body's exact point
classification). Looked at: straight edges parallel to the round's (a
hollow's corner), cylinders about parallel axes (a rounded corner), and a
picked concave parallel edge's own round, which fills the corner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: 1668's R7 past the inside corner is refused at 4 + 2 sqrt2

The round's centre (32 - r, 42 - r) leaves the hollow's corner (30, 40)
outside its circle, opening the wall, where sqrt2 (r - 2) = r: the case
expects the refusal naming 6.828. 2852's R30, refused naming 25.24, now
passes too: both come off the known-failing list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* xtask: known-failing grades a nextest junit report against tests/KNOWN_FAILING_TESTS

`cargo xtask known-failing --junit PATH` reads nextest's junit (a file, or every .xml under a
directory, so all of a run's junit artifacts at once) and fails on a test that failed and the
list does not name, and on a listed test that passed (FIXED: take its line off, as the kernel
rig's gate does). A listed test that did not run is neither, since a pull request tests only the
packages it touches. The list has the rig's KNOWN_FAILING format (`<test> <cause>`, sorted, the
rig's own parser), with `<test>` nextest's `<binary id>::<test name>`; `cargo xtask lists`
checks it is sorted. The list starts empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* CI: the test jobs grade their junit against tests/KNOWN_FAILING_TESTS

Native Linux tests and the GPU path test shards no longer fail on any failed test: nextest's
"tests failed" exit (100) goes to `cargo xtask known-failing --junit`, which fails on a failure
the list does not name and on a listed test that passes. Any other nextest exit (a build error,
a bad filter) still fails the step at once. The tests skill says to list a failing test with its
cause, in place of ignoring it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the known-failing list takes develop's 10 failing tests

Develop 38fd4a4f6 (CI run 41157648345, after the SMLib eaa998a pin) fails 10 cargo tests; each
is listed with the cause its failure message gives. Seven are SMLib refusals or results off
their derived volumes (fillet, chamfer and shell), the cli action matrix and naming corpus
among them; the two corner_g2 tests are the fitted G2 corner patch bulging past the box, which
the explicit G2 corner fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reference tests: the eight cases that fail on SMLib eaa998a name their cause as known failures

Develop 38fd4a4f6's Reference tests fail 34, 35, 77, 78 and 81 (STEP export finds fillet edges
4.6e-5 to 6.1e-5 off their surfaces against 2e-5), 37 (the apex blend 0.193 off), 80 (the
taper-to-fit area) and 83 (thicken status 1001). Each expected.json names its cause in
known_failure, which the oracle already reads: a known failure that passes fails the job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sweep path: a curve of several pieces is turned round whole

The path chain oriented its first piece, not its first curve: a first curve
of several exact pieces (a fit spline, an ellipse, a projected free-form
edge) was never turned round, so a path whose next curve meets it at its
start was refused as "not connected end to end". The chain now orients
curve by curve: the first runs toward the second where they meet at one
end only (else from the end nearest the profile), each next one starts
where the previous ended, with one joint tolerance for both questions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin 2fc375f (tangency-labs/smlib#71, #72, #73)

A sheet's side is extended exactly the distance asked, or the call says it cannot (#71);
NVIDIA's -Werror build passes again (#72); a body splits by a sheet of several faces as it
is, smlib_split_body_by_sheet (#73). The C API is ABI 6 (the new entry), so the binding
expects 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: Extend grows a surface of several faces face by face

A surface body of more than one face (a fit-point spline's spans extruded, #3830) was refused.
Each face with a picked edge is now extended alone by SMLib's extension of its surface, and the
faces are sewn back together, each the face it was. A side that lengthens onto a face meeting it
tangent takes that face along, past its edge continuing the picked one; across a crease the
neighbour grows only when its edge is picked too, otherwise the extension is refused. Faces whose
lengthened sides no longer meet are refused. Up to a target keeps the pieces every grown face
lies in.

3830's extensions now build; its split still fails (the tool point picks one span, and a face
tool cuts with that face's surface alone), so it stays on the list with that reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: Split Body by a face of a smooth sheet cuts with the whole sheet

A face tool cut with that face's surface alone, so a face of a surface body made of spans joined
tangent (a fit-point spline extruded, #3830) cut nothing where its span ends inside the body.
Split Body by a face of a surface body now takes the faces joined to it tangentially (the exact
check Extend uses, within the one angle for smooth) and slices with them as they are, through
SMLib's slice by a sheet (smlib_split_body_by_sheet, tangency-labs/smlib 7a01f1b), its sides those
of the picked face. A sheet that only nicks the body cuts nothing, as before; a lone face, or a
face of a solid, still cuts with its surface extended.

3830 comes off the booleans list. Its answer counted the two halves of the cup and not the surface
that cut it, which stays as a body of its own (4879 removes its surface for that reason): three
bodies, the volume unchanged.

Needs SMLib 7a01f1b pinned (SMLIB_REV, prebuilt; its SMLIB_ABI_VERSION 6, which crates/smlib now expects) to link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a cylinder strip's run-offs are 100 pi + 100 to 1e-6, SMLib's exact area

The tangent and curvature run-offs of the quarter cylinder r 10 strip, 5 across the surface,
are its section swept 20 along z: exactly 10 pi/2 20 + 5 x 20 = 414.159265. measure is SMLib's
integration on the exact surface (1e-8), not a mesh, so the run-off check is 1e-6 relative and
the 'measured on meshes' notes go. Red until SMLib's extension is solved to its distance
(smlib-extend-converges 590d8a1): eaa998a's curvature run-off is 4.986 long, area 413.882.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: an extension SMLib cannot make exact says so, naming the length asked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sketch: a control spline can carry its own knots and weights

A sketch spline over control points was always the clamped uniform B-spline
over them, so a free-form edge whose knots are not evenly spaced (or whose
weights are not 1) could only come into a sketch as one curve per Bezier
span. A control spline now may save `nurbs`: its clamped knots and its
weights. Its points, polyline, exact pieces (one a knot span; conics for a
rational quadratic), the solver's distance and curvature, links, parallel
re-projection and inspect.sketch all read them; a loaded design's are
checked. One pending format file (spline-knots).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sketch projection: a free-form edge comes in as the one exact spline it is

A projected spline edge of several Bezier spans came into the sketch as one
curve per span (#1508), so a G2 round's bottom edge was 16 curves and a path
naming the corner named one span of it (#3604). The kernel now reads such an
edge (a spline, or an elliptical arc of several spans) as the one clamped
B-spline it is over the edge's interval, its knots and weights its own, and
the sketch takes it as one control spline whose ends sit on the edge's
vertices. Planar regions still read edges span by span. The 3604 case builds
with its original path and leaves KNOWN_FAILING.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: blends past an outer rim of their faces build, on SMLib smlib-blends-past-rims

The owner's ruling: a round or chamfer that runs past an outer edge of its face into open air
builds, tangent where it has room and cut by the face beyond where it runs out. SMLib's branch
smlib-blends-past-rims builds them by the rig's analytic answers. Off the known-failing list:
the disc's rim past its 2 mm wall (190), the hole's top rim R12 past the plate's bottom, the
chamfer past the cylinder's bottom (2893), each closing on the wall continued as itself, and
926's chamfer ending on the boss's wall, which now builds to its answer too.

The sloped basins' R4 rim rounds (1080, mitred rounds built together where one overflows) build
to their analytic volumes (to 6e-9), and stay listed with that reason: their continuity check
(g1 at every blend seam) takes in the mitres' creases, G0 by the mitre ruling.
2893-chamfer-two-distances-elliptical-rim is graded as a solid (the owner: it builds) and stays
listed, waiting on the ruling on unequal chamfers along a rim whose angle varies.
5158-fillet-round-just-past-a-10mm-face stays listed with its cause found: the round passes
5e-6 under the box's top back edge, inside the body's tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Naming: test that a round of a round's end has no seam with that round's faces

The r1 round of a block's top edge, chained onto the end curve of the r2
round of its arc at a cylinder (rig fillets/every-block-cylinder-crease-
top-edge-after-arc-round-r1), ends where it runs into the cylinder. That
edge is no seam of the r1 round: the cylinder is a face of the r2 round,
not of the r1. blend_seams takes it for one today (the r2 round's name
F3:blend:F1:+z|F2:side holds a | of its own), and the rig reads it as a
contact seam at 60 degrees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Naming: a blend's seams split its edge's name at the | between its two faces

A blend face's name holds the edge it replaced, <face>|<face>, and a side
of that edge can be a blend face whose own name holds a |. Whether a face
is a contact of the blend was read as the edge's name starting or ending
with the face's name next to a |, so the r2 round's own face F2:side read
as a contact of the r1 round F4:blend:F1:+y|F3:blend:F1:+z|F2:side. The
edge's name is now split into its two faces, a blend side read whole as
the two faces of its own edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: five refused blends build, off the known-failing list

926 (the chamfer ending on the boss's wall), the oblique cut's r0.1
round, the every-block r1 round (its seam with the cylinder is no
contact seam, after the blend_seams fix), the up-down squares' concave
chamfers and the shelled box's lip chamfer build with SMLib branch
smlib-blend-refusals (f8650b8 and later). 1207 r0.5 passes SMLib's check
on its rails now and stays listed for the next cause: its end rib on the
boss, which starts where the round and the boss are tangent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the trough and the pocket whose floors fall to a drain build

SMLib now offsets a vertex where four faces meet (two walls and two facets at the floor's
corners, four facets at the drain) to two vertices joined by a new edge (tangency-labs/smlib
branch smlib-shells). Both volumes match their closed forms. The pocket's lining, hanging from
the top's rim round the pocket, stands apart from the slab's outer walls with the cavity rising
between them to the open top: the case says two shells in the one body.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the plate with a hole through its arc side shells open at its far end

SMLib's merge now intersects the offsets of an edge's faces where they could not be mated along
it (the hole's offset poking out through the half-round side's; tangency-labs/solidcore#1795):
one closed valid solid with the one face open, as the owner ruled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the ring cut frame and the up-down join shell

SMLib's inset now keeps only the regions that are cavity, not the one the offsets close where
they overlap (between the two faces of #545's 0.5 floor, round the up-down join's two empty
octants). The frame's core under the recess is hollowed to a sealed void, so the case says two
shells and its closed form, 21044 mm³.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: #616's lid shells open at a rib's side, with the 0.15 lip

SMLib keeps the skirt top's offset where its loops wind the other way under the opening, the
cavity's floor (the owner's ruling of 2026-10-31: build it; a lip thinner than the wall is no
break-through).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing tests: the action matrix's shells and chamfers as they fail with SMLib batch 7

The ring cut frame's and the up-down join's shells build now, and so do the up-down join's and
modern-plastic's chamfers (SMLib smlib-blend-refusals). #616's lid in the corpus still fails
SMLib's loop check, the shelled box shelled again at an inner wall is unchanged, and the
oblique cut of a cylinder's fillet still fails SmSurfOfRevolution's Test #7: 3 actions of 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin 26cc451 (batch 7: rounds past a rim, blend refusals that build, shells)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing tests: the shell after a cut whose end touches an arc side builds on SMLib batch 7

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Surface fair test: the energy falls strictly, the face moves, and the edges are read after the fair

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sketch scaling test: the first dimension sets l1 to 40 and scales both joined rectangles about the origin

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames tests: a pick on a moved component or an instance removes the exact round and bore volumes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Issue 1080 tests: the rib's rounds and the mitred corner chamfers and rounds have their exact volumes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Engine tests: lip_after_boss checks each lip's and groove's exact band, hole_as_deep_as_the_plate each hole's exact bore

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Robustness tests: lip_after_boss and hole_as_deep_as_the_plate live once, in the engine's tests.rs with exact volumes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Engine tests: loft_cut goes; loft_spacing's hollow elbow covers its section counts and more

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel loft test: the square-to-circle loft has the oracle's exact ruled volume, without printing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tessellation lens test: the lens's triangles fill exactly the rhombus through its arcs' midpoints

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pattern test: six chamfered holes take exactly five more holes' bore and chamfer rings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel pocket floor fillet test: the corner rounds and the floor loop round add their exact volumes, by Pappus at the corners

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Shell regression: the saddle-corner shell opened on the top box's side has its exact volume

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib history test: every operand's order is the identity on its record's faces and edges

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Boolean history tests: the SMLib module's box-minus-sphere, box-minus-cylinder and box-union-box copies go; the top-level ones check more

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Modify history tests: shell, offset and thicken are one test each through the public API, with the volumes, refusals and history the SMLib copies checked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chamfer history test: the chamfer after each box cut is exactly one face on the painted block too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Grid test: a pole side's face is the five triangles fanned from its one grid node, none degenerate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel tests: the twelve ignored print-only debug tests and surveys go; coplanar_curved_booleans checks the flush-capped cylinder cuts and unions they printed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel: the #883 board fixture generator is an example, not an ignored test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import test: a seam sphere whose meridian stops short of the pole imports as the whole 2 mm ball

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Material tests: the nine copies in material_properties go; the persistence file checks the library copy's card and formats 20 and 21 in one loop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sample test: one loop checks every sample builds cleanly and without a panic; the robustness copy goes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing: the non-antipodal seam sphere import, refused for a loop of no (u, v) area

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: rustfmt the board fixture example and the coplanar asserts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two 3871 cone cases were byte-for-byte the 258 cases; the 258 cases carry their sources

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: a volume or area can be graded as a hand-derived range where analysis only bounds it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: fillets keeps one case per regime; 17 replications of a case in the same regime go

The sloped-basin chamfers and rounds at 0.5 mm rims repeat the 1 mm rim's regimes; two of the
three knife-edge chamfer tips, the r1 and box r3 curvature corners, the r1 tangent corner, the
1 mm pocket-rim and hole-rim chamfers short of the floor and the r1 together-round each repeat a kept case's regime
and grades. #854 moves to 851-chamfer-arc-top-edge-9-5, and the cases that cited a dropped one
cite the kept one or state its formula.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: five cases outside fillets repeat a kept case's regime and go

A square cut is the slanted plane's ordinary crossing; the cam's half turn is the quarter turn's
contact at a symmetric angle; the r15 slab stands inside the same coincidence tolerance as the r10;
the 90 degree unfold and the 40 degree flange repeat the 72 degree and 20 degree cases' formulas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3243 rim and tooth join graded on its volume (rim plus the trimmed tooth less their 0.01 mm overlap)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3782 emboss on a cylinder graded on its volume, area, faces and box (the wrapped 4 x 5 badge raised 1 mm)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3604 G2 swept-tool cut graded on a volume range (filleted box minus the swept corner section)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4505 coil joined through a cylinder wall graded on its volume, area and box (cylinder plus the wire's screw-swept segment outside r 76)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4879 window cut through a thickened spline revolve graded on a volume range and its faces

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4623 join of crossing pleated loft skins graded on its volume and box (both skins less their overlap)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 831 tapered glyph extrude graded on a volume range and box (the font's S drafted in by 10 deg)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 2357 ring of 90 cylinder segments graded on its volume and box (the segments less their 90 joint overlaps)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4542 fluted wall joined on a revolved base graded on its volume and box (the base by Pappus plus the fit-spline ring)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1985 and 2243 STEP-export enclosures graded on their volume and box (the outline less the cavity, plus gusset and standoffs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: both 4092 loft, ribs and pad unions graded on their volume and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1525 graded on its volume (the convex body's exact 2 mm inward offset), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1494 graded on its volume (box and cylinder less the 1 mm-offset cavity, sharp to rounded concave edges) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4492 graded on its box and a volume range (the face's 19 mm sweep added, within the block's sides)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 745 graded on its volume (the end moved 1 mm plus the spline boss's exact area), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4567 graded on its volume (the revolved spline less its revolved 2 mm offset), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the up-down squares shell graded on its volume (the columns less the 0.346 mm-offset cavity, sharp to rounded concave edges) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 545 graded on its volume (the frame less its 0.5 mm-offset cavity, sharp to rounded concave edges), its sealed pillar void and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the shell-again case graded on its volume (the shelled box less the 0.5 mm-offset cavity in its walls) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the arc-sided plate shell graded on its volume (sharp to rounded at the hole's bottom), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 616 graded on its volume (the lid less its 0.5 mm-offset cavity, sharp to rounded concave edges) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 391 graded on its volume (the shelled housing, sharp to rounded at the flange, less the letters' 0.6 mm deboss) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: shell/3576 was the ladder's drafted box with rounds shelled, recipe for recipe; the ladder case grades it and carries #3576 and #3573

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two 851 chamfers of 2 graded on their volume (the cone's sweep, and its union with the front edge's prism)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the chamfered corner of the lipped shell graded on its volume (the chamfer's triangle through the wall)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the concave round into the peg's cylinder graded on a volume range (the torus it must add, the band it can't leave)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two folded 72 degree trays graded on their volume (flat area x thickness) and the walls' reach

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the flanged rhombus graded on its volume (flat area x thickness, all four reliefs cut) and its walls' ends

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the base with two adjacent flanges and a hole graded on its volume (base, bends and panels folded)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the flange beside the ledge graded on a volume range (the flange's two readings of its length)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two G0 window patches graded on the box the part they close keeps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the hub's six swept grooves graded on its volume (the revolved hub less each tube's part inside it)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the cut mirrored loft graded on the box its sections pin

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the three modelled-thread joins and the fine M48 graded on their volume (the basic profile's groove, Pappus)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the oblique-cut round graded by its seams (tangent, not curvature-continuous); the flanged rhombus says what it tests (its reliefs stay apart at 60 mm)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3841 is 168's rim touching its coin along a circle, and 4092's reduced recipe is its report less a flange clear of the failing join; the kept cases carry their sources

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the oblique-cut round keeps its old grade until the new blend algorithm lands

Its seams grade needs the continuity check to skip the body the round is not on. Fillet cases
wait for the new algorithm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1985's enclosure is 78 x 77 (74 and 73 inside, 2 mm walls); its volume 38063.827 by hand

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the three spline walls' face counts wait for the one-wall decision; their volumes grade them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import: a face bounded by seams alone runs its loop the other way, never turns over

A loop that uses each of its edges once each way (a whole torus within its tube and ring seams)
is the same set of uses run backwards, so it says nothing of the face's side. One written
clockwise in (u, v) turned the face over, against its same_sense: the torus came in inside out
with a warning. Such a loop is now reversed and the face keeps its side.

Test: seam_only_torus_imports_as_a_whole_ring, both orders of the two seams, volume 2π²Rr².

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import: a face bounded by a slit alone is the whole of its closed surface

A loop that runs out along a chain of edges and straight back (a meridian from a sphere's pole
stopping short of the other, out and back) encloses no (u, v) area, yet on a closed surface it
bounds all of it less a cut of none. The reader only read such a face when the slit already ran
pole to pole (and moved the sphere's frame onto it only then), so the 2 mm ball whose meridian
stops at 2.5 rad was refused for its empty loop.

The slit is now made the face's seams, so its loop bounds the surface's whole domain: on a
sphere, a revolution whose profile ends on its axis, or a spline closed round u that collapses
at both ends, the slit's meridian is run on to both poles, out and back (a sphere's frame put
on the slit first, whichever two points it joins); on a torus, the circle the slit lies along is
closed and the other circle through its start is the second seam. The seams on a sphere are its
own meridians (angle 0 on the equator), so their pcurves are exact lines on its form.

Tests: non_antipodal_seam_sphere_imports_as_a_whole_ball passes (its known-failing line goes);
seam_only_torus_imports_as_a_whole_ring adds a torus bounded by a slit along its tube.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg's concave arc and front top edge rounded together stay within the body's box

A new fillet case, report-fillet-concave-arc-and-front-top-edge-together-solver-residues:
the reported part's bar (with the sketch solver's residues) whose sides run tangent into the
cylinder, its concave arc and front top edge rounded r2 together. The plane of the front face
bounds the whole body, so every blend lies within the unblended body's exact box (SMLib's tight
box); graded to 4e-5, the corner patch's own tolerance. On SMLib 2fc375f the corner patch
stands 0.0374 out of the front face (box y min 0.0205): listed in KNOWN_FAILING.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg corner at r5 and r7

Two more fillet cases, the reported part's concave arc and front top edge rounded together at
r5 and r7, with the same exact-box containment check (graded to 4e-5, the corner patch's
tolerance). On SMLib 2fc375f the corner patch stands 0.128 (r5) and 0.230 (r7) out of the
bar's front face (box y min -0.0699 and -0.1723): listed in KNOWN_FAILING.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: blends that end where their face runs tangent into another

Fifteen fillet cases on the test-peg's shape with clean numbers: a bar 40 x 16 x 10 whose far
end is a half disc R8, a disc R8 standing 10 on its top, joined, so the front face runs tangent
into the cylinder along x = 40 and the front top edge (convex) meets the concave arc of the top
tangentially there. Each blend ends on a face tangent to the one it rolls on.

- Rounds: both edges together at r2 and r5; one after the other in either order at r2, and at
  r1.5 and r3; the front edge alone as a curvature round, whose end on the cylinder is a
  semicubical cusp. The containment invariant (the unblended body's exact box, to 4e-5) and
  G1 seams, or the analytic volume where the blend has a closed section.
- Chamfers: the front edge alone and the concave arc alone (analytic volumes: the section along
  x up to the wall, the cone's spandrel ring clipped by the sides), both together, and one after
  the other (1 then 2).
- STEP: the peg written to STEP and read back, its front edge rounded (analytic) and both edges
  rounded together.
- A cone: the peg drafted 5 deg, whose front face runs tangent into a cone along a generator,
  its front edge alone and both edges together.

The quadratures are tanh-sinh, converged to 1e-13; SMLib's own volumes of the passing analytic
cases agree to 4e-9. A sphere is left out: a plane meets a sphere tangentially at a point, not
along a seam, so it is not this ending.

On SMLib 2fc375f eight fail, listed in KNOWN_FAILING: every chamfer that ends tangent (status
1001, SmFilletNx1Corner), the two rounds together (the corner patch 0.0374 at r2 and 0.128 at r5
out of the front face, and the rounds meeting with normals 180 degrees apart where their
contact lines on the top cross), the same on the STEP-read peg (status 1001) and on the drafted
peg (its corner refused as unsupported).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: fillet corners graded curvature-continuous, the default to be

Six fillet cases that pick their edges with no type, so they take the fillet's default, which the
owner has ruled is to be curvature-continuous (G2) at every corner, with circular rounds kept as
an option. Each grades every seam of the rounds and of the corner patch G2, on one valid body:

- an oblique convex corner (a block drafted 15 deg);
- a four-edge and a five-edge apex corner (pyramids lofted to a point);
- a pocket's concave corner;
- a mixed corner (a step: one concave edge, two convex);
- a corner beside a cylinder (the top corner of a half cylinder).

All six fail on SMLib 2fc375f, listed in KNOWN_FAILING: today's default is the circular round,
whose seams jump in curvature by 1/r. On the five-edge apex the corner patch also meets two
rounds at 8.45 degrees (G0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg's front chamfer builds

With the SMLib fork's smlib-tangent-ends (a rail's end on its side edge is the rail/edge
crossing), report-peg-front-chamfer-d2 passes. Its line leaves KNOWN_FAILING, for the pin that
carries that fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the curvature-continuous corner cases pick the curvature fillet

The six corner cases added in 3a854104a took the fillet's default type, on the premise that the
default would become curvature-continuous. The default stays the circular round, so each case
now asks for the curvature fillet itself (type curvature: curvature-continuous sections and
corner patches) and keeps its grading: every seam of the rounds and of the corner patch G2, one
valid body. They are renamed from cov-fillet-g2-default-* to cov-fillet-g2-*.

The oblique three-edge corner (a block drafted 15 deg) and the pocket corner pass. Four fail, as
KNOWN_FAILING now says:

- the corner beside a cylinder: the curvature fillet builds its sections only between planar
  faces;
- the four- and five-edge apex corners: refused because the default setback is shorter than
  where the rounds' contact lines meet (3.90 and 3.51 mm from the apex);
- the mixed corner: SMLib sets back a corner only where its edges are all convex or all
  concave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg's concave chamfer, alone and after the front chamfer, builds

With SMLib's tangent end as an event of the fillet's trace (blend-end-event 6d73e4f), the
concave chamfer's rail on the cylinder ends where it crosses the seam along which the front
face runs tangent into the cylinder, continued past the vertex, and its end rib on the front
face is built from there. report-peg-concave-chamfer-d2 and
report-peg-front-chamfer-d1-then-concave-chamfer-d2 pass and leave KNOWN_FAILING. The two
chamfers together still fail, now at the mixed-convexity corner where they meet: its line says
so. Rig against SMLib 0cc48bd: no area regresses (963/993 pass, 961 on a87c502), ladder 168/168,
kernel lib only its listed failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: constant rounds of the exact classes, and a tee's round

A plane cutting a cylinder or a cone at an angle, a sphere or a cone coaxial with the other face, a
cone and a cylinder touching one ball, two pipes touching at a point: their rounds' centre lines
are rational, so the rounds are rational surfaces of degrees fixed by the construction ((4, 2),
(2, 2) revolved, (6, 2), (12, 2)). The tee's centre line is not rational; its round is graded on
its volume. Volumes from the divergence theorem over the exact pieces, at rel 1e-6. The six that
SMLib 0cc48bd traces are listed in KNOWN_FAILING with what they come out as.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the exact-class rounds pass on SMLib's classified exact rounds

The rounds now come as the rational surfaces their classes give, closed ones as two faces split
at their seams, the touching pipes' as four: one splines entry a face, each of the class's degrees.
Their KNOWN_FAILING lines go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin 7ac037e (the new blend's tangent-end event, zero-speed G2 ends, and its exact-class rounds)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the fillets known-failing list is the 22 cases that fail on SMLib 7ac037e

Twelve listed cases build on the new blend's end event and exact classes, or were already
built on develop: they come off the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: #316's bottom rounds as large as the wall, or larger, shell with a step wall at the opening, not refused

Where the round meets the open bottom the cavity's wall steps down along the bottom's normal, so the
round meets it at 90 degrees and the opening is exactly the picked face. The cases are renamed and
graded on the exact volumes, and come off the shell known-failing list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Merge fixes: every crate and test target compiles on the merged tree, but for crates/geom's hlr

world_state, view::bounds, home_camera and scene return Result on develop; new
main code takes that with ? or session_world. New fixtures carry the spline's
nurbs. ForeignCopy::of returns Result. occurrence_placement_with walks the path
with its moves, since the placement index holds pending_moves only.

The hlr port is separate and still to come: this commit does not compile as it
stands in crates/geom/src/hlr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Drawings hidden lines: read develop's B-rep records

Edges come from the record's edge list, cut to their interval (C3::of_edge), and
faces from its face list; a cylinder, cone, sphere or torus chart takes its bounds
from where its NURBS form lies on its label (S3::of_face). A rigidly placed
revolution has main's revolution chart; other placements stay refused. Moving a body
to its centre goes through Brep::moved. Loops are read against the natural normal of
the face's parameters where a chart wraps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden-line fixtures: build develop's records from the fixtures' data

Fixtures keep their bounded curves and surfaces and their own edge numbers; a private
builder makes the canonical record, and the local prepare puts the edges back in the
fixture's numbering. Assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden lines: tests of the bounded edges, face charts and placed revolutions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* drawing-hlr doc: what is drawn and refused on develop's records

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* hlr tests: a placed revolution is refused when its placement is not rigid

The new model has one record for main's Revolution, which was drawn, and its
PlacedRevolution, which was refused. An identity placement is now the former, so
this test's fixture takes a non-rigid one. The refusal it asserts is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden lines: a traced intersection is drawn only where its spline lies on both surfaces

A leader off either surface is refused like a curve with no spline to follow. Tests: a traced rim
drawn on the circle and plane within tolerance, the same leader 1 mm off refused, and kernel bodies
with arcs through the production prepare against closed forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden lines: kernel bodies through the production prepare against closed forms

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Tests from main: the world state is a Result here

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* A blend's pick measures close edges on their curves, not their polylines

A polyline can be a chord off its edge, more than two edges are apart near a
tangent point. A pick exactly on a ball's rim took the straight edge the rim is
tangent to, and solidcore built a chamfer of that edge with a clean check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk
(cherry picked from commit c786db6bf49804fb83a02f0eb7f83bd9f82fa643)

* Merge fixes from the first SMLib test pass

Model cache key covers the crates develop's kernel adds under doc (profile, smlib, step).
A piece taking a name also takes the feature that made it: SMLib lists a cut's pieces in another
order, and the swap left the name on a piece of the wrong feature.
A replaced analysis keeps its status slot. A command with no world picks does not place the model
first, so assembly.mass_properties answers for a flattening placement. FeatureCommon loses the
touching key the merge added; only the contracts that read it take it.
Two of main's tests listed as failing on SMLib, with why.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Merge fixes from the ui test pass and the gates

Main's thread.direction keys go with develop's thread hand, which replaced them. Vietnamese for the
messages develop added while main made vi a complete catalog. CGA and 1-bit themes set develop's
comb and section hatch colours. A ribbon button with a persistent effect is pressed only while its
tool runs, so persistent_ribbon_pressed alone decides how its effect is shown; other analyses stay
pressed while on. Two of main's ui tests listed as failing on SMLib, with why.
Gates: fixed thread tables become slices, one collapsed if, rustfmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* A silhouette takes its facing from the surface's normals

A flat triangle beside the outline can tip the other way from the surface it approximates, and its
edges joined the outline. On SMLib's sphere that made 192 segments instead of the equator's 64, 100
curves and 95 profiles from the tight fit of #7989. Each corner's normal is used where it is close
to the triangle's own; a mesh without such normals (none, zero, not numbers, or averaged across
creases) keeps the triangle's normal, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Clippy and rustfmt on the merged tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Stepwise open checks every feature under the session's mode

OpenSteps::start evaluated under the default check mode, and finish kept those results under the session's mode: an each_step or off session opened in steps recomputed nothing. start now takes the mode (the app passes its session's), and a mode that changed before finish evaluates the design again under the new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Clippy without SMLib: the planar-sheet edge reader is built only with it

Its one caller is in the smlib-only sheets module, so without the feature it was dead code and
clippy -D warnings refused the kernel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* SMLib: pin d01d7b0 (the new blend's one Gⁿ section generator: the chord, circle and curvature sections, and the variable rounds as the union of their balls)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the section orders, chord, circle and curvature section, on planes and against a cylinder

Eight fillet cases for the blend's cross-section by its order of contact with the faces, each
graded on its analytic volume at rel 1e-7 and its exact continuity (the order, and not the next):

- a box's top back edge chamfered 3 (G0), rounded r3 (G1) and curvature-rounded 3 (G2): the
  areas cut off the corner s^2/2, (1 - pi/4) s^2 and 113/756 s^2, the last by the default
  thumbweight's definition;
- a pipe R10 dipping into a plate, its concave edge chamfered 2 (the chord between the contacts of
  the ball SMLib rolls for that setback, radius 1), rounded r2 and curvature-rounded 2, each
  section's added area by Green's theorem along the plate, the section and the pipe's arc; the
  order-2 section is built from the faces' feet of the point at distance d from both, which on
  the pipe are not linear in d;
- a boss root curvature-rounded 2, the square corner's section revolved (Pappus);
- a variable round r1 to r5 along a box edge (rel 1e-5): the balls' envelope is a circular cone,
  and the volume is the cone's sections integrated along the edge.

Three fail today and are listed: the two curvature rounds whose faces are not a square corner of
planes (SMLib's quintic blend curve, not the order-2 section: rel 6.5e-7 and 1.2e-5) and the
variable round (great circles, not the envelope's: rel 4.8e-5). The other five pass on SMLib
7ac037e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the curvature fillets' expected bodies from the order-2 section at thumbweight 0

SMLIB_BLEND_CURVATURE's section is now the order-2 G^n section at thumbweight 0. Between two
planes square to each other it cuts A = 0.154192655384275 s^2 off the corner, its first moment
about either face 0.0291753295725360 s^3 (Green's theorem on the section): the curvature cases
built on that corner (862, 2708, every-box-edge, every-hole-top-rim, every-l-bracket,
every-block-cylinder-crease, the three-edges-at-bar-corner reports, 3604's fillet) take their
volumes from it by their own methods, the peg's front blend 23.3237146876 (its section along x
up to the wall). Between planes the section's t^3 term vanishes (their feet are linear in the
distance): the box edge case is exactly G3. The boss root is a certified fit, G3 to the plate and
G2 to the wall at Continuity Analysis's tolerances: at least G2. The boss root and the pipe on
the plate pass on SMLib's section and leave the known-failing list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Curvature fillets: the section's default thumbweight is equal area, so the round's volumes are the circle's

On the round's rails the order-2 section takes off what the ball's circle does: (1 - pi/4) s^2 at a
square corner, first moment 0.0474559669443 s^3 (w = -0.5252123889). The kernel and engine tests
and the curvature rig cases take their volumes from it by their own methods; the pipe on the plate
from its own wedge (70.52878 degrees, w = -0.8544103493). The G2 corner patch's seam test is listed
until the corner step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: four G2 corners wait for the corner step: their patch meets the new section's rounds G1 at one face seam

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the turn at a corner of two rounds, Mitre (the default) and Swept, at a pocket's floor and a boss's base, by exact volumes

A round's spandrel A = (1 - pi/4) r^2 and its first moment about its wall M = r^3 (5/6 - pi/4):
Mitre adds L A -+ 2 M per edge (cut at, or run on to, the corners' bisector planes), Swept turns
the section about a convex corner's edge, (pi/2) M a corner, and refuses a concave corner rounded
less than the ball. The pocket's tangent chain round its R3 corners is a torus each. Graded to
1e-7, where Mitre and Swept differ by 6.6e-6. The Swept cases are listed until solid.fillet
takes a turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: a junction family: oblique wedges 30 to 150 degrees rounded and chamfered (exact), bosses upright and tilted, pipe tees and a Y junction

Four are listed with their causes: the equal-pipe tee (its exact conic-pair rounds meet at the
ellipses' crossings in a corner the old corner code cannot join), the tilted bosses (1001, before the
blend rework too) and the Y junction (refused for room at its triple points).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Variable rounds: graded by the union of their balls (their envelope), not the balls' great circles

The smlib crate's laws and ladder 005, 006, 007 and 012 take the volumes the balls' envelope
removes; the law with a corner is its own test, listed as failing until the corner step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel tests: variable rounds graded by the union of their balls, the removed volume to 1e-4 of itself

removed_by_balls integrates, in each plane square to a right-angled edge, the corner the union
of the balls leaves (by rays from the edge, the least entry over the balls), cut to the body's
section. The law with a corner through a middle point is its own test, listed as failing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel tests: a spline radius whose balls fold over one another at its peak is refused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the variable round on its cone passes (the round is the balls' envelope)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: three rounds of different radii at a corner listed: the corner's transition kinks with the balls' touch circles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Ladder: the variable rounds graded to 1e-6 by the union of their balls; 012 by its law going on past the edge

At the default 1e-3 the great circles' volumes (4e-6 off) passed too. SMLib builds each within
1.6e-7. The golden takes the new volumes and areas; counts unchanged. The G2 corner test listed
as failing passes on SMLib's step 3 and leaves the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reference tests: the variable rounds 77, 78 and 81 pass on SMLib d01d7b0; their known-failure marks come off

The new section builds their edges on the surfaces, so STEP export no longer finds them 4.6e-5
to 6.1e-5 off. develop's Reference tests (60393a718) report all three as passing while marked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import: a ball's halves whose seams are off each other's quarter lines each form within one turn

A sphere split into two halves along a circle about its axis, each half covering a pole with no
seam, gets a seam per half from the first vertex of its loop to the pole. The circles between the
halves group their frames so they turn together, and when the two seams are not a whole number of
quarters apart no one turn fits both: the group kept its frames, a half's form ran past one turn,
SMLib's trim (SMLib and solidcore alike) across the form's end crossed the face, and the mesh
folded over the ball (a rotor's ball showed torn; its half had 196 times its area in triangles).

When no one turn fits the group, each spilling face is now turned on its own to start on a quarter
line. On the rotor file this also clears three other faces that were filled leniently and a
0.076 mm edge gap; regression test in step_in/tests.rs with the area and volume of each half.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz
(cherry picked from commit b3188e005d427043b918267449c2336a1777e54f)

* SMLib: pin 5e8c9c1 (the new blend's corners: Ball and End/Join; exact fold and room checks with fit sizes; overflow in place; the round as its definition)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: a law's dip shows its corner ball's sphere, a peak's two rounds cross (the reasons had them swapped)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reference tests: the variable rounds 77, 78, 80 and 81 expect the union of their balls

A variable round is the envelope of the balls rolled along the edge, which takes less than a
quarter round in each section. The expectations are now that union, the law continued past the
edge's ends along its end slopes, integrated by Gauss-Legendre panels in x and t; 2, 4 and 8
panels agree to 1e-9 of the body's values, and 77's removed volume matches a brute-force union of
balls to 2.5e-10. The nearest-ball search now scans the balls the ray meets around ball x
(|x - s| < r(s) sqrt(sin 2t)) on their own, which near the faces and where 78's radius closes to 0
are narrower than the global scan's step. Regenerating keeps each case's known_failure. 79, a
constant radius, is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing: the law corners' kernel and crate tests and rig 1207 pass on SMLib 48ea616

SMLib builds a variable round's law corners as its balls' union (the corner
ball's zone at a dip, the sides' crossing at a peak): the kernel's corner
through a middle point (39.5410) and the crate's 4 -> 2 -> 4 law (39.5421) pass.
Rig 1207 (the bar's top edge rounded after the boss's arc, r0.5) builds and
grades on the same SMLib; it failed on c820346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: every fillet and chamfer case rounds its tangent chain

The owner's ruling of 2026-11-01: the rig and the ladder round with tangent_chain true, how a
user's default pick behaves. The 38 fillets-area recipes and the ladder's 07-fillets/016 and 018
that passed false now pass true. The shell recipes keep theirs: a shell's tangent_chain is its
open-face chain, a different feature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the partial-selection cases kept as -partial-chain copies, tangent chain off

Where a case's point is one edge of a tangent chain rounded alone, a copy keeps tangent_chain
false as its own case (SMLib rounds exactly the picked edges, ending at the smooth vertex); their
expectations stay as they were, to be re-derived:
- fillets/1207-fillet-box-end-edge-into-unblended-round-partial-chain;
- fillets/every-fillet-after-fillet-curvature-front-then-side-r3-partial-chain;
- fillets/1207-fillet-bar-top-edge-after-boss-arc-round-partial-chain, renamed from
  ...-no-tangent-chain: with the chain on it is exactly 1207-fillet-bar-top-edge-after-boss-arc-round,
  which the rig already has;
- ladder/07-fillets/020 and 021, the r5/r3/r7 and r5/r3/r2 corners (016 and 018) with the r3 on
  its edge alone: with the chain on, the r3 runs on along the r5 round's end arc and down the
  vertical edge the third round was to take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the concave arc between the block's tangent sides kept with tangent chain off

fillets/every-block-cylinder-tangent-concave-arc-r2-partial-chain: the pick takes one piece of the
concave half circle, which SMLib splits; with the chain off its other pieces are left out, and the
blend is refused at the piece's end (the base gate's outcome). With the chain on the case rounds
the whole half circle. The copy keeps its expectation, to be re-derived.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: two chains that now build graded by their exact volumes

With the tangent chain on, two cases round more than the edge they pick, and their old
expectations were the single edge's:
- 1207-fillet-box-end-edge-into-unblended-round: the r1 chain is the end face's top edge, the r3
  round's end arc and the back upright; 34 A + (pi/2) A (3 - c) by Pappus on the arc:
  V = 7953.139216 (it built 7953.139216, the old 7957.505 passed only inside 1e-3), 10 faces.
- 851-fillet-top-front-then-front-left-upright: the upright's chain runs up the first round's
  end arc on x = 0 and along the left top edge, so the corner becomes the R2 ball's eighth:
  V0 less the first round's spandrel to the wall (35.344727) less 27 (4 - pi) + 2 pi/3:
  V = 9530.777979 (built 9530.777987), 10 faces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: a curvature chain round a round's end refused for its size; the concave half circle builds

- every-fillet-after-fillet-curvature-front-then-side-r3: the side edge's chain runs round the
  first curvature round's end curve, whose radius of curvature has a weighted mean of 3 (its
  setback) and is unbounded at the ends, so somewhere below 3: the size-3 blend's contact line
  folds back on itself. Refused, "larger than the faces beside its edges allow", as ladder
  07-fillets/016's r7 on the r5 arc. (It was solid or refused for running on tangentially.)
- every-block-cylinder-tangent-concave-arc-r2-no-tangent-chain: the chain takes every piece of
  the half circle and ends at the convex edges it runs on into; it builds the analytic 19091.9620,
  so the outcome is solid (the refusal alternative was the chain-off one's).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known failing: two 851 chains whose corner piece is a ball of tube-centre radius 0

851-fillet-arc-then-top-front and 851-fillet-top-front-then-upright: with the tangent chain on,
each R2 chain runs along the end curve of an R2 round on a curved face (the arc round's end on the
front face; the first round's end on the wall), where the rolling ball sits on that round's own
centre line, so the piece is the ball about (39.2538, -19, 8): the three-edge rolling-ball corner.
SMLib fails with status 1001; the same piece on a plane end arc builds (front-left upright).
Expectations unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Ladder: 016 and 018 refused, their r3 chain takes the vertical edge; 020 and 021 recorded

With the tangent chain on, 016's and 018's r3 runs on along the r5 round's end arc and down the
vertical edge, so the third pick (60, 40, 8) is 3 from both of that round's contact lines and
names no edge: refused, asking for a point along one edge. The corners they were made for are
020 and 021 (the r3 alone), whose golden entries are 016's and 018's (021 measured on f12a101).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: three rounds at a box corner end on one rational patch on the ball's sphere, not an analytic sphere

SMLib's Ball corner is always the rational patch exactly on the sphere (owner ruling, blend
design §23), so the corner counts as an 'other' face beside the three cylinders and six planes.
The removed volume still checks the corner against r³ − πr³/6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the curvature round on a pipe on a plate is listed: a seam grades G3 where exactly G2 is wanted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: the box-and-fillet wire fixture records the round's cylinder frame as SMLib now keeps it

The round's cylinder keeps the frame it was made on when it is turned (SMLib's SwapUV no longer
re-derives it): its origin sits at x = −20 on the same axis line, (x, 2, 8) along x, radius 2.
Same cylinder; one number in the record moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known failing: two kernel tests' reasons as they fail on SMLib 5e8c9c1 (a partial selection running into an unblended tangent edge)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: two curvature rounds get 600 s, past the 180 s default, while G2 certification is slow (tangency-labs/smlib#96)

On the CI runners the boss root and the hole rim, both size-2/size-1 curvature rounds, build
correctly but take more than 180 s: the order-2 section's span certificate and the round's
definition are evaluated station by station. The per-case limit is the one the thread cases use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Lid ring sketch test: find the ring under the pick, not by main's kernel's name

On SMLib the lip join's exact history names the lid underside's ring a piece
of the lid's own start (F14:start#[...]), as the naming rule says for a face
that came from the feature's input; main's kernel named it after the case's
top it rests on (F2:top). The test looked the ring up by that name and so
stopped before the attachment it guards. It now takes the underside piece
under the pick point, which the cap certificate attaches on either kernel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Viewport culling test: each box's triangles from its mesh, not 12

SMLib meshes a 10 mm box in 108 triangles, so the hard-coded 12 a box stopped
the test before it reached the culling. The expected counts are now each
body's span in the scene.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Timeline chip test: a fillet that really reduces

The R20 fillet with fit reduce on one top edge of a 10 mm box builds on SMLib
without a reduced-radius warning, so the fixture had no warned feature. It
now rounds the four vertical edges at R6, reduced to the full round (5), as
the copy-warning test beside it does, and checks the warning says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Oracle: 34-chamfer-then-fillet and 35-fillet-curved-curved pass on SMLib 5e8c9c1 (their STEP edges are on their surfaces)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known-failing: the shell of a fully rounded box opened at one face fails on SMLib 5e8c9c1 (tangency-labs/smlib#102)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known-failing: the action matrix's oblique cylinder cut fillet passes on SMLib 5e8c9c1; two shells still fail

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the boss root's curvature round gets the rig's 1800 s cap: on the CI runners, 8 cases at a time, its G2 certification passed 600 s (tangency-labs/smlib#96)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: a case's continuity can ask for an order per seam (seams: [{order, edges, exact}])

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the pipe on a plate's curvature round meets the plate G2 and the pipe G3, 40307.8856312 (option B's order-2 jets, tangency-labs/solidcraft#10845)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Edge names: a seam names its one face once; the curve-id test reads every edge kernel-neutrally

A seam's two sides are the same face, and edge names list each face an edge
bounds once, so SMLib's extruded circle names its side's seam F2:side:c1, with
no separator. The name grammar now says one face also means a seam. The #5858
test no longer counts one '|' an edge: every part of every edge name is a
whole face name of the edge, one per face it bounds, two for the rims and one
only for the side's seam (checked to run bottom to top on the circle).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* rustfmt on the merged tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Known failing on SMLib: two of main's new tests assume truck's box mesh and fillet torus

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* SMLib: pin f916a8d (a round on a definition face is its definition; the G1 setback fill certified convex, setbacks too short refused naming the least; the G2 certificate halves a span no level can certify at once)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Fillet: a setback too short for its corner is refused naming the least that builds (smlib_blend_fit_size)

SMLib's setback corner takes a G1 fill only once certified convex, and refuses a setback too
short for that as SMLIB_ERR_NO_ROOM with SMLIB_FIT_SETBACK_AT_LEAST, the smallest setback that
builds. The kernel reads it (solidcraft-smlib binds smlib_blend_fit_size) and names it; the
Fillet dialog says it in plain words. Other room refusals keep their words. The r5 box corner
set back 5.5 is refused naming 5.962, which builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: three rounds of different radii at a corner meet in SMLib's setback corner

Each round runs whole to its section square to its edge at its setback (the owner's rule, at
least 1.5 r, scaled to the least at which the G1 fill is certified convex), and the hole is the
setback split: one patch per round and the triangle in three quadrilaterals, 15 faces, G1.
Outside the box the sections span the body is the three strips', so its volume is theirs within
that box's. A later r3 round at the mitred corner makes the body all three at once make
(7928.142563938, 15 faces), as the engine and the model-cache tests have it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: SMLib's own corner between curvature rounds is curvature continuous, as the G2 patch is

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the boss root's and the hole rim's curvature rounds take the default timeout again (37 s and 34 s on the box under the rig's parallel load, tangency-labs/smlib#96)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Agents: model decisions use exact geometry; a mesh is for display, export, previews and mesh bodies

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* xtask: mesh-decisions, model decisions use exact geometry; today's 176 mesh decision sites are listed and the list only shrinks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Sheet metal: cuts and holes pass over sheets and bends by their exact boxes, never a mesh's

A primitive cut skips the sheets kernel::apart (exact bounds grown by the record tolerance)
finds clear of its tool; the bend check leaves the clear case to kernel::boolean, which answers
it from the same exact boxes with no intersection work. The mesh-box helpers are gone, and their
four lines leave xtask/mesh-decisions.txt (172 sites left).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Agents: AGENTS.md loses a stray merge-conflict marker line at its end

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Locales: Vietnamese for the setback-too-short refusal, now that vi is a complete catalog

Main made vi a complete catalog; develop's new message (ui.fillet_error_setback_short) had no vi
entry, so every_complete_catalog_carries_every_english_message failed on the merged tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: exact volumes for 1213's bent-tube round and 4782's bar round, rel 1e-6

1213: the loft is a cubic skin through the five sections (ellipses between
them), not a torus; its volume 131601.597487935 by quadrature less the exact
rolling-ball removal 233.662461919 gives 131367.935026 (was a Pappus estimate
on a torus, 131360.148, at rel 5e-4).

4782: the section's area in closed form, 25 pi/3 - 5 sqrt(75) + 25, so
V = 630.2934873 (was a grid estimate, 630.293125).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Kernel rig: the boss root's and the hole rim's curvature rounds take 600 s again: under CI's parallel load they pass the 180 s default (develop 820b7b6)

They take 37 s and 34 s alone on the box, but CI runs 8 cases at once on slower runners. Their
G2 certificate cost is the open item (tangency-labs/smlib#106, moved to solidcore#2344).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge: clippy's auto-deref, and the mesh-decisions list for the merged tree

Develop's list was taken on develop alone. Main's code (tap-marking reach, cut and hole box
checks, join pieces, print faces, placed measuring, selection items, imported mesh payloads) and
the branch's own exact_edges and named_vertex use meshes too; three listed functions were renamed
by main (face_outline and plate_recesses into FaceSlice, paste into build).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* After the merge: main's new tests on the SMLib kernel

- Cut To the far side of a curved wall (#8634): the tool stops past the first crossing of the
  face ahead of the profile; SMLib's whole bore is one face that a line crosses twice, so the
  single-crossing rule found none and the cut took nothing.
- Clearing view analyses goes through refresh_display, as main's #10687 made the others, so an
  open feature editor keeps OK and Cancel after Zebra.
- vi, a complete catalog on main, gets the setback-too-short message.
- fillets/KNOWN_FAILING: 4782's cause is now its continuity check (SMLib f916a8d builds the
  expected volume).
- Known failing, as main's tests assume truck: the spline wall's spans as one mesh patch, a
  hole touching an edge at a point leaving one body, and a copy of a copy's triangles matching
  a fresh mesh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Twisted sweep: circles about a straight path are exact cylinders (solidcore#2184)

A twist about a straight path maps a profile circle centred on the path's
line onto itself, so its swept wall is exactly the cylinder. The skin
through the stations stayed within 3.9e-9 of it (6.6e-9 on the outer wall),
and a boolean with another body on that cylinder failed with status 1001
(solidcore#2184; the kernel's handling of a B-spline face lying on a
cylinder stays open there).

sweep_controlled now builds those walls exactly when the path is lines
along the profile's normal and there is no end scale or rails: a profile
whose every loop is such a circle is swept untwisted, and such holes in
another outer loop are cut as exact cylinders from the skinned sweep of
the rest. Other loops, and an axis-centred arc inside a loop of other
curves, are skinned as before; a failed cut falls back to skinning all.

Regression test in smlib_sweeps_tests.rs: #2184's tubes joined at 10, 16,
18, 20 and 30 degrees give one closed body of 11.5625 pi with cylinder
walls; a twisted hexagon with the bore keeps a cylinder bore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEtwSrdwZxqTQp5MfnU

* After the merge: a hole that misses is found by exact boxes; a face is a one-face patch; main's mesh-box helpers gone

- `hole_misses` (main's #10701, through brett's branch) decided from the targets' mesh boxes. It now uses their exact boxes (`Body::exact_bounds`). An unknown box still leaves the hole not known to miss.
- With #10303's two shortcuts and `hole_misses` off the mesh, `body_box`, `mesh_box` and `padded_box` have no caller left, and are deleted.
- `project`'s intersection link passes its one face to `meeting_edges` as a one-element patch. This branch picks one face, not #9009's mesh patch.
- xtask/mesh-decisions.txt drops the six sites that no longer use a mesh here: `apply_traced_with`, `cut_end_past_face`, `beyond_cylinder_reach`, `hole_misses`, `body_box`/`mesh_box`/`padded_box`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge: split_move's Result reaches its callers; to_local's duplicated move check goes

`frames::split_move` returns a Result on this branch: an unplaceable model is an error, not a silent no-split.
- Move/Copy of a component (main's #9914) propagates it, as its other calls do.
- `to_local` had the solid.move check twice after the merge (brett's Option one and ours). Ours stays, after the no-picks/not-placed return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge: main's two new tests take world_state's Result, as the rest of their files do

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Native B-rep: a ball patch is its own surface kind, read from and written to SMLib's flat kind 6

SMLib's flat arrays now carry the corner of three equal rounds as `SURFACE_BALL_PATCH` (kind 6): its net as a NURBS face's block, with its sphere's centre and radius as its definition (ids 36 and 166). The record reads it as `ball_patch {center, radius}`, a label like the analytic kinds, with the net as its `nurbs`. A plain sphere with a form won't do: the net is not a piece of SMLib's sphere NURBS, so SMLib's `IsNurbSurfaceSphere` would refuse it.

Written back, a ball patch is kind 6 with the same definition, which SMLib takes once its net is certified on that sphere. Elsewhere:
- Offsets classify it as its sphere, so its offsets stay exact and collapse at the centre.
- Face kinds count it as a sphere: fillet_three_edges_at_a_corner's corner is now `sphere`, no longer `other`.
- STEP, which has no ball-patch entity, gets the net as the face's B-spline surface, pcurves included.
- Iso curves and SSI of the label are refused; the face's form is what evaluates.

Test: a_rounded_cubes_ball_patches_go_round_with_their_spheres. The cube's eight corners are ball patches about the corners pulled in by r. Points of each patch lie on its sphere to 1e-12. The patches are kind 6 again after import, with the same definitions bit for bit, and the closed-form volume holds.

Format: pending/ball-patch-faces.rs. Docs: docs/native-brep.md and the rig README's `surface_types` (`ball_patch`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* SMLib: pin v1.1.0-alpha (a18bbe5): the generic blend's step-4 corners, the Ball's sphere patch through the flat arrays, all-target CI

Since f916a8d:
- #120: every target again, plus the warnings fix;
- #121: the Ball's patch as flat kind 6 with its sphere, read by the previous commit;
- #122: tests gated on counts;
- #123: the Mixed corner;
- #124: the End at a smooth vertex;
- #125: four or more rounds, and open setbacks;
- #126: the equal-area thumbweight guard;
- #127: the trunk merge.

The SMLIB_PREBUILT checksums are from the release prebuilt-a18bbe5…, written by `scripts/fetch-smlib.sh --pin`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* smlib export tests: rustfmt's line for the rounded cube's edge midpoints

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the fillet and ladder results on SMLib v1.1.0-alpha, the new failures recorded with their reasons

Fixed (off the known-failing list): the Mixed corner's peg cases and the concave arc with the front top edge (smlib #123), and the 40° boss junction (smlib #124). Eight cases in all.

New failures, recorded as they are, each with its reason. They passed on f916a8d.
- **Six cases grade a blend seam G0 where G1 (or G2) is wanted,** at the end of the round's contact seam, after smlib #124's End at a smooth vertex. Two of them also shift in volume.
- **Four cases come back unsupported** after smlib #125, which leaves setbacks to the Setback's corners only.
- **Ladder 07/012** makes 9 faces, 20 edges and 13 vertices, where its golden had 8, 18 and 12. Its golden entry is the new result, with the reason added.

Whether each change is by design or a defect is being established. A defect is fixed in solidcore, where the End and the Setback are being brought over (#2364, #2365), not in the frozen SMLib.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel ladder: 07/021 and 06/018 recorded as they are on SMLib v1.1.0-alpha, each with its reason

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel ladder: a golden case marked unstable is gated on its status, and 06/018 is marked

On SMLib v1.1.0-alpha, 06/018 makes 597 or 594 edges from the same input:
the union's post-process keeps pointers to edges it has deleted. A golden
entry's `unstable` reason makes the gate compare that case's status only
and name it in its output; recording keeps the reason, and only an edit of
the golden removes it. v1.1.0-alpha.1 fixes the cause and removes the mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge with main: its new code on develop's exact bounds, types and thread fields

- The sheet cut's cull (#10301) and the tapped wall's (#10227) use each
  body's exact box (`exact_box`), not its display mesh.
- model.threads replies with develop's thread fields: form, hand (right,
  left or both) and starts.
- surface.boundary's schema checks a network curve's continuity as the
  handler does, and words a list entry's error as it does.
- Main's new tests take develop's Hole fields and world_state's Result.
- mesh-decisions: contact_sweep's triangle check is now `depth` (main
  split `hits`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known failing: the 14 cargo tests SMLib v1.1.0-alpha fails, with what each sees; two cases that pass now

Develop's CI after the a18bbe5 pin (run 41522001173) fails 14 tests that
passed on f916a8d, and passes two listed ones. Each new line says what the
test sees on v1.1.0-alpha; v1.1.0-alpha.1 fixes the setback hole's cause.
shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls and
oracle 37-pyramid-apex-blend pass and leave their lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Cargo.lock: develop's profile, smlib and step crates at main's 0.30.1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: main's six new sketch-only commands are exempt from a kernel case

sketch.construction_line (and its horizontal and vertical forms) and
sketch.spline.insert_point, remove_point and reverse change only the 2D
sketch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Cuts leave the bodies their tools can't reach, by exact boxes (#10225 on exact geometry)

- The per-target cut loop skips a body whose exact box lies clear of
  every tool's, as main's version did with mesh boxes. The sheet culls
  (#10226, #10301) and this one now leave the far sheets and bodies alone:
  a_cut_leaves_bodies_it_cannot_reach_as_they_were passes and leaves the
  known-failing list.
- a_cut_still_runs_where_its_tool_touches_grazes_or_meets_a_curved_face:
  a tool 0.5 µm clear of the block is now left out (exact boxes; 0.5 µm is
  far past the bodies' tolerances); touching and 0.1 mm in still cut.
- Known failing, with reasons: main's edge lookup by a stored point
  (#11286, on the display mesh) is not taken; SMLib refuses the
  wrong-way chamfer for its tangent chain first.
- EXEMPT: main's eight new sketch-only commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: main's new view, rendering, appearance and settings commands are exempt from a case

62 of the commands main added change no geometry: the view and render
panes, rendering lights and results, appearance tools, settings profiles,
point clouds (drawn as points, never a body), the selection, two sketch
edits, component links and History bar visibility, edit.repeat,
timeline.play, inspect.compare_picture (a picture against the outline),
and component.paste_from_design, which pastes the app's cross-window
clipboard that no command fills. Each joins EXEMPT's first section under
its family's reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: construct.plane.axis_point gets construction cases

The plane through a box edge and its far corner, graded against its
closed-form normal (0,-2,3)/sqrt(13) through the origin, and the refusal
of a point on the axis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: assembly cases for mass properties, align, find limits and moving items between parts

- assembly.mass_properties: two boxes (2 g/cm3) in a rigid group: mass
  0.006 kg, centre (18.333,5,5), inertia diag(0.1, 1.0333, 1.0333) kg mm2
  by the parallel-axis theorem.
- occurrence.align: a block's end face onto a base's top face: a quarter
  turn about y, centre (70,20,20), box (65,15,10)-(75,25,30).
- joint.find_limits: a slider between two stops: min -20, max 10 mm.
- component.move_features, browser.reparent and
  component.move_sketches.to_parts: items moved into a turned and moved
  part keep their world place (volumes, centres and boxes by hand).

The mass case assigns a material it creates, so material.create and
material.assign leave EXEMPT. PATHS names the new command modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: export and print face cases in the import area

- file.export_step, export_stl, export_3mf, export_obj: a 30x20x10 box
  written and read back (the meshes converted to a solid): V 6000,
  A 2200, 6 faces, box (5,-10,0)-(35,10,10).
- file.export_urdf: a hinged arm on a grounded base: 3 links, 2 joints,
  and the base's mesh, written in metres, reads back as the
  1 x 0.5 x 0.2 box (V 0.1, A 1.6).
- body.print_face: a cylinder's flat end is accepted, its side refused.

PATHS adds the URDF writer and the print face modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

---------

Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: brett19 <brett19@gmail.com>
2026-11-02 22:53:32 +00:00

5165 lines
289 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::f64::consts::PI;
use serde_json::{Value, json};
use crate::*;
mod mesh_convert;
/// Counts the copies `Session::doc_mut` makes of a shared document.
pub(crate) mod doc_copies {
use std::cell::Cell;
thread_local! {
static COUNT: Cell<usize> = const { Cell::new(0) };
}
pub fn record() {
COUNT.with(|c| c.set(c.get() + 1));
}
/// The count since the last call.
pub fn take() -> usize {
COUNT.with(|c| c.replace(0))
}
}
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn volume(s: &mut Session) -> f64 {
let m = run(s, "inspect.measure", json!({}));
m["total"]["volume_mm3"].as_f64().unwrap()
}
fn rel(a: f64, b: f64) -> f64 {
(a - b).abs() / b.abs().max(1e-12)
}
#[test]
fn round_as_tall_as_a_disc_uses_up_its_wall() {
// #190: a disc 13 in radius and 2 high, its top edge rounded by 2.
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 13, "height": 2}));
run(&mut s, "solid.fillet", json!({"edges": [[0, 13, 2], [0, -13, 2]], "radius": "2 mm"}));
let (a, c) = ((1.0 - PI / 4.0) * 4.0, 2.0 * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)));
let expect = PI * 169.0 * 2.0 - a * 2.0 * PI * (13.0 - c);
assert!(rel(volume(&mut s), expect) < 2e-4, "{} vs {expect}", volume(&mut s));
}
/// #783: an edge pick far from every edge (beside the body, above it, inside it, or on another
/// body than the one named) is refused and adds nothing, instead of rounding the nearest edge;
/// a pick on an edge, or a little off it as a click lands, still works.
#[test]
fn edge_picks_far_from_every_edge_are_refused() {
let mut s = Session::default();
for (name, x) in [("A", 0), ("B", 40), ("C", 80), ("D", 120)] {
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0], "operation": "new", "body_name": name}));
}
run(&mut s, "solid.fillet", json!({"body": "A", "edges": [[10, 0, 10]], "radius": 1}));
run(&mut s, "solid.fillet", json!({"body": "B", "edges": [[50, 0.4, 10.3]], "radius": 1}));
let features = s.doc.features.len();
for (id, p, far) in [
("solid.fillet", json!({"body": "B", "edges": [[50, -15, 10]], "radius": 1}), "15.0"),
("solid.chamfer", json!({"body": "C", "edges": [[90, 10, 40]], "distance": 1}), "31.623 mm"),
("solid.fillet", json!({"edges": [[130, 10, 5]], "radius": 1}), "11.180 mm"),
("solid.fillet", json!({"body": "C", "edges": [[10, 20, 10]], "radius": 1}), "mm away"),
("solid.press_pull", json!({"edges": [[50, -15, 10]], "distance": 1}), "15.0"),
] {
let err = s.execute(id, &p).expect_err(&format!("{id} {p}")).to_string();
assert!(err.contains("no edge at") && err.contains(far), "{id} {p}: {err}");
}
assert_eq!(s.doc.features.len(), features);
}
#[test]
fn edge_picks_at_a_corner_are_refused() {
for (id, size) in [("solid.chamfer", "distance"), ("solid.fillet", "radius")] {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20}));
let features = s.doc.features.len();
for edge in [json!([20, 20, 20]), json!({"point": [20, 20, 20]})] {
let err = s.execute(id, &json!({"edges": [edge], size: 2})).unwrap_err().to_string();
assert!(err.contains("[20, 20, 20]") && err.contains("3 edges") && err.contains("midpoint"), "{id}: {err}");
assert_eq!(s.doc.features.len(), features);
assert!((volume(&mut s) - 8000.0).abs() < 1e-6);
}
// 1 mm from the corner along one edge: near the other two, but on just that one.
run(&mut s, id, json!({"edges": [[19, 20, 20]], size: 2}));
assert_eq!(s.doc.features.len(), features + 1);
let removed = if id == "solid.chamfer" { 40.0 } else { (4.0 - PI) * 20.0 };
assert!(rel(volume(&mut s), 8000.0 - removed) < 2e-4);
}
}
#[test]
fn fillet_as_wide_as_a_face_rounds_it_off() {
// #199: 14 x 6 x 10 box, the four vertical edges at r = 3 (half the 6 mm end faces).
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 14, "width": 6, "height": 10, "corner": [14, 0, 0]}));
run(&mut s, "solid.fillet", json!({"edges": [[14, 0, 5], [28, 0, 5], [14, 6, 5], [28, 6, 5]], "radius": "3"}));
let expect = 840.0 - (4.0 - PI) * 9.0 * 10.0;
assert!(rel(volume(&mut s), expect) < 2e-4, "{} vs {expect}", volume(&mut s));
assert!(s.execute("solid.fillet", &json!({"edges": [[21, 0, 10]], "radius": 3.5})).is_err());
}
/// The owner's ruling of 2026-10-30: two edges of a 20 mm box rounded r2 in one fillet (they
/// meet in a mitre at the corner (20, 0, 20), the upright edge there sharp), then the upright edge
/// r3 in a second fillet, whose tangent chain takes the mitre's seam with it. The corner is the
/// body rounding all three at once makes (kernel `fillet_radii` of the box with each edge's
/// radius, `three_rounds_at_a_corner`: SMLib's setback corner, 15 faces, 7928.142563938 mm³); the
/// r2 rounds keep their names, and the r3 round and the corner's patches are the second fillet's.
#[test]
fn a_later_round_at_a_mitred_corner_is_blended_with_the_rounds_there() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Box"}));
let first = run(&mut s, "solid.fillet", json!({"edges": [[20, 10, 20], [10, 0, 20]], "radius": 2}))["feature"].as_u64().unwrap();
// A point halfway along each r2 round, at 45° between its faces.
let k = 2.0 - 2.0_f64.sqrt();
let rounds = [solidcraft_geom::Vec3::new(20.0 - k, 10.0, 20.0 - k), solidcraft_geom::Vec3::new(10.0, k, 20.0 - k)];
let named = |s: &mut Session, at: solidcraft_geom::Vec3| {
let st = s.model.state();
let (d, index) = solidcraft_doc::appearance::nearest_face(st.body("Box").unwrap(), at).unwrap();
// Found on the display mesh, whose facets lie within its chord of the faces.
assert!(d < 0.05, "{at:?} is {d} off the nearest face");
let faces = run(s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default();
faces.iter().find(|f| f["index"].as_u64() == Some(index as u64)).and_then(|f| f["name"].as_str()).unwrap_or_default().to_string()
};
let before: Vec<String> = rounds.iter().map(|p| named(&mut s, *p)).collect();
assert!(before.iter().all(|n| n.starts_with(&format!("F{first}:blend:"))), "{before:?}");
let second = run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 3}))["feature"].as_u64().unwrap();
assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results);
let v = volume(&mut s);
assert!((v - 7928.142563938).abs() < 1e-6, "{v}");
let faces = run(&mut s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default();
assert_eq!(faces.len(), 15);
let after: Vec<String> = rounds.iter().map(|p| named(&mut s, *p)).collect();
assert_eq!(after, before);
// The r3 round (halfway up, at 45°) and the corner's patches: the faces the second fillet made.
let k3 = 3.0 - 4.5_f64.sqrt();
assert!(named(&mut s, solidcraft_geom::Vec3::new(20.0 - k3, k3, 10.0)).starts_with(&format!("F{second}:blend:")));
let made = faces.iter().filter(|f| f["name"].as_str().is_some_and(|n| n.starts_with(&format!("F{second}:")))).count();
// the r3 round and the corner's six patches (a setback patch per round, three in the triangle)
assert_eq!(made, 7, "{faces:?}");
}
#[test]
fn join_extrude_from_a_chamfered_top_face() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name":"height","expression":"20 mm"}));
run(&mut s, "parameters.add", json!({"name":"bevel","expression":"2 mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}));
let source = run(&mut s, "solid.extrude", json!({"distance": "height","name":"Stem"}))["feature"].as_u64().unwrap();
run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": "bevel"}));
let base = volume(&mut s);
let id = run(&mut s, "sketch.create", json!({"plane": {"face": [0, 0, 20]}}))["sketch"].as_u64().unwrap();
let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: Some(anchor), .. }, sketch } =
&s.doc.feature(id).unwrap().kind
else {
panic!("the chamfered cap retains its exact original construction support");
};
assert_eq!(anchor.target.origin_feature, source);
assert!(matches!(anchor.target.certificate, Some(solidcraft_doc::config::FaceCertificate::ExtrudeCap { high: true, .. })));
assert!(!sketch.links.is_empty());
assert!(sketch.links.iter().all(|link| link.auto_face && !link.lost));
// The default linked cap outline is radius8; no explicit fixed plane or
// duplicate manually drawn circle is required to join a pad to that face.
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"}));
assert_eq!(s.model.state().bodies.len(), 1);
assert!(rel(volume(&mut s), base + PI * 64.0 * 5.0) < 5e-4);
for (height, bevel) in [(20., 2.), (25., 3.)] {
run(&mut s, "parameters.change", json!({"name":"height","expression":format!("{height} mm")}));
run(&mut s, "parameters.change", json!({"name":"bevel","expression":format!("{bevel} mm")}));
let expected = PI * (100. * height - (10. * bevel * bevel - bevel * bevel * bevel / 3.) + (10. - bevel) * (10. - bevel) * 5.);
let loaded = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
let mut cold = Session::new(loaded);
let warm_volume = volume(&mut s);
let cold_volume = volume(&mut cold);
assert!(rel(warm_volume, expected) < 5e-4, "{warm_volume} vs {expected}");
assert!((warm_volume - cold_volume).abs() < 1e-8);
for current in [&s, &cold] {
assert!(current.model.results.iter().all(|result| result.error.is_none() && result.warning.is_none()), "{:?}", current.model.results);
let state = current.model.state();
assert_eq!(state.bodies.len(), 1);
let solved = state.sketch(id).unwrap();
assert!((solved.plane.origin.z - height).abs() < 1e-8);
assert!(solved.sketch.links.iter().all(|link| link.auto_face && !link.lost));
let body = &state.bodies[0];
assert_eq!(body.body.classify_point(solidcraft_geom::Vec3::new(0., 0., height + 4.)).unwrap(), solidcraft_kernel::PointClass::Inside);
assert_eq!(body.body.classify_point(solidcraft_geom::Vec3::new(0., 0., height + 6.)).unwrap(), solidcraft_kernel::PointClass::Outside);
assert_eq!(
body.body.classify_point(solidcraft_geom::Vec3::new(10. - bevel - 0.5, 0., height + 4.)).unwrap(),
solidcraft_kernel::PointClass::Inside
);
assert_eq!(
body.body.classify_point(solidcraft_geom::Vec3::new(10. - bevel + 0.5, 0., height + 4.)).unwrap(),
solidcraft_kernel::PointClass::Outside
);
}
}
}
#[test]
fn a_body_cut_in_pieces_twice_gets_pieces_of_their_own_names() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 5, "height": 5, "body_name": "Bar"}));
for x in [10, 25] {
run(&mut s, "solid.box", json!({"corner": [x, -1, -1], "length": 2, "width": 7, "height": 7, "body_name": "Gap"}));
run(&mut s, "solid.combine", json!({"target": "Bar", "tools": ["Gap"], "operation": "cut"}));
}
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
let unique: std::collections::BTreeSet<&String> = names.iter().collect();
assert_eq!(unique.len(), 3, "{names:?}");
assert!(names.contains(&"Bar (2)".to_string()), "{names:?}");
}
/// A join that bridges two bodies makes them one body, not an overlap of the first and the second.
#[test]
fn extrude_a_face_where_another_body_lies_flush_on_it() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 4, "body_name": "A"}));
run(&mut s, "solid.box", json!({"corner": [10, 0, 4], "length": 10, "width": 20, "height": 1, "body_name": "B"}));
// A's top and B's bottom both lie at the point: which one is meant has to be said.
let e = s.execute("solid.extrude", &json!({"face": [15, 5, 4], "distance": "2 mm", "operation": "new"})).unwrap_err().to_string();
assert!(e.contains("A") && e.contains("B") && e.contains("face_body"), "{e}");
let r = run(&mut s, "solid.extrude", json!({"face": [15, 5, 4], "face_body": "A", "distance": "2 mm", "operation": "new", "body_name": "C"}));
let m = run(&mut s, "inspect.measure", json!({"bodies": ["C"]}));
let v = m["total"]["volume_mm3"].as_f64().unwrap();
assert!((v - 20.0 * 20.0 * 2.0).abs() < 1e-6, "{v} {r}");
let e = s.execute("solid.extrude", &json!({"face": [15, 5, 4], "face_body": "Nope", "distance": "2 mm"})).unwrap_err().to_string();
assert!(e.contains("Nope"), "{e}");
}
#[test]
fn join_bridging_two_bodies_merges_them() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "new_body"}));
run(&mut s, "solid.box", json!({"length": 20, "width": 4, "height": 4, "corner": [5, 3, 3], "operation": "join"}));
let st = s.model.state();
assert_eq!(st.bodies.len(), 1, "both boxes and the bar are one body");
assert_eq!(st.bodies[0].name, "Body1");
assert_eq!(st.bodies[0].body.lumps().unwrap().len(), 1);
// 2 boxes + the bar's 10 mm outside them.
assert!(rel(volume(&mut s), 2000.0 + 10.0 * 16.0) < 1e-6);
}
/// A join touching only the second body merges into that body and leaves the first alone.
#[test]
fn join_merges_into_the_body_it_meets() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "new_body"}));
// Sits on Body2's top face: a face contact, no shared volume.
run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [23, 3, 10], "operation": "join"}));
let st = s.model.state();
assert_eq!(st.bodies.len(), 2);
let b1 = st.bodies.iter().find(|b| b.name == "Body1").unwrap();
let b2 = st.bodies.iter().find(|b| b.name == "Body2").unwrap();
assert_eq!(b1.body.face_count(), 6, "Body1 is untouched");
assert_eq!(b2.body.lumps().unwrap().len(), 1);
assert!(rel(volume(&mut s), 2064.0) < 1e-6);
}
/// A join that meets no body still joins the first body, as a separate lump, and says nothing:
/// pieces that touch nothing stay one body.
#[test]
fn join_meeting_nothing_keeps_the_first_body() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
let r = run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 0, 0], "operation": "join"}));
assert!(r.get("notice").is_none(), "{r}");
let st = s.model.state();
assert_eq!(st.bodies.len(), 1);
assert_eq!(st.bodies[0].body.lumps().unwrap().len(), 2);
assert!(rel(volume(&mut s), 1064.0) < 1e-6);
}
/// A join of a box touching the first only along an edge keeps it a body of its own and says
/// so, with the edit that makes them one body.
#[test]
fn join_touching_along_an_edge_keeps_a_separate_body() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
let r = run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [10, 10, 0], "operation": "join"}));
assert_eq!(r["notice"]["contact"], "along_edge", "{r}");
assert_eq!(r["notice"]["message"], "These bodies only touch along an edge, so they were kept as separate bodies.", "{r}");
assert_eq!(r["notice"]["action"]["params"]["set"], json!({"touching": "one_body"}), "{r}");
assert_eq!(s.model.state().bodies.len(), 2);
}
/// A 1 mm floor extruded into a through hole, from the sketch the plate was extruded from: the
/// disc's wall lies on the hole's and its foot in the plate's bottom face. A wedge extruded
/// sideways on top keeps the plate from being a prism along Z (the 2D route would take it
/// otherwise), and the join failed with "boolean Union: the operation failed: no result".
#[test]
fn join_a_floor_into_a_through_hole() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Plate"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]}));
run(&mut s, "sketch.circle.center", json!({"center": [60, 30], "radius": 20}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Plate", "profiles": [{"point": [5, 5]}], "distance": 10}));
run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Wedge"}));
run(&mut s, "sketch.line", json!({"points": [[5, -10], [25, -10], [5, -16]], "closed": true}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Wedge", "distance": 40, "operation": "join"}));
let before = volume(&mut s);
run(&mut s, "solid.extrude", json!({"sketch": "Plate", "profiles": [{"point": [60, 30]}], "distance": 1, "operation": "join"}));
let st = s.model.state();
assert_eq!(st.bodies.len(), 1);
assert_eq!(st.bodies[0].body.lumps().unwrap().len(), 1);
assert!(st.bodies[0].body.validity().is_empty(), "{:?}", st.bodies[0].body.validity());
// Exact: the disc isn't moved to get the bodies to intersect, so the feature has no warning.
let warning = s.model.results.last().and_then(|r| r.warning.clone());
assert!(warning.is_none(), "{warning:?}");
let added = volume(&mut s) - before;
assert!(rel(added, PI * 400.0) < 1e-3, "{added}");
}
/// Two spheres of one size: the join's contact test tried every pair of their finely meshed
/// triangles and refused the join as too much work (#232).
#[test]
fn join_of_two_overlapping_equal_spheres_is_not_refused() {
let mut s = Session::default();
run(&mut s, "solid.sphere", json!({"radius": 10, "center": [0, 0, 0], "body_name": "A"}));
run(&mut s, "solid.sphere", json!({"radius": 10, "center": [12, 0, 0], "body_name": "B"}));
run(&mut s, "solid.combine", json!({"target": "A", "tools": ["B"], "operation": "join"}));
assert_eq!(s.model.state().bodies.len(), 1);
// Two spheres less the lens they share: 2 * 4/3 pi r^3 - pi (4r + d) (2r - d)^2 / 12.
let (r, d) = (10.0, 12.0);
let want = 2.0 * 4.0 / 3.0 * PI * r * r * r - PI * (4.0 * r + d) * (2.0 * r - d) * (2.0 * r - d) / 12.0;
let got = volume(&mut s);
assert!(rel(got, want) < 1e-3, "{got} vs {want}");
}
/// Area two discs of radii `r1`, `r2` with centres `d` apart have in common.
fn disc_overlap(r1: f64, r2: f64, d: f64) -> f64 {
if d >= r1 + r2 {
return 0.0;
}
if d <= (r1 - r2).abs() {
return PI * r1.min(r2) * r1.min(r2);
}
let a = ((d * d + r1 * r1 - r2 * r2) / (2.0 * d * r1)).acos();
let b = ((d * d + r2 * r2 - r1 * r1) / (2.0 * d * r2)).acos();
r1 * r1 * a + r2 * r2 * b - 0.5 * ((-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2)).sqrt()
}
/// Two thick rings 11 mm apart: their walls cross, and the join was refused as too much work (#232).
#[test]
fn join_of_two_overlapping_rings_is_not_refused() {
let mut s = Session::default();
for (name, x) in [("RingA", 0.0), ("RingB", 11.0)] {
run(
&mut s,
"solid.cylinder",
json!({"diameter": 120, "height": 60, "base": [x, 0, 0], "operation": "new", "name": format!("{name}Outer"), "body_name": name}),
);
run(
&mut s,
"solid.cylinder",
json!({"diameter": 96, "height": 60, "base": [x, 0, 0], "operation": "cut", "targets": [name], "name": format!("{name}Bore")}),
);
}
run(&mut s, "solid.combine", json!({"target": "RingA", "tools": ["RingB"], "operation": "join"}));
assert_eq!(s.model.state().bodies.len(), 1);
// Union of the two rings' plan areas: both less what they share, which is the overlap of the
// two outer discs less the two bores (each inside the other's outer disc) plus the bores' own overlap.
let (outer, bore, d) = (60.0, 48.0, 11.0);
let ring = PI * (outer * outer - bore * bore);
let shared = disc_overlap(outer, outer, d) - 2.0 * disc_overlap(bore, outer, d) + disc_overlap(bore, bore, d);
let want = (2.0 * ring - shared) * 60.0;
let got = volume(&mut s);
assert!(rel(got, want) < 1e-3, "{got} vs {want}");
}
/// A disc with a lobe on its rim, patterned six times about its centre: every copy shares the
/// whole disc with the target, and joining them was refused as too much contact work (#1029).
#[test]
fn join_of_a_lobed_disc_pattern_is_not_refused() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "diameter": 15}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 7.5], "diameter": 5}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "profiles": "all", "operation": "new", "body_name": "Disc"}));
run(&mut s, "solid.pattern.circular", json!({"bodies": ["Disc"], "axis": "Z", "count": 6}));
let tools: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).filter(|n| n != "Disc").collect();
assert_eq!(tools.len(), 5);
run(&mut s, "solid.combine", json!({"target": "Disc", "tools": tools, "operation": "join"}));
assert_eq!(s.model.state().bodies.len(), 1);
// The disc plus six lobes, each less the part inside the disc; neighbouring lobes stay apart.
let (disc, lobe) = (7.5, 2.5);
let want = (PI * disc * disc + 6.0 * (PI * lobe * lobe - disc_overlap(disc, lobe, disc))) * 10.0;
let got = volume(&mut s);
assert!(rel(got, want) < 1e-3, "{got} vs {want}");
}
mod barrel_join;
mod blend_fit;
mod component_frames;
mod curved_seam_round;
mod flush_join_loft;
mod gltf_import;
mod import_component;
mod large_step_import;
mod loft_ring;
mod loft_spacing;
mod mirror_placed;
mod mirror_planes;
#[cfg(not(target_arch = "wasm32"))]
mod native_cad_import;
mod nudge_slivers;
mod path_scope;
mod pleat_join;
mod primitive_points;
mod rim_cut;
mod robustness;
mod rounded_loft_face;
mod sphere_lens;
mod spiral_join;
mod step_import_options;
mod xz_plane;
/// Plan area a round of radius `r` fills at the concave corner `x` where circles (c1, r1) and
/// (c2, r2) cross: the triangle of its contacts and the corner, less the three circular segments.
fn round_gap(c1: [f64; 2], r1: f64, c2: [f64; 2], r2: f64, x: [f64; 2], r: f64) -> f64 {
let (a, b) = (r1 + r, r2 + r);
let d = (c2[0] - c1[0]).hypot(c2[1] - c1[1]);
let u = [(c2[0] - c1[0]) / d, (c2[1] - c1[1]) / d];
let along = (a * a - b * b + d * d) / (2.0 * d);
let side = if (x[0] - c1[0]) * -u[1] + (x[1] - c1[1]) * u[0] < 0.0 { -1.0 } else { 1.0 };
let off = (a * a - along * along).sqrt() * side;
let f = [c1[0] + u[0] * along - u[1] * off, c1[1] + u[1] * along + u[0] * off];
let t1 = [c1[0] + (f[0] - c1[0]) * r1 / a, c1[1] + (f[1] - c1[1]) * r1 / a];
let t2 = [c2[0] + (f[0] - c2[0]) * r2 / b, c2[1] + (f[1] - c2[1]) * r2 / b];
let angle = |c: [f64; 2], p: [f64; 2], q: [f64; 2]| {
let (v, w) = ([p[0] - c[0], p[1] - c[1]], [q[0] - c[0], q[1] - c[1]]);
((v[0] * w[0] + v[1] * w[1]) / (v[0].hypot(v[1]) * w[0].hypot(w[1]))).clamp(-1.0, 1.0).acos()
};
let segment = |r: f64, t: f64| r * r * (t - t.sin()) / 2.0;
let triangle = ((x[0] - t1[0]) * (t2[1] - t1[1]) - (t2[0] - t1[0]) * (x[1] - t1[1])).abs() / 2.0;
triangle - segment(r1, angle(c1, t1, x)) - segment(r2, angle(c2, x, t2)) - segment(r, angle(f, t2, t1))
}
/// A profile of two overlapping arcs, extruded: the vertical edges where the two walls meet are
/// straight lines between cylinders, and their rounds end on the caps across curved edges.
#[test]
fn fillet_the_edges_between_two_overlapping_cylinders() {
let (c1, r1) = ([0.0, 0.0], 17.140595088852663);
let (c2, r2) = ([10.715766135516247, 13.378055020402751], 9.666944358807896);
let (p, q) = ([1.7728134670876865, 17.048669520256194], [16.250324167975673, 5.452243981674495]);
let profile = 1087.5018766864137;
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.arc.center_point", json!({"center": c1, "start": p, "end": q}));
run(&mut s, "sketch.arc.center_point", json!({"center": c2, "start": q, "end": p}));
let si = run(&mut s, "sketch.inspect", json!({}));
assert!(rel(si["profiles"][0]["area_mm2"].as_f64().unwrap(), profile) < 1e-9, "{si}");
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10}));
let counts = |s: &mut Session| {
let m = run(s, "inspect.measure", json!({}));
(m["total"]["faces"].as_u64(), m["total"]["edges"].as_u64(), m["total"]["vertices"].as_u64())
};
assert_eq!(counts(&mut s), (Some(4), Some(6), Some(4)));
let (gp, gq) = (round_gap(c1, r1, c2, r2, p, 6.0), round_gap(c1, r1, c2, r2, q, 6.0));
// One round: a blend face; the edge becomes two contact lines and two end arcs.
run(&mut s, "solid.fillet", json!({"edges": [[p[0], p[1], 5]], "radius": 6, "name": "Round"}));
let (v, expect) = (volume(&mut s), (profile + gp) * 10.0);
assert!(rel(v, expect) < 2e-4, "{v} vs {expect}");
assert_eq!(counts(&mut s), (Some(5), Some(9), Some(6)));
// Both corners in one fillet.
run(
&mut s,
"timeline.redefine",
json!({"feature": "Round", "command": "solid.fillet", "params": {"edges": [[p[0], p[1], 5], [q[0], q[1], 5]], "radius": 6}}),
);
let (v, expect) = (volume(&mut s), (profile + gp + gq) * 10.0);
assert!(rel(v, expect) < 2e-4, "{v} vs {expect}");
assert_eq!(counts(&mut s), (Some(6), Some(12), Some(8)));
// A larger round, whose contacts are found on the long arcs from their far ends too.
run(&mut s, "timeline.redefine", json!({"feature": "Round", "command": "solid.fillet", "params": {"edges": [[q[0], q[1], 5]], "radius": 13}}));
let (v, expect) = (volume(&mut s), (profile + round_gap(c1, r1, c2, r2, q, 13.0)) * 10.0);
assert!(rel(v, expect) < 2e-4, "{v} vs {expect}");
}
/// A bar 40 long, 16 wide and 10 tall whose far end is a half disc of radius 8 about (40, 8),
/// with a disc of radius 8 about the same centre sketched on its top (the top's outline
/// projected) and extruded 10 up, joined: the bar's sides run tangent into the cylinder.
/// V0 = 40·16·10 + π·8²·10/2 + π·8²·10.
fn peg(s: &mut Session) -> f64 {
run(s, "sketch.create", json!({"plane": "XY", "name": "Peg"}));
run(s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
run(s, "sketch.arc.center_point", json!({"center": [40, 8], "start": [40, 0], "end": [40, 16]}));
run(s, "sketch.line", json!({"points": [[40, 16], [0, 16]]}));
run(s, "sketch.line", json!({"points": [[0, 16], [0, 0]]}));
run(s, "sketch.finish", json!({}));
run(s, "solid.extrude", json!({"sketch": "Peg", "distance": 10, "body_name": "Peg"}));
run(s, "sketch.create", json!({"plane": {"origin": [0, 0, 10], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Top"}));
run(s, "sketch.project", json!({"refs": [{"face": [2, 8, 10]}]}));
run(s, "sketch.circle.center", json!({"center": [40, 8], "radius": 8}));
run(s, "sketch.finish", json!({}));
run(
s,
"solid.extrude",
json!({"sketch": "Top", "distance": 10, "operation": "join", "targets": ["Peg"], "profiles": [{"point": [40, 8]}], "exact_regions": true}),
);
6400.0 + 960.0 * PI
}
/// Simpson's rule over [a, b] with `n` (even) intervals.
fn simpson(f: impl Fn(f64) -> f64, a: f64, b: f64, n: usize) -> f64 {
let h = (b - a) / n as f64;
let inner: f64 = (1..n).map(|i| if i % 2 == 1 { 4.0 } else { 2.0 } * f(a + h * i as f64)).sum();
(f(a) + f(b) + inner) * h / 3.0
}
/// The material an r2 round of the peg's front top edge (y = 0, z = 10) takes off: the spandrel
/// (height 2 - sqrt(4 - (2 - y)²) above the round at y) from x = `from` to where the cylinder's
/// wall, x = 40 - sqrt(64 - (8 - y)²), takes over (the round runs into the wall there).
fn peg_front_round(from: f64) -> f64 {
let spandrel = |y: f64| 2.0 - (4.0 - (2.0 - y) * (2.0 - y)).max(0.0).sqrt();
let wall = |y: f64| 40.0 - (64.0 - (8.0 - y) * (8.0 - y)).max(0.0).sqrt();
simpson(|y| spandrel(y) * (wall(y) - from), 0.0, 2.0, 20_000)
}
/// The peg's front top edge rounded r2: SMLib's result holds the upper half of the cylinder's
/// wall as a rational spline whose parameter range runs more than a turn round, past the face's
/// trims (half a turn). Taken as a cylinder over the spline's range (past 360°) SMLib refused it
/// on the way back (SM_ERR_INVALID_INPUT), so the round seemed to build and the body could not
/// be measured or changed. It goes back as the cylinder over the face's own range: the body
/// measures, a round of the three edges at the bar's other top corner builds on it, and that
/// wall comes back from SMLib a cylinder of radius 8.
#[test]
fn rounds_on_a_bar_running_tangent_into_a_cylinder() {
let mut s = Session::default();
let v0 = peg(&mut s);
run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2}));
let (v, expect) = (volume(&mut s), v0 - peg_front_round(0.0));
assert!(rel(v, expect) < 1e-7, "{v} vs {expect}");
// The vertical edge, the left top edge and the round's end arc on the left face: each
// spandrel (1 - π/4)·r² along the edge outside the corner cube of side 2, the cube less the
// rolling ball's eighth, 8 - 4π/3.
run(&mut s, "solid.fillet", json!({"edges": [[0, 0, 4], [0, 9, 10], [0, 0.5858, 9.4142]], "radius": 2}));
let strip = (1.0 - PI / 4.0) * 4.0;
let expect = v0 - peg_front_round(2.0) - strip * (8.0 + 14.0) - (8.0 - 4.0 * PI / 3.0);
let v = volume(&mut s);
assert!(rel(v, expect) < 1e-7, "{v} vs {expect}");
for b in &s.model.state().bodies {
let bad = b.body.validity();
assert!(bad.is_empty(), "{}: {bad:?}", b.name);
}
// The wall's upper half (x < 40, z in [10, 20], round (40, 8)): every face on the surface
// through (32, 8, 15) is a cylinder of radius 8.
let state = s.model.state();
let rec = state.bodies[0].body.record();
let p0 = solidcraft_geom::Vec3::new(32.0, 8.0, 15.0);
let on: Vec<&solidcraft_geom::brep::Surface> = rec
.faces
.iter()
.map(|f| &f.surface)
.filter(|s| {
let e = solidcraft_geom::brep::eval::SurfaceEval::new(s).ok();
e.and_then(|e| e.project(p0, None, 1e-6).and_then(|uv| e.point(uv))).is_some_and(|q| q.dist(p0) < 1e-6)
})
.collect();
let kinds: Vec<String> = on.iter().map(|s| format!("{s:?}").chars().take(48).collect()).collect();
assert!(
!on.is_empty() && on.iter().all(|s| matches!(s, solidcraft_geom::brep::Surface::Cylinder { radius, .. } if (radius - 8.0).abs() < 1e-9)),
"{kinds:?}"
);
}
/// After the peg's front top round, the edge where that round runs into the cylinder's wall: its
/// faces are tangent at its lower end (40, 0, 8), where the round's contact with the front face
/// meets the wall's tangent line with it, and meet at a crease everywhere else. It is no smooth
/// edge (it was refused as one, judged at that end alone); the wall's seam with the front face,
/// tangent all along, still is.
#[test]
fn an_edge_tangent_at_one_end_only_is_not_smooth() {
let mut s = Session::default();
peg(&mut s);
run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2}));
let fillet = |s: &mut Session, at: [f64; 3]| s.execute("solid.fillet", &json!({"edges": [at], "radius": 1, "tangent_chain": false}));
if let Err(e) = fillet(&mut s, [37.2641, 0.4827, 9.3025]) {
assert!(!e.to_string().contains("is smooth"), "{e}");
}
let seam = fillet(&mut s, [40.0, 0.0, 4.0]).unwrap_err().to_string();
assert!(seam.contains("is smooth: its faces meet tangentially"), "{seam}");
}
/// The top outline of two overlapping cylinders whose concave edges were rounded: the walls of
/// the rounds meet the cylinders along the rolling-ball contact lines, straight but not lines.
#[test]
fn fillet_and_chamfer_the_top_loop_of_rounded_overlapping_cylinders() {
use std::f64::consts::{PI, TAU};
let (big, round, h) = (25.0_f64, 5.0_f64, 10.0);
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": big}));
run(&mut s, "sketch.circle.center", json!({"center": [-big, 0], "radius": big}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": h, "profiles": [0, 1, 2]}));
// Plan view: ball centres at x = −12.5, |y| = yb; each round's arc turns by th, each big arc by
// TAU − 2·a1, and the loop turns by TAU in all.
let half = big / 2.0;
let yb = ((big + round).powi(2) - half * half).sqrt();
run(&mut s, "solid.fillet", json!({"edges": [[-half, half * 3f64.sqrt(), 5], [-half, -half * 3f64.sqrt(), 5]], "radius": round}));
let (a1, th) = (yb.atan2(half), 2.0 * (half / (big + round)).asin());
let base = volume(&mut s);
let top = [[big, 0.0, h], [-2.0 * big, 0.0, h], [-half, yb - round, h], [-half, round - yb, h]];
// Removed volume by Pappus: the corner's section swept along the loop at its centroid's offset.
let removed = |area: f64, xb: f64| area * (2.0 * (TAU - 2.0 * a1) * (big - xb) + 2.0 * th * (round + xb));
run(&mut s, "solid.fillet", json!({"edges": top, "radius": 2}));
let r: f64 = 2.0;
let expect = base - removed(r * r * (1.0 - PI / 4.0), (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)) * r);
let v = volume(&mut s);
assert!((v - expect).abs() < 1.5, "{v} vs {expect}");
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["bodies"][0]["kernel"]["faces"].as_u64(), Some(10), "{m}");
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.chamfer", json!({"edges": top, "distance": 2}));
let expect = base - removed(2.0, 2.0 / 3.0);
let v = volume(&mut s);
assert!((v - expect).abs() < 1.5, "{v} vs {expect}");
}
/// Sketch a 40 x 30 rectangle with dimensions, extrude 20, fillet a vertical edge, cut a hole.
#[test]
fn box_fillet_cut_part() {
let mut s = Session::default();
run(&mut s, "parameters.change", json!({"name": "width", "expression": "40 mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [38, 29]}));
let l: Vec<String> = r["curves"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
let corner = s.doc.sketch(s.active_sketch.unwrap()).unwrap().curves[0].clone();
let start = match corner.kind {
solidcraft_sketch::CurveKind::Line { a, .. } => s.doc.sketch(s.active_sketch.unwrap()).unwrap().points[a].id.clone(),
_ => panic!(),
};
run(&mut s, "sketch.constraint.coincident", json!({"a": start, "b": "origin"}));
run(&mut s, "sketch.dimension", json!({"entities": [l[0]], "value": "width"}));
run(&mut s, "sketch.dimension", json!({"entities": [l[1]], "value": 30}));
let si = run(&mut s, "sketch.inspect", json!({}));
assert_eq!(si["dof"], 0, "{si}");
assert_eq!(si["profiles"].as_array().unwrap().len(), 1);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 20}));
assert!(rel(volume(&mut s), 24000.0) < 1e-9);
run(&mut s, "solid.fillet", json!({"edges": [[0, 0, 10]], "radius": 3}));
let filleted = 24000.0 - (9.0 - PI * 9.0 / 4.0) * 20.0;
assert!(rel(volume(&mut s), filleted) < 2e-4);
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [20, 15], "radius": 5}));
run(&mut s, "solid.extrude", json!({"distance": 20, "operation": "cut"}));
let expect = filleted - PI * 25.0 * 20.0;
let v = volume(&mut s);
assert!(rel(v, expect) < 5e-4, "{v} vs {expect}");
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["bodies"][0]["faces"], 8, "{m}");
// Parameter edit re-evaluates the timeline from the sketch.
let r = run(&mut s, "parameters.change", json!({"name": "width", "expression": "50"}));
assert_eq!(r["errors"].as_array().unwrap().len(), 0, "{r}");
let expect2 = 30000.0 - (9.0 - PI * 9.0 / 4.0) * 20.0 - PI * 25.0 * 20.0;
assert!(rel(volume(&mut s), expect2) < 5e-4);
// Undo the parameter change, redo it.
run(&mut s, "edit.undo", json!({}));
assert!(rel(volume(&mut s), expect) < 5e-4);
run(&mut s, "edit.redo", json!({}));
assert!(rel(volume(&mut s), expect2) < 5e-4);
// Export STL and STEP.
let dir = std::env::temp_dir().join(format!("solidcraft-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let stl = dir.join("part.stl");
run(&mut s, "file.export", json!({"path": stl.to_string_lossy()}));
assert!(std::fs::metadata(&stl).unwrap().len() > 1000);
let step = dir.join("part.step");
run(&mut s, "file.export", json!({"path": step.to_string_lossy()}));
assert!(std::fs::read_to_string(&step).unwrap().contains("ISO-10303-21"));
let design = dir.join("part.solidcraft");
run(&mut s, "file.save_as", json!({"path": design.to_string_lossy()}));
let mut s2 = Session::default();
run(&mut s2, "doc.open", json!({"path": design.to_string_lossy()}));
assert!(rel(volume(&mut s2), expect2) < 5e-4);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn revolve_and_primitives() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XZ"}));
run(&mut s, "sketch.line", json!({"points": [[10, 0], [15, 0], [15, 5], [10, 5]], "closed": true}));
run(&mut s, "solid.revolve", json!({"axis": "y"}));
assert!(rel(volume(&mut s), PI * 125.0 * 5.0) < 5e-4);
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0]}));
run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 20, "base": [35, 5, -5]}));
run(&mut s, "solid.combine", json!({"target": "Body2", "tools": ["Body3"], "operation": "cut"}));
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["body_count"], 2, "{m}");
assert!(rel(m["bodies"][1]["volume_mm3"].as_f64().unwrap(), 1000.0 - PI * 4.0 * 10.0) < 5e-4);
run(&mut s, "solid.chamfer", json!({"edges": [[30, 5, 10]], "distance": 1}));
run(&mut s, "timeline.rollback", json!({"position": 3}));
assert_eq!(run(&mut s, "inspect.measure", json!({}))["body_count"], 2);
run(&mut s, "timeline.rollback", json!({}));
run(&mut s, "timeline.edit", json!({"feature": "Revolve1", "set": {"angle": "180 deg"}}));
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Body1"]}));
assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), PI * 125.0 * 5.0 / 2.0) < 5e-4);
}
/// #726: a revolve swept each profile edge into two or three patches and left the planar ones
/// apart, so a pick on such a face took part of it, and a sketch or an extrude there was refused
/// ("the selected planar face no longer exists") until a later feature merged them.
#[test]
fn revolved_planar_faces_come_out_whole() {
for angle in [360, 240] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XZ"}));
run(&mut s, "sketch.line", json!({"points": [[8, 0], [30, 0], [30, -6], [18, -6], [18, -22], [8, -22]], "closed": true}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.revolve", json!({"axis": "Z", "angle": angle}));
// Picks at 170°, in the last patch, which 240° covers whichever way it turns.
let at = |r: f64, z: f64| json!([r * 170f64.to_radians().cos(), r * 170f64.to_radians().sin(), z]);
// The flange's top annulus (z = 6, r 18…30), well inside it.
let sk = run(&mut s, "sketch.create", json!({"plane": {"face": at(24.0, 6.0)}}));
assert_eq!(sk["attachment"], "exact_face", "{angle}°: {sk}");
run(&mut s, "sketch.finish", json!({}));
// The bottom annulus (z = 0, r 8…30).
let v = volume(&mut s);
run(&mut s, "solid.extrude", json!({"face": at(20.0, 0.0), "distance": 2, "operation": "join"}));
assert!(volume(&mut s) > v + 1.0, "{angle}°: the extrude added nothing");
}
}
/// A spherical shell (a half ring between two arcs, both radial lines on the axis) revolved on a
/// sketch plane that does not pass through the origin: the body is the shell, as it is on XY.
/// Before, built in place, it measured a third too large (truck tessellates the degenerate faces
/// on the axis reliably only with the axis through the origin).
#[test]
fn revolve_a_spherical_shell_off_the_origin() {
for (plane, z) in [(json!("XY"), 0.0), (json!({"origin": [0, 0, 10], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}), 10.0)] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": plane, "name": "Ring"}));
run(&mut s, "sketch.line", json!({"points": [[-40, 0], [40, 0]]}));
run(&mut s, "sketch.arc.center_point", json!({"center": [0, 0], "start": [40, 0], "end": [-40, 0]}));
run(&mut s, "sketch.arc.center_point", json!({"center": [0, 0], "start": [18.5, 0], "end": [-18.5, 0]}));
run(&mut s, "sketch.finish", json!({}));
// The half ring: the larger of the two regions above the axis.
let si = run(&mut s, "sketch.inspect", json!({"sketch": "Ring"}));
let ring = si["profiles"]
.as_array()
.unwrap()
.iter()
.max_by(|a, b| a["area_mm2"].as_f64().unwrap().total_cmp(&b["area_mm2"].as_f64().unwrap()))
.unwrap()["index"]
.clone();
run(&mut s, "solid.revolve", json!({"sketch": "Ring", "profiles": [ring], "axis": "l1", "body_name": "Shell"}));
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Shell"]}));
let want = 4.0 / 3.0 * PI * (40.0f64.powi(3) - 18.5f64.powi(3));
let v = m["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(v, want) < 5e-4, "plane at z {z}: {v} vs {want}");
let b = &m["bodies"][0]["bbox"];
assert!((b["min"][2].as_f64().unwrap() - (z - 40.0)).abs() < 1e-6 && (b["max"][2].as_f64().unwrap() - (z + 40.0)).abs() < 1e-6, "{b}");
}
}
#[test]
fn extrude_of_adjacent_profiles_has_whole_edges() {
// A holder from two regions of one sketch (a disc and the ring around it, both cut off by a
// chord): the chord used to stay split where the inner circle met it, leaving vertices right
// on the surface of a handle of that radius, and cutting the handle out of the holder failed.
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Holder"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 40}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 35}));
let x = (40.0f64 * 40.0 - 33.0 * 33.0).sqrt();
run(&mut s, "sketch.line", json!({"points": [[-x, -33], [x, -33]]}));
run(&mut s, "sketch.finish", json!({}));
let si = run(&mut s, "sketch.inspect", json!({"sketch": "Holder"}));
let below: Vec<Value> = si["profiles"]
.as_array()
.unwrap()
.iter()
.filter(|p| (500.0..4900.0).contains(&p["area_mm2"].as_f64().unwrap()))
.map(|p| p["index"].clone())
.collect();
assert_eq!(below.len(), 2, "{si}");
run(&mut s, "solid.extrude", json!({"sketch": "Holder", "profiles": below, "distance": 23, "body_name": "Holder"}));
let topo = run(&mut s, "model.faces", json!({"body": "Holder"}));
// The arc side (one face: SMLib keeps a cylinder's arc of more than half a turn whole), the
// chord's flat side and the two ends.
assert_eq!(topo["faces"].as_array().unwrap().len(), 4, "a cut-off cylinder: {topo}");
let lo = run(&mut s, "inspect.measure", json!({"bodies": ["Holder"]}))["bodies"][0]["bbox"]["min"][1].as_f64().unwrap();
run(&mut s, "solid.move", json!({"bodies": ["Holder"], "translate": [0, -5.0 - lo, 0]}));
// The handle: r35 on the Y axis with a bevelled end.
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Handle"}));
for pts in [
[[0.0, 0.0], [0.0, 230.0]],
[[0.0, 0.0], [25.0, 0.0]],
[[25.0, 0.0], [35.0, 11.5]],
[[35.0, 11.5], [35.0, 230.0]],
[[35.0, 230.0], [0.0, 230.0]],
] {
run(&mut s, "sketch.line", json!({ "points": pts }));
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.revolve", json!({"sketch": "Handle", "profiles": [0], "axis": "Y", "body_name": "Handle"}));
let before = run(&mut s, "inspect.measure", json!({"bodies": ["Holder"]}))["total"]["volume_mm3"].as_f64().unwrap();
run(&mut s, "solid.combine", json!({"target": "Holder", "tools": ["Handle"], "operation": "cut", "keep_tools": true}));
let after = run(&mut s, "inspect.measure", json!({"bodies": ["Holder"]}))["total"]["volume_mm3"].as_f64().unwrap();
assert!(after > 1000.0 && after < before * 0.5, "{before} -> {after}");
}
#[test]
fn sketch_tools_and_constraints() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "YZ"}));
run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [10, 5]}));
run(&mut s, "sketch.rectangle.three_point", json!({"p0": [20, 0], "p1": [30, 5], "p2": [28, 10]}));
run(&mut s, "sketch.circle.two_point", json!({"p0": [40, 0], "p1": [44, 0]}));
run(&mut s, "sketch.circle.three_point", json!({"p0": [50, 0], "p1": [52, 2], "p2": [54, 0]}));
run(&mut s, "sketch.arc.three_point", json!({"start": [60, 0], "end": [64, 0], "through": [62, 2]}));
run(&mut s, "sketch.arc.center_point", json!({"center": [70, 0], "start": [72, 0], "end": [70, 2]}));
run(&mut s, "sketch.polygon.inscribed", json!({"center": [80, 0], "radius": 3, "sides": 6}));
run(&mut s, "sketch.polygon.circumscribed", json!({"center": [90, 0], "radius": 3, "sides": 5}));
run(&mut s, "sketch.polygon.edge", json!({"p0": [100, 0], "p1": [103, 0], "sides": 4}));
run(&mut s, "sketch.slot.center_to_center", json!({"p0": [110, 0], "p1": [120, 0], "width": 4}));
run(&mut s, "sketch.slot.overall", json!({"p0": [130, 0], "p1": [140, 0], "width": 4}));
run(&mut s, "sketch.point", json!({"point": [150, 0]}));
let r = run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 21], [20, 30]], "ids": ["m1", "m2"]}));
assert_eq!(r["curves"], json!(["m1", "m2"]));
run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "m1"}));
run(&mut s, "sketch.constraint.perpendicular", json!({"a": "m1", "b": "m2"}));
let _ = s.execute("sketch.dimension", &json!({"entities": ["m1", "m2"], "type": "angle", "value": "90 deg"}));
let si = run(&mut s, "sketch.inspect", json!({}));
assert_eq!(si["status"], "solved", "{}", si["failing"]);
// Over-constraining is rejected and leaves the sketch unchanged.
let before = s.doc.clone();
assert!(s.execute("sketch.constraint.parallel", &json!({"a": "m1", "b": "m2"})).is_err());
assert_eq!(*s.doc, *before);
// Profiles: rectangles, circles, closed arcs/polygons/slots.
let n = si["profiles"].as_array().unwrap().len();
assert!(n >= 8, "{n} profiles");
run(&mut s, "sketch.construction", json!({"curves": ["m1"]}));
run(&mut s, "sketch.delete", json!({"entities": ["m2"]}));
run(&mut s, "sketch.constraint.fix", json!({"entity": "m1"}));
run(&mut s, "sketch.move_point", json!({"point": "m1.end", "to": [15, 20]}));
run(&mut s, "sketch.finish", json!({}));
assert!(s.execute("sketch.line", &json!({"points": [[0, 0], [1, 1]]})).is_err(), "needs an active sketch");
}
/// The recipe format of the 01-box reference drives the same commands.
#[test]
fn script_runs_commands() {
let mut s = Session::default();
let script = json!({"commands": [
{"command": "sketch.create", "params": {"plane": "XY"}},
{"command": "sketch.line", "params": {"points": [[0, 0], [40, 0], [40, 30], [0, 30]], "closed": true, "ids": ["l1", "l2", "l3", "l4"]}},
{"command": "solid.extrude", "params": {"distance": 20, "profiles": [{"loops": [{"outer": true, "curves": ["l1", "l2", "l3", "l4"]}]}], "body_name": "Box"}},
]});
let out = s.run_script(&script).unwrap();
assert_eq!(out.len(), 3);
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["bodies"][0]["name"], "Box");
assert_eq!((m["total"]["faces"].as_u64(), m["total"]["edges"].as_u64(), m["total"]["vertices"].as_u64()), (Some(6), Some(12), Some(8)));
assert!(s.run_script(&json!([{"command": "Nope"}])).is_err());
}
pub(crate) fn hostile_values() -> Vec<Value> {
vec![
Value::Null,
json!(true),
json!(-1),
json!(0),
json!(1e308),
json!(-1e308),
json!(""),
json!("nope"),
json!("1/0"),
json!("((((((((((1"),
json!("w = 20"),
json!("w ="),
json!("= 20"),
json!("mm = 5"),
json!("w = w"),
json!("w == 1/0"),
// Every value input reads `name = expression` (#4071).
json!("a = = 3"),
json!("é = 1e308 * 10"),
json!(format!("{} = 1", "n".repeat(5000))),
json!([]),
json!([1e308, -1e308]),
json!([0, 0, 0]),
json!([[0, 0], [0, 0]]),
json!(["origin", "origin"]),
json!({}),
json!({"x": 1}),
json!([{"point": [0, 0]}]),
json!([{"body": "Body1", "index": 999999}]),
]
}
/// A copy of `s` as it stands: its design and model (sharing their bodies, as undo does), its
/// undo and redo, its open sketch and the design it was entered from, and its log.
fn copy_with_history(s: &Session) -> Session {
Session { undo: s.undo.clone(), redo: s.redo.clone(), sketch_entry: s.sketch_entry.clone(), log: s.log.clone(), ..s.scratch() }
}
/// The hostile-parameter test's copy starts where a session built afresh stands: cancelling its
/// sketch and undoing step for step give the same designs, and the copied session is untouched.
#[test]
fn a_copy_with_history_undoes_like_the_session_it_copies() {
let start = |s: &mut Session| {
run(s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(s, "sketch.create", json!({"plane": "XY"}));
run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [5, 5]}));
};
let mut fresh = Session::default();
start(&mut fresh);
let mut original = Session::default();
start(&mut original);
let before = original.doc.clone();
let mut copy = copy_with_history(&original);
for (command, params) in [("sketch.cancel", json!({})), ("edit.undo", json!({})), ("edit.undo", json!({})), ("edit.redo", json!({}))] {
run(&mut fresh, command, params.clone());
run(&mut copy, command, params);
assert_eq!(*fresh.doc, *copy.doc, "{command}");
assert_eq!(fresh.active_sketch, copy.active_sketch, "{command}");
}
assert!(std::sync::Arc::ptr_eq(&original.doc, &before) && original.active_sketch.is_some(), "the copied session is untouched");
}
/// Every command, every parameter name it documents, every hostile value: no panic escapes and
/// no command panics internally.
#[test]
fn hostile_params_never_panic() {
let keys = [
"plane",
"offset",
"name",
"sketch",
"points",
"closed",
"construction",
"ids",
"infer",
"p0",
"p1",
"p2",
"center",
"corner",
"radius",
"diameter",
"start",
"end",
"through",
"sides",
"angle",
"width",
"point",
"id",
"entities",
"type",
"value",
"line",
"mode",
"a",
"b",
"entity",
"fixed",
"curves",
"to",
"distance",
"profiles",
"direction",
"distance2",
"start_offset",
"operation",
"targets",
"body_name",
"axis",
"length",
"height",
"base",
"major",
"minor",
"top_radius",
"top_diameter",
"edges",
"body",
"target",
"tools",
"keep_tools",
"bodies",
"translate",
"expression",
"unit",
"comment",
"delete",
"features",
"feature",
"position",
"suppressed",
"set",
"items",
"add",
"path",
"format",
"ascii",
"measure",
"refs",
"link",
"project_edges",
"mid",
"near",
"factor",
"copy",
"count",
"spacing",
"count2",
"spacing2",
"dir",
"side",
"chain",
"at",
"curve",
"minor_radius",
"apex",
"rho",
"text",
"lines",
"driven",
"from",
"datum",
"tolerance",
"face",
"new_name",
"favorite",
"favorites",
"filter",
"kind",
"prefix",
"orientation",
"seam",
"twist",
"scale",
"continuity",
"crown",
"faces",
"u",
"v",
"keep",
"with",
"keep_with",
"stitch",
"extend",
"profile",
"anchor",
"density",
"names",
"references",
];
// Commands are independent; worker threads take them one at a time (their costs vary a lot).
let ids: Vec<&str> = command_specs()
.iter()
.map(|spec| spec.id)
.filter(|id| !matches!(*id, "doc.open" | "file.save" | "file.save_as" | "file.export" | "file.save_mesh" | "sketch.export_dxf")) // file system side effects are covered by their own tests
.collect();
let next = std::sync::atomic::AtomicUsize::new(0);
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
let internal: Vec<String> = std::thread::scope(|scope| {
let workers: Vec<_> = (0..threads)
.map(|_| {
scope.spawn(|| {
let mut internal = Vec::new();
while let Some(&id) = ids.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) {
// A model with a sketch, a body and an active sketch, so most commands get far.
// Built once per command and copied for each call: SMLib serialises every
// call behind one lock, so building the box for each of the ~3000 calls
// ran one after another on every thread (over half an hour in CI).
let mut start = Session::default();
let _ = start.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10}));
let _ = start.execute("sketch.create", &json!({"plane": "XY"}));
let _ = start.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]}));
for v in hostile_values() {
for k in keys {
if k == "path"
&& (id.starts_with("parameters.")
|| id == "timeline.export_script"
|| matches!(
id,
"file.export_3mf" | "file.export_obj" | "file.export_step" | "file.export_stl" | "file.export_urdf"
))
{
continue; // parameter, script and export files: covered by their own tests (no stray files)
}
let mut s = copy_with_history(&start);
let p = json!({ k: v.clone() });
if let Err(EngineError::Internal(id, msg)) = s.execute(id, &p) {
internal.push(format!("{id} {p}: {msg}"));
}
// Whole-value hostility too.
if let Err(EngineError::Internal(id, msg)) = s.execute(id, &v) {
internal.push(format!("{id} {v}: {msg}"));
}
}
}
}
internal
})
})
.collect();
workers.into_iter().flat_map(|w| w.join().unwrap()).collect()
});
assert!(internal.is_empty(), "commands panicked:\n{}", internal.join("\n"));
}
/// #6651: a list parameter of the wrong type is refused, not read as an empty list. An empty
/// list means "every body" to most commands, so a number, an object or a list with a number in
/// it was read as no list at all: a cut meant for one body cut every body it touched, and the
/// command reported success.
///
/// `null` is not in this list: the schema contract declares these parameters optional and
/// reads `null` as absent, so it keeps the meaning it always had (no list given).
#[test]
fn a_list_parameter_of_the_wrong_type_is_refused() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"corner": [0, 0, 0], "length": 40, "width": 30, "height": 10, "body_name": "Plate"}));
run(&mut s, "solid.box", json!({"corner": [60, 0, 0], "length": 10, "width": 10, "height": 20, "body_name": "Block"}));
let before = volume(&mut s);
// A tool crossing both bodies, meant for the Block only.
for targets in [json!(7), json!(true), json!({"body": "Block"}), json!(["Block", 42])] {
let params =
json!({"corner": [35, 2, -1], "length": 30, "width": 3, "height": 30, "operation": "cut", "body_name": "Slot", "targets": targets});
let err = s.execute("solid.box", &params).expect_err("a list parameter of the wrong type is refused");
let EngineError::BadParams { cmd, msg } = &err else {
panic!("{params}: {err}");
};
assert_eq!(cmd, "solid.box", "{params}: {err}");
assert!(msg.contains("targets"), "{params}: {err}");
assert_eq!(volume(&mut s), before, "{params}: the design changed");
}
}
#[test]
fn registry_is_consistent() {
let specs = command_specs();
let mut ids: Vec<&str> = specs.iter().map(|c| c.id).collect();
ids.sort();
let n = ids.len();
ids.dedup();
assert_eq!(ids.len(), n, "duplicate command ids");
assert_eq!(find_command("Solid.Extrude").map(|c| c.id), Some("solid.extrude"), "case-insensitive lookup");
let s = Session::default();
assert!(!find_command("sketch.line").unwrap().info(&s).enabled);
}
/// Only SolidCraft's own dotted ids name commands; other ids are unknown commands.
#[test]
fn only_own_ids_name_commands() {
for old in ["Extrude", "SketchCreate", "FusionFilletEdgesCommand"] {
assert!(find_command(old).is_none(), "{old}");
let mut s = Session::default();
let err = s.execute(old, &serde_json::json!({})).unwrap_err();
assert!(matches!(err, crate::EngineError::UnknownCommand(_)), "{old}: {err}");
}
}
/// An unknown command's error names the ids it was probably meant to be: a typo's, or the
/// command that ends in the same word.
#[test]
fn unknown_commands_suggest_the_closest_ids() {
let mut s = Session::default();
let mut msg = |id: &str| s.execute(id, &serde_json::json!({})).unwrap_err().to_string();
assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open`?)");
assert!(msg("solid.extrud").starts_with("unknown command `solid.extrud` (did you mean `solid.extrude`"), "{}", msg("solid.extrud"));
assert!(msg("Extrude").contains("`solid.extrude`"), "{}", msg("Extrude"));
assert_eq!(msg("FusionFilletEdgesCommand"), "unknown command `FusionFilletEdgesCommand`");
let long = "x".repeat(10_000);
assert_eq!(msg(&long), format!("unknown command `{long}`"));
}
#[test]
fn sample_design_builds() {
let mut s = Session::default();
s.run_script(&crate::sample::script()).unwrap();
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["body_count"], 1, "{m}");
let plate = 80.0 * 50.0 * 8.0 - 4.0 * (36.0 - PI * 9.0) * 8.0 - 2.0 * PI * 16.0 * 8.0;
let boss = PI * 144.0 * 14.0;
let bore = PI * 36.0 * 22.0;
let v = m["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(v, plate + boss - bore) < 1e-3, "{v} vs {}", plate + boss - bore);
}
fn silhouette_box(s: &mut Session, name: &str, x0: f64, x1: f64, z: f64) {
let sketch = format!("{name}Sketch");
run(s, "sketch.create", json!({"plane": "XY", "name": sketch}));
run(s, "sketch.rectangle.two_point", json!({"p0": [x0, 0], "p1": [x1, 10]}));
run(s, "sketch.finish", json!({}));
run(s, "solid.extrude", json!({"sketch": sketch, "distance": z, "operation": "new_body", "body_name": name}));
}
fn silhouette_pixels(v: &Value) -> usize {
v["mask"]
.as_array()
.unwrap()
.iter()
.map(|row| row.as_array().unwrap().iter().map(|span| (span[1].as_u64().unwrap() - span[0].as_u64().unwrap()) as usize).sum::<usize>())
.sum()
}
#[test]
fn silhouette_box_standard_views_and_full_mask() {
let mut s = Session::default();
silhouette_box(&mut s, "Box", 0.0, 20.0, 30.0);
let front = run(&mut s, "inspect.silhouette", json!({"rows": 60}));
assert_eq!(front["box_mm"], json!([[0.0, 0.0], [20.0, 30.0]]));
assert_eq!(front["mm_per_px"], 0.5);
assert_eq!((front["width"].as_u64(), front["height"].as_u64()), (Some(40), Some(60)));
assert_eq!(silhouette_pixels(&front), 2400);
assert_eq!(front["bodies"], 1);
let right = run(&mut s, "inspect.silhouette", json!({"view": "right", "rows": 60}));
assert_eq!(right["box_mm"], json!([[0.0, 0.0], [10.0, 30.0]]));
assert_eq!((right["width"].as_u64(), right["height"].as_u64()), (Some(20), Some(60)));
let top = run(&mut s, "inspect.silhouette", json!({"view": "top", "rows": 60}));
assert_eq!(top["box_mm"], json!([[0.0, 0.0], [20.0, 10.0]]));
assert_eq!((top["width"].as_u64(), top["height"].as_u64()), (Some(120), Some(60)));
}
#[test]
fn silhouette_front_and_back_mirror_tall_body() {
let mut s = Session::default();
silhouette_box(&mut s, "Tall", 0.0, 10.0, 30.0);
silhouette_box(&mut s, "Short", 30.0, 40.0, 10.0);
let front = run(&mut s, "inspect.silhouette", json!({"view": "front", "rows": 60}));
let back = run(&mut s, "inspect.silhouette", json!({"view": "back", "rows": 60}));
assert_eq!(front["mask"][0], json!([[0, 20]]));
assert_eq!(back["mask"][0], json!([[60, 80]]));
assert_eq!(front["right"], json!([1.0, 0.0, 0.0]));
assert_eq!(back["right"], json!([-1.0, 0.0, 0.0]));
}
#[test]
fn silhouette_visibility_selection_and_bad_input() {
let mut s = Session::default();
silhouette_box(&mut s, "Shown", 0.0, 20.0, 30.0);
silhouette_box(&mut s, "Hidden", 40.0, 50.0, 10.0);
run(&mut s, "browser.visibility", json!({"items": ["Hidden"], "visible": false}));
assert_eq!(run(&mut s, "inspect.silhouette", json!({}))["bodies"], 1);
let named = run(&mut s, "inspect.silhouette", json!({"bodies": ["Hidden"]}));
assert_eq!(named["bodies"], 1);
assert_eq!(named["box_mm"], json!([[40.0, 0.0], [50.0, 10.0]]));
assert!(s.execute("inspect.silhouette", &json!({"bodies": ["Unknown"]})).unwrap_err().to_string().contains("Unknown"));
assert!(s.execute("inspect.silhouette", &json!({"view": "front", "camera": {}})).is_err());
assert!(s.execute("inspect.silhouette", &json!({"camera": {"target": [0,0,0], "yaw": 0, "pitch": 0, "distance": 0}})).is_err());
}
#[test]
fn silhouette_perspective_scales_the_near_face_and_refuses_bodies_behind_the_eye() {
let mut s = Session::default();
silhouette_box(&mut s, "Box", 0.0, 20.0, 30.0);
// Looking along +Y at the box's centre from 100 mm: the near face (Y 0) is 95 mm from the
// eye, so it is drawn 100/95 times its size on the plane through the target.
let camera = json!({"target": [10, 5, 15], "yaw": 0, "pitch": 0, "distance": 100, "fov": 0.6});
let perspective = run(&mut s, "inspect.silhouette", json!({"camera": camera, "rows": 60}));
assert_eq!(perspective["projection"], "perspective");
assert_eq!(perspective["box_mm"], json!([[-0.5263, -0.7895], [20.5263, 30.7895]]));
let flat = json!({"target": [10, 5, 15], "yaw": 0, "pitch": 0, "distance": 100});
let parallel = run(&mut s, "inspect.silhouette", json!({"camera": flat, "rows": 60}));
assert_eq!(parallel["projection"], "parallel");
assert_eq!(parallel["box_mm"], json!([[0.0, 0.0], [20.0, 30.0]]));
let inside = json!({"target": [10, 5, 15], "yaw": 0, "pitch": 0, "distance": 1, "fov": 0.6});
assert!(s.execute("inspect.silhouette", &json!({"camera": inside})).unwrap_err().to_string().contains("behind the camera"));
// Between two bodies, looking -X from X 28: Short (X 30..40) is behind the eye.
silhouette_box(&mut s, "Short", 30.0, 40.0, 10.0);
let between = json!({"target": [25, 5, 15], "yaw": -std::f64::consts::FRAC_PI_2, "pitch": 0, "distance": 3, "fov": 0.6});
assert!(s.execute("inspect.silhouette", &json!({"camera": between})).unwrap_err().to_string().contains("behind the camera"));
assert_eq!(run(&mut s, "inspect.silhouette", json!({"camera": between, "bodies": ["Box"]}))["bodies"], 1);
}
#[test]
fn silhouette_is_an_agent_command_not_a_toolbar_button() {
let specs = command_specs();
let spec = specs.iter().find(|c| c.id == "inspect.silhouette").unwrap();
assert!(spec.tab.is_empty(), "{} › {}", spec.tab, spec.panel);
assert!(!spec.undoable);
}
#[test]
fn sample_edges_chain_and_faces() {
let mut s = Session::default();
s.run_script(&crate::sample::script()).unwrap();
let st = s.model.state();
let m = st.bodies[0].mesh();
let e = (0..m.edges.len()).find(|i| m.edges[*i].iter().all(|p| (p.z - 8.0).abs() < 1e-6 && p.y.abs() < 1e-6)).expect("front top edge");
let chain = m.tangent_chain(e, 2f64.to_radians());
// The plate's top outline: 4 lines and 4 corner arcs (a boolean may leave an edge twice,
// once per face; count distinct ones).
let mut mids: Vec<solidcraft_geom::Vec3> = Vec::new();
for i in &chain {
let p = &m.edges[*i];
let mid = p[p.len() / 2];
assert!(p.iter().all(|q| (q.z - 8.0).abs() < 1e-6), "{p:?}");
if !mids.iter().any(|q| q.dist(mid) < 1e-6) {
mids.push(mid);
}
}
assert_eq!(mids.len(), 8, "{chain:?}");
// Every edge bounds a face, and the top face has the outline and the hole rims.
assert!(m.edge_faces.iter().all(|f| !f.is_empty()));
}
/// timeline.inspect returns a feature's definition in the shape timeline.edit's `set` takes, so
/// an agent can read the field names instead of guessing them.
#[test]
fn timeline_inspect_shows_what_timeline_edit_changes() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Slab"}));
run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2, "name": "Round"}));
let i = run(&mut s, "timeline.inspect", json!({"feature": "Slab"}));
assert_eq!(i["type"], "extrude", "{i}");
assert_eq!(i["type_name"], "ExtrudeFeature", "{i}");
assert_eq!(i["definition"]["extent"]["distance"], "10", "{i}");
assert_eq!(i["definition"]["operation"], "new_body", "{i}");
assert!(i["definition"].get("type").is_none() && i["definition"].get("param_names").is_none(), "{i}");
assert_eq!(i["inputs"][0]["label"], "Distance", "{i}");
assert_eq!(i["inputs"][0]["unit"], "mm", "{i}");
let d = i["inputs"][0]["param"].as_str().unwrap().to_string();
// The definition's field names are what timeline.edit takes.
run(&mut s, "timeline.edit", json!({"feature": "Slab", "set": {"extent": {"distance": "12"}}}));
let i = run(&mut s, "timeline.inspect", json!({"feature": i["id"]}));
assert_eq!(i["definition"]["extent"]["distance"], "12", "{i}");
assert_eq!(i["inputs"][0]["param"], d.as_str(), "{i}");
let f = run(&mut s, "timeline.inspect", json!({"feature": "Round"}));
assert_eq!(f["definition"]["radius"], "2", "{f}");
run(&mut s, "timeline.edit", json!({"feature": "Round", "set": {"radius": "3"}}));
assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": "Round"}))["definition"]["radius"], "3");
// A sketch leaves its geometry out (sketch.inspect has it) and says so.
let k = run(&mut s, "timeline.inspect", json!({"feature": "Base"}));
assert!(k["definition"].get("sketch").is_none() && k["definition"].get("plane").is_some(), "{k}");
assert_eq!(k["omitted"][0]["field"], "sketch", "{k}");
// Read-only: no undo step; bad input is refused.
let undo = s.undo.len();
run(&mut s, "timeline.inspect", json!({"feature": "Slab"}));
assert_eq!(s.undo.len(), undo);
for bad in [json!({}), json!({"feature": "Nope"}), json!({"feature": [1]}), json!({"feature": 1e300}), json!({"feature": null})] {
assert!(s.execute("timeline.inspect", &bad).is_err(), "{bad}");
}
}
#[test]
fn timeline_edits_reresolve_references() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "name": "Base"}));
run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 20]], "radius": 3, "name": "Round"}));
run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 6, "name": "Bore"}));
let fillet = |l: f64| (9.0 - 9.0 * PI / 4.0) * l;
let expect = |l: f64, h: f64| l * 30.0 * h - fillet(l) - PI * 9.0 * h;
assert!(rel(volume(&mut s), expect(40.0, 20.0)) < 1e-3);
// Taller box: the fillet's edge point is now 5 mm below the edge; the edge is found by its
// name (no warning) and the hole moves up with the top face.
run(&mut s, "timeline.edit", json!({"feature": "Base", "set": {"height": "25"}}));
assert!(rel(volume(&mut s), expect(40.0, 25.0)) < 1e-3, "{}", volume(&mut s));
let round = s.doc.find_feature("Round").map(|f| f.id).unwrap();
assert_eq!(s.model.result(round).and_then(|r| r.warning.clone()), None);
// Longer box: the point still lies on the (longer) edge.
run(&mut s, "timeline.edit", json!({"feature": "Base", "set": {"length": "60"}}));
assert!(rel(volume(&mut s), expect(60.0, 25.0)) < 1e-3, "{}", volume(&mut s));
// Reorder: the fillet can't go before the box; the hole can go before the fillet.
let e = s.execute("timeline.reorder", &json!({"feature": "Round", "position": 0})).unwrap_err().to_string();
assert!(e.contains("breaks"), "{e}");
run(&mut s, "timeline.reorder", json!({"feature": "Bore", "position": 1}));
let names: Vec<&str> = s.doc.features.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["Base", "Bore", "Round"]);
assert!(rel(volume(&mut s), expect(60.0, 25.0)) < 1e-3);
// Redefine the fillet in place with a new radius; it keeps its name and position.
run(&mut s, "timeline.redefine", json!({"feature": "Round", "command": "solid.fillet", "params": {"edges": [[30, 0, 25]], "radius": 4}}));
let f4 = (16.0 - 16.0 * PI / 4.0) * 60.0;
assert!(rel(volume(&mut s), 60.0 * 30.0 * 25.0 - f4 - PI * 9.0 * 25.0) < 1e-3);
assert_eq!(s.doc.features.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["Base", "Bore", "Round"]);
// Dependents and roll back.
let d = run(&mut s, "timeline.dependents", json!({"feature": "Base"}));
assert_eq!(d["would_fail"].as_array().map(|a| a.len()), Some(2), "{d}");
run(&mut s, "timeline.roll_to", json!({"feature": "Base"}));
assert!(rel(volume(&mut s), 60.0 * 30.0 * 25.0) < 1e-6);
run(&mut s, "timeline.roll_to", json!({}));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(rel(volume(&mut s), 60.0 * 30.0 * 25.0 - f4 - PI * 9.0 * 25.0) < 1e-3);
}
/// A 40 × 30 × 20 box exported to a STEP file in a fresh temp directory.
fn step_box_file(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("solidcraft-step-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let p = dir.join("Block.step");
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
p
}
/// File → Open of a STEP file gives an Import base feature, and features work on its faces.
#[test]
fn step_open_then_model_on_it() {
let p = step_box_file("open");
let mut s = Session::default();
let r = run(&mut s, "doc.open", json!({"path": p.to_string_lossy()}));
assert_eq!(r["features"], 1, "{r}");
assert_eq!(s.doc.name, "Block");
assert_eq!(s.doc.features[0].kind.type_name(), "BaseFeature");
assert!(matches!(&s.doc.features[0].kind, doc::FeatureKind::Import { file, .. } if file == "Block.step"));
assert!(s.is_dirty() && s.path.is_none() && s.undo.is_empty());
assert!(rel(volume(&mut s), 24000.0) < 1e-6);
let corner = run(&mut s, "inspect.measure", json!({}))["bodies"][0]["bbox"]["min"].clone();
let (x0, y0, z0) = (corner[0].as_f64().unwrap(), corner[1].as_f64().unwrap(), corner[2].as_f64().unwrap());
let at = |x: f64, y: f64, z: f64| json!([x0 + x, y0 + y, z0 + z]);
// Fillet a vertical edge, drill a through hole, cut a pocket sketched on the top face.
run(&mut s, "solid.fillet", json!({"edges": [at(0.0, 0.0, 10.0)], "radius": 3}));
let mut want = 24000.0 - (9.0 - PI * 9.0 / 4.0) * 20.0;
assert!(rel(volume(&mut s), want) < 2e-4);
run(&mut s, "solid.hole", json!({"position": at(28.0, 15.0, 20.0), "diameter": 6}));
want -= PI * 9.0 * 20.0;
assert!(rel(volume(&mut s), want) < 5e-4, "{} vs {want}", volume(&mut s));
// Modified imported faces no longer have an immutable construction certificate; the top
// attaches by its exact history name instead.
let top = run(&mut s, "sketch.create", json!({"plane": {"face": at(10.0, 15.0, 20.0)}}))["sketch"].as_u64().unwrap();
assert!(matches!(
s.placed_document().sketch_face_attachment(top, &s.model),
doc::FaceAttachmentStatus::Healthy {
target: doc::config::ConfigFaceTarget { certificate: Some(doc::config::FaceCertificate::Lineage), .. },
..
}
));
let c = [x0 + 10.0, y0 + 15.0];
// Sketch coordinates on the face are relative to the model origin projected onto it.
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [c[0] - 4.0, c[1] - 4.0], "p1": [c[0] + 4.0, c[1] + 4.0]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": -5, "operation": "cut"}));
want -= 64.0 * 5.0;
assert!(rel(volume(&mut s), want) < 5e-4, "{} vs {want}", volume(&mut s));
assert_eq!(s.model.results.iter().filter(|r| r.error.is_some()).count(), 0);
// The design saves and reopens without the STEP file.
let before = volume(&mut s);
let design = p.with_extension("solidcraft");
run(&mut s, "file.save_as", json!({"path": design.to_string_lossy()}));
std::fs::remove_file(&p).unwrap();
let mut s2 = Session::default();
run(&mut s2, "doc.open", json!({"path": design.to_string_lossy()}));
assert!(rel(volume(&mut s2), before) < 1e-6);
}
/// A join onto an imported body of thousands of planar faces (a converted mesh, say): each face of
/// the result was compared with every planar face of the inputs whose source is unknown, and the
/// join was refused past the comparison budget.
#[test]
fn join_onto_a_finely_faceted_import() {
let dir = std::env::temp_dir().join(format!("solidcraft-step-faceted-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let n = 4000;
let mut pts: Vec<[f64; 2]> =
(0..n).map(|i| std::f64::consts::TAU * f64::from(i) / f64::from(n)).map(|a| [20.0 * a.cos(), 20.0 * a.sin()]).collect();
pts.push(pts[0]);
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "P"}));
run(&mut s, "sketch.line", json!({"points": pts}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "P", "distance": 10}));
let p = dir.join("Faceted.step");
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
let prism = volume(&mut s);
let mut d = Session::default();
// The import is a component (#1386): the pin is made in it to join its body.
let r = run(&mut d, "file.insert_step", json!({"path": p.to_string_lossy()}));
run(&mut d, "component.activate", json!({"component": r["component"]}));
run(&mut d, "sketch.create", json!({"plane": "XY", "name": "Pin"}));
run(&mut d, "sketch.rectangle.two_point", json!({"p0": [-5, -5], "p1": [5, 5]}));
run(&mut d, "sketch.finish", json!({}));
run(&mut d, "solid.extrude", json!({"sketch": "Pin", "distance": 25, "operation": "join"}));
assert_eq!(d.model.state().bodies.len(), 1);
assert!(rel(volume(&mut d), prism + 10.0 * 10.0 * 15.0) < 1e-6, "{}", volume(&mut d));
}
/// Shell an imported body; insert STEP into an existing design; extension case; bad files.
#[test]
fn step_insert_shell_and_errors() {
let p = step_box_file("insert");
let upper = p.with_file_name("BLOCK.STP");
std::fs::copy(&p, &upper).unwrap();
let mut s = Session::default();
run(&mut s, "doc.open", json!({"path": upper.to_string_lossy()}));
let top = run(&mut s, "inspect.measure", json!({}))["bodies"][0]["bbox"]["max"].clone();
let (x1, y1, z1) = (top[0].as_f64().unwrap(), top[1].as_f64().unwrap(), top[2].as_f64().unwrap());
run(&mut s, "solid.shell", json!({"faces": [[x1 - 20.0, y1 - 15.0, z1]], "thickness": 2}));
let walls = 24000.0 - 36.0 * 26.0 * 18.0;
assert!(rel(volume(&mut s), walls) < 5e-4, "{}", volume(&mut s));
let mut d = Session::default();
run(&mut d, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [100, 0, 0]}));
let r = run(&mut d, "file.insert_step", json!({"path": p.to_string_lossy()}));
assert_eq!(r["bodies"].as_array().unwrap().len(), 1, "{r}");
run(&mut d, "file.insert_step", json!({"path": p.to_string_lossy()}));
let names: Vec<String> = d.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names.len(), 3);
let mut uniq = names.clone();
uniq.dedup();
assert_eq!(uniq.len(), 3, "{names:?}");
assert!(rel(volume(&mut d), 125.0 + 48000.0) < 1e-6);
run(&mut d, "edit.undo", json!({}));
assert_eq!(d.model.state().bodies.len(), 2);
let junk = p.with_file_name("junk.step");
std::fs::write(&junk, "ISO-10303-21;\nDATA;\n#1=CARTESIAN_POINT('',(0.,0.,0.));\nENDSEC;\nEND-ISO-10303-21;\n").unwrap();
let before = d.doc.clone();
assert!(d.execute("file.insert_step", &json!({"path": junk.to_string_lossy()})).is_err());
assert!(d.execute("doc.open", &json!({"path": junk.to_string_lossy()})).is_err());
assert!(d.execute("file.insert_step", &json!({"path": "/nonexistent/a.step"})).is_err());
assert!(d.execute("file.insert_step", &json!({"path": p.with_extension("stl").to_string_lossy()})).is_err());
assert_eq!(*d.doc, *before);
}
fn body_volume(st: &solidcraft_doc::ModelState) -> f64 {
st.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum()
}
/// Deleting an inserted assembly keeps the names of the bodies that remain, and leaves no assembly
/// ownership behind.
#[test]
fn step_insert_delete_removes_assembly_and_undo_restores_it() {
let dir = std::env::temp_dir().join(format!("solidcraft-step-delete-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("parts.step");
let mut source = Session::default();
for (name, x) in [("Part", 0), ("Other", 20)] {
run(&mut source, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "operation": "new", "body_name": name}));
}
run(&mut source, "component.from_bodies", json!({"bodies": ["Part", "Other"]}));
run(&mut source, "file.export", json!({"path": path.to_string_lossy()}));
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Part"}));
let kept = s.doc_mut().add_component(Some("Kept"), 0).unwrap();
let kept_occurrence = s.doc.occurrence_of(kept).unwrap().clone();
run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy(), "name": "Imported"}));
let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert!(reopened.find_feature("Imported").unwrap().inserted, "the insert keeps its mark through save");
run(&mut s, "solid.mirror", json!({"bodies": ["Part"], "plane": {"origin": [0, 30, 0], "normal": [0, 1, 0]}}));
assert!(s.model.state().body("Part (3)").is_some());
assert!(!s.doc.assembly.joints.is_empty());
assert!(!s.doc.body_components.is_empty());
let before = s.doc.clone();
let history = s.undo.len();
run(&mut s, "timeline.delete", json!({"feature": "Imported"}));
assert_eq!(s.undo.len(), history + 1);
assert_eq!(s.doc.components.iter().map(|c| c.id).collect::<Vec<_>>(), [kept]);
assert_eq!(s.doc.occurrences, [kept_occurrence]);
assert!(s.doc.assembly.joints.is_empty());
assert!(s.doc.body_components.is_empty());
assert!(s.doc.body_offsets.is_empty());
let state = s.model.state();
let mirrored = state.body("Part (3)").unwrap();
assert_eq!(s.doc.model_body_component(mirrored), 0);
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [40, 0, 0], "operation": "new", "body_name": "Other"}));
assert_eq!(s.doc.model_body_component(s.model.state().body("Other").unwrap()), 0);
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc, before);
assert!(s.model.state().body("Part (3)").is_some());
run(&mut s, "edit.redo", json!({}));
assert!(s.doc.body_components.is_empty());
assert!(s.doc.assembly.joints.is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
/// Previews evaluate on a scratch copy: the document, undo history and model are untouched.
#[test]
fn preview_has_no_side_effects() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
run(&mut s, "sketch.finish", json!({}));
let doc = s.doc.clone();
let (undo, rev) = (s.undo.len(), s.revision);
let p = s.preview(&[("solid.extrude".into(), json!({"distance": 15}))]).unwrap();
assert!(p.before.bodies.is_empty());
assert!(rel(body_volume(&p.after), 40.0 * 30.0 * 15.0) < 1e-9);
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!((s.undo.len(), s.revision), (undo, rev));
assert!(s.model.state().bodies.is_empty());
// Errors come back as errors and change nothing either.
assert!(s.preview(&[("solid.extrude".into(), json!({"distance": "nonsense"}))]).is_err());
assert!(Arc::ptr_eq(&doc, &s.doc));
// Fillet preview on a real body.
run(&mut s, "solid.extrude", json!({"distance": 20}));
let (doc, undo) = (s.doc.clone(), s.undo.len());
let p = s.preview(&[("solid.fillet".into(), json!({"edges": [[0, 0, 10]], "radius": 3}))]).unwrap();
let filleted = 24000.0 - (9.0 - PI * 9.0 / 4.0) * 20.0;
assert!(rel(body_volume(&p.after), filleted) < 2e-4);
assert!(rel(body_volume(&p.before), 24000.0) < 1e-9);
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(s.undo.len(), undo);
}
/// Previewing an edit shows the rebuilt feature although the timeline is rolled back to it.
#[test]
fn preview_of_an_edit() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
run(&mut s, "sketch.finish", json!({}));
let r = run(&mut s, "solid.extrude", json!({"distance": 20}));
let fid = r["feature"].as_u64().unwrap();
let idx = s.doc.feature_index(fid).unwrap();
run(&mut s, "timeline.roll_to", json!({"position": idx}));
assert!(s.model.state().bodies.is_empty());
let doc = s.doc.clone();
let p = s.preview(&[("timeline.redefine".into(), json!({"feature": fid, "command": "solid.extrude", "params": {"distance": 10}}))]).unwrap();
assert!(rel(body_volume(&p.after), 12000.0) < 1e-9);
assert!(Arc::ptr_eq(&doc, &s.doc));
}
/// `operation: "auto"`: into a body cuts; additions default to Join when a solid exists.
#[test]
fn extrude_auto_operation() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
// A face pushed in (negative distance) cuts.
let p = json!({"face": [20, 15, 20], "distance": -5, "operation": "auto"});
assert_eq!(auto_operation(&s, &p).unwrap(), Some("cut"));
run(&mut s, "solid.extrude", p);
assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0) < 1e-6);
// Pulled out, it joins.
assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 5})).unwrap(), Some("join"));
// Pushed in far past the bottom (halfway is below the box), it still cuts (#1257).
assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": -50})).unwrap(), Some("cut"));
assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 50, "direction": "negative"})).unwrap(), Some("cut"));
// A sketch on XY under the box: up goes into it (cut), down grows out of it (join), and a
// profile beside the box still defaults to Join (New Body remains explicit).
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [60, 5], "p1": [70, 15]}));
run(&mut s, "sketch.finish", json!({}));
let at = |x: f64, d: f64| json!({"profiles": [{"point": [x, 10]}], "distance": d});
assert_eq!(auto_operation(&s, &at(10.0, 8.0)).unwrap(), Some("cut"));
assert_eq!(auto_operation(&s, &at(10.0, -8.0)).unwrap(), Some("join"));
assert_eq!(auto_operation(&s, &at(65.0, 8.0)).unwrap(), Some("join"));
run(&mut s, "solid.extrude", json!({"profiles": [{"point": [10, 10]}], "distance": 8, "operation": "auto"}));
assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0 - 100.0 * 8.0) < 1e-6);
}
/// #467: the automatic operation is decided where the extrude starts. A profile on a plate's top
/// going down cuts; started From Object at the plate's bottom (or 15 mm lower by a start offset)
/// the same distance goes out of it, and joins.
#[test]
fn extrude_auto_operation_counts_from_the_start() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "corner": [0, 0, 0]}));
run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 10], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]}));
run(&mut s, "sketch.finish", json!({}));
let down = json!({"profiles": [{"point": [10, 10]}], "distance": -5});
assert_eq!(auto_operation(&s, &down).unwrap(), Some("cut"));
let mut from = down.clone();
from["from"] = json!([20, 15, 0]);
assert_eq!(auto_operation(&s, &from).unwrap(), Some("join"));
let mut offset = down.clone();
offset["start_offset"] = json!("-15 mm");
assert_eq!(auto_operation(&s, &offset).unwrap(), Some("join"));
// Up from the bottom face into the plate it cuts again.
let mut up = from.clone();
up["distance"] = json!(5);
assert_eq!(auto_operation(&s, &up).unwrap(), Some("cut"));
}
/// #1666: a loft between two 18-point polylines has twisted (bilinear) side faces. Each was
/// meshed as two flat triangles, which cross the surface; the mesh volume was 16 800.6 mm³
/// against the B-rep's 17 884. Divided to the chord tolerance, the mesh matches the B-rep.
#[test]
fn twisted_ruled_faces_are_meshed_to_the_chord_tolerance() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"}));
run(
&mut s,
"sketch.line",
json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24.76384,3],[-16.0568,14.97217],[-8,4.90117],[0,14.90117],[8,4.90117],[16.0568,14.97217],[24.76384,3],[26,3],[26,0],[23.23616,0],[15.9432,10.02783],[8,0.09883],[0,10.09883],[-8,0.09883],[-15.9432,10.02783],[-23.23616,0],[-26,0]]}),
);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 90.5, "name": "Top"}));
run(
&mut s,
"sketch.line",
json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24,3],[-16,3],[-8,3],[0,3],[8,3],[16,3],[24,3],[26,3],[26,0],[24,0],[16,0],[8,0],[0,0],[-8,0],[-16,0],[-24,0],[-26,0]]}),
);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom"}, {"sketch": "Top"}], "operation": "new"}));
let st = s.model.state();
let body = &st.bodies.first().unwrap().body;
let exact = solidcraft_kernel::measure(body).unwrap().volume;
let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap();
let volume: f64 = mesh
.triangles
.iter()
.map(|t| {
let p = |i: u32| mesh.positions[i as usize];
p(t[0]).dot(p(t[1]).cross(p(t[2]))) / 6.0
})
.sum();
assert!(mesh.triangles.len() > 72, "the twisted faces are divided: {} triangles", mesh.triangles.len());
assert!(rel(volume.abs(), exact) < 2e-3, "mesh {volume} against B-rep {exact}");
}
/// #1633: to an object, the extrude goes to it on whichever side it is, whatever its
/// `direction`: through the body to its far face is a Cut, out to something above is a Join.
#[test]
fn extrude_auto_operation_follows_the_to_object() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "corner": [0, 0, 50], "body_name": "Above"}));
for direction in ["positive", "negative"] {
// From the top face to the bottom face: through the body.
let down = json!({"face": [20, 15, 20], "to": [10, 10, 0], "distance": 19, "direction": direction});
assert!(extrude_reach(&s, &down).is_some_and(|h| (h + 20.0).abs() < 1e-6), "{down}");
assert_eq!(auto_operation(&s, &down).unwrap(), Some("cut"), "{down}");
// From the top face up to the box above: out of the body.
let up = json!({"face": [20, 15, 20], "to": [10, 10, 50], "distance": 19, "direction": direction});
assert!(extrude_reach(&s, &up).is_some_and(|h| (h - 30.0).abs() < 1e-6), "{up}");
assert_eq!(auto_operation(&s, &up).unwrap(), Some("join"), "{up}");
}
// Without a To object the direction still counts.
assert_eq!(extrude_reach(&s, &json!({"face": [20, 15, 20], "distance": 5, "direction": "negative"})), Some(-5.0));
}
/// #1678: a hole's `position` takes length expressions, keeps them and follows the parameters: a
/// hole on a plate's middle line stays there when the plate gets wider. A position of plain
/// numbers is stored as before, with no `at`.
#[test]
fn a_hole_position_of_expressions_follows_the_parameters() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "width", "expression": "30 mm"}));
run(&mut s, "parameters.add", json!({"name": "t", "expression": "4 mm"}));
run(&mut s, "solid.box", json!({"length": 100, "width": "width", "height": "t", "body_name": "Plate"}));
run(&mut s, "solid.hole", json!({"position": ["40", "width/2", "t"], "clearance": "M5", "name": "Middle"}));
run(&mut s, "solid.hole", json!({"position": [80, 10, 4], "clearance": "M5", "name": "Fixed"}));
let centre_y = |s: &Session| {
let st = s.model.state();
solidcraft_kernel::measure(&st.body("Plate").unwrap().body).unwrap().centroid.y
};
let hole = |s: &Session, name: &str| -> Value {
let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
saved["features"].as_array().and_then(|f| f.iter().find(|f| f["name"] == name)).cloned().unwrap()
};
assert_eq!(hole(&s, "Middle")["at"], json!([40.0, "width/2", "t"]), "the expressions are kept");
assert!(hole(&s, "Fixed").get("at").is_none(), "plain numbers are stored as before");
// The fixed hole sits off the middle line, so it alone moves the centre; widen the plate.
let before = centre_y(&s);
run(&mut s, "parameters.change", json!({"name": "width", "expression": "40 mm"}));
let after = centre_y(&s);
// The middle hole is at y = 20 now (the plate's middle); the fixed one stays at y = 10. With
// the middle hole left at y = 15 the centre would sit lower still.
let plate = 100.0 * 40.0 * 4.0;
let hole_v = std::f64::consts::PI * (5.5f64 / 2.0).powi(2) * 4.0;
let want = (plate * 20.0 - hole_v * 20.0 - hole_v * 10.0) / (plate - 2.0 * hole_v);
assert!((after - want).abs() < 1e-3, "centre y {after}, want {want} (was {before})");
// A bad expression is refused.
assert!(s.execute("solid.hole", &json!({"position": ["40", "nope/2", "t"], "diameter": 3})).is_err());
}
/// Additive extrusions default to joining even when only a profile side touches material.
#[test]
fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() {
for operation in ["auto", "new"] {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 30}));
run(&mut s, "sketch.create", json!({"plane": {"origin": [10, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 20], "p1": [30, 30]}));
run(&mut s, "sketch.finish", json!({}));
// The profile centre is outside the vertical arm. Contact is along its
// y=10 side, not behind the centre along the extrusion's X direction.
let p = json!({"distance": 10, "to": [0, 15, 25], "operation": operation});
assert_eq!(auto_operation(&s, &p).unwrap(), Some("join"));
run(&mut s, "solid.extrude", p);
assert!((volume(&mut s) - 5000.0).abs() < 1e-6);
let st = s.model.state();
assert_eq!(st.bodies.len(), if operation == "auto" { 1 } else { 2 });
if operation == "auto" {
let body = &st.bodies.first().unwrap().body;
assert!(body.validity().is_empty());
assert_eq!(body.lumps().unwrap().len(), 1);
assert_eq!(body.face_count(), 8, "the two flat elbow sides must be single faces");
assert_eq!(body.classify_point(geom::Vec3::new(5.0, 10.0, 25.0)).unwrap(), solidcraft_kernel::PointClass::Inside);
}
}
}
#[test]
fn auto_extrude_joins_corner_screw_boss() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 30}));
run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 30], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}}));
run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 4}));
run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 1}));
run(&mut s, "sketch.finish", json!({}));
let p = json!({"profiles": [{"point": [12, 10]}], "distance": 5, "operation": "auto"});
assert_eq!(auto_operation(&s, &p).unwrap(), Some("join"));
run(&mut s, "solid.extrude", p);
assert!(rel(volume(&mut s), 3000.0 + PI * 15.0 * 5.0) < 1e-3);
let st = s.model.state();
assert_eq!(st.bodies.len(), 1);
let body = &st.bodies.first().unwrap().body;
assert_eq!(body.lumps().unwrap().len(), 1);
assert!(body.validity().is_empty());
assert_eq!(body.classify_point(geom::Vec3::new(10.0, 10.0, 32.0)).unwrap(), solidcraft_kernel::PointClass::Outside, "the screw hole stays open");
}
#[test]
fn auto_extrude_starts_new_body_in_empty_component() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(&mut s, "component.create", json!({"name": "Other"}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 2}));
run(&mut s, "sketch.finish", json!({}));
assert_eq!(auto_operation(&s, &json!({"distance": 5})).unwrap(), Some("new"));
assert_eq!(auto_operation(&s, &json!({"distance": 5, "participants": ["missing"]})).unwrap(), Some("new"));
}
/// Measuring picked geometry: distance between faces, angle, edge length.
#[test]
fn measure_origin_planes_axes_and_points() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let at = |p: [f64; 3]| json!({"type": "vertex", "body": "Body1", "point": p});
// A point 10 above the XY plane.
let r = run(&mut s, "inspect.measure", json!({"items": [{"type": "plane", "name": "XY"}, at([5.0, 5.0, 10.0])]}));
assert!((r["distance_mm"].as_f64().unwrap() - 10.0).abs() < 1e-9, "{r}");
assert_eq!(r["from"], json!([5.0, 5.0, 0.0]));
// The point's distance from the Z axis.
let r = run(&mut s, "inspect.measure", json!({"items": [{"type": "axis", "name": "Z"}, at([3.0, 4.0, 7.0])]}));
assert!((r["distance_mm"].as_f64().unwrap() - 5.0).abs() < 1e-9, "{r}");
// The XY plane and the Z axis meet: nothing between them.
let r = run(&mut s, "inspect.measure", json!({"items": [{"type": "plane", "name": "XY"}, {"type": "axis", "name": "Z"}]}));
assert!(r["distance_mm"].as_f64().unwrap().abs() < 1e-9, "{r}");
}
#[test]
fn measure_items() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let st = s.model.state();
let m = st.body("Body1").unwrap().mesh();
// Find the faces by their centroid: top (z = 20), bottom (z = 0), front (y = 0).
let face_at = |z: Option<f64>, y: Option<f64>| -> usize {
(0..6)
.find(|f| {
let tris: Vec<_> = m.triangles.iter().zip(&m.tri_face).filter(|(_, tf)| **tf as usize == *f).filter_map(|(t, _)| m.tri(t)).collect();
tris.iter().all(|t| t.iter().all(|p| z.is_none_or(|z| (p.z - z).abs() < 1e-9) && y.is_none_or(|y| (p.y - y).abs() < 1e-9)))
})
.unwrap()
};
let (ft, fb, ff) = (face_at(Some(20.0), None), face_at(Some(0.0), None), face_at(None, Some(0.0)));
let face = |i: usize, p: [f64; 3]| json!({"type": "face", "body": "Body1", "index": i, "point": p});
let r = run(&mut s, "inspect.measure", json!({"items": [face(ft, [20.0, 15.0, 20.0]), face(fb, [20.0, 15.0, 0.0])]}));
assert!((r["distance_mm"].as_f64().unwrap() - 20.0).abs() < 1e-9, "{r}");
assert!((r["angle_deg"].as_f64().unwrap() - 180.0).abs() < 1e-6, "{r}");
let r = run(&mut s, "inspect.measure", json!({"items": [face(ft, [20.0, 15.0, 20.0]), face(ff, [20.0, 0.0, 10.0])]}));
assert!(r["distance_mm"].as_f64().unwrap() < 1e-9);
assert!((r["angle_deg"].as_f64().unwrap() - 90.0).abs() < 1e-6);
let r = run(&mut s, "inspect.measure", json!({"items": [face(ft, [20.0, 15.0, 20.0])]}));
assert!((r["items"][0]["area_mm2"].as_f64().unwrap() - 1200.0).abs() < 1e-6, "{r}");
let v = json!({"type": "vertex", "body": "Body1", "point": [0, 0, 0]});
let w = json!({"type": "vertex", "body": "Body1", "point": [40, 30, 20]});
let r = run(&mut s, "inspect.measure", json!({"items": [v, w]}));
assert!((r["distance_mm"].as_f64().unwrap() - (1600.0f64 + 900.0 + 400.0).sqrt()).abs() < 1e-9);
assert!(s.execute("inspect.measure", &json!({"items": []})).is_err());
assert!(s.execute("inspect.measure", &json!({"items": [{"type": "nonsense"}]})).is_err());
}
/// Section Analysis sets and clears the view cut without touching the design or history.
#[test]
fn section_analysis() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let (doc, undo) = (s.doc.clone(), s.undo.len());
let r = run(&mut s, "inspect.section", json!({"plane": "XZ", "offset": 15}));
let (o, n) = s.section.unwrap();
assert!((o - n * 15.0).len() < 1e-12 && (n.y.abs() - 1.0).abs() < 1e-12);
// The cut faces are hatched unless `hatch` says otherwise.
assert!(s.section_hatch && r["section"]["hatch"] == true, "{r}");
let r = run(&mut s, "inspect.section", json!({"plane": "XZ", "offset": 15, "hatch": false}));
assert!(!s.section_hatch && r["section"]["hatch"] == false, "{r}");
run(&mut s, "inspect.section", json!({"plane": "XZ", "offset": 15}));
assert!(s.section_hatch);
run(&mut s, "inspect.section", json!({"plane": {"origin": [0, 0, 5], "normal": [0, 0, 2]}, "flip": true}));
let (o, n) = s.section.unwrap();
assert!((o.z - 5.0).abs() < 1e-12 && (n.z + 1.0).abs() < 1e-12);
assert!(s.execute("inspect.section", &json!({"plane": {"normal": [0, 0, 0]}})).is_err());
run(&mut s, "inspect.section", json!({"clear": true}));
assert!(s.section.is_none());
// XZ's normal is +Y: an offset moves the cut to +Y, `at` places it at a world Y, and the
// result says where the cut landed either way.
let r = run(&mut s, "inspect.section", json!({"plane": "XZ", "offset": 10}));
assert_eq!((r["section"]["axis"].as_str(), r["section"]["at"].as_f64()), (Some("Y"), Some(10.0)), "{r}");
for (plane, at, flip) in [("XZ", -282.5, false), ("XZ", 7.0, true), ("XY", 3.0, false), ("YZ", -4.0, true)] {
let r = run(&mut s, "inspect.section", json!({"plane": plane, "at": at, "flip": flip}));
assert_eq!(r["section"]["at"].as_f64(), Some(at), "{plane} {r}");
let (o, _) = s.section.unwrap();
assert!(((o.x + o.y + o.z) - at).abs() < 1e-12, "{plane} {o:?}");
}
assert!(s.execute("inspect.section", &json!({"plane": "XZ", "at": 1, "offset": 1})).is_err());
assert!(s.execute("inspect.section", &json!({"plane": {"normal": [0, 1, 0]}, "at": 1})).is_err());
run(&mut s, "inspect.section", json!({"clear": true}));
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(s.undo.len(), undo);
}
/// A section index finds the same cut segments, in the same order and to the bit, as cutting
/// every triangle: one index for every normal (tilting a Section Analysis turns it every frame,
/// #10373), axis and tilted, cuts through vertices, at the ends and beyond the part, and a
/// triangle with a corner that is not a number.
#[test]
fn section_index_cuts_like_every_triangle() {
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 12, "height": 30}));
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 8, "operation": "join"}));
let st = s.model.state();
let m = st.bodies.first().unwrap().mesh();
assert!(m.triangles.len() > 64, "enough triangles for several cells: {}", m.triangles.len());
let bits = |v: Vec<(Vec3, Vec3)>| v.iter().flat_map(|(a, b)| [a.x, a.y, a.z, b.x, b.y, b.z].map(f64::to_bits)).collect::<Vec<_>>();
let mut hostile = (*m).clone();
hostile.positions.push(Vec3::new(f64::NAN, 0.0, 0.0));
let nan = u32::try_from(hostile.positions.len() - 1).unwrap();
hostile.triangles.extend([[0, 1, nan], [0, 1, u32::MAX]]);
for m in [&*m, &hostile] {
let index = view::SectionIndex::new(m);
let mut normals = vec![Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()];
// A tilt drag: the normal turns a little every frame.
normals.extend((0..30).map(|k| {
let a = (5.0 + 3.0 * k as f64).to_radians();
Vec3::new(0.1, a.sin(), a.cos()).normalized().unwrap()
}));
for n in normals {
let heights: Vec<f64> = m.positions.iter().map(|p| n.dot(*p)).filter(|h| h.is_finite()).collect();
let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h)));
let mut cuts: Vec<f64> = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect();
cuts.extend(heights.iter().step_by(7).copied());
cuts.extend([lo, hi]);
for at in cuts {
let o = n * at;
assert_eq!(bits(index.segments(m, o, n)), bits(view::section_segments(m, o, n)), "{n:?} at {at}");
}
}
}
}
/// Press Pull: positive pulls a face out, negative pushes it in (a cut), edges get a fillet.
#[test]
fn press_pull() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.press_pull", json!({"face": [20, 15, 20], "distance": 5}));
assert!(rel(volume(&mut s), 40.0 * 30.0 * 25.0) < 1e-6);
run(&mut s, "solid.press_pull", json!({"face": [20, 15, 25], "distance": "-10"}));
assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0) < 1e-6);
assert!(s.execute("solid.press_pull", &json!({"face": [20, 15, 15], "distance": 0})).is_err());
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.press_pull", json!({"edges": [[0, 0, 7]], "distance": 3}));
assert!(rel(volume(&mut s), 24000.0 - (9.0 - PI * 9.0 / 4.0) * 20.0) < 2e-4);
}
/// Extruding a planar body face (press-pull style): the face boundary becomes a sketch profile.
#[test]
fn extrude_a_body_face() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.extrude", json!({"face": [20, 15, 20], "distance": 15, "operation": "join"}));
assert!(rel(volume(&mut s), 40.0 * 30.0 * 35.0) < 1e-6);
assert!(s.active_sketch.is_none());
// A face with a round hole: the hole stays open (a new body: joins of curved bodies on a
// shared face are a kernel gap for now).
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [20, 15], "radius": 5}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 20, "operation": "cut"}));
let before = volume(&mut s);
run(&mut s, "solid.extrude", json!({"face": [5, 5, 20], "distance": 10, "operation": "new"}));
let v = volume(&mut s);
assert!(rel(v - before, (1200.0 - PI * 25.0) * 10.0) < 1e-3, "{v} {before}");
assert!(s.execute("solid.extrude", &json!({"face": [500, 5, 20], "distance": 10})).is_err());
}
/// Export 3MF; open and insert it as mesh bodies; mesh bodies move and export but refuse
/// solid features.
#[test]
fn threemf_export_open_insert() {
let dir = std::env::temp_dir().join(format!("solidcraft-3mf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [100, 0, 0]}));
let p = dir.join("Parts.3MF");
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
let want = volume(&mut s);
// With face tags it is still a 3MF any reader opens, with the same bodies.
let tagged = dir.join("tagged.3mf");
let r = run(&mut s, "file.export", json!({"path": tagged.to_string_lossy(), "format": "3mf-tagged"}));
assert_eq!(r["format"], "ThreeMfTagged", "{r}");
let mut t = Session::default();
let r = run(&mut t, "doc.open", json!({"path": tagged.to_string_lossy()}));
assert_eq!(r["bodies"].as_array().unwrap().len(), 2, "{r}");
assert!(rel(volume(&mut t), want) < 2e-3, "{} vs {want}", volume(&mut t));
let mut m = Session::default();
let r = run(&mut m, "doc.open", json!({"path": p.to_string_lossy()}));
assert_eq!(r["bodies"].as_array().unwrap().len(), 2, "{r}");
assert_eq!(m.doc.features[0].kind.type_name(), "MeshFeature");
assert!(rel(volume(&mut m), want) < 2e-3, "{} vs {want}", volume(&mut m));
let meas = run(&mut m, "inspect.measure", json!({}));
assert!(meas["bodies"][0]["face_types"]["mesh"].as_u64().unwrap() >= 12, "{meas}");
let e = m.execute("solid.fillet", &json!({"edges": [[0, 0, 10]], "radius": 2})).unwrap_err().to_string();
assert!(e.contains("mesh"), "{e}");
assert!(m.execute("file.export", &json!({"path": dir.join("x.step").to_string_lossy()})).is_err());
let stl = dir.join("again.stl");
run(&mut m, "file.export", json!({"path": stl.to_string_lossy()}));
// Insert the STL into the solid design; names stay unique.
run(&mut s, "file.insert_mesh", json!({"path": stl.to_string_lossy()}));
assert_eq!(s.model.state().bodies.len(), 3);
assert!(rel(volume(&mut s), 2.0 * want) < 2e-3);
assert!(s.execute("file.insert_mesh", &json!({"path": dir.join("x.step").to_string_lossy()})).is_err());
let junk = dir.join("junk.3mf");
std::fs::write(&junk, b"PK\x03\x04 not really").unwrap();
let before = s.doc.clone();
assert!(s.execute("file.insert_mesh", &json!({"path": junk.to_string_lossy()})).is_err());
assert!(s.execute("doc.open", &json!({"path": junk.to_string_lossy()})).is_err());
assert_eq!(*s.doc, *before);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn holes_at_sketch_points_threads_and_components() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10, "name": "Plate"}));
run(&mut s, "sketch.create", json!({"plane": {"face": [30, 20, 10]}, "name": "HolePoints"}));
let mut ids = Vec::new();
for (k, (x, y)) in [(10.0, 10.0), (50.0, 10.0), (50.0, 30.0), (10.0, 30.0)].into_iter().enumerate() {
let id = format!("h{k}");
run(&mut s, "sketch.point", json!({ "point": [x, y], "id": id }));
ids.push(id);
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.hole", json!({"sketch": "HolePoints", "points": ids, "diameter": 5, "thread": "M6", "name": "Holes"}));
let v = volume(&mut s);
assert!(rel(v, 60.0 * 40.0 * 10.0 - 4.0 * PI * 6.25 * 10.0) < 1e-3, "{v}");
let t = run(&mut s, "model.threads", json!({}));
let threads = t["threads"].as_array().unwrap();
assert_eq!(threads.len(), 4, "{t}");
assert_eq!(threads[0]["designation"], "M6");
assert_eq!(threads[0]["internal"], true);
// A cosmetic thread on a shaft; designation from its size.
run(&mut s, "solid.cylinder", json!({"base": [100, 0, 0], "radius": 4, "height": 20, "name": "Shaft", "body_name": "Shaft"}));
let th = run(&mut s, "solid.thread", json!({"face": [104, 0, 10], "length": 12, "from": [100, 0, 0]}));
assert_eq!(th["thread"]["designation"], "M8", "{th}");
assert!((th["thread"]["end"].as_f64().unwrap() - th["thread"]["start"].as_f64().unwrap() - 12.0).abs() < 1e-6, "{th}");
assert!(s.execute("solid.thread", &json!({"face": [104, 0, 10], "designation": "M20"})).is_err());
// Components: features made while one is active belong to it.
let c = run(&mut s, "component.create", json!({"name": "Bracket"}));
let cid = c["component"].as_u64().unwrap();
run(&mut s, "solid.box", json!({"corner": [0, 60, 0], "length": 10, "width": 10, "height": 10, "name": "Block"}));
run(&mut s, "component.activate", json!({"component": "root"}));
let l = run(&mut s, "component.list", json!({}));
let comps = l["components"].as_array().unwrap();
let bracket = comps.iter().find(|x| x["id"] == cid).unwrap();
assert_eq!(bracket["features"], json!(["Block"]), "{l}");
assert_eq!(bracket["bodies"].as_array().map(|a| a.len()), Some(1), "{l}");
let r = run(&mut s, "component.from_bodies", json!({"bodies": ["Shaft"]}));
assert_eq!(r["components"].as_array().map(|a| a.len()), Some(1));
// Saved and loaded with the components.
let text = s.doc.to_json();
let back = solidcraft_doc::Document::from_json(&text).unwrap();
assert_eq!(back.components.len(), 2);
let assigned = r["components"][0]["component"].as_u64().unwrap();
let transfer = r["components"][0]["feature"].as_u64().unwrap();
assert!(
matches!(&back.feature(transfer).unwrap().kind, solidcraft_doc::FeatureKind::BodyTransfer { bodies, to, .. } if bodies == &["Shaft"] && *to == assigned)
);
let reopened = Session::new(back);
assert_eq!(reopened.model.state().body("Shaft").unwrap().component, assigned);
assert_eq!(reopened.world_state().unwrap().threads.len(), s.world_state().unwrap().threads.len());
}
#[test]
fn pipe_scale_offset_bounding_and_materials() {
let mut s = Session::default();
// Pipe along an L path (line, arc, line) on XZ.
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Path"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]], "ids": ["l1"]}));
run(&mut s, "sketch.arc.center_point", json!({"center": [30, 10], "start": "l1.end", "end": [40, 10], "id": "a1"}));
run(&mut s, "sketch.line", json!({"points": ["a1.end", [40, 40]], "ids": ["l2"]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.pipe", json!({"path_sketch": "Path", "path": ["l1", "a1", "l2"], "diameter": 4, "wall": 1, "body_name": "Tube"}));
let len = 30.0 + PI * 10.0 / 2.0 + 30.0;
let v = volume(&mut s);
assert!(rel(v, PI * (4.0 - 1.0) * len) < 2e-3, "{v} vs {}", PI * 3.0 * len);
// Bounding solid around it; then scale a box and push one of its faces.
run(&mut s, "solid.bounding_solid", json!({"bodies": ["Tube"], "margin": 1, "body_name": "Stock"}));
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Stock"]}));
let bb = &m["bodies"][0]["bbox"];
assert!((bb["min"][1].as_f64().unwrap() + 3.0).abs() < 1e-6 && (bb["max"][1].as_f64().unwrap() - 41.0).abs() < 1e-6, "{bb}");
run(&mut s, "solid.box", json!({"corner": [100, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Cube"}));
run(&mut s, "solid.scale", json!({"bodies": ["Cube"], "factor": 2, "origin": [100, 0, 0]}));
let vc = run(&mut s, "inspect.measure", json!({"bodies": ["Cube"]}))["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(vc, 8000.0) < 1e-9, "{vc}");
run(&mut s, "solid.offset_face", json!({"faces": [[110, 10, 20]], "distance": 5}));
let vc = run(&mut s, "inspect.measure", json!({"bodies": ["Cube"]}))["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(vc, 20.0 * 20.0 * 25.0) < 1e-9, "{vc}");
// Materials and mass.
run(&mut s, "material.assign", json!({"bodies": ["Cube"], "material": "aluminum"}));
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Cube"]}));
assert!((m["bodies"][0]["mass_g"].as_f64().unwrap() - 10_000.0 * 2.7 / 1000.0).abs() < 1e-6, "{m}");
assert_eq!(m["bodies"][0]["material"], "Aluminum");
assert!(s.execute("material.assign", &json!({"bodies": ["Cube"], "material": "unobtainium"})).is_err());
}
/// Regression: deleting a pipe's path sketch left the pipe in the timeline ("unknown sketch").
#[test]
fn deleting_a_path_sketch_deletes_its_pipe() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Path"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]], "ids": ["l1"]}));
run(&mut s, "sketch.finish", json!({}));
let pipe = run(&mut s, "solid.pipe", json!({"path_sketch": "Path", "path": ["l1"], "diameter": 4}));
let deps = run(&mut s, "timeline.dependents", json!({"feature": "Path"}));
assert_eq!(deps["deleted_with_it"].as_array().map(Vec::len), Some(1), "{deps} (pipe {pipe})");
let r = run(&mut s, "timeline.delete", json!({"features": ["Path"]}));
assert_eq!(r["deleted"].as_array().map(Vec::len), Some(2), "{r}");
assert!(s.doc.features.is_empty(), "{:?}", s.doc.features.iter().map(|f| &f.name).collect::<Vec<_>>());
assert!(s.model.results.iter().all(|r| r.error.is_none()));
}
/// Regression: batches were rolled back by undoing as many steps as the undo history grew,
/// which is none once the history is full, leaving their sketches behind.
#[test]
fn checkpoint_restores_with_a_full_undo_history() {
let mut s = Session::default();
for i in 0..MAX_UNDO + 5 {
run(&mut s, "parameters.add", json!({"name": format!("p{i}"), "expression": "1 mm"}));
}
assert_eq!(s.undo.len(), MAX_UNDO);
let labels: Vec<String> = s.undo.iter().map(|u| u.label.clone()).collect();
let doc = s.doc.clone();
let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "TapHole"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 2}));
assert!(s.active_sketch.is_some());
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id}));
assert!(Arc::ptr_eq(&s.doc, &doc) && s.active_sketch.is_none());
assert!(s.doc.find_feature("TapHole").is_none());
assert_eq!(s.undo.iter().map(|u| u.label.clone()).collect::<Vec<_>>(), labels);
// Used up: a second restore is an error, not a jump somewhere else.
assert!(s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).is_err());
// Forgetting one leaves the design alone.
let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Kept"}));
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id, "forget": true}));
assert!(s.doc.find_feature("Kept").is_some());
assert!(s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).is_err());
}
/// Regression (#9746): a checkpoint restored already, or one of more than the 16 kept, was
/// refused with only "no checkpoint N", so a script that restores twice could not tell why.
#[test]
fn a_used_up_or_dropped_checkpoint_says_why() {
let mut s = Session::default();
let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id}));
let used = s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).unwrap_err().to_string();
assert!(used.contains("used up") && used.contains("16"), "{used}");
let first = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();
for _ in 0..MAX_CHECKPOINTS {
run(&mut s, "edit.checkpoint", json!({}));
}
let dropped = s.execute("edit.restore_checkpoint", &json!({"checkpoint": first})).unwrap_err().to_string();
assert!(dropped.contains("16"), "{dropped}");
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": first + 1}));
}
/// Regression (#3242): `file.new` replaced the session and its checkpoints with it, so a
/// batch that failed after `file.new` could not go back to the design it began in.
#[test]
fn a_checkpoint_survives_file_new() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 1.0, "width": 1.0, "height": 1.0}));
let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();
run(&mut s, "file.new", json!({"name": "Replacement"}));
// The volume as SMLib integrates it, to rounding (a unit box measures 1 + 2e-16).
let volume = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN);
run(&mut s, "solid.box", json!({"length": 2.0, "width": 2.0, "height": 2.0}));
assert!((volume(&mut s) - 8.0).abs() < 1e-12);
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id}));
assert!((volume(&mut s) - 1.0).abs() < 1e-12);
// The undo history is the restored design's own: one step back is the empty design.
run(&mut s, "edit.undo", json!({}));
assert!(volume(&mut s).abs() < 1e-12);
}
#[test]
fn components_occurrences_and_world_placement() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Base"}));
// A component, active: its box is authored in its frame.
let c = run(&mut s, "component.create", json!({"name": "Arm", "grounded": false}));
let (cid, occ) = (c["component"].as_u64().unwrap(), c["occurrence"].as_u64().unwrap());
run(&mut s, "solid.box", json!({"corner": [20, 0, 0], "length": 10, "width": 4, "height": 4, "body_name": "ArmBody"}));
run(&mut s, "component.activate", json!({"component": 0}));
let bbox = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({ "bodies": [b] }))["bodies"][0]["bbox"].clone();
assert_eq!(bbox(&mut s, "ArmBody")["min"][0], 20.0);
// Move the occurrence: the world placement follows, the authoring model doesn't change.
run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 50, 0]}));
assert!((bbox(&mut s, "ArmBody")["min"][1].as_f64().unwrap() - 50.0).abs() < 1e-9);
assert_eq!(s.model.state().body("ArmBody").unwrap().mesh().bounds().min.y, 0.0);
// A fillet picked in the world, while the component is active, lands on its edge.
run(&mut s, "component.activate", json!({"component": "Arm"}));
run(&mut s, "solid.fillet", json!({"edges": [[25, 54, 4]], "radius": 1}));
let v = run(&mut s, "inspect.measure", json!({"bodies": ["ArmBody"]}))["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(v, 160.0 - (1.0 - PI / 4.0) * 10.0) < 1e-4, "{v}");
run(&mut s, "component.activate", json!({"component": 0}));
// Instances share the contents; a copy is independent.
run(&mut s, "occurrence.copy", json!({"component": cid, "translate": [0, 20, 0]}));
let w = s.world_state().unwrap();
assert_eq!(w.bodies.len(), 3, "{:?}", w.bodies.iter().map(|b| &b.name).collect::<Vec<_>>());
let pn = run(&mut s, "component.paste_new", json!({"component": cid, "translate": [0, -30, 0]}));
assert_eq!(pn["features"].as_array().map(|a| a.len()), Some(2));
assert_eq!(s.world_state().unwrap().bodies.len(), 4);
// Ground stops moves; pending moves show until captured or reverted.
run(&mut s, "occurrence.ground", json!({"occurrence": occ}));
assert!(s.execute("occurrence.move", &json!({"occurrence": occ, "translate": [1, 0, 0]})).is_err());
run(&mut s, "occurrence.ground", json!({"occurrence": occ, "grounded": false}));
run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 0, 5], "capture": false}));
assert!((bbox(&mut s, "ArmBody")["min"][2].as_f64().unwrap() - 5.0).abs() < 1e-9);
run(&mut s, "component.revert_position", json!({}));
assert!(bbox(&mut s, "ArmBody")["min"][2].as_f64().unwrap().abs() < 1e-9);
run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 0, 5], "capture": false}));
run(&mut s, "component.capture_position", json!({}));
assert!(s.pending_moves.is_empty());
assert!((bbox(&mut s, "ArmBody")["min"][2].as_f64().unwrap() - 5.0).abs() < 1e-9);
// A component placed twice gets a body in both instances, placed by the placement named or
// active: with neither, the move is refused and names the parameter that would settle it.
let document = s.doc.to_json();
let pending = s.pending_moves.clone();
let error = s.execute("component.move_bodies", &json!({"bodies": ["Base"], "component": "Arm"})).unwrap_err();
assert!(error.to_string().contains("placed more than once") && error.to_string().contains("`component_path`"), "{error}");
assert_eq!(s.doc.to_json(), document);
assert_eq!(s.pending_moves, pending);
// Placed by the first placement, the body stays where it is in the world there.
run(&mut s, "component.move_bodies", json!({"bodies": ["Base"], "component": "Arm", "component_path": [occ]}));
assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, cid);
assert_eq!(bbox(&mut s, "Base")["min"], json!([0.0, 0.0, 0.0]));
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.to_json(), document);
// The independent Paste New result has one placement and can receive it.
let copied = pn["component"].as_u64().unwrap();
run(&mut s, "component.move_bodies", json!({"bodies": ["Base"], "component": copied}));
let l = run(&mut s, "component.list", json!({}));
let arm = l["components"].as_array().unwrap().iter().find(|x| x["id"] == cid).unwrap().clone();
assert!(!arm["bodies"].as_array().unwrap().iter().any(|b| b == "Base"), "{arm}");
let receiver = l["components"].as_array().unwrap().iter().find(|x| x["id"] == copied).unwrap();
assert!(receiver["bodies"].as_array().unwrap().iter().any(|b| b == "Base"), "{receiver}");
assert_eq!(bbox(&mut s, "Base")["min"], json!([0.0, 0.0, 0.0]));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "component.move_sketches", json!({"sketches": ["S1"], "component": cid}));
assert_eq!(s.doc.find_feature("S1").unwrap().component, cid);
// Undo/redo and the timeline work with features in components.
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.find_feature("S1").unwrap().component, 0);
run(&mut s, "edit.redo", json!({}));
run(&mut s, "timeline.roll_to", json!({"position": 1}));
// The ownership boundary is later: before it Base remains the sole root body.
assert_eq!(s.world_state().unwrap().bodies.len(), 1);
assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, 0);
run(&mut s, "timeline.roll_to", json!({}));
// Saved and loaded; older designs get occurrences.
let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert_eq!(back.occurrences.len(), s.doc.occurrences.len());
let mut old: serde_json::Value = serde_json::from_str(&s.doc.to_json()).unwrap();
old.as_object_mut().unwrap().remove("occurrences");
let migrated = solidcraft_doc::Document::from_json(&old.to_string()).unwrap();
assert_eq!(migrated.occurrences.len(), migrated.components.len());
}
#[test]
fn feature_inputs_are_parameters() {
let mut s = Session::default();
run(&mut s, "parameters.change", json!({"name": "w", "expression": "15 mm", "comment": "width"}));
run(&mut s, "solid.box", json!({"length": 10, "width": "w", "height": "1 in", "name": "B"}));
let l = run(&mut s, "parameters.list", json!({}));
let rows = l["parameters"].as_array().unwrap();
let feat: Vec<&Value> = rows.iter().filter(|r| r["source"] == "feature").collect();
assert_eq!(feat.len(), 3, "{l}");
let height = feat.iter().find(|r| r["input"] == "Height").unwrap();
assert!((height["value"].as_f64().unwrap() - 25.4).abs() < 1e-9);
let length_name = feat.iter().find(|r| r["input"] == "Length").unwrap()["name"].as_str().unwrap().to_string();
// A feature parameter changes the feature; other expressions can use it.
run(&mut s, "parameters.change", json!({"name": length_name, "expression": "2 * w"}));
assert!(rel(volume(&mut s), 30.0 * 15.0 * 25.4) < 1e-9);
run(&mut s, "parameters.change", json!({"name": "t", "expression": format!("{length_name} / 3")}));
let t = run(&mut s, "parameters.list", json!({}))["parameters"].as_array().unwrap().iter().find(|r| r["name"] == "t").unwrap()["value"]
.as_f64()
.unwrap();
assert!((t - 10.0).abs() < 1e-9);
// Cycles are refused.
assert!(s.execute("parameters.change", &json!({"name": "w", "expression": "t"})).is_err());
// Favourites, export and import.
run(&mut s, "parameters.favorite", json!({"name": "w"}));
assert_eq!(run(&mut s, "parameters.list", json!({"favorites": true}))["parameters"].as_array().unwrap().len(), 1);
let csv = run(&mut s, "parameters.export", json!({}))["text"].as_str().unwrap().to_string();
assert!(csv.contains("w,mm,15 mm,15,width,true"), "{csv}");
run(&mut s, "parameters.import", json!({"text": "name,unit,expression,comment\nw,mm,20 mm,wider\nnew_p,mm,\"w + 1\","}));
assert!(rel(volume(&mut s), 40.0 * 20.0 * 25.4) < 1e-9);
run(&mut s, "parameters.import", json!({"text": "[{\"name\": \"w\", \"expression\": \"12\"}]"}));
assert!(rel(volume(&mut s), 24.0 * 12.0 * 25.4) < 1e-9);
assert!(s.execute("parameters.import", &json!({"text": "name,expression\nw,1/"})).is_err());
// Saved and reloaded, the names stay.
let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert_eq!(back.features[0].param_names, s.doc.features[0].param_names);
}
#[test]
fn rolling_back_and_forward_leaves_no_projection_warnings() {
let mut s = Session::default();
s.run_script(&crate::sample::script()).unwrap();
let warnings = |s: &Session| -> Vec<String> {
s.doc.features.iter().filter_map(|f| s.model.result(f.id).and_then(|r| r.warning.clone()).map(|w| format!("{}: {w}", f.name))).collect()
};
assert!(warnings(&s).is_empty(), "{:?}", warnings(&s));
for pos in 0..s.doc.features.len() {
run(&mut s, "timeline.roll_to", json!({ "position": pos }));
run(&mut s, "timeline.roll_to", json!({}));
assert!(warnings(&s).is_empty(), "after rolling to {pos}: {:?}", warnings(&s));
}
}
/// Export STEP, validate the file, read it back: no warnings, same volume, area and faces.
fn step_round_trip(s: &mut Session, tag: &str) -> solidcraft_kernel::StepImport {
let p = std::env::temp_dir().join(format!("solidcraft-steprt-{tag}-{}.step", std::process::id()));
run(s, "file.export", json!({"path": p.to_string_lossy()}));
let text = std::fs::read_to_string(&p).unwrap();
let _ = std::fs::remove_file(&p);
solidcraft_kernel::step_validate(&text).unwrap();
assert_eq!(solidcraft_kernel::step_orientation_errors(&text).unwrap(), Vec::<String>::new());
assert!(text.contains("AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF"));
let imp = solidcraft_kernel::step_import(&text).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
imp
}
#[test]
fn sample_plate_step_round_trip() {
let mut s = Session::default();
s.run_script(&crate::sample::script()).unwrap();
let imp = step_round_trip(&mut s, "sample");
let st = s.world_state().unwrap();
assert_eq!(imp.bodies.len(), st.bodies.len());
for (a, b) in st.bodies.iter().zip(&imp.bodies) {
assert_eq!(a.name, b.name);
let (ma, mb) = (solidcraft_kernel::measure(&a.body).unwrap(), solidcraft_kernel::measure(&b.body).unwrap());
assert!(rel(mb.volume, ma.volume) < 1e-4, "{} vs {}", mb.volume, ma.volume);
assert!(rel(mb.area, ma.area) < 1e-4, "{} vs {}", mb.area, ma.area);
assert!(b.file_faces <= a.body.face_count() && b.file_faces >= ma.merged.faces.min(a.body.face_count()));
assert_eq!(mb.merged.faces, ma.merged.faces);
}
}
/// Bodies export in the colour they are shown in: a material's look, an appearance over it,
/// none for the default; and colours read from a STEP file survive the next export.
#[test]
fn material_and_appearance_colours_export_to_step() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "BrassBox"}));
run(&mut s, "solid.box", json!({"corner": [20, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "RedAbs"}));
run(&mut s, "solid.box", json!({"corner": [40, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Plain"}));
run(&mut s, "material.assign", json!({"bodies": ["BrassBox"], "material": "Brass"}));
run(&mut s, "material.assign", json!({"bodies": ["RedAbs"], "material": "ABS Plastic"}));
run(&mut s, "appearance.assign", json!({"bodies": ["RedAbs"], "color": "#d01c1c"}));
assert!(s.execute("appearance.assign", &json!({"bodies": ["RedAbs"], "color": "#12"})).is_err());
let rgb = |c: [u8; 3]| c.map(|x| x as f32 / 255.0);
let want =
[("BrassBox", Some(rgb(solidcraft_doc::material_color("Brass").unwrap()))), ("RedAbs", Some(rgb([0xd0, 0x1c, 0x1c]))), ("Plain", None)];
let same = |a: Option<[f32; 3]>, b: Option<[f32; 3]>| match (a, b) {
(Some(a), Some(b)) => a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3),
(None, None) => true,
_ => false,
};
let check = |imp: &solidcraft_kernel::StepImport| {
for (name, c) in want {
let b = imp.bodies.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("no body {name}"));
assert!(same(b.body.color(), c), "{name}: {:?} vs {c:?}", b.body.color());
}
};
check(&step_round_trip(&mut s, "colours"));
// Open the export and export again: the file's colours are kept.
let p = std::env::temp_dir().join(format!("solidcraft-colours-{}.step", std::process::id()));
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
let mut s2 = Session::default();
run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()}));
let _ = std::fs::remove_file(&p);
check(&step_round_trip(&mut s2, "colours2"));
}
/// The OBJ export carries the colours of the bodies: the mesh file names a material library
/// beside it, and the library holds a material per body.
#[test]
fn obj_export_writes_the_colours_of_the_bodies() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Red Box"}));
run(&mut s, "appearance.assign", json!({"bodies": ["Red Box"], "color": "#d03030"}));
let dir = std::env::temp_dir().join(format!("solidcraft-objcolours-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let obj = dir.join("part.obj");
run(&mut s, "file.export", json!({"path": obj.to_string_lossy(), "format": "obj"}));
let text = std::fs::read_to_string(&obj).unwrap();
assert!(text.contains("\nmtllib part.mtl\n"), "{text}");
let mtl = std::fs::read_to_string(dir.join("part.mtl")).unwrap();
assert!(mtl.contains("\nnewmtl Red_Box\n"), "{mtl}");
assert!(mtl.contains("Kd 0.816 0.188 0.188"), "{mtl}");
let _ = std::fs::remove_dir_all(&dir);
}
/// Face appearances and see-through bodies export: STEP styles on the faces with a
/// transparency, read back as face colours.
#[test]
fn face_colours_and_opacity_export() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Cube"}));
run(&mut s, "appearance.assign", json!({"bodies": ["Cube"], "color": "#2040c0", "opacity": 0.5}));
run(&mut s, "appearance.assign", json!({"faces": [[5, 5, 10]], "color": "#ff0000"}));
let imp = step_round_trip(&mut s, "facecol");
let b = &imp.bodies[0];
let paint = b.body.paint().expect("paint read back");
assert!((paint.opacity - 0.5).abs() < 1e-3, "{paint:?}");
let faces = b.body.faces(0.01).unwrap();
let top = faces.iter().position(|f| (f.centroid.z - 10.0).abs() < 1e-6).unwrap();
assert_eq!(paint.faces.len(), 1, "{paint:?}");
assert_eq!(paint.faces[0].face, top);
assert!((paint.faces[0].color[0] - 1.0).abs() < 1e-3 && paint.faces[0].color[1].abs() < 1e-3, "{paint:?}");
// Opened again, the face keeps its colour (shown and exported).
let p = std::env::temp_dir().join(format!("solidcraft-facecol-{}.step", std::process::id()));
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
let mut s2 = Session::default();
run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()}));
let _ = std::fs::remove_file(&p);
let st = s2.world_state().unwrap();
let looks = s2.doc.face_colors(&st.bodies[0]);
assert_eq!(looks.len(), 1);
assert_eq!(looks[0].1.color, [255, 0, 0]);
}
/// IGES: a design exports as IGES and the file opens again as an Import feature with the same
/// bodies, names and colours.
#[test]
fn iges_export_and_open() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "body_name": "Plate"}));
run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [10, 10, 5], "body_name": "Pin"}));
run(&mut s, "appearance.assign", json!({"bodies": ["Pin"], "color": "#ff0000"}));
let want: Vec<f64> = s.world_state().unwrap().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect();
let p = std::env::temp_dir().join(format!("solidcraft-iges-{}.igs", std::process::id()));
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
let mut s2 = Session::default();
run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()}));
let _ = std::fs::remove_file(&p);
let st = s2.world_state().unwrap();
let names: Vec<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["Plate", "Pin"]);
for (b, v) in st.bodies.iter().zip(&want) {
assert!(rel(solidcraft_kernel::measure(&b.body).unwrap().volume, *v) < 1e-4);
}
assert_eq!(st.bodies[1].body.color(), Some([1.0, 0.0, 0.0]));
}
/// Split Body by a face of another body (its surface extended): a box cut by a cylinder's
/// side into the core and the rest; volumes add up exactly.
#[test]
fn split_body_by_a_face() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"}));
run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 40, "base": [5, 10, -5], "body_name": "Tool"}));
run(&mut s, "solid.split_body", json!({"body": "Block", "tool": {"body": "Tool", "point": [9, 10, 10]}}));
let st = s.world_state().unwrap();
let mut v: Vec<f64> =
st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect();
v.sort_by(f64::total_cmp);
let core = PI * 16.0 * 30.0;
assert!(v.len() == 2 && rel(v[0], core) < 1e-3 && rel(v[1], 6000.0 - core) < 1e-3, "{v:?}");
assert!(s.execute("solid.split_body", &json!({"body": "Block", "tool": {"body": "Tool", "point": [100, 0, 0]}})).is_err());
}
/// Split Body by a sketch line (#1552): the plane through the line along the sketch's normal
/// splits a box; the split follows the line when the sketch changes, the design saves the line,
/// and anything but a straight line of a sketch is refused.
#[test]
fn split_body_by_a_sketch_line() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"}));
let sk = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap();
run(&mut s, "sketch.line", json!({"points": [[4, -5], [4, 25]], "ids": ["cut"]}));
run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 2, "id": "c"}));
run(&mut s, "sketch.finish", json!({}));
let volumes = |s: &Session| {
let st = s.world_state().unwrap();
let mut v: Vec<f64> =
st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect();
v.sort_by(f64::total_cmp);
v
};
for bad in [
json!({"body": "Block", "sketch": sk, "line": "c"}),
json!({"body": "Block", "sketch": sk}),
json!({"body": "Block", "sketch": 999, "line": "cut"}),
] {
assert!(s.execute("solid.split_body", &bad).is_err(), "{bad}");
}
run(&mut s, "solid.split_body", json!({"body": "Block", "sketch": sk, "line": "cut"}));
let v = volumes(&s);
assert!(v.len() == 2 && rel(v[0], 2400.0) < 1e-6 && rel(v[1], 3600.0) < 1e-6, "{v:?}");
// The split follows the line.
run(&mut s, "sketch.edit", json!({"sketch": sk}));
run(&mut s, "sketch.move_point", json!({"point": "cut.start", "to": [2, -5]}));
run(&mut s, "sketch.move_point", json!({"point": "cut.end", "to": [2, 25]}));
run(&mut s, "sketch.finish", json!({}));
let v = volumes(&s);
assert!(v.len() == 2 && rel(v[0], 1200.0) < 1e-6 && rel(v[1], 4800.0) < 1e-6, "{v:?}");
// The design keeps the sketch and the line.
let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
let split = saved["features"].as_array().and_then(|f| f.iter().find(|f| f["type"] == "split")).cloned().unwrap();
assert_eq!((split["sketch"].as_u64(), split["line"].as_str()), (Some(sk), Some("cut")), "{split}");
}
/// Fillet types: chord length (radius from the face angle) and a radius varying along the
/// edge; volumes from the removed material.
#[test]
fn chord_and_variable_fillets() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"}));
run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 4, "type": "chord"}));
let r = 4.0 / 2f64.sqrt();
let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume;
assert!(rel(v, 6000.0 - (1.0 - PI / 4.0) * r * r * 20.0) < 1e-4, "{v}");
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"}));
run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 5, "start": [10, 0, 30]}));
let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume;
let removed = (1.0 - PI / 4.0) * 20.0 * (4.0 + 10.0 + 25.0) / 3.0;
assert!(rel(v, 6000.0 - removed) < 1e-4, "{v}");
assert!(s.execute("solid.fillet", &json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable"})).is_err());
// Down to zero at the far end: the round closes to the corner.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"}));
run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 4, "type": "variable", "radius2": 0, "start": [10, 0, 30]}));
let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume;
assert!(rel(v, 6000.0 - (1.0 - PI / 4.0) * 20.0 * 16.0 / 3.0) < 1e-4, "{v}");
// A radius through a middle point (a user parameter), straight between: 2 → 4 → 2.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"}));
run(&mut s, "parameters.add", json!({"name": "waist", "expression": "4 mm"}));
run(
&mut s,
"solid.fillet",
json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 2, "start": [10, 0, 30], "mid": [[0.5, "waist"]]}),
);
let vol = |s: &Session| solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume;
let removed = 2.0 * (1.0 - PI / 4.0) * 10.0 * (4.0 + 8.0 + 16.0) / 3.0;
assert!(rel(vol(&s), 6000.0 - removed) < 1e-4, "{}", vol(&s));
// The middle radius follows its parameter.
run(&mut s, "parameters.change", json!({"name": "waist", "expression": "3 mm"}));
let removed = 2.0 * (1.0 - PI / 4.0) * 10.0 * (4.0 + 6.0 + 9.0) / 3.0;
assert!(rel(vol(&s), 6000.0 - removed) < 1e-4, "{}", vol(&s));
assert!(
s.execute(
"solid.fillet",
&json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 2, "start": [10, 0, 30], "mid": [[1.5, 3]]})
)
.is_err()
);
}
/// Components export as a STEP assembly: products, occurrences, placements.
#[test]
fn components_export_as_step_assembly() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "name": "Plate"}));
run(&mut s, "component.create", json!({"name": "Pin"}));
run(&mut s, "solid.cylinder", json!({"radius": 2, "height": 10, "base": [5, 5, 5]}));
run(&mut s, "occurrence.copy", json!({"component": "Pin", "translate": [20, 0, 0]}));
let want: f64 = s.world_state().unwrap().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum();
let imp = step_round_trip(&mut s, "asm");
assert_eq!(imp.bodies.len(), 3, "{:?}", imp.bodies.iter().map(|b| &b.name).collect::<Vec<_>>());
let got: f64 = imp.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum();
assert!(rel(got, want) < 1e-4, "{got} vs {want}");
let root = &imp.tree[0];
assert_eq!(root.children.len(), 2);
assert!(root.children.iter().all(|c| c.name == "Pin"));
// The second pin sits 20 mm along X from the first.
let xs: Vec<f64> = imp
.bodies
.iter()
.filter(|b| b.path.last().is_some_and(|p| p == "Pin"))
.map(|b| solidcraft_kernel::measure(&b.body).unwrap().centroid.x)
.collect();
assert_eq!(xs.len(), 2);
assert!(((xs[0] - xs[1]).abs() - 20.0).abs() < 1e-6, "{xs:?}");
}
/// A face extrude follows its face when earlier features change.
#[test]
fn face_extrude_follows_edits() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "name": "Base"}));
run(&mut s, "solid.extrude", json!({"face": [20, 15, 20], "distance": 10, "operation": "join", "name": "Pad"}));
assert!(rel(volume(&mut s), 40.0 * 30.0 * 30.0) < 1e-6);
run(&mut s, "timeline.edit", json!({"feature": "Base", "set": {"height": "25", "length": "50"}}));
assert!(rel(volume(&mut s), 50.0 * 30.0 * 35.0) < 1e-6, "{}", volume(&mut s));
// A face revolved about a line: Pappus (area × centroid path).
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let before = volume(&mut s);
run(
&mut s,
"solid.revolve",
json!({"face": [40, 15, 10], "axis": {"origin": [40, 0, 30], "dir": [0, 1, 0]}, "angle": "90 deg", "operation": "new"}),
);
let added = volume(&mut s) - before;
let want = 30.0 * 20.0 * 20.0 * PI / 2.0;
assert!(rel(added, want) < 1e-4, "{added} vs {want}");
}
/// Appearances on faces, bodies and components: face > body > component > material.
#[test]
fn appearances_by_face_body_and_component() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Root"}));
run(&mut s, "component.create", json!({"name": "Case"}));
run(&mut s, "solid.box", json!({"corner": [20, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Shell"}));
run(&mut s, "component.activate", json!({"component": "root"}));
let lib = run(&mut s, "appearance.library", json!({}));
assert!(lib["appearances"].as_array().is_some_and(|a| a.len() >= 15 && a.iter().any(|x| x["name"] == "Glass - Clear")));
let look = |s: &mut Session, b: &str| run(s, "appearance.list", json!({"body": b}))["body"].clone();
// Material, then component, then body.
run(&mut s, "material.assign", json!({"bodies": ["Shell"], "material": "Brass"}));
assert_eq!(look(&mut s, "Shell")["appearance"]["name"], "Brass");
run(&mut s, "appearance.assign", json!({"components": ["Case"], "appearance": "ABS - Blue"}));
assert_eq!(look(&mut s, "Shell")["appearance"]["name"], "ABS - Blue");
assert!(look(&mut s, "Root")["appearance"].is_null(), "root bodies have no component look");
run(&mut s, "appearance.assign", json!({"bodies": ["Shell"], "color": [255, 0, 0], "opacity": 0.5}));
let l = look(&mut s, "Shell");
assert_eq!((l["appearance"]["color"].as_str(), l["appearance"]["opacity"].as_f64()), (Some("#ff0000"), Some(0.5)), "{l}");
// A face: the top of Shell.
run(&mut s, "appearance.assign", json!({"faces": [[25, 5, 10]], "appearance": "Glass - Clear"}));
let l = look(&mut s, "Shell");
let faces = l["faces"].as_array().cloned().unwrap_or_default();
assert_eq!(faces.len(), 1, "{l}");
assert_eq!(faces[0]["appearance"]["name"], "Glass - Clear");
// Clearing goes back down the chain.
run(&mut s, "appearance.assign", json!({"faces": [[26, 6, 10]]}));
assert_eq!(look(&mut s, "Shell")["faces"].as_array().map(Vec::len), Some(0), "cleared by another point on the same face");
run(&mut s, "appearance.assign", json!({"bodies": ["Shell"], "color": null}));
assert_eq!(look(&mut s, "Shell")["appearance"]["name"], "ABS - Blue");
run(&mut s, "appearance.assign", json!({"components": ["Case"]}));
assert_eq!(look(&mut s, "Shell")["appearance"]["name"], "Brass");
// Saved and opened again.
run(&mut s, "appearance.assign", json!({"faces": [[5, 5, 10]], "color": "#00ff00"}));
let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert_eq!(back.appearances, s.doc.appearances);
assert!(s.execute("appearance.assign", &json!({"bodies": ["Shell"], "appearance": "Unobtainium"})).is_err());
assert!(s.execute("appearance.assign", &json!({"color": "#ffffff"})).is_err(), "no target");
assert!(s.execute("appearance.assign", &json!({"faces": [[500, 500, 500]], "color": "#ffffff"})).is_err(), "no face there");
}
/// The evaluation cache gives exactly what evaluating from scratch gives, through edits,
/// suppression, roll-back, undo and redo.
#[test]
fn cached_evaluation_matches_from_scratch() {
let mut s = Session::default();
s.run_script(&crate::sample::script()).unwrap();
run(
&mut s,
"solid.pattern.rectangular",
json!({"bodies": ["Plate"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 100, "dir2": [0, 1, 0], "count2": 2, "spacing2": 70}),
);
run(&mut s, "solid.box", json!({"corner": [-50, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Side"}));
let same = |s: &Session, what: &str| {
let mut fresh = solidcraft_doc::Model::new();
fresh.no_cache = true;
fresh.evaluate(&s.doc);
let errs = |m: &solidcraft_doc::Model| m.results.iter().map(|r| (r.id, r.error.clone(), r.skipped)).collect::<Vec<_>>();
assert_eq!(errs(&s.model), errs(&fresh), "{what}: feature results");
let shape = |st: &solidcraft_doc::ModelState| {
st.bodies
.iter()
.map(|b| {
let m = solidcraft_kernel::measure(&b.body).unwrap();
// Volume and area to 1e-9: two evaluations from scratch differ in the last
// bits too (the kernel's tessellation is not bit-for-bit repeatable).
(b.name.clone(), b.feature, (m.volume * 1e6).round(), (m.area * 1e6).round(), m.faces, m.edges, m.vertices, m.merged.faces)
})
.collect::<Vec<_>>()
};
assert_eq!(shape(&s.model.state()), shape(&fresh.state()), "{what}: bodies");
assert_eq!(s.model.state().sketches.len(), fresh.state().sketches.len(), "{what}: sketches");
};
// Two evaluations from scratch agree to the same precision.
let mut a = solidcraft_doc::Model::new();
a.no_cache = true;
a.evaluate(&s.doc);
let mut b = solidcraft_doc::Model::new();
b.no_cache = true;
b.evaluate(&s.doc);
let vols = |m: &solidcraft_doc::Model| {
m.state().bodies.iter().map(|x| (solidcraft_kernel::measure(&x.body).unwrap().volume * 1e6).round()).collect::<Vec<_>>()
};
assert_eq!(vols(&a), vols(&b));
same(&s, "built");
let hits = |s: &Session| s.model.cache.lock().map(|c| c.hits).unwrap_or(0);
for (step, (id, p)) in [
("parameters.change", json!({"name": "width", "expression": "90 mm"})),
("parameters.change", json!({"name": "width", "expression": "80 mm"})),
("parameters.change", json!({"name": "thickness", "expression": "10 mm"})),
("edit.undo", json!({})),
("edit.redo", json!({})),
("timeline.suppress", json!({"feature": "Holes", "suppressed": true})),
("timeline.suppress", json!({"feature": "Holes", "suppressed": false})),
("timeline.roll_to", json!({"position": 6})),
("timeline.roll_to", json!({})),
("edit.undo", json!({})),
("edit.undo", json!({})),
]
.into_iter()
.enumerate()
{
let before = hits(&s);
run(&mut s, id, p.clone());
same(&s, &format!("step {step}: {id} {p}"));
// Setting the width back solves the sketch again from its current state; the
// features after it see the same geometry and reuse their results. So does undo.
if step == 1 || step == 3 {
assert!(hits(&s) > before, "step {step} reuses the earlier results");
}
}
}
/// A fillet keeps its edge when an earlier sketch dimension resizes the body (QA s06).
#[test]
fn fillet_follows_its_edge_after_an_upstream_resize() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
let bottom = r["curves"][0].as_str().unwrap_or_default().to_string();
let d = run(&mut s, "sketch.dimension", json!({"entities": [bottom], "value": 40}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10}));
run(&mut s, "solid.fillet", json!({"edges": [[40, 15, 10]], "radius": 2}));
let v = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(0.0);
let strip = (4.0 - std::f64::consts::PI) * 30.0;
assert!((v(&mut s) - (12000.0 - strip)).abs() < 0.05, "{}", v(&mut s));
let name = d["param"].as_str().or_else(|| d["name"].as_str()).map(str::to_string).unwrap_or_else(|| "d1".into());
run(&mut s, "parameters.change", json!({"name": name, "expression": "60"}));
// The right top edge, now at x = 60: 18000 less the same 30 mm strip.
assert!((v(&mut s) - (18000.0 - strip)).abs() < 0.05, "{}", v(&mut s));
let fillet = s.doc.features.last().map(|f| f.id).unwrap_or(0);
assert!(s.model.result(fillet).and_then(|r| r.warning.clone()).is_none(), "followed without a warning");
}
mod naming {
use serde_json::{Value, json};
use super::run;
use crate::Session;
fn volume(s: &mut Session) -> f64 {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(0.0)
}
fn warning(s: &Session, name: &str) -> Option<String> {
let id = s.doc.find_feature(name).map(|f| f.id)?;
s.model.result(id).and_then(|r| r.warning.clone())
}
/// The reference feature `name` failed on, asking for it to be picked again.
fn reselect(s: &Session, name: &str) -> Option<String> {
let id = s.doc.find_feature(name).map(|f| f.id)?;
let error = s.model.result(id).and_then(|r| r.error.clone())?;
solidcraft_doc::reselect_parts(&error).filter(|(feature, _)| *feature == name).map(|(_, reference)| reference.to_string())
}
/// A 40 x 30 x 10 block (sketch S: l1…l4 counter-clockwise from the origin), a hole H, a
/// fillet on the right top edge.
fn block() -> Session {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 40}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Block"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "H"}));
run(&mut s, "sketch.circle.center", json!({"center": [12, 15], "radius": 4}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "H", "distance": 10, "operation": "cut", "name": "Hole"}));
run(&mut s, "solid.fillet", json!({"edges": [[40, 15, 10]], "radius": 2, "name": "Round"}));
s
}
const STRIP: f64 = (4.0 - std::f64::consts::PI) * 30.0;
#[test]
fn faces_and_edges_are_named_from_their_history() {
let mut s = block();
let f = run(&mut s, "model.faces", json!({"body": "Body1"}));
let names: Vec<&str> = f["faces"].as_array().into_iter().flatten().filter_map(|x| x["name"].as_str()).collect();
for want in ["F2:start", "F2:top", "F2:side:l1", "F2:side:l2", "F2:side:l3", "F2:side:l4"] {
assert!(names.contains(&want), "{want} in {names:?}");
}
assert!(names.iter().any(|n| n.starts_with("F4:side:c1")), "{names:?}");
assert!(names.iter().any(|n| n.starts_with("F5:blend:")), "{names:?}");
let round = s.doc.find_feature("Round").cloned().unwrap();
assert_eq!(round.edge_names, vec!["F2:side:l2|F2:top".to_string()]);
}
#[test]
fn a_resize_keeps_the_edge() {
let mut s = block();
let d = s.doc.find_feature("S").and_then(|f| f.param_names.first().cloned()).unwrap_or_else(|| "d1".into());
run(&mut s, "parameters.change", json!({"name": d, "expression": "60"}));
assert!((volume(&mut s) - (18000.0 - std::f64::consts::PI * 16.0 * 10.0 - STRIP)).abs() < 0.1, "{}", volume(&mut s));
assert_eq!(warning(&s, "Round"), None);
}
#[test]
fn suppress_and_reorder_upstream_keep_the_edge() {
let mut s = block();
let v = volume(&mut s);
run(&mut s, "timeline.suppress", json!({"feature": "Hole", "suppressed": true}));
assert!((volume(&mut s) - (12000.0 - STRIP)).abs() < 0.1);
assert_eq!(warning(&s, "Round"), None);
run(&mut s, "timeline.suppress", json!({"feature": "Hole", "suppressed": false}));
assert!((volume(&mut s) - v).abs() < 1e-6);
// The hole after the fillet: same part, same edge.
run(&mut s, "timeline.reorder", json!({"feature": "Hole", "position": 4}));
assert!((volume(&mut s) - v).abs() < 0.1, "{} {v}", volume(&mut s));
assert_eq!(warning(&s, "Round"), None);
}
/// The notch leaves the filleted edge in two pieces: neither is the edge, so the fillet fails,
/// asking for its edge again, and never rounds the piece nearest the pick.
#[test]
fn a_split_edge_fails_the_fillet_asking_for_the_edge_again() {
let mut s = block();
// Upstream of the fillet, a notch through the middle of the filleted edge.
run(&mut s, "timeline.roll_to", json!({"feature": "Hole"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "N"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [36, 12], "p1": [44, 18]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "N", "distance": 10, "operation": "cut", "name": "Notch"}));
run(&mut s, "timeline.roll_to", json!({}));
assert_eq!(reselect(&s, "Round").as_deref(), Some("F2:side:l2|F2:top"));
}
/// The face the filleted edge bounded is gone with its sketch line: the fillet fails, asking
/// for its edge again.
#[test]
fn a_removed_segment_fails_the_fillet_asking_for_the_edge_again() {
let mut s = block();
// Replace the right side (l2) of the rectangle with a new line: the face it made is gone.
let sk = s.doc.find_feature("S").map(|f| f.id).unwrap();
run(&mut s, "sketch.edit", json!({"sketch": sk}));
run(&mut s, "sketch.delete", json!({"entities": ["l2"]}));
run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]], "ids": ["right"]}));
let r: Result<Value, _> = s.execute("sketch.finish", &json!({}));
assert!(r.is_ok() || r.is_err());
assert_eq!(reselect(&s, "Round").as_deref(), Some("F2:side:l2|F2:top"));
}
fn face_names(s: &mut Session, body: &str) -> Vec<String> {
let f = run(s, "model.faces", json!({ "body": body }));
f["faces"].as_array().into_iter().flatten().filter_map(|x| x["name"].as_str().map(str::to_string)).collect()
}
#[test]
fn primitives_revolves_and_pattern_copies_are_named() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "B"}));
let n = face_names(&mut s, "B");
for want in ["F1:+x", "F1:-x", "F1:+y", "F1:-y", "F1:+z", "F1:-z"] {
assert!(n.contains(&want.to_string()), "{want} in {n:?}");
}
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["B"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20}));
let bodies: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
let copy = face_names(&mut s, &bodies[2]);
assert!(copy.iter().all(|x| x.starts_with("F1:") && x.contains("@F2.")), "{copy:?}");
// A revolved ring: the section's four lines name the four faces.
let mut r = Session::default();
run(&mut r, "sketch.create", json!({"plane": "XZ"}));
run(&mut r, "sketch.line", json!({"points": [[10, 0], [15, 0], [15, 5], [10, 5]], "closed": true, "ids": ["a", "b", "c", "d"]}));
run(&mut r, "sketch.finish", json!({}));
run(&mut r, "solid.revolve", json!({"axis": "y", "angle": "270 deg"}));
let body = r.model.state().bodies[0].name.clone();
let n = face_names(&mut r, &body);
for want in ["F2:side:a", "F2:side:b", "F2:side:c", "F2:side:d", "F2:start", "F2:end"] {
assert!(n.iter().any(|x| x.starts_with(want)), "{want} in {n:?}");
}
}
#[test]
fn a_sketch_on_a_face_stays_on_that_face() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Block"}));
run(&mut s, "sketch.create", json!({"plane": {"face": [30, 15, 10]}, "name": "Top"}));
run(&mut s, "sketch.circle.center", json!({"center": [30, 15], "radius": 3}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Top", "distance": 5, "operation": "join", "name": "Peg"}));
let top = |s: &mut Session| run(s, "inspect.measure", json!({}))["bodies"][0]["bbox"]["max"][2].as_f64().unwrap_or(0.0);
assert!((top(&mut s) - 15.0).abs() < 1e-6);
let attached = |s: &Session| s.model.state().sketch(s.doc.find_feature("Top").unwrap().id).map(|sketch| sketch.plane.origin.z);
assert_eq!(attached(&s), Some(10.));
run(&mut s, "timeline.edit", json!({"feature":"Block","set":{"extent":{"distance":"12"}}}));
assert_eq!(attached(&s), Some(12.));
assert!((top(&mut s) - 17.).abs() < 1e-6);
run(&mut s, "edit.undo", json!({}));
assert_eq!(attached(&s), Some(10.));
assert!((top(&mut s) - 15.).abs() < 1e-6);
let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
let mut model = solidcraft_doc::Model::new();
model.evaluate(&reopened);
assert_eq!(model.state().sketch(reopened.find_feature("Top").unwrap().id).unwrap().plane.origin.z, 10.);
assert!((model.state().bodies[0].mesh().bounds().max.z - 15.).abs() < 1e-6);
// A format-10 attachment has only the face name that build worked out from geometry, and
// no strong anchor: that name finds no face today. The sketch fails, asking for its face
// again, and so does the peg on it; the block builds.
let mut old = (*s.doc).clone();
let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, name, .. }, sketch } =
&mut old.features.iter_mut().find(|f| f.name == "Top").unwrap().kind
else {
panic!("fixture must contain a face sketch");
};
*anchor = None;
let saved = name.clone().unwrap();
for link in &mut sketch.links {
if link.auto_face {
link.auto_face = false;
link.face_name = name.clone();
}
}
old.format = "solidcraft/10".into();
let legacy = Session::new(solidcraft_doc::Document::from_json(&old.to_json()).unwrap());
let error = |s: &Session, name: &str| s.model.results.iter().find(|r| r.id == s.doc.find_feature(name).unwrap().id).unwrap().error.clone();
let reference = format!("{}{saved}", solidcraft_doc::naming::LEGACY_MARK);
assert_eq!(error(&legacy, "Top").as_deref().and_then(solidcraft_doc::reselect_parts), Some(("Top", reference.as_str())));
assert!(error(&legacy, "Peg").is_some());
assert!(error(&legacy, "Block").is_none());
// An upstream join that trims the certified face: the attachment stays on what is left
// of it and never follows the substitute roof (see face_tests for a face covered whole).
run(&mut s, "timeline.roll_to", json!({"feature": "Block"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "B"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8, -5], "p1": [45, 35]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "B", "distance": 20, "operation": "join", "name": "Boss"}));
run(&mut s, "timeline.roll_to", json!({}));
let failed = |s: &Session, name: &str| s.model.results.iter().find(|r| r.id == s.doc.find_feature(name).unwrap().id).unwrap().error.is_some();
assert!(!failed(&s, "Top"));
assert!(!failed(&s, "Peg"));
assert_eq!(attached(&s), Some(10.), "the strip of Block's top left beside the boss is still that face");
assert!((top(&mut s) - 20.0).abs() < 1e-6, "{}", top(&mut s));
run(&mut s, "timeline.suppress", json!({"feature":"Boss","suppressed":true}));
assert!(!failed(&s, "Top"));
assert_eq!(attached(&s), Some(10.));
assert!((top(&mut s) - 15.).abs() < 1e-6);
}
#[test]
fn shell_inner_faces_are_named_after_the_walls() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "B"}));
run(&mut s, "solid.shell", json!({"faces": [[20, 15, 20]], "thickness": 2}));
let n = face_names(&mut s, "B");
for want in ["F2:inner:F1:-z", "F2:inner:F1:+x", "F2:inner:F1:-x", "F2:inner:F1:+y", "F2:inner:F1:-y"] {
assert!(n.contains(&want.to_string()), "{want} in {n:?}");
}
}
#[test]
fn shell_and_hole_faces_follow_by_name() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "name": "Base"}));
run(&mut s, "solid.shell", json!({"faces": [[20, 15, 20]], "thickness": 2, "name": "Hollow"}));
let shell = |h: f64| 40.0 * 30.0 * h - 36.0 * 26.0 * (h - 2.0);
assert!((volume(&mut s) - shell(20.0)).abs() < 0.5, "{}", volume(&mut s));
// Taller: the picked point is 5 mm under the open face now; its name still finds it.
run(&mut s, "timeline.edit", json!({"feature": "Base", "set": {"height": "25"}}));
assert!((volume(&mut s) - shell(25.0)).abs() < 0.5, "{}", volume(&mut s));
assert_eq!(warning(&s, "Hollow"), None);
let h = s.doc.find_feature("Hollow").map(|f| f.face_names.clone()).unwrap_or_default();
assert_eq!(h, vec!["F1:+z".to_string()]);
}
}
/// Tapped holes take the tap drill (major − pitch); clearance holes the ISO 273 diameter.
#[test]
fn tapped_and_clearance_holes() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10}));
let v0 = volume(&mut s);
run(&mut s, "solid.hole", json!({"position": [10, 15, 10], "thread": "M6"}));
let v1 = volume(&mut s);
assert!(rel(v0 - v1, PI * 2.5 * 2.5 * 10.0) < 1e-3, "{}", v0 - v1);
run(&mut s, "solid.hole", json!({"position": [30, 15, 10], "clearance": "M6"}));
let v2 = volume(&mut s);
assert!(rel(v1 - v2, PI * 3.3 * 3.3 * 10.0) < 1e-3, "{}", v1 - v2);
run(&mut s, "solid.hole", json!({"position": [20, 5, 10], "clearance": "M4", "fit": "close"}));
assert!(rel(v2 - volume(&mut s), PI * 2.15 * 2.15 * 10.0) < 1e-3);
assert!(s.execute("solid.hole", &json!({"position": [20, 25, 10], "clearance": "M7"})).is_err());
assert!(s.execute("solid.hole", &json!({"position": [20, 25, 10]})).is_err());
}
/// In an inch design, a bare length typed into a feature means inches (stored with the unit);
/// lengths with units and angles are left alone.
#[test]
fn bare_lengths_take_the_design_units() {
let mut s = Session::default();
s.doc_mut().units = "in".into();
run(&mut s, "solid.box", json!({"length": 2, "width": "10 mm", "height": 1}));
let m = run(&mut s, "inspect.measure", json!({}));
let max = |i: usize| m["bodies"][0]["bbox"]["max"][i].as_f64().unwrap_or(0.0);
assert!((max(0) - 50.8).abs() < 1e-9 && (max(1) - 10.0).abs() < 1e-9 && (max(2) - 25.4).abs() < 1e-9, "{m}");
let d = s.doc.features[0].param_names[2].clone();
run(&mut s, "parameters.change", json!({"name": d, "expression": "2"}));
let m = run(&mut s, "inspect.measure", json!({}));
assert!((m["bodies"][0]["bbox"]["max"][2].as_f64().unwrap_or(0.0) - 50.8).abs() < 1e-9);
assert_eq!(s.doc.features[0].kind.inputs()[2].1, "2 in");
}
/// Press Pull on a fillet's face changes its radius; on another curved face it offsets it.
#[test]
fn press_pull_on_curved_faces() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.fillet", json!({"edges": [[40, 0, 10]], "radius": 3, "name": "Round"}));
let corner = |r: f64| (4.0 - PI) * r * r / 4.0 * 20.0;
assert!(rel(volume(&mut s), 24000.0 - corner(3.0)) < 1e-4);
// A point on the fillet: the arc's middle.
let c = Vec3::new(37.0, 3.0, 10.0);
let on = c + Vec3::new(1.0, -1.0, 0.0).normalized().unwrap() * 3.0;
let out = run(&mut s, "solid.press_pull", json!({"face": [on.x, on.y, on.z], "distance": 2}));
assert_eq!(out["edited"], "Round", "{out}");
assert!(rel(volume(&mut s), 24000.0 - corner(5.0)) < 1e-4, "{}", volume(&mut s));
// A hole's wall: pulled along its normal (into the hole), the hole gets smaller.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 10}));
let v0 = volume(&mut s);
run(&mut s, "solid.press_pull", json!({"face": [25, 15, 10], "distance": 1}));
let v1 = volume(&mut s);
assert!(rel(v1 - v0, PI * (25.0 - 16.0) * 20.0) < 1e-3, "{v0} {v1}");
// A shell's inner wall behind a fillet (`F3:inner:F2:blend:…`) only names the fillet: it is
// offset like any curved face, not taken for the shell's fillet. Pulled 0.5 into the cavity
// (radius 3 to 2.5), the wall alone moves, stepping in from its tangent neighbours: the
// quarter ring between the radii, 18 high, is added.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20}));
run(&mut s, "solid.fillet", json!({"edges": [[40, 40, 10]], "radius": 5}));
run(&mut s, "solid.shell", json!({"faces": [[20, 20, 20]], "thickness": 2}));
let on = Vec3::new(35.0, 35.0, 10.0) + Vec3::new(1.0, 1.0, 0.0).normalized().unwrap() * 3.0;
let v0 = volume(&mut s);
let out = run(&mut s, "solid.press_pull", json!({"face": [on.x, on.y, on.z], "distance": 0.5}));
assert!(out["name"].as_str().is_some_and(|n| n.starts_with("OffsetFace")) && out.get("edited").is_none(), "{out}");
let ring = PI / 4.0 * (3.0 * 3.0 - 2.5 * 2.5) * 18.0;
// Each volume to the measure's 2e-7.
assert!((volume(&mut s) - v0 - ring).abs() < 4e-7 * v0, "{} vs {ring}", volume(&mut s) - v0);
}
/// #4986: Press Pull on a chamfer's flat face changes the chamfer's distance, as on a fillet's
/// face it changes the radius, rather than extruding the face.
#[test]
fn press_pull_on_a_chamfer_face_edits_the_chamfer() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"}));
let cut = |d: f64| d * d / 2.0 * 20.0;
assert!(rel(volume(&mut s), 24000.0 - cut(3.0)) < 1e-6);
// The chamfer's face runs from (37, 0) to (40, 3); its middle.
let out = run(&mut s, "solid.press_pull", json!({"face": [38.5, 1.5, 10], "distance": 2}));
assert_eq!(out["edited"], "Bevel", "{out}");
assert_eq!(s.doc.features.len(), 2, "no extrude added");
assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{}", volume(&mut s));
// A point on the flat front face 0.02 mm from its edge with the chamfer (which now runs from
// (35, 0) to (40, 5)) is the front face's: it is extruded, the chamfer is left alone.
let mut t = Session::default();
run(&mut t, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut t, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"}));
let out = run(&mut t, "solid.press_pull", json!({"face": [36.98, 0, 10], "distance": 1}));
assert!(out.get("edited").is_none(), "{out}");
assert!(matches!(t.doc.features.last().map(|f| &f.kind), Some(solidcraft_doc::FeatureKind::Extrude { .. })), "an extrude added: {out}");
assert!(
matches!(&t.doc.features[1].kind, solidcraft_doc::FeatureKind::Chamfer { distance, .. } if distance == "3"),
"{:?}",
t.doc.features[1].kind
);
// Too far in (past zero) or too far out: an error, the chamfer as it was.
let on = [39.0, 1.0, 10.0];
for d in [-10.0, 1e9] {
assert!(s.execute("solid.press_pull", &json!({"face": on, "distance": d})).is_err(), "{d}");
assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{d}: {}", volume(&mut s));
}
// An unequal chamfer's first distance changes and its second stays; an angle chamfer keeps
// its angle.
// Each chamfer's face crosses the corner's bisector at legs a, b: (40 - u, u), u = ab / (a + b).
let tan30 = (PI / 6.0).tan();
for (extra, u) in [(json!({"distance2": 4}), 8.0 / 6.0), (json!({"angle": "30 deg"}), 2.0 * tan30 / (1.0 + tan30))] {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let mut p = json!({"edges": [[40, 0, 10]], "distance": 2, "name": "Bevel"});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
run(&mut s, "solid.chamfer", p);
let v0 = volume(&mut s);
let out = run(&mut s, "solid.press_pull", json!({"face": [40.0 - u, u, 10.0], "distance": 1}));
assert_eq!(out["edited"], "Bevel", "{extra}: {out}");
assert_eq!(s.doc.features.len(), 2, "{extra}");
let Some(solidcraft_doc::FeatureKind::Chamfer { distance2, angle, .. }) = s.doc.features.last().map(|f| &f.kind) else { panic!("{extra}") };
assert_eq!(distance2.as_ref().map(|e| e.to_string()), extra.get("distance2").map(|v| v.to_string()), "{extra}");
assert_eq!(angle.as_ref().map(|e| e.to_string()), extra.get("angle").and_then(|v| v.as_str()).map(str::to_string), "{extra}");
assert!(volume(&mut s) < v0 - 1.0, "{extra}: a bigger chamfer cuts more");
}
}
/// A cut in one component leaves other components' bodies alone unless they are named as
/// participants; auto join/cut looks at the active component only.
#[test]
fn booleans_stay_in_their_component() {
let mut s = Session::default();
for (name, x) in [("A", 0), ("B", 20)] {
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": name}));
run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "corner": [x, 0, 0], "body_name": format!("{name}Box")}));
}
// A's box spans x 0…20, B's x 20…40 (in their own frames, both occurrences in place).
run(&mut s, "component.activate", json!({"component": "A"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Slot"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8, 2], "p1": [28, 8]}));
run(&mut s, "sketch.finish", json!({}));
let vol = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["total"]["volume_mm3"].as_f64().unwrap_or(0.0);
assert_eq!(auto_operation(&s, &json!({"sketch": "Slot", "distance": 10})).unwrap(), Some("cut"));
run(&mut s, "solid.extrude", json!({"sketch": "Slot", "distance": 10, "operation": "cut", "name": "Cut"}));
assert!((vol(&mut s, "ABox") - (2000.0 - 12.0 * 6.0 * 10.0)).abs() < 1e-6, "{}", vol(&mut s, "ABox"));
assert!((vol(&mut s, "BBox") - 2000.0).abs() < 1e-6, "B untouched: {}", vol(&mut s, "BBox"));
// Named as a participant, B is cut too.
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Slot", "distance": 10, "operation": "cut", "participants": ["ABox", "BBox"]}));
assert!((vol(&mut s, "BBox") - (2000.0 - 8.0 * 6.0 * 10.0)).abs() < 1e-6, "{}", vol(&mut s, "BBox"));
assert!(s.execute("solid.extrude", &json!({"sketch": "Slot", "distance": 1, "operation": "cut", "participants": ["Nope"]})).is_err());
}
/// #1234: a cut sketched in the root, where there is no body, through a body in each of two
/// components cuts both (the root has nothing of its own to cut). A cut in a component with a
/// body of its own still stays there (`booleans_stay_in_their_component`).
#[test]
fn a_cut_from_a_component_without_bodies_cuts_the_parts_it_meets() {
let mut s = Session::default();
for (name, x) in [("A", 0), ("B", 30)] {
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": name}));
run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "corner": [x, 0, 0], "body_name": format!("{name}Box")}));
}
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Slot"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 2], "p1": [40, 8]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Slot", "distance": 10, "operation": "cut"}));
let vol = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["total"]["volume_mm3"].as_f64().unwrap_or(0.0);
assert!((vol(&mut s, "ABox") - (2000.0 - 10.0 * 6.0 * 10.0)).abs() < 1e-6, "{}", vol(&mut s, "ABox"));
assert!((vol(&mut s, "BBox") - (2000.0 - 10.0 * 6.0 * 10.0)).abs() < 1e-6, "{}", vol(&mut s, "BBox"));
}
/// A unit-less parameter used as a length means the design's units.
#[test]
fn unitless_parameters_used_as_lengths_take_the_design_units() {
let mut s = Session::default();
s.doc_mut().units = "in".into();
run(&mut s, "parameters.add", json!({"name": "w", "expression": "2", "unit": ""}));
run(&mut s, "solid.box", json!({"length": "w", "width": "w * 1", "height": "10 mm"}));
let m = run(&mut s, "inspect.measure", json!({}));
let max = |i: usize| m["bodies"][0]["bbox"]["max"][i].as_f64().unwrap_or(0.0);
assert!((max(0) - 50.8).abs() < 1e-9 && (max(1) - 50.8).abs() < 1e-9 && (max(2) - 10.0).abs() < 1e-9, "{m}");
}
/// A chamfer on a tapered pocket survives parameter edits and undo/redo.
#[test]
fn chamfer_sloped_basin_rim_recomputes() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 100, "width": 60, "height": 30}));
for (name, z, p0, p1) in [("Rim", 30, [20, 4], [80, 50]), ("Floor", 10, [30, 20], [70, 40])] {
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": z, "name": name}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": p0, "p1": p1}));
run(&mut s, "sketch.finish", json!({}));
}
run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Rim"}, {"sketch": "Floor"}], "operation": "cut"}));
run(&mut s, "parameters.add", json!({"name": "rim_chamfer", "expression": "1 mm"}));
let base = volume(&mut s);
run(&mut s, "solid.chamfer", json!({"edges": [[50, 4, 30]], "distance": "rim_chamfer"}));
let expected = |size: f64| {
let wall_slope: f64 = (20.0 - 4.0) / (30.0 - 10.0); // horizontal run / vertical drop
let drop = size / (1.0 + wall_slope.powi(2)).sqrt();
base - 0.5 * size * drop * (60.0 - drop / 3.0)
};
assert!(rel(volume(&mut s), expected(1.0)) < 1e-8);
let edited = run(&mut s, "parameters.change", json!({"name": "rim_chamfer", "expression": "2 mm"}));
assert_eq!(edited["errors"].as_array().unwrap().len(), 0, "{edited}");
assert!(rel(volume(&mut s), expected(2.0)) < 1e-8);
run(&mut s, "edit.undo", json!({}));
assert!(rel(volume(&mut s), expected(1.0)) < 1e-8);
run(&mut s, "edit.redo", json!({}));
assert!(rel(volume(&mut s), expected(2.0)) < 1e-8);
}
/// Chamfers with two distances or a distance and an angle.
#[test]
fn unequal_chamfers() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
// Top front edge: 2 along the top (the face facing up), 4 down the front.
run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 20]], "distance": 2, "distance2": 4}));
assert!(rel(volume(&mut s), 24000.0 - 0.5 * 2.0 * 4.0 * 40.0) < 1e-6, "{}", volume(&mut s));
// Bottom back edge: 3 along the bottom, at 30° from it (down the back face 3·tan 30°).
run(&mut s, "solid.chamfer", json!({"edges": [[20, 30, 0]], "distance": 3, "angle": "30 deg", "flip": true}));
let d2 = 3.0 * (30f64).to_radians().tan();
assert!(rel(volume(&mut s), 24000.0 - 160.0 - 0.5 * 3.0 * d2 * 40.0) < 1e-6, "{}", volume(&mut s));
assert!(s.execute("solid.chamfer", &json!({"edges": [[0, 15, 20]], "distance": 1, "distance2": 2, "angle": "30 deg"})).is_err());
}
/// Unequal chamfers of a cylinder's circular rims: each cross-section is a right triangle
/// revolved about the axis (Pappus: area × the path of its centroid).
#[test]
fn unequal_chamfers_on_circular_rims() {
use std::f64::consts::PI;
let ring = |r: [f64; 3], legs: (f64, f64)| 2.0 * PI * (r[0] + r[1] + r[2]) / 3.0 * 0.5 * legs.0 * legs.1;
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20}));
// The measured volume is of the meshed cylinder: compare what each chamfer takes away.
let full = volume(&mut s);
assert!(rel(full, PI * 100.0 * 20.0) < 1e-3);
// Top rim: 2 across the top (the face facing up), 3 down the wall.
run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": 2, "distance2": 3}));
let top = ring([10.0, 8.0, 10.0], (2.0, 3.0));
assert!(rel(full - volume(&mut s), top) < 5e-3, "{} vs {top}", full - volume(&mut s));
// Bottom rim: 2 along the bottom at 30° from it (flipped: the wall would be first).
run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 0]], "distance": 2, "angle": "30 deg", "flip": true}));
let d2 = 2.0 * 30f64.to_radians().tan();
let bottom = ring([10.0, 8.0, 10.0], (2.0, d2));
assert!(rel(full - volume(&mut s), top + bottom) < 5e-3, "{} vs {}", full - volume(&mut s), top + bottom);
// Flipped on the top rim instead: 2 down the wall, 3 across the top (a different solid).
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": 2, "distance2": 3, "flip": true}));
let flipped = ring([10.0, 7.0, 10.0], (2.0, 3.0));
assert!(rel(full - volume(&mut s), flipped) < 5e-3, "{} vs {flipped}", full - volume(&mut s));
}
/// An enclosure built in the usual order: shell, bosses, then the lip on the rim.
#[test]
fn lip_after_boss() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 30}));
run(&mut s, "solid.shell", json!({"faces": [[40, 25, 30]], "thickness": 2}));
run(&mut s, "plastic.boss", json!({"position": [10, 10, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5}));
run(&mut s, "plastic.boss", json!({"position": [70, 40, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5}));
let v0 = volume(&mut s);
run(&mut s, "plastic.lip", json!({"face": [1, 25, 30], "width": 1, "height": 2}));
// The band inside the rim, 1 wide and 2 high: (78 × 48 − 76 × 46) × 2; the bosses stop
// at z = 14, well under it.
let inside = (78.0 * 48.0 - 76.0 * 46.0) * 2.0;
assert!(rel(volume(&mut s) - v0, inside) < 1e-6, "{}", volume(&mut s) - v0);
// Bosses up to the rim, with ribs, against a wall; lips, grooves and outside rims. None
// reaches the rim's bands, so each lip adds, and the groove (no gap) takes, its band: the
// inside one (78 × 48 − 76 × 46) × 2, the outside one (80 × 50 − 78 × 48) × 2.
let bosses = [
json!({"position": [15, 15, 2], "diameter": 8, "height": 28, "hole_diameter": 3}),
// Ribs out to the inner walls (15 − 4 − 9 = 2), and short of them.
json!({"position": [15, 15, 2], "diameter": 8, "height": 12, "ribs": 4, "rib_thickness": 1.5, "rib_length": 9}),
json!({"position": [15, 15, 2], "diameter": 8, "height": 12, "ribs": 4, "rib_thickness": 1.5, "rib_length": 6}),
json!({"position": [5.5, 25, 2], "diameter": 7, "height": 12, "hole_diameter": 2.5}),
json!({"position": [40, 25, 2], "diameter": 8, "height": 20, "draft": "1 deg", "fillet": 1}),
];
let outside = (80.0 * 50.0 - 78.0 * 48.0) * 2.0;
let lips = [
(json!({"face": [1, 25, 30], "width": 1, "height": 2}), inside),
(json!({"face": [1, 25, 30], "width": 1, "height": 2, "type": "groove"}), -inside),
(json!({"face": [1, 25, 30], "width": 1, "height": 2, "side": "outside"}), outside),
];
for (i, b) in bosses.iter().enumerate() {
for (j, (l, band)) in lips.iter().enumerate() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 30}));
run(&mut s, "solid.shell", json!({"faces": [[40, 25, 30]], "thickness": 2}));
let r = s.execute("plastic.boss", b);
assert!(r.is_ok(), "boss {i}: {r:?}");
let v0 = volume(&mut s);
let r = s.execute("plastic.lip", l);
assert!(r.is_ok(), "boss {i} lip {j}: {r:?}");
assert!(rel(volume(&mut s) - v0, *band) < 1e-6, "boss {i} lip {j}: {} vs {band}", volume(&mut s) - v0);
}
}
}
/// A lip on a rim with a face elsewhere in line with the pick: a notch under the floor whose
/// wall lies in the plane y = 25 through the picked point. The pick is the rim's, the face the
/// point lies on, not the first face whose plane runs through it.
#[test]
fn lip_on_a_rim_in_line_with_another_face() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 30}));
run(&mut s, "solid.shell", json!({"faces": [[40, 25, 30]], "thickness": 2}));
run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 1, "corner": [30, 25, 0], "operation": "cut", "targets": ["Body1"]}));
let v0 = volume(&mut s);
run(&mut s, "plastic.lip", json!({"face": [1, 25, 30], "width": 1, "height": 2}));
// The band inside the rim, 1 wide and 2 high: (78 × 48 − 76 × 46) × 2.
assert!(rel(volume(&mut s) - v0, 496.0) < 1e-6, "{}", volume(&mut s) - v0);
}
/// A drilled hole as deep as the plate: the drill point breaks through the bottom.
#[test]
fn hole_as_deep_as_the_plate() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 50, "width": 25, "height": 10}));
let v0 = volume(&mut s);
// The depth is to the drill point's shoulder: the bore, radius 3, runs the plate's 10 and the
// point is in the air below it.
run(&mut s, "solid.hole", json!({"position": [25, 12.5, 10], "diameter": 6, "depth": 10, "type": "drilled"}));
let v = volume(&mut s);
assert!((v0 - v - PI * 9.0 * 10.0).abs() < 4e-7 * v0, "{v0} {v}");
// Other sizes and places, the defaults, and a tapped hole: each a through bore of its drill,
// 10 long. The 8.5 at (12, 6) overlaps the 5 at (10, 10) (√20 apart, under 2.5 + 4.25), so
// it takes its bore less the lens they share, 10 long.
let (r, q, d) = (2.5f64, 4.25f64, 20f64.sqrt());
let lens = r * r * ((d * d + r * r - q * q) / (2.0 * d * r)).acos() + q * q * ((d * d + q * q - r * r) / (2.0 * d * q)).acos()
- 0.5 * ((-d + r + q) * (d + r - q) * (d - r + q) * (d + r + q)).sqrt();
for (i, (p, cut)) in [
(json!({"position": [10, 10, 10], "diameter": 5, "depth": 10, "type": "drilled"}), PI * 6.25 * 10.0),
(json!({"position": [40, 15, 10], "diameter": 5, "depth": 10}), PI * 6.25 * 10.0),
(json!({"position": [12, 6, 10], "diameter": 8.5, "depth": 10}), (PI * q * q - lens) * 10.0),
// M6 × 1: the tap maker's 5.0 drill.
(json!({"position": [30, 7, 10], "thread": "M6", "depth": 10}), PI * 6.25 * 10.0),
(json!({"position": [20, 18, 10], "diameter": 4, "depth": 10, "tip_angle": 90}), PI * 4.0 * 10.0),
]
.into_iter()
.enumerate()
{
let before = volume(&mut s);
let r = s.execute("solid.hole", &p);
assert!(r.is_ok(), "{i} {p}: {r:?}");
let v = volume(&mut s);
assert!((before - v - cut).abs() < 4e-7 * before, "{i} {p}: {} vs {cut}", before - v);
}
}
/// Appearances outlive later features: a coloured face keeps its colour after a fillet on a
/// neighbouring edge; an imported STEP's body and face colours survive a hole.
#[test]
fn appearances_survive_later_features() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "B"}));
run(&mut s, "appearance.assign", json!({"faces": [[20, 15, 20]], "color": "#ff0000"}));
run(&mut s, "solid.fillet", json!({"edges": [[40, 15, 0]], "radius": 3}));
let red = |s: &mut Session, body: &str| {
let l = run(s, "appearance.list", json!({ "body": body }));
l["body"]["faces"].as_array().into_iter().flatten().any(|f| f["appearance"]["color"] == "#ff0000")
};
assert!(red(&mut s, "B"), "the top face is still red after the fillet");
// Exported with a body colour and the red face, then opened: the colours come in as the
// body's own; a hole afterwards keeps them.
run(&mut s, "appearance.assign", json!({"bodies": ["B"], "color": "#2050c0"}));
let dir = std::env::temp_dir().join(format!("solidcraft-paint-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let step = dir.join("painted.step");
run(&mut s, "file.export", json!({"path": step.to_string_lossy()}));
let mut t = Session::default();
run(&mut t, "doc.open", json!({"path": step.to_string_lossy()}));
let body = t.model.state().bodies[0].name.clone();
let before = t.doc.body_color(&t.model.state().bodies[0]);
assert!(before.is_some());
run(&mut t, "solid.hole", json!({"position": [10, 10, 20], "diameter": 4}));
let st = t.model.state();
let b = st.body(&body).unwrap();
assert!(b.body.paint().is_none(), "the hole made a new kernel body");
assert_eq!(t.doc.body_color(b), before, "the imported body colour carries on");
assert!(red(&mut t, &body), "the imported red face carries on");
let _ = std::fs::remove_dir_all(&dir);
}
/// The original #2 RGB import acceptance, including later topology and placement edits.
#[test]
fn imported_rgb_appearances_survive_edits_reopen_and_step_export() {
let dir = std::env::temp_dir().join(format!("solidcraft-imported-rgb-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("rgb.step");
let saved = dir.join("edited.solidcraft");
let output = dir.join("edited.step");
let mut source = Session::default();
for (name, x, color) in [("Red", 0, "#ff0000"), ("Green", 40, "#00ff00"), ("Blue", 80, "#0000ff")] {
run(&mut source, "solid.box", json!({"corner":[x,0,0],"length":30,"width":20,"height":20,"body_name":name}));
run(&mut source, "appearance.assign", json!({"bodies":[name],"color":color}));
}
run(&mut source, "appearance.assign", json!({"faces":[[15,10,20]],"color":"#ffff00"}));
run(&mut source, "file.export", json!({"path":input}));
let check = |session: &Session| {
let state = session.model.state();
assert_eq!(state.bodies.len(), 3);
for (name, color) in [("Red", [1., 0., 0.]), ("Green", [0., 1., 0.]), ("Blue", [0., 0., 1.])] {
let body = state.body(name).unwrap();
assert_eq!(session.doc.body_color(body), Some(color), "{name} retains its imported body colour");
}
let red = state.body("Red").unwrap();
assert!(session.doc.face_colors(red).iter().any(|(_, look)| look.color == [255, 255, 0]), "Red retains its yellow top face");
assert!(session.model.results.iter().all(|result| result.error.is_none()));
};
let mut edited = Session::default();
run(&mut edited, "doc.open", json!({"path":input}));
check(&edited);
let initial_volume = volume(&mut edited);
run(&mut edited, "solid.fillet", json!({"bodies":["Red"],"edges":[[0,10,20]],"radius":2}));
check(&edited);
run(&mut edited, "solid.move", json!({"bodies":["Red"],"translate":[0,0,5]}));
check(&edited);
run(&mut edited, "solid.box", json!({"corner":[85,5,15],"length":10,"width":10,"height":10,"body_name":"Cutter"}));
run(&mut edited, "solid.combine", json!({"target":"Blue","tools":["Cutter"],"operation":"cut"}));
check(&edited);
run(&mut edited, "solid.box", json!({"corner":[65,0,0],"length":10,"width":20,"height":20,"body_name":"Joiner"}));
run(&mut edited, "solid.combine", json!({"target":"Green","tools":["Joiner"],"operation":"join"}));
check(&edited);
let edited_volume = volume(&mut edited);
// The join adds 5*20*20, the pocket removes 10*10*5, and the
// radius-2 quarter-round replaces a 2*2 square along a 20 mm edge.
let expected_volume = initial_volume + 2000. - 500. - (4. - PI) * 20.;
assert!((edited_volume - expected_volume).abs() < 0.1, "{edited_volume} vs {expected_volume}");
run(&mut edited, "edit.undo", json!({}));
run(&mut edited, "edit.redo", json!({}));
check(&edited);
run(&mut edited, "file.save_as", json!({"path":saved}));
let mut reopened = Session::default();
run(&mut reopened, "doc.open", json!({"path":saved}));
check(&reopened);
assert!(rel(volume(&mut reopened), edited_volume) < 1e-8);
run(&mut reopened, "file.export", json!({"path":output}));
let mut roundtrip = Session::default();
run(&mut roundtrip, "doc.open", json!({"path":output}));
check(&roundtrip);
assert!(rel(volume(&mut roundtrip), edited_volume) < 1e-3);
let _ = std::fs::remove_dir_all(dir);
}
/// Extrude To Object (a parallel face, with an offset; a slanted face) and From Object.
#[test]
fn extrude_to_and_from_objects() {
let mut s = Session::default();
// A 10 mm plate at z 30…40 to extrude up to, and a profile on XY.
run(&mut s, "solid.box", json!({"corner": [0, 0, 30], "length": 40, "width": 40, "height": 10, "body_name": "Roof"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "P"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]}));
run(&mut s, "sketch.finish", json!({}));
let top = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["bodies"][0]["bbox"]["max"][2].as_f64().unwrap_or(0.0);
run(&mut s, "solid.extrude", json!({"sketch": "P", "to": [20, 20, 30], "body_name": "Post"}));
assert!((top(&mut s, "Post") - 30.0).abs() < 1e-6, "{}", top(&mut s, "Post"));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "P", "to": [20, 20, 30], "to_offset": -5, "body_name": "Post"}));
assert!((top(&mut s, "Post") - 25.0).abs() < 1e-6);
run(&mut s, "edit.undo", json!({}));
// From the roof's top face (z 40) to 10 mm above it.
run(&mut s, "solid.extrude", json!({"sketch": "P", "from": [20, 20, 40], "distance": 10, "body_name": "Post"}));
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Post"]}));
assert!((m["bodies"][0]["bbox"]["min"][2].as_f64().unwrap_or(0.0) - 40.0).abs() < 1e-6 && (top(&mut s, "Post") - 50.0).abs() < 1e-6, "{m}");
// The To face is kept by its persistent name, so it is followed when it moves.
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "P", "to": [20, 20, 30], "body_name": "Post"}));
let name = s.doc.features.last().map(|f| f.face_names.clone()).unwrap_or_default();
assert_eq!(name, vec!["F1:-z".to_string()], "the To face is stored by name");
assert!(s.execute("solid.extrude", &json!({"sketch": "P", "to": "nope"})).is_err());
}
/// Revolve Two Sides, Symmetric and To Object.
#[test]
fn revolve_two_sides_symmetric_and_to_object() {
let ring = |extra: Value| {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "S"}));
run(&mut s, "sketch.line", json!({"points": [[10, 0], [15, 0], [15, 5], [10, 5]], "closed": true}));
run(&mut s, "sketch.finish", json!({}));
let mut p = json!({"sketch": "S", "axis": "y", "angle": "90 deg"});
for (k, v) in extra.as_object().into_iter().flatten() {
p[k] = v.clone();
}
run(&mut s, "solid.revolve", p);
let m = run(&mut s, "inspect.measure", json!({}));
(m["total"]["volume_mm3"].as_f64().unwrap_or(0.0), m["bodies"][0]["bbox"].clone())
};
let full = PI * (225.0 - 100.0) * 5.0;
let (v, _) = ring(json!({}));
assert!(rel(v, full / 4.0) < 1e-3);
let (v, _) = ring(json!({"angle2": "45 deg"}));
assert!(rel(v, full * 135.0 / 360.0) < 1e-3, "{v}");
let (v, b) = ring(json!({"direction": "symmetric"}));
assert!(rel(v, full / 4.0) < 1e-3);
// Split evenly: the extent either side of the sketch plane (y = 0) is the same.
assert!((b["max"][1].as_f64().unwrap_or(0.0) + b["min"][1].as_f64().unwrap_or(0.0)).abs() < 1e-3, "{b}");
// To a point a quarter turn round: the same as 90°.
let (v90, b90) = ring(json!({}));
let corner = if b90["max"][1].as_f64().unwrap_or(0.0) > 1.0 { json!([0, 12, 0]) } else { json!([0, -12, 0]) };
let (v, _) = ring(json!({"to": corner}));
assert!(rel(v, v90) < 1e-3, "{v} {v90}");
}
/// Shell Inside, Outside and Both, and a tangent chain of open faces.
#[test]
fn shell_directions_and_tangent_chain() {
let shell = |extra: Value| {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
let mut p = json!({"faces": [[20, 15, 20]], "thickness": 2});
for (k, v) in extra.as_object().into_iter().flatten() {
p[k] = v.clone();
}
run(&mut s, "solid.shell", p);
let m = run(&mut s, "inspect.measure", json!({}));
(m["total"]["volume_mm3"].as_f64().unwrap_or(0.0), m["bodies"][0]["bbox"].clone())
};
let (v, _) = shell(json!({}));
assert!(rel(v, 40.0 * 30.0 * 20.0 - 36.0 * 26.0 * 18.0) < 1e-6, "{v}");
// Outside: the walls grow out; the original box is the cavity.
let (v, b) = shell(json!({"direction": "outside"}));
assert!(rel(v, 44.0 * 34.0 * 22.0 - 40.0 * 30.0 * 20.0) < 1e-6, "{v} {b}");
// Both: 1 mm out, 1 mm in.
let (v, _) = shell(json!({"direction": "both"}));
assert!(rel(v, 42.0 * 32.0 * 21.0 - 38.0 * 28.0 * 19.0) < 1e-6, "{v}");
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
assert!(s.execute("solid.shell", &json!({"faces": [[20, 15, 20]], "thickness": 2, "direction": "sideways"})).is_err());
}
/// #209: selecting a tangent chain must explain why no shell can remain.
#[test]
fn shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 60}));
run(
&mut s,
"solid.fillet",
json!({
"edges": [[0,0,30], [40,0,30], [40,30,30], [0,30,30],
[20,0,60], [20,30,60], [0,15,60], [40,15,60],
[20,0,0], [20,30,0], [0,15,0], [40,15,0]],
"radius": 1.5
}),
);
let before = s.doc.to_json();
for direction in ["inside", "outside", "both"] {
let error = s
.execute(
"solid.shell",
&json!({
"faces": [[20,0,30]], "thickness": 2, "tangent_chain": true, "direction": direction
}),
)
.unwrap_err()
.to_string();
assert!(error.contains("Tangent Chain") && error.contains("every face") && error.contains("turn off"), "{direction}: {error}");
assert_eq!(s.doc.to_json(), before, "a refused shell must preserve the design");
}
run(&mut s, "solid.shell", json!({"faces": [[20,0,30]], "thickness": 2, "tangent_chain": false}));
// The rounded box (its 37 x 27 x 57 core grown by the 1.5 ball) less the cavity, which the
// 2 mm walls leave sharp, open through the front: 36 x 56 x 28. To the measure's 2e-7.
let (a, b, c, r) = (37.0, 27.0, 57.0, 1.5);
let rounded = a * b * c + 2.0 * r * (a * b + b * c + a * c) + PI * r * r * (a + b + c) + 4.0 / 3.0 * PI * r * r * r;
let want = rounded - 36.0 * 56.0 * 28.0;
assert!((volume(&mut s) - want).abs() < 2e-7 * rounded, "{} vs {want}", volume(&mut s));
assert_eq!(s.model.state().bodies.len(), 1);
}
/// Hole To Object (a face it meets, or a point) and holes at every point of a sketch.
#[test]
fn hole_to_object_and_at_sketch_points() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
// A pocket from below: its ceiling is at z = 10.
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Pocket"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 10], "p1": [30, 20]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Pocket", "distance": 10, "operation": "cut"}));
let v0 = volume(&mut s);
run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 4, "to": [25, 15, 10]}));
assert!(rel(v0 - volume(&mut s), PI * 4.0 * 10.0) < 1e-3, "{}", v0 - volume(&mut s));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.hole", json!({"position": [5, 5, 20], "diameter": 4, "to": [5, 5, 12]}));
assert!(rel(v0 - volume(&mut s), PI * 4.0 * 8.0) < 1e-3, "{}", v0 - volume(&mut s));
// Every point of a sketch: three points (the rectangle's corners are not hole points).
let mut t = Session::default();
run(&mut t, "solid.box", json!({"length": 40, "width": 30, "height": 10}));
run(&mut t, "sketch.create", json!({"plane": {"face": [20, 15, 10]}, "name": "Spots"}));
for x in [10, 20, 30] {
run(&mut t, "sketch.point", json!({"point": [x, 15]}));
}
run(&mut t, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [6, 6]}));
run(&mut t, "sketch.finish", json!({}));
let w0 = volume(&mut t);
let r = run(&mut t, "solid.hole", json!({"sketch": "Spots", "diameter": 3}));
assert!(rel(w0 - volume(&mut t), 3.0 * PI * 2.25 * 10.0) < 1e-3, "{r} {}", w0 - volume(&mut t));
}
/// Combine keeps its tools on request and can put its result in a new component.
#[test]
fn combine_keep_tools_and_new_component() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "A"}));
run(&mut s, "solid.box", json!({"corner": [10, 0, 0], "length": 20, "width": 20, "height": 20, "body_name": "B"}));
let r = run(&mut s, "solid.combine", json!({"target": "A", "tools": ["B"], "operation": "cut", "keep_tools": true, "new_component": true}));
let comp = r["component"].as_u64().unwrap_or(0);
assert!(comp > 0, "{r}");
let st = s.model.state();
assert!(st.body("B").is_some(), "the tool is kept");
let a = st.body("A").unwrap();
assert_eq!(s.doc.body_component("A", a.feature), comp);
assert!(rel(solidcraft_kernel::measure(&a.body).unwrap().volume, 4000.0) < 1e-9);
}
/// Align with snap points: a box's vertex onto another's face centre, an edge midpoint onto a
/// hole's circle centre.
#[test]
fn align_with_snap_points() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "body_name": "Base"}));
run(&mut s, "solid.box", json!({"corner": [100, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Cube"}));
// Cube's corner (100, 0, 0) onto Base's top face centre (20, 20, 10).
run(
&mut s,
"solid.align",
json!({"bodies": ["Cube"], "from": {"snap": "vertex", "at": [100.4, 0.3, 0.2]}, "to": {"snap": "face_center", "at": [5, 5, 10]}}),
);
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Cube"]}));
let min = |i: usize| m["bodies"][0]["bbox"]["min"][i].as_f64().unwrap_or(f64::NAN);
assert!((min(0) - 20.0).abs() < 1e-6 && (min(1) - 20.0).abs() < 1e-6 && (min(2) - 10.0).abs() < 1e-6, "{m}");
assert!(s.execute("solid.align", &json!({"bodies": ["Cube"], "from": {"snap": "nope", "at": [0, 0, 0]}, "to": [0, 0, 0]})).is_err());
}
/// Boundary Fill: the lens two overlapping boxes share, and one box less the other.
#[test]
fn boundary_fill_cells() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "A"}));
run(&mut s, "solid.box", json!({"corner": [10, 0, 0], "length": 20, "width": 20, "height": 20, "body_name": "B"}));
let r = run(&mut s, "solid.boundary_fill", json!({"tools": ["A", "B"], "cells": [[15, 10, 10]], "remove_tools": true}));
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["body_count"], 1, "{r} {m}");
assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap_or(0.0), 10.0 * 20.0 * 20.0) < 1e-9);
run(&mut s, "edit.undo", json!({}));
run(&mut s, "solid.boundary_fill", json!({"tools": ["A", "B"], "cells": [[5, 10, 10], [25, 10, 10]], "remove_tools": true}));
let m = run(&mut s, "inspect.measure", json!({}));
assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap_or(0.0), 2.0 * 10.0 * 20.0 * 20.0) < 1e-9, "{m}");
assert!(s.execute("solid.boundary_fill", &json!({"tools": ["A"], "cells": [[100, 100, 100]]})).is_err());
}
/// Rectangles name their sides and corners, so they can be dimensioned without inspecting the
/// sketch first, whichever way round the corners were given.
#[test]
fn rectangle_names_sides_and_corners() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [40, 30], "p1": [0, 0]}));
let pos = |s: &Session, id: &Value| {
let sk = s.doc.sketch(s.active_sketch.unwrap()).unwrap();
sk.point(sk.resolve_point(id.as_str().unwrap()).unwrap()).unwrap()
};
for (corner, at) in [("bottom_left", [0.0, 0.0]), ("bottom_right", [40.0, 0.0]), ("top_right", [40.0, 30.0]), ("top_left", [0.0, 30.0])] {
let p = pos(&s, &r["corners"][corner]);
assert!((p.x - at[0]).abs() < 1e-9 && (p.y - at[1]).abs() < 1e-9, "{corner}: {p:?} in {r}");
}
for (side, from, to) in [
("bottom", "bottom_left", "bottom_right"),
("right", "bottom_right", "top_right"),
("top", "top_right", "top_left"),
("left", "top_left", "bottom_left"),
] {
let line = r["sides"][side].as_str().unwrap();
assert!(r["curves"].as_array().unwrap().iter().any(|c| c == line), "{r}");
assert_eq!(pos(&s, &json!(format!("{line}.start"))), pos(&s, &r["corners"][from]), "{side} in {r}");
assert_eq!(pos(&s, &json!(format!("{line}.end"))), pos(&s, &r["corners"][to]), "{side} in {r}");
}
run(&mut s, "sketch.constraint.coincident", json!({"a": r["corners"]["bottom_left"], "b": "origin"}));
run(&mut s, "sketch.dimension", json!({"entities": [r["sides"]["bottom"]], "value": 50}));
run(&mut s, "sketch.dimension", json!({"entities": [r["sides"]["left"]], "value": 20}));
let si = run(&mut s, "sketch.inspect", json!({}));
assert_eq!(si["dof"], 0, "{si}");
let p = pos(&s, &r["corners"]["top_right"]);
assert!((p.x - 50.0).abs() < 1e-6 && (p.y - 20.0).abs() < 1e-6, "{p:?}");
let c = run(&mut s, "sketch.rectangle.center", json!({"center": [100, 0], "corner": [90, 5]}));
let p = pos(&s, &c["corners"]["bottom_left"]);
assert!((p.x - 90.0).abs() < 1e-9 && (p.y + 5.0).abs() < 1e-9, "{c}");
assert_eq!(pos(&s, &json!(format!("{}.start", c["sides"]["top"].as_str().unwrap()))), pos(&s, &c["corners"]["top_right"]), "{c}");
}
/// Points drawn exactly onto an existing point (the origin, a corner) are connected to it;
/// `connect: false` leaves them free, and tying them again by hand is a no-op, not a conflict.
#[test]
fn drawing_on_existing_points_connects_to_them() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let n = |v: &Value| v["constraints"].as_array().map_or(0, Vec::len);
// Horizontal/vertical x4, plus the corner on the origin.
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
assert_eq!(n(&r), 5, "{r}");
run(&mut s, "sketch.dimension", json!({"entities": [r["curves"][0]], "value": 40}));
run(&mut s, "sketch.dimension", json!({"entities": [r["curves"][1]], "value": 30}));
let si = run(&mut s, "sketch.inspect", json!({}));
assert_eq!(si["dof"], 0, "fully constrained without a hand-made coincident: {si}");
let again = run(&mut s, "sketch.constraint.coincident", json!({"a": "origin", "b": "l1.start"}));
assert_eq!(again["existing"], true, "{again}");
// A line from a corner, a circle on a corner and a point on the origin connect too.
assert_eq!(n(&run(&mut s, "sketch.line", json!({"points": [[40, 30], [60, 30]]}))), 1);
assert_eq!(n(&run(&mut s, "sketch.circle.center", json!({"center": [0, 30], "radius": 3}))), 1);
assert_eq!(n(&run(&mut s, "sketch.point", json!({"point": [0, 0]}))), 1);
// Close is not on it, and `connect: false` opts out.
assert_eq!(n(&run(&mut s, "sketch.point", json!({"point": [40.001, 0]}))), 0);
assert_eq!(n(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [0, -10]], "connect": false}))), 0);
let si = run(&mut s, "sketch.inspect", json!({}));
assert_ne!(si["status"], "conflict", "{si}");
}
#[test]
fn computed_import_preserves_file_and_earlier_undo_history() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
s.path = Some("existing.solidcraft".into());
s.mark_saved();
let saved = s.doc.clone();
let mut computed = s.scratch();
run(&mut computed, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [30, 0, 0]}));
s.accept_computed(computed);
assert_eq!(s.path.as_deref(), Some("existing.solidcraft"));
assert!(s.is_dirty());
assert_eq!(s.model.state().bodies.len(), 2);
run(&mut s, "edit.undo", json!({}));
assert!(std::sync::Arc::ptr_eq(&saved, &s.doc));
assert!(!s.is_dirty());
run(&mut s, "edit.undo", json!({}));
assert!(s.model.state().bodies.is_empty());
}
/// The unsaved-changes answer is worked out once per pair of documents and revision, and stays
/// right through every way the design changes: an edit in place (`doc_mut`, which stays in
/// place), one that bypasses it, a new document equal to the saved one, Save, a change of what
/// is hidden, and undo back to the saved design. Each answer is checked against the plain
/// comparison it stands for.
#[test]
fn the_unsaved_changes_answer_follows_every_change() {
let plain = |s: &Session| (!std::sync::Arc::ptr_eq(&s.doc, &s.saved) && *s.doc != *s.saved) || s.visibility != s.saved_visibility;
let check = |s: &Session, want: bool, why: &str| {
for _ in 0..2 {
assert_eq!(s.is_dirty(), want, "{why}");
assert_eq!(plain(s), want, "{why}: the plain comparison");
}
};
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
s.mark_saved();
check(&s, false, "saved");
// An edit in place: the cached answer holds the document, yet the edit is not a copy.
s.doc = std::sync::Arc::new((*s.doc).clone());
check(&s, false, "an equal copy of the saved design");
let at = std::sync::Arc::as_ptr(&s.doc);
s.doc_mut().name = "Renamed".into();
assert_eq!(std::sync::Arc::as_ptr(&s.doc), at, "doc_mut edits in place");
check(&s, true, "renamed in place, same revision");
s.doc_mut().name = s.saved.name.clone();
check(&s, false, "named back in place");
// An edit that goes around doc_mut while the answer holds the document copies it.
std::sync::Arc::make_mut(&mut s.doc).name = "Elsewhere".into();
check(&s, true, "edited past doc_mut");
s.mark_saved();
check(&s, false, "saved again");
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [30, 0, 0]}));
check(&s, true, "a command");
run(&mut s, "edit.undo", json!({}));
check(&s, false, "undone back to the saved design");
s.visibility.hidden_bodies.push("Body1".into());
check(&s, true, "a body hidden");
s.visibility.hidden_bodies.clear();
check(&s, false, "shown again");
}
/// Commands evaluated ahead (off the window thread) and then run for real take what was
/// evaluated: on a design whose states are past the shared cache's budget the second run
/// evaluated everything again, so an off-thread command cost twice its time.
#[test]
fn commands_evaluated_ahead_are_not_evaluated_again() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "w", "expression": "40 mm"}));
run(&mut s, "solid.box", json!({"length": "w", "width": 30, "height": 10, "body_name": "Block"}));
run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 10]], "distance": 1}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 20, "corner": [2, 2, 0], "operation": "cut"}));
let commands = vec![("parameters.change".to_string(), json!({"name": "w", "expression": "50 mm"}))];
let evaluated = s.ahead().evaluate(&commands).unwrap();
// The shared cache dropped those results (as it does past its budget).
s.model.cache = Default::default();
let mut unprimed = s.scratch();
s.prime(&evaluated);
let r = run(&mut s, "parameters.change", json!({"name": "w", "expression": "50 mm"}));
s.unprime();
assert_eq!((&r["recomputed"], &r["restored"]), (&json!(0), &json!(3)), "every feature taken from the evaluation ahead: {r}");
let r = run(&mut unprimed, "parameters.change", json!({"name": "w", "expression": "50 mm"}));
assert_eq!(r["recomputed"], 3, "without it, all evaluated again: {r}");
for (a, b) in s.model.state().bodies.iter().zip(&unprimed.model.state().bodies) {
assert_eq!(a.mesh().bounds(), b.mesh().bounds());
}
// Inputs that differ from those evaluated ahead are evaluated, as usual.
s.model.cache = Default::default();
s.prime(&evaluated);
let r = run(&mut s, "parameters.change", json!({"name": "w", "expression": "60 mm"}));
s.unprime();
assert_eq!(r["recomputed"], 3, "{r}");
assert!((s.model.state().body("Block").unwrap().mesh().bounds().max.x - 60.0).abs() < 1e-9);
}
#[test]
fn adopting_a_computed_component_keeps_its_warm_world_geometry() {
let mut s = Session::default();
run(&mut s, "component.create", json!({"name": "Part"}));
run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10}));
let mut computed = s.scratch();
run(&mut computed, "solid.box", json!({"length":5,"width":5,"height":5,"corner":[30,0,0]}));
let prepared = computed.world_state().unwrap();
for b in &prepared.bodies {
let _ = b.mesh();
}
s.accept_computed(computed);
assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state().unwrap()));
s.invalidate_view(100);
assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state().unwrap()));
}
/// Every file command checked the size with the metadata and then read to the end. A character
/// device reports a length of 0, so the cap passed and the read never finished; a FIFO blocked
/// the calling thread, which over the control channel is the thread drawing the window.
#[cfg(unix)]
#[test]
fn special_files_are_refused_by_every_file_command() {
let mut s = Session::default();
for cmd in ["doc.open", "parameters.import"] {
let r = s.execute(cmd, &json!({"path": "/dev/zero"}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("not a regular file")), "{cmd}: {r:?}");
}
// The commands that check the extension first need a special file with the right name.
let dir = std::env::temp_dir().join(format!("solidcraft-special-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
for (cmd, name) in [("file.insert_step", "x.step"), ("file.insert_mesh", "x.3mf"), ("sketch.insert_dxf", "x.dxf")] {
let p = dir.join(name);
let _ = std::fs::remove_file(&p);
if !std::process::Command::new("mkfifo").arg(&p).status().map(|st| st.success()).unwrap_or(false) {
continue;
}
let r = s.execute(cmd, &json!({"path": p.to_string_lossy()}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("not a regular file")), "{cmd}: {r:?}");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A cut targeted at one body leaves a non-target body alone, even one the tool covers completely (#260).
#[test]
fn targeted_cut_keeps_a_covered_body_that_is_not_a_target() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "Frame"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "new_body", "body_name": "Other"}));
// Exactly Other's extent; it does not touch Frame.
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "cut", "targets": ["Frame"]}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["Frame", "Other"]);
assert!(rel(volume(&mut s), 2000.0) < 1e-6);
}
/// A frame's opening cut over a separate mesh body that sits in it: the mesh survives (#260).
#[test]
fn targeted_cut_keeps_an_overlapping_body_that_is_not_a_target() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 50, "width": 50, "height": 5, "operation": "new_body", "body_name": "Frame"}));
run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 1, "corner": [10, 10, 2], "operation": "new_body", "body_name": "Mesh"}));
run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 5, "corner": [10, 10, 0], "operation": "cut", "targets": ["Frame"]}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["Frame", "Mesh"]);
assert!(rel(volume(&mut s), 50.0 * 50.0 * 5.0 - 30.0 * 30.0 * 5.0 + 900.0) < 1e-6);
}
/// A join with explicit `targets` merges into those bodies only; a touched non-target stays (#259).
#[test]
fn join_with_targets_leaves_other_touched_bodies_alone() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "A"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [10, 0, 0], "operation": "new_body", "body_name": "B"}));
// Straddles the face between A and B; only A is a target.
run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [8, 3, 3], "operation": "join", "targets": ["A"]}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["A", "B"], "B is not a target and must stay a body");
let b = run(&mut s, "inspect.measure", json!({"bodies": ["B"]}))["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(b, 1000.0) < 1e-6, "B is unchanged: {b}");
// A gains the half of the tool outside it.
let a = run(&mut s, "inspect.measure", json!({"bodies": ["A"]}))["total"]["volume_mm3"].as_f64().unwrap();
assert!(rel(a, 1032.0) < 1e-6, "A: {a}");
}
/// Deleting a sketch takes its extrude with it; a later combine that names the extrude's body must
/// not be left failing silently: it is deleted too, or the reply reports it (#267).
#[test]
fn deleting_a_sketch_leaves_no_silently_failing_feature() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 20]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": "10", "body_name": "P"}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [18, 5, 0], "operation": "new_body", "body_name": "Q"}));
run(&mut s, "solid.combine", json!({"target": "P", "tools": ["Q"], "name": "JoinPQ"}));
let reply = run(&mut s, "timeline.delete", json!({"features": ["S"]}));
if let Ok(join) = s.execute("timeline.inspect", &json!({"feature": "JoinPQ"})) {
assert!(
join["error"].is_null() || reply.to_string().contains("JoinPQ"),
"JoinPQ now fails ({}) but the reply only says {reply}",
join["error"]
);
}
}
#[test]
fn default_extrude_profiles_preserve_two_holes() {
let mut sketch = Session::default();
run(&mut sketch, "sketch.create", json!({"plane": "XY"}));
run(&mut sketch, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [60, 40]}));
for x in [15, 45] {
run(&mut sketch, "sketch.circle.center", json!({"center": [x, 20], "radius": 5}));
}
run(&mut sketch, "sketch.finish", json!({}));
for (selection, expected) in [
(None, (2400.0 - 50.0 * PI) * 5.0),
(Some(json!([0])), (2400.0 - 50.0 * PI) * 5.0),
(Some(json!("all")), 12000.0),
(Some(json!([0, 1, 2])), 12000.0),
] {
let mut s = Session::new((*sketch.doc).clone());
let mut params = json!({"distance": 5});
if let Some(selection) = selection {
params["profiles"] = selection;
}
run(&mut s, "solid.extrude", params);
let actual = volume(&mut s);
assert!(rel(actual, expected) < 1e-4, "{actual} vs {expected}");
}
}
#[test]
fn default_extrude_profiles_keep_even_depth_islands_and_separate_outlines() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
for (p0, p1) in [([0, 0], [30, 30]), ([5, 5], [25, 25]), ([10, 10], [20, 20]), ([40, 0], [50, 10])] {
run(&mut s, "sketch.rectangle.two_point", json!({"p0": p0, "p1": p1}));
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5}));
assert_eq!(s.model.state().bodies.len(), 3);
let expected = (900.0 - 400.0 + 100.0 + 100.0) * 5.0;
let actual = volume(&mut s);
assert!(rel(actual, expected) < 1e-6, "{actual} vs {expected}");
}
/// The face of `body` whose normal points along +x, as a plane pick.
fn side_face_pick(s: &Session, body: &str) -> Value {
let world = s.world_state().unwrap();
let b = world.body(body).unwrap();
let face = b
.body
.faces(0.01)
.unwrap()
.into_iter()
.filter(|f| f.plane_normal.is_some_and(|n| n.dot(solidcraft_geom::Vec3::X) > 0.999))
.max_by(|a, b| a.centroid.x.total_cmp(&b.centroid.x))
.unwrap();
json!({"body": b.name, "index": face.index, "face": [face.centroid.x, face.centroid.y, face.centroid.z]})
}
#[test]
fn extruding_a_sketch_on_a_side_face_takes_the_whole_drawn_profile() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Base"}));
let pick = side_face_pick(&s, "Base");
let id = run(&mut s, "sketch.create", json!({"plane": pick, "name": "Side"}))["sketch"].as_u64().unwrap();
// The rectangle straddles the top edge of the face, so the projected outline cuts it in two.
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 15], "p1": [20, 25]}));
run(&mut s, "sketch.finish", json!({}));
for selection in [json!([1]), json!([2]), json!([{"point": [15, 17]}]), json!([{"point": [15, 22]}])] {
let mut s2 = Session::new((*s.doc).clone());
run(&mut s2, "solid.extrude", json!({"sketch": id, "distance": 5, "operation": "new", "body_name": "Rib", "profiles": selection.clone()}));
let state = s2.model.state();
let rib = state.bodies.iter().find(|b| b.name == "Rib").unwrap();
let v = rib.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume;
assert!(rel(v, 500.0) < 1e-6, "{selection}: {v}");
}
}
/// A pick on a region of a drawn profile that reference geometry bounds from inside (the rim of
/// a hole in the face) takes only that region: the rim is a real boundary of the material, and
/// the drawn outline around it is not cut by it (#5302).
#[test]
fn a_pick_bounded_by_a_projected_rim_takes_only_that_region() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Base"}));
run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 10}));
let id = run(&mut s, "sketch.create", json!({"plane": {"face": [20, 5, 20]}}))["sketch"].as_u64().unwrap();
// The square around the hole: the hole's rim is projected into the sketch and bounds an
// inner region of it, but does not cut the square.
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 5], "p1": [30, 25]}));
run(&mut s, "sketch.finish", json!({}));
let mut s2 = Session::new((*s.doc).clone());
run(&mut s2, "solid.extrude", json!({"sketch": id, "distance": 5, "operation": "new", "body_name": "Pad", "profiles": [{"point": [12, 7]}]}));
let state = s2.model.state();
let pad = state.bodies.iter().find(|b| b.name == "Pad").unwrap();
let v = pad.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume;
// The square with the hole's rim cut out of it, not the whole square. The mesh measures the
// round rim as a polygon, so the volume is a little under the analytic one.
let want = (400.0 - PI * 25.0) * 5.0;
assert!(rel(v, want) < 5e-3, "{v} vs {want}");
}
/// A circle drawn partly past the edge of the top face its sketch is on: the face's projected
/// outline cuts it into a lens on the face and a crescent past it. A pick that asks for exactly
/// its region, as the dialogs do, builds that region alone (#6724); a plain pick still takes the
/// whole drawn circle (#5302).
#[test]
fn an_exact_pick_of_a_region_cut_by_the_face_outline_takes_only_that_region() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "body_name": "Base"}));
let id = run(&mut s, "sketch.create", json!({"plane": {"face": [0, 0, 10]}}))["sketch"].as_u64().unwrap();
run(&mut s, "sketch.circle.center", json!({"center": [10, 0], "radius": 6}));
run(&mut s, "sketch.finish", json!({}));
// The two circles' lens, and the rest of the drawn circle past the face.
let (r1, r2, d) = (10.0_f64, 6.0_f64, 10.0_f64);
let lens = r1 * r1 * ((d * d + r1 * r1 - r2 * r2) / (2.0 * d * r1)).acos() + r2 * r2 * ((d * d + r2 * r2 - r1 * r1) / (2.0 * d * r2)).acos()
- 0.5 * ((-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2)).sqrt();
let disc = PI * r2 * r2;
let crescent = disc - lens;
let state = s.model.state();
let ss = state.sketch(id).unwrap();
assert_eq!(ss.profiles.len(), 3, "the lens, the crescent past the face and the rest of the face");
let at = |x: f64| ss.profiles.iter().position(|p| p.region.contains(solidcraft_geom::Vec2::new(x, 0.0))).unwrap();
let (on_face, past_face) = (at(7.0), at(14.0));
// The volume of the new body, and how many profiles its extrude is built from.
let extrude = |extra: Value| -> (f64, usize) {
let mut s2 = Session::new((*s.doc).clone());
let mut p = json!({"sketch": id, "distance": 5, "operation": "new", "body_name": "Pad"});
if let (Some(p), Value::Object(extra)) = (p.as_object_mut(), extra) {
p.extend(extra);
}
run(&mut s2, "solid.extrude", p);
let state = s2.model.state();
let Some(solidcraft_doc::FeatureKind::Extrude { profiles, .. }) = s2.doc.features.last().map(|f| &f.kind) else { panic!("an extrude") };
let count = solidcraft_doc::profile_selection_indices(state.sketch(id).unwrap(), profiles).unwrap().len();
let v = state
.bodies
.iter()
.filter(|b| b.name.starts_with("Pad"))
.map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume)
.sum();
(v, count)
};
for (profiles, want, n) in [
(json!([on_face]), lens, 1),
(json!([past_face]), crescent, 1),
(json!([{"point": [7, 0]}]), lens, 1),
(json!([{"point": [14, 0]}]), crescent, 1),
(json!([on_face, past_face]), disc, 2),
] {
let (v, count) = extrude(json!({"profiles": profiles.clone(), "exact_regions": true}));
assert!(rel(v, want * 5.0) < 5e-3, "{profiles}: {v} vs {}", want * 5.0);
assert_eq!(count, n, "{profiles}");
}
// Without `exact_regions`, a pick on either piece takes the whole drawn circle (#5302).
for profiles in [json!([on_face]), json!([{"point": [14, 0]}])] {
let (v, count) = extrude(json!({"profiles": profiles.clone()}));
assert!(rel(v, disc * 5.0) < 5e-3, "{profiles}: {v} vs {}", disc * 5.0);
assert_eq!(count, 2, "{profiles}");
}
}
/// An explicit pick of a drawn hole still fills only that hole (#5176).
#[test]
fn an_explicit_pick_of_a_drawn_hole_fills_only_that_hole() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [60, 40]}));
run(&mut s, "sketch.circle.center", json!({"center": [30, 20], "radius": 5, "id": "ring"}));
run(&mut s, "sketch.finish", json!({}));
let ring = s.model.state().sketches[0].profiles.iter().position(|p| p.outer_curves == ["ring"]).unwrap();
run(&mut s, "solid.extrude", json!({"distance": 5, "profiles": [ring]}));
assert!(rel(volume(&mut s), 25.0 * PI * 5.0) < 1e-4, "the hole alone: {}", volume(&mut s));
}
/// Every body a multi-profile `new` extrude creates carries its `body_name`, not a generic BodyN (#266).
#[test]
fn multi_profile_extrude_names_every_body_after_body_name() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "R"}));
for x in [0, 10, 20] {
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [x, 0], "p1": [x + 5, 30]}));
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": "10", "operation": "new_body", "body_name": "Ribs"}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert!(names.iter().all(|n| n.starts_with("Ribs")), "{names:?}");
assert!(rel(volume(&mut s), 4500.0) < 1e-6);
}
/// Renaming one pattern copy leaves the other copies' names alone (#265).
#[test]
fn renaming_a_pattern_copy_keeps_the_other_copies_names() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "X"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20}));
run(&mut s, "body.rename", json!({"body": "X (2)", "name": "Second"}));
let third = run(&mut s, "inspect.measure", json!({"bodies": ["X (3)"]}));
assert_eq!(third["bodies"][0]["bbox"]["min"][0].as_f64().map(f64::round), Some(40.0), "X (3) is still the copy at x = 40: {third}");
run(&mut s, "body.rename", json!({"body": "X (3)", "name": "Third"}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["X", "Second", "Third"]);
}
/// Three solids in one STEP file that carry the same label: the file written for three boxes, each
/// named `X`.
fn step_three_solids_labelled_x(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("solidcraft-step-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::default();
for (i, label) in ["Aa", "Bb", "Cc"].iter().enumerate() {
let corner = [30.0 * i as f64, 0.0, 0.0];
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": corner, "operation": "new_body", "body_name": label}));
}
let p = dir.join("Three.step");
run(&mut s, "file.export", json!({"path": p.to_string_lossy()}));
let mut text = std::fs::read_to_string(&p).unwrap();
for label in ["Aa", "Bb", "Cc"] {
assert!(text.contains(&format!("MANIFOLD_SOLID_BREP('{label}'")), "the file names its solids: {label}");
text = text.replace(&format!("MANIFOLD_SOLID_BREP('{label}'"), "MANIFOLD_SOLID_BREP('X'");
}
std::fs::write(&p, text).unwrap();
p
}
/// Renaming one of several imported bodies that share a label leaves the names of the others alone:
/// the model lists them as `X`, `X (2)`, `X (3)`, and `X (3)` is still there after `X (2)` is renamed.
#[test]
fn renaming_an_imported_body_keeps_the_names_of_its_duplicates() {
let p = step_three_solids_labelled_x("duplicate-labels");
let mut s = Session::default();
run(&mut s, "file.insert_step", json!({"path": p.to_string_lossy()}));
let names = |s: &Session| s.model.state().bodies.iter().map(|b| b.name.clone()).collect::<Vec<_>>();
assert_eq!(names(&s), ["X", "X (2)", "X (3)"]);
let x_of =
|s: &mut Session, body: &str| run(s, "inspect.measure", json!({"bodies": [body]}))["bodies"][0]["bbox"]["min"][0].as_f64().map(f64::round);
assert_eq!(x_of(&mut s, "X (3)"), Some(60.0));
run(&mut s, "body.rename", json!({"body": "X (2)", "name": "Second"}));
assert_eq!(names(&s), ["X", "Second", "X (3)"]);
assert_eq!(x_of(&mut s, "X (3)"), Some(60.0), "X (3) is still the solid at x = 60");
run(&mut s, "body.rename", json!({"body": "X (3)", "name": "Third"}));
assert_eq!(names(&s), ["X", "Second", "Third"]);
assert_eq!(x_of(&mut s, "Third"), Some(60.0));
// The names survive a rebuild and a reopen of the saved design.
let design = p.with_file_name("Three.solidcraft");
run(&mut s, "file.save_as", json!({"path": design.to_string_lossy()}));
let mut r = Session::default();
run(&mut r, "doc.open", json!({"path": design.to_string_lossy()}));
assert_eq!(names(&r), ["X", "Second", "Third"]);
}
/// The same when the first of the three is renamed: `X (2)` and `X (3)` do not slide down to `X` and
/// `X (2)`, and what is set on one of them (a material) stays with it.
#[test]
fn renaming_the_first_imported_duplicate_keeps_the_numbers_of_the_others() {
let p = step_three_solids_labelled_x("duplicate-labels-first");
let mut s = Session::default();
run(&mut s, "file.insert_step", json!({"path": p.to_string_lossy()}));
run(&mut s, "material.assign", json!({"bodies": ["X (3)"], "material": "Steel"}));
run(&mut s, "body.rename", json!({"body": "X", "name": "First"}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["First", "X (2)", "X (3)"]);
assert!(s.doc.materials.contains_key("X (3)"), "the material is still on X (3): {:?}", s.doc.materials.keys().collect::<Vec<_>>());
}
/// Parameters that work are listed in the command's params doc, which is all agents see (#271).
#[test]
fn params_docs_list_working_parameters() {
let mut s = Session::default();
let cmds = run(&mut s, "engine.commands", json!({}));
let params =
|id: &str| cmds.as_array().unwrap().iter().find(|c| c["id"] == id).and_then(|c| c["params"].as_str()).unwrap_or_default().to_string();
// Both work today: a named base flange, and a loft cut limited to its targets.
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "A"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [50, 50]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sheet.flange", json!({"sketch": "A", "body_name": "Panel A"}));
assert!(s.model.state().body("Panel A").is_some());
assert!(params("sheet.flange").contains("body_name"), "sheet.flange: {}", params("sheet.flange"));
assert!(params("solid.loft").contains("targets"), "solid.loft: {}", params("solid.loft"));
}
/// Every body-creating feature documents the keys `add_feature` reads for all of them (`name`,
/// `body_name`), and those that take `targets` say so (#271).
#[test]
fn feature_params_docs_list_shared_keys() {
let mut s = Session::default();
let cmds = run(&mut s, "engine.commands", json!({}));
let params =
|id: &str| cmds.as_array().unwrap().iter().find(|c| c["id"] == id).and_then(|c| c["params"].as_str()).unwrap_or_default().to_string();
let with_targets = ["solid.extrude", "solid.revolve", "solid.sweep", "solid.loft", "solid.pipe", "solid.coil"];
let without_targets = ["solid.box", "solid.cylinder", "solid.sphere", "solid.torus", "solid.cone", "sheet.flange"];
for id in with_targets.iter().chain(&without_targets) {
let doc = params(id);
assert!(doc.contains("name?") && doc.contains("body_name?"), "{id}: {doc}");
}
for id in with_targets {
assert!(params(id).contains("targets?"), "{id}: {}", params(id));
}
}
#[test]
fn a_pattern_repeats_a_fillet_on_the_edges_it_found() {
// #219: a filleted pocket patterned along the plate, its height from a parameter. A taller
// pocket moves its far corner edges away from the points picked for the fillet; the pattern
// repeats the edges the fillet found (by name), not those points.
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "n", "expression": "14", "unit": ""}));
run(&mut s, "parameters.add", json!({"name": "h", "expression": "(419.1 mm - 3.175 mm - (n - 1) * 3.175 mm) / n", "unit": "mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [150, 422.275]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 19.05, "name": "Plate"}));
run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 19.05, "name": "PocketPlane"}));
run(&mut s, "sketch.create", json!({"plane": "PocketPlane"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [3.175, 3.175], "p1": [146.825, 29.9357]}));
run(&mut s, "sketch.dimension", json!({"entities": ["origin", "p1"], "type": "horizontal", "value": "3.175"}));
run(&mut s, "sketch.dimension", json!({"entities": ["origin", "p1"], "type": "vertical", "value": "3.175"}));
run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "type": "length", "value": "143.65"}));
run(&mut s, "sketch.dimension", json!({"entities": ["l4"], "type": "length", "value": "h"}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 12.7, "direction": "negative", "operation": "cut", "name": "Pocket"}));
run(
&mut s,
"solid.fillet",
json!({"edges": [[3.175, 3.175, 12.700000000000001], [146.825, 3.175, 12.700000000000001], [146.825, 29.9357, 12.700000000000001], [3.175, 29.9357, 12.700000000000001]], "radius": 3.2}),
);
run(
&mut s,
"solid.pattern.rectangular",
json!({"features": ["Pocket", "Fillet1"], "dir1": [0, 1, 0], "count1": "n", "spacing1": "h + 3.175 mm"}),
);
let r = run(&mut s, "parameters.change", json!({"name": "n", "expression": "10"}));
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
let (n, h) = (10.0, (419.1 - 3.175 - 9.0 * 3.175) / 10.0);
let pocket = 143.65 * h * 12.7 - 4.0 * (1.0 - PI / 4.0) * 3.2 * 3.2 * 12.7;
let expect = 150.0 * 422.275 * 19.05 - n * pocket;
assert!(rel(volume(&mut s), expect) < 1e-5, "{} vs {expect}", volume(&mut s));
}
/// A body renamed after a join: the next new body does not take the name the rename freed
/// (#4957). The join changed the body, so the rename is followed by a full evaluation of the
/// design; the numbers the design handed out must not go back with it, or a script that names
/// a body finds another one.
#[test]
fn a_renamed_body_keeps_its_number_from_the_next_body() {
for join in [false, true] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "new"}));
if join {
// A second box joined to the first: the join changes the body, so the rename
// cannot be followed without evaluating the design again.
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 0], "p1": [15, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"}));
}
run(&mut s, "body.rename", json!({"body": "Body1", "name": "First"}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [30, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "new"}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["First", "Body2"], "with a join: {join}");
}
}
/// A copy added by raising the count after a rename takes the next number, not the freed one (#372).
#[test]
fn raising_a_pattern_count_after_a_rename_numbers_the_new_copy_after_the_others() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "X"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20, "name": "Pat"}));
run(&mut s, "body.rename", json!({"body": "X (2)", "name": "Second"}));
run(&mut s, "timeline.edit", json!({"feature": "Pat", "set": {"pattern": {"count1": "4"}}}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["X", "Second", "X (3)", "X (4)"]);
let fourth = run(&mut s, "inspect.measure", json!({"bodies": ["X (4)"]}));
assert_eq!(fourth["bodies"][0]["bbox"]["min"][0].as_f64().map(f64::round), Some(60.0), "{fourth}");
}
/// A profile added to the sketch after a named multi-profile extrude is named after `body_name`
/// too (#373).
#[test]
fn a_profile_added_later_is_named_after_body_name() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "R"}));
for x in [0, 10, 20] {
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [x, 0], "p1": [x + 5, 30]}));
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "R", "distance": "10", "operation": "new_body", "body_name": "Ribs"}));
run(&mut s, "sketch.edit", json!({"sketch": "R"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [30, 0], "p1": [35, 30]}));
run(&mut s, "sketch.finish", json!({}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["Ribs", "Ribs (2)", "Ribs (3)", "Ribs (4)"]);
}
/// The reply names the bodies the feature created, apart from the ones already there (#374).
#[test]
fn extrude_reply_lists_the_bodies_it_created() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [0, 50, 0], "operation": "new_body", "body_name": "Base"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "R"}));
for x in [0, 10, 20] {
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [x, 0], "p1": [x + 5, 30]}));
}
run(&mut s, "sketch.finish", json!({}));
let r = run(&mut s, "solid.extrude", json!({"sketch": "R", "distance": "10", "operation": "new_body", "body_name": "Ribs"}));
assert_eq!(r["created_bodies"], json!(["Ribs", "Ribs (2)", "Ribs (3)"]), "{r}");
}
/// A design saved before format 14 with fewer stored body names than bodies (#373) opens and
/// evaluates: the first body takes its stored name, and every body has a name of its own. (The
/// names the others had when it was saved are not promised.)
#[test]
fn a_design_saved_before_format_14_with_fewer_body_names_opens_and_names_every_body() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "R"}));
for x in [0, 10, 20] {
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [x, 0], "p1": [x + 5, 30]}));
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "R", "distance": "10", "operation": "new_body", "body_name": "Ribs"}));
let mut legacy: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
legacy["format"] = json!("solidcraft/13");
let extrude = legacy["features"].as_array_mut().unwrap().iter_mut().find(|f| f["type"] == "extrude").unwrap();
extrude["body_names"] = json!(["Ribs"]);
let dir = std::env::temp_dir().join(format!("solidcraft-373-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let design = dir.join("ribs.solidcraft");
std::fs::write(&design, legacy.to_string()).unwrap();
let mut old = Session::default();
run(&mut old, "doc.open", json!({"path": design.to_string_lossy()}));
assert!(old.model.results.iter().all(|r| r.error.is_none()), "{:?}", old.model.results);
let names: Vec<String> = old.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!((names.len(), names.first().map(String::as_str)), (3, Some("Ribs")), "{names:?}");
assert_eq!(names.iter().collect::<std::collections::BTreeSet<_>>().len(), 3, "{names:?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// R21 on the bottom front edge of a 50 x 50 x 20 block overflows the 20 mm front face (its circle
/// about (y, z) = (21, 21) reaches the top only at y = 21 - sqrt(440)) and goes first; the front
/// left upright, picked with it, lies wholly in what it removes (every (0, 0, z) is outside that
/// circle), so it is gone: not rounded, and the feature says so. The block is R21's alone: the
/// section loses 20 (21 - sqrt(440)) + int_0^sqrt(440) (21 - sqrt(441 - u^2)) du, along 50.
#[test]
fn fillet_edge_removed_by_a_larger_overflowing_round_is_noted() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 50, "width": 50, "height": 20}));
let out = run(&mut s, "solid.fillet", json!({"edges": [[25, 0, 0], [0, 0, 10]], "radius": 21, "tangent_chain": false, "name": "Round"}));
let w = 440f64.sqrt();
let f = 0.5 * (w * (441.0 - w * w).sqrt() + 441.0 * (w / 21.0).asin());
let lost = 20.0 * (21.0 - w) + 21.0 * w - f;
let want = 50.0 * 50.0 * 20.0 - 50.0 * lost;
assert!(rel(volume(&mut s), want) < 1e-9, "{} vs {want}", volume(&mut s));
let id = out["feature"].as_u64().unwrap();
let warning = s.model.result(id).and_then(|r| r.warning.clone()).unwrap_or_default();
assert_eq!(warning, "the edge at (0, 0, 10) was removed by the larger round, so it is not rounded");
}
#[test]
fn fillet_fit_reduce_uses_the_largest_radius_that_fits() {
// #293: 3.5 is too large for the 6 mm end faces of a 14 x 6 x 10 box; reduce gives 3 (a full
// round), says so, and refits when the box changes.
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "w", "expression": "6 mm"}));
run(&mut s, "solid.box", json!({"length": 14, "width": "w", "height": 10, "corner": [14, 0, 0]}));
let mids = json!([[14, 0, 5], [28, 0, 5], [14, 6, 5], [28, 6, 5]]);
// The exact fit refuses it, naming the largest radius that fits.
let e = s.execute("solid.fillet", &json!({"edges": mids, "radius": 3.5})).unwrap_err().to_string();
assert!(e.contains("the largest radius that fits is 3 mm"), "{e}");
let out = run(&mut s, "solid.fillet", json!({"edges": mids, "radius": 3.5, "fit": "reduce", "name": "Round"}));
assert_eq!(out["radius_applied"].as_f64(), Some(3.0), "{out}");
let full = 840.0 - (4.0 - PI) * 9.0 * 10.0;
assert!(rel(volume(&mut s), full) < 2e-4, "{} vs {full}", volume(&mut s));
let id = out["feature"].as_u64().unwrap();
let warning = s.model.result(id).and_then(|r| r.warning.clone()).unwrap_or_default();
assert!(warning.contains("reduced to 3 mm"), "{warning}");
// Wider: the requested 3.5 fits, nothing is reduced.
let r = run(&mut s, "parameters.change", json!({"name": "w", "expression": "8 mm"}));
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
assert_eq!(s.model.result(id).and_then(|r| r.state.fitted_radius(id)), None);
assert!(s.model.result(id).and_then(|r| r.warning.clone()).is_none());
// Saved only when set.
let json = serde_json::to_string(&s.doc.features).unwrap();
assert_eq!(json.matches("\"fit\":\"reduce\"").count(), 1, "{json}");
// An unknown mode is refused, and so are reduce and taper with a radius that is not constant.
assert!(s.execute("solid.fillet", &json!({"edges": mids, "radius": 1, "fit": "stretch"})).is_err());
assert!(s.execute("solid.fillet", &json!({"edges": mids, "radius": 1, "fit": "reduce", "type": "chord"})).is_err());
assert!(s.execute("solid.fillet", &json!({"edges": mids, "radius": 1, "fit": "taper", "type": "chord"})).is_err());
}
/// A plate 15 high whose top narrows from 20 to `tip` mm along 40 mm (a wedge at 0), and, with
/// `wall`, a wall standing behind its slanted side from z = -15 to 30, which the plate's top and
/// bottom end on in concave edges: a blend of its front edges can't run past them.
fn tapering_plate(tip: f64, wall: bool) -> Session {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let pts = if tip > 0.0 { json!([[0, 0], [40, 0], [40, tip], [0, 20]]) } else { json!([[0, 0], [40, 0], [0, 20]]) };
run(&mut s, "sketch.line", json!({"points": pts, "closed": true}));
run(&mut s, "solid.extrude", json!({"distance": 15}));
if wall {
run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, -15], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}}));
run(&mut s, "sketch.line", json!({"points": [[40, tip], [0, 20], [0, 30], [40, 30]], "closed": true}));
run(&mut s, "solid.extrude", json!({"distance": 45, "operation": "join"}));
assert_eq!(s.model.state().bodies.len(), 1);
}
s
}
/// [`tapering_plate`]'s volume: the plate, and the wall's 20 (40 − tip) section along 45.
fn tapering_plate_volume(tip: f64, wall: bool) -> f64 {
(40.0 * (20.0 + tip) / 2.0) * 15.0 + if wall { 20.0 * (40.0 - tip) * 45.0 } else { 0.0 }
}
#[test]
fn fillet_fit_taper_follows_the_room_along_the_edge() {
// #293: the top front edge of a plate whose top narrows from 20 to `tip` mm along 40 mm,
// against a wall. At a 2 mm tip it can't take 3 mm; taper keeps 3 where it fits and comes
// down to 0.9 of the 2 mm there. With an 8 mm tip 3 fits and stays constant. The warning
// says what was done.
let (k, edge) = (1.0 - PI / 4.0, json!([[20, 0, 15]]));
let warning = |s: &Session, out: &Value| out["feature"].as_u64().and_then(|id| s.model.result(id)).and_then(|r| r.warning.clone());
let mut s = tapering_plate(2.0, true);
assert!(s.execute("solid.fillet", &json!({"edges": edge, "radius": 3})).is_err());
let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"}));
let w = warning(&s, &out).unwrap_or_default();
assert!(w.contains("tapers to the room on 1 of 1 edges, down to 1.8 mm"), "{w}");
// Between the material a constant 1.8 and a constant 3 would remove.
let (v, full) = (volume(&mut s), tapering_plate_volume(2.0, true));
assert!(v < full - k * 1.8 * 1.8 * 40.0 && v > full - k * 9.0 * 40.0, "{v}");
let json = serde_json::to_string(&s.doc.features).unwrap();
assert_eq!(json.matches("\"fit\":\"taper\"").count(), 1, "{json}");
let mut s = tapering_plate(8.0, true);
let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"}));
assert_eq!(warning(&s, &out), None);
assert!(rel(volume(&mut s), tapering_plate_volume(8.0, true) - k * 9.0 * 40.0) < 2e-4);
// Without the wall the 2 mm top's far edge is a cliff: R3 runs over it and is cut from the
// plate as if the top went on (the blend-overflow decision, 237f0ae74), so it fits and the
// taper leaves it constant. At x the plate's section is [0, w] × [0, 15], w = 20 − 0.45 x:
// the round takes its whole (1 − π/4)·9 where w >= 3, and where w < 3 the part of the
// 3 × 3 corner outside the circle about (3, 3) with s <= w, 3 w − (F(3) − F(3 − w)),
// F(v) = (v √(9 − v²) + 9 asin(v/3)) / 2.
let mut s = tapering_plate(2.0, false);
let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"}));
assert_eq!(warning(&s, &out), None);
let f = |v: f64| 0.5 * (v * (9.0 - v * v).max(0.0).sqrt() + 9.0 * (v / 3.0).asin());
let n = 20000;
let taken: f64 = (0..n)
.map(|i| {
let w = 20.0 - 0.45 * 40.0 * (i as f64 + 0.5) / n as f64;
if w >= 3.0 { 9.0 * k } else { 3.0 * w - (f(3.0) - f(3.0 - w)) }
})
.sum::<f64>()
* 40.0
/ n as f64;
let want = tapering_plate_volume(2.0, false) - taken;
assert!(rel(volume(&mut s), want) < 1e-6, "{} vs {want}", volume(&mut s));
}
#[test]
fn fillet_fit_taper_closes_to_a_point() {
// #293: a wedge against a wall, its top closing to a point at x = 40: no constant radius
// fits there, and taper comes down to 0 at the point.
let mut s = tapering_plate(0.0, true);
assert!(s.execute("solid.fillet", &json!({"edges": [[20, 0, 15]], "radius": 16})).is_err());
let out = run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 15]], "radius": 16, "fit": "taper"}));
let w = out["feature"].as_u64().and_then(|id| s.model.result(id)).and_then(|r| r.warning.clone()).unwrap_or_default();
assert!(w.contains("on 1 of 1 edges, down to 0 mm"), "{w}");
}
#[test]
fn spline_fillet_takes_over_a_taper() {
// A tapered fillet keeps each edge's radius spline; given back as a `spline` fillet it makes
// the same part, and its control radii are then the user's to change.
let mut s = tapering_plate(2.0, true);
let edge = json!([[20, 0, 15]]);
let out = run(&mut s, "solid.fillet", json!({"edges": edge, "radius": 3, "fit": "taper"}));
let id = out["feature"].as_u64().unwrap();
let tapered = s.model.result(id).and_then(|r| r.state.tapered(id).map(<[_]>::to_vec)).unwrap();
let [(_, t)] = &tapered[..] else { panic!("{tapered:?}") };
let tapered_volume = volume(&mut s);
let radii: Vec<Value> = t.spline.radii.iter().skip(1).map(|r| json!(r)).collect();
let spline = json!({"edges": edge, "radius": t.spline.radii[0], "type": "spline", "start": [t.start.x, t.start.y, t.start.z], "knots": t.spline.knots, "radii": radii});
run(&mut s, "timeline.redefine", json!({"feature": id, "command": "solid.fillet", "params": spline}));
assert!(rel(volume(&mut s), tapered_volume) < 1e-9, "{} vs {tapered_volume}", volume(&mut s));
let json = serde_json::to_string(&s.doc.features).unwrap();
assert!(json.contains("\"type\":\"spline\""), "{json}");
// A control radius raised in the middle: more material goes.
let mut raised = spline.clone();
raised["radii"][2] = json!("4 mm");
run(&mut s, "timeline.redefine", json!({"feature": id, "command": "solid.fillet", "params": raised}));
assert!(volume(&mut s) < tapered_volume);
// Knots that don't match the radii are refused.
let mut bad = spline;
bad["knots"] = json!([0, 1]);
assert!(s.execute("solid.fillet", &bad).is_err());
}
#[test]
fn fillet_fit_reduce_keeps_the_radius_where_it_fits() {
// A 14 x 6 x 10 post on a block: its four vertical edges can't take 3.5 (two rounds on its
// 6 mm ends would cross), a corner of the block far from it can. Only the post's edges are
// reduced, to 3 (a full round); the reply gives each edge's radius.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.box", json!({"length": 14, "width": 6, "height": 10, "corner": [2, 2, 20], "operation": "join"}));
assert_eq!(s.model.state().bodies.len(), 1);
let post = [[2.0, 2.0, 25.0], [16.0, 2.0, 25.0], [2.0, 8.0, 25.0], [16.0, 8.0, 25.0]];
let edges = json!([post[0], post[1], post[2], post[3], [40, 0, 10]]);
let out = run(&mut s, "solid.fillet", json!({"edges": edges, "radius": 3.5, "fit": "reduce"}));
assert_eq!(out["radius_applied"].as_f64(), Some(3.0), "{out}");
let each: Vec<(Vec<f64>, f64)> = out["radii_applied"]
.as_array()
.unwrap()
.iter()
.map(|x| (x["edge"].as_array().unwrap().iter().filter_map(Value::as_f64).collect(), x["radius"].as_f64().unwrap()))
.collect();
let mut want_each: Vec<(Vec<f64>, f64)> = post.iter().map(|p| (p.to_vec(), 3.0)).collect();
want_each.push((vec![40.0, 0.0, 10.0], 3.5));
assert_eq!(each, want_each, "{out}");
// The post's full round takes (4 − π)·9 of its section along its 10 mm height, the block's
// corner (1 − π/4)·3.5² along 20.
let removed = (4.0 - PI) * 9.0 * 10.0 + (1.0 - PI / 4.0) * 3.5 * 3.5 * 20.0;
let want = 40.0 * 30.0 * 20.0 + 14.0 * 6.0 * 10.0 - removed;
assert!(rel(volume(&mut s), want) < 2e-4, "{} vs {want}", volume(&mut s));
let id = out["feature"].as_u64().unwrap();
let warning = s.model.result(id).and_then(|r| r.warning.clone()).unwrap_or_default();
assert!(warning.contains("on 4 of 5 edges"), "{warning}");
}
/// A 2 mm fin's top edge at R4 runs over the fin's top, past its far edge (a cliff): it is cut
/// as if the top went on (the blend-overflow decision), so with `fit: reduce` nothing is reduced.
/// The fin's section loses the 4 x 4 square at its edge less the quarter disc about (17, 26)
/// inside the fin (x >= 19), as `fillet_max_each_reduces_only_where_the_radius_does_not_fit`
/// in the kernel finds it.
#[test]
fn fillet_fit_reduce_keeps_a_round_over_a_cliff() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
run(&mut s, "solid.box", json!({"length": 2, "width": 30, "height": 10, "corner": [19, 0, 20], "operation": "join"}));
let out = run(&mut s, "solid.fillet", json!({"edges": [[21, 15, 30], [40, 0, 10]], "radius": 4, "fit": "reduce"}));
assert_eq!(out["radius_applied"].as_f64(), None, "{out}");
let id = out["feature"].as_u64().unwrap();
assert_eq!(s.model.result(id).and_then(|r| r.warning.clone()), None);
let disc = |a: f64| 0.5 * (a * (16.0 - a * a).max(0.0).sqrt() + 16.0 * (a / 4.0).asin());
let removed = (2.0 * 4.0 - (disc(4.0) - disc(2.0))) * 30.0 + (1.0 - PI / 4.0) * 16.0 * 20.0;
let want = 40.0 * 30.0 * 20.0 + 2.0 * 30.0 * 10.0 - removed;
assert!(rel(volume(&mut s), want) < 1e-6, "{} vs {want}", volume(&mut s));
}
#[test]
fn a_pattern_of_a_reduced_fillet_rounds_each_copy_alike() {
// #293: a 6 mm wide post on a plate, its four vertical edges at 3.5 reduced to 3, patterned
// three times: every copy is a full round.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 60, "width": 20, "height": 2}));
run(&mut s, "solid.box", json!({"length": 14, "width": 6, "height": 10, "corner": [2, 7, 2], "operation": "join", "name": "Post"}));
let mids = json!([[2, 7, 7], [16, 7, 7], [2, 13, 7], [16, 13, 7]]);
run(&mut s, "solid.fillet", json!({"edges": mids, "radius": 3.5, "fit": "reduce", "name": "Round"}));
run(&mut s, "solid.pattern.rectangular", json!({"features": ["Post", "Round"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20}));
let expect = 60.0 * 20.0 * 2.0 + 3.0 * (840.0 - (4.0 - PI) * 9.0 * 10.0);
assert!(rel(volume(&mut s), expect) < 2e-4, "{} vs {expect}", volume(&mut s));
}
#[test]
fn extrude_taper_help_explains_both_signs() {
let mut s = Session::default();
let help = run(&mut s, "engine.describe", json!({"command": "solid.extrude"}));
for text in [help["params"].as_str().unwrap(), help["input"]["properties"]["taper"]["description"].as_str().unwrap()] {
assert!(text.contains("positive: outward") && text.contains("negative: inward"), "{text}");
}
}
#[test]
fn extrude_taper_sign_sets_far_face_size() {
for angle in [5.0_f64, -5.0] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "taper": format!("{angle} deg"), "body_name": "Tapered"}));
let faces = run(&mut s, "model.faces", json!({"body": "Tapered"}));
let far = faces["faces"].as_array().unwrap().iter().find(|f| (f["centroid"][2].as_f64().unwrap() - 10.0).abs() < 1e-6).unwrap();
let width = 10.0 + 20.0 * angle.to_radians().tan();
let area = far["area"].as_f64().unwrap();
assert!((area - width * width).abs() < 1e-6, "{angle} deg: {far}");
assert_eq!(area > 100.0, angle > 0.0);
}
}
/// A taper on a profile of lines and an arc (#546). The D profile (back 9.2, sides 7.4, a
/// half-round front R 4.6 tangent to them) grows by d = z · tan 5° with mitred corners:
/// A(d) = A₀ + P·d + (2 + π/2)·d², integrated over the 10 mm height.
#[test]
fn tapered_extrude_of_a_profile_mixing_lines_and_an_arc() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "D"}));
run(&mut s, "sketch.line", json!({"points": [[0, 4.6], [-7.4, 4.6], [-7.4, -4.6], [0, -4.6]], "closed": false}));
run(&mut s, "sketch.arc.center_point", json!({"center": [0, 0], "start": [0, -4.6], "end": [0, 4.6]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "D", "distance": 10, "taper": "5 deg"}));
let (t, h) = (5f64.to_radians().tan(), 10.0);
let (a0, p, k) = (7.4 * 9.2 + PI * 4.6 * 4.6 / 2.0, 2.0 * 7.4 + 9.2 + PI * 4.6, 2.0 + PI / 2.0);
let expect = a0 * h + p * t * h * h / 2.0 + k * t * t * h.powi(3) / 3.0;
assert!(rel(volume(&mut s), expect) < 1e-3, "{} vs {expect}", volume(&mut s));
}
/// A feature that joins into a body creates none, and its reply says so; a primitive's reply
/// names the body it made (#374).
#[test]
fn feature_replies_list_only_the_bodies_they_created() {
let mut s = Session::default();
let r = run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Base"}));
assert_eq!(r["created_bodies"], json!(["Base"]), "{r}");
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Boss"}));
run(&mut s, "sketch.circle.center", json!({"center": [5, 5], "radius": 2}));
run(&mut s, "sketch.finish", json!({}));
let r = run(&mut s, "solid.extrude", json!({"sketch": "Boss", "distance": "15", "operation": "join"}));
assert_eq!(r["created_bodies"], json!([]), "{r}");
assert_eq!(r["bodies"], json!(["Base"]), "{r}");
}
/// A feature reply also says which existing bodies it changed and which are gone, so a client
/// that skips the full body list (MCP `batch` with `verbose: false`, #530) still sees every effect.
#[test]
fn feature_replies_list_the_bodies_they_changed_and_removed() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "new", "body_name": "B"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "operation": "new", "body_name": "C"}));
// A pocket in A changes A only.
let r = run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 10, "corner": [3, 3, 5], "operation": "cut", "targets": ["A"]}));
assert_eq!((&r["created_bodies"], &r["changed_bodies"], &r["removed_bodies"]), (&json!([]), &json!(["A"]), &json!([])), "{r}");
// Joining C into B changes B and removes C.
let r = run(&mut s, "solid.combine", json!({"target": "B", "tools": ["C"], "operation": "join"}));
assert_eq!((&r["changed_bodies"], &r["removed_bodies"]), (&json!(["B"]), &json!(["C"])), "{r}");
// A new body changes nothing else.
let r = run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [0, 50, 0], "operation": "new", "body_name": "D"}));
assert_eq!((&r["created_bodies"], &r["changed_bodies"], &r["removed_bodies"]), (&json!(["D"]), &json!([]), &json!([])), "{r}");
}
/// Drafting a cylinder's side face 5° from the base plane makes a cone frustum (#547): radius 10
/// at the base, 10 − 20 · tan 5° at the top.
#[test]
fn draft_on_a_cylinder_side_makes_a_frustum() {
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20}));
run(&mut s, "solid.draft", json!({"faces": [[10, 0, 10]], "angle": "5 deg", "neutral": "XY"}));
let (big, h) = (10.0, 20.0);
let small = big - h * 5f64.to_radians().tan();
let expect = PI * h / 3.0 * (big * big + big * small + small * small);
assert!(rel(volume(&mut s), expect) < 1e-3, "{} vs {expect}", volume(&mut s));
}
/// The copies added after a rename keep their numbers through undo/redo, save/reopen and a
/// further count change; lowering the count drops the last copies (#372).
#[test]
fn pattern_copies_added_after_a_rename_keep_their_numbers() {
let mut s = Session::default();
let names = |s: &Session| -> Vec<String> { s.model.state().bodies.iter().map(|b| b.name.clone()).collect() };
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "X"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20, "name": "Pat"}));
run(&mut s, "body.rename", json!({"body": "X (2)", "name": "Second"}));
run(&mut s, "timeline.edit", json!({"feature": "Pat", "set": {"pattern": {"count1": "5"}}}));
assert_eq!(names(&s), ["X", "Second", "X (3)", "X (4)", "X (5)"]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&s), ["X", "Second", "X (3)"]);
run(&mut s, "edit.redo", json!({}));
assert_eq!(names(&s), ["X", "Second", "X (3)", "X (4)", "X (5)"]);
let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
assert_eq!(names(&reopened), ["X", "Second", "X (3)", "X (4)", "X (5)"]);
run(&mut s, "timeline.edit", json!({"feature": "Pat", "set": {"pattern": {"count1": "2"}}}));
assert_eq!(names(&s), ["X", "Second"]);
}
/// A sketch side drawn as two collinear lines extrudes into one flat face, not two with an edge
/// between them (#1788); the face is named from the first line and answers to the second.
#[test]
fn a_side_drawn_in_two_collinear_pieces_extrudes_into_one_face() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let r = run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0], [20, 0], [20, 10], [0, 10], [0, 0]]}));
let pieces: Vec<String> = r["created"]["curves"].as_array().into_iter().flatten().take(2).filter_map(|c| c.as_str().map(String::from)).collect();
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5}));
let faces = |s: &mut Session| run(s, "model.faces", json!({"body": "Body1"}))["faces"].as_array().cloned().unwrap_or_default();
let f = faces(&mut s);
assert_eq!(f.len(), 6, "a box has six faces: {f:?}");
assert_eq!(run(&mut s, "inspect.measure", json!({}))["bodies"][0]["kernel"]["faces"], 6);
let names: Vec<&str> = f.iter().filter_map(|x| x["name"].as_str()).collect();
assert!(names.contains(&format!("F2:side:{}", pieces[0]).as_str()), "{names:?}");
// The extrude made the side from both pieces: the second piece's role names that very face
// too, so an edge named after it is that edge.
let st = s.model.state();
let body = st.body("Body1").unwrap();
let edge = format!("F2:side:{}|F2:top", pieces[1]);
let at = solidcraft_doc::naming::find_edge(body, &edge, geom::Vec3::new(15.0, 0.0, 5.0)).unwrap();
assert!(at.y.abs() < 1e-9 && (at.z - 5.0).abs() < 1e-9, "{edge} at {at:?}");
// A sketch attaches to the joined side as to any side.
assert_eq!(run(&mut s, "sketch.create", json!({"plane": {"face": [15, 0, 2.5]}}))["attachment"], "exact_face");
run(&mut s, "sketch.finish", json!({}));
}
/// A sketch made on the second piece's face while the side was two faces (as in a design saved
/// before #1788) stays attached once the side is straight and extrudes into one face.
#[test]
fn a_sketch_on_one_piece_stays_attached_when_the_side_joins() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let r = run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, -2], [20, 0], [20, 10], [0, 10], [0, 0]]}));
let first = r["created"]["curves"][0].as_str().unwrap_or_default().to_string();
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5}));
let faces = |s: &mut Session| run(s, "model.faces", json!({"body": "Body1"}))["faces"].as_array().map(Vec::len).unwrap_or(0);
assert_eq!(faces(&mut s), 7);
assert_eq!(run(&mut s, "sketch.create", json!({"plane": {"face": [15, -1, 2.5]}}))["attachment"], "exact_face");
run(&mut s, "sketch.circle.center", json!({"center": [5, 2.5], "radius": 1}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.edit", json!({"sketch": "Sketch1"}));
run(&mut s, "sketch.move_point", json!({"point": format!("{first}.end"), "to": [10, 0]}));
run(&mut s, "sketch.finish", json!({}));
assert_eq!(faces(&mut s), 6, "the side is straight now: one face");
let sketch = run(&mut s, "timeline.inspect", json!({"feature": "Sketch2"}));
assert!(sketch["error"].is_null() && sketch["warning"].is_null(), "{sketch}");
}
/// With a taper too, a side drawn in two collinear pieces extrudes into one face (#1788).
#[test]
fn a_tapered_side_drawn_in_two_collinear_pieces_is_one_face() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0], [20, 0], [20, 10], [0, 10], [0, 0]]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "taper": "5 deg"}));
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["bodies"][0]["kernel"]["faces"], 6, "{m}");
}
/// #3044: renaming a body of an imported assembly (a part placed twice, so the file has more
/// solids than the part has bodies) evaluates nothing, not even the file again, and leaves the
/// model evaluating the renamed design gives; undo does the same.
#[test]
fn renaming_an_imported_assembly_body_reads_nothing_again() {
let dir = std::env::temp_dir().join(format!("solidcraft-step-rename-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut a = Session::default();
run(&mut a, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Cube"}));
run(&mut a, "solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [30, 0, 2], "operation": "new", "body_name": "Pin"}));
run(&mut a, "component.from_bodies", json!({"bodies": ["Cube"]}));
run(&mut a, "occurrence.copy", json!({"component": "Cube", "translate": [0, 40, 0]}));
let p = dir.join("Assembly.step");
run(&mut a, "file.export", json!({"path": p.to_string_lossy()}));
let mut s = Session::default();
run(&mut s, "doc.open", json!({"path": p.to_string_lossy()}));
let names = |s: &Session| s.model.state().bodies.iter().map(|b| b.name.clone()).collect::<Vec<_>>();
let before = names(&s);
let body = before.first().cloned().unwrap();
s.evaluations = 0;
run(&mut s, "body.rename", json!({"body": body, "name": "Renamed"}));
assert_eq!(s.evaluations, 0, "a rename evaluates nothing");
let after = names(&s);
assert_eq!(after.first().map(String::as_str), Some("Renamed"));
assert_eq!(after.len(), before.len());
let mut fresh = Session::new((*s.doc).clone());
fresh.refresh();
assert_eq!(names(&fresh), after, "the same names as evaluating the renamed design");
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&s), before);
assert_eq!(s.evaluations, 0, "nor does its undo");
let _ = std::fs::remove_dir_all(&dir);
}
/// Renaming one of an imported file's solids whose siblings are numbered after it (`Bolt` beside
/// `Bolt (2)`, as the solids of a STEP file with one label are built) evaluates nothing either: the
/// rename keeps the siblings' names, so the model is the one evaluating the renamed design gives.
#[test]
fn renaming_an_imported_body_with_numbered_siblings_evaluates_nothing() {
let dir = std::env::temp_dir().join(format!("solidcraft-step-rename-siblings-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut a = Session::default();
run(&mut a, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Bolt"}));
run(&mut a, "solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [30, 0, 2], "operation": "new", "body_name": "Bolt (2)"}));
let p = dir.join("Bolts.step");
run(&mut a, "file.export", json!({"path": p.to_string_lossy()}));
let mut s = Session::default();
run(&mut s, "doc.open", json!({"path": p.to_string_lossy()}));
let names = |s: &Session| s.model.state().bodies.iter().map(|b| b.name.clone()).collect::<Vec<_>>();
let before = names(&s);
let first = before.iter().find(|n| !n.ends_with(" (2)")).cloned().unwrap();
assert!(before.contains(&format!("{first} (2)")), "a sibling numbered after it: {before:?}");
s.evaluations = 0;
run(&mut s, "body.rename", json!({"body": first, "name": "Renamed"}));
assert_eq!(s.evaluations, 0, "a rename evaluates nothing");
let after = names(&s);
assert!(after.contains(&"Renamed".to_string()) && after.contains(&format!("{first} (2)")), "{after:?}");
let mut fresh = Session::new((*s.doc).clone());
fresh.refresh();
assert_eq!(names(&fresh), after, "the same names as evaluating the renamed design");
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&s), before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(names(&s), after);
assert_eq!(s.evaluations, 0, "nor do its undo and redo");
let _ = std::fs::remove_dir_all(&dir);
}
/// #2467: renaming a body that later features change (a hole patterned over it, then a chamfer)
/// evaluates nothing, and leaves the bodies, volumes and face names evaluating the renamed
/// design gives; undo and redo do the same.
#[test]
fn renaming_a_body_later_features_change_evaluates_nothing() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [80, 50]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10}));
run(
&mut s,
"solid.hole",
json!({"position": [15, 12, 10], "diameter": 5, "type": "counterbore", "cb_diameter": 9, "cb_depth": 3, "name": "Hole1"}),
);
run(
&mut s,
"solid.pattern.rectangular",
json!({"features": ["Hole1"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 25, "dir2": [0, 1, 0], "count2": 2, "spacing2": 25}),
);
run(&mut s, "solid.chamfer", json!({"edges": [[40, 0, 10], [80, 25, 10]], "distance": 1}));
let looks = |st: &solidcraft_doc::ModelState| {
st.bodies.iter().map(|b| (b.name.clone(), (*solidcraft_doc::naming::face_names(b)).clone())).collect::<Vec<_>>()
};
let before = looks(&s.model.state());
let v = body_volume(&s.model.state());
let old = before.first().map(|b| b.0.clone()).unwrap();
s.evaluations = 0;
run(&mut s, "body.rename", json!({"body": old, "name": "Plate"}));
assert_eq!(s.evaluations, 0, "a rename evaluates nothing");
let after = looks(&s.model.state());
assert_eq!(after.first().map(|b| b.0.as_str()), Some("Plate"));
let mut fresh = Session::new((*s.doc).clone());
fresh.refresh();
assert_eq!(looks(&fresh.model.state()), after, "the bodies and face names evaluating the renamed design gives");
assert!(rel(body_volume(&fresh.model.state()), v) < 1e-9);
run(&mut s, "edit.undo", json!({}));
assert_eq!(looks(&s.model.state()), before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(looks(&s.model.state()), after);
assert_eq!(s.evaluations, 0, "nor do its undo and redo");
}
/// A body whose name later bodies' names are worked out from (`X` patterned into `X (2)`) keeps
/// the same copies and face names as opening the renamed design.
#[test]
fn renaming_a_body_keeps_its_copies_consistent_with_rebuilding() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "X"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20}));
let names = |s: &Session| s.model.state().bodies.iter().map(|b| b.name.clone()).collect::<Vec<_>>();
assert!(names(&s).iter().any(|n| n.starts_with("X (")), "{:?}", names(&s));
run(&mut s, "body.rename", json!({"body": "X", "name": "First"}));
let mut fresh = Session::new((*s.doc).clone());
fresh.refresh();
assert_eq!(names(&fresh), names(&s));
for (a, b) in fresh.model.state().bodies.iter().zip(&s.model.state().bodies) {
assert_eq!(solidcraft_doc::naming::face_names(a), solidcraft_doc::naming::face_names(b));
}
}
/// #3044: on a design with thousands of bodies the cheap commands stay cheap: showing, hiding,
/// selecting, colouring and renaming a body or a feature, and undoing them, recompute no feature
/// (renames don't even look over the timeline) and leave every body's display mesh as it was, so
/// nothing is meshed or uploaded again.
#[test]
fn cheap_commands_on_thousands_of_bodies_evaluate_nothing() {
let mut s = Session::default();
for k in 0..2 {
run(
&mut s,
"solid.box",
json!({"length": 4, "width": 4, "height": 4, "center": [0, 6 * k, 2], "operation": "new", "name": format!("Seed{k}")}),
);
run(
&mut s,
"solid.pattern.rectangular",
json!({"features": [format!("Seed{k}")], "dir1": [1, 0, 0], "count1": 1000, "spacing1": 6, "name": format!("Row{k}")}),
);
}
let st = s.model.state();
assert_eq!(st.bodies.len(), 2000);
let meshes = |s: &Session| s.model.state().bodies.iter().map(|b| std::sync::Arc::as_ptr(&b.mesh())).collect::<Vec<_>>();
let shown = meshes(&s);
s.refresh();
for (command, params) in [
("select.set", json!({"items": [{"type": "body", "name": "Body7"}]})),
("browser.visibility", json!({"visible": false, "items": ["Body7"]})),
("browser.visibility", json!({"visible": true, "items": ["Body7"]})),
("appearance.assign", json!({"bodies": ["Body7"], "appearance": "Aluminum - Satin"})),
("body.rename", json!({"body": "Body7", "name": "Renamed"})),
("timeline.rename", json!({"feature": "Row1", "name": "Second row"})),
("edit.undo", json!({})),
("edit.undo", json!({})),
("edit.redo", json!({})),
] {
s.evaluations = 0;
run(&mut s, command, params);
// Renames are followed in the model; the rest may look over the timeline, which then
// finds every result as it was.
assert_eq!(s.model.last_recomputed, 0, "{command} recomputed a feature");
if command.ends_with("rename") {
assert_eq!(s.evaluations, 0, "{command} evaluated the design");
}
}
assert_eq!(meshes(&s), shown, "every body keeps its mesh");
}
/// #3397: a new, empty component changes nothing a feature reads, so creating one recomputes
/// nothing, the first component of a design included: not a targeted cut, a Combine, a To
/// Object extrude or a sketch on a face without a construction certificate (a legacy face
/// plane, which reads every placed body), all of which read placements.
#[test]
fn creating_a_component_recomputes_nothing() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "operation": "new", "body_name": "Block"}));
run(&mut s, "solid.cylinder", json!({"diameter": 8, "height": 12, "base": [15, 15, -1], "operation": "cut", "targets": ["Block"]}));
run(&mut s, "solid.box", json!({"length": 10, "width": 30, "height": 20, "corner": [0, 0, 10], "operation": "new", "body_name": "Tab"}));
run(&mut s, "solid.combine", json!({"target": "Block", "tools": ["Tab"], "operation": "join"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Post sketch"}));
run(&mut s, "sketch.circle.center", json!({"center": [25, 25], "radius": 2}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Post sketch", "to": [25, 25, 10], "operation": "new", "body_name": "Post"}));
// A sketch on a face without a construction certificate: a face extrude on a plate, saved
// as a design from before face attachments were certified (no anchor), and reopened.
run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 10, "corner": [200, 0, 0], "operation": "new", "body_name": "Plate"}));
run(&mut s, "solid.extrude", json!({"face": [240, 40, 10], "distance": 1, "operation": "join", "name": "Face layer"}));
let mut legacy = (*s.doc).clone();
let mut legacy_face = false;
for f in &mut legacy.features {
if let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, .. }, .. } = &mut f.kind {
*anchor = None;
legacy_face = true;
}
}
assert!(legacy_face, "the face extrude's sketch is on a face plane");
let mut s = Session::new(solidcraft_doc::Document::from_json(&legacy.to_json()).unwrap());
assert!(s.model.results.iter().all(|r| r.error.is_none()), "the legacy design evaluates");
for name in ["First", "Second"] {
run(&mut s, "component.create", json!({"name": name}));
assert_eq!(s.model.last_recomputed, 0, "creating {name} recomputed a feature");
run(&mut s, "component.activate", json!({"component": "root"}));
}
}
#[test]
fn parallel_pipe_large_nominals_support_shallow_and_thin_cylindrical_holes() {
for designation in ["G 1", "Rp 1"] {
for (height, depth) in [(15.0, Some(3.0)), (5.0, None)] {
let mut s = crate::Session::default();
s.execute("solid.box", &format!(r#"{{"length":80,"width":80,"height":{height},"body_name":"Plate"}}"#).parse().unwrap()).unwrap();
let depth_json = depth.map(|d| format!(r#", "depth":{d}"#)).unwrap_or_default();
let result =
s.execute("solid.hole", &format!(r#"{{"position":[40,40,{height}],"thread":"{designation}"{depth_json}}}"#).parse().unwrap());
assert!(result.is_ok(), "{designation}, height={height}, depth={depth:?}: {result:?}");
let reopened = crate::Session::new(crate::doc::Document::from_json(&s.doc.to_json()).unwrap());
assert!(reopened.model.results.iter().all(|r| r.error.is_none()));
let state = reopened.world_state().unwrap();
assert_eq!(state.threads.len(), 1);
assert_eq!(state.threads[0].designation, designation);
assert!((state.threads[0].end - state.threads[0].start - depth.unwrap_or(height)).abs() < 1e-6);
}
}
}
/// #3961: a cut made while a body is hidden leaves that body alone, and keeps doing so once it
/// is shown again (the shown bodies are stored as the cut's targets); with nothing hidden, a
/// cut still goes through every body it meets.
#[test]
fn a_cut_leaves_hidden_bodies_alone() {
let setup = |hide: bool| {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "body_name": "Below"}));
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [0, 0, 10], "body_name": "Above", "operation": "new"}));
if hide {
run(&mut s, "browser.visibility", json!({"items": ["Below"], "visible": false}));
}
run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 20]}}));
run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 30, "direction": "negative", "operation": "cut"}));
s
};
let vol = |s: &Session, name: &str| solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().volume;
let full = 20.0 * 20.0 * 10.0;
let mut hidden = setup(true);
assert!((vol(&hidden, "Below") - full).abs() < 1e-6, "the hidden body is not cut");
assert!(vol(&hidden, "Above") < full - 1.0, "the shown one is");
run(&mut hidden, "browser.visibility", json!({"items": ["Below"], "visible": true}));
assert!((vol(&hidden, "Below") - full).abs() < 1e-6, "shown again, it stays as it was");
let shown = setup(false);
assert!(vol(&shown, "Below") < full - 1.0 && vol(&shown, "Above") < full - 1.0, "with nothing hidden, both are cut");
}
/// #2464: an extrude Join with no targets onto a plate with a hidden coincident copy changes the
/// shown plate only, and keeps the shown bodies as its participants.
#[test]
fn join_leaves_a_hidden_body_alone() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 5, "body_name": "Plate"}));
run(&mut s, "solid.move", json!({"bodies": ["Plate"], "copy": true}));
run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": false}));
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 5, "name": "Rim"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [38, 38]}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [4, 4], "p1": [36, 36]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "Rim", "profiles": [{"point": [3, 3]}], "distance": 3, "operation": "join"}));
let st = s.model.state();
assert_eq!(st.bodies.len(), 2);
let v = |n: &str| solidcraft_kernel::measure(&st.body(n).unwrap().body).unwrap().volume;
assert!(rel(v("Plate"), 8816.0) < 1e-9 && rel(v("Plate (2)"), 8000.0) < 1e-9);
let f = s.doc.features.last().unwrap();
assert_eq!(f.participants, vec!["Plate".to_string()]);
// Showing the copy again doesn't change the model.
run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": true}));
assert_eq!(s.model.state().bodies.len(), 2);
}
/// A pre-command check that refuses one command id.
fn refusing(id: &'static str) -> CommandCheck {
std::sync::Arc::new(move |cmd: &str, _: &Value, _: &Session| if cmd == id { Err(format!("{cmd} is not allowed here")) } else { Ok(()) })
}
#[test]
fn without_a_command_check_every_command_runs() {
let mut s = Session::default();
assert!(s.command_check().is_none());
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]}));
assert_eq!(s.doc.features.len(), 2);
}
#[test]
fn a_command_check_refuses_a_command_and_leaves_the_design() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
s.set_command_check(Some(refusing("solid.box")));
let doc = s.doc.clone();
let (undo, revision) = (s.undo.len(), s.revision);
let r = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]}));
match r {
Err(EngineError::Refused { cmd, reason }) => {
assert_eq!(cmd, "solid.box");
assert_eq!(reason, "solid.box is not allowed here");
}
other => panic!("expected a refusal, got {other:?}"),
}
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "the design is unchanged");
assert_eq!((s.undo.len(), s.revision), (undo, revision));
// Other commands still run, and the check stays with the session across new designs,
// scripts and previews.
run(&mut s, "file.new", json!({"name": "Next"}));
assert!(s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1})).is_err(), "kept by file.new");
assert!(s.run_script(&json!([{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}])).is_err(), "scripts");
assert!(s.preview(&[("solid.box".into(), json!({"length": 1, "width": 1, "height": 1}))]).is_err(), "previews");
s.set_command_check(None);
run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1}));
}
#[test]
fn a_command_check_can_count_the_features() {
const MAX: usize = 3;
let mut s = Session::default();
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, Value)>::new()));
let log = seen.clone();
s.set_command_check(Some(std::sync::Arc::new(move |cmd: &str, params: &Value, s: &Session| {
if let Ok(mut log) = log.lock() {
log.push((cmd.to_string(), params.clone()));
}
if cmd.starts_with("solid.") && s.doc.features.len() >= MAX { Err(format!("at most {MAX} features")) } else { Ok(()) }
})));
for i in 0..MAX {
run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [i * 5, 0, 0]}));
}
let r = s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1, "corner": [50, 0, 0]}));
assert!(matches!(&r, Err(EngineError::Refused { .. })), "{r:?}");
assert_eq!(r.err().map(|e| e.to_string()).as_deref(), Some("at most 3 features"));
assert_eq!(s.doc.features.len(), MAX);
// The check saw each command's id and parameters.
let seen = seen.lock().map(|l| l.clone()).unwrap_or_default();
assert_eq!(seen.len(), MAX + 1);
assert!(seen.iter().all(|(id, p)| id == "solid.box" && p["length"] == 1));
}
#[test]
fn a_command_check_that_panics_refuses_the_command() {
let mut s = Session::default();
s.set_command_check(Some(std::sync::Arc::new(|_: &str, _: &Value, _: &Session| -> std::result::Result<(), String> { panic!("host bug") })));
let r = s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1}));
assert!(matches!(r, Err(EngineError::Internal(..))), "{r:?}");
assert!(s.doc.features.is_empty());
}