"""Geoff Boyle's 'one redhead' beauty setup, rebuilt as a Cycles scene.

Kit (as described in Cooke Optics' "Don't complicate lighting", ~0:55):
  - one redhead (800 W open-face tungsten) low, firing up into
  - a sheet of poly directly over the camera  -> soft key from above the lens
  - a black flag either side of the face        -> negative fill, thins the face
  - a piece of poly behind the head             -> kicks the head/hair up

Usage (inside the Blender container):
  blender -b --factory-startup --python boyle_beauty.py -- --pass full --out /work/renders/full.png
Passes: direct, key, flags, full, overview
"""
import argparse, math, sys
import bpy
from mathutils import Vector

argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
ap = argparse.ArgumentParser()
ap.add_argument("--pass", dest="pas", default="full",
                choices=["direct", "key", "flags", "full", "overview"])
ap.add_argument("--out", default="/work/renders/full.png")
ap.add_argument("--samples", type=int, default=256)
ap.add_argument("--res", type=int, default=1000, help="image height in px")
ap.add_argument("--save-blend", default="")
ap.add_argument("--back", default="0.22,2.05")
ap.add_argument("--ovcam", default="1.0,1.9,2.5")
ap.add_argument("--exposure", type=float, default=2.75)
a = ap.parse_args(argv)
BACK_Y, BACK_Z = map(float, a.back.split(","))

ASSETS = "/work/assets/LeePerrySmith/"
bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene

# ---------------------------------------------------------------- helpers
def look_at(obj, target, up_hint=None):
    d = Vector(target) - obj.location
    obj.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()

def mat_diffuse(name, albedo, rough=0.9):
    m = bpy.data.materials.new(name); m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*albedo, 1)
    b.inputs["Roughness"].default_value = rough
    b.inputs["Specular IOR Level"].default_value = 0.2
    return m

def plane(name, size, loc, target, mat, two_sided=True):
    bpy.ops.mesh.primitive_plane_add(size=1, location=loc)
    o = bpy.context.active_object; o.name = name
    o.scale = (size[0], size[1], 1)
    look_at(o, target)          # plane normal (+Z) is flipped to face target below
    o.rotation_euler.rotate_axis("X", math.pi)
    o.data.materials.append(mat)
    if two_sided:
        mod = o.modifiers.new("thick", "SOLIDIFY"); mod.thickness = 0.01
    return o

def stand(name, top, mat):
    """A thin C-stand pole from the floor to an item, so the overview reads as a set."""
    h = top.z - FLOOR
    bpy.ops.mesh.primitive_cylinder_add(radius=0.012, depth=h,
                                        location=(top.x, top.y, FLOOR + h / 2))
    o = bpy.context.active_object; o.name = name; o.data.materials.append(mat)
    return o

# ---------------------------------------------------------------- subject
bpy.ops.import_scene.gltf(filepath=ASSETS + "LeePerrySmith.glb")
for o in list(bpy.data.objects):
    if o.type != "MESH":
        bpy.data.objects.remove(o)
head = bpy.data.objects["LeePerrySmith"]
S = 0.032                       # scan units -> metres (head+neck ~ 25 cm)
head.scale = (S, S, S)
head.location = (0, 0, 1.55)    # seated subject, eyes ~1.6 m
bpy.ops.object.shade_smooth()
EYE = Vector((0, -0.05, 1.60))  # roughly between the eyes, face looks toward -Y

skin = bpy.data.materials.new("skin"); skin.use_nodes = True
nt = skin.node_tree; N = nt.nodes; L = nt.links
bsdf = N["Principled BSDF"]
def tex(path, non_color=False):
    t = N.new("ShaderNodeTexImage"); t.image = bpy.data.images.load(path)
    if non_color: t.image.colorspace_settings.name = "Non-Color"
    return t
col, spec, nrm = tex(ASSETS + "Map-COL.jpg"), tex(ASSETS + "Map-SPEC.jpg", True), \
    tex(ASSETS + "Infinite-Level_02_Tangent_SmoothUV.jpg", True)
