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

v4.reset()
# Materials
rubber = v4.rubber("sidewall_and_tread_rubber", (0.055, 0.058, 0.056))
tread = v4.rubber("tread_compound", (0.035, 0.038, 0.037))
steel = v4.metal("turned_steel", color=(0.70, 0.72, 0.73), roughness=0.27, brushed=True)
bright = v4.metal("bright_zinc", color=(0.84, 0.85, 0.82), roughness=0.22, brushed=False)
blacksteel = v4.painted("graphite_enamel", (0.12, 0.14, 0.15), roughness=0.28, coat=0.45)
inner = v4.metal("dark_inner_barrel", color=(0.20, 0.22, 0.23), roughness=0.4, brushed=True)
white = v4.mat("raised_sidewall_ink", (0.72, 0.72, 0.68), roughness=0.72)
recess = v4.painted("vent_recess", (0.055, 0.065, 0.07), roughness=0.52)

# Passenger wheel: 17 inch pressed steel wheel, 225/55 tyre. Axis X; hub centre at z=.35.
zc = 0.35
carrier = v4.body("carrier")
axle = v4.body("axle")
wheel = v4.body("wheel")

# Fixed overhead carrier and two bearing supports, kept outside the wheel's axial envelope.
# Bridge is above the tyre, and hanger arms line up with the bearing housings.
v4.box("carrier_bridge", (0.46, 0.075, 0.045), (0, 0, 0.780), bevel=0.006, material=steel, body=carrier)
for s in (0, 1):
    x = (-0.185 if s == 0 else -0.255)
    if s == 0:
        v4.box("bearing_hanger_pair", (0.11, 0.055, 0.380), (-0.22, 0, 0.5675), bevel=0.006, material=steel, body=carrier)
    # Annular pillow bearing housing around the axle journal; profile revolved about local Z then turned onto X.
    v4.lathe(f"bearing_outer_race_{s}", [(0.027, -0.020), (0.044, -0.020), (0.051, -0.014),
                (0.051, 0.014), (0.044, 0.020), (0.027, 0.020)],
             loc=(x, 0, zc), rot=(0, math.pi/2, 0), material=inner, body=carrier)
    v4.torus(f"bearing_seal_{s}", 0.039, 0.003, loc=(x - 0.020, 0, zc),
             rot=(0, math.pi/2, 0), material=bright, body=carrier)
    # Raised pillow-block face flanges, with four cap screws at each exposed face.
    for side in (-1, 1):
        v4.lathe(f"bearing_pillow_flange_{s}_{side}", [(0.027, -0.004), (0.060, -0.004),
                 (0.060, 0.004), (0.027, 0.004)], loc=(x+side*0.0225, 0, zc),
                 rot=(0, math.pi/2, 0), material=steel, body=carrier)
        for k in range(4):
            a = math.pi/4 + k*math.pi/2
            y, z = 0.050*math.cos(a), zc+0.050*math.sin(a)
            v4.cylinder(f"pillow_flange_bolt_{s}_{side}_{k}", 0.0042, 0.006,
                        (x+side*0.0295, y, z), rot=(0, math.pi/2, 0), segments=6,
                        bevel=0.0007, material=bright, body=carrier)
    # Small cap screws on the bearing housing's outer face.
    for k in range(4):
        a = math.pi/4 + k*math.pi/2
        y, z = 0.043*math.cos(a), zc + 0.043*math.sin(a)
        v4.cylinder(f"bearing_bolt_{s}_{k}", 0.0045, 0.003, (x-0.022, y, z),
                    rot=(0, math.pi/2, 0), segments=16, material=bright, body=carrier)

# Welded triangular corner gusset and a drilled-looking stub-axle mounting plate.
v4.extrude("carrier_corner_gusset", [(-0.22, 0), (-0.22, 0.075), (-0.135, 0.075)], 0.040,
           loc=(0, 0.020, 0.705), rot=(math.pi/2, 0, 0), bevel=0.004, material=steel, body=carrier)
v4.box("stub_axle_mount_plate", (0.235, 0.14, 0.012), (0, 0, 0.8085), bevel=0.008, material=steel, body=carrier)
for ix in (-1, 1):
    for iy in (-1, 1):
        v4.cylinder(f"mount_plate_hex_bolt_{ix}_{iy}", 0.008, 0.006,
                    (ix*0.082, iy*0.046, 0.8175), segments=6, bevel=0.001, material=bright, body=carrier)

# Axle shaft spans both fixed bearings and terminates in the wheel hub's running bore.
v4.cylinder("through_axle_shaft", 0.025, 0.43, (-0.075, 0, zc), rot=(0, math.pi/2, 0),
            segments=64, bevel=0.0015, material=steel, body=axle)
