# Noodles Rope - Vectorworks path plug-in object (Python). Noodles by KG3, https://noodles.tech/design
# Draw any polyline, arc or NURBS curve, then Modify > Create Objects from Shapes > Noodles Rope.
# The rope is extruded along the path at the real diameter and the Object Info palette reports
# length, pixels, channels, runs (10 m max each), universes and watts. Fields are worksheet-reportable.
# Plug-in Manager setup: Path Object, record "Noodles Rope", parameters:
#   Model (Popup: Angel Hair / Spaghetti / Spaghetti Black / Bucatini), ShowLabel (Boolean, True),
#   LengthM, Pixels, Channels, Runs, Universes, Watts (Text, computed)
import math
import vs

PRODUCTS = {
    'Angel Hair': {'dia_mm': 20.0, 'px_per_m': 16, 'w_per_m': 21.0},
    'Spaghetti': {'dia_mm': 22.0, 'px_per_m': 16, 'w_per_m': 40.0},
    'Spaghetti Black': {'dia_mm': 22.0, 'px_per_m': 20, 'w_per_m': 23.0},
    'Bucatini': {'dia_mm': 40.0, 'px_per_m': 10, 'w_per_m': 28.8},
}
MAX_RUN_M = 10.0


def run():
    ok, name, obj, rec, wall = vs.GetCustomObjectInfo()
    if not ok:
        return
    model = vs.GetRField(obj, name, 'Model') or 'Spaghetti'
    p = PRODUCTS.get(model, PRODUCTS['Spaghetti'])
    path = vs.GetCustomObjectPath(obj)
    if path == vs.Handle() or path is None:
        return

    upi = vs.GetPrefReal(152)                 # document units per inch
    to_mm = 25.4 / upi
    length_doc = vs.HLength(path)
    if length_doc <= 0:
        length_doc = vs.HPerim(path)
    length_m = length_doc * to_mm / 1000.0
    r_doc = p['dia_mm'] / 2.0 / to_mm

    # 3D: circle profile swept along a NURBS copy of the path
    nurbs = vs.ConvertToNURBS(path, True)
    profile = vs.ArcByCenter(0, 0, r_doc, 0, 360)
    if nurbs != vs.Handle() and profile != vs.Handle():
        eap = vs.ExtrudeAlongPath(nurbs, profile)
        if eap != vs.Handle():
            vs.SetFillBack(eap, 65535, 62000, 56000)
        vs.DelObject(nurbs)
        vs.DelObject(profile)

    # numbers (pixels always round up)
    pixels = int(math.ceil(length_m * p['px_per_m'] - 1e-9))
    channels = pixels * 3
    runs = max(1, int(math.ceil(length_m / MAX_RUN_M - 1e-9)))
    watts = length_m * p['w_per_m']
    vs.SetRField(obj, name, 'LengthM', '%.2f m' % length_m)
    vs.SetRField(obj, name, 'Pixels', str(pixels))
    vs.SetRField(obj, name, 'Channels', str(channels))
    vs.SetRField(obj, name, 'Runs', str(runs))
    vs.SetRField(obj, name, 'Universes', str(runs))   # a 10 m run is at most 480 ch, so one universe per run
    vs.SetRField(obj, name, 'Watts', '%.0f W' % watts)

    # 2D label at the start of the path
    if vs.GetRField(obj, name, 'ShowLabel') in ('True', 'TRUE', '1'):
        okp, pt, _ = vs.PointAlongPoly(path, 0)
        if okp:
            vs.TextSize(8)
            vs.TextOrigin(pt[0] + r_doc * 2, pt[1] + r_doc * 2)
            vs.CreateText('Noodles %s  %.2f m  %d px  %d ch  %.0f W' % (model, length_m, pixels, channels, watts))


run()
