erdevelop_ / courses / rhino-python Glossary Tools TR
Courses · Python in Rhino

Python in Rhino

A 7-day programme for automating repetitive work in Rhino with a few lines of Python. You write your first script in Rhino 8's ScriptEditor, create points, curves and surfaces with rhinoscriptsyntax, get selections and values from the user, and organise layers and object information. You get to know RhinoCommon's geometry classes and write a tool that divides a façade surface into panels, numbers them and writes the panel list to CSV. In the last two days you use the same knowledge in Grasshopper's Python component and, without opening Rhino, with the rhino3dm library.

7 days~4 hours a dayEnglishCode examples can be copied

Before you start

Who is it for

Architects, façade and product designers using Rhino who want to automate repetitive modelling and numbering. Basic Rhino knowledge is enough; no Python knowledge needed, the necessary part is explained on the first day. The Rhino and Grasshopper courses are good preparation.

What you need

  • Rhino 8 (Windows or Mac). Rhino 7 can also be used; the differences are noted in the text. Trial: rhino3d.com.
  • For day 7 outside Rhino: Python 3.9 or later and pip install rhino3dm.
  • Optional: VS Code with the Python extension.

Programme

DayTopicWhat you learnTime
Day 1Introduction to Python in RhinoScriptEditor, Python 3 and IronPython, first script, rhinoscriptsyntax, Python basics: variables, lists, loops, functions~4 hours
Day 2Geometry with rhinoscriptsyntaxPoints, lines, polylines, curves, circles, loft, extrude, layers and colours, object identities (GUID)~4 hours
Day 3Selection and user inputGetObject and GetObjects, filters, GetReal, GetInteger, ListBox, batch renaming, user text (UserText)~4 hours
Day 4RhinoCommonRhino.Geometry, Point3d, Vector3d, Plane, Transform, Curve and Surface methods, scriptcontext.doc, adding objects, Redraw~4 hours
Day 5Façade panel automationSurface parameter domain, UV grid, generating panels, planarity and size checks, numbering, panel list to CSV~4 hours
Day 6Python in GrasshopperScript component, inputs and outputs, type hints, item, list and tree access, attractor example, sharing~4 hours
Day 7Outside Rhino: rhino3dm and a projectInstalling rhino3dm, writing and reading .3dm, layers and user text, generating a model from CSV, producing a report~4 hours

There is a checklist at the end of each day. As you tick items, your progress is saved in this browser. If you only study on weekday evenings, the programme takes about two weeks. Scripts running inside Rhino (rhinoscriptsyntax, RhinoCommon, the Grasshopper component) were written according to Rhino 8's API documentation, but because Rhino was not available in the environment where this course was prepared they could not be run; only their Python syntax was checked, and no output is shown under these blocks. Pure Python examples and all day 7 examples written with rhino3dm 8.35 were run, and the outputs shown are real results. If a command behaves unexpectedly in Rhino, Rhino's ScriptEditor help and the developer.rhino3d.com documentation govern. Code comments and variable names are in Turkish.

DAY 01

Introduction to Python in Rhino

~4 hours · 0/6 checks

Goal

By the end of the day you will open the ScriptEditor in Rhino 8 and write your first Python script, know the difference between Python 3 and IronPython, understand what rhinoscriptsyntax is and learn the Python basics you will use every day when scripting (variables, lists, loops, conditions, functions). Time about 4 hours.

About this course: The examples are chosen from common tasks in façade and product design: generating panels, numbering, sorting into layers, producing lists. Code blocks are of two kinds. Those running inside Rhino you paste into the ScriptEditor and run; no output is shown below them, you see the result in Rhino. The outputs under pure Python examples are real run results.

1. Why Python? (30 min)

Repetitionnumbers for 300 panelsRule-based geometrydivide a surface into panelsChecksplanarity, dimensionsDataCSV, Excel, listsGrasshopperPython componentOutside Rhinorhino3dm, server
Things you can do with Python in Rhino.

In Rhino every task is done with a command, but running the same command one by one for 300 panels is both tiring and error-prone. A script:

  • does repetitive tasks in seconds: numbering 300 panels, colouring by layer, listing the lengths of all curves;
  • creates rule-based geometry: dividing a surface into panels of given sizes, arraying brackets along a curve;
  • performs checks: finding non-planar panels and dimensions exceeding limits;
  • extracts data: transferring the panel list to Excel, an order list or fabrication drawings.

Grasshopper does similar work with visual programming. Python is text-based: it is more comfortable for conditional and repetitive logic, file operations and tools that talk to the user on screen. They are not rivals; on day 6 we will also use Python inside Grasshopper.

2. ScriptEditor and Python versions (45 min)

In Rhino 8 type ScriptEditor in the command line. In the window that opens:

  1. Create a new script with the + at the top left and choose Python 3 as the language.
  2. Write the code.
  3. Press the Run button (green triangle) or F5. print output appears in the console below.
  4. Save the script as .py. You can later run the saved script with the RunPythonScript command or a toolbar button.

Rhino 8 has two Pythons:

Python 3 (CPython 3.9) IronPython 2.7
In Rhino Came with Rhino 8, recommended The Python of Rhino 5–7, for old scripts
First line #! python3 #! python2
External libraries pip packages with a # requirements: numpy line Most don't work
Syntax Modern Python 3 print as a statement, u"..." needed for non-ASCII text

This course uses Python 3. If you use Rhino 7, the EditPythonScript command opens the IronPython editor; the rhinoscriptsyntax and RhinoCommon parts of the course work largely unchanged there, you only need to watch the Python 2 syntax differences.

3. First script (45 min)

ScriptEditornew · Python 3#! python3import rsrs.AddLinelike a commandF5runGUIDobject identityCtrl+Z to undo: everything the script did is one step
The path of the first script: write, run, get object identities.

Type this in the ScriptEditor and run it:

#! python3
import rhinoscriptsyntax as rs

point = rs.AddPoint([0, 0, 0])
line = rs.AddLine([0, 0, 0], [3000, 0, 0])
circle = rs.AddCircle([1500, 0, 0], 500)
print("Added:", point, line, circle)

A point, a 3000-unit line and a 500-unit-radius circle in its middle appear on screen. In the console you see three long identities; these are the unique numbers Rhino gives every object (GUID). In the next steps we will reach objects through these identities.

  • rhinoscriptsyntax (rs for short) is a set of easy-to-use Python functions close to Rhino's commands. rs.AddLine is the script equivalent of Rhino's Line command.
  • Points are given as a list of three numbers in the form [x, y, z].
  • Units are the document's units. Façade files usually use millimetres, so dimensions in the examples are mm.

Ctrl+Z in Rhino is enough to undo: everything the script did is a single undo step.

4. Python basics: variables and lists (45 min)

Knowing a small part of Python is enough to write scripts. The examples in this section don't need Rhino; they give the same output in the ScriptEditor or in any Python on your computer.

width = 1500          # integer (int)
height = 3200.0       # decimal number (float)
kind = "glass"        # text (str)
urgent = False       # boolean (bool)

area = width * height / 1_000_000
print(kind, "panel:", width, "x", height, "mm =", area, "m²")
print(f"{kind} panel {area:.2f} m², urgent: {urgent}")
glass panel: 1500 x 3200.0 mm = 4.8 m²
glass panel 4.80 m², urgent: False

f"..." is formatted text: the value in curly braces is inserted, :.2f means two decimal places. 1_000_000 is one million; the underscore is only for readability.

A list is an ordered collection of values. Indices start at 0; -1 means the last one:

widths = [1500, 1500, 1200, 900]
print(widths[0], widths[-1], len(widths))
widths.append(1350)
print(widths, "total:", sum(widths), "largest:", max(widths))
print(widths[1:3])

point = [1500, 0, 3200]
x, y, z = point
print("x =", x, "z =", z)
1500 900 4
[1500, 1500, 1200, 900, 1350] total: 6450 largest: 1500
[1500, 1200]
x = 1500 z = 3200

The slice [1:3] gives items 1 and 2 (3 not included). x, y, z = point unpacks the list into three variables.

A dictionary holds values accessed by name. Ideal for holding a panel's information:

panel = {"code": "P-101", "width": 1500, "height": 3200, "type": "glass"}
print(panel["code"], panel["type"])
panel["floor"] = 3
print(panel)
print(panel.get("color", "RAL 7016"))
P-101 glass
{'code': 'P-101', 'width': 1500, 'height': 3200, 'type': 'glass', 'floor': 3}
RAL 7016

get returns the default value if the key is missing; asking for a missing key with square brackets gives an error.

5. Loops and conditions (45 min)

floor 0floor 3axis 0axis 4for kat in range(4):for aks in range(5):rs.AddPoint(...)
Two nested loops: the outer loop goes through floors, the inner through axes.

for runs for each item of a list. range(n) produces numbers from 0 to n−1. Indentation (4 spaces) marks the inside of the block:

for i in range(4):
    x = i * 1500
    print(f"Panel {i + 1}: x = {x} mm")

widths = [1500, 1500, 1200, 900, 1350]
total = 0
for g in widths:
    if g >= 1500:
        status = "full"
    elif g >= 1200:
        status = "middle"
    else:
        status = "narrow"
    total += g
    print(g, status)
print("Total facade length:", total)
Panel 1: x = 0 mm
Panel 2: x = 1500 mm
Panel 3: x = 3000 mm
Panel 4: x = 4500 mm
1500 full
1500 full
1200 middle
900 narrow
1350 middle
Total facade length: 6450

enumerate gives both the position and the value, zip walks two lists side by side. A list comprehension creates a new list with a short syntax:

codes = ["P-101", "P-102", "P-103"]
areas = [4.8, 4.8, 3.84]
for i, (code, area) in enumerate(zip(codes, areas), start=1):
    print(i, code, area)

points = [[i * 1500, 0, 0] for i in range(5)]
print(points)
large_ones = [a for a in areas if a > 4]
print(large_ones)
1 P-101 4.8
2 P-102 4.8
3 P-103 3.84
[[0, 0, 0], [1500, 0, 0], [3000, 0, 0], [4500, 0, 0], [6000, 0, 0]]
[4.8, 4.8]

In Rhino you can pass the points (points) list from this second example directly to rs.AddPoints(points) or rs.AddPolyline(points). List comprehension is one of the syntaxes you will use most in scripts.

6. Functions (30 min)

You put repeated calculations into a function. It is defined with def and returns a value with return. Arguments with default values use the default if not given in the call:

def panel_area(width, height):
    """Returns the panel area in m² (dimensions in mm)."""
    return width * height / 1_000_000


def glass_weight(width, height, total_thickness=12):
    """Glass weight about 2.5 kg / m² / mm."""
    return panel_area(width, height) * total_thickness * 2.5


print(round(panel_area(1500, 3200), 2))
print(round(glass_weight(1500, 3200), 1), "kg")
print(round(glass_weight(1500, 3200, total_thickness=16), 1), "kg")
4.8
144.0 kg
192.0 kg

The triple-quoted text (docstring) describes what the function does; the ScriptEditor shows it when you hover over the function.

Now combine what you learned in Rhino. The script below puts a point at the corner of each panel and a line on each floor for a 5-floor × 4-axis façade grid:

#! python3
import rhinoscriptsyntax as rs

PANEL_WIDTH = 1500
FLOOR_HEIGHT = 3200

rs.EnableRedraw(False)
for floor in range(5):
    z = floor * FLOOR_HEIGHT
    rs.AddLine([0, 0, z], [4 * PANEL_WIDTH, 0, z])
    for axis in range(5):
        rs.AddPoint([axis * PANEL_WIDTH, 0, z])
rs.EnableRedraw(True)
print("Grid done")

rs.EnableRedraw(False) stops redrawing the screen each time an object is added; it noticeably speeds up scripts adding many objects. Don't forget to set it to True at the end.

Exercise: Write a script that draws rectangular panels side by side according to a widths (widths) list (for example [1500, 1500, 1200, 900, 1500]): each panel's bottom left corner starts at the previous one's bottom right corner, height 3200. Hint: calculate the corner points and draw a closed line with rs.AddPolyline([p1, p2, p3, p4, p1]); accumulate the x position in a variable in the loop.

End-of-day check (15 min)

DAY 02

Geometry with rhinoscriptsyntax

~4 hours · 0/6 checks

Goal

By the end of the day you will be able to create points, polylines, curves, circles and surfaces with rhinoscriptsyntax; put objects on layers and give them colours and names; and keep object identities (GUIDs) for later operations. You will have written scripts that array brackets along a curve and create a surface between two curves. Time about 4 hours.

1. Points and polylines (45 min)

points and curvessurfaces and solidsrs.AddPoint / AddPointsrs.AddLine / AddPolyliners.AddCurve / AddInterpCurvers.AddCircle / AddRectanglers.AddLoftSrfrs.ExtrudeCurveStraightrs.AddSrfPtrs.CapPlanarHoles
Frequently used geometry functions of rhinoscriptsyntax.

In rhinoscriptsyntax a point is a [x, y, z] list. Functions that add points and draw curves take lists of points:

Function Rhino command What it creates
rs.AddPoint(p) Point Point
rs.AddPoints(items) Points Several points
rs.AddLine(a, b) Line Line
rs.AddPolyline(items) Polyline Polyline; closed if the first point is repeated at the end
rs.AddCurve(items, degree) Curve NURBS curve from control points
rs.AddInterpCurve(items) InterpCrv Curve through points
rs.AddCircle(center, r) Circle Circle
rs.AddRectangle(plane, width, height) Rectangle Rectangle

A function drawing the outer frame of a façade panel as a closed polyline:

#! python3
import rhinoscriptsyntax as rs


def draw_panel(x, z, width, height):
    p1 = [x, 0, z]
    p2 = [x + width, 0, z]
    p3 = [x + width, 0, z + height]
    p4 = [x, 0, z + height]
    return rs.AddPolyline([p1, p2, p3, p4, p1])


guid = draw_panel(0, 0, 1500, 3200)
print("closed:", rs.IsCurveClosed(guid), "length:", rs.CurveLength(guid))

In the console you should see closed: True length: 9400.0 (closed?, length; perimeter: 2 × (1500 + 3200)). Functions return the GUID of the object they create; query functions such as rs.IsCurveClosed and rs.CurveLength also take this identity.

Check dimensions before the script. If you write calculations that don't need Rhino (corner points, lengths) in a separate function, you can try them without opening Rhino:

def panel_corners(x, z, width, height):
    return [[x, 0, z], [x + width, 0, z], [x + width, 0, z + height], [x, 0, z + height]]


def perimeter(points):
    total = 0.0
    for a, b in zip(points, points[1:] + points[:1]):
        total += sum((b[i] - a[i]) ** 2 for i in range(3)) ** 0.5
    return total


k = panel_corners(0, 0, 1500, 3200)
print(k)
print("perimeter:", perimeter(k))
[[0, 0, 0], [1500, 0, 0], [1500, 0, 3200], [0, 0, 3200]]
perimeter: 9400.0

points[1:] + points[:1] shifts the list by one; with zip each corner is paired with the next and the last corner connects to the first. The distance between two points is the square root of the sum of the squares of the coordinate differences.

2. Arraying along a curve (1 hour)

length / target spacing → round → DivideCurve(curve, count) → a bracket at each point
Arraying brackets at equal spacing along a curve.

Dividing a curve into equal parts and placing an object at each point is a very common task: anchor brackets along an edge, posts along a balustrade. rs.DivideCurve(curve, n) divides the curve into n parts and returns n + 1 points (for an open curve):

#! python3
import rhinoscriptsyntax as rs

curve = rs.GetObject("Select the curve for brackets", rs.filter.curve)
if curve:
    length = rs.CurveLength(curve)
    spacing = 1200
    count = max(1, int(round(length / spacing)))
    points = rs.DivideCurve(curve, count)
    rs.EnableRedraw(False)
    for p in points:
        bracket = rs.AddBox([[p[0] - 60, p[1] - 40, p[2] - 100], [p[0] + 60, p[1] - 40, p[2] - 100],
                            [p[0] + 60, p[1] + 40, p[2] - 100], [p[0] - 60, p[1] + 40, p[2] - 100],
                            [p[0] - 60, p[1] - 40, p[2]], [p[0] + 60, p[1] - 40, p[2]],
                            [p[0] + 60, p[1] + 40, p[2]], [p[0] - 60, p[1] + 40, p[2]]])
    rs.EnableRedraw(True)
    print(f"{len(points)} brackets, actual spacing {length / count:.0f} mm")
  • rs.GetObject asks the user to select an object (we will see it in detail tomorrow); rs.filter.curve allows only curves to be selected.
  • Instead of hitting the spacing exactly we rounded the count; the actual spacing varies slightly with curve length. This is also the method used on site: brackets are equally spaced.
  • rs.AddBox takes eight corner points (four bottom, four top).

Let's try the count and spacing calculation without Rhino:

def bracket_count(length, target_spacing):
    count = max(1, int(round(length / target_spacing)))
    return count + 1, length / count


for L in [5000, 7300, 12450]:
    n, a = bracket_count(L, 1200)
    print(f"{L} mm curve → {n} brackets, spacing {a:.1f} mm")
5000 mm curve → 5 brackets, spacing 1250.0 mm
7300 mm curve → 7 brackets, spacing 1216.7 mm
12450 mm curve → 11 brackets, spacing 1245.0 mm

3. Surfaces: loft and extrude (45 min)

AddLoftSrf([bottom, top])ExtrudeCurveStraight + Cap
A loft surface between two curves and a solid by extruding a section.
Function Rhino command
rs.AddLoftSrf(curves) Loft
rs.ExtrudeCurveStraight(curve, start, end) ExtrudeCrv
rs.AddPlanarSrf(curves) PlanarSrf
rs.AddSrfPt([p1, p2, p3, p4]) SrfPt (surface from corner points)
rs.AddPipe(curve, 0, radius) Pipe

A curved façade surface from two different curves at the bottom and top:

#! python3
import rhinoscriptsyntax as rs

