"""Model the operator laboratory in Blender. Run in a new, isolated process."""
import bpy,bmesh,math,os,random
from mathutils import Vector
from pathlib import Path
A=Path(globals().get('MODEL_DIR') or Path(__file__).resolve().parent)
bpy.ops.wm.read_factory_settings(use_empty=True)
sc=bpy.context.scene;sc.name='Operator Assembly Hall';random.seed(26)
def linear(v):
 v=int(v,16)/255;return v/12.92 if v<=.04045 else ((v+.055)/1.055)**2.4
def material(name,hexcolor,metal=0,rough=.52,texture=None,emission=0):
 m=bpy.data.materials.new(name);m.use_nodes=True;b=m.node_tree.nodes.get('Principled BSDF')
 col=tuple(linear(hexcolor[i:i+2]) for i in (0,2,4))+(1,)
 m.diffuse_color=col;b.inputs['Base Color'].default_value=col;b.inputs['Metallic'].default_value=metal;b.inputs['Roughness'].default_value=rough
 if texture:
  tex=m.node_tree.nodes.new('ShaderNodeTexImage');tex.image=bpy.data.images.load(str(A/'textures'/texture),check_existing=True);m.node_tree.links.new(tex.outputs['Color'],b.inputs['Base Color'])
 if emission:
  b.inputs['Emission Strength'].default_value=emission
  if texture:m.node_tree.links.new(tex.outputs['Color'],b.inputs['Emission Color'])
  else:b.inputs['Emission Color'].default_value=col
 return m
alloy=material('Satin machined aluminum','8c9b9c',.53,.39,'alloy.jpg')
titanium=material('Titanium gunmetal','49565a',.52,.38);chrome=material('Polished fasteners','acb9ba',.72,.26);enamel=material('Ivory instrument enamel','d2d1bf',.18,.39);ink=material('Graphite powder coating','303b41',.31,.51);rubber=material('Anti-slip floor panels','424d4d',.07,.84,'rubber.jpg');teal=material('Patinated teal enamel','357f76',.24,.34);ochre=material('Amber witness marks','e3a15d',.26,.36);brass=material('Machined bronze','bd8c54',.65,.28);paper=material('Archival paper','f2f0e1',rough=.91);plaster=material('Cast concrete','abb4af',rough=.88);lamp=material('Opal task lighting','ffebcc',emission=1.7);cool=material('Clerestory glazing','c1dfdd',emission=.60);led=material('Phosphor indicator','9feacf',emission=1.8);printed=material('Facsimile manuscript','eeebda',texture='manuscript.jpg')
cache={}
def cube(name,p,size,mat,bev=.012):
 key=(size,mat.name,bev)
 if key in cache:
  o=bpy.data.objects.new(name,cache[key]);sc.collection.objects.link(o);o.location=p;return o
 bpy.ops.mesh.primitive_cube_add(size=1,location=p);o=bpy.context.object;o.name=name
 for v in o.data.vertices:
  for i in range(3):v.co[i]*=size[i]
 uv=o.data.uv_layers.active
 for f in o.data.polygons:
  n=f.normal;dims=[j for j in range(3) if abs(n[j])<.9]
  for li in f.loop_indices:
   v=o.data.vertices[o.data.loops[li].vertex_index].co
   uv.data[li].uv=(v[dims[0]]/1.45+.45,v[dims[1]]/1.45+.45)
 if bev:
  bm=bmesh.new();bm.from_mesh(o.data);bmesh.ops.bevel(bm,geom=list(bm.edges),offset=min(bev,min(size)*.14),segments=3,affect='EDGES');bm.to_mesh(o.data);bm.free()
 o.data.materials.append(mat);cache[key]=o.data;return o
def rod(name,a,b,r,mat):
 v=Vector(b)-Vector(a);bpy.ops.mesh.primitive_cylinder_add(vertices=20,radius=r,depth=v.length,location=(Vector(a)+Vector(b))/2);o=bpy.context.object;o.name=name;o.rotation_euler=v.to_track_quat('Z','Y').to_euler();o.data.materials.append(mat)
 for f in o.data.polygons:f.use_smooth=len(f.vertices)==4
 return o
def ball(name,p,r,mat,scale=(1,1,1)):
 bpy.ops.mesh.primitive_uv_sphere_add(segments=20,ring_count=12,radius=r,location=p);o=bpy.context.object;o.name=name;o.scale=scale;o.data.materials.append(mat)
 for f in o.data.polygons:f.use_smooth=True
 return o
def picture(name,p,w,h,mat,rot=(math.pi/2,0,0)):
 bpy.ops.mesh.primitive_plane_add(size=1,location=p);o=bpy.context.object;o.name=name;o.scale=(w,h,1);o.rotation_euler=rot;o.data.materials.append(mat);return o
