r/OpenPythonSCAD • • Nov 08 '25

Text + SVG + Extrude?

Thumbnail reddit.com
2 Upvotes

r/OpenPythonSCAD • • Jun 25 '25

wrap function more versatile

5 Upvotes

Always wrapping around a cylinder is quite boring.

Why dont wrap around an arbritary shape ?

'''

from openscad import *

perim=circle(r=5,fn=30)

perim |= square([8,4])+([0,-2])

wall=cube([38.1,0.5,6])

wall -= [ cylinder(r=0.3,h=3,fn=6).rotx(-90)+ [1+2*x+( y & 1),-1,1+1.8*y]

for x in range(19) for y in range(3) ]

wall.wrap(perim).show()

'''

ITs already available in the latest repo. Installers will flollow later

Creating Litopanes becomes super-easy.

Next step is probably bending towards z axis


r/OpenPythonSCAD • • Sep 12 '25

Do we have a full list of operators and their functionalities?

4 Upvotes

I'm aware of these and what they do:

| union

- difference

& intersection

* scale

+ translate

Just today though I learned that ^ has some sort of loop functionality for placing grids. I learned this halfway through my process of assigning it to hull. What other's are in use, I'm currently got @ assigned to rotation so no idea if that overriding anything, and I'd been think on how best to use the other operators but if they're already in use I'd like to know about that before I start giving them vital roles in my code.


r/OpenPythonSCAD • • Jun 17 '25

osimport() error

2 Upvotes

openscad built from the latest openscad/openscad git commit. can show a cube just fine via python. but when I try to osimport() an stl, I get an error:

Running Python 3.13.3 without venv.
ERROR: Traceback (most recent call last):
  File "<string>", line 5, in <module>
NameError: name 'osimport' is not defined

Execution aborted

my file:

from openscad import *
fa=2
fs=.1

d=osimport("cs/2.stl")
d.show()

r/OpenPythonSCAD • • Jul 17 '25

Offset delta

2 Upvotes

Can't tell if this is a bug, or unintuitive inputs. I can't get delta to work with offsets.

I expected square(2).offset(delta=1).show() to produce the same results as scad("offset(delta=1)square(2);").show() but it just produces an error

ERROR: Traceback (most recent call last): File "<string>", line 10, in <module> TypeError: Error during parsing offset(object,r)

r/OpenPythonSCAD • • Mar 17 '25

A work in progress: honeycomb mesh as a library on top of pythonscad

Post image
6 Upvotes

r/OpenPythonSCAD • • Dec 14 '25

Understanding where modules are loaded from and how to update

3 Upvotes

I am trying to load fullcontrolgcode: https://github.com/FullControlXYZ/fullcontrol

and found it necessary to manually load it into:

C:\Users\willa\OneDrive\Documents\OpenSCAD\libraries

along w/ pydantic and pydantic_core, which were successful.

Trying to load typing_extensions.py so as to avoid the error:

ImportError: cannot import name 'Sentinel' from 'typing_extensions' (unknown location)

which is being loaded from:

File "C:\Users\willa\OneDrive\Documents\OpenSCAD\libraries\pydantic_core_init_.py", line 6, in <module> from typing_extensions import Sentinel

but despite replacing every copy of typing_extensions.py, it hasn't worked. There are two associated files:

  • test_typing_extensions.py

  • _typed_dict_test_helper.py

do they also need to be replaced?

There is an "extensions.pyc" file in C:\Program Files\PythonSCAD\python312.zip --- does it need to be replaced?


r/OpenPythonSCAD • • Jun 26 '25

How do I add new processes in .Process notation?

2 Upvotes

I thought I had figured out the differences and capacitates of pythonSCAD well enough to move onto my first project with it, but this is proving incorrect. I need to rebuild my SCAD library before I can really do anything. I've got it imported using 'osuse', and so far everything is working fine. I have to give it a local definition, to avoid having to constantly call the overarching library, but this is a small issue.

I have this in a scad file named ALib:

module MirrorAnd(m=[1,0,0]){
    children();
    mirror(m)
    children();
}

And I have this in a py file:

from openscad import *
ALib=osuse("ALib.scad")

MirrorAnd=ALib.MirrorAnd

c=cube(4);
c=c.translate([2,0,0])
c=MirrorAnd(c,[1,0,0])

c.show();

This works fine, I could alternatively rebuild the function as:

def MirrorAnd(self,vec):#{
    return union(self,self.mirror(vec))
#}

My issue is that I want to use it in the format of c.MirroAnd(vec) instead of MirroAnd(c,vec). I've been playing around with this and have been unable to figure out how to do it. This isn't the only function I need to do this for, with other ones being much more integral to my code practices.

