"""
Taza de café colombiano humeante sobre pedestal — escena de producto 3D
Blender 4.2 · Cycles · vertical 1080x1920 · sin archivos externos

Animación: la cámara da una vuelta completa de 360° alrededor de la taza en
6 s a 24 fps (cuadros 1 a 144), siempre mirándola, y el vapor sube y cambia.

Uso:
    blender -b -P taza_cafe_colombiano.py                       (animación completa)
    blender -b -P taza_cafe_colombiano.py -- --maqueta           (todo gris mate, sin vapor)
    blender -b -P taza_cafe_colombiano.py -- --inicio 1 --fin 24 (solo un rango de cuadros)
    blender -b -P taza_cafe_colombiano.py -- --mp4               (además arma el video .mp4)
    blender -b -P taza_cafe_colombiano.py -- --foto              (una sola imagen, cuadro --inicio)
    blender -b -P taza_cafe_colombiano.py -- --preview           (30% de resolución, 48 samples)
    blender -b -P taza_cafe_colombiano.py -- --scale 50 --samples 256
    blender -b -P taza_cafe_colombiano.py -- --out carpeta --blend escena.blend

Los cuadros salen como PNG numerados (taza_0001.png...) en la carpeta --out
(por defecto ./render_taza o ./render_maqueta). Si se corta, vuelve a correrlo
con --inicio desde el cuadro que faltaba: no se pierde lo ya renderizado.
"""

import bpy
import bmesh
import math
import os
import sys
import argparse
from mathutils import Vector


# ----------------------------------------------------------------------------
# Argumentos (todo lo que va después de "--")
# ----------------------------------------------------------------------------
def parse_args():
    argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    p = argparse.ArgumentParser()
    p.add_argument("--out", default="", help="carpeta de salida")
    p.add_argument("--samples", type=int, default=384)
    p.add_argument("--preview", action="store_true", help="30%% de resolución y 48 samples")
    p.add_argument("--scale", type=int, default=100, help="porcentaje de resolución")
    p.add_argument("--maqueta", action="store_true", help="gris mate, sin colores ni vapor")
    p.add_argument("--inicio", type=int, default=1, help="primer cuadro (1-144)")
    p.add_argument("--fin", type=int, default=144, help="último cuadro (1-144)")
    p.add_argument("--foto", action="store_true", help="renderiza solo el cuadro --inicio")
    p.add_argument("--mp4", action="store_true", help="arma un .mp4 con los cuadros del rango")
    p.add_argument("--blend", default="", help="ruta opcional para guardar el .blend")
    a = p.parse_args(argv)
    if not 1 <= a.inicio <= a.fin <= 144:
        p.error("--inicio y --fin deben cumplir 1 <= inicio <= fin <= 144")
    if a.foto:
        a.fin = a.inicio
    if not a.out:
        a.out = os.path.join(os.getcwd(), "render_maqueta" if a.maqueta else "render_taza")
    return a


ARGS = parse_args()

FPS = 24
CUADROS = 6 * FPS   # 144 cuadros = 6 segundos

# Escena vacía
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.name = "TazaCafe"


# ----------------------------------------------------------------------------
# Utilidades
# ----------------------------------------------------------------------------
def link_obj(obj):
    scene.collection.objects.link(obj)
    return obj


def mesh_obj(name, bm, smooth=True):
    me = bpy.data.meshes.new(name)
    bm.to_mesh(me)
    bm.free()
    if smooth:
        me.polygons.foreach_set("use_smooth", [True] * len(me.polygons))
    return link_obj(bpy.data.objects.new(name, me))


def new_material(name):
    mat = bpy.data.materials.new(name)
    mat.use_nodes = True
    nt = mat.node_tree
    nt.nodes.clear()
    out = nt.nodes.new("ShaderNodeOutputMaterial")
    out.location = (600, 0)
    return mat, nt, out


def node(nt, kind, loc=(0, 0), **props):
    n = nt.nodes.new(kind)
    n.location = loc
    for k, v in props.items():
        setattr(n, k, v)
    return n


def feed(nt, socket, value):
    """Conecta un socket o asigna un valor constante."""
    if isinstance(value, bpy.types.NodeSocket):
        nt.links.new(value, socket)
    else:
        socket.default_value = value


def math_node(nt, op, a, b=None, loc=(0, 0), clamp=False, c=None):
    n = node(nt, "ShaderNodeMath", loc, operation=op, use_clamp=clamp)
    feed(nt, n.inputs[0], a)
    if b is not None:
        feed(nt, n.inputs[1], b)
    if c is not None:
        feed(nt, n.inputs[2], c)
    return n.outputs[0]


def map_range(nt, value, f0, f1, t0, t1, loc=(0, 0), smooth=True):
    n = node(nt, "ShaderNodeMapRange", loc)
    if smooth:
        n.interpolation_type = "SMOOTHSTEP"
    n.clamp = True
    feed(nt, n.inputs[0], value)
    for i, v in zip((1, 2, 3, 4), (f0, f1, t0, t1)):
        n.inputs[i].default_value = v
    return n.outputs[0]


def principled(nt, color, rough, loc=(200, 0), **extra):
    b = node(nt, "ShaderNodeBsdfPrincipled", loc)
    feed(nt, b.inputs["Base Color"], color)
    feed(nt, b.inputs["Roughness"], rough)
    for k, v in extra.items():
        feed(nt, b.inputs[k], v)
    return b


def animar_lineal(owner, path, v0, v1, index=-1):
    """Keyframes lineales: v0 en el cuadro 1 y v1 en el cuadro 145.
    Así los cuadros 1-144 cubren justo una vuelta sin repetir el primero."""
    def poner(frame, v):
        if index >= 0:
            getattr(owner, path)[index] = v
        else:
            setattr(owner, path, v)
        owner.keyframe_insert(path, index=index, frame=frame)
    poner(1, v0)
    poner(CUADROS + 1, v1)
    anim = owner.id_data.animation_data
    for fc in anim.action.fcurves:
        for k in fc.keyframe_points:
            k.interpolation = "LINEAR"
        fc.extrapolation = "LINEAR"


def look_at(obj, target):
    direction = Vector(target) - obj.location
    obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()


# ----------------------------------------------------------------------------
# Materiales
# ----------------------------------------------------------------------------
def mat_ceramica_colombia():
    """Cerámica blanca brillante con franja tricolor (amarillo, azul, rojo)."""
    mat, nt, out = new_material("Ceramica_Colombia")
    tc = node(nt, "ShaderNodeTexCoord", (-900, 0))
    sep = node(nt, "ShaderNodeSeparateXYZ", (-700, 0))
    nt.links.new(tc.outputs["Object"], sep.inputs[0])

    ramp = node(nt, "ShaderNodeValToRGB", (-450, 0))
    cr = ramp.color_ramp
    cr.interpolation = "CONSTANT"
    blanco = (0.86, 0.84, 0.80, 1)
    cr.elements[0].position = 0.0
    cr.elements[0].color = blanco
    cr.elements[1].position = 0.64
    cr.elements[1].color = blanco
    for pos, col in ((0.40, (0.55, 0.012, 0.018, 1)),   # rojo
                     (0.46, (0.005, 0.06, 0.30, 1)),    # azul
                     (0.52, (0.95, 0.62, 0.01, 1))):    # amarillo
        e = cr.elements.new(pos)
        e.color = col
    nt.links.new(sep.outputs["Z"], ramp.inputs["Fac"])

    b = principled(nt, ramp.outputs["Color"], 0.12,
                   **{"Coat Weight": 0.6, "Coat Roughness": 0.04,
                      "Subsurface Weight": 0.05, "Subsurface Radius": (0.2, 0.2, 0.2)})
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    return mat


def mat_ceramica_blanca():
    mat, nt, out = new_material("Ceramica_Blanca")
    b = principled(nt, (0.86, 0.84, 0.80, 1), 0.12,
                   **{"Coat Weight": 0.6, "Coat Roughness": 0.04})
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    return mat


def mat_cafe():
    """Tinto oscuro con un anillo de crema muy sutil en el borde."""
    mat, nt, out = new_material("Cafe_Tinto")
    tc = node(nt, "ShaderNodeTexCoord", (-900, 0))
    vlen = node(nt, "ShaderNodeVectorMath", (-700, 0), operation="LENGTH")
    nt.links.new(tc.outputs["Object"], vlen.inputs[0])
    edge = map_range(nt, vlen.outputs["Value"], 0.80, 1.0, 0.0, 1.0, (-500, 0))
    mix = node(nt, "ShaderNodeMix", (-250, 0), data_type="RGBA")
    nt.links.new(edge, mix.inputs["Factor"])
    mix.inputs["A"].default_value = (0.018, 0.006, 0.002, 1)
    mix.inputs["B"].default_value = (0.20, 0.09, 0.035, 1)
    b = principled(nt, mix.outputs["Result"], 0.04, **{"IOR": 1.34})
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    return mat


def mat_vapor():
    """Volumen procedural: hilos de vapor que suben, ondulan y se abren."""
    mat, nt, out = new_material("Vapor")
    tc = node(nt, "ShaderNodeTexCoord", (-1600, 0))
    sep = node(nt, "ShaderNodeSeparateXYZ", (-1400, 0))
    nt.links.new(tc.outputs["Object"], sep.inputs[0])
    x, y, z = sep.outputs["X"], sep.outputs["Y"], sep.outputs["Z"]

    zn = math_node(nt, "MULTIPLY_ADD", z, 0.5, (-1200, 200), c=0.5)   # 0 abajo → 1 arriba

    # Reloj en segundos (0 → 6) que mueve todo el vapor
    reloj = node(nt, "ShaderNodeValue", (-1600, -400), label="Tiempo (s)")
    animar_lineal(reloj.outputs[0], "default_value", 0.0, CUADROS / FPS)
    t = reloj.outputs[0]

    # Ondulación lateral que crece con la altura y viaja hacia arriba
    fase = math_node(nt, "MULTIPLY_ADD", t, -2.8, (-1200, 400), c=0.6)
    wave = math_node(nt, "SINE", math_node(nt, "MULTIPLY_ADD", zn, 7.0, (-1000, 300), c=fase), loc=(-850, 300))
    xs = math_node(nt, "ADD", x, math_node(nt, "MULTIPLY", wave,
                   math_node(nt, "MULTIPLY", zn, 0.22, (-850, 450)), (-700, 350)), (-550, 300))

    comb = node(nt, "ShaderNodeCombineXYZ", (-400, 250))
    nt.links.new(xs, comb.inputs["X"])
    nt.links.new(y, comb.inputs["Y"])
    rlen = node(nt, "ShaderNodeVectorMath", (-250, 250), operation="LENGTH")
    nt.links.new(comb.outputs[0], rlen.inputs[0])

    width = math_node(nt, "MULTIPLY_ADD", zn, 0.50, (-400, 450), c=0.42)  # se abre al subir
    rnorm = math_node(nt, "DIVIDE", rlen.outputs["Value"], width, (-100, 300))
    radial = map_range(nt, rnorm, 0.0, 1.0, 1.0, 0.0, (50, 300))

    v_in = map_range(nt, zn, 0.0, 0.10, 0.0, 1.0, (-100, 100))
    v_out = map_range(nt, zn, 0.25, 1.0, 1.0, 0.0, (-100, -50))
    vmask = math_node(nt, "MULTIPLY", v_in, v_out, (100, 50))

    # Ruido estirado en vertical → hilos
    scale = node(nt, "ShaderNodeVectorMath", (-1000, -200), operation="MULTIPLY")
    nt.links.new(tc.outputs["Object"], scale.inputs[0])
    scale.inputs[1].default_value = (1.6, 1.6, 0.55)
    # El ruido se desplaza hacia abajo en el espacio de textura → el vapor sube
    subida = node(nt, "ShaderNodeCombineXYZ", (-1000, -400))
    nt.links.new(math_node(nt, "MULTIPLY", t, -0.44, (-1200, -400)), subida.inputs["Z"])
    mover = node(nt, "ShaderNodeVectorMath", (-900, -300), operation="ADD")
    nt.links.new(scale.outputs[0], mover.inputs[0])
    nt.links.new(subida.outputs[0], mover.inputs[1])
    noise = node(nt, "ShaderNodeTexNoise", (-800, -200), noise_dimensions="4D")
    nt.links.new(mover.outputs[0], noise.inputs["Vector"])
    # La 4ª dimensión hace que la forma de los hilos cambie mientras suben
    nt.links.new(math_node(nt, "MULTIPLY", t, 0.35, (-1000, -550)), noise.inputs["W"])
    noise.inputs["Scale"].default_value = 2.2
    noise.inputs["Detail"].default_value = 6.0
    noise.inputs["Roughness"].default_value = 0.55
    noise.inputs["Distortion"].default_value = 1.4
    wisps = map_range(nt, noise.outputs["Fac"], 0.48, 0.72, 0.0, 1.0, (-550, -200))

    dens = math_node(nt, "MULTIPLY", math_node(nt, "MULTIPLY", wisps, radial, (250, 0)), vmask, (400, 0))
    dens = math_node(nt, "MULTIPLY", dens, 2.6, (550, 0))

    vol = node(nt, "ShaderNodeVolumePrincipled", (700, 0))
    vol.inputs["Color"].default_value = (0.95, 0.93, 0.90, 1)
    vol.inputs["Anisotropy"].default_value = 0.45     # dispersa hacia delante: brilla a contraluz
    nt.links.new(dens, vol.inputs["Density"])
    out.location = (950, 0)
    nt.links.new(vol.outputs[0], out.inputs["Volume"])
    return mat