def area(name,p,t,power,size,c):
 data=bpy.data.lights.new(name,'AREA');data.energy=power;data.shape='DISK';data.size=size;data.color=c
 o=bpy.data.objects.new(name,data);sc.collection.objects.link(o);o.location=p;o.rotation_euler=(Vector(t)-o.location).to_track_quat('-Z','Y').to_euler()
def disc(name,x,y,z,r,h,m,v=64):
 bpy.ops.mesh.primitive_cylinder_add(vertices=v,radius=r,depth=h,location=(x,y,z));o=bpy.context.object;o.name=name;o.data.materials.append(m)
 for f in o.data.polygons:f.use_smooth=len(f.vertices)==4
 mod=o.modifiers.new('Machined lip','BEVEL');mod.width=min(.015,h*.13);mod.segments=2;bpy.ops.object.modifier_apply(modifier=mod.name)
 return o
def ring(name,r,z,minor,m,xy=(0,0)):
 bpy.ops.mesh.primitive_torus_add(major_segments=96,minor_segments=10,location=(*xy,z),major_radius=r,minor_radius=minor)
 o=bpy.context.object;o.name=name;o.data.materials.append(m)
 for f in o.data.polygons:f.use_smooth=True
 return o
def face(name,key,x,y,z,w,h):
 m=material(name+' screen','d6ddd1',rough=.72,texture=key+'.jpg',emission=.20)
 cube(name+' housing',(x,y+.028,z),(w+.09,.09,h+.09),ink);picture(name+' interface',(x,y-.022,z),w,h,m)
def railpoint(r,a):return r*math.cos(a),r*math.sin(a)
def bolt(name,x,y,z):return disc(name,x,y,z,.03,.017,chrome,6)
def instrument(x,y,w,d,h):
 cube('Sealed instrument cabinet',(x,y,h*.49),(w,d,h*.95),enamel,.055)
 cube('Floating black plinth',(x,y,.11),(w-.18,d-.15,.20),ink,.025)
 cube('Service deck',(x,y,h),(w+.06,d+.06,.075),titanium,.03)
 for dx in [-w*.42,w*.42]:
  for dy in [-d*.37,d*.37]:bolt('Deck fastener',x+dx,y+dy,h+.047)
 cube('Vent surround',(x,y-d/2-.012,h*.51),(w*.61,.035,.32),ink)
 for j in range(7):cube('Vent louver',(x,y-d/2-.04,h*.38+j*.033),(w*.55,.065,.010),alloy,.003)
 for dx in [-w*.40,w*.40]:cube('Service latch',(x+dx,y-d/2-.027,h*.64),(.054,.042,.106),chrome)
def support(x,y,z,h=.7):
 disc('Isolating mount',x,y,z,.18,.10,ink);disc('Machined riser',x,y,z+h/2,.065,h,alloy);disc('Upper flange',x,y,z+h,.13,.07,chrome)
# Twelve bays surround the apparatus. Perimeter panels, observation windows and a roof oculus.
disc('Subfloor',0,0,-.10,7.8,.22,plaster,96)
disc('Precision floor',0,0,.015,7.64,.07,rubber,96)
for radius in [1.95,2.03,2.64,4.79,4.86,6.36]:ring('Recessed survey ring',radius,.055,.009,alloy)
for k in range(72):
 a=k*math.tau/72;x,y=railpoint(2.38,a)
 o=cube('Scale graduation',(x,y,.057),(.15 if k%6==0 else .07,.016,.009),ochre if k%6==0 else alloy,.001);o.rotation_euler.z=a
for k in range(12):
 a=math.tau*k/12;x,y=railpoint(7.06,a);rot=a+math.pi/2
 for label,z,sz,mat in [('Lower bulkhead',.88,(3.81,.22,1.72),enamel),('Window reveal',3.07,(3.79,.20,2.57),titanium),('Clerestory',3.10,(3.53,.23,2.28),cool),('Upper coffer',5.20,(3.81,.28,1.70),plaster)]:
  o=cube(label,(x,y,z),sz,mat);o.rotation_euler.z=rot
 for k2 in [-1,0,1]:
  xx,yy=railpoint(6.91,a);xx+=k2*1.16*math.cos(rot);yy+=k2*1.16*math.sin(rot)
  o=cube('Window mullion',(xx,yy,3.06),(.065,.12,2.42),titanium);o.rotation_euler.z=rot
 xx,yy=railpoint(6.90,a);o=cube('Window transom',(xx,yy,3.40),(3.68,.14,.052),titanium);o.rotation_euler.z=rot
 aa=a+math.pi/12;x1,y1=railpoint(6.78,aa);x2,y2=railpoint(2.39,aa)
 rod('Roof rib',(x1,y1,4.10),(x2,y2,5.87),.098,titanium);rod('Roof chord',(x1,y1,4.49),(x2,y2,6.10),.065,alloy)
 for f in [.23,.54,.81]:
  xx=x1*(1-f)+x2*f;yy=y1*(1-f)+y2*f;rod('Truss web',(xx,yy,4.1+1.77*f),(xx,yy,4.49+1.61*f),.034,alloy)
