r/OpenPythonSCAD • u/rebuyer10110 • Nov 05 '25
Auto unwind transformation scopes (using "with" statements in Python)
I’m excited to share something I’ve been building!
TL;DR: By combining monads, Python context managers (with statements), and incremental transform matrices, I can now auto-unwind transforms (translate/rotate/scale) within a scoped block. This eliminates the manual, error-prone process of restoring positions in CSG-style modeling.
Problem: In OpenSCAD/PythonSCAD, many operations (like rotate_extrude()) are origin-centric. When working with solids away from the origin, I’d manually translate, operate, then “undo” transforms. This has been a tedious and brittle process.
Solution: Using a monadic abstraction with Python’s context manager, I record each transform matrix on a stack. When the with block exits, transforms automatically unwind. The system tracks incremental matrices per operation and even allows manual overrides when needed.
Challenges: Calculating correct incremental matrices wasn’t always straightforward. Some operations (like unions) don’t yield predictable transforms. I added an “escape hatch” for manual overrides.
Demo:
- Example using monads: https://github.com/wiw-pub/ztools/blob/monads/examples/transformlineagemonad_example.py#L120-L169
- Comparison without monads: https://github.com/wiw-pub/ztools/blob/monads/examples/transformlineagemonad_example.py#L88-L117. Don't let the "less code" aspect fool you; it is much more manual and error prone. It takes much more tweaking to get those unwinding movements right.
View all comments
Show parent comment
3
u/Robots_In_Disguise Nov 05 '25
BREP definitely does have a huge learning curve compared to typical CSG tools out there. For that complexity there are many benefits though.
Regarding implicit parameters of build123d -- it is critical (and often ignored) to note that they are always optional by design in builder mode. There is also algebra mode which doesn't use implicit parameters at all.
Consider the following builder example with implicit parameters:
and without implicit parameters: