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

v4.reset()
# Palette
concrete = v4.mat('warm_grey_cast_concrete', (0.49,0.48,0.44), roughness=0.88)
steel = v4.metal('galvanized_steel', (0.68,0.71,0.72), roughness=0.33)
darksteel = v4.metal('darkened_structural_steel', (0.16,0.20,0.22), roughness=0.37)
white = v4.painted('off_white_enamel', (0.82,0.84,0.82), roughness=0.28)
yellow = v4.painted('safety_yellow', (0.95,0.52,0.035), roughness=0.3)
mirror = v4.metal('silvered_glass_mirror', (0.86,0.90,0.94), roughness=0.105, brushed=False)
mirror_back = v4.painted('mirror_dark_protective_back', (0.12,0.15,0.17), roughness=0.48, coat=0.18)
receiver = v4.metal('receiver_stainless', (0.72,0.74,0.76), roughness=0.23, brushed=True)
receiver_glass = v4.glass('borosilicate_receiver_envelope', (0.82,0.91,0.98), roughness=0.045)
glass_bsdf=receiver_glass.node_tree.nodes.get('Principled BSDF')
glass_bsdf.inputs['Transmission Weight'].default_value=0.88
glass_bsdf.inputs['Roughness'].default_value=0.035
glass_bsdf.inputs['Metallic'].default_value=0.0
glass_bsdf.inputs['Coat Weight'].default_value=0.12
selective = v4.mat('selective_absorber_coating', (0.055,0.065,0.072), metallic=0.72, roughness=0.24)
black = v4.rubber('bearing_elastomer', (0.055,0.06,0.06))
labelmat = v4.mat('dark_label', (0.035,0.06,0.065), roughness=0.5)
sensor_blue = v4.glass('sun_sensor_blue_glass', (0.12,0.40,0.62), roughness=0.12)
brass = v4.metal('warm_fastener_zinc', (0.72,0.57,0.30), roughness=0.32)

# Dimensions and parabolic profile: focus is the absorber/tracking axis.
L, aperture, focus_z = 12.0, 5.8, 3.30
f = 2.43
yrim = aperture/2
zvertex = focus_z - f

def surf_z(y): return zvertex + y*y/(4*f)

def mesh_obj(name, verts, faces, material, body, bevel=0):
    mesh=bpy.data.meshes.new(name+'_mesh'); mesh.from_pydata(verts, [], faces); mesh.materials.append(material); mesh.update()
    ob=bpy.data.objects.new(name,mesh); bpy.data.collections['Asset'].objects.link(ob)
    if bevel:
        mod=ob.modifiers.new('soft_edge','BEVEL'); mod.width=bevel; mod.segments=2
    v4.part(ob,body)
    return ob

def annular_sleeve(name, x0, x1, inner_r, outer_r, material, body, segments=64):
    verts=[]; faces=[]
    for x,r in ((x0,outer_r),(x1,outer_r),(x0,inner_r),(x1,inner_r)):
        for i in range(segments):
            a=2*math.pi*i/segments
            verts.append((x,r*math.cos(a),focus_z+r*math.sin(a)))
    o0,o1,i0,i1=0,segments,segments*2,segments*3
    for i in range(segments):
        j=(i+1)%segments
        faces.extend(((o0+i,o1+i,o1+j,o0+j),(i0+i,i0+j,i1+j,i1+i),
                      (o0+i,o0+j,i0+j,i0+i),(o1+i,i1+i,i1+j,o1+j)))
    return mesh_obj(name,verts,faces,material,body)

base=v4.body('foundation')
move=v4.body('collector_assembly')
half=L/2
stations=(-half-0.45,half+0.45)
# Ground footings and long anchor rails
# Two end footing beams stay outside the mirror sweep, but tie each pair of columns together.
for x in stations:
    v4.box('concrete_anchor_rail', (0.50,1.72,0.30),(x,0,0.15),bevel=0.035,material=concrete,body=base)
