Skip to content

SDF ray marching: rays inside leave at the first exit - #144

Merged
StackEnjoyer merged 2 commits into
masterfrom
fix/sdf-inside-march
Oct 19, 2026
Merged

StackEnjoyer merged 2 commits into
masterfrom
fix/sdf-inside-march

Conversation

@TacHawkes

@TacHawkes TacHawkes commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Bugfixes

  • Changes results: rays inside non-convex SDF shapes (meniscus and concave lenses, rings, mirrors with holes, differences) could leave at a later exit or find none; 216 of 11,600 test rays on master, 0 of 29,000 now
  • Changes results: a ray that starts below an SDF surface is inside in any direction

Performance

  • Aspheric lenses ~55 % slower, spherical lenses ~7 % (more steps to leave the starting surface)

Deprecations

  • The preference sdf_inside_step (get_sdf_inside_step) is no longer used

Agent skill

  • No skill files affected

Closes #142

`_raymarch_inside` stepped a fixed 1 m along the ray and then marched
back from outside. It thus found the last exit within that metre, not
the first. Rays from a surface into an object (as after refraction)
compared with a reference from the sign of the SDF, 200 per shape for
58 shapes: 216 of 11600 left at a wrong point, by up to 33 mm, e.g. in
meniscus lenses, plano- and bi-concave lenses, concave and acylindrical
surfaces, rings, mirrors with holes and differences of SDFs; some found
no exit at all. In addition, `intersect3d` took a ray that starts below
the surface for a ray outside if the SDF increases along it, e.g. from
the middle of the wall of a ring towards its inner face.

The ray is now marched inside by the distance `-sdf`, which does not
pass the exit for an SDF that is exact or a lower bound inside:
- a minimum step leaves the starting surface and the internal faces of
  composite SDFs, where the SDF is about 0 within the object; a point
  with sdf about 0 is an exit only if the ray is outside just behind it
- an over-relaxed step (Keinert et al., 2014) is kept only if the balls
  around both ends cover it
- a step that ends outside brackets the exit, which is found by the
  Illinois method on the sign of the SDF; the returned point lies
  outside, at most `eps` behind the last point inside, such that the
  next ray from it does not start inside (Issue#11 would fail otherwise)
- the normal is evaluated `eps` outside of the exit, as for hits from
  outside: inside a composite SDF the gradient may stem from another
  part, and exactly on the surface some SDFs have no gradient; a normal
  against the leaving ray (a part that touches the exit point from
  outside, Issue#82) is evaluated `h` outside instead
- a ray below the surface counts as inside in any direction

The same 58 shapes with 500 rays each: 0 of 29000 wrong in exit point,
normal or side of the surface. New tests: a ring wall and a lens in
`TestAbstractSDF.jl`, all shapes of `TestSDFBoundingSpheres.jl` against
the sign reference. The preference `sdf_inside_step` is no longer used.

Cost: an aspheric lens takes ~55 % longer (2000 rays 17.8 -> 27.8 ms,
before the speed-up of the aspheric SDF in #137), spherical lenses ~7 %:
leaving the starting surface needs more steps than the jump did.

Fixes #142
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@TacHawkes TacHawkes added this to the v0.14.0 milestone Oct 11, 2026
@codecov

codecov Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.11321% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.31%. Comparing base (66b711e) to head (1c4c17c).

Files with missing lines Patch % Lines
src/SDFs/AbstractSDF.jl 98.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #144      +/-   ##
==========================================
+ Coverage   89.22%   89.31%   +0.09%     
==========================================
  Files          81       81              
  Lines        4500     4539      +39     
==========================================
+ Hits         4015     4054      +39     
  Misses        485      485              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

`_bracketed_exit` returned the outer end of the final bracket, which
moves in steps of the bracket width `eps` when a parameter of the setup
changes. Finite differences saw this as noise: the derivative of a spot
position w.r.t. a lens shift differed from ForwardDiff by 7e-6 relative
(1e-11 on master), which matters for optimizers and tolerancing based on
finite differences.

The exit is now the secant root of the final bracket with the unscaled
SDF values. It changes continuously, and lies within `eps` of the
surface, far below the threshold `h` at which the next ray from it would
count as starting inside. Finite differences and ForwardDiff agree to
~1e-11 again.

Part of #142
@TacHawkes TacHawkes added the bug Something isn't working label Oct 11, 2026
@StackEnjoyer

StackEnjoyer commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

This issue is fundamentally rooted in the original assumption that all SDFs implemented in BMO are sufficiently convex. This has been the case for most practical purposes since I introduced SDFs and my "interpretation" of ray-marchign, however, the assumption does not hold for more and more shapes as we push the capabilities of BMO.

This PR is a stopgap measure that fixes the shortcomings of a narrowly designed system. I am in principle fine with this. However, we should consider if the entire ray-marching procedure should be overhauled in light of the major breaking 0.14 release. I think now would be a good time to fix this once and for all with a much more sophisticated, robust algoritm.

@TacHawkes

Copy link
Copy Markdown
Collaborator Author

Agreed on the diagnosis. The root problem is broader than convexity: sphere tracing is only safe for exact (or Lipschitz ≤ 1) distance fields, and many of ours are not. Union and difference via min/max are not distances inside the shape, and the conics and aspheres are only bounds. The inside march takes blind fixed steps of dl. The string of bugs behind this PR (union seams, normals taken from the wrong operand, exit points nm inside or exactly on the surface) all come from that.

My proposal for a proper fix:

  • Ray-interval CSG instead of marching. Each primitive returns the entry/exit intervals of a ray, with analytic normals: closed form for planes, spheres, cylinders and cones; a bracketed Newton/bisection root find for aspheres and acylinders, as sequential optical design codes do. Union, intersection and difference become set operations on these interval lists. This is exact for non-convex shapes and for rays that start inside or on the surface, and it removes the eps/h/dl tolerances. It is also much faster than 50–1000 SDF evaluations per ray, and AD-friendly.
  • Keep marching as the fallback for user-defined SDFs, so the extension promise holds. Harden it with Lipschitz bounds (segment tracing) and a bracketed root refinement in place of the fixed dl.

On timing: I'd merge this PR now. Its tests and the analytic references from #156 make a good regression base for the rewrite. The geometry backend is mostly internal, so the rewrite is only breaking if the interface for custom SDFs changes. For 0.14 I'd only reserve that hook, e.g. an optional intersect_intervals(shape, ray) that defaults to marching, and do the actual rewrite in 0.15 without time pressure. Happy to write up a design issue.

@StackEnjoyer
StackEnjoyer merged commit d27a435 into master Oct 19, 2026
7 checks passed
@StackEnjoyer
StackEnjoyer deleted the fix/sdf-inside-march branch October 19, 2026 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rays inside an SDF shape can leave at the wrong point

2 participants