def mat_grano():
    """Grano tostado brillante con la ranura central en relieve."""
    mat, nt, out = new_material("Grano_Cafe")
    tc = node(nt, "ShaderNodeTexCoord", (-900, 0))
    sep = node(nt, "ShaderNodeSeparateXYZ", (-700, 0))
    nt.links.new(tc.outputs["Object"], sep.inputs[0])
    ay = math_node(nt, "ABSOLUTE", sep.outputs["Y"], loc=(-550, 100))
    groove = map_range(nt, ay, 0.0, 0.10, 1.0, 0.0, (-400, 100))
    top = map_range(nt, sep.outputs["Z"], 0.0, 0.35, 0.0, 1.0, (-400, -50))
    mask = math_node(nt, "MULTIPLY", groove, top, (-250, 50))

    mix = node(nt, "ShaderNodeMix", (-50, 150), data_type="RGBA")
    nt.links.new(mask, mix.inputs["Factor"])
    mix.inputs["A"].default_value = (0.11, 0.045, 0.018, 1)
    mix.inputs["B"].default_value = (0.03, 0.012, 0.005, 1)
    bump = node(nt, "ShaderNodeBump", (-50, -100), invert=True)
    bump.inputs["Strength"].default_value = 1.0
    bump.inputs["Distance"].default_value = 0.03
    nt.links.new(mask, bump.inputs["Height"])
    b = principled(nt, mix.outputs["Result"], 0.32, **{"Coat Weight": 0.35, "Coat Roughness": 0.2})
    nt.links.new(bump.outputs[0], b.inputs["Normal"])
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    return mat


def mat_piedra():
    """Piedra oscura satinada con variación sutil."""
    mat, nt, out = new_material("Piedra_Pedestal")
    tc = node(nt, "ShaderNodeTexCoord", (-900, 0))
    noise = node(nt, "ShaderNodeTexNoise", (-700, 0))
    nt.links.new(tc.outputs["Object"], noise.inputs["Vector"])
    noise.inputs["Scale"].default_value = 3.0
    noise.inputs["Detail"].default_value = 10.0
    rough = map_range(nt, noise.outputs["Fac"], 0.3, 0.7, 0.28, 0.55, (-450, -100), smooth=False)
    col = node(nt, "ShaderNodeMix", (-450, 100), data_type="RGBA")
    nt.links.new(noise.outputs["Fac"], col.inputs["Factor"])
    col.inputs["A"].default_value = (0.030, 0.028, 0.027, 1)
    col.inputs["B"].default_value = (0.065, 0.060, 0.056, 1)
    b = principled(nt, col.outputs["Result"], rough)
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    return mat