Edit: I've gotten some stuff to work using the forbiddenfruit library. Given the name, its quite apparent that this solution is of a dubious quality, but it works and thats all that matters.


r/OpenPythonSCAD • • Aug 28 '25

Adding customized member functions

5 Upvotes

One of the problems with PythonSCAD so far was, that python does not allow to extend builtin data types.

People which decided to go with PythonSCAD soon wanted to add their own member functions to solids and failed. They put hard efford to subclass openscad to circumvent this restriction.

With latest release this is not needed anymore . Define a custom function and just register it. (see exmple)

This is a simple example but it can be easily extended


r/OpenPythonSCAD • • Oct 25 '25

Are older versions accessible?

3 Upvotes

I ran into a bug that crashes on newer versions. I want to install an older version to see which version the crash started.

Is there a place to view and download older versions?


r/OpenPythonSCAD • • Feb 10 '26

Triangular Shelf for Laser cutting

4 Upvotes

Today I plan to create something for my daughter , a wooden shelf where she

can put her collected stones and dinosaurs.

This is made from interlocking plywood sheets in 3 different directions.

The opening gap is enlarged by Tan(60) to support the acute angle where the single pieces

cross. Look forward to realizing that in real life.


r/OpenPythonSCAD • • Apr 15 '26

PythonSCAD v0.20.0 released

8 Upvotes

Hi everyone,

We’re happy to announce PythonSCAD v0.20.0. The headline change is session management: the app can remember how you left off and bring that workspace back on the next launch. This is similar to what applications like NotedPad++ and Visual Studio Code are doing. We’ve also improved reliability in a few places, rounded out Python API documentation, and made small quality-of-life updates. Full technical notes are in the changelog on the release PR.

Session management (new)

v0.20.0 introduces session persistence. When you quit and reopen PythonSCAD, you can get back your open tabs and editors, multi-window layout, customizer state, view and find state, and per-tab language—so routine work is easier to resume without rebuilding your environment from scratch.

The feature also includes autosave-style crash recovery, a clearer flow when closing tabs with unsaved changes, and a session option in Advanced preferences if you want to control the behavior. Customizer tweaks can apply without always pressing F5, and the stack includes dry-run safety so heavy preview work is harder to trigger by accident.

