"""Editable Sovereignty CC0 asset recipe. Run with a Blender Python or blender --background --python recipe.py -- <arguments>."""
import argparse
import json
import math
import sys
from pathlib import Path

import bpy
from mathutils import Matrix, Vector

PI = math.pi
MATERIALS = {}


def material(name, rgb, metallic=0.55, emission=0):
    mat = bpy.data.materials.new(name)
    mat.diffuse_color = (*rgb, 1)
    mat.use_nodes = True
    shader = mat.node_tree.nodes.get('Principled BSDF')
    for prop, val in [('Base Color', (*rgb,1)), ('Metallic', metallic), ('Roughness', .36),
                      ('Emission Color', (*rgb,1)), ('Emission Strength', emission)]:
        shader.inputs[prop].default_value = val
    MATERIALS[name] = mat


def finish(obj, name, color, bevel=0):
    obj.name = name
    obj.data.materials.append(MATERIALS[color])
    if bevel:
        edge = obj.modifiers.new('Machined chamfer', 'BEVEL')
        edge.width = bevel
        edge.segments = 2
        obj.modifiers.new('Panel normals', 'WEIGHTED_NORMAL')
    return obj


def box(name, pos, dims, color='Slate', bevel=.07):
    bpy.ops.mesh.primitive_cube_add(size=1, location=pos)
    obj = bpy.context.object
    obj.dimensions = dims
    bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
    return finish(obj, name, color, min(bevel, min(dims)/4))


def cylinder(name, pos, radius, depth, color='Steel', axis='Z', radius2=None, vertices=24):
    rotation = {'X':(0,PI/2,0), 'Y':(PI/2,0,0), 'Z':(0,0,0)}[axis]
    bpy.ops.mesh.primitive_cone_add(vertices=vertices, radius1=radius, radius2=radius if radius2 is None else radius2,
                                    depth=depth, location=pos, rotation=rotation)
    return finish(bpy.context.object, name, color, .025)


def beam(name, start, end, width, color='Steel'):
    a,b=Vector(start),Vector(end)
    obj=box(name,(a+b)/2,(width,width,(b-a).length),color)
    obj.rotation_euler=(b-a).to_track_quat('Z','Y').to_euler()
    return obj


def ring(name, pos, radius, tube, color, axis='Z'):
    bpy.ops.mesh.primitive_torus_add(location=pos, major_segments=32, minor_segments=8, major_radius=radius,minor_radius=tube,
                                    rotation={'X':(0,PI/2,0),'Y':(PI/2,0,0),'Z':(0,0,0)}[axis])
    return finish(bpy.context.object,name,color)


def pod(x, y, z):
    box('Removable freight pod',(x,y,z),(.94,1.14,.76),'Ivory',.13)
    for dy in (-.36,.36):
        box('Cargo tie-down',(x,y+dy,z),(.98,.085,.80),'Ochre')
    box('Manifest status',(x,y-.577,z),(.36,.025,.10),'Cyan')


def engine(x,y,z,scale=1):
    cylinder('Propulsion bell',(x,y,z),.63*scale,1.1*scale,'Graphite','Y',.43*scale)
    ring('Exhaust ceramic rim',(x,y+.56*scale,z),.52*scale,.085*scale,'Steel','Y')
    cylinder('Ion throat',(x,y+.57*scale,z),.43*scale,.035*scale,'Cyan','Y')
    for d in (0,.28):
        ring('Engine cooling band',(x,y-d*scale,z),(.51-.04*d)*scale,.058*scale,'Ochre','Y')


def tender():
    for side in (-1,1):
        x=2.0*side
        box('Service hull pontoon',(x,.2,0),(1.16,7.4,1.16),'Teal',.26)
        prow=box('Sloped bow cheek',(x,-3.68,.04),(.94,1.25,.85),'Ivory',.21)
        prow.rotation_euler.x=-.18
        for y in (-2.65,-1.35,-.05):
            pod(x,y,.93)
        engine(x,3.94,0)
        for y in (1.22,1.72,2.22):
            box('Service-bay deck stripe',(x-side*.5,y,.58),(.15,.20,.06),'Ochre')
        beam('Gantry leg',(x,-1.3,.54),(x,-1.1,2.45),.24,'Ochre')
        beam('Bay entrance brace',(x,-1.22,2.38),(x-side*.55,-1.22,2.75),.18,'Steel')
    box('Open center service floor',(0,-.03,-.50),(3.18,4.65,.24),'Graphite')
    for x in (-1.05,1.05):
        box('Illuminated alignment rail',(x,-.2,-.34),(.08,3.9,.055),'Cyan')
    box('Overhead crane bridge',(0,-1.2,2.55),(4.55,.31,.27),'Ochre')
    box('Mobile hoist carriage',(-.56,-1.2,2.31),(.74,.52,.34),'Graphite')
    cylinder('Retracted grapple',(-.56,-1.2,1.88),.13,.55,'Steel')
    box('Aft engineering block',(0,2.54,.34),(3.25,2.1,1.65),'Ivory',.21)
    box('Raised bridge',(0,2.06,1.35),(2.35,1.42,.67),'Teal',.17)
    box('Bridge glazing',(0,1.33,1.42),(1.79,.12,.25),'Cyan')
    for x in (-.70,0,.70):
        box('Aft heat exchanger',(x,3.10,1.24),(.34,.84,.22),'Graphite')
    cylinder('Communications mast',(.68,2.48,2.16),.065,1.2,'Steel')
    cylinder('Mast beacon',(.68,2.48,2.78),.11,.14,'Amber')


def drone():
    box('Armored keel',(0,0,0),(2.45,3.1,.83),'Graphite',.28)
    box('Ochre instrument brow',(0,-1.08,.53),(2.12,1.22,.65),'Ochre',.22)
    cylinder('Stereo survey lens',(0,-1.74,.51),.33,.20,'Steel','Y')
    cylinder('Survey lens glass',(0,-1.855,.51),.225,.055,'Cyan','Y')
    box('Ore hopper floor',(0,.75,.44),(1.55,1.67,.16),'Steel')
    for side in (-1,1):
        rim=box('Flared hopper side',(side*.82,.74,.84),(.18,1.87,.86),'Ochre')
        rim.rotation_euler.y=side*.21
        beam('Cutter shoulder',(side*.85,-.66,.12),(side*1.56,-1.12,-.05),.36,'Steel')
        beam('Cutter drive arm',(side*1.56,-1.12,-.05),(side*1.72,-2.41,-.21),.31,'Ochre')
        cylinder('Cutter drive axle',(side*1.72,-2.41,-.2),.28,.68,'Graphite','X')
        cylinder('Rotary extraction wheel',(side*1.91,-2.47,-.19),.66,.21,'Steel','X',vertices=32)
        for angle in range(12):
            a=angle*PI/6
            tooth=box('Replaceable cutting tooth',(side*1.91,-2.47+.68*math.sin(a),-.19+.68*math.cos(a)),(.30,.22,.26),'Ivory')
            tooth.rotation_euler.x=-a+.29
        for y in (-.40,1.20):
            beam('Thruster outrigger',(side*.9,y,-.12),(side*1.67,y,-.18),.2,'Graphite')
            cylinder('Maneuvering thruster',(side*1.61,y,-.24),.34,.52,'Steel','Z',.24)
            cylinder('Thruster exit',(side*1.61,y,-.52),.22,.045,'Cyan')
    for y in (-.1,1.59):
        box('Hopper end wall',(0,y,.81),(1.78,.13,.78),'Teal')
    for x,y,z,r in ((-.39,.58,.69,.34),(.26,.84,.68,.31),(.34,.29,.65,.24),(-.24,1.18,.67,.29)):
        bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1,radius=r,location=(x,y,z))
        finish(bpy.context.object,'Ore sample','Copper')


def replicator():
    box('Fabrication bed',(0,0,0),(4.2,3.25,.42),'Graphite')
    box('Pattern projection grid',(0,0,.25),(3.35,2.50,.10),'Cyan')
    for x in (-1.87,1.87):
        for y in (-1.35,1.35):
            beam('Chamber rail',(x,y,.20),(x,y,3.35),.26,'Ivory')
        box('Gantry runway',(x,0,3.32),(.4,3.1,.24),'Teal')
    box('Tool traverse',(0,.32,3.24),(3.8,.37,.32),'Ochre')
    beam('Tool arm',(-.56,.32,3.1),(-.26,.12,2.12),.30,'Steel')
    beam('Articulated head',(-.26,.12,2.12),(.43,-.30,1.50),.24,'Ochre')
    cylinder('Emitter nozzle',(.43,-.30,1.27),.11,.50,'Copper','Z',.23)


def cargo_mule():
    box('Rover chassis',(0,0,.60),(2.5,4.8,.58),'Ochre',.20)
    cab=box('Forward cab',(0,-1.65,1.34),(2.2,1.38,1.2),'Ivory',.19)
    box('Pilot windscreen',(0,-2.35,1.50),(1.67,.10,.54),'Teal')
    for side in (-1,1):
        for y in (-1.65,0,1.65):
            cylinder('Traction wheel',(side*1.35,y,.38),.59,.47,'Graphite','X')
            cylinder('Axle cap',(side*1.61,y,.38),.26,.09,'Steel','X')
        for y in (.02,1.28): pod(side*.55,y,1.28)


def cooling():
    cylinder('Coolant plinth',(0,0,.18),1.6,.36,'Graphite',vertices=8)
    cylinder('Pressure column',(0,0,2.5),.77,4.55,'Steel')
    for k in range(11):
        cylinder('Radial heat fins',(0,0,.63+k*.36),1.31,.12,'Teal',vertices=16)
    for x in (-1.25,1.25):
        cylinder('Visible return pipe',(x,0,2.55),.13,4.15,'Copper')
        beam('Return manifold',(x,0,.50),(0,0,.50),.19,'Steel')
    ring('Service walkway',(0,0,4.70),1.06,.15,'Ochre')
    cylinder('Top vent',(0,0,4.98),.83,.25,'Graphite')


def bottle():
    cylinder('Containment sleeve',(0,0,1.1),.74,1.67,'Teal','Z',.74)
    for z in (.23,1.96):
        cylinder('Impact collar',(0,0,z),.89,.33,'Graphite',vertices=8)
    for a in range(6):
        t=a*PI/3
        beam('Magnetic rail',(.76*math.cos(t),.76*math.sin(t),.34),(.76*math.cos(t),.76*math.sin(t),1.82),.105,'Ochre')
    cylinder('Fuel interlock',(0,0,2.22),.38,.26,'Copper')
    ring('Interlock status',(0,0,2.36),.28,.038,'Cyan')


def coil():
    for z in (-1.25,1.25):
        ring('Coil cage hoop',(0,0,z),1.55,.17,'Steel')
    for k in range(16): ring('Insulated copper winding',(0,0,-1.05+k*.14),1.12,.092,'Copper')
    for k in range(6):
        a=k*PI/3
        beam('Cage stay',(1.55*math.cos(a),1.55*math.sin(a),-1.25),(1.55*math.cos(a),1.55*math.sin(a),1.25),.16,'Teal')


def thruster():
    cylinder('Pressure vessel',(0,0,0),.98,1.70,'Steel','Y')
    cylinder('Expanding exhaust',(0,1.42,0),1.23,1.15,'Graphite','Y',.72)
    ring('Exhaust liner',(0,2,0),1.07,.10,'Copper','Y')
    cylinder('Luminous exhaust throat',(0,2.02,0),.80,.07,'Cyan','Y')
    for side in (-1,1):
        box('Mounting shoe',(side*.88,-.15,-.40),(.48,1.25,.45),'Ochre')
    for i in range(6):
        a=i*PI/3; x,z=math.cos(a),math.sin(a)
        beam('Cooling return',(x*.91,-.7,z*.91),(x*.91,.60,z*.91),.12,'Copper')


def probe():
    bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1,radius=.84,location=(0,0,0))
    finish(bpy.context.object,'Instrument bus','Ochre')
    for i in range(3):
        a=i*2*PI/3; x,y=math.cos(a),math.sin(a)
        beam('Antenna boom',(x*.63,y*.63,0),(x*2.12,y*2.12,.32),.09,'Steel')
        panel=box('Fold-out detector segment',(x*1.45,y*1.45,.14),(1.16,.54,.08),'Teal');panel.rotation_euler.z=a
        cylinder('Attitude nozzle',(x*.50,y*.50,-.61),.15,.29,'Graphite','Z',.09)
    cylinder('Signal mast',(0,0,1.06),.07,.93,'Steel')
    ring('Telemetry loop',(0,0,1.58),.32,.045,'Copper','X')


def dish():
    # Lathed open parabolic reflector with an offset feed. Each ring is editable.
    ribs,steps=32,6
    verts=[(0,0,.58)]
    for s in range(1,steps+1):
        r=2.1*s/steps
        for i in range(ribs):
            a=2*PI*i/ribs
            verts.append((math.cos(a)*r,math.sin(a)*r,.58+.17*r*r))
    faces=[(0,1+i,1+(i+1)%ribs) for i in range(ribs)]
    for s in range(steps-1):
        a=1+s*ribs;b=a+ribs
        for i in range(ribs):
            n=(i+1)%ribs;faces.append((a+i,b+i,b+n,a+n))
    mesh=bpy.data.meshes.new('Reflector petals');mesh.from_pydata(verts,[],faces);mesh.update()
    panel=bpy.data.objects.new('Deep-space deflector dish',mesh);bpy.context.collection.objects.link(panel);finish(panel,panel.name,'Copper')
    plate=panel.modifiers.new('Bowl thickness','SOLIDIFY');plate.thickness=.055
    ring('Retaining rim',(0,0,1.34),2.1,.08,'Ivory')
    cylinder('Gimbal pedestal',(0,0,0),.77,1.2,'Graphite')
    for a in (0,2*PI/3,4*PI/3):beam('Receiver strut',(1.92*math.cos(a),1.92*math.sin(a),1.24),(0,0,2.12),.09,'Steel')
    cylinder('Field feed',(0,0,2.18),.20,.45,'Cyan')


def tug():
    box('Towing spine',(0,0,.06),(1.66,5.2,1.14),'Teal',.24)
    box('Pilot blister',(0,-1.58,.85),(1.55,1.47,.84),'Ivory',.19)
    box('Pilot glass',(0,-2.31,.94),(1.08,.12,.38),'Cyan')
    for side in (-1,1):
        engine(side*1.12,2.12,-.05,1.02)
        beam('Swing boom',(side*.72,-.12,.21),(side*1.92,-1.69,.29),.37,'Ochre')
        beam('Inward grapple',(side*1.92,-1.69,.29),(side*1.46,-2.65,.26),.22,'Steel')
    cylinder('Cable drum',(0,1.19,.88),.62,1.19,'Copper','X')
    for x in (-.58,.58):cylinder('Winch flange',(x,1.19,.88),.72,.10,'Graphite','X')


def shuttle():
    box('Pressurized freight volume',(0,.25,.30),(2.72,4.3,1.83),'Ivory',.35)
    nose=box('Sloping forward cab',(0,-2.06,.18),(2.08,1.58,1.26),'Teal',.26)
    nose.rotation_euler.x=-.15
    box('Flight deck glazing',(0,-2.85,.40),(1.39,.12,.43),'Cyan')
    ramp=box('Hinged loading ramp',(0,2.98,-.48),(1.96,1.72,.16),'Ochre');ramp.rotation_euler.x=-.25
    box('Hold bulkhead',(0,2.41,.38),(2.22,.11,1.24),'Graphite')
    for x in (-.74,.74):
        for y in (-1.55,1.45):
            beam('Landing strut',(x,y,-.31),(x*1.27,y,-1.05),.17,'Steel')
            box('Landing skid',(x*1.27,y,-1.1),(.38,.76,.14),'Graphite')
    for side in (-1,1):engine(side*1.49,.96,.14,.66)


def hub():
    cylinder('Octagonal pressure module',(0,0,0),1.72,1.92,'Ivory',vertices=8)
    cylinder('Operations cupola',(0,0,1.18),1.03,.56,'Teal',vertices=8)
    for i in range(6):
        a=i*PI/3;x,y=math.cos(a),math.sin(a)
        spine=box('Expansion tunnel',(x*2.05,y*2.05,-.04),(1.54,.78,.64),'Graphite');spine.rotation_euler.z=a
        rim=box('Standard docking flange',(x*2.75,y*2.75,-.04),(.22,1.02,.85),'Ochre');rim.rotation_euler.z=a
        light=box('Approach beacon',(x*2.88,y*2.88,.14),(.06,.47,.08),'Cyan');light.rotation_euler.z=a
    ring('Pressure seam',(0,0,.49),1.65,.07,'Copper')


def freighter():
    box('Bent lower keel',(0,0,-.5),(1.4,6.5,.4),'Graphite')
    for i,y in enumerate((-2.6,-1.7,-.8,.1,1,1.9,2.8)):
        for side in (-1,1):
            beam('Exposed rib',(side*.56,y,-.48),(side*1.30,y,.69),.14,'Copper')
            if (i+int(side))%3:
                plate=box('Torn cargo plating',(side*1.06,y,.09),(.22,.75,1.09),'Steel')
                plate.rotation_euler.y=side*(.31 if i!=4 else .79)
    box('Forward bulkhead',(0,-2.8,.24),(2.25,.42,1.44),'Ochre')
    engine(-.67,3.05,-.12,.69)
    for i in range(3):beam('Severed conduit',(.4+i*.18,1.4,.2),(.55+i*.21,2.96,.91-i*.17),.06,'Copper')


def rock(name,pos,size,seed,color):
    import random
    rng=random.Random(seed)
    bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=2,radius=size,location=pos)
    obj=bpy.context.object
    for vert in obj.data.vertices:
        f=rng.uniform(.86,1.12);vert.co.x*=1.28*f;vert.co.y*=.84*f;vert.co.z*=f
    finish(obj,name,color)
    return obj


def asteroid():
    rock('Fractured parent body',(0,0,0),1.65,308,'Basalt')
    for i,(x,y,z) in enumerate(((-1,.15,1.13),(-.57,.15,1.48),(0,.15,1.6),(.44,.18,1.53),(.83,.17,1.46))):
        vert=rock('Exposed mineral seam',(x,y,z),.27,403+i,'Copper');vert.scale=(1.4,.7,.55)
    for i in range(3):
        crystal=cylinder('Surface crystal',(-.58+i*.19,-.75,1.17+i*.06),.13,.53,'Teal','Z',0,vertices=5)
        crystal.rotation_euler.y=.23*i


def belt():
    for i,(x,y,z,r) in enumerate(((-2.2,-.6,.21,.89),(-.53,.45,-.21,.61),(.63,-.8,.1,.50),(1.91,.5,.23,.79),(.69,1.26,.41,.33))):
        rock('Floating belt fragment '+str(i+1),(x,y,z),r,813+i,'Basalt' if i%2==0 else 'Stone')


def pad():
    cylinder('Landing apron',(0,0,0),3.3,.34,'Graphite',vertices=8)
    ring('Touchdown circle',(0,0,.20),1.69,.055,'Ochre')
    for i in range(8):
        a=i*PI/4;x,y=math.cos(a),math.sin(a)
        box('Perimeter beacon',(x*2.88,y*2.88,.23),(.22,.22,.2),'Cyan')
    for x in (-.42,.42):box('Landing alignment bars',(x,0,.20),(.11,1.38,.04),'Ivory')
    box('Touchdown crossbar',(0,0,.20),(.90,.11,.04),'Ivory')
    box('Approach service kiosk',(2.28,.41,.53),(.53,.76,.80),'Teal')


def deck():
    box('Interlocking support plate',(0,0,0),(3.98,3.98,.26),'Graphite')
    for x in (-.98,.98):
        for y in (-.98,.98):
            box('Armored tile quadrant',(x,y,.18),(1.82,1.82,.14),'Slate',.12)
            for dx in (-.66,.66):
                for dy in (-.66,.66):
                    cylinder('Countersunk panel stud',(x+dx,y+dy,.259),.056,.016,'Steel',vertices=8)
    for a in (-1.20,1.20):
        box('Inset service light',(0,a,.185),(.05,.71,.035),'Cyan')
        box('Hazard marker',(a,0,.185),(.61,.08,.035),'Ochre')


def planet(mode):
    from mathutils import noise
    bpy.ops.mesh.primitive_uv_sphere_add(segments=64,ring_count=36,radius=2)
    o=bpy.context.object;o.name=mode
    colors={'Temperate colony':['Ocean','Land','Forest','Cloud','Ice'],'Scarred mining moon':['Basalt','Stone','Copper'],
            'Ringed gas giant':['Cloud','Ochre','Sand','Ivory']}[mode]
    for c in colors:o.data.materials.append(MATERIALS[c])
    for poly in o.data.polygons:
        p=poly.center.normalized();n=noise.noise_vector(p*3.2).x
        if mode=='Temperate colony':
            field=n+.25*noise.noise_vector(p*8).x
            idx=4 if abs(p.z)>.87 else 3 if noise.noise_vector(p*6+Vector((2,1,4))).z>.51 else 0 if field<.12 else 1 if field<.40 else 2
        elif mode=='Scarred mining moon':idx=2 if abs(n)<.021 and p.z>-.5 else int(n>.03)
        else:idx=int((p.z+.10*n+1)*10)%4
        poly.material_index=idx;poly.use_smooth=True
    if mode=='Ringed gas giant':
        for i in range(7):
            obj=ring('Ring band',(0,0,0),2.65+i*.11,.053,'Sand' if i%3 else 'Copper')
            obj.scale.z=.22;obj.rotation_euler.y=.28
    if mode=='Scarred mining moon':
        for x,y,r in ((-.80,-.74,.32),(.60,-.35,.24),(-.22,.91,.39)):
            v=Vector((x,y,(4-x*x-y*y)**.5))
            crater=ring('Impact rim',v*.994,r,.05,'Stone');crater.rotation_euler=v.to_track_quat('Z','Y').to_euler()
    if mode=='Temperate colony':
        for x,y in ((.29,-.82),(.38,-.79),(.43,-.73),(-.62,-.65),(-.68,-.63)):
            v=Vector((x,y,.48)).normalized()*2.005
            cylinder('Colony light',v,.022,.022,'Amber',vertices=6)


def carrier():
    box('Broad flight deck',(0,0,.54),(4.7,6.8,.43),'Slate',.34)
    box('Lower hangar hull',(0,.31,-.21),(3.82,5.84,1.18),'Teal',.31)
    for x in (-1.12,1.12):
        box('Split hangar entrance',(x,-2.67,-.13),(1.66,.18,.82),'Graphite')
        box('Illuminated hangar lintel',(x,-2.78,.25),(1.65,.07,.055),'Cyan')
        box('Flight deck centerline',(x,.1,.77),(.07,4.81,.035),'Ivory')
        for y in (-2.48,-1.32,1.36,2.58):
            box('Deck landing marker',(x,y,.79),(.51,.078,.04),'Ochre')
        engine(x,3.05,-.2,.79)
    box('Raised starboard island',(1.80,1.05,1.17),(.82,1.94,.82),'Ivory',.14)
    box('Flight control windows',(1.76,.051,1.21),(.62,.07,.19),'Cyan')
    cylinder('Signal mast',(1.80,1.43,2.03),.065,1.05,'Steel')
    box('Antenna array',(1.80,1.43,2.52),(.91,.1,.13),'Ochre')
    for y in (-1.35,-.2,.95):
        box('Port-side service sponson',(-2.29,y,.08),(.73,.89,.48),'Ivory',.10)


def salvage_drone():
    cylinder('Recovery drone drum',(0,0,0),.94,1.35,'Teal','X')
    ring('Tow shackle',(0,1.26,.06),.41,.10,'Ochre','X')
    box('Tow anchor',(0,.87,.01),(.58,.66,.39),'Graphite')
    for side in (-1,1):
        beam('Manipulator shoulder',(side*.54,-.44,0),(side*1.20,-1.23,.16),.22,'Ochre')
        beam('Manipulator forearm',(side*1.20,-1.23,.16),(side*.92,-1.95,-.12),.15,'Steel')
        engine(side*.77,.60,-.1,.43)
    cylinder('Salvage torch',(-.92,-2.09,-.1),.14,.43,'Copper','Y',.07)
    for dx in (-.18,.18):
        beam('Salvage gripper',(.92,-1.9,-.12),(.92+dx,-2.29,-.14),.085,'Steel')


def hull(name, sections, color):
    vertices = []
    faces = []
    for y, half_width, floor, roof in sections:
        vertices.extend([(-half_width * .72, y, floor), (half_width * .72, y, floor),
                         (half_width, y, roof * .56), (half_width * .62, y, roof),
                         (-half_width * .62, y, roof), (-half_width, y, roof * .56)])
    faces.append(tuple(range(6)))
    for offset in range(0, len(vertices) - 6, 6):
        for edge in range(6):
            current = offset + edge
            following = offset + (edge + 1) % 6
            faces.append((current, current + 6, following + 6, following))
    faces.append(tuple(reversed(range(len(vertices) - 6, len(vertices)))))
    mesh = bpy.data.meshes.new(name)
    mesh.from_pydata(vertices, [], faces)
    mesh.update()
    panel = bpy.data.objects.new(name, mesh)
    bpy.context.collection.objects.link(panel)
    return finish(panel, name, color, .055)


def iron_choir():
    hull('Processional hull', [(-4.6,.27,-.25,.35),(-2.90,1.70,-.62,.91),
        (.35,2.03,-.80,1.12),(2.90,1.78,-.63,1.03),(3.55,1.18,-.42,.83)], 'Basalt')
    for side in (-1,1):
        for y in (-1.88,-.46,.96,2.17):
            beam('Vaulted copper rib',(side*1.97,y,-.01),(side*.60,y+.29,1.16),.25,'Copper')
            beam('Amber clerestory',(side*1.60,y-.18,.56),(side*.98,y-.01,.93),.10,'Amber')
        beam('Split prow fin',(side*1.48,-2.35,.18),(side*.73,-4.73,-.11),.31,'Steel')
        engine(side*1.16,3.28,-.04,1.02)
    for y,height in ((-.55,.89),(.58,1.36),(1.69,.90)):
        cylinder('Octagonal tower',(0,y,1.10+height/2),.43,height,'Graphite',vertices=8)
        cylinder('Crown',(0,y,1.10+height+.18),.49,.38,'Copper',radius2=.14,vertices=8)
        cylinder('Crown light',(0,y,1.10+height+.41),.092,.16,'Amber')


def torpedo_corvette():
    hull('Needle hull',[(-3.82,.12,-.14,.17),(-1.15,.99,-.50,.73),
        (1.42,.91,-.48,.60),(2.70,.58,-.30,.39)],'Ivory')
    hull('Cockpit canopy',[(-1.96,.10,.31,.40),(-.90,.53,.38,1.02),(.25,.43,.44,.86)],'Teal')
    engine(0,2.72,-.08,.77)
    for side in (-1,1):
        x=side*1.18
        beam('Swept outrigger',(side*.47,.98,.06),(x,-.26,.09),.32,'Copper')
        cylinder('Sealed flux nacelle',(x,-.24,.06),.42,3.28,'Teal','Y',vertices=8)
        cylinder('Nacelle nose',(x,-1.99,.06),.32,.26,'Graphite','Y',vertices=8)
        ring('Luminous octant',(x,-2.14,.06),.24,.047,'Cyan','Y')
        for y in (-.87,.38,1.11):
            cylinder('Nacelle collar',(x,y,.06),.46,.105,'Ivory','Y',vertices=8)
        beam('V-tail',(x,.91,.21),(x*1.72,2.15,.89),.19,'Teal')


def flux_housing():
    for x in (-.86,.86):
        box('Mounting foot',(x,0,.03),(.64,3.26,.26),'Steel')
        box('Outer sill',(x,0,.33),(.27,3.42,.44),'Ochre')
    cylinder('Faceted equipment housing',(0,0,.96),.99,2.80,'Graphite','Y',vertices=8)
    for y in (-1.36,-.62,.29,1.38):
        cylinder('Ceramic jacket',(0,y,.96),1.07,.22,'Ivory','Y',vertices=8)
    cylinder('Recessed field lens',(0,-1.50,.96),.68,.06,'Teal','Y',vertices=12)
    ring('Flux halo',(0,-1.55,.96),.54,.067,'Cyan','Y')
    ring('Inner aperture marker',(0,-1.57,.96),.30,.038,'Copper','Y')
    for x in (-.44,.44):
        box('Top guide',(x,.04,1.91),(.15,2.68,.17),'Ochre')
    box('Rear service cover',(0,1.47,.96),(1.18,.22,1.40),'Steel',.12)
    for z in (.64,.95,1.26):
        box('Service marking',(1.01,.39,z),(.05,.49,.07),'Amber')



def hydroponic_bay():
    box('Habitat pressure deck',(0,0,0),(4.9,7.0,.42),'Ivory',.18)
    for x in (-2.17,2.17):
        box('Fluid service trunk',(x,0,.34),(.48,6.70,.36),'Teal')
        for y in (-3.05,0,3.05):
            beam('Pressure frame upright',(x,y,.2),(x,y,2.45),.18,'Steel')
            beam('Roof rafter',(x,y,2.45),(0,y,3.5),.18,'Ivory')
        beam('Continuous roof sill',(x,-3.05,2.45),(x,3.05,2.45),.16,'Steel')
    beam('Roof spine',(0,-3.05,3.5),(0,3.05,3.5),.19,'Ivory')
    for x in (-1.18,1.18):
        for y in (-2.1,0,2.1):
            box('Cultivation trough',(x,y,.62),(1.55,1.83,.65),'Teal',.12)
            box('Growing substrate',(x,y,.97),(1.33,1.61,.08),'Basalt')
            for dx in (-.43,0,.43):
                for dy in (-.5,0,.5):
                    cylinder('Plant stem',(x+dx,y+dy,1.12),.037,.23,'Land',vertices=6)
                    for side in (-1,1):
                        leaf=box('Crop leaf',(x+dx+side*.085,y+dy,1.28),(.23,.12,.045),'Forest',.016)
                        leaf.rotation_euler.y=side*.48
        beam('Irrigation feed',(x,-2.95,.53),(x,2.95,.53),.09,'Copper')
        box('Grow-light rail',(x,0,2.52),(.22,5.6,.12),'Steel')
        box('Grow-light face',(x,0,2.44),(.15,5.5,.035),'Cyan')
    for y in (-3.25,3.25):
        ring('Habitat transfer flange',(0,y,1.4),.82,.14,'Steel','Y')
    cylinder('Nutrient reservoir',(1.8,2.65,1.30),.27,1.3,'Ivory',vertices=16)
    box('Crop monitoring console',(-1.80,-2.72,1.03),(.48,.56,.91),'Graphite')
    box('Console status',(-1.80,-3.02,1.30),(.32,.04,.18),'Cyan')


def pressure_airlock():
    box('Deck interface',(0,0,-1.36),(3.50,4.6,.35),'Slate')
    for y in (-1.85,-.65,.65,1.85):
        for k in range(8):
            a=k*PI/4
            b=(k+1)*PI/4
            beam('Octagonal pressure frame',(1.42*math.cos(a),y,1.42*math.sin(a)),(1.42*math.cos(b),y,1.42*math.sin(b)),.19,'Steel')
    for side in (-1,1):
        box('Side pressure shell',(side*1.39,0,0),(.21,3.8,1.9),'Ivory')
        box('Internal utility raceway',(side*1.13,0,-.74),(.19,3.3,.27),'Teal')
        box('Pressure status strip',(side*1.13,0,.82),(.075,2.9,.13),'Cyan')
        for y in (-1.85,1.85):
            box('Recessed sliding door leaf',(side*.93,y,.05),(.49,.21,2.16),'Graphite',.12)
            box('Door safety edge',(side*.69,y,.05),(.07,.25,2.02),'Ochre')
    box('Walking threshold',(0,0,-1.13),(2.05,4.10,.14),'Graphite')
    for y in (-1.96,1.96):
        box('Threshold marker',(0,y,-1.04),(1.35,.14,.045),'Amber')
        box('Header',(0,y,1.30),(2.5,.28,.26),'Ivory')
    for x in (-.54,.54):
        box('Ceiling service channel',(x,0,1.20),(.18,3.7,.16),'Teal')
    box('Atmosphere control cabinet',(1.03,.43,.10),(.44,.65,.92),'Ochre')
    box('Pressure display',(.78,.43,.34),(.05,.45,.18),'Cyan')
    for y in (-.35,.1,.55):
        cylinder('Vent intake',(-1.23,y,.31),.13,.08,'Graphite','X',vertices=12)
    beam('Overhead equalization line',(-1.15,-1.6,1.03),(-1.15,1.6,1.03),.09,'Copper')


def solar_power_array():
    cylinder('Mounting pedestal',(0,0,.32),.67,.64,'Graphite',vertices=16)
    cylinder('Azimuth gimbal',(0,0,.76),.48,.29,'Copper',vertices=16)
    box('Central distribution bus',(0,0,1.18),(1.20,2.5,.57),'Ivory')
    for y in (-.82,.82):
        cylinder('Pitch hinge',(0,y,1.37),.27,1.65,'Steel','X',vertices=16)
    for side in (-1,1):
        for section in range(3):
            x=side*(1.60+section*2.05)
            box('Panel perimeter backplate',(x,0,1.35),(1.94,2.55,.16),'Graphite',.04)
            for dy in (-1.16,1.16):
                box('Panel edge rail',(x,dy,1.46),(1.95,.11,.12),'Steel',.02)
            for dx in (-.90,.90):
                box('Cell frame end',(x+dx,0,1.46),(.10,2.45,.12),'Steel',.02)
            for i in range(4):
                for j in range(6):
                    px=x+(i-1.5)*.42
                    py=(j-2.5)*.37
                    box('Photovoltaic cell',(px,py,1.47),(.385,.338,.055),'Ocean',.008)
                    box('Cell busbar',(px,py,1.502),(.025,.31,.012),'Copper',.002)
            if section<2:
                cylinder('Fold axis',(x+side*1.025,0,1.35),.11,2.64,'Copper','Y',vertices=12)
        beam('Rear deployment spar',(side*.55,0,1.1),(side*6.56,0,1.1),.12,'Teal')
        box('Wing tip telemetry',(side*6.57,0,1.46),(.15,.35,.09),'Cyan')
    box('Power junction',(0,0,.99),(.70,.82,.28),'Teal')
    box('Output status',(0,-1.27,1.21),(.48,.055,.19),'Amber')



def water_reclamation_skid():
    box('Skid frame',(0,0,.18),(4.8,3.6,.36),'Graphite')
    for x in (-1.25,1.25):
        cylinder('Vertical filtration vessel',(x,.28,1.35),.66,2.18,'Ivory',vertices=16)
        cylinder('Removable filter cap',(x,.28,2.50),.72,.19,'Steel',vertices=16)
        for z in (.68,1.95):
            ring('Vessel clamp',(x,.28,z),.66,.055,'Teal')
        beam('Water return',(x,.28,.45),(x,-1.28,.45),.14,'Copper')
        cylinder('Return valve',(x,-1.28,.64),.19,.32,'Ochre',vertices=12)
    box('Membrane control cabinet',(0,-1.25,1.15),(1.05,.68,1.46),'Teal')
    box('Water quality display',(0,-1.61,1.45),(.66,.04,.24),'Cyan')
    for x in (-.35,.35):
        cylinder('Clean-water outlet',(x,-1.65,.65),.14,.40,'Steel','Y')
    beam('Upper distribution pipe',(-1.25,.28,2.72),(1.25,.28,2.72),.14,'Copper')
    for x in (-1.25,1.25):
        beam('Top riser',(x,.28,2.55),(x,.28,2.72),.14,'Copper')
    for x in (-2.12,2.12):
        box('Forklift access channel',(x,0,.39),(.25,3.1,.17),'Ochre')


def cargo_elevator():
    box('Foundation',(0,0,.15),(4.6,4.2,.3),'Graphite')
    for x in (-1.85,1.85):
        for y in (-1.62,1.62):
            beam('Tower upright',(x,y,.3),(x,y,6.4),.28,'Steel')
        for z in (2.0,4.0,6.1):
            beam('Crossmember',(x,-1.62,z),(x,1.62,z),.22,'Teal')
        for i in range(3):
            beam('Diagonal brace',(x,-1.62,.4+i*1.9),(x,1.62,2.0+i*1.9),.13,'Steel')
        box('Guide track',(x,0,3.34),(.21,.30,5.95),'Copper')
    for y in (-1.62,1.62):
        beam('Crown girder',(-1.85,y,6.4),(1.85,y,6.4),.32,'Ochre')
    box('Cargo platform',(0,0,2.10),(3.38,3.02,.35),'Slate')
    for x in (-1.52,1.52):
        box('Safety curb',(x,0,2.40),(.19,2.95,.26),'Ochre')
        beam('Hoist cable',(x,0,2.4),(x,0,6.15),.045,'Steel')
    cylinder('Hoist drum',(0,0,6.15),.35,2.20,'Graphite','X',vertices=16)
    box('Lift control pedestal',(2.04,-1.2,.88),(.48,.46,1.15),'Teal')
    box('Lift call indicator',(2.04,-1.45,1.12),(.24,.04,.19),'Amber')


def crew_quarters_cutaway():
    box('Habitat deck',(0,0,.15),(4.8,6.2,.3),'Slate')
    box('Rear pressure bulkhead',(0,2.93,1.58),(4.8,.28,2.85),'Ivory')
    box('Port pressure bulkhead',(-2.26,0,1.58),(.28,5.6,2.85),'Ivory')
    for x in (-1.28,1.28):
        box('Bunk frame',(x,1.86,.66),(1.18,1.9,.38),'Teal')
        box('Lower sleeping pad',(x,1.86,.91),(1.08,1.77,.18),'Sand')
        box('Pillow',(x,2.47,1.05),(.82,.35,.15),'Ivory')
        box('Upper bunk frame',(x,1.86,1.98),(1.18,1.9,.22),'Steel')
        box('Upper sleeping pad',(x,1.86,2.17),(1.08,1.77,.18),'Sand')
        for y in (.96,2.75):
            beam('Bunk support',(x-.56,y,.45),(x-.56,y,2.2),.10,'Steel')
        for z in (.55,.88,1.21,1.54,1.87):
            beam('Bunk ladder rung',(x-.52,.83,z),(x-.12,.83,z),.06,'Ochre')
    box('Galley cabinet',(-1.68,-1.28,.75),(1.05,1.7,1.2),'Teal')
    box('Galley worktop',(-1.68,-1.28,1.39),(1.12,1.82,.12),'Steel')
    box('Fold-down table',(.64,-1.26,.89),(1.2,1.2,.12),'Ivory')
    beam('Table leg',(.64,-1.26,.3),(.64,-1.26,.83),.15,'Steel')
    for y in (-2.12,-.40):
        box('Seat cushion',(.64,y,.58),(.91,.42,.22),'Teal')
        box('Seat base',(.64,y,.35),(.78,.36,.30),'Graphite')
    box('Viewport inset',(0,2.76,2.25),(.9,.055,.48),'Ocean')
    box('Ceiling light housing',(0,2.64,2.82),(1.55,.30,.15),'Steel')
    box('Ceiling light strip',(0,2.45,2.78),(1.35,.06,.09),'Cyan')



def medical_triage_bay():
    box('Triage deck',(0,0,.14),(5.6,5.4,.28),'Slate')
    box('Rear bulkhead',(0,2.56,1.57),(5.6,.28,2.86),'Ivory')
    box('Partition',(-2.66,.45,1.57),(.28,3.95,2.86),'Ivory')
    for x in (-1.43,1.43):
        box('Treatment bed base',(x,.38,.52),(.72,1.65,.54),'Graphite')
        box('Treatment bed frame',(x,.38,.88),(1.05,2.22,.19),'Steel')
        box('Sterile mattress',(x,.38,1.02),(.92,2.08,.18),'Ivory')
        box('Head cushion',(x,1.14,1.17),(.78,.42,.12),'Teal')
        for y in (-.3,.63):
            beam('Bed safety rail',(x-.54,y,.99),(x-.54,y,1.28),.055,'Steel')
        box('Bedside monitor pedestal',(x+.76,1.18,.75),(.32,.36,1.25),'Teal')
        box('Monitor housing',(x+.76,1.18,1.43),(.53,.28,.39),'Graphite')
        box('Vitals screen',(x+.76,1.025,1.43),(.43,.035,.25),'Cyan',.01)
    for x in (-1.78,0,1.78):
        box('Rear medical locker',(x,2.15,1.12),(1.12,.55,1.92),'Teal')
        box('Locker pull',(x,1.85,1.27),(.23,.07,.05),'Steel')
    for x in (-.5,.5):
        box('Triage station counter',(x,-1.9,.94),(.92,.62,.18),'Ivory')
        box('Counter support',(x,-1.9,.48),(.67,.49,.77),'Steel')
    for x in (-1.8,1.8):
        box('Overhead examination light',(x,.4,2.72),(.82,.52,.15),'Steel')
        beam('Examination light mount',(x,2.47,2.78),(x,.4,2.78),.10,'Steel')
        box('Examination diffuser',(x,.4,2.62),(.67,.4,.04),'Cyan')


def cryogenic_freight_vault():
    box('Refrigerated container skid',(0,0,.2),(4.3,5.0,.4),'Graphite')
    for x in (-2.0,2.0):
        box('Insulated vault sidewall',(x,0,1.62),(.26,4.9,2.48),'Ivory')
        for y in (-1.8,-.9,0,.9,1.8):
            box('Structural wall rib',(x,y,1.64),(.38,.13,2.55),'Steel')
    box('Insulated roof',(0,0,2.92),(4.28,4.95,.26),'Ivory')
    box('Rear refrigeration bulkhead',(0,2.31,1.6),(3.85,.36,2.47),'Teal')
    for x in (-1.05,1.05):
        cylinder('Refrigerant pressure reservoir',(x,2.59,1.6),.32,1.55,'Steel',vertices=16)
        ring('Reservoir mounting clamp',(x,2.59,1.21),.32,.045,'Copper')
    beam('External coolant header',(-1.05,2.59,2.44),(1.05,2.59,2.44),.13,'Copper')
    for x in (-1.40,1.40):
        box('Interior cold storage shelf',(x,.15,.82),(.84,3.7,.19),'Steel')
        box('Interior upper shelf',(x,.15,1.85),(.84,3.7,.19),'Steel')
        for y in (-1.20,.05,1.30):
            box('Sealed cold freight case',(x,y,1.14),(.71,1.08,.45),'Ocean')
            box('Cold freight status',(x,y-.55,1.14),(.38,.025,.09),'Cyan')
    for x in (-1.47,1.47):
        leaf=box('Open insulated door leaf',(x,-2.93,1.62),(1.08,.22,2.40),'Teal')
        leaf.rotation_euler.z=(-1 if x<0 else 1)*.73
    box('Temperature controller',(1.91,-2.49,1.82),(.36,.18,.47),'Graphite')
    box('Temperature status',(1.91,-2.60,1.88),(.25,.04,.15),'Cyan')


def atmospheric_processor():
    cylinder('Anchored foundation',(0,0,.20),2.05,.40,'Graphite',vertices=32)
    cylinder('Central compression housing',(0,0,1.40),.84,2.08,'Teal',vertices=24)
    cylinder('Filter stack',(0,0,2.89),.70,1.19,'Ivory',vertices=24)
    for z in (.55,1.72,2.55,3.35):
        ring('Compression casing seam',(0,0,z),.84 if z<2.5 else .7,.075,'Steel')
    for i in range(4):
        angle=i*PI/2
        x,y=1.35*math.cos(angle),1.35*math.sin(angle)
        cylinder('Radial intake tower',(x,y,1.2),.38,1.75,'Ivory',vertices=16)
        cylinder('Intake plenum',(x,y,2.13),.48,.32,'Graphite',vertices=16)
        for z in (1.98,2.08,2.18,2.28):
            ring('Intake grille ring',(x,y,z),.47,.034,'Steel')
        beam('Intake pipe',(x,y,.63),(x*.46,y*.46,.63),.17,'Copper')
        beam('Compression brace',(x,y,.32),(x*.45,y*.45,1.65),.13,'Steel')
    cylinder('Purified gas exhaust',(0,0,3.68),.41,.57,'Steel',vertices=24)
    ring('Exhaust aperture rim',(0,0,3.97),.42,.08,'Ochre')
    cylinder('Exhaust aperture',(0,0,3.98),.32,.035,'Graphite',vertices=24)
    box('Environmental control cabinet',(.65,-1.20,.80),(.70,.58,1.15),'Teal')
    box('Air-quality status',(.65,-1.51,1.05),(.48,.035,.22),'Cyan')
    for i in range(8):
        a=i*PI/4
        cylinder('Anchor bolt',(1.88*math.cos(a),1.88*math.sin(a),.45),.08,.13,'Ochre',vertices=8)



def surface_drill_rig():
    box('Tracked foundation frame',(0,0,.32),(4.8,5.8,.48),'Graphite')
    for x in (-1.95,1.95):
        box('Crawler tread chassis',(x,0,.45),(.78,5.0,.82),'Slate',.24)
        for y in (-1.95,-1.25,-.55,.15,.85,1.55):
            cylinder('Crawler road wheel',(x*1.16,y,.44),.29,.16,'Steel','X',vertices=16)
        for y in (-2.65,2.65):
            box('Outrigger jack foot',(x,y,.12),(.86,.68,.18),'Ochre')
            cylinder('Leveling jack',(x,y,.50),.13,.65,'Steel',vertices=16)
    box('Rotary table deck',(0,.62,.77),(2.45,2.35,.35),'Teal')
    ring('Bore aperture',(0,.62,1.0),.58,.12,'Steel')
    for x in (-.88,.88):
        for y in (.0,1.24):
            beam('Drill mast upright',(x,y,.95),(x*.67,y,5.45),.18,'Ochre')
        for z in (1.4,2.65,3.9):
            beam('Mast diagonal brace',(x,0,z),(x*.85,1.24,z+1.18),.10,'Steel')
    box('Crown block',(0,.62,5.46),(1.48,1.57,.32),'Slate')
    cylinder('Hoist drum',(0,.62,5.17),.27,1.05,'Copper','X',vertices=20)
    cylinder('Drill string',(0,.62,2.45),.17,4.60,'Steel',vertices=16)
    cylinder('Rotary drive head',(0,.62,3.70),.42,.54,'Teal')
    for z in (1.35,2.20,3.05):
        ring('Threaded tool coupling',(0,.62,z),.19,.045,'Copper')
    cylinder('Cutting bit',(0,.62,.25),.30,.54,'Graphite',radius2=.16,vertices=12)
    box('Operator control cabin',(-.95,-1.88,1.63),(1.30,1.45,1.52),'Ivory')
    box('Cabin forward window',(-.95,-2.62,1.89),(1.05,.06,.57),'Teal')
    box('Drive power pack',(1.05,-1.76,1.36),(1.65,1.72,1.02),'Ochre')
    for y in (-2.2,-1.9,-1.6,-1.3):
        box('Power cooling grille',(1.89,y,1.4),(.04,.11,.61),'Graphite')
    for x in (-.8,.8):
        box('Mast work lamp',(x,-.08,5.10),(.32,.20,.16),'Cyan')


def communications_relay_satellite():
    cylinder('Octagonal relay bus',(0,0,0),.77,1.95,'Ivory','Y',vertices=8)
    for y in (-.88,.88):
        cylinder('Bus end flange',(0,y,0),.83,.13,'Graphite','Y',vertices=8)
    for x in (-1,1):
        beam('Antenna outrigger',(x*.55,0,0),(x*2.68,0,0),.13,'Steel')
        cylinder('Array gimbal',(x*1.35,0,0),.21,.35,'Copper','X',vertices=16)
        box('Phased array panel',(x*2.10,0,.12),(1.52,1.48,.15),'Graphite')
        for i in range(5):
            for j in range(5):
                box('Radiating patch',(x*2.10+(i-2)*.265,(j-2)*.25,.223),(.20,.19,.05),'Copper',.01)
        box('Array electronics spine',(x*2.1,0,-.03),(.32,1.40,.16),'Teal')
    for side in (-1,1):
        a=side*.58
        beam('Crosslink antenna strut',(a,.58,.35),(side*.95,1.18,1.20),.10,'Steel')
        cylinder('Crosslink transmitter',(side*.95,1.18,1.20),.22,.38,'Teal','Z',vertices=16)
        cylinder('Crosslink face',(side*.95,1.18,1.41),.16,.045,'Cyan',vertices=16)
    beam('High gain feed mast',(0,-.72,.45),(0,-1.45,1.38),.09,'Steel')
    cylinder('High gain antenna aperture',(0,-1.48,1.45),.48,.18,'Ivory','Y',.24,32)
    ring('Aperture rim',(0,-1.60,1.45),.42,.05,'Steel','Y')
    cylinder('Aperture receiver',(0,-1.69,1.45),.13,.15,'Cyan','Y')
    for x in (-.45,.45):
        cylinder('Attitude control nozzle',(x,1.07,-.23),.16,.25,'Graphite','Y',.09,12)
    box('Relay status stripe',(0,-.99,-.32),(.55,.04,.12),'Amber')


def emergency_escape_capsule():
    cylinder('Capsule heat shield',(0,0,.18),1.40,.36,'Graphite',radius2=1.22,vertices=32)
    cylinder('Pressure shell lower',(0,0,.87),1.22,1.08,'Ivory',radius2=1.02,vertices=24)
    cylinder('Tapered upper cabin',(0,0,1.70),1.02,.58,'Ochre',radius2=.67,vertices=24)
    cylinder('Recovery nose cap',(0,0,2.13),.67,.28,'Ivory',radius2=.40,vertices=24)
    ring('Separation collar',(0,0,.40),1.23,.06,'Copper')
    ring('Cabin join seam',(0,0,1.37),1.04,.05,'Steel')
    box('Side escape hatch',(0,-1.08,1.03),(.82,.19,1.12),'Slate',.15)
    box('Hatch rescue marking',(0,-1.19,.81),(.58,.025,.14),'Ochre')
    cylinder('Hatch porthole frame',(0,-1.18,1.29),.24,.11,'Steel','Y',vertices=24)
    cylinder('Porthole glazing',(0,-1.25,1.29),.17,.045,'Teal','Y',vertices=24)
    beam('External hatch handle',(-.18,-1.23,.99),(.18,-1.23,.99),.065,'Steel')
    for i in range(3):
        a=PI/2+i*2*PI/3
        x,y=math.cos(a),math.sin(a)
        beam('Landing leg',(x*.93,y*.93,.56),(x*1.67,y*1.67,.20),.15,'Steel')
        beam('Landing brace',(x*.76,y*.76,1.0),(x*1.50,y*1.50,.28),.09,'Ochre')
        box('Landing foot',(x*1.67,y*1.67,.10),(.40,.40,.18),'Graphite')
        cylinder('Rescue beacon',(x*.73,y*.73,1.82),.11,.15,'Amber',vertices=12)
    cylinder('Recovery transponder',(0,0,2.35),.10,.25,'Steel')
    cylinder('Transponder indicator',(0,0,2.50),.14,.09,'Cyan')
    for x in (-.55,.55):
        cylinder('Descent thruster nozzle',(x,.80,.47),.19,.32,'Steel','Y',.12,16)



def observation_dome():
    # Open cutaway with a curved observation canopy and an unobstructed entry.
    cylinder('Octagonal habitat foundation',(0,0,.15),3.15,.30,'Graphite',vertices=12)
    cylinder('Observation floor',(0,0,.34),2.89,.10,'Slate',vertices=12)
    for i in range(9):
        a=(i+1)*PI/6
        x,y=math.cos(a),math.sin(a)
        for j in range(5):
            p=j*PI/10;q=(j+1)*PI/10
            beam('Canopy meridian',(2.85*x*math.cos(p),2.85*y*math.cos(p),.4+2.65*math.sin(p)),
                 (2.85*x*math.cos(q),2.85*y*math.cos(q),.4+2.65*math.sin(q)),.095,'Ivory')
    for i in range(1,9):
        a=i*PI/6;b=(i+1)*PI/6
        for p in (.26,.78,1.30):
            q=p+.25
            verts=[(2.79*math.cos(t)*math.cos(v),2.79*math.sin(t)*math.cos(v),.4+2.62*math.sin(v))
                   for t,v in ((a,p),(b,p),(b,q),(a,q))]
            mesh=bpy.data.meshes.new('Canopy glazing');mesh.from_pydata(verts,[],[(0,1,2,3)]);mesh.update()
            obj=bpy.data.objects.new('Tinted observation pane',mesh);bpy.context.collection.objects.link(obj)
            finish(obj,obj.name,'Teal')
    cylinder('Central observation plinth',(0,0,.55),.65,.32,'Steel',vertices=12)
    cylinder('Star chart projection',(0,0,.73),.51,.05,'Cyan',vertices=24)
    for a in (PI/3,PI,5*PI/3):
        x,y=1.72*math.cos(a),1.72*math.sin(a)
        seat=box('Observation bench',(x,y,.72),(1.25,.42,.22),'Ivory')
        seat.rotation_euler.z=a+PI/2
        box('Bench support',(x,y,.50),(.32,.32,.36),'Graphite')
    for x in (-.9,.9):
        box('Entry jamb',(x,-2.48,1.06),(.18,.25,1.44),'Ochre')
    box('Entry lintel',(0,-2.48,1.82),(1.98,.25,.17),'Ochre')


def freight_rail_junction():
    # Three separate track branches, central switch linkage and freight signal.
    box('Ballast slab',(0,0,.10),(7.4,7.6,.20),'Basalt')
    for y in (-3.5,-2.9,-2.3,-1.7,-1.1,-.5,.1,.7,1.3,1.9,2.5,3.1):
        shift=max(0,y)*.58
        box('Main track sleeper',(0,y,.27),(1.70,.22,.16),'Slate')
        if y>.1:
            box('Branch track sleeper',(shift,y,.27),(1.7,.22,.16),'Slate')
            box('Branch track sleeper',(-shift,y,.27),(1.7,.22,.16),'Slate')
    for x in (-.55,.55):
        beam('Straight rail',(x,-3.75,.43),(x,3.75,.43),.14,'Steel')
        for side in (-1,1):
            beam('Diverging branch rail',(x,-.7,.43),(x+side*2.18,3.75,.43),.14,'Steel')
    box('Switch drive housing',(1.32,-.80,.53),(.60,.96,.55),'Ochre')
    beam('Switch actuator',(1.32,-.80,.55),(.12,-.80,.43),.09,'Copper')
    for x in (-2.70,2.70):
        box('Signal pedestal',(x,-2.40,.38),(.47,.47,.36),'Graphite')
        cylinder('Signal mast',(x,-2.40,1.22),.085,1.65,'Steel')
        box('Signal head',(x,-2.40,2.05),(.31,.25,.56),'Graphite')
        cylinder('Signal lens',(x,-2.545,2.15),.10,.05,'Cyan','Y')
        cylinder('Signal lens',(x,-2.545,1.95),.10,.05,'Amber','Y')
    for x in (-3.1,3.1):
        box('Maintenance walkway',(x,.20,.29),(.40,6.8,.18),'Graphite')
        for y in (-2.6,-1.3,0,1.3,2.6):
            box('Walkway edge marker',(x,y,.39),(.36,.08,.03),'Ochre')


def geothermal_station():
    # Closed-loop settlement generator with wellheads, turbine and heat rejection.
    box('Plant foundation',(0,0,.12),(7.0,5.4,.24),'Graphite')
    for x in (-2.40,2.40):
        cylinder('Wellhead pressure collar',(x,-1.55,.52),.55,.64,'Steel',vertices=16)
        cylinder('Wellhead casing',(x,-1.55,1.08),.31,.65,'Copper')
        ring('Wellhead control wheel',(x,-1.55,1.49),.31,.045,'Ochre')
        beam('Vertical brine pipe',(x,-1.55,1.28),(x,-1.55,2.05),.23,'Copper')
        beam('Brine pipe header',(x,-1.55,2.05),(x,.35,2.05),.23,'Copper')
        beam('Brine downcomer',(x,.35,2.05),(x,.35,1.20),.23,'Copper')
    box('Turbine mounting frame',(0,.10,.47),(3.65,2.40,.45),'Slate')
    cylinder('Turbine housing',(0,.12,1.25),.80,2.60,'Teal','X')
    for x in (-1.29,1.29):
        ring('Turbine bolted flange',(x,.12,1.25),.81,.085,'Steel','X')
    cylinder('Generator end bell',(1.55,.12,1.25),.58,.50,'Ochre','X')
    for x in (-2.4,2.4):
        beam('Turbine supply manifold',(x,.35,1.20),(x/2,.35,1.20),.23,'Copper')
    for x in (-1.8,0,1.8):
        box('Air-cooled heat exchanger',(x,1.88,1.28),(1.38,.58,1.68),'Steel')
        for z in (.62,.87,1.12,1.37,1.62,1.87):
            box('Radiator fin',(x,1.55,z),(1.28,.11,.095),'Graphite')
        beam('Return line',(x,1.88,.46),(x,.67,.46),.16,'Copper')
    box('Switchgear cabinet',(0,-1.65,.87),(1.08,.64,1.25),'Ivory')
    box('Generator status display',(0,-1.985,1.03),(.66,.04,.25),'Cyan')
    for x in (-.30,0,.30):
        box('Isolation switch',(x,-1.985,.73),(.12,.045,.16),'Ochre')



def habitat_command_center():
    box('Raised operations deck',(0,0,.18),(7.8,6.2,.36),'Graphite')
    for x in (-3.65,3.65):
        box('Side bulkhead',(x,.85,1.45),(.25,4.1,2.5),'Slate')
        for y in (-.9,1.9):
            box('Bulkhead rib',(x,y,1.48),(.42,.23,2.58),'Steel')
    box('Rear bulkhead',(0,2.86,1.45),(7.4,.26,2.5),'Slate')
    box('Operations display wall',(0,2.66,1.79),(5.6,.15,1.6),'Graphite')
    for x in (-1.82,0,1.82):
        box('Mission status screen',(x,2.56,1.88),(1.68,.055,1.16),'Teal')
        for z,w in ((1.51,1.27),(1.77,.74),(2.04,1.38)):
            box('Illuminated status track',(x,2.515,z),(w,.025,.045),'Cyan',0)
    cylinder('Circular command table',(0,.2,.9),1.18,.18,'Ivory',vertices=32)
    cylinder('Table pedestal',(0,.2,.57),.38,.62,'Graphite')
    ring('Tactical projection rim',(0,.2,1.02),.91,.055,'Cyan')
    for i in range(6):
        a=i*PI/3
        cylinder('Map marker',(.67*math.cos(a),.2+.67*math.sin(a),1.07),.065,.09,'Amber',vertices=12)
    for x in (-2.3,2.3):
        for y in (-1.7,.95):
            box('Operator console base',(x,y,.65),(.78,.65,.65),'Slate')
            panel=box('Angled operator console',(x,y,.99),(1.17,.80,.15),'Ivory')
            panel.rotation_euler.x=.18
            screen=box('Console interface',(x,y-.06,1.085),(.83,.38,.05),'Cyan')
            screen.rotation_euler.x=.18
            box('Operator seat',(x,y-.8,.62),(.47,.47,.13),'Teal')
            box('Seat back',(x,y-1.02,.88),(.47,.12,.49),'Graphite')
            cylinder('Seat pedestal',(x,y-.8,.40),.12,.42,'Steel')
    for x in (-1.4,1.4):
        box('Access lane strip',(x,-2.5,.38),(.08,1.0,.04),'Ochre')
    for x in (-3.28,3.28):
        box('Overhead light rail',(x,.8,2.60),(.10,3.8,.09),'Cyan')


def surface_weather_station():
    box('Instrument foundation',(0,0,.15),(4.8,4.2,.30),'Slate')
    box('Weather electronics cabinet',(-1.22,.72,.85),(1.35,1.12,1.32),'Ivory')
    box('Cabinet telemetry display',(-1.22,.13,1.04),(.74,.05,.30),'Cyan')
    for x in (-1.6,-.85):
        box('Cabinet latch',(x,.10,.64),(.075,.08,.25),'Ochre')
    cylinder('Meteorological tower',(.88,.56,2.12),.10,3.85,'Steel')
    for a in (0,2*PI/3,4*PI/3):
        p=(.88+1.12*math.cos(a),.56+1.12*math.sin(a),.32)
        beam('Tower diagonal brace',p,(.88,.56,2.35),.09,'Ochre')
    cylinder('Anemometer shaft',(.88,.56,4.12),.065,.34,'Graphite')
    for a in (0,2*PI/3,4*PI/3):
        p=(.88+.47*math.cos(a),.56+.47*math.sin(a),4.30)
        beam('Wind rotor spoke',(.88,.56,4.30),p,.055,'Steel')
        cylinder('Rotor cup',p,.13,.17,'Ochre',vertices=16)
    beam('Wind vane cross arm',(.88,.56,3.53),(1.79,.56,3.53),.075,'Steel')
    box('Wind vane tail',(1.74,.56,3.66),(.28,.08,.36),'Ivory')
    beam('Radiation sensor arm',(.88,.56,2.64),(.18,.56,2.64),.075,'Steel')
    cylinder('Radiometer',(.18,.56,2.75),.18,.18,'Cyan',vertices=20)
    cylinder('Precipitation collector',(1.45,-1.1,.95),.34,1.24,'Steel',radius2=.43)
    ring('Collector rim',(1.45,-1.1,1.59),.43,.055,'Ochre')
    for z in (.78,.94,1.10,1.26,1.42):
        cylinder('Ventilated temperature shield',(-.25,-.95,z),.31,.075,'Ivory',radius2=.25)
    cylinder('Temperature sensor support',(-.25,-.95,.62),.07,.65,'Steel')
    box('Ground monitoring panel',(-1.1,-1.42,.53),(1.1,.70,.14),'Teal')
    for x in (-1.48,-1.10,-.72):
        box('Panel cell stripe',(x,-1.42,.61),(.035,.62,.025),'Copper')


def orbital_fuel_depot():
    cylinder('Depot axial bus',(0,0,0),.66,7.8,'Graphite','Y')
    for y in (-3.4,0,3.4):
        ring('Axial reinforcement flange',(0,y,0),.78,.14,'Steel','Y')
    for side in (-1,1):
        x=side*1.88
        for y in (-1.76,1.76):
            cylinder('Cryogenic propellant tank',(x,y,0),.85,2.65,'Ivory','Y',vertices=32)
            for dy in (-1.33,1.33):
                cylinder('Tank dished end',(x,y+dy,0),.85,.30,'Steel','Y',radius2=.64,vertices=32)
                ring('Tank retaining band',(x,y+dy*.72,0),.88,.09,'Ochre','Y')
            beam('Tank mounting truss',(side*.45,y,-.48),(x,y,-.48),.22,'Slate')
            beam('Tank upper mounting truss',(side*.45,y,.48),(x,y,.48),.22,'Slate')
            beam('Propellant transfer line',(x,y,.85),(side*.56,y,.85),.13,'Copper')
            cylinder('Isolating valve',(side*1.10,y,.85),.19,.20,'Ochre','X')
        box('Radiator spine',(side*3.0,0,0),(.25,5.6,.20),'Slate')
        for y in (-1.8,0,1.8):
            box('Radiator support',(side*2.70,y,0),(.75,.15,.18),'Steel')
            box('Thermal rejection panel',(side*3.22,y,0),(.62,1.58,.10),'Teal')
            for dy in (-.52,-.26,0,.26,.52):
                box('Radiator fin',(side*3.22,y+dy,.07),(.58,.035,.045),'Copper',0)
    for y in (-4.05,4.05):
        cylinder('Transfer docking collar',(0,y,0),.74,.37,'Steel','Y')
        ring('Docking guide rim',(0,y+math.copysign(.22,y),0),.57,.105,'Cyan','Y')
        cylinder('Recessed transfer port',(0,y+math.copysign(.20,y),0),.40,.08,'Graphite','Y')
    box('Depot telemetry module',(0,0,1.02),(1.02,1.50,.64),'Teal')
    box('Telemetry status strip',(0,-.77,1.02),(.65,.06,.18),'Cyan')
    cylinder('Navigation beacon',(0,0,1.62),.10,.62,'Steel')
    cylinder('Beacon light',(0,0,1.98),.14,.12,'Amber')



def regolith_sintering_kiln():
    # Surface construction materials: open feed hopper, continuous belt, insulated furnace and cooling rack.
    box('Kiln skid',(0,0,.18),(8.4,3.8,.36),'Graphite')
    for x in (-3.4,-2.0,0,2.0,3.4):
        for y in (-.76,.76):
            box('Conveyor pedestal',(x,y,.55),(.20,.24,.50),'Steel')
    box('Continuous conveyor bed',(0,0,.85),(7.6,1.62,.22),'Slate')
    for x in (-3.55,-3.18,-2.81,-2.44,-2.07,2.07,2.44,2.81,3.18,3.55):
        cylinder('Conveyor roller',(x,0,1.00),.095,1.49,'Steel','Y',vertices=12)
    for y in (-.83,.83):
        box('Conveyor guard',(0,y,1.05),(7.55,.10,.24),'Ochre')
        box('Hopper side plate',(-2.8,y*.87,1.85),(1.62,.16,1.10),'Ochre').rotation_euler.x=y*.29
    for x in (-3.60,-2.00):
        box('Hopper end plate',(x,0,1.85),(.15,1.48,1.10),'Steel').rotation_euler.y=(x+2.8)*.27
    for x,y,r in ((-3.1,-.22,.28),(-2.7,.27,.32),(-2.45,-.25,.24)):
        bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1,radius=r,location=(x,y,1.65))
        finish(bpy.context.object,'Unprocessed regolith','Stone')
    for y in (-1.12,1.12):
        box('Insulated furnace wall',(0,y,1.92),(3.35,.43,2.08),'Ivory',.13)
        for x in (-1.35,-.45,.45,1.35):
            box('Thermal jacket rib',(x,y*1.17,1.92),(.13,.15,1.88),'Steel')
    box('Refractory furnace roof',(0,0,3.02),(3.35,2.65,.36),'Teal')
    for x in (-1.61,1.61):
        box('Portal lintel',(x,0,2.42),(.22,2.12,.45),'Graphite')
        box('Furnace heat indicator',(x,0,2.12),(.23,1.42,.08),'Amber')
    cylinder('Filtered exhaust stack',(.55,.46,3.53),.25,.94,'Steel')
    cylinder('Exhaust hood',(.55,.46,4.04),.37,.18,'Ochre')
    for x in (2.25,2.95,3.50):
        for y in (-.36,.36):
            box('Sintered construction brick',(x,y,1.19),(.52,.56,.26),'Sand',.035)
    box('Kiln controller',(0,-1.62,1.0),(1.05,.46,1.35),'Slate')
    box('Process monitor',(0,-1.87,1.27),(.65,.05,.32),'Cyan')
    for x in (-.29,0,.29):
        cylinder('Control switch',(x,-1.89,.85),.065,.06,'Amber','Y',vertices=12)


def sample_analysis_laboratory():
    # Walk-in assay room: open front, microscopes, glovebox and sample carousel.
    box('Laboratory raised floor',(0,0,.15),(6.8,5.4,.30),'Slate')
    box('Rear service bulkhead',(0,2.58,1.48),(6.8,.24,2.66),'Ivory')
    for x in (-3.29,3.29):
        box('Side service bulkhead',(x,1.1,1.48),(.22,3.1,2.66),'Ivory')
        box('Utility channel',(x,1.1,2.48),(.30,3.0,.16),'Teal')
    for x in (-1.80,1.80):
        box('Laboratory bench cabinet',(x,1.66,.72),(2.75,1.10,.84),'Teal')
        box('Chemical-resistant countertop',(x,1.66,1.19),(2.86,1.24,.12),'Graphite')
        for dx in (-.86,0,.86):
            box('Cabinet door',(x+dx,1.08,.72),(.78,.055,.64),'Ivory')
            box('Cabinet pull',(x+dx,1.03,.89),(.19,.08,.05),'Steel')
    for x in (-2.48,-1.42):
        cylinder('Microscope stage',(x,1.54,1.34),.25,.15,'Steel')
        beam('Microscope support',(x,1.85,1.34),(x,1.82,1.96),.15,'Ivory')
        beam('Optical head',(x,1.82,1.96),(x,1.44,1.83),.19,'Teal')
        cylinder('Objective lens',(x,1.44,1.63),.09,.20,'Graphite')
        box('Sample slide',(x,1.54,1.45),(.22,.16,.025),'Cyan')
    box('Glovebox housing',(1.8,1.66,1.72),(2.45,1.02,1.04),'Slate')
    box('Observation window',(1.8,1.125,1.84),(2.16,.055,.59),'Teal')
    for x in (1.29,2.31):
        ring('Glove port',(x,1.07,1.57),.18,.045,'Steel','Y')
        cylinder('Glove port seal',(x,1.06,1.57),.15,.07,'Graphite','Y')
    box('Sample island base',(0,-.62,.66),(2.6,1.38,.72),'Ivory')
    box('Sample island worktop',(0,-.62,1.09),(2.75,1.50,.14),'Graphite')
    cylinder('Indexing sample carousel',(0,-.62,1.26),.56,.18,'Steel',vertices=32)
    for i in range(8):
        a=i*PI/4
        x,y=.40*math.cos(a),-.62+.40*math.sin(a)
        cylinder('Sealed sample vial',(x,y,1.46),.075,.26,'Cyan' if i%2 else 'Copper',vertices=12)
        cylinder('Sample vial cap',(x,y,1.61),.082,.05,'Ivory',vertices=12)
    for x in (-2.5,2.5):
        box('Instrument readout',(x,2.42,2.02),(1.10,.10,.57),'Graphite')
        box('Assay display',(x,2.35,2.02),(.94,.045,.43),'Cyan')
    for x in (-2.8,2.8):
        box('Overhead laboratory light',(x,1.0,2.78),(.12,2.4,.10),'Cyan')


def modular_footbridge():
    # Open pedestrian span with landing interfaces, guardrails and under-deck trusses.
    for x in (-3.65,3.65):
        box('Habitat connection landing',(x,0,.22),(1.4,2.7,.44),'Slate')
        for y in (-.9,.9):
            box('Landing foot',(x,y,-.16),(.68,.65,.32),'Graphite')
        box('Connection threshold',(x,0,.46),(1.12,2.35,.06),'Ochre')
    for y in (-1.04,1.04):
        beam('Upper span chord',(-3.0,y,.38),(3.0,y,.38),.21,'Steel')
        beam('Lower span chord',(-3.0,y,-.62),(3.0,y,-.62),.19,'Teal')
        for i in range(6):
            x=-3.0+i
            beam('Truss web diagonal',(x,y,-.62 if i%2==0 else .38),(x+1,y,.38 if i%2==0 else -.62),.14,'Steel')
        for x in (-3,-2,-1,0,1,2,3):
            beam('Guardrail upright',(x,y,.47),(x,y,1.57),.11,'Ivory')
        beam('Continuous handrail',(-3.2,y,1.56),(3.2,y,1.56),.13,'Ivory')
        beam('Intermediate guardrail',(-3.0,y,1.0),(3.0,y,1.0),.09,'Steel')
        for x in (-2.5,-.5,1.5,2.5):
            box('Edge marker lamp',(x,y,.58),(.29,.12,.10),'Cyan')
    for i in range(12):
        x=-2.75+.50*i
        box('Replaceable walking deck panel',(x,0,.40),(.48,2.02,.18),'Graphite',.02)
        box('Anti-slip tread',(x,0,.51),(.10,1.70,.028),'Steel',0)
    for x in (-2.5,-.5,1.5,2.5):
        beam('Underdeck cross brace',(x,-1.04,-.62),(x,1.04,-.62),.15,'Steel')
    for x in (-3.65,3.65):
        for y in (-1.14,1.14):
            cylinder('Landing bollard',(x,y,.77),.10,.58,'Ochre',vertices=12)
            cylinder('Landing marker',(x,y,1.08),.085,.08,'Amber',vertices=12)



def deepwater_survey_submersible():
    # Compact science vehicle; forward viewport, ballast tanks, skids and a sample arm.
    body=cylinder('Pressure vessel',(0,0,0),.90,3.25,'Ivory','Y',vertices=32)
    cylinder('Forward pressure cap',(0,-1.68,0),.90,.42,'Teal','Y',.65,vertices=32)
    ring('Viewport retaining flange',(0,-1.94,0),.47,.09,'Steel','Y')
    cylinder('Forward observation glass',(0,-2.00,0),.43,.12,'Cyan','Y',vertices=32)
    for side in (-1,1):
        x=side*1.10
        cylinder('Ballast cylinder',(x,.12,.12),.39,2.65,'Ochre','Y',vertices=24)
        for y in (-.85,.85):
            ring('Ballast retaining band',(x,y,.12),.40,.052,'Graphite','Y')
            beam('Ballast bracket',(side*.64,y,.12),(x,y,.12),.17,'Steel')
        cylinder('Shrouded water thruster',(x,1.60,.12),.39,.52,'Graphite','Y')
        ring('Thruster guard',(x,1.89,.12),.31,.055,'Steel','Y')
        for i in range(4):
            a=i*PI/2
            beam('Impeller blade',(x,1.9,.12),(x+.25*math.cos(a),1.9,.12+.25*math.sin(a)),.075,'Teal')
        box('Seabed skid',(side*.82,0,-1.02),(.26,3.5,.18),'Steel',.06)
        for y in (-1.13,1.13):
            beam('Skid stanchion',(side*.82,y,-1),(side*.57,y,-.46),.14,'Steel')
        cylinder('Survey floodlight',(side*.65,-1.75,.49),.16,.18,'Graphite','Y')
        cylinder('Floodlight lens',(side*.65,-1.86,.49),.13,.055,'Ivory','Y')
    cylinder('Dorsal hatch',(0,.43,.92),.34,.17,'Steel')
    cylinder('Acoustic beacon',(0,.43,1.23),.09,.46,'Amber')
    beam('Sampler shoulder',(.53,-1.19,-.55),(1.06,-1.82,-.63),.20,'Ochre')
    beam('Sampler elbow',(1.06,-1.82,-.63),(.81,-2.38,-.95),.15,'Steel')
    cylinder('Sampler wrist',(.81,-2.38,-.95),.13,.18,'Graphite','Y')
    for x in (.70,.92):
        beam('Sample claw',(x,-2.42,-.95),(x,-2.68,-1.08),.075,'Steel')
    box('Sample basket',(-.70,-1.14,-.69),(.66,.72,.33),'Teal')
    for y in (-1.37,-.91):
        box('Basket rim',(-.70,y,-.47),(.70,.08,.10),'Steel')


def orbital_optical_observatory():
    # Long open optical truss, primary mirror assembly, instrument bus and sunshade.
    cylinder('Instrument bus',(0,0,-.90),1.12,1.1,'Slate',vertices=12)
    cylinder('Primary mirror support',(0,0,-.22),1.45,.36,'Steel',vertices=48)
    for i in range(18):
        a=2*PI*i/18
        x,y=1.04*math.cos(a),1.04*math.sin(a)
        tile=cylinder('Segmented primary mirror',(x,y,.02),.28,.08,'Copper',vertices=6)
        tile.rotation_euler.z=a
    cylinder('Central optical aperture',(0,0,.06),.31,.08,'Graphite',vertices=32)
    for i in range(6):
        a=2*PI*i/6
        x,y=1.38*math.cos(a),1.38*math.sin(a)
        beam('Optical truss spar',(x,y,-.13),(x,y,2.55),.10,'Ivory')
        b=a+PI/3
        beam('Diagonal truss brace',(x,y,.15),(1.38*math.cos(b),1.38*math.sin(b),2.55),.075,'Steel')
    ring('Aperture ring',(0,0,2.55),1.38,.075,'Teal')
    for i in range(3):
        a=2*PI*i/3
        beam('Secondary mirror spider',(1.38*math.cos(a),1.38*math.sin(a),2.55),(0,0,2.25),.075,'Graphite')
    cylinder('Secondary mirror',(0,0,2.25),.30,.12,'Copper',vertices=24)
    for side in (-1,1):
        beam('Sunshade support',(side*.75,0,-.9),(side*2.35,0,-.9),.17,'Steel')
        box('Thermal shade panel',(side*2.45,0,-.9),(1.65,2.40,.11),'Ivory',.04)
        for y in (-.9,-.3,.3,.9):
            box('Shade stiffener',(side*2.45,y,-.82),(1.55,.045,.05),'Steel',0)
    for i in range(4):
        a=i*PI/2
        cylinder('Attitude control pod',(1.03*math.cos(a),1.03*math.sin(a),-1.23),.18,.34,'Graphite')
    box('Science telemetry transceiver',(0,-1.10,-.83),(.65,.27,.44),'Teal')
    box('Telemetry indicator',(0,-1.25,-.83),(.34,.035,.14),'Cyan')


def habitat_recreation_court():
    # Open, walkable low-gravity sports court with goals, spectator benches and scoreboard.
    box('Court structural slab',(0,0,.14),(9.0,5.8,.28),'Slate')
    box('Resilient playing surface',(0,0,.30),(8.1,4.3,.06),'Teal',.02)
    for x in (-3.92,3.92):
        box('End boundary stripe',(x,0,.345),(.065,4.0,.025),'Ivory',0)
    for y in (-1.98,1.98):
        box('Sideline stripe',(0,y,.345),(7.9,.065,.025),'Ivory',0)
    box('Center line',(0,0,.345),(.065,4.0,.025),'Ivory',0)
    ring('Center circle',(0,0,.348),.69,.026,'Ivory')
    for side in (-1,1):
        x=side*3.76
        for y in (-.78,.78):
            beam('Goal upright',(x,y,.36),(x,y,1.85),.13,'Ochre')
            beam('Goal rear stay',(x,y,1.85),(x+side*.54,y,.36),.09,'Steel')
        beam('Goal crossbar',(x,-.78,1.85),(x,.78,1.85),.13,'Ochre')
        for y in (-.60,-.30,0,.30,.60):
            beam('Goal net cord',(x,y,1.80),(x+side*.54,y,.40),.025,'Ivory')
        box('Goal padded backstop',(x+side*.59,0,.58),(.13,1.68,.45),'Graphite')
    for x in (-2.50,0,2.50):
        box('Spectator seat',(x,2.57,.68),(2.15,.45,.16),'Ivory')
        for dx in (-.78,.78):
            box('Seat mounting foot',(x+dx,2.57,.48),(.12,.36,.34),'Steel')
        box('Seat back',(x,2.77,.98),(2.15,.10,.38),'Slate')
    for x in (-3.45,3.45):
        beam('Court lighting post',(x,2.66,.32),(x,2.66,2.70),.14,'Steel')
        box('Court floodlight',(x,2.49,2.65),(.75,.35,.18),'Cyan')
    beam('Scoreboard support',(0,2.78,.32),(0,2.78,2.44),.14,'Steel')
    box('Scoreboard enclosure',(0,2.65,2.53),(2.10,.27,.65),'Graphite')
    for x in (-.57,.57):
        box('Score display',(x,2.49,2.53),(.78,.04,.43),'Cyan')
    box('Court equipment rack',(0,-2.61,.59),(1.8,.46,.53),'Slate')
    for x in (-.55,0,.55):
        bpy.ops.mesh.primitive_uv_sphere_add(segments=16,ring_count=8,radius=.17,location=(x,-2.61,.98))
        finish(bpy.context.object,'Training ball','Ochre')



def habitat_market_hall():
    box('Market foundation',(0,0,.12),(10.0,6.8,.24),'Graphite',.10)
    box('Public concourse',(0,-.65,.27),(9.7,4.9,.12),'Slate',.025)
    for i,x in enumerate((-3.25,0,3.25)):
        hue=('Teal','Ochre','Copper')[i]
        box('Vendor counter',(x,.65,.90),(2.50,.68,1.02),'Ivory')
        box('Counter worktop',(x,.65,1.46),(2.70,.82,.14),hue)
        box('Rear shelving frame',(x,2.42,1.43),(2.65,.30,2.60),'Graphite')
        for z in (.80,1.44,2.08):
            box('Stock shelf',(x,2.15,z),(2.40,.55,.10),'Steel')
            for k in range(4):
                box('Stock carton',(x-.87+k*.58,2.10,z+.18),(.42,.40,.26),('Ivory','Ochre','Teal','Slate')[(i+k)%4],.035)
        for dx in (-1.40,1.40):
            beam('Canopy pillar',(x+dx,.65,.30),(x+dx,.65,3.12),.13,'Steel')
        canopy=box('Colored canopy',(x,1.52,3.12),(2.85,2.15,.14),hue)
        canopy.rotation_euler.x=-.08
        box('Vendor illuminated sign',(x,.42,2.88),(1.58,.10,.25),'Cyan')
        box('Payment terminal',(x+.88,.57,1.61),(.28,.26,.20),'Graphite')
    cylinder('Exchange kiosk pedestal',(0,-2.05,.70),.54,.80,'Teal',vertices=8)
    cylinder('Exchange information desk',(0,-2.05,1.15),.78,.16,'Ivory',vertices=8)
    for side in (-1,1):
        box('Exchange display',(side*.30,-2.05,1.40),(.10,.48,.36),'Cyan')
        box('Concourse edge light',(side*4.75,-.70,.35),(.07,3.8,.04),'Cyan',0)
        box('Waiting bench',(side*3.15,-2.35,.58),(1.65,.55,.16),'Ivory')
        for dx in (-.55,.55):
            box('Bench leg',(side*3.15+dx,-2.35,.42),(.12,.42,.28),'Steel')


def surface_seismic_array():
    cylinder('Recorder foundation',(0,0,.14),.98,.28,'Basalt',vertices=12)
    cylinder('Sealed recorder cabinet',(0,0,.68),.62,.85,'Ivory',vertices=8)
    box('Recorder display',(0,-.58,.79),(.50,.09,.32),'Cyan')
    cylinder('Central survey mast',(0,0,1.92),.11,2.40,'Steel')
    ring('Antenna loop',(0,0,3.10),.41,.045,'Copper','X')
    cylinder('Telemetry beacon',(0,0,3.42),.10,.19,'Amber')
    for i in range(3):
        a=2*PI*i/3+PI/6
        x,y=3.25*math.cos(a),3.25*math.sin(a)
        cylinder('Seismic anchor plate',(x,y,.08),.62,.16,'Graphite',vertices=12)
        cylinder('Ground-coupled spike',(x,y,-.24),.18,.48,'Steel','Z',.32,vertices=12)
        cylinder('Sensor suspension',(x,y,.32),.31,.42,'Copper',vertices=16)
        cylinder('Seismometer enclosure',(x,y,.65),.44,.34,'Ochre',vertices=12)
        cylinder('Level bubble',(x,y,.85),.13,.06,'Cyan')
        for j in range(3):
            t=a+2*PI*j/3
            ex,ey=x+.75*math.cos(t),y+.75*math.sin(t)
            beam('Ground contact leg',(x+.32*math.cos(t),y+.32*math.sin(t),.47),(ex,ey,.10),.09,'Steel')
            cylinder('Contact foot',(ex,ey,.06),.12,.12,'Graphite',vertices=12)
        beam('Protected data conduit',(x*.21,y*.21,.09),(x*.83,y*.83,.09),.09,'Copper')
        for f in (.35,.55,.75):
            box('Cable retaining clip',(x*f,y*f,.12),(.20,.20,.12),'Slate')
        marker=box('Survey index flag',(x*.78,y*.78,.54),(.30,.08,.23),'Ivory')
        marker.rotation_euler.z=a


def orbital_passenger_ferry():
    # Two end vestibules flank an extended civilian passenger pressure cabin.
    cylinder('Passenger pressure hull',(0,0,0),1.20,6.60,'Ivory','Y',vertices=32)
    for side in (-1,1):
        y=side*3.75
        cylinder('Tapered vestibule',(0,y,0),.84,.94,'Teal','Y',1.18 if side<0 else .84,vertices=24)
        ring('Docking collar',(0,side*4.25,0),.69,.11,'Steel','Y')
        cylinder('Pressure hatch',(0,side*4.28,0),.54,.12,'Graphite','Y',vertices=24)
        for i in range(4):
            a=i*PI/2
            box('Docking alignment lug',(.75*math.cos(a),side*4.31,.75*math.sin(a)),(.18,.20,.18),'Ochre')
        for y in (-2.40,-1.60,-.80,0,.80,1.60,2.40):
            box('Passenger window surround',(side*1.10,y,.36),(.20,.61,.42),'Graphite',.08)
            box('Panoramic cabin glazing',(side*1.21,y,.36),(.05,.48,.28),'Cyan',.025)
        beam('Nacelle mounting spar',(side*.82,.98,-.55),(side*2.05,1.24,-.44),.34,'Steel')
        box('Civilian propulsion nacelle',(side*2.02,1.23,-.42),(.91,2.68,.82),'Teal',.20)
        cylinder('Nacelle forward cap',(side*2.02,-.19,-.42),.37,.23,'Ivory','Y',vertices=24)
        engine(side*2.02,2.66,-.42,.68)
        box('Passenger service stripe',(side*1.19,0,-.32),(.07,5.25,.14),'Ochre')
        for y in (-1.86,1.86):
            box('Equipment access hatch',(side*.72,y,-.94),(.55,.72,.12),'Slate')
    for y in (-2.92,2.92):
        ring('Pressure section seam',(0,y,0),1.18,.055,'Steel','Y')
    box('Dorsal equipment spine',(0,.52,1.20),(.74,2.80,.28),'Teal')
    beam('Navigation aerial',(0,-2.2,1.05),(0,-2.2,1.83),.08,'Steel')
    cylinder('Navigation beacon',(0,-2.2,1.86),.13,.12,'Amber')



def surface_storm_shelter():
    # Buried-looking ribbed shell with visible protected entrance and open cutaway.
    box('Anchored foundation',(0,0,.12),(6.4,5.2,.24),'Graphite')
    box('Interior deck',(0,0,.28),(5.6,4.5,.18),'Slate')
    for y in (-1.9,-.95,0,.95,1.9):
        points=[(-2.55,y,.35),(-2.55,y,1.4),(-1.8,y,2.45),(-.8,y,2.9),(.8,y,2.9),(1.8,y,2.45),(2.55,y,1.4),(2.55,y,.35)]
        for a,b in zip(points,points[1:]): beam('Pressure shell rib',a,b,.19,'Steel')
        for x in (-2.65,2.65):
            box('Ground anchor',(x,y,.22),(.48,.45,.22),'Ochre')
    for y in (-1.4,-.5,.4,1.3):
        box('Overhead dust armor',(0,y,2.98),(1.7,.88,.12),'Ivory')
        for x in (-2.58,2.58): box('Shielded lower wall',(x,y,.9),(.18,.88,1.02),'Teal')
    for x in (-1.65,1.65):
        box('Emergency supply locker',(x,1.55,.91),(.68,.64,1.05),'Ochre')
        box('Locker handle',(x,1.19,.95),(.18,.08,.08),'Graphite')
        box('Fold-down bench',(x,-.7,.68),(.7,1.55,.15),'Ivory')
        for y in (-1.28,-.1): box('Bench bracket',(x,y,.45),(.15,.15,.42),'Steel')
    box('Rear protective bulkhead',(0,2.2,1.35),(5.0,.24,2.12),'Teal')
    box('Entrance threshold',(0,-2.38,.32),(2.1,.55,.14),'Ochre')
    for x in (-1.08,1.08): box('Entrance jamb',(x,-2.24,1.28),(.23,.38,2.05),'Ivory')
    box('Entrance header',(0,-2.24,2.3),(2.4,.38,.32),'Ivory')
    box('Shelter beacon',(0,-2.45,2.48),(.64,.15,.15),'Amber')
    box('Emergency control console',(1.35,1.38,1.48),(.45,.25,.30),'Graphite')
    box('Control display',(1.35,1.23,1.48),(.30,.04,.16),'Cyan')


def material_recovery_line():
    # Open sorting conveyor with three independent collection bins and overhead optical scanner.
    box('Sorting line base',(0,0,.13),(6.2,3.8,.26),'Graphite')
    for x in (-2.4,-.8,.8,2.4):
        for y in (-.60,.60): box('Conveyor support',(x,y,.55),(.22,.22,.85),'Steel')
    box('Belt bed',(0,0,.99),(5.55,1.6,.20),'Teal')
    box('Continuous belt',(0,0,1.13),(5.35,1.34,.08),'Graphite')
    for i in range(15): cylinder('Belt roller',(-2.55+i*.36,0,1.18),.075,1.38,'Slate','Y',vertices=12)
    for x in (-1.75,0,1.75):
        box('Recovery bin floor',(x,1.36,.32),(1.42,1.12,.14),'Ivory')
        for dx in (-.67,.67): box('Bin side',(x+dx,1.36,.69),(.12,1.12,.68),'Teal')
        box('Bin face',(x,1.90,.69),(1.42,.12,.68),'Teal')
        box('Sorting class indicator',(x,1.98,.82),(.42,.05,.16),'Amber' if x==0 else 'Cyan')
        ramp=box('Drop chute',(x,.8,1.05),(1.08,.70,.12),'Steel');ramp.rotation_euler.x=-.30
        for y in (-.82,.82): box('Scanner upright',(x,y,1.7),(.17,.17,1.45),'Ochre')
        box('Scanner bridge',(x,0,2.43),(.40,1.85,.22),'Ochre')
        box('Optical head',(x,0,2.23),(.35,.53,.19),'Graphite')
        box('Detector window',(x,0,2.12),(.25,.40,.04),'Cyan')
    for i in range(5):
        obj=box('Unsorted material',(-2.3+i*.42,(-1)**i*.24,1.34),(.26,.29,.18),'Copper' if i%2 else 'Ivory');obj.rotation_euler.z=i*.47
    box('Control pedestal',(2.35,-1.32,.79),(.44,.54,1.23),'Graphite')
    box('Sort status display',(2.35,-1.61,1.30),(.30,.06,.20),'Cyan')


def habitat_archive_room():
    # Open public reading room with individually editable shelving and archive terminals.
    box('Public reading deck',(0,0,.12),(7.6,5.8,.24),'Slate')
    box('Rear archive wall',(0,2.66,1.55),(7.5,.18,2.85),'Ivory')
    for x in (-2.65,0,2.65):
        for dx in (-1.02,1.02): box('Archive shelf upright',(x+dx,2.25,1.50),(.13,.66,2.55),'Teal')
        for z in (.40,1.03,1.66,2.29):
            box('Archive shelf',(x,2.25,z),(2.12,.66,.10),'Steel')
            for i in range(5):
                h=.30+.05*((i+int(z*10))%3)
                box('Catalog cartridge',(x-.76+i*.36,2.12,z+.06+h/2),(.27,.38,h),('Ivory','Ochre','Teal','Copper','Slate')[i],.025)
    for x in (-1.83,1.83):
        box('Reading table',(x,-.35,.86),(2.0,1.35,.13),'Ivory')
        for dx in (-.78,.78):
            for dy in (-.47,.47): box('Table leg',(x+dx,-.35+dy,.47),(.12,.12,.68),'Steel')
        for y in (-1.45,.75):
            box('Reader seat',(x,y,.52),(.58,.58,.14),'Teal')
            box('Seat pedestal',(x,y,.32),(.20,.20,.33),'Graphite')
            box('Seat back',(x,y+(-.25 if y<0 else .25),.83),(.58,.12,.59),'Teal')
        for dx in (-.52,.52):
            box('Reader terminal base',(x+dx,-.35,.97),(.42,.38,.08),'Graphite')
            screen=box('Reader display',(x+dx,-.26,1.22),(.44,.08,.43),'Cyan');screen.rotation_euler.x=-.18
    cylinder('Central index pedestal',(0,-1.83,.63),.38,.98,'Teal',vertices=12)
    box('Index display',(0,-1.83,1.18),(.70,.54,.12),'Cyan')
    for x in (-3.43,3.43):
        box('Reading area lamp post',(x,-1.5,1.55),(.12,.12,2.65),'Steel')
        box('Reading area luminaire',(x,-1.5,2.9),(.68,.36,.14),'Ivory')
        box('Reading light diffuser',(x,-1.5,2.80),(.52,.26,.05),'Cyan')



def surface_cargo_cableway():
    # Twin braced pylons support a hanging freight gondola and moving cable.
    for x in (-3.8,3.8):
        box('Pylon foundation',(x,0,.15),(1.75,2.4,.3),'Graphite')
        for y in (-.75,.75):
            beam('Tapered pylon leg',(x,y,.3),(x,y*.37,3.9),.24,'Ivory')
            beam('Diagonal pylon brace',(x,y,.8),(x,-y*.4,3.1),.13,'Steel')
        box('Sheave crosshead',(x,0,4),(1.1,1.65,.32),'Ochre')
        for y in (-.48,.48):
            cylinder('Cable return sheave',(x,y,4.18),.45,.19,'Steel','Y',vertices=24)
            cylinder('Sheave hub',(x,y-.12,4.18),.13,.08,'Copper','Y')
        box('Safety beacon',(x,0,4.38),(.22,.25,.22),'Amber')
    for y in (-.48,.48):
        for x1,x2 in zip((-3.8,-1.9,0,1.9),(-1.9,0,1.9,3.8)):
            z=lambda x:3.96+.22*(x/3.8)**2
            beam('Tensioned aerial cable',(x1,y,z(x1)),(x2,y,z(x2)),.055,'Graphite')
    box('Gondola travel carriage',(0,0,3.78),(1.0,1.25,.24),'Ochre')
    for x in (-.44,.44):
        beam('Suspension strut',(x,0,3.68),(x,0,2.3),.16,'Steel')
    box('Suspended freight bed',(0,0,1.77),(1.72,1.6,.24),'Teal')
    for x in (-.72,.72):
        box('Retention rail',(x,0,2.13),(.12,1.6,.64),'Ochre')
    for x in (-.39,.39):
        box('Freight cassette',(x,0,2.09),(.66,1.16,.48),'Ivory')
    box('Delivery indicator',(0,-.84,1.92),(.38,.05,.10),'Cyan')


def eva_suit_service_bay():
    # Open-front maintenance alcove with three independent suit-support stands.
    box('Service deck',(0,0,.13),(6.6,4.1,.26),'Slate')
    box('Utility backplane',(0,1.84,1.55),(6.6,.24,2.85),'Ivory')
    for x in (-2.05,0,2.05):
        box('Suit locker frame',(x,1.48,2.75),(1.7,.58,.25),'Teal')
        for dx in (-.79,.79):
            box('Locking upright',(x+dx,1.48,1.5),(.13,.58,2.5),'Steel')
        cylinder('Turntable foot',(x,.75,.35),.63,.18,'Graphite',vertices=16)
        box('Backpack shell',(x,1.12,1.64),(.70,.42,.92),'Ochre',.10)
        box('Chest pressure shell',(x,.75,1.65),(.79,.50,.82),'Ivory',.17)
        bpy.ops.mesh.primitive_uv_sphere_add(segments=20,ring_count=12,radius=.33,location=(x,.72,2.32))
        finish(bpy.context.object,'Helmet pressure shell','Ivory')
        visor=box('Helmet visor',(x,.40,2.34),(.49,.17,.25),'Teal',.07)
        for side in (-1,1):
            beam('Upper sleeve',(x+side*.38,.76,1.88),(x+side*.60,.62,1.48),.20,'Ivory')
            beam('Glove assembly',(x+side*.60,.62,1.48),(x+side*.58,.45,1.20),.17,'Graphite')
            beam('Pressure trouser',(x+side*.19,.75,1.23),(x+side*.24,.75,.65),.29,'Ivory')
            box('Magnetic boot',(x+side*.24,.62,.53),(.33,.57,.22),'Graphite')
        box('Oxygen and battery monitor',(x,1.19,2.65),(.63,.10,.18),'Cyan')
    box('Service bench',(0,-1.1,.83),(2.5,.65,.15),'Ivory')
    for x in (-1.03,1.03):
        box('Bench pedestal',(x,-1.1,.46),(.18,.48,.64),'Steel')
    for x in (-.7,0,.7):
        cylinder('Spare oxygen cartridge',(x,-1.1,1.04),.12,.31,'Copper',vertices=16)


def aquaculture_nursery():
    # Open raceway tanks with visible aeration, filter banks and feed hoppers.
    box('Wet service deck',(0,0,.12),(7.8,5.8,.24),'Slate')
    for x in (-2.1,2.1):
        box('Raceway floor',(x,0,.42),(2.35,4.5,.20),'Ivory')
        for dx in (-1.15,1.15):
            box('Raceway long wall',(x+dx,0,.91),(.18,4.5,.88),'Teal')
            box('Non-slip rim',(x+dx,0,1.36),(.25,4.6,.13),'Steel')
        for y in (-2.16,2.16):
            box('Raceway end wall',(x,y,.91),(2.28,.18,.88),'Teal')
        box('Water surface representation',(x,0,1.13),(2.07,4.08,.035),'Ocean',0)
        for i in range(6):
            y=-1.65+i*.61
            fish=box('Juvenile fish silhouette',(x+(-1)**i*.43,y,1.17),(.18,.40,.07),'Ivory',.025)
            fish.rotation_euler.z=(-1)**i*.35
            tail=box('Juvenile tail',(x+(-1)**i*.43,y+.23,1.17),(.19,.10,.04),'Sand',.012)
            tail.rotation_euler.z=.4
        for y in (-1.4,0,1.4):
            cylinder('Aeration diffuser',(x,y,1.18),.15,.045,'Cyan',vertices=12)
        cylinder('Feed silo',(x,2.42,1.79),.35,.72,'Ochre',radius2=.26,vertices=16)
        beam('Feed nozzle',(x,2.42,1.43),(x,1.83,1.35),.12,'Copper')
    for x in (-.43,.43):
        cylinder('Biofilter column',(x,2.15,1.2),.30,1.8,'Ivory',vertices=16)
        ring('Filter service collar',(x,2.15,1.9),.28,.04,'Ochre')
        beam('Circulation return',(x,2.15,.5),(x*4.7,2.15,.5),.15,'Copper')
    box('Water quality console',(0,-1.9,.83),(.60,.47,1.14),'Graphite')
    box('Water quality display',(0,-2.16,1.22),(.45,.05,.24),'Cyan')



def surface_crawler_crane():
    # Mobile heavy-lift chassis, elevated lattice boom and freely inspectable hook.
    box('Slewing chassis',(0,0,.72),(2.8,4.8,.60),'Graphite',.18)
    for side in (-1,1):
        x=side*1.47
        box('Track belt',(x,0,.45),(.68,4.75,.72),'Graphite',.20)
        for y in (-1.86,-1.24,-.62,0,.62,1.24,1.86):
            cylinder('Track road wheel',(x+side*.34,y,.45),.30,.12,'Steel','X',vertices=16)
        for j in range(18):
            y=-2.16+j*.254
            box('Track top grouser',(x,y,.84),(.72,.12,.09),'Steel',.015)
        beam('Outrigger beam',(side*.95,.9,.72),(side*2.3,.9,.72),.23,'Ochre')
        cylinder('Outrigger jack',(side*2.3,.9,.42),.14,.70,'Steel')
        box('Outrigger foot',(side*2.3,.9,.10),(.54,.54,.16),'Graphite')
    cylinder('Slew bearing',(0,.25,1.15),.98,.35,'Steel',vertices=32)
    box('Rotating upper works',(0,.40,1.56),(2.1,2.1,.60),'Ochre',.14)
    box('Operator cab',(-.78,-.25,2.03),(.72,1.12,.85),'Ivory',.10)
    box('Cab windscreen',(-.78,-.83,2.13),(.56,.045,.42),'Teal')
    box('Counterweight',(0,1.35,1.75),(1.76,.66,.83),'Graphite')
    for x in (-.34,.34):
        beam('Lattice boom lower chord',(x,-.24,1.84),(x,-3.78,5.34),.15,'Ochre')
        beam('Lattice boom upper chord',(x,.16,2.24),(x,-3.38,5.74),.15,'Ochre')
        for i in range(5):
            t=i/5
            beam('Lattice diagonal',(x,-.24-3.54*t,1.84+3.50*t),(x,.16-3.54*(t+.2),2.24+3.50*(t+.2)),.09,'Steel')
    for i in range(6):
        t=i/5
        beam('Cross member',(-.34,-.24-3.54*t,1.84+3.50*t),(.34,-.24-3.54*t,1.84+3.50*t),.11,'Steel')
    cylinder('Winch drum',(0,.75,2.0),.29,.78,'Copper','X')
    cylinder('Head sheave',(0,-3.62,5.54),.25,.32,'Steel','X')
    beam('Load line',(0,-3.75,5.45),(0,-3.75,2.95),.045,'Graphite')
    box('Hook block',(0,-3.75,2.82),(.32,.32,.26),'Ochre')
    ring('Load attachment',(0,-3.75,2.51),.20,.065,'Steel','X')