def mat_fondo():
    mat, nt, out = new_material("Fondo_Estudio")
    b = principled(nt, (0.045, 0.031, 0.023, 1), 0.85)
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    return mat


# ----------------------------------------------------------------------------
# Geometría
# ----------------------------------------------------------------------------
def crear_taza():
    # Perfil (radio, altura): base → pared exterior → borde → pared interior → fondo
    perfil = [
        (0.0, 0.0), (0.30, 0.0), (0.38, 0.0), (0.41, 0.005), (0.425, 0.02),
        (0.43, 0.05), (0.445, 0.30), (0.46, 0.60), (0.47, 0.90), (0.472, 0.965),
        (0.468, 0.99), (0.458, 1.0), (0.448, 0.99), (0.443, 0.965), (0.44, 0.90),
        (0.43, 0.60), (0.415, 0.30), (0.40, 0.12), (0.38, 0.09), (0.30, 0.08), (0.0, 0.08),
    ]
    bm = bmesh.new()
    verts = [bm.verts.new((r, 0.0, z)) for r, z in perfil]
    edges = [bm.edges.new((verts[i], verts[i + 1])) for i in range(len(verts) - 1)]
    bmesh.ops.spin(bm, geom=verts + edges, cent=(0, 0, 0), axis=(0, 0, 1),
                   angle=math.tau, steps=96, use_merge=True)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    taza = mesh_obj("Taza", bm)
    sub = taza.modifiers.new("Subdivision", "SUBSURF")
    sub.levels, sub.render_levels = 1, 2
    taza.data.materials.append(mat_ceramica_colombia())

    # Asa (curva Bézier con grosor)
    cu = bpy.data.curves.new("Asa", "CURVE")
    cu.dimensions = "3D"
    cu.resolution_u = 32
    cu.bevel_depth = 0.048
    cu.bevel_resolution = 8
    cu.use_fill_caps = True
    sp = cu.splines.new("BEZIER")
    sp.bezier_points.add(1)
    p0, p1 = sp.bezier_points
    p0.co, p0.handle_left, p0.handle_right = (0.43, 0, 0.80), (0.30, 0, 0.78), (0.88, 0, 0.92)
    p1.co, p1.handle_left, p1.handle_right = (0.43, 0, 0.27), (0.86, 0, 0.12), (0.30, 0, 0.30)
    for p in (p0, p1):
        p.handle_left_type = p.handle_right_type = "FREE"
    asa = link_obj(bpy.data.objects.new("Asa", cu))
    asa.scale = (1.0, 0.75, 1.0)        # asa ligeramente ovalada
    asa.data.materials.append(mat_ceramica_blanca())
    asa.parent = taza

    # Café
    bm = bmesh.new()
    bmesh.ops.create_circle(bm, cap_ends=True, radius=1.0, segments=96)
    cafe = mesh_obj("Cafe", bm)
    cafe.scale = (0.452, 0.452, 1)
    cafe.location = (0, 0, 0.92)
    cafe.data.materials.append(mat_cafe())
    cafe.parent = taza

    taza.rotation_euler = (0, 0, math.radians(-38))   # asa hacia la cámara
    return taza


def crear_vapor():
    bm = bmesh.new()
    bmesh.ops.create_cube(bm, size=2.0)
    vapor = mesh_obj("Vapor", bm, smooth=False)
    vapor.location = (0, 0, 1.86)
    vapor.scale = (0.72, 0.72, 1.0)
    vapor.data.materials.append(mat_vapor())
    vapor.visible_shadow = False
    return vapor