All of this ships as one coherent capability (see PR #415).

Note: To go back to the old behavior, you can go to Edit > Preferences > Advanced and disable the session management option. We tested this new feature quite extensively, but any feedback or bug reports on this new feature will be highly appreciated.

Improved unsaved-files dialog

When you want to close PythonSCAD a new dialog will list unsaved tabs and allow you to individually save them or decide to not save the remaining unsaved changes.

Save dialogs and editor language

Save and Save As now match the editor language you’re in: suggested names and filters line up with .py vs .scad, including sensible default folders so native file dialogs behave reliably. This addresses incorrect defaults some people hit in Python mode (#534).

Thanks @bereldhuin for reporting this.

Reliability and polish

  • Context menu / right-click handling is more robust, with fewer crashes in edge cases.

  • The measure tool again shows correct vertex indices when you need them.

  • Windows builds use the PythonSCAD logo in the application and nightly resources (#543, #544).

Documentation

Upstream changes

Of course we merged all changes from OpenSCAD into our codebase again to get the latest bugfixes and enhancement from our upstream project.

Downloads

Pre-built packages are available for Linux (AppImage, .deb, .rpm), macOS (DMG), and Windows (installer and zip):

https://pythonscad.org/downloads/

As always, we’d love to hear from you—feedback and bug reports are welcome!


r/OpenPythonSCAD • • Nov 29 '25

Initial 3D workflow (by way of gcodepreview)

Thumbnail
imgur.com
3 Upvotes

r/OpenPythonSCAD • • Feb 01 '26

How do I set global variables in openscad code from pythonscad

2 Upvotes

I'm a novice to python and especially to pythonscad. How can I set global openscad variables from pythonscad when I use osuse().

This is the python code:

from openscad import *

ska=osuse('./scad/skådis/skådis.scad')

ska.fn = 30
ska.xtolerence = -0.2
ska.ytolerence = 0.2
ska.thk = 5
ska.cols = 10
ska.rows = 10
ska.top = 0
ska.bottom = 0
ska.rounding = 2
ska.walldist = 6
ska.start = 0
ska.spacerDiameter = 8
ska.support = []
ska.screwholes = []
ska.color = "white"

obj=ska.pegboard()
show(obj)

And this is the openscad code:

include <../Round-Anything-master/polyround.scad>

$fn = 30;
xtolerence = -0.2;
ytolerence = 0.2;
thk = 5;
cols = 19;
rows = 19;
top = 0;
bottom = 0;
rounding = 2;
walldist = 6;
start = 0;
spacerDiameter = 8;
support = [];
screwholes = [];
color = "white";

I don't get any errors, but it doesn't change anything to the result either


r/OpenPythonSCAD • • Mar 31 '26

New Release v0.19.1

4 Upvotes

Hi everyone,

Quite some time has passed , many things happened and time is ready to publish a new release v0.19.1.

New nice GUI icons for Export to File

The Formats STEP, Postscript and GCODE did not have any symbols and appeared

as boring text. This is fixed now. William Adams has volunteered to create nice symbols

and made PythonSCAD use them

Formats:

CDR: Yes, there is a new format: PythonSCAD can read CorelDraw (.cdr) now. CDR is closed source, so it's not public but there is libcdr which can do the task and it works

pretty good. Everything which you could do to SVG before, also applies to CDR

SVG: There is better support for reading in SVG Files. Style and Class attribute are parsed and evaluated

Better GCODE Quality

Already in the last Release PythonSCAD was able to create GCODE. Especially in my

Laser cutter, I experience, that cut quality becomes weaker in the right front corner,

probably because it's more distant to the laser tube and the focus becomes more blur ?

However, the solution is to reduce speed and this can be automated with the feedAddX and feedAddY property. When both are configured with -1, the feed rate reduces with the

manhattan distance to the origin.

Other improvements are better arrangements of the cuts within the file. engrave goes before the cut and cuts are from inner to outer, outer cuts are arranged according to the "travelling salesman problem" to minimize traveling between the cuts.

Improved 2D CSG engine

For some special 2D shapes with lots of holes, PythonSCAD got it wrong or added

way too many edges between 2D Union results. This  especially bad, if the edges 

are sent to a laser cutter. Anyway, its fixed

New Primitive polyline

PythonSCAD got a new primitive 'polyline'  which is basically concatenated lines and can have color. They are not only "nice to have" but are actually very meaningful. There are many situations in lasercut where you just want stripes instead of closed polygons. Polylines come in 2 variants:

2D : Very useful to create laser cut temples. Their color can encode  laser power.

3D: Can be used to visualize the toolpath of a 3D printer or any other 3D machine.(William, that's for you!)

Many small fixes in the GUI:

These are mainly small fixes during usage which might be disturbing, internal refactoring, trust handling,  fix crashes, making things smooth. Thanks nomike!

Backward compatibility

As always, we strive to stay in sync with the latest versions of OpenSCAD. All new features and bugfixes of OpenSCAD are included here in addition

Documentation:

All details about new polyline, machineconfig can be found within the tutorial

Downloads

Pre-built packages are available for Linux (AppImage, .deb, .rpm), macOS (DMG), and Windows (installer and zip):

https://pythonscad.org/downloads/

As always, we'd love to hear from you — feedback and bug reports are welcome!

PS: here's a small application of polyline to make a plywood bend test(and it bends greatly)


r/OpenPythonSCAD • • Sep 18 '25

PythonSCAD got a new primitive

7 Upvotes

Its called 'sheet' and it can be used to create a surface which established by sweeping 2 indepent variables.

Simples case might be this one:

But this can be arbritary extended

This could be a solid car tire. its closed by i and j variable.

This is basically a rotate_extruded lisajous shape.

Look forward to testing more fancy shapes


r/OpenPythonSCAD • • Nov 05 '25

Auto unwind transformation scopes (using "with" statements in Python)

3 Upvotes

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:


r/OpenPythonSCAD • • Jan 22 '26

OpenPythonSCAD vs. PythonSCAD

4 Upvotes

Is OpenPythonSCAD a legacy name? The repository https://github.com/pythonscad uses PythonSCAD name.


r/OpenPythonSCAD • • Mar 24 '26

Creating Gears in PythonSCAD

4 Upvotes

PythonSCAD cannot yet create gears, so I coded some functions together with AI.

The Result is a small code snippet which can be used to create 2D gears with quite some parameters(Modus, Teeth, Spokes, HoleDiameter)

You could immeately make use of them by exporting that to GCode and send to your laser cutter. Alternatively, linear_extrude them and use in your 3D design

BTW Code is here: https://bpa.st/OHEA


r/OpenPythonSCAD • • Sep 02 '26

PythonSCAD is getting user-defined Customizer widgets (PyQt6-powered) — coming in 1.2

5 Upvotes

Hey folks, Wanted to share something we've been building for PythonSCAD: the Customizer sidebar can now host fully custom, Python-defined input widgets — not just the built-in sliders, checkboxes, and dropdowns.

What does that actually mean?

Normally, add_parameter() gives you a fixed set of widget types based on the default value you pass in — a number gets a slider, a string gets a text box, a list gets a vector editor, and so on. That covers a lot of cases, but not everything. Sometimes you want something the built-in types just can't express well. With this change, you can register your own widget, built with PyQt6 (which now ships bundled with PythonSCAD), and hook it directly into the Customizer:

add_parameter_widget("color_picker", color_picker_factory)
linecolor = add_parameter("linecolor", "#ff00ff", type="color_picker")
cube(10).color(linecolor)

color_picker_factory is just a normal Python function that returns a PyQt6 widget — in this case a button that pops a native color dialog and reports its value back. From the Customizer's point of view, it behaves exactly like any other parameter: it saves to sets, restores on load, and drives a live preview re-render the moment you change it. One thing worth calling out: add_parameter_widget() itself belongs in your .pythonscadrc, not in the model script. It's registering a widget type, not something tied to a particular design, so it lives with your personal setup and is available to every script you open, the same way you'd register a menu item or an editor helper. (Side note: PyQt6-based custom input windows aren't actually new here — user modules could already pop their own PyQt6 dialogs, e.g. for interactively editing a polygon's points. What's new is hooking a custom widget directly into the Customizer sidebar itself.) Because the widget is just PyQt6, this isn't limited to color pickers — anyone can build their own: a polygon point-editor with drag handles, a curve editor, a searchable dropdown, a live 3D preview widget, whatever your script needs. If PyQt6 can render it, the Customizer can host it.

Demo

Here's a short video showing it in action (color picker widget, live-driven from the Customizer): 🎥 https://www.youtube.com/watch?v=OESyfZGZj_I

Where this is headed

This is landing as part of PythonSCAD 1.2, which is on its way — the PyQt6 connector work that makes this possible has already been merged. More documentation and examples will follow closer to release.


r/OpenPythonSCAD • • Jan 07 '26

Dropping QT5 support for Windows

5 Upvotes

Today MSYS2 introduced an update to qt5-base which broke the qt5 build for PythonSCAD.
I asked on their Discord for advice but didn't receive any response.

As QT5 is end of life since 26th of May 2025, I just decided to no longer test it on Windows or build releasables for it. As QT is bundled with PythonSCAD on Windows, I don't think there will be much impact by this change.

We already had QT5 phased out from macOS when I joined the project last year as QScintilla (the source code editor component PythonSCAD uses) is not packaged for QT5 on macOS Homebrew.

So as of now QT5 versions are only built for Linux (especially since there are no QT6 builds for Ubuntu 22.04 LTS which still supported by Canonical until April 2027).

I heard that OpenSCAD is considering phasing out QT5 altogether, at which point we will most likely follow suit.

Let us know if the removal of a QT5 version for Windows is an issue for you.


r/OpenPythonSCAD • • Jan 01 '26

New: Automated release builds and semantic versioning

4 Upvotes

Happy new year to y'all!

I've started contributing to PythonSCAD a couple of months ago when I was trying to package it for GNU Guix.

In the past few months I was focusing on the build system and recently was able to finalize a few major things:

In order to simplify releases, we've abandoned the date based version numbers we inherited from OpenSCAD and switched to semantic versioning. We also introduced Release Please, to help with change-log- and release-management.

PythonSCAD now also has fully automated release builds for Linux (AppImage), Windows (MXE cross compiled) and macOS (universal binaries).

For now, new releases can be found on the GitHub Releases page, but I'm working on publishing them to < https://pythonscad.org> as well soon.

And if any of you spot any issues or crashes, please create an issue on GitHub. It helps us tremendously.

So, what's your opinion on all of this?


r/OpenPythonSCAD • • Oct 23 '26

Fourier epicycles as real gears – a parametric drawing machine in PythonSCAD

3 Upvotes

Title: Fourier epicycles as real gears – a parametric drawing machine in PythonSCAD


You've probably seen those videos where a chain of rotating circles draws a horse, a portrait or a signature. The math behind it is the complex Fourier series, and the best interactive explanation I know is Jez Swanson's An Interactive Introduction to Fourier Transforms: https://www.jezzamon.com/fourier/ – you can even draw your own shape there and watch it being rebuilt from circles.

I wondered: can this be built as real geometry? Turns out yes, and PythonSCAD is a perfect fit for it.

https://imgur.com/a/KfwOoTa

The idea in three lines

Treat the drawing as a complex curve z(t) = x(t) + i·y(t). Its Fourier series is

z(t) = Σ  c_k · e^(i·k·t)

Every term is an arm of length |c_k| that starts at angle arg(c_k) and rotates k times per revolution. Chain the arms tip to tip and the last tip traces the shape.

Why this is buildable

The frequencies k are integers – and integer speed ratios are exactly what gears do. Each arm sits on a small planetary stage:

  • a sun fixed to the arm two levels below (the base for arm 2),

  • a planet fixed to the new arm, riding at the tip of the arm in between (the carrier).

With carrier speed c, sun speed s and ratio ρ = Z_sun / Z_planet:

  • direct gear mesh: planet = c + (c − s)·ρ → gives 2×, 3×, …

  • open belt: planet = c − (c − s)·ρ → gives 0, −1×, −2×, … (negative frequencies are essential for closed shapes!)

The script picks mesh or belt automatically, computes integer tooth counts, aligns the teeth so they really mesh in every pose, and refuses impossible combinations.

The collision problem

My first version had the pen hanging down through the whole stack – straight through the base gear. The fix: in this stack every part lives in its own layer, and the last arm is always the outermost one. So the whole mechanism hangs upside down from a bridge, the last arm is the lowest, and the pen draws downwards onto paper, resting on it by gravity in a sleeve. The motor sits on top of the bridge and drives arm 1 via a pinion. The frame columns are placed outside the computed swept envelope of all parts.

https://imgur.com/a/yEhWmkb

What can 4 arms draw?

ShapeKLPHI
Heart-1, -3, 2, -237.5, 9, 7.5, 7.590, 270, 270, 270
3-star, sharp tips1, -2, 4, -536, 18, 9, 50, 0, 0, 0
5-star with loops1, -4, 6, -936, 16, 8, 40, 0, 0, 0
7-rosette with loops1, -6, 8, -1336, 14, 8, 40, 0, 0, 0

The heart is a genuine Fourier approximation: the four largest terms of the classic heart curve.

https://imgur.com/a/vet3rgW

Rules of thumb for your own designs:

  • Symmetry: if all k leave the same remainder mod m, the curve has m-fold rotational symmetry (1, −2, 4, −5 → 3-fold).

  • Sharp tips: a cusp appears where the pen velocity Σ k·L·ei(kθ+φ) vanishes – e.g. 1·36 = 2·18 in the 3-star.

  • Loops: a high frequency whose k·L comes close to that of the base term makes loops.

  • Calm shapes: let L fall off roughly like 1/|k| or faster.

  • Keep gear/belt ratios below ~1:8.

The model

Set K, L, PHI at the top, THETA is the drive angle of the shown pose (nice as an add_parameter slider to crank the machine by hand). The console prints the transmission of every stage and the swept envelope.

# Fourier epicycle drawing machine - assembled demo model for PythonSCAD
#
# Arm i rotates with the absolute angle  K[i]*THETA + PHI[i]  and has length L[i].
# The pen at the tip of the last arm therefore traces
#     z(t) = sum_i  L[i] * exp(j*(K[i]*t + PHI[i]))
#
# Stack (mechanism coordinates, built bottom-up, then flipped upside down):
#   base plate  -> drive layer (drive gear on arm 1 + motor pinion)
#   -> arm 1 -> gear layer 1 -> arm 2 -> gear layer 2 -> ... -> arm N
# Every layer only holds parts at its own height; the only part crossing layers
# would be the pen. Since arm N is the outermost layer, the pen side beyond it is
# collision free. The mechanism therefore hangs from a bridge, arm N is lowest,
# and the pen draws downward onto paper (gravity-loaded in a sleeve).
#
# Arm i (i >= 2) is driven by a planetary stage: a "sun" fixed to the body two
# levels up the chain (base for arm 2) and a "planet" fixed to arm i, linked by
# direct gear mesh (planet = c + (c-s)*rho) or by an open belt
# (planet = c - (c-s)*rho), with c = carrier speed, s = sun speed, rho = Zsun/Zplanet.

from openscad import *
import math
from fractions import Fraction

# ---------------- parameters ----------------
K     = [1, 2, -1]     # absolute frequency of each arm (integer multiples of the drive)
L     = [40, 20, 10]   # arm lengths = amplitudes [mm]
PHI   = [0, 30, 90]    # phase of each arm [deg]
THETA = 0              # drive angle of the displayed pose [deg]

T_ARM     = 3      # arm plate thickness
T_GEAR    = 5      # gear / pulley layer thickness
GAP       = 0.5    # vertical play between layers
BASE_T    = 4      # bridge plate thickness
HUB_R     = 4      # radius of the arm ends
POST_R    = 1.5    # axle radius
CLR       = 0.3    # radial clearance of rotating parts on their axles
MIN_TEETH = 12     # minimum tooth count of any planetary gear
PULLEY_R  = 5      # preferred radius of the planet pulley (belt stages)
BELT_T    = 1.2    # belt thickness

DRIVE_ZG  = 36     # teeth of the drive gear on arm 1
DRIVE_ZP  = 12     # teeth of the motor pinion
DRIVE_M   = 1.5    # module of the drive pair
DRIVE_DIR = 0      # direction of the motor seen from the center [deg]
MOTOR_R   = 12
MOTOR_H   = 25

PEN_CLEAR = 15     # distance from the lowest mechanism part to the paper
SLEEVE_L  = 8      # pen guide sleeve below arm N
TABLE_T   = 6
PAPER_T   = 0.3
COL_R     = 4      # frame column radius
MARGIN    = 4      # clearance between swept envelope and columns

CURVE_W    = 0.6   # half line width of the traced curve
CURVE_STEP = 2     # sampling step of the traced curve [deg]
FN         = 48

COLORS = ["red", "dodgerblue", "gold", "limegreen", "orange", "purple"]


# ---------------- helpers ----------------
def polar(r, a):
    """Polar to cartesian, angle in degrees."""
    return [r * math.cos(math.radians(a)), r * math.sin(math.radians(a))]

def at(obj, xy, z=0, a=0):
    """Rotate around own z axis by a degrees, then move to xy / height z."""
    return obj.rotate([0, 0, a]).translate([xy[0], xy[1], z])

def union_all(objs):
    """Balanced union to keep the CSG tree shallow."""
    while len(objs) > 1:
        objs = [objs[i] | objs[i + 1] if i + 1 < len(objs) else objs[i]
                for i in range(0, len(objs), 2)]
    return objs[0]

def hole(r, h):
    return cylinder(r=r, h=3 * h, center=True, fn=24)

def gear2d(z, r_pitch):
    """Simple trapezoidal-tooth gear outline, tooth 0 centered on +x."""
    m = 2 * r_pitch / z
    ra, rr = r_pitch + m, r_pitch - 1.25 * m
    p = 360 / z
    pts = []
    for j in range(z):
        for r, f in [(rr, -0.3), (ra, -0.12), (ra, 0.12), (rr, 0.3)]:
            pts.append(polar(r, j * p + f * p))
    return polygon(pts)

def gear(z, r_pitch, h):
    return linear_extrude(gear2d(z, r_pitch), height=h)

def mesh_angle(a_s, beta, zs, zp):
    """Rotation of gear 2 so that it meshes with gear 1 (rotated a_s).
    beta = direction from gear 1 center to gear 2 center."""
    u = (beta - a_s) * zs / 360
    e = (round(u) - u) * 360 / zs          # offset of the sun tooth nearest the contact line
    return beta + 180 - e * zs / zp - 180 / zp

def pulley(r, h):
    """Plain pulley with an off-center mark so its rotation is visible."""
    return cylinder(r=r, h=h, fn=FN) - at(hole(r * 0.15, h), polar(r * 0.6, 0))


# ---------------- kinematics ----------------
N = len(K)
assert len(L) == N and len(PHI) == N, "K, L and PHI need the same length"

kk = [0] + K                                            # body 0 = base (speed 0)
A = [0] + [K[i] * THETA + PHI[i] for i in range(N)]     # absolute angle of body j
Pos = [[0, 0]]                                          # Pos[j] = tip of arm j
for i in range(N):
    d = polar(L[i], A[i + 1])
    Pos.append([Pos[-1][0] + d[0], Pos[-1][1] + d[1]])
reach = [sum(L[:j]) for j in range(N + 1)]              # max distance of Pos[j] from center

STAGE_H = T_ARM + T_GEAR + 2 * GAP
Z_DRIVE = BASE_T + GAP                                  # drive layer (mechanism coords)
def z_arm(i):  return Z_DRIVE + T_GEAR + GAP + (i - 1) * STAGE_H   # bottom of arm i
def z_gear(j): return z_arm(j) + T_ARM + GAP                       # gear layer below arm j+1
Z_MECH = z_arm(N) + T_ARM + 1                           # incl. axle cap at the last joint

def col(j):
    return "gray" if j == 0 else COLORS[(j - 1) % len(COLORS)]

def stage(i):
    """Transmission driving arm i (i >= 2): ('mesh'|'belt', rho = Zsun/Zplanet)."""
    s, c, k = kk[i - 2], kk[i - 1], kk[i]
    if c == s:
        raise ValueError(f"arm {i-1} does not rotate relative to its reference")
    if k == c:
        raise ValueError(f"arm {i} would be rigidly fixed to arm {i-1}")
    rho = Fraction(k - c, c - s)
    return ("mesh", rho) if rho > 0 else ("belt", -rho)


# ---------------- mechanism (built upright, flipped later) ----------------
mech = []                    # (object, color) in mechanism coordinates
envelope = [0]               # largest radius swept by any moving or fixed part

def add(obj, color):
    mech.append((obj, color))

def sweep(center_reach, r):
    envelope[0] = max(envelope[0], center_reach + r)

# drive: gear on arm 1 + motor pinion on the bridge
rd, rpn = DRIVE_M * DRIVE_ZG / 2, DRIVE_M * DRIVE_ZP / 2
p_pin = polar(rd + rpn, DRIVE_DIR)
drive = gear(DRIVE_ZG, rd, T_GEAR) - hole(POST_R + CLR, T_GEAR)
add(at(drive, [0, 0], Z_DRIVE, A[1]), col(1))
add(at(cylinder(r=HUB_R, h=GAP, fn=FN) - hole(POST_R + CLR, GAP), [0, 0], Z_DRIVE + T_GEAR), col(1))
add(at(gear(DRIVE_ZP, rpn, T_GEAR), p_pin, Z_DRIVE, mesh_angle(A[1], DRIVE_DIR, DRIVE_ZG, DRIVE_ZP)), "silver")
add(at(cylinder(r=POST_R, h=Z_DRIVE + MOTOR_H, fn=24), p_pin, -MOTOR_H), "silver")
add(at(cylinder(r=MOTOR_R, h=MOTOR_H - 2, fn=FN), p_pin, -MOTOR_H), "dimgray")
sweep(0, rd + DRIVE_M)
sweep(rd + rpn, rpn + DRIVE_M)

# bridge plate (radius fixed later, stored as placeholder index)
BRIDGE_IDX = len(mech)
add(None, "lightgray")

# arms (hole at the pivot, axle for the next arm fused at the tip)
for i in range(1, N + 1):
    a, b = Pos[i - 1], Pos[i]
    outline = hull(at(circle(r=HUB_R, fn=FN), a), at(circle(r=HUB_R, fn=FN), b))
    plate = linear_extrude(outline, height=T_ARM) - at(hole(POST_R + CLR, T_ARM), a)
    add(plate.translate([0, 0, z_arm(i)]), col(i))
    sweep(reach[i], HUB_R)

# axles: post at Pos[j] is fixed to body j and carries the sun of the next stage
for j in range(N):
    zb = BASE_T if j == 0 else z_arm(j) + T_ARM
    zt = z_gear(j + 1) + T_GEAR if j + 1 <= N - 1 else z_arm(j + 1) + T_ARM + 1
    add(at(cylinder(r=POST_R, h=zt - zb, fn=24), Pos[j], zb), col(j))

# planetary stages
for i in range(2, N + 1):
    j = i - 1                    # gear layer below arm i
    kind, rho = stage(i)
    S, Pc = Pos[i - 2], Pos[i - 1]
    dist = L[i - 2]
    beta = A[i - 1]              # carrier direction (sun -> planet)
    z0 = z_gear(j)

    if kind == "mesh":
        n = max(math.ceil(MIN_TEETH / rho.denominator), math.ceil(MIN_TEETH / rho.numerator))
        zp, zs = rho.denominator * n, rho.numerator * n
        rs, rp = dist * zs / (zs + zp), dist * zp / (zs + zp)
        m = 2 * dist / (zs + zp)
        a_s = A[i - 2]
        a_p = mesh_angle(a_s, beta, zs, zp)
        sun, planet = gear(zs, rs, T_GEAR), gear(zp, rp, T_GEAR)
        sweep(reach[i - 2], rs + m)
        sweep(reach[i - 1], rp + m)
        info = f"gear mesh {zs}:{zp}, module {m:.2f}"
    else:
        rp = min(PULLEY_R, 0.8 * dist / (1 + float(rho)))
        rs = rp * float(rho)
        a_s, a_p = A[i - 2], A[i]
        sun, planet = pulley(rs, T_GEAR), pulley(rp, T_GEAR)
        inner = hull(at(circle(r=rs, fn=FN), S), at(circle(r=rp, fn=FN), Pc))
        outer = hull(at(circle(r=rs + BELT_T, fn=FN), S), at(circle(r=rp + BELT_T, fn=FN), Pc))
        belt = linear_extrude(outer - inner, height=T_GEAR * 0.6)
        add(belt.translate([0, 0, z0 + T_GEAR * 0.2]), "dimgray")
        sweep(reach[i - 2], rs + BELT_T)
        sweep(reach[i - 1], rp + BELT_T)
        info = f"belt, pulleys {rs:.1f}:{rp:.1f} mm (ratio {rho})"

    add(at(sun, S, z0, a_s), col(i - 2))
    planet = planet - hole(POST_R + CLR, T_GEAR)
    add(at(planet, Pc, z0, a_p), col(i))
    hub = cylinder(r=min(HUB_R, rp), h=GAP, fn=FN) - hole(POST_R + CLR, GAP)
    add(at(hub, Pc, z0 + T_GEAR), col(i))
    print(f"arm {i}: k={kk[i]}, sun on body {i-2} (k={kk[i-2]}), carrier k={kk[i-1]} -> {info}")

# frame geometry from the swept envelope
R_COL = envelope[0] + MARGIN + COL_R
R_BRIDGE = R_COL + COL_R + 3
bridge = cylinder(r=R_BRIDGE, h=BASE_T, fn=96) - at(hole(POST_R + CLR, BASE_T), p_pin)
mech[BRIDGE_IDX] = (bridge, "lightgray")


# ---------------- world: flip mechanism, add frame, paper, pen ----------------
Z_PAPER = TABLE_T + PAPER_T
TOP = Z_PAPER + PEN_CLEAR + Z_MECH          # world height of mechanism z = 0
def W(z): return TOP - z                    # mechanism z -> world z

parts = [obj.mirror([0, 0, 1]).translate([0, 0, TOP]).color(c) for obj, c in mech]

# table, paper, columns
side = 2 * (R_BRIDGE + 5)
parts.append(cube([side, side, TABLE_T]).translate([-side / 2, -side / 2, 0]).color("burlywood"))
ps = 2 * (sum(L) + 10)
parts.append(cube([ps, ps, PAPER_T]).translate([-ps / 2, -ps / 2, TABLE_T]).color("white"))
for k in range(4):
    p = polar(R_COL, 45 + 90 * k)
    parts.append(at(cylinder(r=COL_R, h=W(0) - TABLE_T, fn=24), p, TABLE_T).color("gray"))

# pen: sleeve fixed to arm N, pen resting on the paper by gravity
tip = Pos[N]
z_armN_low = W(z_arm(N) + T_ARM)            # lower face of arm N in world coords
z_armN_top = W(z_arm(N))
sleeve = cylinder(r=2.2, h=SLEEVE_L, fn=24) - hole(1.4, SLEEVE_L)
parts.append(at(sleeve, tip, z_armN_low - SLEEVE_L).color(col(N)))
pen = at(cylinder(r1=0.3, r2=1.2, h=2, fn=16), tip, Z_PAPER) \
    | at(cylinder(r=1.2, h=z_armN_top - Z_PAPER - 2, fn=16), tip, Z_PAPER + 2)
parts.append(pen.color("black"))

# traced curve on the paper
pts = []
for t in range(0, 360, CURVE_STEP):
    x = y = 0
    for i in range(N):
        d = polar(L[i], K[i] * t + PHI[i])
        x, y = x + d[0], y + d[1]
    pts.append([x, y])
segs = [hull(at(circle(r=CURVE_W, fn=8), p), at(circle(r=CURVE_W, fn=8), q))
        for p, q in zip(pts, pts[1:] + pts[:1])]
parts.append(linear_extrude(union_all(segs), height=0.2).translate([0, 0, Z_PAPER]).color("magenta"))

print(f"swept envelope r = {envelope[0]:.1f} mm, columns at r = {R_COL:.1f} mm, "
      f"total height = {TOP + MOTOR_H:.1f} mm")

show(parts)

Next steps on my list: printable parts (bearings, belt tooth profiles) and an automatic collision check over the full revolution using PythonSCAD's intersection. Happy to hear ideas – and if you find a nice 4-arm parameter set, post it!


r/OpenPythonSCAD • • Feb 24 '26

PythonSCAD goes Jupyter

6 Upvotes

Jupyter is a web interface which is mainly uses in science.

Its somewhat similar to a Calculator.

Why shouln't that be used to create 3D models ...

https://youtu.be/pXBKZfUDQ9c

Instructions how to use will follow soon


r/OpenPythonSCAD • • Dec 15 '24

Using existing SCAD libraries in PythonSCAD

7 Upvotes

This small demonstration shows, how you existing libraries along with your PythonSCAD code.

Simple use "osinclude" to turn a SCAD library into an class variable with all the modules and variables available as members.

You can simple call these members by invoking them with parameters. Even Childs to SCAD modules are possible. just add them to the arguments

This feature is available since 2024-12-15 Windows release.