def habitat_fire_suppression_station():
    # Open-front emergency utility alcove with pumps, hose reels and accessible controls.
    box('Service plinth',(0,0,.12),(5.8,3.4,.24),'Slate')
    box('Utility backplane',(0,1.48,1.55),(5.8,.24,2.9),'Ivory')
    for x in (-2.68,2.68):
        box('Side pilaster',(x,1.23,1.54),(.32,.66,2.85),'Graphite')
        box('Emergency marker',(x,.87,2.63),(.20,.05,.32),'Amber')
    for x in (-1.95,-.95):
        cylinder('Suppression reservoir',(x,.73,1.28),.40,1.9,'Ochre',vertices=24)
        cylinder('Reservoir valve',(x,.73,2.34),.12,.24,'Copper')
        ring('Reservoir retaining strap',(x,.73,1.68),.40,.045,'Steel')
        beam('Reservoir feed',(x,.73,2.44),(x,.73,2.69),.11,'Copper')
    beam('Shared feed header',(-1.95,.73,2.69),(1.93,.73,2.69),.13,'Copper')
    for x in (.63,1.92):
        cylinder('Hose reel hub',(x,1.12,1.83),.49,.26,'Graphite','Y',vertices=24)
        for j in range(4):
            ring('Wound hose',(x,.98-j*.085,1.83),.38,.052,'Ochre','Y')
        cylinder('Reel face',(x,.62,1.83),.45,.065,'Steel','Y',vertices=24)
        beam('Hose drop',(x,.68,1.47),(x,.68,.68),.095,'Ochre')
        cylinder('Hose nozzle',(x,.68,.52),.09,.25,'Steel')
    box('Pump skid',(0,.68,.35),(1.10,1.24,.25),'Graphite')
    cylinder('Pump motor',(0,.64,.77),.31,.68,'Teal','Y')
    cylinder('Pump volute',(0,.15,.77),.41,.29,'Steel','Y')
    box('Emergency isolation console',(-.52,-.76,.93),(.75,.55,1.35),'Graphite')
    box('Isolation display',(-.52,-1.06,1.40),(.48,.04,.24),'Cyan')
    for i in range(3):
        cylinder('Status button',(-.72+i*.20,-1.07,1.13),.065,.06,'Amber','Y',vertices=12)
    box('Overhead alert panel',(0,1.25,2.83),(1.25,.11,.24),'Ochre')
    box('Alert light strip',(0,1.18,2.83),(.82,.035,.10),'Amber')


def orbital_gravity_centrifuge():
    # Open mechanical ring with opposite laboratory capsules and an axial service hub.
    cylinder('Axial mounting hub',(0,0,0),.78,2.6,'Graphite','Y',vertices=16)
    for y in (-1.35,1.35):
        ring('Axial bearing collar',(0,y,0),.70,.10,'Copper','Y')
        cylinder('Service hatch',(0,y*1.06,0),.46,.08,'Ivory','Y',vertices=16)
    for y in (-.42,.42):
        ring('Outer centrifuge rail',(0,y,0),3.40,.16,'Steel','Y')
        ring('Inner centrifuge rail',(0,y,0),2.89,.10,'Teal','Y')
    for i in range(16):
        a=i*2*PI/16
        x,z=math.cos(a),math.sin(a)
        beam('Ring cross brace',(x*3.40,-.42,z*3.40),(x*3.40,.42,z*3.40),.13,'Ochre')
        beam('Radial web',(x*2.89,-.42,z*2.89),(x*3.40,.42,z*3.40),.10,'Steel')
    for side in (-1,1):
        for y in (-.42,.42):
            beam('Radial structural spoke',(side*.68,y,0),(side*2.78,y,0),.21,'Ivory')
            beam('Spoke diagonal',(side*.68,y,0),(side*2.78,-y,.40),.12,'Steel')
        box('Laboratory capsule',(side*3.12,0,0),(.86,1.38,1.18),'Ivory',.18)
        box('Laboratory window',(side*3.12,-.71,.16),(.57,.055,.40),'Teal',.05)
        box('Capsule power bus',(side*3.62,0,0),(.18,.94,.70),'Ochre')
        box('Capsule identification lamp',(side*3.12,-.75,-.30),(.32,.04,.10),'Cyan')
    for z in (-1.20,1.20):
        box('Hub avionics rack',(0,0,z),(.84,.86,.42),'Teal')
        box('Hub status panel',(0,-.46,z),(.42,.05,.15),'Cyan')



def colony_tram():
    # Low-floor shuttle, two independent bogies, walk-through doors and overhead power pickup.
    box('Low floor chassis',(0,0,.63),(2.15,6.5,.42),'Graphite',.15)
    box('Passenger roof',(0,0,2.55),(2.16,6.3,.32),'Ivory',.16)
    for y in (-2.35,2.35):
        box('Bogie frame',(0,y,.38),(1.64,1.05,.24),'Slate')
        for dy in (-.38,.38):
            cylinder('Wheel axle',(0,y+dy,.37),.10,2.06,'Steel','X',vertices=16)
            for x in (-.96,.96):
                cylinder('Rail wheel',(x,y+dy,.37),.34,.22,'Graphite','X',vertices=20)
                cylinder('Wheel hub',(x*1.13,y+dy,.37),.16,.05,'Steel','X',vertices=12)
    for side in (-1,1):
        x=side*1.03
        box('Side lower sill',(x,0,1.03),(.14,5.9,.45),'Teal')
        for y in (-2.3,-1.48,1.48,2.3):
            box('Passenger window',(x,y,1.90),(.095,.69,.74),'Cyan',.05)
        for y in (-2.82,-1.90,-.98,.98,1.90,2.82):
            box('Window mullion',(x,y,1.93),(.15,.13,1.1),'Ivory')
        for y in (-.47,.47):
            box('Sliding door leaf',(x,y,1.68),(.16,.89,1.65),'Steel')
            box('Door window',(x*1.09,y,2.0),(.045,.59,.54),'Teal')
        box('Door boarding step',(x*1.13,0,.68),(.27,1.84,.13),'Ochre')
    for side in (-1,1):
        y=side*3.0
        box('Driver cab end',(0,y,1.57),(2.06,.55,1.84),'Ivory',.21)
        box('Driver windscreen',(0,side*3.29,2.02),(1.48,.06,.58),'Teal',.10)
        for x in (-.66,.66):
            box('Marker lamp',(x,side*3.31,1.13),(.25,.08,.15),'Cyan')
        box('Coupler',(0,side*3.48,.68),(.40,.52,.25),'Steel')
    box('Power pickup base',(0,0,2.79),(.82,1.14,.20),'Graphite')
    for x in (-.28,.28):
        beam('Pantograph lower link',(x,-.45,2.86),(x,.22,3.35),.09,'Ochre')
        beam('Pantograph upper link',(x,.22,3.35),(x,-.08,3.82),.09,'Steel')
    box('Collector strip',(0,-.08,3.84),(1.64,.20,.09),'Graphite')


def orbital_tether_spool():
    # Exposed cable drum suspended within a load-bearing frame with controlled payout guide.
    box('Mounting keel',(0,0,-1.68),(4.7,3.3,.38),'Slate')
    for x in (-1.92,1.92):
        for y in (-1.25,1.25):
            beam('Bearing tower leg',(x,y,-1.48),(x,0,.10),.32,'Ivory')
            box('Deck mounting foot',(x,y,-1.45),(.63,.62,.15),'Ochre')
        cylinder('Axle bearing',(x,0,0),.53,.38,'Steel','X')
    cylinder('Tether reel barrel',(0,0,0),1.02,2.95,'Graphite','X',vertices=32)
    for x in (-1.57,1.57):
        cylinder('Drum flange',(x,0,0),1.37,.18,'Teal','X',vertices=32)
        ring('Flange reinforcement',(x,0,0),1.24,.07,'Steel','X')
        cylinder('Axle cap',(x*1.30,0,0),.29,.22,'Ochre','X',vertices=16)
    for i in range(21):
        ring('Wound tether turn',(-1.38+i*.138,0,0),1.09,.061,'Copper','X')
    for x in (-1.6,1.6):
        beam('Payout guide support',(x,1.15,-1.46),(x,1.81,.78),.19,'Steel')
    beam('Guide traversal rail',(-1.72,1.81,.78),(1.72,1.81,.78),.15,'Ochre')
    box('Traversing payout carriage',(.6,1.81,.78),(.48,.48,.45),'Graphite')
    ring('Tether guide eye',(.6,2.08,.78),.16,.055,'Steel','Y')
    beam('Paid out tether',(.60,.80,.75),(.60,2.1,.78),.045,'Copper')
    box('Motor controller',(-1.0,-1.20,-1.09),(.9,.55,.62),'Ivory')
    box('Controller status',(-1.0,-1.49,-.98),(.56,.05,.17),'Cyan')


def habitat_seed_bank():
    # Walkable conservation vault with individual cold-storage drawers and inventory station.
    box('Vault deck',(0,0,-.14),(6.2,5.6,.28),'Slate')
    box('Rear insulated wall',(0,2.55,1.42),(6.2,.25,2.84),'Ivory')
    for side in (-1,1):
        x=side*2.46
        box('Storage rack frame',(x,.45,1.36),(1.0,3.9,2.72),'Graphite',.09)
        for i in range(4):
            for j in range(3):
                y=-.91+j*1.28; z=.47+i*.61
                box('Sealed seed drawer',(x-side*.04,y,z),(.86,1.12,.48),'Teal',.06)
                box('Drawer index plate',(x-side*.49,y,z+.09),(.04,.38,.12),'Cyan')
                box('Recessed pull',(x-side*.53,y,z-.11),(.10,.40,.07),'Steel')
        box('Rack thermal manifold',(x,2.45,1.48),(.40,.32,2.54),'Steel')
    box('Inventory desk',(0,1.50,.91),(1.58,.80,.20),'Ivory')
    for x in (-.59,.59):
        box('Desk leg',(x,1.50,.44),(.17,.60,.88),'Steel')
    box('Inventory terminal',(0,1.67,1.28),(.75,.24,.51),'Graphite')
    box('Terminal display',(0,1.53,1.30),(.60,.04,.35),'Cyan')
    for x in (-.55,.55):
        cylinder('Sample vial',(x,1.37,1.10),.08,.18,'Teal',vertices=16)
        cylinder('Vial cap',(x,1.37,1.21),.09,.04,'Ochre',vertices=16)
    for x in (-1.1,1.1):
        box('Aisle lighting strip',(x,0,.025),(.08,4.8,.04),'Cyan')
    box('Cold storage compressor',(0,2.20,2.22),(1.65,.50,.58),'Steel')
    for x in (-.55,0,.55):
        box('Compressor vent',(x,1.93,2.23),(.36,.06,.36),'Graphite')



def atmospheric_balloon_probe():
    # Free-floating atmospheric survey platform, segmented lifting envelope and suspended instrument gondola.
    bpy.ops.mesh.primitive_uv_sphere_add(segments=32,ring_count=16,location=(0,0,4.8))
    envelope=bpy.context.object
    envelope.scale=(1.55,1.55,2.02)
    bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
    finish(envelope,'Lifting envelope','Ivory')
    for i in range(8):
        a=i*PI/4
        for j in range(10):
            t0=.12+j*(PI-.24)/10; t1=.12+(j+1)*(PI-.24)/10
            def pt(t): return (1.56*math.sin(t)*math.cos(a),1.56*math.sin(t)*math.sin(a),4.8+2.03*math.cos(t))
            beam('Envelope load tape',pt(t0),pt(t1),.055,'Ochre')
        beam('Suspension line',(.50*math.cos(a),.50*math.sin(a),2.83),(.65*math.cos(a),.65*math.sin(a),1.31),.045,'Steel')
    cylinder('Envelope valve',(0,0,2.78),.32,.20,'Teal')
    box('Gondola chassis',(0,0,1.02),(1.52,1.22,.34),'Graphite')
    box('Instrument enclosure',(0,0,1.29),(1.15,.85,.45),'Teal',.10)
    for x in (-.92,.92):
        box('Solar wing',(x,0,1.1),(.58,1.20,.10),'Steel')
        for y in (-.38,0,.38):
            box('Photovoltaic cell',(x,y,1.17),(.48,.32,.035),'Ocean')
    cylinder('Sampling inlet',(0,-.59,.80),.13,.44,'Copper','Y')
    beam('Instrument boom',(0,0,.87),(0,0,-.05),.07,'Steel')
    cylinder('Pressure sensor',(0,0,-.12),.19,.21,'Ochre')
    cylinder('Telemetry beacon',(0,.34,1.69),.10,.22,'Cyan')


def habitat_communal_galley():
    # Open walkable kitchen with preparation island, ovens, sinks and a serving pass.
    box('Galley floor',(0,0,-.12),(7.2,5.6,.24),'Slate')
    box('Rear utility wall',(0,2.66,1.45),(7.2,.22,2.90),'Ivory')
    box('Service counter',(0,1.96,.48),(6.45,1.02,.96),'Graphite')
    box('Stainless worktop',(0,1.96,1.01),(6.55,1.10,.14),'Steel')
    for x in (-2.25,-1.23,-.21):
        box('Oven face',(x,1.38,.57),(.87,.10,.72),'Ivory')
        box('Oven inspection window',(x,1.30,.64),(.60,.06,.34),'Teal')
        box('Oven handle',(x,1.23,.91),(.56,.09,.07),'Steel')
        cylinder('Cooking zone',(x,1.96,1.10),.31,.04,'Graphite')
    for x in (1.2,2.2):
        box('Sink inset',(x,1.96,1.09),(.70,.74,.05),'Graphite')
        beam('Faucet riser',(x,2.34,1.09),(x,2.34,1.53),.08,'Steel')
        beam('Faucet spout',(x,2.34,1.53),(x,2.0,1.53),.08,'Steel')
    box('Prep island',(0,-.25,.45),(2.75,1.25,.90),'Teal')
    box('Island worktop',(0,-.25,.96),(2.90,1.39,.12),'Steel')
    for x in (-.94,-.34,.26,.86):
        box('Ingredient drawer',(x,-.90,.48),(.49,.07,.44),'Ivory')
        box('Drawer pull',(x,-.96,.58),(.29,.08,.06),'Ochre')
    box('Serving pass',(2.72,-1.05,.51),(1.25,2.3,1.02),'Graphite')
    box('Serving counter',(2.72,-1.05,1.08),(1.38,2.45,.12),'Steel')
    for y in (-1.75,-1.08,-.41):
        cylinder('Stacked serving plates',(2.72,y,1.19),.24,.13,'Ivory')
    for x in (-2.4,-.9,.6,2.1):
        box('Overhead cabinet',(x,2.42,2.12),(1.30,.52,.60),'Teal')
        box('Task lamp',(x,2.20,1.78),(1.0,.12,.05),'Cyan')


def subsea_cable_repeater():
    # Seabed telecommunications node on a protective sled with dual cable termination cones.
    for x in (-1.2,1.2):
        box('Seabed skid runner',(x,0,.18),(.28,5.1,.36),'Ochre')
        for y in (-2.05,2.05):
            beam('Runner nose',(x,y,.20),(x,y*1.23,.50),.24,'Ochre')
    for y in (-1.65,0,1.65):
        box('Sled crossmember',(0,y,.37),(2.65,.30,.26),'Steel')
    cylinder('Pressure repeater body',(0,0,1.10),.68,2.85,'Teal','Y',vertices=32)
    for y in (-1.25,1.25):
        ring('Pressure flange',(0,y,1.10),.68,.10,'Steel','Y')
        cylinder('Cable strain relief',(0,y*1.48,1.10),.34,.75,'Graphite','Y',.22)
        beam('Protected cable',(0,y*1.75,1.10),(0,y*2.30,.78),.12,'Copper')
    for x in (-.98,.98):
        for y in (-1.45,1.45):
            beam('Protective cage upright',(x,y,.43),(x,y,1.95),.15,'Ochre')
        beam('Cage top rail',(x,-1.45,1.95),(x,1.45,1.95),.15,'Ochre')
    for y in (-1.45,1.45):
        beam('Cage roof crossbrace',(-.98,y,1.95),(.98,y,1.95),.15,'Steel')
    box('ROV service panel',(0,-.36,1.84),(.82,.71,.21),'Ivory')
    for x in (-.25,0,.25):
        cylinder('Wet-mate connector',(x,-.36,1.99),.08,.17,'Copper')
    box('Repeater status strip',(0,-.76,1.86),(.60,.05,.13),'Cyan')