for i, x in enumerate((-0.185, -0.255)):
    v4.lathe(f"rotating_bearing_inner_race_{i}", [(0.025, -0.010), (0.0275, -0.010),
             (0.0275, 0.010), (0.025, 0.010)], loc=(x, 0, zc), rot=(0, math.pi/2, 0),
             material=bright, body=axle)
v4.lathe("axle_end_retaining_collar", [(0.025, -0.006), (0.034, -0.006),
         (0.034, 0.006), (0.025, 0.006)], loc=(-0.284, 0, zc), rot=(0, math.pi/2, 0),
         material=steel, body=axle)

# Tire is a rounded pneumatic carcass over the one-piece steel rim. A revolved sidewall
# profile makes a broad tread crown and gently rounded shoulders rather than a wire-spoke wheel.
tire_profile = [
    (0.250, -0.112), (0.266, -0.108), (0.285, -0.096), (0.307, -0.078),
    (0.322, -0.061), (0.318, -0.052), (0.328, -0.045), (0.336, -0.027),
    (0.337, -0.012), (0.331, -0.007), (0.340, 0.000), (0.331, 0.007),
    (0.337, 0.012), (0.336, 0.027), (0.328, 0.045), (0.318, 0.052),
    (0.322, 0.061), (0.307, 0.078), (0.285, 0.096), (0.266, 0.108),
    (0.250, 0.112), (0.247, 0.097), (0.247, -0.097), (0.250, -0.112)
]
# Densify the cross-section and vary the tread crown radius by angle to mould diagonal lateral sipes.
profile = []
for i in range(len(tire_profile)-1):
    r0, x0 = tire_profile[i]
    r1, x1 = tire_profile[i+1]
    for j in range(4):
        t = j/4.0
        profile.append((r0*(1-t)+r1*t, x0*(1-t)+x1*t))
profile.append(tire_profile[-1])
segments = 768
verts, faces = [], []
period = 2*math.pi/84.0
for n in range(segments):
    theta = 2*math.pi*n/segments
    for r, x in profile:
        rr = r
        if -0.078 <= x <= 0.078 and r >= 0.318:
            phase = theta - 0.33*(x/0.156)
            d = abs((phase + period/2) % period - period/2)
            rr -= 0.0026 * max(0.0, 1.0-d/0.010)
        verts.append((x, rr*math.sin(theta), zc+rr*math.cos(theta)))
count = len(profile)
for n in range(segments):
    nn = (n+1) % segments
    for j in range(count-1):
        a, b = n*count+j, nn*count+j
        faces.append((a, b, b+1, a+1))
mesh = bpy.data.meshes.new("moulded_tyre_mesh")
mesh.from_pydata(verts, [], faces)
mesh.materials.append(rubber)
mesh.update()
tire = bpy.data.objects.new("pneumatic_tyre_carcass", mesh)
bpy.context.scene.collection.objects.link(tire)
for poly in mesh.polygons:
    poly.use_smooth = True
v4.part(tire, wheel)
# A fine moulded bead witness line on each sidewall, seated into the tyre at the rim edge.
for side in (-1, 1):
    v4.torus(f"tyre_bead_witness_{side}", 0.266, 0.0013, loc=(side*0.108, 0, zc),
             rot=(0, math.pi/2, 0), segments=128, ring_segments=8, material=tread, body=wheel)
# Raised tyre size lettering, pressed against the front sidewall and following its tangent.
v4.text("sidewall_tyre_size", "225/55 R17", 0.014, loc=(0.096, 0, zc+0.285),
        rot=(math.pi/2, 0, math.pi/2), extrude_depth=0.0007, material=white, body=wheel)
# Rim barrel, folded bead flanges and disc pressed from one steel blank; visible as one-piece wheel.
rim_profile = [
    (0.245, -0.103), (0.257, -0.103), (0.263, -0.095), (0.263, -0.084),
    (0.254, -0.075), (0.246, -0.063), (0.246, 0.063), (0.254, 0.075),
    (0.263, 0.084), (0.263, 0.095), (0.257, 0.103), (0.245, 0.103),
    (0.238, 0.094), (0.238, -0.094), (0.245, -0.103)
]
v4.lathe("one_piece_rim_barrel_and_flange", rim_profile, loc=(0, 0, zc), rot=(0, math.pi/2, 0),
         segments=96, material=blacksteel, body=wheel)
