Skip to content

feat(brep): TrimmedCSGStump wires per-primitive Marschner trim-aware SDF#76

Open
lv416e wants to merge 2 commits intomainfrom
feat/trimmed-csg-stump
Open

feat(brep): TrimmedCSGStump wires per-primitive Marschner trim-aware SDF#76
lv416e wants to merge 2 commits intomainfrom
feat/trimmed-csg-stump

Conversation

@lv416e
Copy link
Copy Markdown
Owner

@lv416e lv416e commented Apr 24, 2026

Summary

  • Add TrimmedCSGStump and enrich_with_trim_frames: take a reconstructed CSGStump + its source shape and produce a differentiable composite whose cylinder / sphere / cone / torus primitives route through the Marschner signed blend while plane primitives continue to use their raw half-space SDF.
  • The asymmetry is deliberate (module docstring). Marschner replaces a primitive's untrimmed signed distance with a face-patch distance that is positive when the query projects outside the trim polygon. For curved primitives the untrimmed extension is the CSG phantom source, so the swap kills it. For plane primitives the untrimmed half-space is already the correct CSG ingredient — a closed convex polyhedron is exactly the intersection of its half-spaces — so swapping in a face-patch distance would break the DNF for queries inside the half-space but projecting outside the face.
  • Curved REVERSED faces multiply by sign_flip = -1 in the trim-aware wrapper; to keep the DNF semantics unchanged, the matching column in the intersection matrix is negated. Plane REVERSED faces keep their raw SDF unchanged so no column flip is needed.
  • Six tests on sample_box (plane-only, no phantom — trimmed sdf signs and volume match the untrimmed stump within grid noise) and box_with_holes (trimmed volume differs from untrimmed by more than 1 unit so the Marschner path actually activates, and a query directly above the box on a hole's axis is classified as outside).

Verification

  • uv run pytest 721 passed, 1 skipped (matplotlib), 54 deselected (slow)
  • uv run mypy src/ 0 errors
  • uv run ruff check src/ tests/ clean
  • uv run ruff format src/ tests/ clean
  • The quantitative before/after phantom-reduction benchmark on realistic models (PR D) is out of scope here. This PR just wires the machinery and verifies it is active.

Related

Add TrimmedCSGStump and enrich_with_trim_frames which take a
reconstructed CSGStump + its source shape and produce a
differentiable composite whose cylinder / sphere / cone / torus
primitives route through the Marschner signed-blend trim-aware SDF
while plane primitives continue to use their raw half-space SDF.

The asymmetry is deliberate and documented in the module docstring.
Marschner replaces a primitive's untrimmed signed distance with a
face-patch distance that is positive when the query projects outside
the trim polygon.  For curved primitives the untrimmed extension is
the CSG phantom source, so the swap kills it.  For plane primitives
the untrimmed half-space is already the correct CSG ingredient — a
closed convex polyhedron is exactly the intersection of its half-
spaces — so swapping in a face-patch distance would break the DNF for
any query inside the half-space but projecting outside the face.

Curved REVERSED faces multiply by sign_flip = -1 in the trim-aware
wrapper; to keep the DNF semantics the same, the matching column in
the intersection matrix is negated.  Plane REVERSED faces keep their
raw SDF unchanged so no column flip is needed.

Six tests on sample_box and box_with_holes lock in the wiring
without asserting quantitative phantom reduction (left to PR D):

- sample_box (plane-only, no phantom) -> trimmed SDF signs and
  volume match the untrimmed DifferentiableCSGStump within grid
  noise.
- box_with_holes -> trimmed volume differs from untrimmed by more
  than 1 unit (i.e. the Marschner path actually activates), and a
  query directly above the box on a hole's axis is classified as
  outside by the trim-aware stump.

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 24, 2026

Warning

Rate limit exceeded

@lv416e has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 9 minutes and 41 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 9 minutes and 41 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6b3c1d72-1185-4cf2-8baf-880c503a3f82

📥 Commits

Reviewing files that changed from the base of the PR and between 22bf116 and 8bd3c63.

📒 Files selected for processing (2)
  • src/brepax/brep/trimmed_csg_stump.py
  • tests/unit/brep/test_trimmed_csg_stump.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/trimmed-csg-stump

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces TrimmedCSGStump, which integrates Marschner signed-blend trim-aware SDFs into the CSG-Stump composition to eliminate phantom material from curved primitives like cylinders and spheres. While the implementation correctly handles face orientations and provides a differentiable volume integration path, the review identifies a significant issue: the current SDF dispatch for curved primitives relies on static frames and ignores the primitive objects, which breaks differentiability for those shapes. Additionally, the volume method should be updated to automatically compute bounding boxes when they are not explicitly provided, ensuring consistency with existing API patterns.

Comment thread src/brepax/brep/trimmed_csg_stump.py Outdated
Comment thread src/brepax/brep/trimmed_csg_stump.py Outdated
Two items from Gemini, both adopted:

- **Gradient flow (HIGH)**: the old design kept both primitives
  and frames with independently copied JAX arrays.  Curved
  primitive SDFs read from the frame, so gradients w.r.t. the
  primitives tuple were zeroed out.  Drop the primitives
  field entirely; frames are the single source of truth for
  differentiable parameters.  Plane dispatch now reads the
  outward-normal and origin from the frame directly as well, so
  every slot's gradient flows through frame fields.  A regression
  test verifies jax.grad over the stump produces finite
  gradients on at least one frame's normal.

- **Auto-bounds (MEDIUM)**: volume() accepts optional lo /
  hi and falls back on the bounding box captured at construction
  time.  enrich_with_trim_frames stashes the reconstructed
  stump's bbox_lo / bbox_hi when available (OCCT metadata
  path) and uses _primitives_bounds only as a secondary fallback,
  avoiding the warning emitted for infinite primitives such as
  planes.  Matches the ergonomics of DifferentiableCSGStump.

Unifying on frames also removes the plane/curved matrix-flip
asymmetry: all REVERSED slots now flip their matrix column because
every dispatch consumes the frame's convention (outward normal for
planes, sign-flipped radial distance for curved).  The module
docstring continues to explain why plane slots deliberately skip the
Marschner blend even though they read from the frame.

Eight tests pass (prior six plus the two new ones for bounds and
gradient flow); full suite 723 passed.

Co-Authored-By: Claude <noreply@anthropic.com>
@lv416e
Copy link
Copy Markdown
Owner Author

lv416e commented Apr 24, 2026

Gemini review resolved in this commit (HIGH + MEDIUM):

  • Gradient flow through frames (HIGH): dropped the redundant primitives field. Frames are now the single source of truth for differentiable parameters — plane dispatch reads normal/origin from the frame too, so every slot's gradient flows through frame fields. Added a regression test confirming jax.grad over the stump yields finite gradients on a plane frame's normal.

  • Auto-bounds (MEDIUM): volume() accepts optional lo/hi and falls back on the bounding box captured at construction time. enrich_with_trim_frames stashes stump.bbox_lo/bbox_hi (OCCT metadata) as the primary default and falls back on _primitives_bounds only if the stump has no box, avoiding the warning emitted for infinite primitives. Matches the ergonomics of DifferentiableCSGStump.

Unifying on frames also removes the earlier plane/curved matrix-flip asymmetry: all REVERSED slots now flip their matrix column because every dispatch consumes the frame's convention. The module docstring continues to explain why plane slots deliberately skip the Marschner blend even though they read from the frame.

8 tests pass (6 prior + 2 new); full suite 723.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant