"""Detailed articulated toy refractor telescope for the v4 asset benchmark."""
import math
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Materials: a familiar blue-and-ivory educational telescope with real-looking trim.
blue = v4.painted("deep enamel blue", (0.035, 0.20, 0.48), roughness=0.24, coat=0.7)
ivory = v4.plastic("warm ivory moulding", (0.88, 0.79, 0.59), roughness=0.34)
black = v4.rubber("black grip rubber", (0.018, 0.022, 0.028))
steel = v4.metal("satin aluminium", (0.68, 0.72, 0.75), roughness=0.26, brushed=True)
darksteel = v4.metal("dark hinge steel", (0.22, 0.25, 0.28), roughness=0.32, brushed=False)
brass = v4.metal("warm brass trim", (0.78, 0.53, 0.19), roughness=0.3, brushed=False)
glass = v4.glass("objective blue glass", (0.45, 0.74, 0.92), roughness=0.08)
glass2 = v4.mat("inner lens coating", (0.035, 0.10, 0.17), metallic=0.4, roughness=0.15)
white = v4.plastic("lettering white", (0.96, 0.91, 0.76), roughness=0.3)

# All parts are modelled at their zero-pose world positions. Main optical axis is +X.
Z = 0.50
root = v4.body("telescope_body")
ring = v4.body("focus_ring")
draw1 = v4.body("draw_tube_1")
draw2 = v4.body("draw_tube_2")


def hollow_barrel(name, x0, x1, outer, inner, material, body):
    """Closed-wall turned tube, profile along local Z then oriented along X."""
    profile = [(outer, x0), (outer, x1), (inner, x1), (inner, x0), (outer, x0)]
    return v4.lathe(name, profile, loc=(0, 0, Z), rot=(0, math.pi / 2, 0),
                    material=material, body=body)


def x_cylinder(name, radius, x0, x1, material, body, bevel=0.0007):
    return v4.cylinder(name, radius, x1 - x0, loc=((x0 + x1) / 2, 0, Z),
                       rot=(0, math.pi / 2, 0), material=material, body=body, bevel=bevel)


# Fixed main tube and rear eye assembly.
hollow_barrel("main_enamel_tube", -0.115, 0.125, 0.040, 0.033, blue, root)
x_cylinder("rear_end_bezel", 0.0415, -0.132, -0.114, ivory, root)
hollow_barrel("eyecup_soft_rim", -0.180, -0.135, 0.044, 0.033, black, root)
x_cylinder("eyecup_flange", 0.048, -0.142, -0.133, ivory, root)
# Soft eye guard lip and inset dark eyepiece aperture.
v4.torus("eyecup_rolled_lip", 0.039, 0.004, loc=(-0.178, 0, Z),
         rot=(0, math.pi / 2, 0), material=black, body=root)
x_cylinder("eyepiece_glass", 0.020, -0.137, -0.133, glass2, root, bevel=0.0002)

# Two raised fixed trim collars on the main barrel; each rests against the barrel skin.
for nm, x in (("rear_trim", -0.108), ("front_trim", 0.108)):
    v4.torus(nm + "__annulus", 0.0395, 0.0018, loc=(x + 0.003, 0, Z),
             rot=(0, math.pi / 2, 0), material=brass, body=root)
# Moulded tripod saddle, collar and hub are all fixed to the optical body.
v4.box("saddle_bridge", (0.085, 0.070, 0.022), (0.070, 0, 0.452),
       bevel=0.009, material=ivory, body=root)
v4.box("saddle_blue_inlay", (0.055, 0.074, 0.008), (0.070, 0, 0.437),
       bevel=0.003, material=blue, body=root)
v4.cylinder("tripod_hub", 0.037, 0.055, (0.015, 0, 0.405),
            bevel=0.005, material=ivory, body=root)
v4.cylinder("hub_lower_cap", 0.028, 0.012, (0.015, 0, 0.372),
            bevel=0.003, material=blue, body=root)
# A small central clamping knob, oriented downward and attached to the hub cap.
v4.cylinder("hub_lock_knob", 0.008, 0.018, (0.015, 0, 0.357),
            bevel=0.002, material=black, body=root)

# Focus ring: a separate hollow sleeve with twenty-four raised grip flutes.
hollow_barrel("focus_ring_sleeve", -0.042, 0.018, 0.046, 0.0411, black, ring)
hollow_barrel("focus_ring_front_lip", 0.016, 0.022, 0.0465, 0.0412, brass, ring)
hollow_barrel("focus_ring_rear_lip", -0.046, -0.040, 0.0465, 0.0412, brass, ring)
for i in range(24):
    a = 2 * math.pi * i / 24
    y, z = 0.0438 * math.cos(a), Z + 0.0438 * math.sin(a)
    # Short axial ribs on the rubber sleeve.
    v4.rod("focus_grip_flute_%02d" % i, (-0.034, y, z), (0.010, y, z), 0.00135,
           material=black, body=ring, bevel=0.0003)
# A readable index stripe on the top side of the rotating ring.
v4.box("focus_index_mark", (0.003, 0.0018, 0.007), (-0.012, -0.046, Z),
       bevel=0.0005, material=white, body=ring)

# The first and second draw tubes are hollow, nested, and have sliding overlap.
hollow_barrel("draw_tube_1_shell", 0.077, 0.247, 0.0305, 0.0258, steel, draw1)
x_cylinder("draw1_rear_stop_collar", 0.033, 0.075, 0.083, blue, draw1)
hollow_barrel("draw1_witness_band", 0.231, 0.238, 0.0314, 0.0306, brass, draw1)
hollow_barrel("draw_tube_2_shell", 0.204, 0.330, 0.0232, 0.0172, steel, draw2)
x_cylinder("draw2_rear_stop_collar", 0.0255, 0.201, 0.208, blue, draw2)
hollow_barrel("draw2_witness_band", 0.314, 0.320, 0.0242, 0.0234, brass, draw2)

# Objective cell and glass move as one with the innermost draw tube.
x_cylinder("objective_cell_blue", 0.035, 0.324, 0.347, blue, draw2)
x_cylinder("objective_cell_brass_ring", 0.036, 0.344, 0.351, brass, draw2)
hollow_barrel("objective_retaining_lip", 0.350, 0.358, 0.032, 0.0265, ivory, draw2)
x_cylinder("objective_lens", 0.026, 0.353, 0.357, glass2, draw2, bevel=0.0002)
x_cylinder("objective_inner_coating", 0.016, 0.3571, 0.358, glass, draw2, bevel=0.0001)
# Dark inner baffle visible behind the front element.
x_cylinder("objective_baffle", 0.020, 0.318, 0.321, black, draw2, bevel=0.0002)

# Product lettering and restrained controls on the visible near side of the body.
v4.text("brand_mark", "STAR SCOUT", 0.010, loc=(-0.045, -0.0403, Z + 0.003),
        rot=(math.pi / 2, 0, 0), extrude_depth=0.0005, material=white, body=root)
v4.text("model_mark", "20 x 30  •  REFRACTOR", 0.0048,
        loc=(0.045, -0.0403, Z - 0.009), rot=(math.pi / 2, 0, 0),
        extrude_depth=0.0003, material=white, body=root)
# Three small, flush screw heads on the saddle.
for i, (x, y) in enumerate(((-0.010, -0.028), (0.040, -0.028), (0.015, 0.028))):
    v4.cylinder("saddle_screw_%d" % i, 0.0032, 0.0015, (x, y, 0.432),
                bevel=0.0003, material=darksteel, body=root)

# Folding tripod legs. Hinge pins lie along each tangent; positive rotation
# swings the splayed legs inward beneath the hub.
leg_specs = []
for i, deg in enumerate((30, 150, 270), start=1):
    a = math.radians(deg)
    u = (math.cos(a), math.sin(a))
    tangent = (-math.sin(a), math.cos(a))
    # Three distinct hinge stations around the underside of the hub keep the
    # legs parallel and separated when stowed.
    pivot = (0.015 + u[0] * 0.022, u[1] * 0.022, 0.366)
    # Leg tip is 0.13 m radially from pivot and 0.37 m below it.
    tip = (pivot[0] + u[0] * 0.13, pivot[1] + u[1] * 0.13, 0.022)
    knee = tuple(pivot[k] * 0.38 + tip[k] * 0.62 for k in range(3))
    b = v4.body("tripod_leg_%d" % i)
    # Tapered-looking upper shell and a narrower metallic lower ferrule.
    v4.rod("leg_%d_upper" % i, pivot, knee, 0.0105, material=blue, body=b, bevel=0.001)
    v4.rod("leg_%d_lower" % i, knee, (tip[0], tip[1], tip[2] + 0.025),
           0.0070, material=ivory, body=b, bevel=0.0008)
    v4.rod("leg_%d_lower_collar" % i,
           (knee[0] + (tip[0] - knee[0]) * 0.08,
            knee[1] + (tip[1] - knee[1]) * 0.08,
            knee[2] + (tip[2] + 0.025 - knee[2]) * 0.08),
           (knee[0] + (tip[0] - knee[0]) * 0.20,
            knee[1] + (tip[1] - knee[1]) * 0.20,
            knee[2] + (tip[2] + 0.025 - knee[2]) * 0.20),
           0.0083, material=steel, body=b, bevel=0.0004)
    # Soft foot at the terminal, with a flat sole on the ground plane.
    v4.cylinder("leg_%d_rubber_foot" % i, 0.014, 0.022,
                (tip[0], tip[1], tip[2] + 0.011), bevel=0.003,
                material=black, body=b)
    # Transverse pivot pin sits on the real hinge axis beneath the hub.
    p0 = (pivot[0] - tangent[0] * 0.025, pivot[1] - tangent[1] * 0.025, pivot[2])
    p1 = (pivot[0] + tangent[0] * 0.025, pivot[1] + tangent[1] * 0.025, pivot[2])
    v4.rod("leg_%d_hinge_pin" % i, p0, p1, 0.0045, material=brass, body=b, bevel=0.0004)
    axis = (tangent[0], tangent[1], 0)
    v4.joint("tripod_fold_%d" % i, "revolute", root, b, origin=pivot,
             axis=axis, limits=(0.0, math.radians(20)))

# Kinematic tree and motions: root -> draw1 -> draw2 is the nested self-chain.
v4.joint("focus_rotation", "continuous", root, ring,
         origin=(-0.012, 0, Z), axis=(1, 0, 0))
v4.joint("draw_tube_slide_1", "prismatic", root, draw1,
         origin=(0.14, 0, Z), axis=(1, 0, 0), limits=(0.0, 0.065))
v4.joint("draw_tube_slide_2", "prismatic", draw1, draw2,
         origin=(0.25, 0, Z), axis=(1, 0, 0), limits=(0.0, 0.065))

v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