# the three.js-era textures expect raw glTF UVs; Blender's importer flipped V, so flip it back
uv = N.new("ShaderNodeTexCoord"); mp = N.new("ShaderNodeMapping")
mp.inputs["Location"].default_value[1] = 1.0; mp.inputs["Scale"].default_value[1] = -1.0
L.new(uv.outputs["UV"], mp.inputs["Vector"])
for t in (col, spec, nrm): L.new(mp.outputs["Vector"], t.inputs["Vector"])
L.new(col.outputs["Color"], bsdf.inputs["Base Color"])
# spec map: bright = oily/shiny. Map it into a sane skin roughness range.
rmap = N.new("ShaderNodeMapRange")
rmap.inputs["To Min"].default_value, rmap.inputs["To Max"].default_value = 0.62, 0.38
L.new(spec.outputs["Color"], rmap.inputs["Value"])
L.new(rmap.outputs["Result"], bsdf.inputs["Roughness"])
nmap = N.new("ShaderNodeNormalMap"); nmap.inputs["Strength"].default_value = 0.6
L.new(nrm.outputs["Color"], nmap.inputs["Color"]); L.new(nmap.outputs["Normal"], bsdf.inputs["Normal"])
bsdf.inputs["Subsurface Weight"].default_value = 0.35
bsdf.inputs["Subsurface Radius"].default_value = (1.0, 0.35, 0.2)
bsdf.inputs["Subsurface Scale"].default_value = 0.004     # metres
bsdf.inputs["Specular IOR Level"].default_value = 0.5
head.data.materials.clear(); head.data.materials.append(skin)

# ---------------------------------------------------------------- studio
FLOOR = 0.0
studio_mat = mat_diffuse("studio_grey", (0.18, 0.18, 0.18))     # painted studio walls
bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0.5, 2.0))
room = bpy.context.active_object; room.name = "studio"
room.scale = (7, 9, 4)
room.modifiers.new("flip", "SOLIDIFY").thickness = 0.05
room.data.materials.append(studio_mat)
bpy.ops.object.shade_flat()
# backdrop behind the subject: dark grey paper
paper = mat_diffuse("backdrop", (0.035, 0.035, 0.04))
plane("backdrop", (4, 3), (0, 2.2, 1.5), (0, 0, 1.5), paper)

poly_mat  = mat_diffuse("poly", (0.92, 0.92, 0.90), rough=1.0)   # polystyrene board
flag_mat  = mat_diffuse("duvetyne", (0.025, 0.025, 0.025), rough=1.0)
metal     = mat_diffuse("stand", (0.3, 0.3, 0.3), rough=0.4)

# ---------------------------------------------------------------- camera
cam_data = bpy.data.cameras.new("cam"); cam = bpy.data.objects.new("cam", cam_data)
scn.collection.objects.link(cam); scn.camera = cam
if a.pas == "overview":
    cam.location = tuple(map(float, a.ovcam.split(","))); cam_data.lens = 24
    look_at(cam, (0, -0.45, 1.45))
else:
    cam.location = (0, -1.20, 1.62); cam_data.lens = 150       # tight beauty framing
    look_at(cam, EYE + Vector((0, 0, 0.0)))
cam_data.sensor_width = 36

# a token camera body so the overview shows where the lens is
if a.pas == "overview":
    bpy.ops.mesh.primitive_cube_add(size=1, location=(0, -1.28, 1.62))
    body = bpy.context.active_object; body.scale = (0.14, 0.18, 0.12)
    body.data.materials.append(mat_diffuse("cambody", (0.05, 0.05, 0.05)))
    stand("tripod", Vector((0, -1.28, 1.56)), metal)