def cilindro(name, radio, alto, z_base, mat):
    bm = bmesh.new()
    bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=128,
                          radius1=radio, radius2=radio, depth=alto)
    o = mesh_obj(name, bm)
    o.location = (0, 0, z_base + alto / 2)
    o.data.set_sharp_from_angle(angle=math.radians(30))
    bev = o.modifiers.new("Bevel", "BEVEL")
    bev.width, bev.segments, bev.limit_method = 0.025, 5, "ANGLE"
    bev.harden_normals = True
    o.data.materials.append(mat)
    return o


def crear_pedestal():
    piedra = mat_piedra()
    cilindro("Pedestal", 0.95, 0.60, -0.60, piedra)
    cilindro("Pedestal_Base", 1.06, 0.15, -0.75, piedra)


def crear_granos():
    mat = mat_grano()
    datos = [  # (x, y, z_apoyo, rot_z°, volteado)
        (-0.72, -0.42, 0.0, 25, False),
        (-0.55, -0.68, 0.0, -50, False),
        (0.62, -0.62, 0.0, 70, True),
        (-0.80, 0.05, 0.0, 95, False),
        (0.35, -1.75, -0.75, -20, False),   # en el piso, delante
        (-0.55, -1.55, -0.75, 40, True),
        (0.95, -1.45, -0.75, 110, False),
    ]
    for i, (x, y, z, rz, flip) in enumerate(datos):
        bm = bmesh.new()
        bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0)
        g = mesh_obj(f"Grano_{i}", bm)
        g.scale = (0.085, 0.062, 0.045)
        g.location = (x, y, z + 0.043)
        g.rotation_euler = (math.pi if flip else 0, 0, math.radians(rz))
        g.data.materials.append(mat)


def crear_fondo():
    """Ciclorama redondo (360°): piso que se curva en pared por todos los lados,
    para que la cámara vea estudio en cualquier punto de la vuelta."""
    zf, r_piso, R, alto = -0.75, 7.0, 2.5, 14.0
    perfil = [(0.0, zf), (r_piso * 0.5, zf), (r_piso, zf)]
    for i in range(1, 24):
        a = -math.pi / 2 + (math.pi / 2) * i / 24
        perfil.append((r_piso + R * math.cos(a), zf + R + R * math.sin(a)))
    perfil.append((r_piso + R, alto))
    bm = bmesh.new()
    verts = [bm.verts.new((r, 0.0, z)) for r, z in perfil]
    edges = [bm.edges.new((verts[i], verts[i + 1])) for i in range(len(verts) - 1)]
    bmesh.ops.spin(bm, geom=verts + edges, cent=(0, 0, 0), axis=(0, 0, 1),
                   angle=math.tau, steps=128, use_merge=True)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)
    fondo = mesh_obj("Ciclorama", bm)
    fondo.data.materials.append(mat_fondo())


# ----------------------------------------------------------------------------
# Luces, cámara, mundo
# ----------------------------------------------------------------------------
def luz(name, kind, loc, target, energy, color, size=1.0, **props):
    ld = bpy.data.lights.new(name, kind)
    ld.energy = energy
    ld.color = color
    if kind == "AREA":
        ld.shape, ld.size = "RECTANGLE", size
        ld.size_y = props.pop("size_y", size)
    for k, v in props.items():
        setattr(ld, k, v)
    o = link_obj(bpy.data.objects.new(name, ld))
    o.location = loc
    o.visible_camera = False
    look_at(o, target)
    return o