# Pressed centre disc with shallow dish; lathe profile gives the continuous stamped dish and hub opening wall.
disc_profile = [(0.045, 0.094), (0.078, 0.094), (0.115, 0.082), (0.155, 0.061),
                (0.194, 0.033), (0.224, 0.002), (0.239, -0.034), (0.239, -0.066),
                (0.225, -0.070), (0.205, -0.036), (0.174, -0.005), (0.140, 0.022),
                (0.105, 0.043), (0.075, 0.054), (0.045, 0.054)]
v4.lathe("stamped_disc_face", disc_profile, loc=(0, 0, zc), rot=(0, math.pi/2, 0),
         segments=96, material=blacksteel, body=wheel)
# Six true hand holes through the dish, with a narrow rolled edge highlight at each opening.
for k in range(6):
    a = 2*math.pi*k/6 + math.pi/6
    r = 0.163
    y, z = r*math.cos(a), zc+r*math.sin(a)
    cutter = v4.cylinder(f"hand_hole_cutter_{k}", 0.020, 0.14, (0.025, y, z),
                         rot=(0, math.pi/2, 0), segments=32, bevel=0, material=None)
    v4.boolean(bpy.data.objects["stamped_disc_face"], cutter)
# Rolled bead-seat witness rings on both edges of the one-piece rim barrel.
for side in (-1, 1):
    v4.torus(f"rim_bead_seat_line_{side}", 0.255, 0.0015, loc=(side*0.092, 0, zc),
             rot=(0, math.pi/2, 0), segments=96, ring_segments=8, material=bright, body=wheel)
# Central hub flange and spigot; mounted to pressed disc, all rotating with wheel.
v4.lathe("hub_flange", [(0.026, -0.010), (0.090, -0.010), (0.090, 0.010), (0.026, 0.010)],
         loc=(0.091, 0, zc), rot=(0, math.pi/2, 0), segments=64, material=steel, body=wheel)
v4.lathe("hub_spigot", [(0.026, -0.023), (0.046, -0.023), (0.046, 0.023), (0.026, 0.023)],
         loc=(0.117, 0, zc), rot=(0, math.pi/2, 0), segments=64, material=steel, body=wheel)
# Six lug studs and chamfered nuts on a standard 6 x 139.7 mm bolt circle.
bolt_r = 0.06985
for k in range(6):
    a = 2*math.pi*k/6
    y, z = bolt_r*math.cos(a), zc+bolt_r*math.sin(a)
    v4.cylinder(f"lug_stud_{k}", 0.007, 0.035, (0.105, y, z), rot=(0, math.pi/2, 0),
                segments=24, bevel=0.0007, material=steel, body=wheel)
    v4.cylinder(f"lug_washer_{k}", 0.014, 0.004, (0.1175, y, z), rot=(0, math.pi/2, 0),
                segments=32, bevel=0.0007, material=steel, body=wheel)
    v4.cylinder(f"lug_nut_{k}", 0.0125, 0.014, (0.129, y, z), rot=(0, math.pi/2, 0),
                segments=6, bevel=0.0018, material=bright, body=wheel)
# Domed hub cap and retaining lip.
v4.cylinder("hub_cap_retaining_lip", 0.043, 0.006, (0.1415, 0, zc), rot=(0, math.pi/2, 0),
            segments=64, bevel=0.001, material=bright, body=wheel)
v4.cylinder("domed_hub_cap", 0.039, 0.016, (0.154, 0, zc), rot=(0, math.pi/2, 0), segments=64, bevel=0.004, material=steel, body=wheel)
# Angled tubeless valve stem through the outer disc, with a rubber seating grommet and metal cap.
a = math.radians(-140)
y, z = 0.214*math.cos(a), zc+0.214*math.sin(a)
v4.torus("valve_grommet", 0.008, 0.002, loc=(0.014, y, z), rot=(0, math.pi/2, 0),
         segments=24, ring_segments=8, material=rubber, body=wheel)
end_y, end_z = 0.235*math.cos(a), zc+0.235*math.sin(a)
v4.rod("valve_stem", (0.006, y, z), (0.061, end_y, end_z), 0.0055, material=bright, body=wheel)
v4.rod("valve_hex_cap", (0.057, end_y, end_z), (0.079, end_y, end_z), 0.0065,
       material=bright, body=wheel)
# Pivots: outer bearing rotation for axle, then wheel hub rotation on the axle.
v4.joint("axle_bearings", "continuous", carrier, axle, origin=(0, 0, zc), axis=(1, 0, 0))
v4.joint("wheel_on_axle", "continuous", axle, wheel, origin=(0, 0, zc), axis=(1, 0, 0))

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