AlphaPrism is in active development: features may change and you may run into bugs. Keep backups of your work.Known issuesReport a bug
Skip to content

Example scripts ​

These scripts ship with Prism. Open them from the Open menu in the Script workspace, or copy them into your scripts folder.

Plate with a ring of holes ​

Loops and maths work as in any Python program.

py
"""A plate with a ring of holes: loops and maths work like in any Python program."""
import math
import cadkit as cad

with cad.history("Plate with holes"):          # everything in this block is ONE undo step
    plate = cad.box(width=80, depth=80, height=6)
    for i in range(8):
        a = math.radians(i * 45)
        hole = cad.cylinder(radius=4, height=20, position_x=28 * math.cos(a), position_y=28 * math.sin(a))
        cad.subtract(plate, hole)
    centre = cad.cylinder(radius=10, height=20)
    cad.subtract(plate, centre)

print("Done:", plate.name)
cad.view("iso", fit=True)

Sheet metal bracket ​

A flange from a cross-section sketch, unfolded to a flat pattern.

py
"""Sketch a cross-section, make bent sheet metal from it, then unfold it."""
import cadkit as cad

with cad.history("U bracket"):
    with cad.sketch("XZ") as s:                       # straight lines, sharp corners: the bends are added for you
        s.polyline([(0, 25), (0, 0), (50, 0), (50, 25)])
    body = cad.flange(s.obj, thickness=2, bend_radius=3, width=40)
    cad.flat_pattern(body, k_factor=0.44)

print("Made", body.name, "and its flat pattern")

Vase by revolve ​

py
"""A vase: draw half of the outline, spin it round the Z axis, then hollow it out."""
import cadkit as cad

with cad.history("Vase"):
    with cad.sketch("XZ") as s:
        s.polyline([(0, 0), (18, 0), (26, 25), (16, 60), (10, 80), (14, 95), (0, 95)], closed=True)
    vase = cad.revolve(s.obj, angle=360, axis="World Z")
print("Made", vase.name, "- size", vase.size)
cad.view("front", fit=True)

Ask for a plate ​

A script with its own dialog, so it works as a reusable tool.

py
"""Ask the user for the sizes first: a dialog appears, then the plate is built from the answers."""
import cadkit as cad

answers = cad.ask("Mounting plate",
                  width=80, depth=50, thickness=6,
                  hole_diameter=8.5, holes=True, material=["Steel", "Aluminum", "Brass"])
if answers is None:
    raise SystemExit("Cancelled")                 # the user pressed Cancel

with cad.history("Mounting plate"):
    plate = cad.box(width=answers["width"], depth=answers["depth"], height=answers["thickness"])
    if answers["holes"]:
        r = answers["hole_diameter"] / 2
        for sx in (-1, 1):
            for sy in (-1, 1):
                hole = cad.cylinder(radius=r, height=answers["thickness"] * 3,
                                    position_x=sx * (answers["width"] / 2 - 10), position_y=sy * (answers["depth"] / 2 - 10))
                cad.subtract(plate, hole)

print("Made a", answers["material"], "plate:", plate.name)
cad.view("iso", fit=True)

Freeform steam iron ​

Freeform cages built and edited from code, then converted.

py
"""An editable product study built with cadkit, without importing a prebuilt mesh.

Run in Prism's Script tab, or with cadkit on PYTHONPATH while Prism is open.
Opens its own document. Set PRISM_STUDY_OUTPUT to save the result and screenshot.
"""
import base64
import math
import os
from pathlib import Path

import cadkit as cad


def finish(obj, name, color, metal=0, gloss=0.35):
    obj.rename(name)
    cad.call("material_apply", object=obj.name, color=color, metal=metal, gloss=gloss)
    return obj


def hull(name, height, base, color, sole=False):
    obj = cad.form_box(width=240, depth=110, height=height, faces_x=8, faces_y=4, faces_z=3)
    cage = cad.form_info(obj)
    positions = {}
    for i, (x, y, z) in enumerate(cage["vertices"]):
        t = (x + 120) / 240
        v = z / height
        width = 55 * (1 - 0.92 * t ** 2.4)
        if sole:
            zz = [0, 1, 5, 6][round(v * 3)]
            positions[str(i)] = [x, y / 55 * width, zz]
        else:
            positions[str(i)] = [
                x - 35 * t * v ** 1.1,
                y / 55 * width * (1 - 0.17 * v),
                base + v * (52 - 12 * t + 9 * math.sin(math.pi * t)),
            ]
    cad.form_op(obj, "set_vertices", positions=positions)
    return finish(obj, name, color, metal=0.8 if sole else 0.05, gloss=0.45)


def build():
    cad.call("document_new")
    with cad.history("Freeform steam iron product study"):
        hull("03 Glide - soleplate", 6, 0, "#414A58", sole=True)
        hull("03 Glide - water housing", 70, 7, "#80C4D0")
        points = [[-88, 0, 51], [-92, 0, 83], [-66, 0, 111], [-16, 0, 119], [31, 0, 105], [46, 0, 58]]
        path = cad.run("curve_through", points=points)[0]
        path.rename("03 Glide - handle path")
        handle = cad.form_pipe(path, radius_at_the_start=11, radius_at_the_end=10,
                               sides=8, steps_along_the_path=18, close_the_ends=True)
        finish(handle, "03 Glide - soft grip", "#283748", gloss=0.22)
        cad.call("object_update", object=path.name, visible=False)
        dial = cad.form_cylinder(radius=19, height=8, sides=16, rings=3, position_x=-12, position_z=62)
        finish(dial, "03 Glide - temperature dial", "#E8E0CF", gloss=0.3)
        inlet = cad.form_cylinder(radius=9, height=6, sides=12, rings=3, position_x=68, position_z=52)
        finish(inlet, "03 Glide - water inlet", "#E8E0CF", gloss=0.3)
    cad.select()
    cad.call("view", yaw=-32, pitch=22, fit=True, grid=False, display="shaded")
    cad.call("wait_idle")
    for obj in cad.objects():
        if obj.kind != "Form":
            continue
        report = cad.form_info(obj, summary=True)
        topology = report["topology"]
        assert report["closed"], (obj.name, "open cage")
        assert not topology["nonManifoldEdges"] and not topology["windingConflicts"], (obj.name, topology)
        print(obj.name, report["vertexCount"], "vertices", topology)
    output = os.environ.get("PRISM_STUDY_OUTPUT")
    if output:
        folder = Path(output).resolve()
        folder.mkdir(parents=True, exist_ok=True)
        cad.save(str(folder / "03-glide-steam-iron.prism"))
        picture = cad.screenshot()["_image"]["data"]
        (folder / "03-glide-steam-iron.png").write_bytes(base64.b64decode(picture))


if __name__ == "__main__":
    build()

Camera lens ​

The showcase lens from the website, built only with Solid tools: revolved parts, fillets and chamfers found by geometry, knurling and ribs cut with circular patterns, a glass element from a sphere and a cylinder, and a material for each part.

py
"""A 50 mm camera lens built only with Solid tools: revolve, fillet, chamfer, patterns and booleans.

Each part is its own body so it can have its own material: anodised barrel, rubber focus ring,
polished steel mount, red accent ring, coated glass and printed distance marks.
"""
import cadkit as cad

cad.call("file", action="new")


def turned(name, profile):
    """Revolve a closed (radius, height) profile drawn on XZ about the Z axis."""
    with cad.sketch("XZ") as s:
        s.polyline(profile, closed=True)
    body = cad.revolve(s.obj, angle=360, axis="World Z")
    cad.call("object_update", object=s.obj.name, visible=False)
    return body.rename(name)


def circle_edges(body, radius, z):
    """Edges of a turned part found by radius and height, so the script does not depend on edge numbers."""
    hits = cad.call("solid_find", object=body, kind="edges", type="Circle", limit=60)["hits"]
    return [{"object": body, "edge": h["edge"]} for h in hits
            if abs(h["radius"] - radius) < 0.01 and abs(h["center"][2] - z) < 0.01]


def ring_of(tool, count, target=None, total_angle=360, result="Cut from a body"):
    """Repeat a small body around the Z axis, cutting it from (or joining it to) a target."""
    slots = {"Objects to pattern": [tool.name]}
    if target:
        slots["Target body"] = target
    cad.run("pattern_circular", slots=slots, axis="Z axis", count=count,
            angle="Total angle", angle_value=total_angle, result=result)


with cad.history("Camera lens"):
    # Turned parts: (radius, height) profiles in millimetres, front of the lens at the top.
    turned("Barrel", [(22, 6), (31, 6), (31, 9), (33, 9), (33, 22), (32, 22), (32, 48), (34, 48),
                      (34, 62), (32.5, 66), (27.5, 66), (27.5, 61), (22, 61)])
    turned("Focus ring", [(32, 22.6), (35.6, 22.6), (35.6, 47.4), (32, 47.4)])
    turned("Mount", [(20, 0), (29.5, 0), (29.5, 6), (20, 6)])
    turned("Accent ring", [(34, 54.4), (34.45, 54.4), (34.45, 55.4), (34, 55.4)])

    # Soften the outside edges.
    cad.fillet(circle_edges("Barrel", 31, 6) + circle_edges("Barrel", 33, 9) + circle_edges("Barrel", 33, 22)
               + circle_edges("Barrel", 34, 48) + circle_edges("Barrel", 32.5, 66), radius=0.8)
    cad.fillet(circle_edges("Focus ring", 35.6, 22.6) + circle_edges("Focus ring", 35.6, 47.4), radius=1.4)
    cad.chamfer(circle_edges("Mount", 29.5, 0), distance=0.8)
    cad.chamfer(circle_edges("Mount", 20, 0), distance=0.6)

    # Knurled focus grip and finer ribs on the aperture ring.
    ring_of(cad.box(width=1.2, depth=1.5, height=19, position_x=35.5, position_z=25.6), 72, target="Focus ring")
    ring_of(cad.box(width=1.0, depth=0.8, height=8.6, position_x=33.0, position_z=11.2), 96, target="Barrel")

    # Front element: a spherical cap that fills the 27.3 mm opening with a 3.6 mm rise.
    a, rise, top = 27.3, 3.6, 64.6
    radius = (a * a + rise * rise) / (2 * rise)
    disc = cad.cylinder(radius=a, height=5, position_z=61)
    cad.intersect(disc, cad.sphere(radius=radius, position_z=top - radius))
    disc.rename("Front glass")

    # Distance scale: 13 raised marks over 96 degrees, joined into one body and turned to face the front.
    before = {o.name for o in cad.objects()}
    ring_of(cad.box(width=1.0, depth=0.55, height=2.6, position_x=34.1, position_z=49.6), 13,
            total_angle=96, result="New bodies")
    marks = [o.name for o in cad.objects() if o.name not in before]
    cad.union(marks[0], *marks[1:])
    cad.get(marks[0]).rename("Markings")
    cad.run("rotate", slots={"Objects": ["Markings"]}, axis="Z", angle=-75, pivot="World origin")

    # Appearance. Library materials also give the parts real densities for mass properties.
    looks = {
        "Barrel": dict(material="6061", color="#1B1C20", metal=0.55, gloss=0.45),
        "Focus ring": dict(material="silicone", color="#141416", metal=0.0, gloss=0.12),
        "Mount": dict(material="304", color="#D9DCE1", metal=1.0, gloss=0.95),
        "Accent ring": dict(material="6061", color="#C8102E", metal=0.5, gloss=0.6),
        "Front glass": dict(material="glass", color="#20414F", metal=0.1, gloss=1.0),
        "Markings": dict(color="#F2F2F2", metal=0.0, gloss=0.3),
    }
    for part, look in looks.items():
        cad.call("material_apply", object=part, **look)

for part in ("Barrel", "Focus ring", "Mount", "Accent ring", "Front glass", "Markings"):
    print(cad.get(part))
cad.call("view", yaw=35, pitch=25, target=[0, 0, 33], distance=190)