def surface_medical_rover():
    # Six-wheel rescue vehicle with an accessible rear patient compartment.
    box('Rescue chassis',(0,0,.72),(2.65,5.2,.48),'Graphite',.15)
    box('Cab shell',(0,-1.63,1.45),(2.35,1.55,1.35),'Ivory',.18)
    box('Windscreen',(0,-2.43,1.73),(1.92,.08,.55),'Ocean')
    box('Cab light bar',(0,-1.52,2.2),(1.45,.25,.16),'Cyan')
    box('Patient deck',(0,.88,1.02),(2.27,3.12,.15),'Steel')
    box('Patient roof',(0,.88,2.54),(2.42,3.24,.17),'Ivory')
    for side in (-1,1):
        x=side*1.38
        for y in (-1.75,0,1.76):
            cylinder('All terrain tire',(x,y,.54),.54,.42,'Graphite','X')
            cylinder('Wheel hub',(x+side*.23,y,.54),.25,.09,'Steel','X')
            for k in range(10):
                a=k*PI/5
                tread=box('Tread block',(x,y+.53*math.cos(a),.54+.53*math.sin(a)),(.40,.15,.11),'Slate')
                tread.rotation_euler.x=a-PI/2
        for y in (-.50,2.27):
            beam('Cabin corner post',(side*1.11,y,1.10),(side*1.11,y,2.54),.13,'Ivory')
        box('Lower patient wall',(side*1.12,.90,1.43),(.13,2.80,.63),'Ivory')
        box('Rescue stripe',(side*1.205,.90,1.44),(.045,2.65,.19),'Ochre')
        box('Cab side glass',(side*1.19,-1.68,1.75),(.07,.88,.46),'Ocean')
        box('Side marker',(side*1.22,1.92,2.4),(.08,.25,.12),'Amber')
    box('Stretcher cushion',(-.45,.98,1.43),(.66,1.95,.19),'Teal')
    for y in (.25,1.72):
        beam('Stretcher mount',(-.45,y,1.09),(-.45,y,1.34),.16,'Steel')
    box('Medical monitor',(.72,.05,1.83),(.40,.15,.31),'Cyan')
    ramp=box('Lowered loading ramp',(0,2.95,.66),(1.52,1.52,.12),'Steel')
    ramp.rotation_euler.x=-.53
    for x in (-.65,.65):
        beam('Ramp edge',(x,2.29,1.03),(x,3.61,.29),.09,'Ochre')


def tidal_control_gate():
    # Two independent sluice leaves with exposed rack drives and elevated service walkway.
    box('Concrete sill',(0,0,.16),(8.4,3.25,.32),'Stone')
    for x in (-3.88,0,3.88):
        box('Reinforced pier',(x,0,1.85),(.60,2.35,3.7),'Stone',.12)
        box('Pier cap',(x,0,3.79),(.82,2.54,.24),'Steel')
        for y in (-.85,.85):
            beam('Pier edge reinforcement',(x,y,.38),(x,y,3.55),.14,'Steel')
    for x,z in ((-1.94,1.05),(1.94,2.10)):
        box('Independent sluice leaf',(x,0,z),(3.25,.22,1.95),'Teal',.035)
        for dz in (-.73,0,.73):
            box('Leaf horizontal stiffener',(x,-.18,z+dz),(3.12,.16,.14),'Steel')
        for dx in (-1.42,1.42):
            box('Gate guide',(x+dx,.07,1.78),(.14,.37,3.0),'Graphite')
            beam('Lift rack',(x+dx*.65,0,z+.78),(x+dx*.65,0,4.16),.14,'Steel')
            for k in range(8):
                box('Rack tooth',(x+dx*.65,-.09,3.0+k*.15),(.16,.09,.055),'Copper')
            cylinder('Drive pinion',(x+dx*.65,-.20,4.04),.24,.21,'Ochre','Y')
        box('Motor bridge',(x,0,4.00),(3.45,.72,.25),'Graphite')
        cylinder('Drive motor',(x,.17,4.26),.23,.70,'Teal','X')
    box('Service catwalk',(0,-1.15,3.78),(8.35,.77,.14),'Steel')
    for x in range(-4,5):
        beam('Guard post',(x,-1.49,3.87),(x,-1.49,4.66),.07,'Ochre')
    beam('Continuous safety rail',(-4,-1.49,4.66),(4,-1.49,4.66),.09,'Ochre')
    box('Gate control cabinet',(3.86,-.97,4.24),(.43,.34,.66),'Ivory')
    box('Gate position display',(3.86,-1.16,4.36),(.28,.04,.18),'Cyan')


def orbital_debris_net():
    # Concave triangulated debris capture net with an independent powered retrieval bus.
    box('Recovery avionics bus',(0,0,-1.26),(1.48,1.28,.82),'Ivory',.12)
    cylinder('Retrieval capstan',(0,0,-.66),.40,.38,'Copper')
    for x in (-.64,.64):
        cylinder('Stationkeeping nozzle',(x,0,-1.79),.21,.32,'Graphite','Z',.14)
        cylinder('Nozzle status',(x,0,-1.96),.12,.025,'Cyan')
    for i in range(6):
        a=i*PI/3
        p=(2.9*math.cos(a),2.9*math.sin(a),.82)
        q=(2.9*math.cos(a+PI/3),2.9*math.sin(a+PI/3),.82)
        beam('Capture frame perimeter',p,q,.15,'Ochre')
        beam('Deployable radial strut',(.55*math.cos(a),.55*math.sin(a),-.93),p,.13,'Steel')
        cylinder('Hinge actuator',p,.15,.23,'Graphite')
        box('Capture beacon',(p[0],p[1],1.01),(.19,.19,.12),'Cyan')
    def net_point(radius,i):
        a=i*PI/3
        return (radius*math.cos(a),radius*math.sin(a),-.36+1.18*(radius/2.9)**2)
    for k in range(1,6):
        radius=2.9*k/5
        for i in range(6):
            p=net_point(radius,i);q=net_point(radius,i+1)
            beam('Net circumferential strand',p,q,.045,'Copper')
            beam('Net radial strand',net_point(radius-2.9/5,i),p,.045,'Steel')
            if k>1:
                beam('Net diagonal strand',net_point(radius-2.9/5,i),q,.034,'Steel')
    for x in (-1.02,1.02):
        box('Power panel',(x,0,-1.12),(.45,1.18,.10),'Ocean')
        for y in (-.4,0,.4):
            box('Photovoltaic strip',(x,y,-1.055),(.37,.31,.035),'Teal')


MODELS={'fleet-tender':tender,'mining-drone':drone,'industrial-replicator':replicator,
        'cargo-mule':cargo_mule,'coolant-exchange-tower':cooling,'antimatter-containment-bottle':bottle,
        'warp-field-coil':coil,'impulse-thruster-module':thruster,'survey-probe':probe,'navigational-deflector':dish,'fleet-salvage-tug':tug,'cargo-shuttle':shuttle,
        'modular-station-hub':hub,'derelict-freighter':freighter,'resource-asteroid':asteroid,'asteroid-set':belt,
        'shuttle-landing-pad':pad,'armored-station-deck-tile':deck,'salvage-drone':salvage_drone,'light-carrier':carrier,
        'temperate-colony-planet':lambda:planet('Temperate colony'),'scarred-mining-moon':lambda:planet('Scarred mining moon'),
        'ringed-gas-giant':lambda:planet('Ringed gas giant'),
        'iron-choir-drakken-warship':iron_choir,'torpedo-corvette':torpedo_corvette,'flux-launcher-housing':flux_housing,
        'hydroponic-bay':hydroponic_bay,'pressure-airlock':pressure_airlock,'solar-power-array':solar_power_array,
        'water-reclamation-skid':water_reclamation_skid,'cargo-elevator':cargo_elevator,'crew-quarters-cutaway':crew_quarters_cutaway,
        'medical-triage-bay':medical_triage_bay,'cryogenic-freight-vault':cryogenic_freight_vault,'atmospheric-processor':atmospheric_processor,
        'surface-drill-rig':surface_drill_rig,'communications-relay-satellite':communications_relay_satellite,'emergency-escape-capsule':emergency_escape_capsule,
        'habitat-observation-dome':observation_dome,'surface-freight-rail-junction':freight_rail_junction,'geothermal-power-station':geothermal_station,
        'habitat-command-center':habitat_command_center,'surface-weather-station':surface_weather_station,'orbital-fuel-depot':orbital_fuel_depot,
        'regolith-sintering-kiln':regolith_sintering_kiln,'sample-analysis-laboratory':sample_analysis_laboratory,'modular-footbridge':modular_footbridge,
        'deepwater-survey-submersible':deepwater_survey_submersible,'orbital-optical-observatory':orbital_optical_observatory,'habitat-recreation-court':habitat_recreation_court,
        'habitat-market-hall':habitat_market_hall,'surface-seismic-array':surface_seismic_array,'orbital-passenger-ferry':orbital_passenger_ferry,
        'surface-storm-shelter':surface_storm_shelter,'material-recovery-line':material_recovery_line,'habitat-archive-room':habitat_archive_room,
        'surface-cargo-cableway':surface_cargo_cableway,'eva-suit-service-bay':eva_suit_service_bay,'aquaculture-nursery':aquaculture_nursery,
        'surface-crawler-crane':surface_crawler_crane,'habitat-fire-suppression-station':habitat_fire_suppression_station,'orbital-gravity-centrifuge':orbital_gravity_centrifuge,
        'colony-tram':colony_tram,'orbital-tether-spool':orbital_tether_spool,'habitat-seed-bank':habitat_seed_bank,
        'atmospheric-balloon-probe':atmospheric_balloon_probe,'habitat-communal-galley':habitat_communal_galley,'subsea-cable-repeater':subsea_cable_repeater,
        'surface-medical-rover':surface_medical_rover,'tidal-control-gate':tidal_control_gate,'orbital-debris-net':orbital_debris_net}


def bounds(objects):
    bpy.context.view_layer.update()
    pts=[o.matrix_world @ Vector(x) for o in objects if o.type=='MESH' for x in o.bound_box]
    return [Vector([fn(v[i] for v in pts) for i in range(3)]) for fn in (min,max)]


def stats(objects):
    lo,hi=bounds(objects)
    meshes=[o for o in objects if o.type=='MESH']
    for o in meshes: o.data.calc_loop_triangles()
    return {'meshObjects':len(meshes),'vertices':sum(len(o.data.vertices) for o in meshes),
            'triangles':sum(len(o.data.loop_triangles) for o in meshes),'materials':len({m.name for o in meshes for m in o.data.materials if m}),
            'dimensions':[round(v,4) for v in hi-lo]}


def render(objects, path):
    lo,hi=bounds(objects); center=(lo+hi)/2; span=max(hi-lo)
    scene=bpy.context.scene
    scene.render.engine='CYCLES';scene.cycles.device='CPU';scene.cycles.samples=12;scene.cycles.use_denoising=True
    scene.render.threads_mode='FIXED';scene.render.threads=3
    scene.world=bpy.data.worlds.new('Studio ambience'); scene.world.color=(.26,.30,.35)
    def face(obj): obj.rotation_euler=(center-obj.location).to_track_quat('-Z','Y').to_euler()
    for name,offset,power,color,size in [('Softbox',(2,-4,6),195,(.84,.91,1),3.5),('Warm edge',(-4,3,3),230,(1,.74,.47),2.3),('Fill',(-4,-2,1.5),88,(.50,.8,1),3)]:
        bpy.ops.object.light_add(type='AREA',location=center+Vector(offset)*span/2)
        lamp=bpy.context.object;lamp.name=name;lamp.data.energy=power*span**2;lamp.data.color=color;lamp.data.shape='DISK';lamp.data.size=size*span/2;face(lamp)
    bpy.ops.object.camera_add(location=center+Vector((1.12,-1.53,1.02))*span)
    camera=bpy.context.object;face(camera);scene.camera=camera;camera.data.type='ORTHO'
    bpy.context.view_layer.update()
    proj=[camera.matrix_world.inverted() @ (obj.matrix_world @ Vector(vertex)) for obj in objects if obj.type=='MESH' for vertex in obj.bound_box]
    w=max(p.x for p in proj)-min(p.x for p in proj);h=max(p.y for p in proj)-min(p.y for p in proj)
    camera.data.ortho_scale=max(w,h*1.2)*1.18;camera.data.clip_end=max(1000,span*8)
    scene.render.resolution_x=960;scene.render.resolution_y=800;scene.render.resolution_percentage=100
    scene.render.film_transparent=True;scene.render.image_settings.color_mode='RGBA';scene.render.image_settings.file_format='PNG'
    scene.render.filepath=str(path);bpy.ops.render.render(write_still=True)


def set_ports(count):
    assemblies=sorted((o for o in bpy.context.scene.objects if o.get('role')=='docking-port'),key=lambda o:o['port'])
    if not assemblies: raise ValueError('Reference has no authored docking assemblies')
    if len(assemblies)==count: return
    first=assemblies[0]
    for obj in assemblies[1:]:
        for child in list(obj.children_recursive): bpy.data.objects.remove(child,do_unlink=True)
        bpy.data.objects.remove(obj,do_unlink=True)
    for n in range(2,count+1):
        group=first.copy(); bpy.context.collection.objects.link(group)
        group.name=f'Docking Port {n} Assembly';group['port']=n
        group.matrix_local=Matrix.Rotation(-2*PI*(n-1)/count,4,'Y') @ first.matrix_local
        for base in first.children:
            child=base.copy();bpy.context.collection.objects.link(child);child.parent=group
            child.name=base.name.replace(' 1',' '+str(n))
            if child.get('name'): child['name']=str(child['name']).replace(' 1',' '+str(n))


def build(slug,dest,reference=None,scale=1,lod=1,paint=None,ports=None):
    dest.mkdir(parents=True,exist_ok=True)
    bpy.ops.wm.read_factory_settings(use_empty=True)
    for name,rgb,em in [('Graphite',(.040,.065,.083),0),('Slate',(.12,.18,.22),0),('Steel',(.33,.42,.46),0),
                        ('Teal',(.043,.25,.26),0),('Ivory',(.75,.79,.71),0),('Ochre',(.88,.39,.045),0),
                        ('Basalt',(.095,.072,.061),0),('Stone',(.34,.28,.23),0),('Sand',(.66,.51,.32),0),
                        ('Ocean',(.012,.14,.31),0),('Land',(.24,.40,.18),0),('Forest',(.035,.23,.12),0),
                        ('Ice',(.70,.82,.87),0),('Cloud',(.59,.66,.68),0),('Cyan',(.05,.64,.75),1.7),('Amber',(.98,.29,.035),1.4),('Copper',(.61,.25,.11),0)]:
        material(name,rgb,emission=em)
    if reference:
        bpy.ops.import_scene.gltf(filepath=str(reference))
    else:
        MODELS[slug]()
    if ports is not None: set_ports(ports)
    originals=list(bpy.context.scene.objects)
    meshes=[o for o in originals if o.type=='MESH']
    assert meshes
    if ports is not None:
        assert sorted(o.get('port') for o in originals if o.get('role')=='docking-port') == list(range(1,ports+1))
    root=bpy.data.objects.new('Sovereignty asset',None);bpy.context.collection.objects.link(root)
    for o in originals:
        if not o.parent:o.parent=root
    if reference:
        lo,hi=bounds(meshes)
        if (hi-lo).y < min((hi-lo).x,(hi-lo).z)*.84: root.rotation_euler.x=PI/2
    root.scale=(scale,)*3
    if paint:
        mat=next((slot.material for o in meshes for slot in o.material_slots if slot.material),None)
        rgb=tuple(int(paint[i:i+2],16)/255 for i in (0,2,4))
        mat.diffuse_color=(*rgb,1);mat.node_tree.nodes.get('Principled BSDF').inputs['Base Color'].default_value=(*rgb,1)
    if lod<1:
        for o in meshes:
            if len(o.data.polygons)>12: o.modifiers.new('LOD reduction','DECIMATE').ratio=lod
    bpy.context.view_layer.update()
    bpy.ops.object.select_all(action='DESELECT')
    for o in [root,*originals]: o.select_set(True)
    bpy.ops.export_scene.gltf(filepath=str(dest/'export.glb'),export_format='GLB',use_selection=True,export_apply=True,export_extras=True,
                              export_texcoords=True,export_cameras=False,export_lights=False)
    report=stats(meshes)
    render(meshes,dest/'preview.png')
    bpy.context.preferences.filepaths.save_version=0
    bpy.ops.wm.save_as_mainfile(filepath=str(dest/'model.blend'),compress=True)
    bpy.ops.wm.open_mainfile(filepath=str(dest/'model.blend'))
    assert stats(list(bpy.context.scene.objects))['meshObjects']==report['meshObjects']
    bpy.ops.wm.read_factory_settings(use_empty=True)
    bpy.ops.import_scene.gltf(filepath=str(dest/'export.glb'))
    loaded=stats(list(bpy.context.scene.objects))
    assert loaded['triangles']>0 and min(loaded['dimensions'])>0
    if ports is not None:
        assert len([o for o in bpy.context.scene.objects if o.get('role')=='docking-port'])==ports
    (dest/'specs.json').write_text(json.dumps({**loaded,'blender':bpy.app.version_string,'ports':ports,'preview':'Cycles CPU render of model.blend'},indent=2)+'\n')


if __name__=='__main__':
    args=sys.argv[sys.argv.index('--')+1:] if '--' in sys.argv else sys.argv[1:]
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--model',required=True);p.add_argument('--output',required=True,type=Path);p.add_argument('--reference',type=Path)
    p.add_argument('--ports',type=int,choices=[4,6]);p.add_argument('--scale',type=float,default=1);p.add_argument('--lod',type=float,default=1)
    p.add_argument('--paint',help='Hex RGB for the primary material')
    a=p.parse_args(args)
    if not (0<a.scale<=100 and 0<a.lod<=1):p.error('Scale and LOD must be positive and within range')
    build(a.model,a.output.resolve(),a.reference,a.scale,a.lod,a.paint,a.ports)
