"""Detailed retractable USB-A flash drive. Run with Blender's background Python."""
import math
import os
import sys

import bpy
import bmesh

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

v4.reset()

# Materials: satin injection-moulded shell, coated track and familiar metal contacts.
shell = v4.plastic("charcoal_ABS", (0.075, 0.085, 0.095), roughness=0.31, texture=0.08)
lower = v4.plastic("lower_shell", (0.12, 0.13, 0.14), roughness=0.38, texture=0.04)
track_mat = v4.mat("track_graphite", (0.025, 0.030, 0.035), roughness=0.52)
rubber = v4.rubber("thumb_grip", (0.035, 0.043, 0.050), roughness=0.78)
steel = v4.metal("nickel_usb_shell", (0.72, 0.75, 0.77), roughness=0.30, brushed=True)
for node in steel.node_tree.nodes:
    if node.type == "BUMP":
        node.inputs["Strength"].default_value = 0.10
        node.inputs["Distance"].default_value = 0.00016
    elif node.type == "MAP_RANGE":
        node.inputs["To Min"].default_value = 0.27
        node.inputs["To Max"].default_value = 0.33
dark_metal = v4.metal("retention_spring_steel", (0.38, 0.41, 0.43), roughness=0.33, brushed=False)
gold = v4.metal("gold_contacts", (0.88, 0.60, 0.18), roughness=0.24, brushed=False)
green = v4.mat("FR4_green", (0.035, 0.24, 0.11), roughness=0.4)
chip = v4.mat("controller_epoxy", (0.035, 0.04, 0.045), roughness=0.3)
white = v4.mat("silkscreen", (0.82, 0.84, 0.82), roughness=0.55)
blue = v4.mat("blue_accent", (0.03, 0.31, 0.68), roughness=0.3)
led = v4.emissive("status_red", (1.0, 0.035, 0.018), strength=1.4)

# Dimensions in metres. The compact shell is 55 x 20 x 8 mm.
L, W, H = 0.055, 0.020, 0.008
zmid = H / 2
base = v4.body("housing")
move = v4.body("connector_carriage")

# Lower shell and internal ledges. Side rails form the open-sided guide channel.
v4.box("case_floor", (0.0535, 0.019, 0.0012), (0.0035, 0, 0.0006), bevel=0.0015, material=lower, body=base)
for sy in (-1, 1):
    v4.box("case_side_rail_%s" % sy, (0.0535, 0.0012, 0.0062), (0.0035, sy*0.0094, 0.0042),
           bevel=0.00055, material=shell, body=base)
# Continuous top deck encloses most of the slider mechanism. A narrow travel slot
# lets only the button's connecting stalk reach the internal carriage.
top_cover = v4.box("top_cover", (0.0515, 0.0188, 0.0011), (0.00175, 0, 0.00745), bevel=0.00145,
                   material=shell, body=base)
slot_cutter = v4.box("guide_slot_cutter", (0.0200, 0.0048, 0.0018), (0.0060, 0, 0.00745),
                     bevel=0, material=None)
v4.boolean(top_cover, slot_cutter)
# Shallow recessed pocket under the complete thumb-button travel envelope.
pocket_cutter = v4.box("thumb_pocket_cutter", (0.028, 0.0104, 0.0011),
                        (0.006, 0, 0.00795), bevel=0, material=None)
v4.boolean(top_cover, pocket_cutter)
# Fine molded lips frame the slot and protect its edges while the stalk travels.
for sy in (-1, 1):
    v4.box("guide_slot_lip_%s" % sy, (0.022, 0.00028, 0.00020),
           (0.006, sy*0.00262, 0.00750), bevel=0.000055, material=dark_metal, body=base)
# Longitudinal shoulder lands are the fixed edges of the slider slot.
for sy in (-1, 1):
    v4.box("track_shoulder_%s" % sy, (0.030, 0.0014, 0.00048), (0.0065, sy*0.0057, 0.00657),
           bevel=0.00020, material=lower, body=base)
# Front bezel: upper/lower lips and cheeks surround a real clearance opening for the plug.
v4.box("nose_top_lip", (0.0030, 0.0132, 0.00090), (0.0300, 0, 0.00735), bevel=0.00028,
       material=shell, body=base)
v4.box("nose_bottom_lip", (0.0030, 0.0132, 0.00078), (0.0300, 0, 0.00085), bevel=0.00022,
       material=lower, body=base)
for sy in (-1, 1):
    v4.box("nose_cheek_%s" % sy, (0.0030, 0.0008, 0.0051), (0.0300, sy*0.0069, 0.0040),
           bevel=0.00024, material=shell, body=base)

# Fixed polymer track and two low guide ribs; carriage remains supported over its full stroke.
v4.box("slider_track_bed", (0.031, 0.0095, 0.00065), (0.0085, 0, 0.00635), bevel=0.0015,
       material=track_mat, body=base)
for sy in (-1, 1):
    v4.box("guide_rib_%s" % sy, (0.028, 0.00065, 0.00042), (0.008, sy*0.0039, 0.00661),
           bevel=0.0003, material=dark_metal, body=base)

# PCB is fixed in the covered rear half of the housing. Fine traces and components are
# kept on its upper face; the shell opening at the slider channel exposes the mechanism.
v4.box("flash_pcb", (0.027, 0.0105, 0.0010), (-0.0105, 0, 0.00235), bevel=0.00045,
       material=green, body=base)
# Gold edge pads and subtle board traces.
for i in range(6):
    x = -0.021 + i*0.0032
    v4.box("pcb_edge_pad_%02d" % i, (0.0015, 0.0015, 0.00012), (x, -0.0047, 0.00292),
           bevel=0.00015, material=gold, body=base)
for i in range(4):
    v4.box("pcb_trace_%02d" % i, (0.014, 0.00018, 0.00010), (-0.009, 0.0010+i*0.0012, 0.0029),
           bevel=0.00008, material=gold, body=base)
v4.box("flash_controller", (0.0060, 0.0052, 0.0010), (-0.012, 0.0003, 0.00335), bevel=0.00045,
       material=chip, body=base)
for i in range(4):
    v4.box("controller_pin_%d" % i, (0.00045, 0.00055, 0.00015), (-0.014+i*0.0011, -0.00265, 0.0030),
           bevel=0.0001, material=gold, body=base)
for i in range(2):
    v4.box("passive_%d" % i, (0.0020, 0.0013, 0.00065), (-0.003+i*0.004, 0.0023, 0.0032),
           bevel=0.00025, material=chip, body=base)
v4.sphere("activity_led", 0.00055, (-0.001, -0.0030, 0.00325), segments=16, material=led, body=base)

# Full-width molded rear cap closes the body around the PCB. A metal lug embedded
# in the cap carries the upright lanyard eye outside the rear edge.
v4.box("rear_end_cap", (0.0012, 0.020, 0.0062), (-0.0235, 0, 0.0042),
       bevel=0.00035, material=shell, body=base)
v4.torus("lanyard_eye", 0.0030, 0.00062, loc=(-0.0270, 0, 0.0041), rot=(math.pi/2, 0, 0),
         material=dark_metal, body=base)
v4.rod("lanyard_lug", (-0.0243, 0, 0.0041), (-0.0226, 0, 0.0041), 0.00078,
       material=dark_metal, body=base)
v4.box("blue_id_bar", (0.0038, 0.0010, 0.00012), (-0.0219, 0, 0.00806), bevel=0.00008,
       material=blue, body=base)

# Moving carriage. At zero, the plug nose sits just inside the bezel at X=29 mm.
# Its 16 mm travel takes the thumb pad to the end of the track and exposes the plug.
v4.box("carriage_shuttle", (0.019, 0.0102, 0.0032), (0.0085, 0, 0.00455), bevel=0.0010,
       material=track_mat, body=move)
# One manifold thumb pad with four shallow raised transverse grip bars molded into
# the top profile. Keeping these in the same mesh makes the ribs part of the pad.
def make_grip_pad():
    xmin, xmax = -0.00725, 0.00325
    zbottom, ztop, zpeak = 0.00765, 0.00880, 0.00898
    top = [(xmin, ztop)]
    for c in (-0.0059, -0.0035, -0.0011, 0.0013):
        top.extend([(c-0.00055, ztop), (c-0.00030, zpeak),
                    (c+0.00030, zpeak), (c+0.00055, ztop)])
    top.append((xmax, ztop))
    outline = [(xmin, zbottom), (xmax, zbottom)] + list(reversed(top))
    n = len(outline)
    halfw = 0.0046
    verts = [(x, -halfw, z) for x, z in outline] + [(x, halfw, z) for x, z in outline]
    faces = [tuple(range(n-1, -1, -1)), tuple(range(n, 2*n))]
    for i in range(n):
        j = (i+1) % n
        faces.append((i, j, n+j, n+i))
    mesh = bpy.data.meshes.new("molded_thumb_pad_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new("thumb_slider", mesh)
    bpy.context.scene.collection.objects.link(obj)
    obj.data.materials.append(rubber)
    v4.part(obj, move)
    bevel = obj.modifiers.new("soft_molded_edges", "BEVEL")
    bevel.width = 0.00010
    bevel.segments = 3
    return obj

make_grip_pad()
# Narrow neck passes through the open part of the case slot and ties the thumb pad
# directly to the inner carriage.
v4.box("thumb_stalk", (0.0030, 0.0040, 0.0024), (-0.0020, 0, 0.00725), bevel=0.00035,
       material=track_mat, body=move)

# USB-A male shell: four separate thin walls meet edge-to-edge and leave the front mouth open.
# Overall shell 12 x 12 x 4.5 mm, with refined 0.30 mm plated walls.
plug_x0, plug_x1 = 0.0170, 0.0290
plug_cx = (plug_x0+plug_x1)/2
plug_yw, plug_zh, wall = 0.0120, 0.0045, 0.00030
plug_zc = 0.00415
v4.box("usb_shell_bottom", (0.0114, plug_yw, wall), (0.0230, 0, plug_zc-plug_zh/2+wall/2),
       bevel=0.00018, material=steel, body=move)
usb_top = v4.box("usb_shell_top", (0.0103, plug_yw, wall), (0.02245, 0, plug_zc+plug_zh/2-wall/2),
                 bevel=0.00012, material=steel, body=move)
# Paired retention apertures punched through the broad upper shell wall.
for i, sy in enumerate((-0.00325, 0.00325)):
    punch = v4.box("retention_hole_punch_%d" % i, (0.0019, 0.0021, 0.0010),
                    (0.0233, sy, plug_zc+plug_zh/2-wall/2), bevel=0, material=None)
    v4.boolean(usb_top, punch)
for sy in (-1, 1):
    v4.box("usb_shell_side_%s" % sy, (0.012, wall, plug_zh-2*wall), (plug_cx, sy*(plug_yw/2-wall/2), plug_zc),
           bevel=0.00015, material=steel, body=move)
# Black tongue and four individually spaced gold contact strips in the open mouth.
v4.box("usb_insulator_tongue", (0.0100, 0.0080, 0.00064), (0.0234, 0, plug_zc+0.00022),
       bevel=0.00032, material=chip, body=move)
for i in range(4):
    y = (i-1.5)*0.00165
    v4.box("usb_contact_%d" % i, (0.0067, 0.00082, 0.00012), (0.0250, y, plug_zc+0.00060),
           bevel=0.00008, material=gold, body=move)

# Branding and finish details on the fixed case roof. Text is wrapped onto its surface.
v4.text("brand_wordmark", "NOVA", 0.0030, loc=(-0.014, 0.0006, 0.00803),
        rot=(0, 0, 0), material=white, body=base, on="auto", height=0.00016)
v4.text("capacity_mark", "32 GB  |  USB", 0.00115, loc=(-0.014, -0.0031, 0.00803),
        rot=(0, 0, 0), material=white, body=base, on="auto", height=0.00012)
# Two small moulded seam screws on the roof corners.
for x in (-0.020, -0.006):
    for sy in (-1, 1):
        v4.cylinder("case_fastener_%s_%s" % (x, sy), 0.00062, 0.00020,
                    (x, sy*0.0072, 0.00802), segments=16, bevel=0.00008,
                    material=dark_metal, body=base)

# Slide axis follows the long case axis. v4's prismatic frame local +Z is aligned to world +X.
v4.joint("connector_slide", "prismatic", base, move, origin=(0, 0, 0.0040),
         axis=(1, 0, 0), limits=(0.0, 0.0160))

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