# Low grade beams tie the end footings outside the moving collector sweep.
v4.box('foundation_grade_beam',(stations[1]-stations[0],0.20,0.15),(0,1.10,0.075),bevel=0.025,material=concrete,body=base)
for x in stations:
    v4.box('footing_grade_beam_joint',(0.50,0.50,0.15),(x,0.90,0.075),bevel=0.02,material=concrete,body=base)
# Three bearing stations, each with twin tapered legs and crosshead
for i,x in enumerate(stations):
    # legs rise from two feet to a crosshead under the rotary axis
    for s in (-1,1):
        p0=(x, s*0.52,0.25); p1=(x,s*0.30,2.98)
        v4.rod('support_column',p0,p1,0.105,material=white,body=base,square=True)
        v4.box('column_foot',(0.24,0.26,0.045),(x,s*0.52,0.267),bevel=0.008,material=steel,body=base)
        v4.box('column_anchor_plate',(0.32,0.32,0.05),(x,s*0.52,0.24),bevel=0.006,material=steel,body=base)
        for bx in (-0.085,0.085):
            for by in (-0.09,0.09):
                v4.cylinder('foundation_anchor_bolt',0.018,0.038,(x+bx,s*0.52+by,0.264),segments=20,material=steel,body=base)
                v4.cylinder('foundation_anchor_nut',0.025,0.012,(x+bx,s*0.52+by,0.289),segments=6,material=brass,body=base)
        # diagonal stiffener
        v4.rod('column_gusset_strut',(x,s*0.52,0.5),(x,s*0.30,2.05),0.028,material=steel,body=base,square=True)
    v4.box('bearing_crosshead',(0.65,0.76,0.20),(x,0,3.015),bevel=0.035,material=white,body=base)
    v4.box('bearing_saddle',(0.48,0.50,0.05),(x,0,3.14),bevel=0.018,material=darksteel,body=base)
    # Retaining bearing cheek plates either side of tube (shaft axis X)
    for sy in (-1,1):
        v4.box('bearing_cheek',(0.11,0.15,0.30),(x,sy*0.22,3.30),bevel=0.035,material=steel,body=base)
        v4.cylinder('bearing_cap_bolt',0.025,0.018,(x,sy*0.22,3.30),rot=(0,math.pi/2,0),material=darksteel,body=base)
    v4.box('bearing_top_cap',(0.18,0.49,0.07),(x,0,3.49),bevel=0.025,material=white,body=base)
    for sy in (-1,1):
        v4.cylinder('cap_fastener',0.018,0.012,(x,sy*0.18,3.524),material=steel,body=base)
    # Deep split bearing ring with a dark liner around the receiver-axis shaft.
    v4.torus('bearing_housing_ring',0.165,0.035,(x,0,focus_z),rot=(0,math.pi/2,0),material=darksteel,body=base)
    v4.torus('bearing_liner',0.126,0.012,(x,0,focus_z),rot=(0,math.pi/2,0),material=black,body=base)
# Drive housing at east end, mounted on outboard extension of end support
drive_station=stations[1]
drive_cx=drive_station+0.33
v4.box('gearbox_main_case',(0.48,0.52,0.62),(drive_cx,-1.00,3.08),bevel=0.065,material=darksteel,body=base)
v4.box('gearbox_bolted_cover',(0.06,0.39,0.48),(drive_cx+0.27,-1.00,3.08),bevel=0.04,material=steel,body=base)
v4.rod('gearbox_pylon_bracket',(drive_station+0.20,-0.34,3.015),(drive_station+0.20,-0.76,3.015),0.045,material=steel,body=base,square=True)
# vertical electric motor above gearbox, with cooling fins and end bell
v4.cylinder('tracking_motor_body',0.19,0.52,(drive_cx,-1.40,3.28),rot=(math.pi/2,0,0),material=white,body=base)
v4.cylinder('motor_end_bell',0.205,0.10,(drive_cx,-1.71,3.28),rot=(math.pi/2,0,0),material=steel,body=base)
for a in range(12):
    ang=2*math.pi*a/12
    v4.rod('motor_cooling_fin',(drive_cx+0.16*math.cos(ang),-1.38,3.28+0.16*math.sin(ang)),(drive_cx+0.19*math.cos(ang),-1.38,3.28+0.19*math.sin(ang)),0.012,material=white,body=base)
v4.box('motor_terminal_box',(0.20,0.18,0.14),(drive_cx,-1.26,3.50),bevel=0.025,material=white,body=base)
# Conduit from terminal box into drive housing
v4.tube('motor_conduit',[(drive_cx,-1.26,3.43),(drive_cx,-1.14,3.43),(drive_cx,-1.14,3.30)],0.018,material=darksteel,body=base)
# drive warning / maker plates on exposed case side
v4.box('gearbox_id_plate',(0.008,0.25,0.13),(drive_cx+0.299,-1.00,3.08),bevel=0.008,material=labelmat,body=base)
# Compact slew ring and worm-drive housing on the powered end portal.
drive_x=drive_station-0.20
v4.torus('slew_drive_ring',0.230,0.035,(drive_x,0,focus_z),rot=(0,math.pi/2,0),material=darksteel,body=base)
for k in range(24):
    a=2*math.pi*k/24
    y,z=0.260*math.cos(a),focus_z+0.260*math.sin(a)
    v4.cylinder('slew_ring_gear_tooth',0.026,0.060,(drive_x,y,z),rot=(0,math.pi/2,0),segments=12,material=steel,body=base)
    v4.rod('slew_drive_mount',(drive_x,-0.225,focus_z),(drive_station+0.09,-0.74,focus_z),0.045,material=steel,body=base,square=True)
# Tracking sensor and controller enclosure on the opposite pylon.
v4.box('solar_controller_case',(0.34,0.30,0.34),(stations[0],-0.43,2.38),bevel=0.035,material=white,body=base)
v4.box('controller_faceplate',(0.012,0.20,0.22),(stations[0],-0.588,2.38),bevel=0.014,material=darksteel,body=base)
for z in (2.31,2.36,2.41,2.46):
    v4.box('controller_vent_slot',(0.008,0.105,0.012),(stations[0],-0.598,z),bevel=0.004,material=steel,body=base)
v4.box('sensor_mount_plate',(0.27,0.24,0.035),(stations[0],-0.43,2.563),bevel=0.008,material=steel,body=base)
v4.box('sun_sensor_housing',(0.23,0.20,0.15),(stations[0],-0.43,2.648),bevel=0.025,material=darksteel,body=base)
v4.box('sun_sensor_window',(0.16,0.13,0.012),(stations[0],-0.43,2.729),bevel=0.01,material=sensor_blue,body=base)
for sx in (-1,1):
    for sy in (-1,1):
        v4.box('quadrant_sensor_cell',(0.058,0.052,0.006),(stations[0]+sx*0.035,-0.43+sy*0.031,2.739),bevel=0.004,material=mirror,body=base)

# Offset torque tube below the mirror vertex. End yokes couple it to the receiver-axis bearings.
spine_z=zvertex-0.28
v4.cylinder('longitudinal_torque_tube',0.16,L+0.20,(0,0,spine_z),rot=(0,math.pi/2,0),segments=64,material=darksteel,body=move)
for s in (-1,1):
    x=s*(half+0.05)
    # Triangular end webs land on the spine and the rotating shaft at the bearing axis.
    v4.rod('end_yoke_center',(x,0,focus_z),(x,0,spine_z),0.045,material=white,body=move,square=True)
    for sy in (-1,1):
        v4.rod('end_yoke_diagonal',(x,sy*0.30,focus_z-0.035),(x,0,spine_z),0.055,material=steel,body=move,square=True)