for radius,z,height,mat in [(7.42,6.33,.12,enamel),(2.42,6.24,.10,cool)]:disc('Roof canopy',0,0,z,radius,height,mat,96)
for radius,z,minor,mat in [(6.84,4.13,.10,ink),(6.78,4.03,.033,lamp),(2.46,5.86,.12,titanium),(2.41,5.73,.044,lamp),(2.06,6.11,.050,alloy)]:ring('Overhead service ring',radius,z,minor,mat)
# Central isolation pedestal and tool-steel loading bridge.
for rad,z,h,m in [(1.78,.13,.21,titanium),(1.66,.29,.13,alloy),(1.51,.40,.12,ink),(1.39,.78,.72,teal),(1.46,1.13,.11,chrome),(1.50,1.22,.10,ink)]:
 disc('Rotary assembly bed',0,0,z,rad,h,m)
for k in range(24):
 a=k*math.tau/24;x,y=railpoint(1.52,a);bolt('Base stud',x,y,.362)
for x in [-1.07,1.07]:
 for y in [-.58,.58]:support(x,y,1.30,1.88);disc('Guide head',x,y,3.22,.098,.20,brass)
for y in [-.58,.58]:
 cube('Bridge bar',(0,y,3.22),(2.35,.15,.18),alloy)
 cube('Inspection strip',(0,y,3.12),(2.12,.095,.028),lamp)
for x in [-1.07,1.07]:cube('Bridge cheek',(x,0,3.22),(.15,1.26,.18),titanium)
for j,xx in enumerate([-.58,0,.58]):
 cube('Receiving socket',(xx,0,1.33),(.50,.70,.16),titanium,.024)
 for y in [-.26,.26]:
  rod('Cassette guide',(xx-.23,y,1.46),(xx+.23,y,1.46),.034,chrome)
 # Each cassette follows its own inspection motion in Three.js.
 objs=[]
 for name,offset,size,mat in [('Frame',(0,0,0),(.46,.58,.16),alloy),('Core',(0,0,.14),(.33,.43,.20),teal),('Cap',(0,0,.26),(.45,.55,.065),brass),('Mark',(0,-.295,0),(.18,.014,.040),led)]:
  dx,dy,dz=offset;o=cube('Cassette%02d_%s'%(j,name),(xx+dx,dy,1.55+dz),size,mat);objs.append(o)
 for k in [-1,1]:
  o=bolt('Cassette%02d_Fastener'%j,xx+k*.155,-.17,1.852);objs.append(o)
for xx in [-.29,.29]:rod('Transfer coupler',(xx-.10,0,1.57),(xx+.10,0,1.57),.057,ochre)
face('Assembly data','towerplate',0,-1.02,.81,1.12,.54)
# A two-axis vector gimbal on a separate measuring cabinet.
instrument(-3.55,-2.04,1.48,1.18,1.0);disc('Gimbal base',-3.55,-2.04,1.07,.49,.10,titanium)
ring('Azimuth dial',.41,1.16,.032,brass,(-3.55,-2.04));support(-3.55,-2.04,1.13,.30)
face('Finite operator','planeplate',-3.55,-2.66,.65,.91,.43)
# Dual-ended rail with independent micrometer wheels, a transverse lead screw and readout.
instrument(-3.82,1.65,2.65,1.25,.97)
for yy in [1.47,1.87]:rod('Optical guide',(-4.95,yy,1.14),(-2.70,yy,1.14),.043,chrome)
for xx,mat in [(-4.59,teal),(-3.82,titanium),(-3.05,ochre)]:
 cube('Slot carriage',(xx,1.67,1.24),(.43,.62,.16),mat)
 for dy in [-.20,.20]:rod('Pickup post',(xx,1.67+dy,1.30),(xx,1.67+dy,1.78),.029,alloy)
 rod('Endpoint winding',(xx,1.45,1.73),(xx,1.89,1.73),.096,brass)
for x in [-5.07,-2.57]:
 rod('Rail micrometer',(x-.09,1.64,1.12),(x+.09,1.64,1.12),.135,ink)