# ---------------------------------------------------------------- the kit
def redhead(loc, target, spot_deg):
    """800 W open-face tungsten: ~3200 K, beam spread set by focus knob/barn doors."""
    ld = bpy.data.lights.new("redhead", "SPOT")
    ld.energy = 800 * 0.12        # Blender watts are radiant; ~12% of tungsten lamp watts is visible-ish output
    ld.spot_size = math.radians(spot_deg); ld.spot_blend = 0.35
    ld.shadow_soft_size = 0.03    # small open-face bulb
    ld.use_nodes = True
    bb = ld.node_tree.nodes.new("ShaderNodeBlackbody"); bb.inputs[0].default_value = 3200
    em = ld.node_tree.nodes["Emission"]
    ld.node_tree.links.new(bb.outputs[0], em.inputs["Color"])
    o = bpy.data.objects.new("redhead", ld); scn.collection.objects.link(o)
    o.location = loc; look_at(o, target)
    # visible lamp housing for the overview
    if a.pas == "overview":
        bpy.ops.mesh.primitive_cylinder_add(radius=0.07, depth=0.16, location=loc)
        h = bpy.context.active_object; h.rotation_euler = o.rotation_euler
        h.data.materials.append(mat_diffuse("redhead_body", (0.5, 0.05, 0.03), 0.5))
        h.visible_shadow = False
        stand("redhead_stand", Vector(loc) - Vector((0, 0, 0.1)), metal)
    return o

if a.pas == "direct":
    # the naive version: redhead straight at the face from beside the camera
    redhead((0.35, -1.4, 1.75), EYE, 40)
else:
    # poly directly over the camera, tilted to face the subject
    poly_c = Vector((0, -1.05, 2.15))
    p = plane("poly_over_camera", (1.2, 1.2), poly_c, EYE + Vector((0, 0, -0.1)), poly_mat)
    # redhead on the floor in front of the subject, firing up into the poly
    rh = redhead((0, -0.65, 0.55), poly_c, 55)
    if a.pas == "overview":
        stand("poly_stand", poly_c + Vector((0.6, 0, 0)), metal)

if a.pas in ("flags", "full", "overview"):
    for side in (-1, 1):
        # just out of frame, between the edges of the overhead poly and the cheeks:
        # they cut the poly's wrap-around so the sides of the face fall off
        c = Vector((side * 0.22, -0.38, 1.58))
        plane(f"black_flag_{'L' if side < 0 else 'R'}", (0.5, 0.9), c,
              c + Vector((-side, 0.15, 0)), flag_mat)
        if a.pas == "overview":
            stand(f"flag_stand_{side}", c, metal)

if a.pas in ("full", "overview"):
    # poly behind and just above the head (above frame): it catches the
    # overhead poly's light that passes the head and bounces it back onto the crown
    bc = Vector((0, BACK_Y, BACK_Z))
    plane("poly_behind_head", (1.0, 0.5), bc, Vector((0, 0.0, 1.82)), poly_mat)
    if a.pas == "overview":
        stand("back_poly_stand", bc, metal)

if a.pas == "overview":
    # a dim work light so the set itself is legible
    wl = bpy.data.lights.new("worklight", "AREA"); wl.energy = 25; wl.size = 3
    w = bpy.data.objects.new("worklight", wl); scn.collection.objects.link(w)
    w.location = (1.5, -2.5, 3.8); look_at(w, (0, 0, 1))

# ---------------------------------------------------------------- render
scn.render.engine = "CYCLES"
scn.cycles.device = "CPU"
scn.cycles.samples = a.samples
scn.cycles.use_denoising = True
scn.cycles.max_bounces = 12
scn.render.resolution_y = a.res
scn.render.resolution_x = int(a.res * (16 / 9 if a.pas == "overview" else 4 / 5))
scn.view_settings.view_transform = "AgX"
scn.view_settings.look = "AgX - Base Contrast"
scn.view_settings.exposure = a.exposure if a.pas != "overview" else a.exposure - 1.0
# camera white-balanced to tungsten, as you would on set
scn.view_settings.use_white_balance = a.pas != "overview"   # overview: neutral, so the redhead reads warm
scn.view_settings.white_balance_temperature = 3200
scn.world = bpy.data.worlds.new("black"); scn.world.color = (0, 0, 0)
scn.render.filepath = a.out
if a.save_blend:
    bpy.ops.wm.save_as_mainfile(filepath=a.save_blend)
bpy.ops.render.render(write_still=True)
print("WROTE", a.out)