# Receiver: a dark selective absorber inside a distinct clear borosilicate envelope.
v4.cylinder('absorber_tube',0.035,L+2.10,(0,0,focus_z),rot=(0,math.pi/2,0),segments=48,material=selective,body=move)
v4.cylinder('receiver_glass_envelope',0.0625,L+2.00,(0,0,focus_z),rot=(0,math.pi/2,0),segments=48,material=receiver_glass,body=move)
# Hollow rotating journal sleeves nest the glass receiver and run inside both fixed bearings.
annular_sleeve('receiver_bearing_journal_positive',half-0.50,half+0.50,0.0625,0.114,steel,move)
annular_sleeve('receiver_bearing_journal_negative',-half-0.50,-half+0.50,0.0625,0.114,steel,move)
# end receiver bellows and fittings
for s in (-1,1):
    # Corrugated metal expansion bellows and end unions around the exposed receiver ends.
    for k in range(5):
        x=s*(half+0.56+k*0.046)
        v4.torus('receiver_expansion_bellows',0.064,0.010,(x,0,focus_z),rot=(0,math.pi/2,0),material=receiver,body=move)
    v4.cylinder('receiver_transition_coupling',0.073,0.17,(s*(half+0.82),0,focus_z),rot=(0,math.pi/2,0),material=steel,body=move)
    x=s*(half+0.93)
    v4.cylinder('receiver_end_flange',0.085,0.05,(x,0,focus_z),rot=(0,math.pi/2,0),material=steel,body=move)
    v4.cylinder('receiver_end_union',0.065,0.08,(s*(half+1.02),0,focus_z),rot=(0,math.pi/2,0),material=selective,body=move)
    v4.torus('receiver_end_gasket',0.067,0.009,(s*(half+0.98),0,focus_z),rot=(0,math.pi/2,0),material=black,body=move)
# Rotating hub collar inside the outer slew ring on the powered end.
v4.torus('rotating_drive_hub',0.062,0.016,(drive_station-0.30,0,focus_z),rot=(0,math.pi/2,0),material=steel,body=move)

# Five transverse parabolic ribs, below the mirror facets with attachment tabs
rib_x=(-5.85,-3.90,-1.95,0,1.95,3.90,5.85)
for x in rib_x:
    # continuous swept web under the mirror facets
    pts=[]
    for i in range(41):
        y=-yrim + 2*yrim*i/40
        pts.append((x,y,surf_z(y)-0.11))
    v4.tube('parabolic_rib',pts,0.033,material=white,body=move)
    # A lower parabolic chord and repeated posts turn each bow into a deep web truss.
    lower=[]
    for i in range(41):
        y=-yrim + 2*yrim*i/40
        lower.append((x,y,surf_z(y)-0.24))
    v4.tube('parabolic_rib_lower_chord',lower,0.028,material=darksteel,body=move)
    web_ys=[-yrim+2*yrim*i/12 for i in range(13)]
    for i,y in enumerate(web_ys):
        ztop,zlow=surf_z(y)-0.11,surf_z(y)-0.24
        v4.rod('rib_web_post',(x,y,zlow),(x,y,ztop),0.020,material=steel,body=move,square=True)
        if i<12:
            yn=web_ys[i+1]
            if i%2==0:
                p0=(x,y,zlow); p1=(x,yn,surf_z(yn)-0.11)
            else:
                p0=(x,y,ztop); p1=(x,yn,surf_z(yn)-0.24)
            v4.rod('rib_web_diagonal',p0,p1,0.018,material=darksteel,body=move,square=True)
    # Broad cantilever arms fan out from the offset torque tube under the reflector.
    for side in (-1,1):
        for y in (0.72,1.45,2.25,2.65):
            v4.rod('cantilever_support_arm',(x,side*0.075,spine_z),(x,side*y,surf_z(y)-0.11),0.040,material=steel,body=move,square=True)
        v4.rod('spine_ladder_crossbrace',(x,side*0.075,spine_z),(x,side*0.43,spine_z-0.07),0.032,material=darksteel,body=move,square=True)
# Longitudinal lower chords tie the five cross-trusses into one rigid collector space frame.
for side in (-1,1):
    v4.rod('space_frame_lower_chord',(-5.85,side*0.43,spine_z-0.07),(5.85,side*0.43,spine_z-0.07),0.044,material=white,body=move,square=True)
    v4.rod('parabolic_back_stringer',(-5.90,side*1.82,surf_z(1.82)-0.24),(5.90,side*1.82,surf_z(1.82)-0.24),0.038,material=darksteel,body=move,square=True)
    # End yokes meet the space-frame chord and torque tube at the rotating hubs.
    for sx in (-1,1):
        v4.rod('end_yoke_to_lower_chord',(sx*5.85,side*0.43,spine_z-0.07),(sx*(half+0.05),0,spine_z),0.045,material=steel,body=move,square=True)
