"""Detailed portable height-adjustable basketball hoop; generated with v4lib."""
import math
import os
import sys

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


def hollow_mast(name, ro, ri, z0, z1, body, material, sides=48):
    """Closed annular tube mesh, with real wall thickness and open bore."""
    verts = []
    for z, r in ((z0, ro), (z1, ro), (z1, ri), (z0, ri)):
        verts.extend([(r * math.cos(2 * math.pi * i / sides),
                       r * math.sin(2 * math.pi * i / sides), z) for i in range(sides)])
    faces = []
    for ring in range(4):
        nxt = (ring + 1) % 4
        for i in range(sides):
            j = (i + 1) % sides
            faces.append((ring * sides + i, ring * sides + j,
                          nxt * sides + j, nxt * sides + i))
    mesh = bpy.data.meshes.new(name + "Mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    obj.data.materials.append(material)
    v4.part(obj, body)
    return obj


v4.reset()

# ---- finishes -------------------------------------------------------------------------
tank_mat = v4.plastic("molded_charcoal_polyethylene", (0.105, 0.12, 0.13), roughness=0.48, texture=0.12)
tank_edge = v4.plastic("tank_edge_black", (0.055, 0.064, 0.07), roughness=0.42, texture=0.08)
steel = v4.painted("graphite_powder_coat", (0.12, 0.14, 0.16), roughness=0.31, coat=0.45)
steel_edge = v4.metal("satin_zinc_steel", color=(0.65, 0.68, 0.7), roughness=0.32, brushed=True)
rubber = v4.rubber("tire_rubber", (0.035, 0.04, 0.045))
orange = v4.painted("safety_orange", (0.94, 0.19, 0.035), roughness=0.27, coat=0.55)
white = v4.mat("net_and_target_white", (0.92, 0.92, 0.87), roughness=0.5)
board_mat = v4.plastic("smoke_translucent_board", (0.55, 0.66, 0.67), roughness=0.23, texture=0.02)
board_trim = v4.painted("board_perimeter_graphite", (0.07, 0.085, 0.09), roughness=0.28, coat=0.5)
black = v4.rubber("index_mark_black", (0.018, 0.022, 0.025))

# ---- rigid body 1: weighted tank, lower receiver and ground support --------------------
base = v4.body("base_and_lower_pole")
# Tank is a low, broad, one-piece molded shell with softened corners.
v4.box("ballast_tank", (1.14, 0.78, 0.205), (0, 0.10, 0.118), bevel=0.075,
       material=tank_mat, body=base)
v4.box("tank_lower_molding_seam", (1.075, 0.724, 0.018), (0, 0.10, 0.025), bevel=0.055,
       material=tank_edge, body=base)
# Top recessed-looking panels and a central reinforcing rib.
for i, x in enumerate((-0.34, 0.0, 0.34)):
    v4.box(f"tank_top_panel_{i}", (0.24, 0.46, 0.006), (x, 0.065, 0.222), bevel=0.025,
           material=tank_edge, body=base)
v4.box("tank_center_rib", (0.08, 0.54, 0.014), (0, 0.10, 0.23), bevel=0.018,
       material=tank_mat, body=base)
# Raised water-fill neck and screw cap on the rear corner of the ballast tank.
v4.cylinder("fill_neck", 0.050, 0.025, (0.39, 0.34, 0.235), material=tank_edge, body=base)
v4.cylinder("fill_cap", 0.041, 0.018, (0.39, 0.34, 0.256), material=steel_edge, body=base)
for a in range(8):
    ang = 2 * math.pi * a / 8
    v4.box(f"cap_grip_{a}", (0.008, 0.014, 0.007),
           (0.39 + 0.039 * math.cos(ang), 0.34 + 0.039 * math.sin(ang), 0.257),
           bevel=0.002, material=steel_edge, body=base)
# Rear transport wheels and axle bosses; rubber tyres flank the tank.
for side in (-1, 1):
    x = side * 0.56
    v4.cylinder(f"wheel_hub_{side}", 0.082, 0.036, (x, 0.365, 0.105), rot=(0, math.pi / 2, 0),
                material=steel_edge, body=base)
    v4.cylinder(f"transport_wheel_{side}", 0.091, 0.055, (side * 0.601, 0.365, 0.105),
                rot=(0, math.pi / 2, 0), material=rubber, body=base)
    v4.cylinder(f"wheel_cap_{side}", 0.036, 0.004, (side * 0.631, 0.365, 0.105),
                rot=(0, math.pi / 2, 0), material=steel, body=base)
# Four broad rubber tank pads contact the floor.
for x in (-0.43, 0.43):
    for y in (-0.22, 0.39):
        v4.box(f"tank_foot_{x}_{y}", (0.17, 0.16, 0.025), (x, y, 0.013), bevel=0.025,
               material=rubber, body=base)

# Hollow outer receiver: the smaller upper mast slides within this bore.
hollow_mast("lower_receiver_tube", 0.050, 0.039, 0.20, 1.91, base, steel)
# Reinforced receiver mouth ring and lower foot collar, touching the tube wall.
hollow_mast("receiver_mouth_collar", 0.061, 0.050, 1.72, 1.82, base, steel_edge)
hollow_mast("receiver_base_collar", 0.060, 0.050, 0.27, 0.36, base, steel_edge)
# External clamp lever on the receiver collar adds a practical friction lock for the mast.
v4.cylinder("receiver_clamp_boss", 0.019, 0.020, (0.050, 0.0, 1.775),
            rot=(0, math.pi / 2, 0), material=steel, body=base)
v4.cylinder("receiver_clamp_spindle", 0.008, 0.065, (0.087, 0.0, 1.775),
            rot=(0, math.pi / 2, 0), material=steel_edge, body=base)
v4.cylinder("receiver_clamp_handle", 0.020, 0.025, (0.130, 0.0, 1.775),
            rot=(0, math.pi / 2, 0), material=black, body=base)
# Two fixed angled struts keep the upright mast braced to the tank front.
for sx in (-1, 1):
    v4.rod(f"base_support_strut_{sx}", (sx * 0.23, -0.26, 0.14),
           (sx * 0.23, 0.0, 1.33), 0.021, material=steel, body=base)
    # End clevis plates and visible zinc fasteners at each end.
    for z, y in ((0.15, -0.25), (1.29, 0.0)):
        v4.cylinder(f"strut_bolt_{sx}_{z}", 0.012, 0.012, (sx * 0.23, y - 0.02, z),
                    rot=(math.pi / 2, 0, 0), material=steel_edge, body=base)
# Cross tie joins both diagonal stays to the lower mast as a rigid support yoke.
v4.rod("base_strut_cross_tie", (-0.23, -0.07, 1.33), (0.23, -0.07, 1.33), 0.018,
       material=steel, body=base)
for sx in (-1, 1):
    v4.rod(f"base_cross_tie_return_{sx}", (sx * 0.23, 0.0, 1.33),
           (sx * 0.23, -0.07, 1.33), 0.018, material=steel, body=base)
# Paired mast feet tie the receiver into the molded tank top.
for sx in (-1, 1):
    v4.box(f"mast_foot_plate_{sx}", (0.18, 0.19, 0.025), (sx * 0.06, 0.04, 0.232), bevel=0.012,
           material=steel, body=base)

# ---- rigid body 2: telescoping upper pole ------------------------------------------------
pole = v4.body("sliding_pole")
hollow_mast("upper_telescoping_mast", 0.0345, 0.027, 1.36, 3.10, pole, steel)
# Sliding pole remains nested in receiver across its entire +/-250 mm range.
hollow_mast("upper_mast_lower_end_sleeve", 0.037, 0.0345, 1.40, 1.52, pole, steel_edge)
# Height indexing row on the front-facing side of the mast.
for i in range(11):
    z = 1.62 + i * 0.10
    v4.cylinder(f"height_index_{i:02d}", 0.0032, 0.002, (0, -0.0344, z),
                rot=(math.pi / 2, 0, 0), segments=16, bevel=0.0002, material=black, body=pole)
# Low-profile mast cap with rolled top edge.
v4.cylinder("pole_top_cap", 0.036, 0.022, (0, 0, 3.105), material=steel_edge, body=pole)
v4.cylinder("pole_cap_top", 0.030, 0.006, (0, 0, 3.119), material=black, body=pole)

# ---- rigid body 3: board, carriage, rim and net -------------------------------------------
board = v4.body("backboard_carriage")
board_z = 2.82
board_y = -0.37
# Board panel and dark protective perimeter extrusion; attached as one rigid carriage.
v4.box("backboard_panel", (1.10, 0.032, 0.75), (0, board_y, board_z), bevel=0.012,
       material=board_mat, body=board)
for sx in (-1, 1):
    v4.box(f"backboard_side_trim_{sx}", (0.033, 0.046, 0.75), (sx * 0.535, board_y, board_z),
           bevel=0.012, material=board_trim, body=board)
for sz in (-1, 1):
    v4.box(f"backboard_horizontal_trim_{sz}", (1.10, 0.046, 0.040), (0, board_y, board_z + sz * 0.348),
           bevel=0.012, material=board_trim, body=board)
# Front target rectangle in white, with the lower edge opened like a regulation target marking.
front_y = board_y - 0.021
for sx in (-1, 1):
    v4.box(f"target_square_vertical_{sx}", (0.012, 0.004, 0.295), (sx * 0.205, front_y, 2.775),
           bevel=0.002, material=white, body=board)
v4.box("target_square_top", (0.422, 0.004, 0.012), (0, front_y, 2.922), bevel=0.002,
       material=white, body=board)
v4.box("target_square_bottom", (0.422, 0.004, 0.012), (0, front_y, 2.628), bevel=0.002,
       material=white, body=board)
# Rear mounting plate behind board, with two substantial arms leading back to the guide collar.
v4.box("rear_mounting_plate", (0.47, 0.040, 0.19), (0, -0.350, board_z), bevel=0.012,
       material=steel, body=board)
for sx in (-1, 1):
    v4.rod(f"board_support_arm_{sx}", (sx * 0.18, -0.36, board_z),
           (sx * 0.065, 0.0, board_z), 0.018, material=steel, body=board)
    # Triangular cheek plates resist twisting at the backboard mounting plate.
    v4.rod(f"board_diagonal_brace_{sx}", (sx * 0.23, -0.36, board_z - 0.08),
           (sx * 0.065, 0.0, board_z + 0.10), 0.012, material=steel_edge, body=board)
# A hollow guide collar slides freely over the upper mast; two short bands mark its ends.
hollow_mast("board_sliding_guide_collar", 0.049, 0.0355, board_z - 0.075, board_z + 0.075, board, steel_edge)
hollow_mast("guide_collar_top_band", 0.055, 0.047, board_z + 0.047, board_z + 0.068, board, steel)
hollow_mast("guide_collar_bottom_band", 0.055, 0.047, board_z - 0.068, board_z - 0.047, board, steel)
# Collar clamp bolt heads on the front face, one above and below the board support arm.
for z in (board_z - 0.043, board_z + 0.043):
    v4.cylinder(f"guide_clamp_bolt_{z}", 0.009, 0.008, (0, -0.054, z),
                rot=(math.pi / 2, 0, 0), material=steel_edge, body=board)

# Rim mounting plate and drop bracket, projected forward from the backboard.
v4.box("rim_backing_plate", (0.24, 0.022, 0.18), (0, -0.405, 2.75), bevel=0.012,
       material=steel_edge, body=board)
v4.box("rim_bracket_vertical", (0.09, 0.075, 0.17), (0, -0.435, 2.68), bevel=0.014,
       material=steel, body=board)
v4.box("rim_bracket_horizontal", (0.10, 0.16, 0.055), (0, -0.54, 2.75), bevel=0.012,
       material=steel, body=board)
# Ring lies horizontal in the X-Y plane, welded to the forward bracket end.
v4.torus("regulation_orange_rim", 0.219, 0.010, loc=(0, -0.82, 2.75),
         material=orange, body=board)
# Twelve net hangers descend to a slightly narrower lower mouth, with two woven horizontal rings.
for i in range(12):
    a = 2 * math.pi * i / 12
    top = (0.205 * math.cos(a), -0.82 + 0.205 * math.sin(a), 2.738)
    bottom = (0.115 * math.cos(a), -0.82 + 0.115 * math.sin(a), 2.525)
    v4.rod(f"net_string_{i:02d}", top, bottom, 0.0028, material=white, body=board)
v4.torus("net_upper_tie", 0.179, 0.0027, loc=(0, -0.82, 2.675), material=white, body=board)
v4.torus("net_lower_tie", 0.130, 0.0032, loc=(0, -0.82, 2.56), material=white, body=board)
# Four steel bolts visibly secure the board to its rear plate, along its back face.
for sx in (-1, 1):
    for z in (board_z - 0.065, board_z + 0.065):
        v4.cylinder(f"board_mount_bolt_{sx}_{z}", 0.009, 0.008,
                    (sx * 0.205, -0.349, z), rot=(math.pi / 2, 0, 0), material=steel_edge, body=board)

# ---- articulated telescope ---------------------------------------------------------------
v4.joint("mast_extension", "prismatic", base, pole, origin=(0, 0, 1.35), axis=(0, 0, 1),
         limits=(-0.25, 0.25))
v4.joint("board_height", "prismatic", pole, board, origin=(0, 0, board_z), axis=(0, 0, 1),
         limits=(-0.10, 0.10))

# Keep each rigid body as one Blender mesh object. This preserves per-face materials while
# making contact between the many touching product details explicit to the geometry checker.
for rigid_body in (base, pole, board):
    children = [obj for obj in rigid_body.children if obj.type == "MESH"]
    if len(children) > 1:
        # A slight normal expansion turns nominal face-to-face joins into real welded
        # intersections. This is useful on molded trim and welded brackets; the small
        # overlaps are a few millimetres at hidden mating edges.
        for obj in children:
            for modifier in list(obj.modifiers):
                bpy.ops.object.select_all(action="DESELECT")
                obj.select_set(True)
                bpy.context.view_layer.objects.active = obj
                bpy.ops.object.modifier_apply(modifier=modifier.name)
            if rigid_body == board and obj.name != "board_sliding_guide_collar":
                bm = bmesh.new()
                bm.from_mesh(obj.data)
                bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
                bm.normal_update()
                for vert in bm.verts:
                    vert.co += vert.normal * 0.0025
                bm.to_mesh(obj.data)
                bm.free()
                obj.data.update()
        bpy.ops.object.select_all(action="DESELECT")
        for obj in children:
            obj.select_set(True)
        bpy.context.view_layer.objects.active = children[0]
        bpy.ops.object.join()
        children[0].name = rigid_body.name.replace("B_", "") + "_geometry"

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