def crear_iluminacion():
    centro = (0, 0, 0.6)
    # Key: softbox grande, arriba-izquierda-frente, cálido
    luz("Key_Softbox", "AREA", (-3.2, -3.0, 3.4), centro, 650, (1.0, 0.92, 0.82), size=2.6, size_y=3.4)
    # Contraluz detrás de la taza: ilumina el vapor y deja el fondo oscuro
    luz("Contraluz_Vapor", "AREA", (0.6, 3.2, 2.6), (0, 0, 1.7), 900, (1.0, 0.95, 0.88), size=1.2)
    # Rim derecho para dibujar el borde de la taza y el asa
    luz("Rim_Derecho", "AREA", (3.0, 1.6, 1.8), centro, 320, (0.92, 0.95, 1.0), size=0.6, size_y=3.0)
    # Fill suave desde la derecha-frente
    luz("Fill", "AREA", (3.4, -3.6, 1.2), centro, 90, (1.0, 0.96, 0.92), size=4.0)
    # Halo cálido en el fondo, detrás del pedestal
    luz("Halo_Fondo", "SPOT", (0, 1.2, 0.4), (0, 6.0, 2.2), 1100, (1.0, 0.55, 0.25),
        spot_size=math.radians(70), spot_blend=1.0, shadow_soft_size=0.5)


def crear_camara():
    """Cámara montada en un brazo (empty) que gira 360° sobre el eje de la taza.
    Como la cámara es hija del brazo, gira con él y siempre mira la taza."""
    brazo = link_obj(bpy.data.objects.new("Orbita_Camara", None))
    brazo.empty_display_type = "CIRCLE"
    brazo.empty_display_size = 9.0

    cd = bpy.data.cameras.new("Camara")
    cd.lens = 70
    cd.sensor_fit = "AUTO"
    cam = link_obj(bpy.data.objects.new("Camara", cd))
    cam.location = (0, -9.0, 2.55)
    look_at(cam, (0, 0, 0.95))
    cam.parent = brazo

    foco = link_obj(bpy.data.objects.new("Foco", None))   # gira con la cámara
    foco.location = (0, -0.35, 0.55)
    foco.parent = brazo
    cd.dof.use_dof = True
    cd.dof.focus_object = foco
    cd.dof.aperture_fstop = 3.2
    scene.camera = cam

    # Vuelta completa: 0° en el cuadro 1 → 360° en el 145 (= cuadro 1 otra vez)
    animar_lineal(brazo, "rotation_euler", 0.0, math.tau, index=2)


def crear_mundo():
    w = bpy.data.worlds.new("Estudio")
    w.use_nodes = True
    bg = w.node_tree.nodes["Background"]
    bg.inputs["Color"].default_value = (0.012, 0.009, 0.007, 1)
    bg.inputs["Strength"].default_value = 1.0
    scene.world = w


def aplicar_maqueta():
    """Modo maqueta: todo gris mate (material override), luces neutras, sin vapor."""
    mat, nt, out = new_material("Maqueta_Gris")
    b = principled(nt, (0.18, 0.18, 0.18, 1), 0.7, **{"Specular IOR Level": 0.3})
    nt.links.new(b.outputs[0], out.inputs["Surface"])
    for vl in scene.view_layers:
        vl.material_override = mat
    for o in scene.objects:
        if o.type == "LIGHT":
            o.data.color = (1.0, 1.0, 1.0)
    scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.03, 0.03, 0.03, 1)


# ----------------------------------------------------------------------------
# Render
# ----------------------------------------------------------------------------
def configurar_dispositivo():
    try:
        prefs = bpy.context.preferences.addons["cycles"].preferences
        for tipo in ("OPTIX", "CUDA", "HIP", "METAL", "ONEAPI"):
            try:
                prefs.compute_device_type = tipo
            except TypeError:
                continue
            prefs.get_devices()
            gpus = [d for d in prefs.devices if d.type == tipo]
            if gpus:
                for d in prefs.devices:
                    d.use = d.type == tipo
                scene.cycles.device = "GPU"
                return f"GPU ({tipo})"
        prefs.compute_device_type = "NONE"
    except Exception as e:
        print("Aviso GPU:", e)
    scene.cycles.device = "CPU"
    return "CPU"