bottom = rs.AddInterpCurve([[0, 0, 0], [6000, 1200, 0], [12000, 0, 0]])
top = rs.AddInterpCurve([[0, 0, 12800], [6000, 2000, 12800], [12000, 0, 12800]])
facade = rs.AddLoftSrf([bottom, top])
if facade:
    print("surface:", facade[0], "area:", round(rs.SurfaceArea(facade[0])[0] / 1e6, 1), "m²")

rs.AddLoftSrf returns a list (a loft can create several surfaces); that's why we used facade[0]. rs.SurfaceArea also returns a [area, error] list. This surface will be the façade we divide into panels on day 5; don't forget to save it.

Extruding a profile along a straight path (for example a mullion section):

#! python3
import rhinoscriptsyntax as rs

section = rs.AddRectangle(rs.WorldXYPlane(), 60, 150)
mullion = rs.ExtrudeCurveStraight(section, [0, 0, 0], [0, 0, 3200])
rs.CapPlanarHoles(mullion)
print("solid:", rs.IsPolysurfaceClosed(mullion))

CapPlanarHoles closes the open ends and turns the object into a closed solid.

4. Layers, colours and names (45 min)

CEPHEPanelGlassCompositeBracket"CEPHE::Panel::Cam"rs.AddLayer(name, colour)rs.ObjectLayer(id, name)rs.ObjectName(id, "P-101")
Sub-layers are written with ::; the script sets up the layer standard the same way every time.

Keeping the created objects organised is at least as important a job for a script as the geometry. rs.AddLayer(name, color) creates a layer (leaves it untouched if it exists); :: is the sub-layer separator:

#! python3
import rhinoscriptsyntax as rs

LAYERS = {
    "FACADE::Panel::Glass": (120, 170, 220),
    "FACADE::Panel::Composite": (180, 180, 180),
    "FACADE::Bracket": (220, 120, 40),
}
for name, color in LAYERS.items():
    if not rs.IsLayer(name):
        rs.AddLayer(name, color)

panel = rs.AddPolyline([[0, 0, 0], [1500, 0, 0], [1500, 0, 3200], [0, 0, 3200], [0, 0, 0]])
rs.ObjectLayer(panel, "FACADE::Panel::Glass")
rs.ObjectName(panel, "P-101")
print(rs.ObjectLayer(panel), rs.ObjectName(panel))

In rhinoscriptsyntax many functions do two jobs: with one argument they read (rs.ObjectLayer(id) returns the layer name), with two arguments they write (rs.ObjectLayer(id, "name")). rs.ObjectColor(id, (r, g, b)) gives the object a colour independent of its layer; most of the time taking colour from the layer (the default) is tidier.

Collecting layer names and colours in one dictionary means writing the team's layer standard into the script: every script creates the same layers with the same names.

5. Keeping GUIDs and using them later (30 min)

As the script progresses you keep the objects you create in a list, to group them, move them to a layer or delete them at the end:

#! python3
import rhinoscriptsyntax as rs

created = []
for i in range(4):
    x = i * 1500
    created.append(rs.AddPolyline([[x, 0, 0], [x + 1500, 0, 0], [x + 1500, 0, 3200], [x, 0, 3200], [x, 0, 0]]))

group = rs.AddGroup("axis_A")
rs.AddObjectsToGroup(created, group)
rs.SelectObjects(created)
print(len(created), "panels grouped and selected")

GUIDs are valid during a session and are saved with the file. But if an object is deleted and recreated it gets a new identity; so for a permanent link (for example a panel code) a name or user text (tomorrow) is used instead of the identity.

Exercise: Write a script that asks for a curve and adds mullion lines (rs.AddLine) 3200 mm high perpendicular to the curve every 1500 mm along it. Put the mullions on the FACADE::Mullion layer and name them D-01, D-02… (hint: f"D-{i:02d}"). Then create an rs.AddLoftSrf surface between the two end mullions.

End-of-day check (15 min)

DAY 03

Selection and user input

~4 hours · 0/6 checks

Goal

By the end of the day you will be able to write scripts that ask the user to select objects, enter numbers and choose from a list; filter selections by type and layer; rename many objects in bulk and distribute them to layers; and add permanent information to objects with user text (UserText). Time about 4 hours.

1. Asking for objects (45 min)

GetObjectsfilter: curveNone?Esc → exitfilterclosed?processarea, nameresultprint / dotpreselect=True: uses objects selected beforehand
Skeleton of a script that asks for a selection.

Most scripts start with "let the user select something and I'll work with it":

Function What it returns
rs.GetObject(message, filter_) A single GUID, or None if cancelled
rs.GetObjects(message, filter_) List of GUIDs or None
rs.GetPoint(message) The point clicked or None
rs.SelectedObjects() Currently selected objects
rs.ObjectsByLayer(layer) All objects on a layer

Filters: rs.filter.point, rs.filter.curve, rs.filter.surface, rs.filter.polysurface, rs.filter.mesh, rs.filter.annotation. Multiple filters are combined with +: rs.filter.surface + rs.filter.polysurface.

#! python3
import rhinoscriptsyntax as rs

ids = rs.GetObjects("Select panels", rs.filter.curve, preselect=True)
if not ids:
    print("Nothing selected.")
else:
    closed = [i for i in ids if rs.IsCurveClosed(i) and rs.IsCurvePlanar(i)]
    total = sum(rs.CurveArea(i)[0] for i in closed) / 1e6
    print(f"{len(ids)} curves selected, {len(closed)} closed and planar, total {total:.2f} m²")
  • preselect=True: if the user selected objects before running the script, they are used without asking again.
  • If the user presses Esc the function returns None. Always check; otherwise you get an error on the next line.
  • rs.CurveArea gives the area of a closed planar curve as [area, error].

2. Getting numbers and options (45 min)

#! python3
import rhinoscriptsyntax as rs

spacing = rs.GetReal("Bracket spacing (mm)", 1200, 300, 3000)
count = rs.GetInteger("Number of floors", 5, 1, 60)
kind = rs.ListBox(["glass", "composite", "stone"], "Panel type", "Panel")
confirm = rs.MessageBox(f"{count} floors, {spacing:.0f} mm spacing, {kind}. Continue?", 4 | 32, "Confirm")
if spacing is None or count is None or kind is None or confirm != 6:
    print("Cancelled.")
else:
    print("Continuing:", spacing, count, kind)
  • rs.GetReal(message, default, minimum, maximum): decimal number (message, default, minimum, maximum). rs.GetInteger integer.
  • rs.ListBox(options, message, title): single choice from a list; rs.MultiListBox multiple choice.
  • rs.MessageBox(text, buttons, title): 4 Yes/No, 32 question icon; returns 6 if Yes is pressed.

Remembering defaults: If you want the user to see their last values when running the same script again, you can store the values in the sc.sticky dictionary (import scriptcontext as sc; sc.sticky["spacing"] = spacing). This dictionary lives until Rhino closes.

3. Batch renaming (1 hour)

P-101P-102P-103P-104P-201P-202P-203P-204floor 1floor 2sorting: (floor, x)
Numbering: first by floor, then left to right within the floor.

The most common order when numbering panels: by floor (z), then by axis (x). First let's write and test the sorting logic without Rhino. Suppose the centroid coordinates of each panel are given:

def number_panels(centers, prefix="P", floor_height=3200, tolerance=50):
    """centers: [(id, x, y, z), ...] -> {id: code}. Floor by z, order by x."""
    def floor_no(z):
        return int((z + tolerance) // floor_height) + 1

    ordered = sorted(centers, key=lambda m: (floor_no(m[3]), m[1]))
    codes = {}
    counter = {}
    for pid, x, y, z in ordered:
        k = floor_no(z)
        counter[k] = counter.get(k, 0) + 1
        codes[pid] = f"{prefix}-{k}{counter[k]:02d}"
    return codes


sample = [("a", 3000, 0, 1600), ("b", 0, 0, 1600), ("c", 1500, 0, 4800),
         ("d", 1500, 0, 1590), ("e", 0, 0, 4810), ("f", 4500, 0, 1600)]
for pid, code in number_panels(sample).items():
    print(pid, code)
b P-101
d P-102
a P-103
f P-104
e P-201
c P-202
  • sorted(..., key=lambda m: (floor, x)) sorts first by floor, then by x within the floor.
  • tolerance (tolerance) is there because the centres of panels on the same floor may differ by a few millimetres (panel d is at 1590 but still on floor 1).
  • Code format P-101: the floor number and a two-digit position within the floor.

Let's apply the same logic to curves selected in Rhino. rs.CurveAreaCentroid is used for the centre:

#! python3
import rhinoscriptsyntax as rs


def number_panels(centers, prefix="P", floor_height=3200, tolerance=50):
    def floor_no(z):
        return int((z + tolerance) // floor_height) + 1
    ordered = sorted(centers, key=lambda m: (floor_no(m[3]), m[1]))
    codes, counter = {}, {}
    for pid, x, y, z in ordered:
        k = floor_no(z)
        counter[k] = counter.get(k, 0) + 1
        codes[pid] = f"{prefix}-{k}{counter[k]:02d}"
    return codes


ids = rs.GetObjects("Select panels to number", rs.filter.curve, preselect=True)
if ids:
    centers = []
    for i in ids:
        c = rs.CurveAreaCentroid(i)[0]
        centers.append((i, c[0], c[1], c[2]))
    codes = number_panels(centers, prefix="P", floor_height=3200)
    rs.EnableRedraw(False)
    for pid, code in codes.items():
        rs.ObjectName(pid, code)
        rs.AddTextDot(code, rs.CurveAreaCentroid(pid)[0])
    rs.EnableRedraw(True)
    print(len(codes), "panels numbered")

rs.AddTextDot places a small label at the centre of each panel that always faces the screen; very useful for checking. When done you can find them all with rs.ObjectsByType(8192) (the text dot type) and delete them.

4. User text: adding information to objects (45 min)

P-101closed polylinetypeglassalan_m24.800statusdesignsupplierCamSanSetUserText(id, key, value) · values are always text
User text: key–value information added to an object and saved with the file.

An object's name is a single text. To store a panel's type, colour, order status and supplier, user text (UserText, Attribute User Text) is used: key–value pairs added to the object. It appears in the Attribute User Text tab of Rhino's Properties panel and is saved with the .3dm file.

#! python3
import rhinoscriptsyntax as rs

ids = rs.GetObjects("Select panels to annotate", rs.filter.curve, preselect=True)
if ids:
    for i in ids:
        area = rs.CurveArea(i)[0] / 1e6
        rs.SetUserText(i, "type", "glass")
        rs.SetUserText(i, "area_m2", f"{area:.3f}")
        rs.SetUserText(i, "status", "design")
    sample = ids[0]
    for key in rs.GetUserText(sample):
        print(key, "=", rs.GetUserText(sample, key))
  • rs.SetUserText(id, key, value): the value is always text; format numbers when writing and convert with float() when reading.
  • rs.GetUserText(id) gives the list of keys, rs.GetUserText(id, key) the value.
  • User text can be used in selection with Rhino commands such as SelUserText, in listings with Tables, and in Grasshopper. On day 7 we will also read it with rhino3dm without opening Rhino.

5. Operations by layer (30 min)

Filtering by user text and distributing to layers:

#! python3
import rhinoscriptsyntax as rs

STATUS_LAYER = {"design": (160, 160, 160), "production": (230, 170, 40), "installation": (60, 160, 80)}
for status, color in STATUS_LAYER.items():
    name = f"STATUS::{status}"
    if not rs.IsLayer(name):
        rs.AddLayer(name, color)

counter = {}
for i in rs.AllObjects():
    status = rs.GetUserText(i, "status")
    if status in STATUS_LAYER:
        rs.ObjectLayer(i, f"STATUS::{status}")
        counter[status] = counter.get(status, 0) + 1
print(counter)

Now you can see from the colour on screen what stage each panel is at. When a panel is installed, all you need to do is change the status (status) value in its user text and run the script again.

Exercise: Write a check script that finds the selected panels without a kind (type) key in their user text, keeps those selected and deselects the others (rs.UnselectAllObjects, rs.SelectObjects) and warns "N panels are missing a type".

End-of-day check (15 min)

DAY 04

RhinoCommon

~4 hours · 0/6 checks

Goal

By the end of the day you will get to know the RhinoCommon library underneath rhinoscriptsyntax; you will be able to calculate geometry with Point3d, Vector3d, Plane and Transform, use the methods of curves and surfaces and add geometry to the document via scriptcontext.doc. Time about 4 hours.

1. Two layers: rhinoscriptsyntax and RhinoCommon (30 min)

Your scriptrhinoscriptsyntax (rs)Grasshopper PythonRhinoCommon (Rhino.Geometry, scriptcontext)Rhino core (C++)
rhinoscriptsyntax and the Grasshopper component run on top of RhinoCommon.

rhinoscriptsyntax is a set of convenience functions written on top of RhinoCommon, Rhino's real programming interface. RhinoCommon is Rhino's .NET library, also used from C#, and is accessed directly from Python.

rhinoscriptsyntax RhinoCommon
Objects GUIDs and lists Real geometry objects (Curve, Brep)
Document Every function adds to the document You calculate in memory first and add if you want
Scope Common tasks Everything Rhino can do
Speed Can slow down with many objects Fast
Grasshopper Usable Its native language

Both can be used together in the same script. Practical rule: rhinoscriptsyntax when dealing with objects in the document, RhinoCommon for intermediate calculations and heavy geometry work.

#! python3
import Rhino.Geometry as rg
import scriptcontext as sc
import rhinoscriptsyntax as rs

line = rg.Line(rg.Point3d(0, 0, 0), rg.Point3d(3000, 0, 0))
print("length:", line.Length)
guid = sc.doc.Objects.AddLine(line)
sc.doc.Views.Redraw()

curve = rs.coercecurve(guid)
print(type(curve).__name__, curve.GetLength())
  • sc.doc is the active Rhino document; sc.doc.Objects.AddLine/AddCurve/AddBrep/AddPoint add geometry and return a GUID.
  • After adding with RhinoCommon you need to update the screen with sc.doc.Views.Redraw().
  • rs.coercecurve(id), rs.coercebrep(id), rs.coerce3dpoint(...) convert from a GUID to a RhinoCommon object.

2. Points and vectors (1 hour)

abv = b − aa + v × 0.5Ztangentcross
Point − point = vector; the cross product gives the direction perpendicular to two vectors.

Point3d is a position, Vector3d a direction and magnitude. Arithmetic is natural in RhinoCommon: point − point = vector, point + vector = point, vector × number = vector.

#! python3
import Rhino.Geometry as rg

a = rg.Point3d(0, 0, 0)
b = rg.Point3d(1500, 0, 3200)
v = b - a
print("distance:", a.DistanceTo(b), "vector length:", v.Length)
mid = a + v * 0.5
print("mid-point:", mid)
v.Unitize()
normal = rg.Vector3d.CrossProduct(v, rg.Vector3d.ZAxis)
print("normal to facade:", normal)

The three most common things done with vectors:

  • Unit vector (Unitize): direction only; for offsets and moves.
  • Cross product (CrossProduct): a third vector perpendicular to two vectors; to find an outward normal from a façade line.
  • Angle (VectorAngle): the angle between two directions (radians); converted to degrees with math.degrees.

To try these basic calculations without Rhino, the rhino3dm library we will use on day 7 offers some of the same classes. The example below was run outside Rhino:

import math
import rhino3dm as r3

v = r3.Vector3d(3, 4, 0)
v.Unitize()
print("unit:", v)
print("cross:", r3.Vector3d.CrossProduct(r3.Vector3d(1, 0, 0), r3.Vector3d(0, 1, 0)))
angle = r3.Vector3d.VectorAngle(r3.Vector3d(1, 0, 0), r3.Vector3d(1, 1, 0))
print("angle:", round(math.degrees(angle), 1), "degrees")
unit: 0.6,0.8,0
cross: 0,0,1
angle: 45.0 degrees

(rhino3dm is not all of RhinoCommon; for example point–point subtraction is not available there. Details on day 7.)

3. Planes and transforms (1 hour)

profileWorldXYPlaneToPlaneframe perpendicular to the curve: PerpendicularFrameAt(t)
Placing a profile at each point of a curve, perpendicular to the curve.

A Plane is a local coordinate system made of an origin and two axes. To say "50 mm out along the panel's own axis" on an inclined façade you use that panel's plane.

A Transform is a move, rotation, scale or mirror. It is given to the geometry's Transform method and changes the geometry in place.

Constructor What it does
Transform.Translation(vector) Moves
Transform.Rotation(angle_rad, axis_vec, center) Rotates
Transform.Scale(center, ratio) Scales
Transform.Mirror(plane) Mirrors
Transform.PlaneToPlane(a, b) Places geometry from one plane onto another

Let's try rotation and translation outside Rhino with rhino3dm; the syntax is the same in RhinoCommon:

import math
import rhino3dm as r3

p = r3.Point3d(1000, 0, 0)
p.Transform(r3.Transform.Rotation(math.radians(90), r3.Vector3d(0, 0, 1), r3.Point3d(0, 0, 0)))
print("rotated 90°:", p)
p.Transform(r3.Transform.Translation(r3.Vector3d(0, 0, 3200)))
print("one floor up:", p)

xy = r3.Plane.WorldXY()
print("on plane (10, 20):", xy.PointAt(10, 20))
rotated 90°: 0,1000,0
one floor up: 0,1000,3200
on plane (10, 20): 10,20,0

Inside Rhino: placing a panel at each point on a curve, perpendicular to the curve, is done with PlaneToPlane:

#! python3
import Rhino.Geometry as rg
import rhinoscriptsyntax as rs
import scriptcontext as sc

guid = rs.GetObject("Select the path curve", rs.filter.curve)
if guid:
    path = rs.coercecurve(guid)
    profile = rg.Rectangle3d(rg.Plane.WorldXY, rg.Interval(-30, 30), rg.Interval(-75, 75)).ToNurbsCurve()
    for t in path.DivideByCount(10, True):
        ok, frame = path.PerpendicularFrameAt(t)
        if ok:
            copy_ = profile.DuplicateCurve()
            copy_.Transform(rg.Transform.PlaneToPlane(rg.Plane.WorldXY, frame))
            sc.doc.Objects.AddCurve(copy_)
    sc.doc.Views.Redraw()
  • DivideByCount(n, True) divides the curve into n parts and returns a list of parameters (not points), including the end points.
  • PerpendicularFrameAt(t) gives a plane perpendicular to the curve at that point; it returns a (success, plane) pair.
  • We take a copy with DuplicateCurve(), because Transform changes the geometry in place.

4. Curve and surface methods (45 min)

The methods of RhinoCommon objects are richer than rhinoscriptsyntax. The most useful:

Object Method What it gives
Curve GetLength(), PointAt(t), TangentAt(t) Length, point, tangent
Curve ClosestPoint(p) (success, t): parameter of the closest point
Curve Offset(plane, offset_dist, tolerance, corner) Offset curves
Surface Domain(0), Domain(1) u and v parameter domains
Surface PointAt(u, v), NormalAt(u, v) Point and normal on the surface
Brep Faces, Edges, GetArea(), GetVolume() Faces, edges, area, volume
Brep CreateFromCornerPoints(a, b, c, d, tol) Surface from four corners

Always take the tolerance from the document: sc.doc.ModelAbsoluteTolerance. Typing 0.001 by hand gives different results in millimetre and metre documents.

#! python3
import rhinoscriptsyntax as rs
import scriptcontext as sc

guid = rs.GetObject("Select a surface", rs.filter.surface)
if guid:
    surface_ = rs.coercebrep(guid).Faces[0]
    u, v = surface_.Domain(0), surface_.Domain(1)
    mid = surface_.PointAt(u.Mid, v.Mid)
    normal = surface_.NormalAt(u.Mid, v.Mid)
    print("u:", u, "v:", v)
    print("mid-point:", mid, "normal:", normal)
    print("area:", round(rs.coercebrep(guid).GetArea() / 1e6, 2), "m²",
          "tolerance:", sc.doc.ModelAbsoluteTolerance)

A surface's parameter domain is the (u, v) address of every point on the surface. Tomorrow we will divide this domain into equal parts and find panel corners.

5. Catching errors and undo (15 min)

If a long script fails halfway, half-finished objects remain in the document. Two good habits:

  1. Collect the generated geometry in a list first and add it to the document after everything has been calculated.
  2. Put the adding in try / finally so that screen redraw is turned on in every case:
#! python3
import rhinoscriptsyntax as rs
import scriptcontext as sc

rs.EnableRedraw(False)
try:
    for curve in computed_curves:
        sc.doc.Objects.AddCurve(curve)
finally:
    rs.EnableRedraw(True)

Exercise: Write a script that creates 300 mm lines on a selected curve, perpendicular to the curve's tangent and horizontal (cross product with the z axis), every 1000 mm. Hint: get the t parameters with DivideByLength(1000, True), find the tangent with TangentAt(t) and calculate the horizontal normal with Vector3d.CrossProduct(tangent, Vector3d.ZAxis).

End-of-day check (15 min)

DAY 05

Façade panel automation

~4 hours · 0/6 checks

Goal

By the end of the day you will write a tool that divides a façade surface into a UV grid according to target panel sizes, generates the panels, checks each panel's planarity and size, numbers the panels, adds user text and writes the panel list to a CSV file. This is a project day where the first four days come together. Time about 4 hours.

1. Dividing the surface: parameter and length (45 min)

(i, j)uvus[i] … us[i+1]vs[j] … vs[j+1]
UV grid in the surface parameter space: each cell is a panel.

As we saw yesterday, every point of a surface is addressed by (u, v) parameters. The simplest division is splitting the u and v domains into equal parts. But careful: equal parameter steps do not mean equal length on curved surfaces. So we first calculate how many panels are needed from the surface's edge lengths, then divide the edge curve into equal lengths and use the parameters of the points found.

The panel count calculation can be written without Rhino:

import math


def panel_count(length, target, max_size=None):
    """Integer count closest to the target size without exceeding it. max_size: largest allowed panel size."""
    n = max(1, round(length / target))
    if max_size:
        n = max(n, math.ceil(length / max_size))
    return n, length / n


for L in [12400, 11240, 13600]:
    n, a = panel_count(L, 1500, max_size=1600)
    print(f"edge {L} mm → {n} panels × {a:.1f} mm")
edge 12400 mm → 8 panels × 1550.0 mm
edge 11240 mm → 8 panels × 1405.0 mm
edge 13600 mm → 9 panels × 1511.1 mm

On the 12400 and 13600 mm edges the count closest to the target already stays below the 1600 mm limit. At 11240 mm, however, the closest count would be 7 and the panel would be 1605.7 mm; because that exceeds the limit, the script raised the count to 8. Such rules always exist in façade design: glass size, transport size, sheet width.

2. Planarity check (45 min)

planar: deviation 04th corner out of planedeviation
Planarity of a four-cornered panel: the distance of the fourth corner from the plane.

On a curved surface a four-cornered panel is usually not planar: the fourth corner is slightly outside the plane defined by the first three. For flat glass and sheet panels this deviation must not exceed a certain limit (for example a few millimetres, depending on the system and panel size); if it does, the panel needs cold bending, triangular division or curved fabrication.

Deviation calculation: find the normal of the plane through the first three points (cross product) and measure the distance of the fourth point from this plane. In pure Python:

def diff(a, b):
    return [a[i] - b[i] for i in range(3)]


def cross(u, v):
    return [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]


def plane_deviation(p1, p2, p3, p4):
    """Distance of p4 from the p1-p2-p3 plane (same units)."""
    n = cross(diff(p2, p1), diff(p3, p1))
    height = sum(c * c for c in n) ** 0.5
    return abs(sum(n[i] * (p4[i] - p1[i]) for i in range(3))) / height


flat = plane_deviation([0, 0, 0], [1500, 0, 0], [1500, 0, 3200], [0, 0, 3200])
skewed = plane_deviation([0, 0, 0], [1500, 40, 0], [1500, 0, 3200], [0, 0, 3200])
print(f"flat panel: {flat:.2f} mm, panel with a corner 40 mm off: {skewed:.2f} mm")
flat panel: 0.00 mm, panel with a corner 40 mm off: 39.98 mm

In the second panel one corner is 40 mm off and almost all of the deviation was measured. This simple method puts the whole deviation on the fourth corner. A real check looks at the best-fit plane through the four points (Plane.FitPlaneToPoints in RhinoCommon); in a warped quadrilateral each corner deviates from this plane by about a quarter. Here we used the simple method to see the logic. Inside Rhino rs.PlaneFromPoints and rs.DistanceToPlane do the same job.

3. Generating the panels (1 hour)

select surfacetarget sizescountedge lengthUV gridIsoCurvepanel4 corners, deviationmarklayerresults in sc.sticky → the CSV script reads them
Flow of the panel tool.

The tool's flow: select the surface → get target sizes → calculate counts → set up the (u, v) grid → evaluate four corners for each cell → draw, check, number and annotate the panel.

#! python3
"""Divides a facade surface into panels, checks and numbers them."""
import math
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
import scriptcontext as sc

LAYER_OK = "PANEL::OK"
LAYER_WARN = "PANEL::Check"


def panel_count(length, target, max_size=None):
    n = max(1, round(length / target))
    if max_size:
        n = max(n, math.ceil(length / max_size))
    return n


def equal_parameters(edge, n):
    """Divides the edge curve into n equal lengths and returns the parameters."""
    return list(edge.DivideByCount(n, True))


def main():
    guid = rs.GetObject("Select the facade surface", rs.filter.surface, preselect=True)
    if not guid:
        return
    target_width = rs.GetReal("Target panel width (mm)", 1500, 300, 4000)
    target_height = rs.GetReal("Target panel height (mm)", 3200, 300, 6000)
    limit = rs.GetReal("Planarity limit (mm)", 3, 0.1, 50)
    if None in (target_width, target_height, limit):
        return

    surface_ = rs.coercebrep(guid).Faces[0].UnderlyingSurface()
    bottom_edge = surface_.IsoCurve(0, surface_.Domain(1).Min)    # in u direction, v = min
    left_edge = surface_.IsoCurve(1, surface_.Domain(0).Min)    # in v direction, u = min
    nu = panel_count(bottom_edge.GetLength(), target_width, max_size=target_width * 1.07)
    nv = panel_count(left_edge.GetLength(), target_height)
    us = equal_parameters(bottom_edge, nu)
    vs = equal_parameters(left_edge, nv)

    for name, color in [(LAYER_OK, (90, 160, 210)), (LAYER_WARN, (220, 80, 60))]:
        if not rs.IsLayer(name):
            rs.AddLayer(name, color)

    tol = sc.doc.ModelAbsoluteTolerance
    rows = []
    rs.EnableRedraw(False)
    try:
        for j in range(nv):
            for i in range(nu):
                k = [surface_.PointAt(us[i], vs[j]), surface_.PointAt(us[i + 1], vs[j]),
                     surface_.PointAt(us[i + 1], vs[j + 1]), surface_.PointAt(us[i], vs[j + 1])]
                plane = rg.Plane(k[0], k[1], k[2])
                deviation = abs(plane.DistanceTo(k[3]))
                width = k[0].DistanceTo(k[1])
                height = k[0].DistanceTo(k[3])
                code = f"P-{j + 1}{i + 1:02d}"
                panel = rs.AddPolyline(k + [k[0]])
                rs.ObjectName(panel, code)
                is_ok = deviation <= limit
                rs.ObjectLayer(panel, LAYER_OK if is_ok else LAYER_WARN)
                for key, value in [("code", code), ("width_mm", f"{width:.0f}"), ("height_mm", f"{height:.0f}"),
                                       ("deviation_mm", f"{deviation:.2f}")]:
                    rs.SetUserText(panel, key, value)
                rows.append((code, j + 1, i + 1, width, height, deviation, is_ok))
    finally:
        rs.EnableRedraw(True)

    warnings = sum(1 for s in rows if not s[6])
    print(f"{nu} × {nv} = {len(rows)} panels, {warnings} panels exceed the planarity limit (tolerance {tol})")
    sc.sticky["last_panels"] = rows


main()

New parts:

  • UnderlyingSurface() is the surface beneath a Brep face; IsoCurve(direction, param) extracts a constant u or v curve from the surface. We measured edge lengths from these curves.
  • rg.Plane(a, b, c) gives a plane through three points, DistanceTo a signed distance.
  • The check result is reflected in the layer: panels exceeding the limit are on the red PANEL::Check layer.
  • We stored the results in sc.sticky; the next script (writing CSV) will use them.
  • Putting the code in a main() function and exiting early with return is more readable than nested ifs.

Try it on the curved façade surface you made with a loft on day 2: the panels in the middle will most likely come out red.

4. Writing the panel list to CSV (45 min)

correctif not donedelimiter=";"encoding="utf-8-sig" (BOM)decimal: 4,84comma separator → single columnno BOM → Turkish letters garbleddot → taken as a date or text
Three settings for a Turkish-locale Excel to open the CSV correctly.

The panel list should be a CSV that opens in Excel. Python's csv module handles the separator and quoting correctly. For a Turkish-locale Excel to open the file properly, two settings: a semicolon separator and a UTF-8 BOM (encoding="utf-8-sig"). We also convert the decimal separator in numbers to a comma. (With an English-locale Excel use a comma separator and a decimal point.)

import csv

rows = [("P-101", 1, 1, 1511.1, 3200.0, 0.0, True), ("P-102", 1, 2, 1511.1, 3200.0, 4.73, False),
            ("P-201", 2, 1, 1511.1, 3200.0, 1.28, True)]


def tr(number, decimals=1):
    return f"{number:.{decimals}f}".replace(".", ",")


with open("panel_list.csv", "w", newline="", encoding="utf-8-sig") as f:
    write = csv.writer(f, delimiter=";")
    write.writerow(["Code", "Floor", "Order", "Width (mm)", "Height (mm)", "Area (m²)", "Deviation (mm)", "Status"])
    for code, floor, order, width, height, deviation, is_ok in rows:
        write.writerow([code, floor, order, tr(width), tr(height), tr(width * height / 1e6, 2), tr(deviation, 2), "ok" if is_ok else "CHECK"])

with open("panel_list.csv", encoding="utf-8-sig") as f:
    print(f.read())
Code;Floor;Order;Width (mm);Height (mm);Area (m²);Deviation (mm);Status
P-101;1;1;1511,1;3200,0;4,84;0,00;ok
P-102;1;2;1511,1;3200,0;4,84;4,73;CHECK
P-201;2;1;1511,1;3200,0;4,84;1,28;ok

Inside Rhino you run the same code by reading from sc.sticky["last_panels"]. To let the user choose the file path use rs.SaveFileName("Panel list", "CSV (*.csv)|*.csv||"); the folder of the open document comes from rs.DocumentPath().

5. Making the tool usable (30 min)

If a script will be used in a team:

  1. Toolbar button: Right-click a toolbar in Rhino and add a new button; in the command field write ! _-RunPythonScript "C:\Scripts\panel_split.py". If the path contains spaces it must be in quotes.
  2. Alias: In Options › Aliases define a short name such as pb and give the same command.
  3. Settings at the top: Layer names, default sizes and limits should sit at the very top of the script as upper-case constants, so a colleague can change them without reading the code.
  4. Version and date: Write a version number in the comment at the top of the file and keep scripts in a shared folder (or in Git).

Exercise: Extend the tool: (1) if a panel width deviates more than 5% from the target, write "size_warning": "yes" (size warning: yes) to its user text; (2) group panels with the same size (±2 mm), give each group a type code (T1, T2…) and print the number of types. A division with few types is a great help in fabrication.

End-of-day check (15 min)

DAY 06

Python in Grasshopper

~4 hours · 0/6 checks

Goal

By the end of the day you will be able to use the Python script component in Grasshopper; define inputs and outputs and give type hints, know the difference between item, list and tree access, and write in Python the classic parametric façade example that changes panel openings with an attractor. Time about 4 hours.

1. The Script component (45 min)

Python 3 Scriptcodepanel (List, Curve)cekici (attractor) (Item, Point3d)etki (influence) (Item, float)a opening curvesb ratiosout print
Grasshopper Python component: named inputs (with access and type hints) and outputs.

The Python component is used when Grasshopper's built-in components are not enough for a task or when you want to collect a ten-component chain into one piece of logic.

In Rhino 8 drag the Python 3 Script component from the Maths › Script tab onto the canvas (or double-click the canvas and type python). By default it has two inputs (x, y) and one output (a); the out output also shows what is written with print. Double-click the component to open the editor.

  • Adding inputs/outputs: Zoom in on the component; add or remove with the + and − that appear next to the inputs. Right-click an input's name to rename it: the variable name in the code is this name.
  • Giving output: Assign a value to a variable with the same name as the output. If you write a = 5, 5 appears in output a.
  • The component reruns whenever an input changes; so the code must be fast and must not add objects to the document: you give geometry as output and Grasshopper displays it. sc.doc.Objects.Add... is not used inside Grasshopper (baking is a separate task).

First example: a component producing points side by side from an n (integer) and spacing (spacing, number) input:

import Rhino.Geometry as rg

points = [rg.Point3d(i * spacing, 0, 0) for i in range(n)]
a = points
print(f"{n} points, total length {(n - 1) * spacing}")

2. Type hints (30 min)

Whatever is connected to an input in Grasshopper (number, text, curve), the component takes it as it is. A type hint converts the incoming value to a specific type: right-click the input › Type Hint › float, int, str, Point3d, Curve, Brep… The right type hint does three things:

  1. A number slider arrives not as text but as a number you can calculate with.
  2. A curve referenced from Rhino arrives directly as a Curve object, not as a GUID; you can use methods such as PointAt and GetLength.
  3. If something of the wrong type is connected, the component gives an understandable error.

An input without a type hint may receive ghdoc or a GUID; then rhinoscriptsyntax functions work but RhinoCommon methods don't. Rule: give every input a type hint.

3. Item, list and tree access (1 hour)

component runsvalue in the codeItem: once per itemList: once per branchTree: once, the whole treex → a single valuex → a Python listx → DataTree (treehelpers)
Input access types.

In Grasshopper data flows in a tree structure: branches and a list in each branch. A Python component can receive an input in three ways (right-click the input):

Access In the code How many times the component runs
Item (default) A single value Once for each item in the list
List A Python list Once per branch
Tree The whole tree (DataTree) Once

Most common mistake: leaving access on Item when you want to process the list at once. The component runs separately for each item and code like len(x) fails. If you need totals, sorting or neighbouring items, choose List access.

When working with trees, the easiest way is to convert the tree into nested Python lists and back:

import ghpythonlib.treehelpers as th

rows = th.tree_to_list(tree)          # [[...], [...], ...]
totals = [sum(branch) for branch in rows]
a = th.list_to_tree(totals)

You can also try the nested list logic without Grasshopper. Let each floor of a façade be a separate branch:

floors = [
    [1500, 1500, 1200],
    [1500, 1500, 1200, 900],
    [1500, 1200],
]
for i, floor in enumerate(floors):
    print(f"{{0;{i}}}: {len(floor)} panels, total {sum(floor)} mm")
all_ = [g for floor in floors for g in floor]
print("flattened:", len(all_), "panels")
transposed = [[floor[i] for floor in floors if i < len(floor)] for i in range(max(len(k) for k in floors))]
print("by axis:", transposed)
{0;0}: 3 panels, total 4200 mm
{0;1}: 4 panels, total 5100 mm
{0;2}: 2 panels, total 2700 mm
flattened: 9 panels
by axis: [[1500, 1500, 1500], [1500, 1500, 1200], [1200, 1200], [900]]

Notation such as {0;0} is Grasshopper's branch address. Flattening and flip matrix do the same job as their Grasshopper counterparts.

4. Parametric façade with an attractor (1 hour)

attractor
Small openings in panels near the attractor, large ones further away.

A classic parametric façade rule: the opening (for example a hole or glazed opening) is small in panels near an attractor point and large in panels further away. The rule is pure mathematics; let's first write it in pure Python:

def opening(distance, smallest=0.15, largest=0.85, influence=6000):
    """Opening ratio 0–1 by distance to the attractor. influence: distance (mm) at which the ratio reaches its maximum."""
    t = min(distance / influence, 1.0)
    t = t * t * (3 - 2 * t)          # smooth transition (smoothstep)
    return smallest + (largest - smallest) * t


attractor = (4500, 0, 6400)
for floor in range(4):
    row = []
    for axis in range(6):
        center = (axis * 1500 + 750, 0, floor * 3200 + 1600)
        d = sum((center[i] - attractor[i]) ** 2 for i in range(3)) ** 0.5
        row.append(f"{opening(d):.2f}")
    print(f"floor {floor + 1}: " + " ".join(row))
floor 1: 0.85 0.82 0.78 0.78 0.82 0.85
floor 2: 0.68 0.46 0.30 0.30 0.46 0.68
floor 3: 0.68 0.46 0.30 0.30 0.46 0.68
floor 4: 0.85 0.82 0.78 0.78 0.82 0.85

The attractor sits between floors 2 and 3, on the boundary of axes 3 and 4; these four panels have the smallest ratio (0.30), growing with distance. The table is symmetric because the attractor is exactly in the middle. The smoothstep function gives a curve that eases at the start and end instead of a linear transition; it looks more natural on a façade.

In Grasshopper: inputs panel (List access, type hint Curve: closed panel frames), attractor (attractor; Item, Point3d), influence (influence; Item, float). Output a: an opening curve at the centre of each panel, scaled by the ratio.

import Rhino.Geometry as rg


def opening(distance, smallest=0.15, largest=0.85, influence=6000):
    t = min(distance / influence, 1.0)
    t = t * t * (3 - 2 * t)
    return smallest + (largest - smallest) * t


openings = []
ratios = []
for p in panel:
    area = rg.AreaMassProperties.Compute(p)
    if area is None:
        continue
    center = area.Centroid
    ratio = opening(center.DistanceTo(attractor), influence=influence)
    copy_ = p.DuplicateCurve()
    copy_.Transform(rg.Transform.Scale(center, ratio ** 0.5))
    openings.append(copy_)
    ratios.append(ratio)

a = openings
b = ratios
  • AreaMassProperties.Compute(curve) gives the area and centroid of a closed planar curve.
  • For the opening's area to follow the ratio, the linear scale must be the square root of the ratio (area grows with the square of the scale).
  • We also added a b output: the ratios. You can connect them to a Gradient component to colour the panels or write them to a list as on day 5.

As you drag the attractor point in Rhino, the façade updates instantly. You can generate the panel frames with Grasshopper's Divide Domain² + Isotrim components or reference the panels you drew in Rhino on day 5 in a Curve parameter.

5. Sharing and keeping things tidy (30 min)

  • Keeping code outside: You can keep long code not inside the component but in a .py file and import it in the component. In Rhino 8 a module created in the ScriptEditor can be shared by components; changes are made in one place.
  • User object: Right-click the component › Create User Object to put it in your own tab; everyone on the team uses it with its name, description and icon.
  • Errors: If the component turns red, the balloon above it shows the error and the line number. Writing intermediate values to the out output with print is the fastest debugging method.
  • Performance: With Item access the component restarts for each item; with thousands of items, switching to List access and processing in a single loop is much faster.

Exercise: Change the attractor component to work with two attractor points: compute the ratio from the distance to the nearest attractor (min(p.DistanceTo(c) for c in attractors)). Don't forget to switch the attractor input to List access. Try it first in the pure Python example with two attractors and see how the table changes.

End-of-day check (15 min)

DAY 07

Outside Rhino: rhino3dm and a project

~4 hours · 0/6 checks

Goal

By the end of the day you will be able to read and write .3dm files with ordinary Python without opening Rhino: layers, objects, names and user text. The course ends with a project: two scripts that divide a curved façade surface into panels, check planarity, write the result to a layered .3dm file and a CSV list, then read the file back and produce a report. Time about 4 hours.

All of today's examples were run without Rhino; the outputs are real results.

1. What is rhino3dm? (30 min)

Python scriptimport rhino3dm.3dm filelayers, UserTextRhinoopens the same fileOn a computer without Rhino, on a server, in Docker
rhino3dm: reading and writing .3dm without opening Rhino.

rhino3dm is the Python version of McNeel's open-source openNURBS library. It lets you read and write .3dm files on a computer without Rhino, on a server or in a Docker container. Installation:

pip install rhino3dm
import rhino3dm as r3

print(r3.__version__)
c = r3.Circle(r3.Point3d(0, 0, 0), 500)
print(round(c.Circumference, 2))
8.35.0
3141.59

What it can and cannot do:

Can Cannot
Read and write .3dm (Rhino 4–8 versions) Boolean, intersection, offset, fillet
Layers, object attributes, user text Meshing (mesh from surface)
Point, curve, NURBS surface, Brep, mesh objects Run Rhino commands
Evaluating points on curves and surfaces (PointAt) Some calculations such as curve length and area

Heavy geometry operations need McNeel's Rhino.Compute server (which offers Rhino's calculation engine as a web service) or Rhino itself. But rhino3dm is enough for extracting data, producing reports and writing simple rule-based geometry.

Caution: the classes in rhino3dm resemble RhinoCommon but are not identical. For example you cannot subtract Point3d objects with the minus sign; you calculate with the coordinates (.X, .Y, .Z).

2. Writing .3dm (1 hour)

File3dm()empty documentLayerLayers.AddAttributeslayer, nameObjects.Add…geometryWrite(yol, 8)Rhino 8
Steps for writing a .3dm file.

A File3dm object is an empty Rhino document. You add layers and objects and save with Write:

import rhino3dm as r3

model = r3.File3dm()
model.Settings.ModelUnitSystem = r3.UnitSystem.Millimeters


def layer(name, color):
    k = r3.Layer()
    k.Name = name
    k.Color = (*color, 255)
    return model.Layers.Add(k)


glass = layer("Panel_Glass", (90, 160, 210))
label = layer("Label", (40, 40, 40))

for i, x in enumerate([0, 1500, 3000]):
    frame = r3.Polyline()
    for px, pz in [(x, 0), (x + 1500, 0), (x + 1500, 3200), (x, 3200), (x, 0)]:
        frame.Add(px, 0, pz)
    attr = r3.ObjectAttributes()
    attr.LayerIndex = glass
    attr.Name = f"P-1{i + 1:02d}"
    attr.SetUserString("type", "glass")
    attr.SetUserString("area_m2", "4.80")
    model.Objects.AddPolyline(frame, attr)

    text = r3.ObjectAttributes()
    text.LayerIndex = label
    model.Objects.AddTextDot(attr.Name, r3.Point3d(x + 750, 0, 1600), text)

print("written:", model.Write("sample_panels.3dm", 8))
print(len(model.Objects), "objects,", len(model.Layers), "layers")
written: True
6 objects, 2 layers
  • Write(path, 8): saves in Rhino 8 format; 7 or 6 can be given for older Rhinos.
  • Colour has four components: (red, green, blue, transparency).
  • An object's layer, name and user text sit in an ObjectAttributes object and are given when the object is added.

When you open this file in Rhino you see three panels on the Panel_Glass layer, with their labels and with the kind and area_m2 information under Properties › Attribute User Text.

3. Reading .3dm (45 min)

Let's open the file we just wrote and list its contents. The same code works for any file drawn in Rhino:

import collections
import rhino3dm as r3

model = r3.File3dm.Read("sample_panels.3dm")
print("unit:", model.Settings.ModelUnitSystem)
print("layers:", [k.Name for k in model.Layers])

counter = collections.Counter()
for obj in model.Objects:
    attr = obj.Attributes
    lay = model.Layers[attr.LayerIndex].Name
    otype = type(obj.Geometry).__name__
    counter[(lay, otype)] += 1
    if attr.Name and attr.Name.startswith("P-"):
        print(attr.Name, otype, dict(attr.GetUserStrings()))
print(dict(counter))
unit: UnitSystem.Millimeters
layers: ['Panel_Glass', 'Label']
P-101 PolylineCurve {'type': 'glass', 'area_m2': '4.80'}
P-102 PolylineCurve {'type': 'glass', 'area_m2': '4.80'}
P-103 PolylineCurve {'type': 'glass', 'area_m2': '4.80'}
{('Panel_Glass', 'PolylineCurve'): 3, ('Label', 'TextDot'): 3}

GetUserStrings() gives all user texts as key–value pairs. With this method you can scan all .3dm files in a project folder and produce a panel list, a take-off or a report of "objects missing user text"; no Rhino licence or open Rhino is needed.

4. Project: dividing a curved façade into panels (1 h 15 min)

Panel tool without Rhinocephe.pysurface + panelsdeviation3 mm limit.3dm + CSVlayered, listedrapor.pysummary by axis
Final project: generate, check, write, read back.

This time we generate ourselves something similar to the curved façade we made with a loft on day 2: a ruled surface formed by straight lines between a bottom and a top curve. Then, as on day 5, panels, planarity check and a list. Save the script below as facade.py:

"""Divides a curved facade into panels; writes .3dm and CSV (no Rhino needed)."""
import csv
import rhino3dm as r3

WIDTH_TARGET, HEIGHT_TARGET, LIMIT_MM = 1500, 3200, 3.0


def point_diff(a, b):
    return [a.X - b.X, a.Y - b.Y, a.Z - b.Z]


def distance(a, b):
    return sum(c * c for c in point_diff(a, b)) ** 0.5


def deviation(p1, p2, p3, p4):
    u, v = point_diff(p2, p1), point_diff(p3, p1)
    n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
    height = sum(c * c for c in n) ** 0.5
    w = point_diff(p4, p1)
    return abs(sum(n[i] * w[i] for i in range(3))) / height


def curve_length(curve, sample=200):
    d = curve.Domain
    points = [curve.PointAt(d.T0 + (d.T1 - d.T0) * i / sample) for i in range(sample + 1)]
    return sum(distance(a, b) for a, b in zip(points, points[1:]))


def facade_surface():
    bottom = [r3.Point3d(0, 0, 0), r3.Point3d(6000, 900, 0), r3.Point3d(12000, 0, 0)]
    top = [r3.Point3d(p.X, p.Y * 0.9, 12800) for p in bottom]
    a = r3.Curve.CreateControlPointCurve(bottom, 2)
    b = r3.Curve.CreateControlPointCurve(top, 2)
    return r3.NurbsSurface.CreateRuledSurface(a, b), a, b


def main():
    surface_, bottom_curve, left_height = facade_surface()
    L = curve_length(bottom_curve)
    nu = max(1, round(L / WIDTH_TARGET))
    nv = max(1, round(12800 / HEIGHT_TARGET))
    du, dv = surface_.Domain(0), surface_.Domain(1)
    us = [du.T0 + (du.T1 - du.T0) * i / nu for i in range(nu + 1)]
    vs = [dv.T0 + (dv.T1 - dv.T0) * j / nv for j in range(nv + 1)]

    model = r3.File3dm()
    model.Settings.ModelUnitSystem = r3.UnitSystem.Millimeters
    layer = {}
    for name, color in [("Facade", (200, 200, 200)), ("Panel_OK", (90, 160, 210)),
                     ("Panel_Check", (220, 80, 60)), ("Label", (40, 40, 40))]:
        k = r3.Layer()
        k.Name, k.Color = name, (*color, 255)
        layer[name] = model.Layers.Add(k)

    attr = r3.ObjectAttributes()
    attr.LayerIndex = layer["Facade"]
    model.Objects.AddSurface(surface_, attr)

    rows = []
    for j in range(nv):
        for i in range(nu):
            k = [surface_.PointAt(us[i], vs[j]), surface_.PointAt(us[i + 1], vs[j]),
                 surface_.PointAt(us[i + 1], vs[j + 1]), surface_.PointAt(us[i], vs[j + 1])]
            s = deviation(*k)
            code = f"P-{j + 1}{i + 1:02d}"
            width, height = distance(k[0], k[1]), distance(k[0], k[3])
            is_ok = s <= LIMIT_MM
            pl = r3.Polyline()
            for p in k + [k[0]]:
                pl.Add(p.X, p.Y, p.Z)
            attr = r3.ObjectAttributes()
            attr.LayerIndex = layer["Panel_OK" if is_ok else "Panel_Check"]
            attr.Name = code
            for key, value in [("floor", str(j + 1)), ("axis", str(i + 1)), ("width_mm", f"{width:.0f}"),
                                   ("height_mm", f"{height:.0f}"), ("deviation_mm", f"{s:.2f}")]:
                attr.SetUserString(key, value)
            model.Objects.AddPolyline(pl, attr)
            et = r3.ObjectAttributes()
            et.LayerIndex = layer["Label"]
            m = surface_.PointAt((us[i] + us[i + 1]) / 2, (vs[j] + vs[j + 1]) / 2)
            model.Objects.AddTextDot(code, m, et)
            rows.append([code, j + 1, i + 1, round(width), round(height), round(s, 2), "ok" if is_ok else "CHECK"])

    model.Write("facade_panels.3dm", 8)
    with open("facade_panels.csv", "w", newline="", encoding="utf-8-sig") as f:
        write = csv.writer(f, delimiter=";")
        write.writerow(["code", "floor", "order", "width_mm", "height_mm", "deviation_mm", "status"])
        write.writerows(rows)
    check = sum(1 for s in rows if s[-1] != "ok")
    print(f"bottom edge {L:.0f} mm → {nu} × {nv} = {len(rows)} panels, {check} panels need checking")
    print("written: facade_panels.3dm, facade_panels.csv")


if __name__ == "__main__":
    main()

New parts:

  • rhino3dm has no curve length method; curve_length samples the curve at 200 points and sums the short straight segments. This is an approximation, but with 200 samples it is accurate to below a millimetre.
  • The top curve's curvature is slightly (10%) less than the bottom one. Because the bottom and top curves are not parallel, the straight lines between them rotate slightly and the surface is twisted; this is why the panels are not planar.
  • Floor and axis numbers were also written to the user text; the report won't have to parse them from the name.
  • This version divides parameters equally (instead of equal length as on day 5). This is enough for a simple curve; we will see the small difference between panels in the table.
python3 facade.py
sed -n '2,9p' facade_panels.csv
bottom edge 12045 mm → 8 × 4 = 32 panels, 16 panels need checking
written: facade_panels.3dm, facade_panels.csv
P-101;1;1;1513;3200;4.88;CHECK
P-102;1;2;1507;3200;3.5;CHECK
P-103;1;3;1502;3200;2.11;ok
P-104;1;4;1500;3200;0.7;ok
P-105;1;5;1500;3200;0.7;ok
P-106;1;6;1502;3200;2.11;ok
P-107;1;7;1507;3200;3.5;CHECK
P-108;1;8;1513;3200;4.88;CHECK

sed -n '2,9p' skipped the header line and showed the eight panels of floor 1. Panel widths grow slightly at the ends (1513 mm) because we divided the parameter equally. The deviation of the end panels exceeds the 3 mm limit.

5. Reading the report back (30 min)

The second script opens the .3dm file and produces a summary by floor. Even if someone changes the panels' user text in Rhino, the report reads the latest state of the file:

"""Per-axis summary from the panel .3dm file."""
import collections
import sys
import rhino3dm as r3

path = sys.argv[1] if len(sys.argv) > 1 else "facade_panels.3dm"
model = r3.File3dm.Read(path)
axes = collections.defaultdict(list)
for n in model.Objects:
    attr = n.Attributes
    if not attr.GetUserString("axis"):
        continue
    layer = model.Layers[attr.LayerIndex].Name
    axes[int(attr.GetUserString("axis"))].append((attr.Name, float(attr.GetUserString("deviation_mm")), layer))

print(f"{path}: {sum(len(v) for v in axes.values())} panels")
print("axis  panel    check  max deviation")
for axis in sorted(axes):
    items = axes[axis]
    check = sum(1 for _, _, k in items if k == "Panel_Check")
    worst = max(items, key=lambda x: x[1])
    print(f"{axis:>3}  {len(items):>5}  {check:>7}  {worst[1]:6.2f} mm ({worst[0]})")
python3 report.py
facade_panels.3dm: 32 panels
axis  panel    check  max deviation
  1      4        4    4.89 mm (P-401)
  2      4        4    3.50 mm (P-102)
  3      4        0    2.11 mm (P-103)
  4      4        0    0.70 mm (P-104)
  5      4        0    0.70 mm (P-105)
  6      4        0    2.11 mm (P-106)
  7      4        4    3.50 mm (P-107)
  8      4        4    4.89 mm (P-408)

The table shows a clear pattern: deviation does not vary by floor but by axis. In the end axes (where the curves turn most) panels exceed the limit; those in the middle are below it. On a ruled surface the twist is almost constant over the height; that's why the same axes are problematic on every floor. With this information the design team can decide on narrower panels, cold bending or triangular division only for the end axes; the middle panels stay flat glass.

The report read floor and axis information from user text, not from the panel name. A good habit: store information explicitly in user text rather than parsing it from the name; the code won't break even if the name format changes or the number of floors exceeds 9.

6. Next steps (15 min)

  • Rhino.Compute: For things rhino3dm cannot do (intersection, offset, running Grasshopper definitions) you can run Rhino's calculation engine on a server and call it from Python.
  • On the web: With the JavaScript version of rhino3dm (rhino3dm.js) you can open .3dm files in the browser and display them with three.js.
  • Data analysis: To analyse the panel list with pandas, see the site's Data Analysis with Python course.
  • With C#: The same RhinoCommon knowledge applies in C#; the C# for Rhino and Grasshopper course is the way to faster and distributable plug-ins.
  • Grasshopper: For parametric workflows, the Grasshopper course.

Exercise: (1) Extend report.py with an option to group by floor instead of axis (python report.py facade_panels.3dm floor). (2) Try increasing the number of panels (nu) in facade.py: with 12 axes instead of 8, how does the number of panels needing checks change? How do narrower panels affect the twist?

End-of-day check (15 min)