Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
46 changes: 25 additions & 21 deletions docs/demos.md
Original file line number Diff line number Diff line change
Expand Up @@ -1124,43 +1124,47 @@ Source: [`tests/live/test_live_sw_multi_body.py`](https://github.com/andrewbarte

### Boolean logic on a cube and a sphere {#boolean-logic}

![A blue 40 mm cube and an orange sphere on its top edge: joined, each cut by the other, their common quarter, then the exclusive or built from copies](assets/demos/multi-body/test_boolean_logic_on_a_cube_and_a_sphere-motion.gif)
![A blue 40 mm cube with an orange sphere of radius 25 at its centre, only its six caps showing: joined, each cut by the other, their common rounded cube, then the exclusive or built from copies and pulled apart into seven pieces](assets/demos/multi-body/test_boolean_logic_on_a_cube_and_a_sphere-motion.gif)

> *Example prompt:* Make a 40 mm cube and a 20 mm sphere centred on its
> top edge, as separate bodies, and show me every boolean of the two.
> *Example prompt:* Make a 40 mm cube and a sphere of radius 25 at its
> centre, as separate bodies, and show me every boolean of the two.

**What it shows.** Every boolean of two bodies, each one measured and then
deleted so the next starts from the same cube and sphere. The sphere sits
on the middle of the cube's top edge, so exactly a quarter of it,
8,377.6 mm³, is inside the cube, and every result has an exact volume:
deleted so the next starts from the same cube and sphere. The sphere is
centred in the cube and is 5 mm bigger than its half-side, so it pokes out
of each face as a cap 5 mm high, and the cube's corners and edges stick out
past the sphere. Each cap is πh²(3R − h)/3 = 1,832.6 mm³, six of them
10,995.6 mm³, and every result has an exact volume:

| Boolean | Tools | Expected | Measured |
| --- | --- | --- | --- |
| A 40 mm cube and, unmerged, a 20 mm sphere | `create_extrusion`, `create_revolve` | 64,000 + 33,510.3 mm³ | 64,000 + 33,510.3 mm³ |
| Union | `combine_bodies` add | 89,132.7 mm³, one body | 89,132.7 mm³ |
| Cube minus sphere | `combine_bodies` subtract | 55,622.4 mm³ | 55,622.4 mm³ |
| Sphere minus cube | `combine_bodies` subtract | 25,132.7 mm³ | 25,132.7 mm³ |
| Intersection | `combine_bodies` common | 8,377.6 mm³ | 8,377.6 mm³ |
| Exclusive or: both, less the shared quarter | `move_copy_body`, `combine_bodies` ×2, `move_copy_body` | 80,755.2 mm³, two bodies | 80,755.2 mm³ |
| A 40 mm cube and, unmerged, a sphere of radius 25 at its centre | `create_extrusion`, `create_revolve` | 64,000 + 65,449.8 mm³ | 64,000 + 65,449.8 mm³ |
| Union | `combine_bodies` add | 74,995.6 mm³, one body | 74,995.4 mm³ |
| Cube minus sphere: the corners and edges, hollowed | `combine_bodies` subtract | 9,545.7 mm³ | 9,545.8 mm³ |
| Sphere minus cube: the six caps | `combine_bodies` subtract | 10,995.6 mm³, six bodies | 10,995.4 mm³, six bodies |
| Intersection: a sphere with six flat faces | `combine_bodies` common | 54,454.3 mm³ | 54,454.2 mm³ |
| Exclusive or: the hollowed cube and the six caps | `move_copy_body`, `combine_bodies` ×2, `move_copy_body` | 20,541.3 mm³, seven bodies | 20,541.1 mm³, seven bodies |

SolidWorks has no exclusive-or feature, so it is built from the tools:
copy both bodies 100 mm aside, take the cube minus the sphere on one pair
and the sphere minus the cube on the other, then move the sphere's piece
back. Two calls fail **on purpose**: a body name that doesn't exist
(`invalid_input`, with the bodies there are) and an intersection of bodies
100 mm apart, which SolidWorks can't build (`feature_not_built`). The
colours are the demo's staging, not a tool: cube material is blue, sphere
material orange.
and the sphere minus the cube on the other, then move the six caps back.
Each cap is then pulled 15 mm out along its face's normal, so the seven
pieces can be seen. Two calls fail **on purpose**: a body name that doesn't
exist (`invalid_input`, with the bodies there are) and an intersection of
bodies 100 mm apart, which SolidWorks can't build (`feature_not_built`).
The colours are the demo's staging, not a tool: flat faces blue, curved
faces orange.

**Tool calls**

1. `create_part`, a 40 mm square on Top, `create_extrusion({"depth": 40})`
2. On Front: `add_centerline`, a half circle (`add_arc` three-point) and `add_line`; `create_revolve({"angle": 360, "merge_result": false})`
2. On Front: `add_centerline`, a half circle of radius 25 about (0, 20) (`add_arc` three-point) and `add_line`; `create_revolve({"angle": 360, "merge_result": false})`
3. `list_bodies` names them: `Boss-Extrude1` (cube) and `Revolve1` (sphere)
4. `combine_bodies({"operation": "add", "main_body": "Boss-Extrude1", "tool_bodies": ["Revolve1"]})`, then `delete_feature({"name": "Combine1"})`; the same for subtract both ways and common
5. `move_copy_body({"bodies": ["Boss-Extrude1", "Revolve1"], "translate": [100, 0, 0], "as_copy": true})`
6. `combine_bodies` subtract on each pair, `move_copy_body` the sphere's piece back by `[-100, 0, 0]`
7. `verify_model({"volume_mm3": 80755.2, "solid_body_count": 2})`
6. `combine_bodies` subtract on each pair, `move_copy_body` the six caps back by `[-100, 0, 0]`
7. `move_copy_body` each cap 15 mm out along its face's normal
8. `verify_model({"volume_mm3": 20541.3, "solid_body_count": 7})`

## Run a demo yourself

Expand Down
168 changes: 98 additions & 70 deletions tests/live/test_live_sw_multi_body.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""Multi-body tools (queue item 35), checked on real SolidWorks.

1. Boolean logic: a 40 mm cube (blue) and a 20 mm sphere (orange) centred
on its top edge, so a quarter of the sphere, 8,377.6 mm³, is shared.
Union (89,132.7 mm³), cube minus sphere (55,622.4), sphere minus cube
(25,132.7) and intersection (8,377.6), each shown, then deleted. Then the
exclusive or, from copies, two subtracts and a move back: two pieces,
80,755.2 mm³.
1. Boolean logic: a 40 mm cube (flat faces blue) and, at its centre, a
sphere of radius 25 (curved faces orange): the sphere's six caps stand
5 mm out of the faces and the cube's corners and edges out of the
sphere. Union (74,995.6 mm³), cube minus sphere (9,545.7, the corners
and edges), sphere minus cube (10,995.6, six caps) and intersection
(54,454.3), each shown, then deleted. Then the exclusive or, from
copies, two subtracts and a move back: seven pieces, 20,541.3 mm³,
the caps pulled out to show them.
On purpose: an unknown body, and an intersection of bodies that don't
touch.
2. A split and a keep: the block split at the Right Plane into two halves of
Expand Down Expand Up @@ -72,43 +74,49 @@ async def _extrude(


# A 40 mm cube on the Top Plane (x and z -20..20, y 0..40) and a sphere of
# radius 20 centred on the middle of its top right edge, (20, 40, 0). The
# edge cuts the sphere into quarters, so exactly one quarter is inside.
CUBE_MM3 = 40.0**3
SPHERE_MM3 = 4 / 3 * math.pi * 20**3
SHARED_MM3 = SPHERE_MM3 / 4
# radius 25 at its centre, (0, 20, 0). The radius is between the half side
# (20) and the half face diagonal (28.3), so each face cuts off one cap,
# 5 mm high, and the six caps don't meet: every volume is exact.
HALF_MM = 20.0
RADIUS_MM = 25.0
CENTRE_MM = (0.0, HALF_MM, 0.0)
CUBE_MM3 = (2 * HALF_MM) ** 3
SPHERE_MM3 = 4 / 3 * math.pi * RADIUS_MM**3
_CAP_H = RADIUS_MM - HALF_MM
CAPS_MM3 = 6 * math.pi * _CAP_H**2 * (3 * RADIUS_MM - _CAP_H) / 3
SHARED_MM3 = SPHERE_MM3 - CAPS_MM3
EXPLODE_MM = 15.0
COPY_OFFSET_MM = 100.0
_ISO_VIEW = 7 # swStandardViews_e.swIsometricView
_BLUE = [0.15, 0.45, 0.85]
_ORANGE = [0.95, 0.55, 0.1]


def _show(adapter: Any, bodies: list[dict[str, Any]]) -> None:
"""Colour each body by where it came from, then turn the camera isometric.
def _show(adapter: Any) -> None:
"""Colour every face by where it came from, then turn the camera isometric.

Staging for the viewer, not a tool call: a body holding cube material is
blue, one that is all sphere is orange. A body's box tells them apart:
the cube's starts at x = -20 (or -20 plus the copy offset).
Staging for the viewer, not a tool call: a flat face is the cube's
(blue), a curved one the sphere's (orange), so a result shows which
surfaces each body gave it.
"""
from solidworks_mcp.adapters import sw_type_info
from solidworks_mcp.adapters.solidworks.com_utils import double_array

model = adapter.currentModel
cube_like = {
b["name"]
for b in bodies
if abs((b["bounding_box_mm"]["min"][0] + 20) % COPY_OFFSET_MM) < 0.5
}

def paint() -> None:
part = sw_type_info.flagged(model, "IPartDoc")
for found in part.GetBodies2(0, False) or ():
body = sw_type_info.flagged(found, "IBody2")
rgb = _BLUE if body.Name in cube_like else _ORANGE
# R, G, B, ambient, diffuse, specular, shininess, transparency,
# emission, as a VT_R8 array: a plain list is misread.
values = [*rgb, 1.0, 1.0, 0.3, 0.3, 0.0, 0.0]
body.MaterialPropertyValues2 = double_array(values)
for raw in body.GetFaces() or ():
face = sw_type_info.flagged(raw, "IFace2")
surface = sw_type_info.flagged(face.GetSurface(), "ISurface")
rgb = _BLUE if surface.IsPlane() else _ORANGE
# R, G, B, ambient, diffuse, specular, shininess,
# transparency, emission, as a VT_R8 array: a plain list
# is misread.
values = [*rgb, 1.0, 1.0, 0.3, 0.3, 0.0, 0.0]
face.MaterialPropertyValues = double_array(values)

adapter._attempt(paint, default=None)
# A body left selected shows in the highlight colour, hiding its own.
Expand All @@ -122,6 +130,11 @@ async def _bodies(tools: dict[str, Any]) -> list[dict[str, Any]]:
return list((await _ok(await tools["list_bodies"]()))["bodies"])


def _is_cube(body: dict[str, Any]) -> bool:
"""A cube (or its copy) starts at y = 0; the sphere reaches below it."""
return bool(body["bounding_box_mm"]["min"][1] > -1)


def _brief(bodies: list[dict[str, Any]]) -> dict[str, Any]:
"""Body names and volumes, for a caption."""
return {
Expand All @@ -135,33 +148,36 @@ async def _cube_and_sphere(tools: dict[str, Any], adapter: Any) -> tuple[str, st
await _ok(await tools["create_part"]({"name": "boolean-logic"}))
await _extrude(tools, BLOCK, 40, merge=True)
await _ok(await tools["create_sketch"]({"plane": "Front"}))
centreline = {"x1": 20, "y1": 15, "x2": 20, "y2": 65}
x, y, _ = CENTRE_MM
low, high = y - RADIUS_MM, y + RADIUS_MM
centreline = {"x1": x, "y1": low - 5, "x2": x, "y2": high + 5}
await _ok(await tools["add_centerline"](centreline))
arc = {
"kind": "three_point",
"start_x": 20,
"start_y": 20,
"end_x": 20,
"end_y": 60,
"through_x": 40,
"through_y": 40,
"start_x": x,
"start_y": low,
"end_x": x,
"end_y": high,
"through_x": x + RADIUS_MM,
"through_y": y,
}
await _ok(await tools["add_arc"](arc))
await _ok(await tools["add_line"]({"x1": 20, "y1": 60, "x2": 20, "y2": 20}))
await _ok(await tools["add_line"]({"x1": x, "y1": high, "x2": x, "y2": low}))
await _ok(await tools["exit_sketch"]())
await _ok(await tools["create_revolve"]({"angle": 360, "merge_result": False}))
bodies = await _bodies(tools)
_show(adapter, bodies)
_show(adapter)
evidence(
"a 40 mm cube (blue) and a 20 mm sphere (orange), not merged; "
f"a quarter of the sphere, {SHARED_MM3:,.1f} mm³, is inside the cube",
"a 40 mm cube (blue faces) and, at its centre, a sphere of radius 25 "
f"(orange), not merged; {SHARED_MM3:,.1f} mm³ of the sphere is inside "
"the cube and its six caps stand out of the faces",
_brief(bodies),
call="list_bodies()",
)
assert sorted(b["volume_mm3"] for b in bodies) == pytest.approx(
[SPHERE_MM3, CUBE_MM3], rel=1e-4
sorted([SPHERE_MM3, CUBE_MM3]), rel=1e-4
)
cube = next(b["name"] for b in bodies if b["volume_mm3"] > SPHERE_MM3 * 1.5)
cube = next(b["name"] for b in bodies if _is_cube(b))
sphere = next(b["name"] for b in bodies if b["name"] != cube)
return cube, sphere

Expand All @@ -177,7 +193,7 @@ async def _combine_and_undo(
starting(label, f"combine_bodies({call})")
made = await _ok(await tools["combine_bodies"](call))
bodies = await _bodies(tools)
_show(adapter, bodies)
_show(adapter)
evidence(
f"{label} (expect {expected:,.1f} mm³)",
{**_brief(bodies), "feature": made["combine"]["name"]},
Expand All @@ -187,7 +203,7 @@ async def _combine_and_undo(
gone = {"name": made["combine"]["name"]}
await _ok(await tools["delete_feature"](gone))
restored = await _bodies(tools)
_show(adapter, restored)
_show(adapter)
evidence(
f"{gone['name']} deleted: the cube and the sphere are back",
_brief(restored),
Expand All @@ -196,15 +212,17 @@ async def _combine_and_undo(
assert len(restored) == 2


@pytest.mark.timeout(1200) # paced for a demo: a hold on every step
async def test_boolean_logic_on_a_cube_and_a_sphere(scratch: Any) -> None:
"""Every boolean of a cube and a sphere, each shown, measured and undone.

Union, cube minus sphere, sphere minus cube and intersection are one
``combine_bodies`` each. The exclusive or (keep what only one of them
holds, drop the shared quarter) has no SolidWorks feature, so it is
built from tools: copy both bodies aside, take the cube minus the sphere
on one pair and the sphere minus the cube on the other, then move the
sphere's piece back: the two pieces left are the answer.
holds, drop what they share) has no SolidWorks feature, so it is built
from tools: copy both bodies aside, take the cube minus the sphere on
one pair and the sphere minus the cube on the other, then move the
sphere's six caps back: the seven pieces left are the answer. Each cap
is then pulled out along its face's normal so the pieces show.
"""
adapter = scratch.adapter
tools = await _tools(adapter)
Expand All @@ -219,11 +237,11 @@ async def test_boolean_logic_on_a_cube_and_a_sphere(scratch: Any) -> None:

booleans = (
("union: one body", "add", cube, sphere, CUBE_MM3 + SPHERE_MM3 - SHARED_MM3),
("cube minus sphere: a bite out of the cube", "subtract", cube, sphere,
CUBE_MM3 - SHARED_MM3),
("sphere minus cube: three quarters of the sphere", "subtract", sphere,
cube, SPHERE_MM3 - SHARED_MM3),
("intersection: only the shared quarter", "common", cube, sphere,
("cube minus sphere: the corners and edges, hollowed", "subtract",
cube, sphere, CUBE_MM3 - SHARED_MM3),
("sphere minus cube: the six caps", "subtract", sphere, cube,
CAPS_MM3),
("intersection: a sphere with six flat faces", "common", cube, sphere,
SHARED_MM3),
) # fmt: skip
for label, operation, main, tool, expected in booleans:
Expand All @@ -235,15 +253,15 @@ async def test_boolean_logic_on_a_cube_and_a_sphere(scratch: Any) -> None:
copy["as_copy"] = True
copied = await _ok(await tools["move_copy_body"](copy))
bodies = await _bodies(tools)
_show(adapter, bodies)
_show(adapter)
evidence(
"exclusive or, step 1: both bodies copied 100 mm along x",
_brief(bodies),
call=f"move_copy_body({copy})",
)
assert copied["move"]["body_count_after"] == 4
far = [b for b in bodies if b["bounding_box_mm"]["min"][0] > 50]
cube_copy = next(b["name"] for b in far if b["volume_mm3"] > SPHERE_MM3 * 1.5)
cube_copy = next(b["name"] for b in far if _is_cube(b))
sphere_copy = next(b["name"] for b in far if b["name"] != cube_copy)

# On purpose: an intersection of bodies 100 mm apart shares nothing.
Expand All @@ -262,49 +280,59 @@ async def test_boolean_logic_on_a_cube_and_a_sphere(scratch: Any) -> None:
call = {"operation": "subtract", "main_body": main, "tool_bodies": [tool]}
await _ok(await tools["combine_bodies"](call))
bodies = await _bodies(tools)
_show(adapter, bodies)
_show(adapter)
evidence(
f"exclusive or, {label}", _brief(bodies), call=f"combine_bodies({call})"
)

# Step 4: slide the sphere's three quarters back onto the bitten cube.
caps = next(b["name"] for b in bodies if b["bounding_box_mm"]["min"][0] > 50)
back = {"bodies": [caps], "translate": [-COPY_OFFSET_MM, 0, 0]}
# Step 4: slide the sphere's six caps back onto the hollowed cube.
caps = [b["name"] for b in bodies if b["bounding_box_mm"]["min"][0] > 50]
back = {"bodies": caps, "translate": [-COPY_OFFSET_MM, 0, 0]}
await _ok(await tools["move_copy_body"](back))
bodies = await _bodies(tools)
_show(adapter, bodies)
_show(adapter)
evidence(
"exclusive or, step 4: the sphere's three quarters moved back onto the cube",
"exclusive or, step 4: the sphere's six caps moved back onto the cube",
_brief(bodies),
call=f"move_copy_body({back})",
)

expected = CUBE_MM3 + SPHERE_MM3 - 2 * SHARED_MM3
evidence(
"exclusive or: the bitten cube and three quarters of the sphere, "
f"two bodies, the shared quarter gone (expect {expected:,.1f} mm³)",
"exclusive or: the hollowed cube and the six caps, seven bodies, "
f"what they shared gone (expect {expected:,.1f} mm³)",
_brief(bodies),
)
assert len(bodies) == 2
assert len(bodies) == 7
total = sum(b["volume_mm3"] for b in bodies)
assert total == pytest.approx(expected, rel=1e-4)

# Pull the sphere's piece up 30 mm so both pieces show.
piece = next(b["name"] for b in bodies if b["volume_mm3"] < SPHERE_MM3)
lift = {"bodies": [piece], "translate": [0, 30, 0]}
await _ok(await tools["move_copy_body"](lift))
# Pull each cap out along its face's normal so the pieces show.
for body in bodies:
box = body["bounding_box_mm"]
if box["max"][0] - box["min"][0] > 30:
continue # the hollowed cube stays put
middle = [
(lo + hi) / 2 - c
for lo, hi, c in zip(box["min"], box["max"], CENTRE_MM, strict=True)
]
axis = max(range(3), key=lambda i: abs(middle[i]))
step = [0.0, 0.0, 0.0]
step[axis] = math.copysign(EXPLODE_MM, middle[axis])
out = {"bodies": [body["name"]], "translate": step}
await _ok(await tools["move_copy_body"](out))
bodies = await _bodies(tools)
_show(adapter, bodies)
_show(adapter)
evidence(
"the two pieces pulled 30 mm apart to show them",
f"the six caps pulled {EXPLODE_MM:.0f} mm out to show the pieces",
_brief(bodies),
call=f"move_copy_body({lift})",
call="move_copy_body once per cap, along its face's normal",
)

checked = await tools["verify_model"](
{"volume_mm3": expected, "solid_body_count": 2}
{"volume_mm3": expected, "solid_body_count": 7}
)
evidence("verify_model on the two pieces", {"verdict": checked.get("verdict")})
evidence("verify_model on the seven pieces", {"verdict": checked.get("verdict")})
assert checked.get("verdict") == "pass", checked


Expand Down
Loading