def configurar_render():
    r = scene.render
    r.engine = "CYCLES"
    r.resolution_x, r.resolution_y = 1080, 1920
    r.resolution_percentage = 30 if ARGS.preview else ARGS.scale
    r.film_transparent = False
    r.fps = FPS
    scene.frame_start, scene.frame_end = ARGS.inicio, ARGS.fin
    r.image_settings.file_format = "PNG"
    r.image_settings.color_mode = "RGB"
    r.image_settings.color_depth = "8"
    r.use_file_extension = True
    r.use_overwrite = True
    r.filepath = os.path.join(os.path.abspath(ARGS.out), "taza_")

    c = scene.cycles
    c.samples = 48 if ARGS.preview else ARGS.samples
    c.use_adaptive_sampling = True
    c.use_denoising = True
    c.denoiser = "OPENIMAGEDENOISE"
    c.max_bounces = 12
    c.volume_bounces = 2
    c.transparent_max_bounces = 8
    c.volume_step_rate = 1.0
    c.caustics_reflective = False
    c.caustics_refractive = False

    vs = scene.view_settings
    try:
        vs.view_transform = "AgX"
        vs.look = "AgX - Medium High Contrast"
    except TypeError:
        vs.view_transform = "Filmic"
    vs.exposure = 0.0
    return configurar_dispositivo()


def armar_mp4(carpeta):
    """Une los PNG del rango en un .mp4 H.264 usando el editor de video de Blender."""
    archivos = [f"taza_{f:04d}.png" for f in range(ARGS.inicio, ARGS.fin + 1)]
    faltan = [a for a in archivos if not os.path.exists(os.path.join(carpeta, a))]
    if faltan:
        print(f">> No armo el mp4: faltan {len(faltan)} cuadros (ej. {faltan[0]})")
        return
    montaje = bpy.data.scenes.new("Montaje")
    ed = montaje.sequence_editor_create()
    strip = ed.sequences.new_image("Cuadros", os.path.join(carpeta, archivos[0]),
                                   channel=1, frame_start=1)
    for a in archivos[1:]:
        strip.elements.append(a)
    r, base = montaje.render, scene.render
    r.resolution_x, r.resolution_y = base.resolution_x, base.resolution_y
    r.resolution_percentage = base.resolution_percentage
    r.fps = FPS
    montaje.frame_start, montaje.frame_end = 1, len(archivos)
    montaje.view_settings.view_transform = "Standard"   # los PNG ya traen el color final
    r.use_sequencer = True
    r.image_settings.file_format = "FFMPEG"
    r.ffmpeg.format = "MPEG4"
    r.ffmpeg.codec = "H264"
    r.ffmpeg.constant_rate_factor = "HIGH"
    r.ffmpeg.ffmpeg_preset = "GOOD"
    r.ffmpeg.audio_codec = "NONE"
    nombre = "maqueta" if ARGS.maqueta else "taza_cafe"
    r.filepath = os.path.join(carpeta, f"{nombre}_")      # Blender agrega el rango: _0001-0144.mp4
    r.use_file_extension = True
    bpy.ops.render.render(animation=True, scene=montaje.name)
    print(f">> Video: {r.frame_path(frame=1)}")   # ruta final con el rango de cuadros


# ----------------------------------------------------------------------------
def main():
    crear_fondo()
    crear_pedestal()
    crear_taza()
    if not ARGS.maqueta:
        crear_vapor()
    crear_granos()
    crear_iluminacion()
    crear_camara()
    crear_mundo()
    if ARGS.maqueta:
        aplicar_maqueta()
    disp = configurar_render()

    carpeta = os.path.abspath(ARGS.out)
    os.makedirs(carpeta, exist_ok=True)
    modo = "MAQUETA" if ARGS.maqueta else "FINAL"
    print(f"\n>> {modo} · cuadros {ARGS.inicio}-{ARGS.fin} de {CUADROS} · "
          f"{scene.render.resolution_x}x{scene.render.resolution_y} al "
          f"{scene.render.resolution_percentage}% · {scene.cycles.samples} samples · {disp}")
    if ARGS.blend:
        scene.frame_set(ARGS.inicio)
        bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(ARGS.blend))
    bpy.ops.render.render(animation=True)
    print(f">> Cuadros en: {carpeta}")
    if ARGS.mp4:
        armar_mp4(carpeta)
    print()


main()