face('Endpoint readout','endpoint',-3.82,1.004,.61,1.33,.61)
# Three evidence screens on independent structural pylons form the observation gallery.
for idx,(xx,key) in enumerate([(-2.46,'fibers'),(0,'splitproof'),(2.46,'limit')]):
 yy=5.56-(.44 if idx!=1 else 0)
 instrument(xx,yy+.21,2.05,.76,.60)
 for dx in [-.67,.67]:support(xx+dx,yy+.15,.64,1.40)
 face('Observation '+key,key,xx,yy,2.37,2.30,1.22)
 for j in range(5):cube('Status segment',(xx-.35+j*.17,yy-.08,1.67),(.118,.03,.021),led if j<=idx+1 else titanium)
# An enclosed verification rack with removable trays and a dedicated front monitor.
instrument(3.69,2.27,1.89,1.23,1.0)
for xx in [3.11,4.25]:support(xx,2.52,1.03,.33)
face('Kernel station','terminal',3.69,2.46,1.84,1.67,.84)
cube('Control rail',(3.69,1.87,1.055),(1.60,.28,.055),ink)
for j in range(3):
 for i in range(12):cube('Console key',(3.16+i*.088,1.79+j*.075,1.09),(.071,.055,.018),alloy,.003)
for j in range(3):ball('Pilot light',(4.32,1.81+j*.075,1.10),.021,led)
instrument(5.32,2.58,.88,.86,2.01)
for i in range(7):
 cube('Compute sled',(5.32,2.12,.39+i*.195),(.74,.075,.147),ink)
 for dx in [-.28,.28]:cube('Rack pull',(5.32+dx,2.06,.39+i*.195),(.03,.07,.093),alloy,.004)
 cube('Activity LED',(5.48,2.065,.39+i*.195),(.046,.012,.015),led,.002)
# A document inspection lightbox with a physical paper facsimile and printed figure.
instrument(3.69,-2.46,1.74,1.30,1.0)
cube('Lightbox surround',(3.69,-2.46,1.08),(1.56,1.04,.095),alloy);cube('Diffuser',(3.69,-2.46,1.137),(1.44,.93,.026),lamp)
picture('Paper on lightbox',(3.38,-2.45,1.158),.53,.77,printed,(0,0,-.04))
leaf=material('Operator matrix offprint','d6dacb',texture='03-stage.png')
picture('Matrix offprint',(4.02,-2.50,1.159),.62,.43,leaf,(0,0,.05))
for xx in [3.12,4.26]:support(xx,-2.01,1.15,.54)
cube('Inspection lamp hood',(3.69,-2.01,1.73),(1.36,.18,.13),titanium);cube('Inspection light',(3.69,-2.01,1.65),(1.23,.12,.022),lamp)
area('Large aperture',(-2,-2,5.5),(0,1,.4),1100,5,(1,.91,.76));area('Clerestory fill',(3.8,.1,4.9),(0,0,1.2),900,4,(.77,.90,1));area('Observation wall',(-1,3.1,4.3),(0,4,1.6),620,3,(1,.94,.83))
cam=bpy.data.cameras.new('Entrance lens');c=bpy.data.objects.new('Entrance camera',cam);sc.collection.objects.link(c);c.location=(2.32,-5.94,2.76);c.rotation_euler=(Vector((-.36,.85,1.82))-c.location).to_track_quat('-Z','Y').to_euler();cam.lens=19;sc.camera=c
sc.world=bpy.data.worlds.new('Diffuse sky');sc.world.color=(.43,.45,.45)
sc.render.engine='CYCLES';sc.cycles.samples=16;sc.cycles.use_denoising=True;sc.render.resolution_x=1400;sc.render.resolution_y=850;sc.render.resolution_percentage=100
bpy.ops.file.pack_all();bpy.context.preferences.filepaths.save_version=0
bpy.ops.wm.save_as_mainfile(filepath=str(A/'Operator Assembly Hall.blend'))
bpy.ops.object.select_all(action='DESELECT')
for m in list(bpy.data.materials):
 objects=[o for o in sc.objects if o.type=='MESH' and o.data.materials and o.data.materials[0]==m and not o.name.startswith('Cassette')]
 if len(objects)<2:continue
 for o in objects:o.select_set(True)
 bpy.context.view_layer.objects.active=objects[0];bpy.ops.object.join();bpy.context.object.name=m.name;bpy.ops.object.select_all(action='DESELECT')
bpy.ops.export_scene.gltf(filepath=str(A/'room.glb'),export_format='GLB',export_cameras=False,export_lights=False,export_yup=True)
print('Operator Assembly Hall exported')