# Three slender receiver posts rise from the central torque member at mirror module seams.
for x in (-2.95,0,2.95):
    v4.rod('receiver_support_post',(x,0,spine_z+0.12),(x,0,focus_z-0.055),0.016,material=steel,body=move,square=True)
    v4.box('receiver_post_foot',(0.16,0.14,0.025),(x,0,spine_z+0.13),bevel=0.008,material=darksteel,body=move)
    v4.torus('receiver_support_ring',0.071,0.012,(x,0,focus_z),rot=(0,math.pi/2,0),material=steel,body=move)
    v4.box('receiver_saddle_insulator',(0.09,0.12,0.035),(x,0,focus_z-0.045),bevel=0.012,material=black,body=move)
# Facet surfaces, eight across by two four-metre modules. Create slight seams and true curve.
ny,nx=4,4
facet_gap_y=0.026; facet_gap_x=0.026
panel_span=L-0.20
for ix in range(nx):
    xa=-panel_span/2+ix*(panel_span/nx)+facet_gap_x/2
    xb=-panel_span/2+(ix+1)*(panel_span/nx)-facet_gap_x/2
    for iy in range(ny):
        ya=-yrim+iy*(aperture/ny)+facet_gap_y/2
        yb=-yrim+(iy+1)*(aperture/ny)-facet_gap_y/2
        verts=[]; faces=[]
        # curved gridded surface; mild segmentation gives a manufactured glass facet, not one flat plate
        rows,cols=10,4
        for j in range(rows+1):
            x=xa+(xb-xa)*j/rows
            for k in range(cols+1):
                y=ya+(yb-ya)*k/cols
                verts.append((x,y,surf_z(y)))
        for j in range(rows):
            for k in range(cols):
                a=j*(cols+1)+k; b=a+cols+1
                faces.append((a,b,b+1,a+1))
        ob=mesh_obj(f'mirror_facet_{ix+1}_{iy+1}',verts,faces,mirror,move)
        ob.data.materials.append(mirror_back)
        solid=ob.modifiers.new('dark_glass_edge_and_backing','SOLIDIFY')
        solid.thickness=0.009; solid.offset=-1.0; solid.material_offset=1; solid.material_offset_rim=1; solid.use_rim=True
        # slim dark backing at 25mm below, reveals facet edges under glancing light
        # border clamps on five rib stations; each small clamp lands on mirror margins
        # Facet edges and seams remain exposed; the continuous support ribs sit immediately below.
        for rx in rib_x:
            if xa <= rx <= xb:
                mount_x=rx
            elif abs(rx) < 0.1:
                mount_x=-0.02 if ix == 0 else 0.02
            else:
                continue
            my=(ya+yb)/2
            v4.rod('facet_mount_standoff',(mount_x,my,surf_z(my)-0.11),(mount_x,my,surf_z(my)-0.001),0.018,material=steel,body=move)
            v4.box('facet_mounting_pad',(0.14,0.12,0.018),(mount_x,my,surf_z(my)-0.017),bevel=0.004,material=steel,body=move)
# End fascia rails on both longitudinal ends, following rim-to-rim outer profile via straight/segmented chords
for x in (-L/2,L/2):
    pts=[]
    for k in range(25):
        y=-yrim+2*yrim*k/24
        pts.append((x,y,surf_z(y)-0.11))
    v4.tube('module_end_fascia',pts,0.046,material=darksteel,body=move)
# Longitudinal rim rails reinforce sides and make aperture perimeter crisp
for s in (-1,1):
    y=s*yrim
    v4.rod('longitudinal_rim_rail',(-L/2,y,surf_z(y)-0.11),(L/2,y,surf_z(y)-0.11),0.055,material=white,body=move,square=True)
# Tracking-axis hinge. Pivot precisely coincident with receiver focal/absorber axis.
v4.joint('tracking_axis','revolute',base,move,origin=(0,0,focus_z),axis=(1,0,0),limits=(-math.radians(70),math.radians(70)))

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