"""Build the optical bench in Blender. All dimensions below are centimetres.

blender -b --factory-startup --python build_bench.py
The emitted glTF uses metres and Y-up coordinates.
"""
from pathlib import Path
import bpy

bpy.ops.wm.read_factory_settings(use_empty=True)
materials = {}
parts = {}


def box(group, colour, centre, size, bevel=0):
    bpy.ops.mesh.primitive_cube_add(size=1)
    obj = bpy.context.object
    obj.location = [v / 100 for v in centre]
    obj.dimensions = [v / 100 for v in size]
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
    if bevel:
        corners = obj.modifiers.new("Eased edges", "BEVEL")
        corners.width = bevel / 100
        corners.segments = 2
        bpy.ops.object.modifier_apply(modifier=corners.name)
    if colour not in materials:
        mat = bpy.data.materials.new(colour)
        rgb = [int(colour[i:i+2], 16) / 255 for i in (0, 2, 4)]
        linear = tuple(v / 12.92 if v < .04045 else ((v + .055) / 1.055) ** 2.4 for v in rgb) + (1,)
        mat.use_nodes = True
        mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = linear
        mat.diffuse_color = linear
        materials[colour] = mat
    obj.data.materials.append(materials[colour])
    parts.setdefault(group, []).append(obj)


# The lamp spans Z = -6..6 at X=0. The forward edge of the opaque card
# sits at X=40, Z=0. The receiver translates only along X in the viewer.
box("Bench", "967451", (35, 0, -14.1), (79, 6.2, 1.2), .25)
for y in (-2.1, 2.1):
    box("Rails", "585e58", (35, y, -13.2), (78, .38, .45), .07)
for x in range(0, 71, 2):
    box("Ruler", "473e32", (x, -2.7, -13.47), (.11, .65 if x % 10 == 0 else .32, .07))
for x, group in [(0, "LampStand"), (40, "CardStand"), (40, "PaperStand")]:
    y = 1.5 if group == "CardStand" else -1.5
    box(group, "625747", (x, y, -12.75), (1.3, 2, .75), .1)
    top = -6.7 if group == "LampStand" else -11.5
    box(group, "736952", (x, y, (-12.6 + top)/2), (.45, .45, 12.6 + top), .06)
box("LampHousing", "754332", (-.77, 0, 0), (1.5, 14, 13.4), .25)
box("Emitter", "ffd99a", (-.025, 0, 0), (.05, 13.6, 12))
box("Card", "373f41", (39.92, 0, -5.75), (.16, 15.5, 11.5))
for y in (-9.1, 9.1):
    box("PaperFrame", "8e765a", (40, y, 0), (.22, .2, 23.4))
for z in (-11.6, 11.6):
    box("PaperFrame", "8e765a", (40, 0, z), (.22, 18.4, .2))

# A single double-sided plane makes the ideal contact case well defined.
mesh = bpy.data.meshes.new("PaperFace")
mesh.from_pydata([(.4, -.09, -.115), (.4, .09, -.115),
                  (.4, .09, .115), (.4, -.09, .115)], [], [(0, 1, 2, 3)])
face = bpy.data.objects.new("PaperFace", mesh)
bpy.context.collection.objects.link(face)
for name, objects in parts.items():
    bpy.ops.object.select_all(action="DESELECT")
    for obj in objects:
        obj.select_set(True)
    bpy.context.view_layer.objects.active = objects[0]
    if len(objects) > 1:
        bpy.ops.object.join()
    bpy.context.object.name = name
    bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)

bpy.ops.export_scene.gltf(
    filepath=str(Path(__file__).resolve().with_name("bench.glb")),
    export_format="GLB", export_yup=True, export_normals=True,
    export_texcoords=False, export_cameras=False, export_lights=False,
)
