Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

blender upbge mais recente: adicione um cenário render eevee estilo pixar com…

  1. User

    blender upbge mais recente: adicione um cenário render eevee estilo pixar com iluminação, ground e uma parede curvada a este script: import bpy from mathutils import Vector

    Parâmetros num_cylinders = 10 distance = 3 total_frames = 500 # ampliado para conter ida + volta

    frames_per_impact = 7 # intervalo entre impactos na animação impact_duration = 15 # duração do "afundar" z_scale_min = 0.2 # escala mínima no Z

    impact_start_frame = 20 # frame em que martelo bate no primeiro cilindro

    Limpar objetos antigos for obj in bpy.data.objects: if obj.name.startswith("Cylinder") or obj.name == "Martelo": bpy.data.objects.remove(obj, do_unlink=True)

    Cria cilindros com origem na base (face inferior) def add_cylinder_with_base_origin(radius=1, depth=2, location=(0,0,0), name="Cylinder"): bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=location) obj = bpy.context.object obj.name = name

    bpy.ops.object.mode_set(mode='OBJECT') bpy.context.view_layer.objects.active = obj obj.location.z += depth / 2 bpy.ops.object.transform_apply(location=True, rotation=False, scale=False) return obj cylinders = [] for i in range(num_cylinders): pos = (i*distance, 0, 0) c = add_cylinder_with_base_origin(radius=1, depth=2, location=pos, name=f"Cylinder.{str(i+1).zfill(3)}") cylinders.append(c) if c.animation_data: c.animation_data_clear()

    Martelo (cubo simples) bpy.ops.mesh.primitive_cube_add(size=1.5, location=(-distance, 0, 1.5)) martelo = bpy.context.object martelo.name = "Martelo" if martelo.animation_data: martelo.animation_data_clear()

    Animação do martelo: batida no primeiro cilindro hammer_back_frame = impact_start_frame - 10

    martelo.location = (-distance, 0, 1.5) martelo.keyframe_insert(data_path="location", frame=hammer_back_frame) martelo.rotation_euler = (0, 0, 0) martelo.keyframe_insert(data_path="rotation_euler", frame=hammer_back_frame)

    martelo.location = (0, 0, 1.5) martelo.keyframe_insert(data_path="location", frame=impact_start_frame) martelo.rotation_euler = (0, 0, 0) martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame)

    martelo.location = (-distance, 0, 1.5) martelo.keyframe_insert(data_path="location", frame=impact_start_frame + 15) martelo.rotation_euler = (0, 0, 0) martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame + 15)

    Função para animar o efeito de "afundar" def animate_sink(obj, start_frame, duration, scale_min): obj.scale = (1, 1, 1) obj.keyframe_insert(data_path="scale", frame=start_frame)

    peak_frame = start_frame + duration // 2 obj.scale = (1, 1, scale_min) obj.keyframe_insert(data_path="scale", frame=peak_frame)

    end_frame = start_frame + duration obj.scale = (1, 1, 1) obj.keyframe_insert(data_path="scale", frame=end_frame) Animação IDA: do primeiro ao último cilindro for i, c in enumerate(cylinders): start = impact_start_frame + i * frames_per_impact animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)

    Calcular frame ao final da ida para começar a volta ida_end_frame = impact_start_frame + (num_cylinders -1) * frames_per_impact + impact_duration volta_start_delay = -7 # frames de pausa entre ida e volta

    Animação VOLTA: do último para o primeiro cilindro, após pausa for i, c in enumerate(reversed(cylinders)): start = ida_end_frame + volta_start_delay + i * frames_per_impact animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)

    Ajustar timeline para cobrir ida + volta scene = bpy.context.scene scene.frame_start = 1 scene.frame_end = ida_end_frame + volta_start_delay + (num_cylinders-1)*frames_per_impact + impact_duration + 20

    print("Animação com ida e volta do efeito afundar criada!")

  2. Assistant

    Claro! Vou incorporar a criação de um cenário no estilo Pixar, com o render usando Eevee, iluminação apropriada, chão e uma parede curva ao seu script existente. Vou respeitar suas configurações de animação e adicionar a parte do cenário antes da animação para organização.

    import bpy
    from mathutils import Vector
    import math
    
    # --- Seu código anterior ---
    
    # Parâmetros
    num_cylinders = 10
    distance = 3
    total_frames = 500  # ampliado para conter ida + volta
    
    frames_per_impact = 7  # intervalo entre impactos na animação
    impact_duration = 15  # duração do "afundar"
    z_scale_min = 0.2  # escala mínima no Z
    
    impact_start_frame = 20  # frame em que martelo bate no primeiro cilindro
    
    # --- Limpar objetos antigos (incluindo luz e câmeras para criar cenário limpo) ---
    for obj in bpy.data.objects:
        if obj.name.startswith("Cylinder") or obj.name == "Martelo" or obj.name.startswith("Light") or obj.name.startswith("Wall") or obj.name == "Ground" or obj.name == "Camera":
            bpy.data.objects.remove(obj, do_unlink=True)
    
    # Limpar meshes órfãos e materiais (opcional, ajuda a manter arquivo limpo)
    for mesh in bpy.data.meshes:
        if not mesh.users:
            bpy.data.meshes.remove(mesh)
    
    for mat in bpy.data.materials:
        if not mat.users:
            bpy.data.materials.remove(mat)
    
    # --- Criar cenário estilo Pixar (Eevee) ---
    
    # Ajustar render para Eevee
    scene = bpy.context.scene
    scene.render.engine = 'BLENDER_EEVEE'
    
    # Criar Material estilo Pixar: simples, base color saturado, suave, com SSS (simples)
    def create_pixar_material(name, base_color):
        mat = bpy.data.materials.new(name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        links = mat.node_tree.links
        nodes.clear()
        # Nodes
        output = nodes.new(type='ShaderNodeOutputMaterial')
        principled = nodes.new(type='ShaderNodeBsdfPrincipled')
        principled.inputs['Base Color'].default_value = base_color
        principled.inputs['Subsurface'].default_value = 0.1
        principled.inputs['Subsurface Color'].default_value = base_color
        principled.inputs['Specular'].default_value = 0.5
        principled.inputs['Roughness'].default_value = 0.3
        principled.location = (-200,0)
        output.location = (200,0)
        links.new(principled.outputs[0], output.inputs[0])
        return mat
    
    # Chão
    bpy.ops.mesh.primitive_plane_add(size=30, location=(distance*(num_cylinders-1)/2, 0, 0))
    ground = bpy.context.object
    ground.name = "Ground"
    ground_mat = create_pixar_material("GroundMat", (0.8,0.7,0.5,1))  # tom bege claro/pixaresco
    ground.data.materials.append(ground_mat)
    
    # Colocar o chão um pouco abaixo (y,z)
    ground.location.z = -0.01
    
    # Parede curva: criar um arco de plano, utilizando curva e then converter para mesh para deformar
    # Processo: Criar um mesh plano, subdividir, aplicar deformação circular
    bpy.ops.mesh.primitive_plane_add(size=15, location=(distance*(num_cylinders-1)/2, 1.6, 7))
    wall = bpy.context.object
    wall.name = "Wall"
    wall.scale.x = 3.0
    wall.scale.y = 0.1
    wall.scale.z = 1.5
    
    # Subdividir para permitir curvar
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.subdivide(number_cuts=30)
    bpy.ops.object.mode_set(mode='OBJECT')
    
    # Aplicar modificador Warp (curva a parede)
    mod_warp = wall.modifiers.new("WarpCurve", type='SIMPLE_DEFORM')
    mod_warp.deform_method = 'BEND'
    mod_warp.deform_axis = 'X'
    mod_warp.angle = math.radians(70)  # curva suave de 70 graus
    
    # Criar e adicionar material parede (tom pastel, levemente saturado e brilhante)
    wall_mat = create_pixar_material("WallMat", (0.9, 0.75, 0.8,1))
    wall.data.materials.append(wall_mat)
    
    # --- Luzes estilo Pixar ---
    # 1. Uma luz principal (key light) quente e suave 
    key_light_data = bpy.data.lights.new(name="KeyLight", type='AREA')
    key_light_data.energy = 1000
    key_light_data.color = (1.0, 0.9, 0.8)  # luz quente
    key_light_data.size = 5
    key_light = bpy.data.objects.new(name="KeyLight", object_data=key_light_data)
    bpy.context.collection.objects.link(key_light)
    key_light.location = (distance*(num_cylinders-1)/2 + 5, -7, 10)
    key_light.rotation_euler = (math.radians(60), 0, math.radians(-25))
    
    # 2. Luz de preenchimento (fill light) fria e sutil para equilibrar sombras
    fill_light_data = bpy.data.lights.new(name="FillLight", type='AREA')
    fill_light_data.energy = 300
    fill_light_data.color = (0.6, 0.7, 1.0)
    fill_light_data.size = 7
    fill_light = bpy.data.objects.new(name="FillLight", object_data=fill_light_data)
    bpy.context.collection.objects.link(fill_light)
    fill_light.location = (distance*(num_cylinders-1)/2 - 10, 3, 5)
    fill_light.rotation_euler = (math.radians(45), 0, math.radians(30))
    
    # 3. Luz de contorno (rim light) para definição da silhueta
    rim_light_data = bpy.data.lights.new(name="RimLight", type='SPOT')
    rim_light_data.energy = 400
    rim_light_data.color = (1, 0.9, 0.7)
    rim_light_data.spot_size = math.radians(45)
    rim_light_data.use_shadow = True
    rim_light = bpy.data.objects.new(name="RimLight", object_data=rim_light_data)
    bpy.context.collection.objects.link(rim_light)
    rim_light.location = (distance*(num_cylinders-1)/2, -10, 8)
    rim_light.rotation_euler = (math.radians(75), 0, 0)
    
    # --- Câmera ---
    cam_data = bpy.data.cameras.new("Camera")
    cam = bpy.data.objects.new("Camera", cam_data)
    bpy.context.collection.objects.link(cam)
    scene.camera = cam
    cam.location = (distance*(num_cylinders-1)/2, -15, 7)
    cam.rotation_euler = (math.radians(70), 0, 0)  # olhe para frente e para cima levemente
    
    # --- Função para criar cilindros (com origem na base conforme seu código já feito) ---
    def add_cylinder_with_base_origin(radius=1, depth=2, location=(0,0,0), name="Cylinder"):
        bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=location)
        obj = bpy.context.object
        obj.name = name
        bpy.ops.object.mode_set(mode='OBJECT')
        bpy.context.view_layer.objects.active = obj
        obj.location.z += depth / 2
        bpy.ops.object.transform_apply(location=True, rotation=False, scale=False)
        return obj
    
    
    # --- Criar cilindros ---
    cylinders = []
    for i in range(num_cylinders):
        pos = (i*distance, 0, 0)
        c = add_cylinder_with_base_origin(radius=1, depth=2, location=pos, name=f"Cylinder.{str(i+1).zfill(3)}")
        cylinders.append(c)
        if c.animation_data:
            c.animation_data_clear()
        # Material Disney/ Pixar simples
        pixar_colors = [
            (0.8,0.3,0.3,1),
            (0.3,0.8,0.3,1),
            (0.3,0.3,0.8,1),
            (0.8,0.8,0.3,1),
            (0.8,0.3,0.8,1),
            (0.3,0.8,0.8,1),
            (0.6,0.4,0.2,1),
            (0.4,0.6,0.7,1),
            (0.7,0.4,0.6,1),
            (0.5,0.5,0.5,1)
        ]
        mat = create_pixar_material(f'CylinderMat{i}', pixar_colors[i%len(pixar_colors)])
        c.data.materials.append(mat)
    
    
    # --- Martelo (cubo simples) ---
    bpy.ops.mesh.primitive_cube_add(size=1.5, location=(-distance, 0, 1.5))
    martelo = bpy.context.object
    martelo.name = "Martelo"
    if martelo.animation_data:
        martelo.animation_data_clear()
    martelo_mat = create_pixar_material("MarteloMat", (0.8,0.5,0.3,1))
    martelo.data.materials.append(martelo_mat)
    
    # --- Animação do martelo: batida no primeiro cilindro ---
    hammer_back_frame = impact_start_frame - 10
    
    martelo.location = (-distance, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=hammer_back_frame)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=hammer_back_frame)
    
    martelo.location = (0, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=impact_start_frame)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame)
    
    martelo.location = (-distance, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=impact_start_frame + 15)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame + 15)
    
    # --- Função para animar o efeito de "afundar" ---
    def animate_sink(obj, start_frame, duration, scale_min):
        obj.scale = (1, 1, 1)
        obj.keyframe_insert(data_path="scale", frame=start_frame)
    
        peak_frame = start_frame + duration // 2
        obj.scale = (1, 1, scale_min)
        obj.keyframe_insert(data_path="scale", frame=peak_frame)
    
        end_frame = start_frame + duration
        obj.scale = (1, 1, 1)
        obj.keyframe_insert(data_path="scale", frame=end_frame)
    
    # --- Animação IDA: do primeiro ao último cilindro ---
    for i, c in enumerate(cylinders):
        start = impact_start_frame + i * frames_per_impact
        animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
    
    # Calcular frame ao final da ida para começar a volta
    ida_end_frame = impact_start_frame + (num_cylinders -1) * frames_per_impact + impact_duration
    volta_start_delay = -7  # frames de pausa entre ida e volta
    
    # --- Animação VOLTA: do último para o primeiro cilindro, após pausa ---
    for i, c in enumerate(reversed(cylinders)):
        start = ida_end_frame + volta_start_delay + i * frames_per_impact
        animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
    
    # Ajustar timeline para cobrir ida + volta
    scene.frame_start = 1
    scene.frame_end = ida_end_frame + volta_start_delay + (num_cylinders-1)*frames_per_impact + impact_duration + 20
    
    print("Animação com ida e volta do efeito afundar criada, com cenário Pixar estilo Eevee!")
    

    O que foi adicionado?

    • Render Engine definido como Eevee.
    • Cena limpa de luzes e câmeras antigas e seus materiais/meshes órfãos.
    • Criação de chão grande com material simples com subsurface scattering.
    • Criação de parede curva feita a partir de plano suavemente curvado via modifier Simple Deform Bend (~ 70 graus).
    • Luz principal, luz de preenchimento e luz de contorno para simular uma iluminação padrão cinematográfica.
    • Câmera posicionada para enquadrar bem os cilindros e o martelo.
    • Materiais dos cilindros e martelo criados com Principled BSDF, valores simples para estilo Pixar (cores saturadas mas suaves, subsurface para efeito de plástico).
    • Manutenção intacta da sua animação original, apenas com pequenas melhorias de organização do código (corrigido indentação e ordem para rodar normalmente no Blender).

    Se desejar posso ajudar com texturas, pós-processamento de Eevee (bloom, etc) ou outras melhorias do cenário!

  3. User

    Python: Traceback (most recent call last): File "\Text", line 36, in TypeError: bpy_struct: item.attr = val: enum "BLENDER_EEVEE" not found in ('BLENDER_EEVEE_NEXT', 'BLENDER_WORKBENCH', 'CYCLES')

  4. Assistant

    O erro acontece porque a enumeração correta para o engine Eevee mudou no Blender/UPBGE recentes: não é mais 'BLENDER_EEVEE' e sim 'BLENDER_EEVEE_NEXT'.

    Então basta ajustar esta linha:

    scene.render.engine = 'BLENDER_EEVEE'
    

    para

    scene.render.engine = 'BLENDER_EEVEE_NEXT'
    

    Código com correção:

    # Ajustar render para Eevee Next (UPBGE 0.3X+ / Blender 3.x+)
    scene.render.engine = 'BLENDER_EEVEE_NEXT'
    

    Se quiser, posso enviar o script completo corrigido com este detalhe para você. Mas essa é a única linha que precisa ser ajustada para corrigir este erro de enumeração.

  5. User

    sim

  6. Assistant

    Claro! Aqui está o seu script completo corrigido, com scene.render.engine = 'BLENDER_EEVEE_NEXT' para evitar o erro, e com a indentação corrigida para rodar diretamente na versão recente do Blender/UPBGE:

    import bpy
    from mathutils import Vector
    import math
    
    # --- Parâmetros ---
    num_cylinders = 10
    distance = 3
    total_frames = 500  # ampliado para conter ida + volta
    
    frames_per_impact = 7  # intervalo entre impactos na animação
    impact_duration = 15  # duração do "afundar"
    z_scale_min = 0.2  # escala mínima no Z
    
    impact_start_frame = 20  # frame em que martelo bate no primeiro cilindro
    
    # --- Limpar objetos antigos (incluindo luz e câmeras para criar cenário limpo) ---
    for obj in bpy.data.objects:
        if obj.name.startswith("Cylinder") or obj.name == "Martelo" or obj.name.startswith("Light") or obj.name.startswith("Wall") or obj.name == "Ground" or obj.name == "Camera":
            bpy.data.objects.remove(obj, do_unlink=True)
    
    # Limpar meshes órfãos e materiais (opcional, ajuda a manter arquivo limpo)
    for mesh in bpy.data.meshes:
        if not mesh.users:
            bpy.data.meshes.remove(mesh)
    
    for mat in bpy.data.materials:
        if not mat.users:
            bpy.data.materials.remove(mat)
    
    # --- Ajustar render para Eevee Next (UPBGE / Blender recentes) ---
    scene = bpy.context.scene
    scene.render.engine = 'BLENDER_EEVEE_NEXT'
    
    # --- Criar Material estilo Pixar ---
    def create_pixar_material(name, base_color):
        mat = bpy.data.materials.new(name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        links = mat.node_tree.links
        nodes.clear()
        output = nodes.new(type='ShaderNodeOutputMaterial')
        principled = nodes.new(type='ShaderNodeBsdfPrincipled')
        principled.inputs['Base Color'].default_value = base_color
        principled.inputs['Subsurface'].default_value = 0.1
        principled.inputs['Subsurface Color'].default_value = base_color
        principled.inputs['Specular'].default_value = 0.5
        principled.inputs['Roughness'].default_value = 0.3
        principled.location = (-200, 0)
        output.location = (200, 0)
        links.new(principled.outputs[0], output.inputs[0])
        return mat
    
    # --- Chão ---
    bpy.ops.mesh.primitive_plane_add(size=30, location=(distance*(num_cylinders-1)/2, 0, 0))
    ground = bpy.context.object
    ground.name = "Ground"
    ground_mat = create_pixar_material("GroundMat", (0.8, 0.7, 0.5, 1))  # tom bege claro/pixaresco
    ground.data.materials.append(ground_mat)
    ground.location.z = -0.01
    
    # --- Parede curva ---
    bpy.ops.mesh.primitive_plane_add(size=15, location=(distance*(num_cylinders-1)/2, 1.6, 7))
    wall = bpy.context.object
    wall.name = "Wall"
    wall.scale.x = 3.0
    wall.scale.y = 0.1
    wall.scale.z = 1.5
    
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.subdivide(number_cuts=30)
    bpy.ops.object.mode_set(mode='OBJECT')
    
    mod_warp = wall.modifiers.new("WarpCurve", type='SIMPLE_DEFORM')
    mod_warp.deform_method = 'BEND'
    mod_warp.deform_axis = 'X'
    mod_warp.angle = math.radians(70)  # curva suave de 70 graus
    
    wall_mat = create_pixar_material("WallMat", (0.9, 0.75, 0.8, 1))
    wall.data.materials.append(wall_mat)
    
    # --- Luzes estilo Pixar ---
    key_light_data = bpy.data.lights.new(name="KeyLight", type='AREA')
    key_light_data.energy = 1000
    key_light_data.color = (1.0, 0.9, 0.8)  # luz quente
    key_light_data.size = 5
    key_light = bpy.data.objects.new(name="KeyLight", object_data=key_light_data)
    bpy.context.collection.objects.link(key_light)
    key_light.location = (distance*(num_cylinders-1)/2 + 5, -7, 10)
    key_light.rotation_euler = (math.radians(60), 0, math.radians(-25))
    
    fill_light_data = bpy.data.lights.new(name="FillLight", type='AREA')
    fill_light_data.energy = 300
    fill_light_data.color = (0.6, 0.7, 1.0)
    fill_light_data.size = 7
    fill_light = bpy.data.objects.new(name="FillLight", object_data=fill_light_data)
    bpy.context.collection.objects.link(fill_light)
    fill_light.location = (distance*(num_cylinders-1)/2 - 10, 3, 5)
    fill_light.rotation_euler = (math.radians(45), 0, math.radians(30))
    
    rim_light_data = bpy.data.lights.new(name="RimLight", type='SPOT')
    rim_light_data.energy = 400
    rim_light_data.color = (1, 0.9, 0.7)
    rim_light_data.spot_size = math.radians(45)
    rim_light_data.use_shadow = True
    rim_light = bpy.data.objects.new(name="RimLight", object_data=rim_light_data)
    bpy.context.collection.objects.link(rim_light)
    rim_light.location = (distance*(num_cylinders-1)/2, -10, 8)
    rim_light.rotation_euler = (math.radians(75), 0, 0)
    
    # --- Câmera ---
    cam_data = bpy.data.cameras.new("Camera")
    cam = bpy.data.objects.new("Camera", cam_data)
    bpy.context.collection.objects.link(cam)
    scene.camera = cam
    cam.location = (distance*(num_cylinders-1)/2, -15, 7)
    cam.rotation_euler = (math.radians(70), 0, 0)  # olhar para frente e para cima levemente
    
    # --- Função para criar cilindros ---
    def add_cylinder_with_base_origin(radius=1, depth=2, location=(0,0,0), name="Cylinder"):
        bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=location)
        obj = bpy.context.object
        obj.name = name
        bpy.ops.object.mode_set(mode='OBJECT')
        bpy.context.view_layer.objects.active = obj
        obj.location.z += depth / 2
        bpy.ops.object.transform_apply(location=True, rotation=False, scale=False)
        return obj
    
    # --- Criar cilindros ---
    cylinders = []
    for i in range(num_cylinders):
        pos = (i*distance, 0, 0)
        c = add_cylinder_with_base_origin(radius=1, depth=2, location=pos, name=f"Cylinder.{str(i+1).zfill(3)}")
        cylinders.append(c)
        if c.animation_data:
            c.animation_data_clear()
        # Material estilo Pixar
        pixar_colors = [
            (0.8,0.3,0.3,1),
            (0.3,0.8,0.3,1),
            (0.3,0.3,0.8,1),
            (0.8,0.8,0.3,1),
            (0.8,0.3,0.8,1),
            (0.3,0.8,0.8,1),
            (0.6,0.4,0.2,1),
            (0.4,0.6,0.7,1),
            (0.7,0.4,0.6,1),
            (0.5,0.5,0.5,1)
        ]
        mat = create_pixar_material(f'CylinderMat{i}', pixar_colors[i%len(pixar_colors)])
        c.data.materials.append(mat)
    
    # --- Martelo (cubo simples) ---
    bpy.ops.mesh.primitive_cube_add(size=1.5, location=(-distance, 0, 1.5))
    martelo = bpy.context.object
    martelo.name = "Martelo"
    if martelo.animation_data:
        martelo.animation_data_clear()
    martelo_mat = create_pixar_material("MarteloMat", (0.8, 0.5, 0.3, 1))
    martelo.data.materials.append(martelo_mat)
    
    # --- Animação do martelo ---
    hammer_back_frame = impact_start_frame - 10
    
    martelo.location = (-distance, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=hammer_back_frame)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=hammer_back_frame)
    
    martelo.location = (0, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=impact_start_frame)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame)
    
    martelo.location = (-distance, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=impact_start_frame + 15)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame + 15)
    
    # --- Função de animação de afundar ---
    def animate_sink(obj, start_frame, duration, scale_min):
        obj.scale = (1, 1, 1)
        obj.keyframe_insert(data_path="scale", frame=start_frame)
    
        peak_frame = start_frame + duration // 2
        obj.scale = (1, 1, scale_min)
        obj.keyframe_insert(data_path="scale", frame=peak_frame)
    
        end_frame = start_frame + duration
        obj.scale = (1, 1, 1)
        obj.keyframe_insert(data_path="scale", frame=end_frame)
    
    # --- Animação ida ---
    for i, c in enumerate(cylinders):
        start = impact_start_frame + i * frames_per_impact
        animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
    
    ida_end_frame = impact_start_frame + (num_cylinders - 1) * frames_per_impact + impact_duration
    volta_start_delay = -7  # frames de pausa entre ida e volta
    
    # --- Animação volta ---
    for i, c in enumerate(reversed(cylinders)):
        start = ida_end_frame + volta_start_delay + i * frames_per_impact
        animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
    
    # --- Ajustar timeline ---
    scene.frame_start = 1
    scene.frame_end = ida_end_frame + volta_start_delay + (num_cylinders - 1)*frames_per_impact + impact_duration + 20
    
    print("Animação com ida e volta do efeito afundar criada, com cenário Pixar estilo Eevee Next!")
    

    Execute assim que abrir um novo arquivo do Blender para evitar conflitos.

    Se precisar de algo mais — texturas, efeitos bloom no Eevee Next, composição ou até animação das luzes — pode pedir!

  7. User

    Python: Traceback (most recent call last): File "\Text", line 57, in File "\Text", line 44, in create_pixar_material KeyError: 'bpy_prop_collection[key]: key "Subsurface" not found'

  8. Assistant

    Esse erro ocorre porque o socket "Subsurface" não existe no shader Principled BSDF na sua versão do Blender/UPBGE (algumas versões podem não expor esse parâmetro ou usarem nomes diferentes).

    Para compatibilidade, vamos:

    • Verificar se o socket existe antes de tentar definir;
    • Ou simplesmente ignorar o SSS (subsurface scattering), que não é crítico para o efeito e é opcional.

    Vou ajustar a função de criação do material para checar a existência desse socket antes de definir seus valores.

    Segue o trecho corrigido da função create_pixar_material e o script completo atualizado:

    def create_pixar_material(name, base_color):
        mat = bpy.data.materials.new(name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        links = mat.node_tree.links
        nodes.clear()
        output = nodes.new(type='ShaderNodeOutputMaterial')
        principled = nodes.new(type='ShaderNodeBsdfPrincipled')
        
        principled.location = (-200, 0)
        output.location = (200, 0)
        
        principled.inputs['Base Color'].default_value = base_color
        
        # Definir subsurface apenas se o input existir
        if 'Subsurface' in principled.inputs:
            principled.inputs['Subsurface'].default_value = 0.1
        if 'Subsurface Color' in principled.inputs:
            principled.inputs['Subsurface Color'].default_value = base_color
            
        principled.inputs['Specular'].default_value = 0.5
        principled.inputs['Roughness'].default_value = 0.3
        
        links.new(principled.outputs[0], output.inputs[0])
        return mat
    

    Script completo atualizado (a parte relevante e corrigida):

    import bpy
    from mathutils import Vector
    import math
    
    num_cylinders = 10
    distance = 3
    total_frames = 500
    
    frames_per_impact = 7
    impact_duration = 15
    z_scale_min = 0.2
    
    impact_start_frame = 20
    
    for obj in bpy.data.objects:
        if obj.name.startswith("Cylinder") or obj.name == "Martelo" or obj.name.startswith("Light") or obj.name.startswith("Wall") or obj.name == "Ground" or obj.name == "Camera":
            bpy.data.objects.remove(obj, do_unlink=True)
    
    for mesh in bpy.data.meshes:
        if not mesh.users:
            bpy.data.meshes.remove(mesh)
    
    for mat in bpy.data.materials:
        if not mat.users:
            bpy.data.materials.remove(mat)
    
    scene = bpy.context.scene
    scene.render.engine = 'BLENDER_EEVEE_NEXT'
    
    def create_pixar_material(name, base_color):
        mat = bpy.data.materials.new(name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        links = mat.node_tree.links
        nodes.clear()
        output = nodes.new(type='ShaderNodeOutputMaterial')
        principled = nodes.new(type='ShaderNodeBsdfPrincipled')
        
        principled.location = (-200, 0)
        output.location = (200, 0)
        
        principled.inputs['Base Color'].default_value = base_color
        
        if 'Subsurface' in principled.inputs:
            principled.inputs['Subsurface'].default_value = 0.1
        if 'Subsurface Color' in principled.inputs:
            principled.inputs['Subsurface Color'].default_value = base_color
            
        principled.inputs['Specular'].default_value = 0.5
        principled.inputs['Roughness'].default_value = 0.3
        
        links.new(principled.outputs[0], output.inputs[0])
        return mat
    
    # O restante do script mantém igual (criando chão, parede curva, luzes, câmera, cilindros, martelo, animações)
    
    # ...
    
    # (coloque todo o restante do seu script abaixo, exatamente igual ao código anterior com essa única atualização da função)
    
    print("Script atualizado e funcionando com correção no material Pixar!")
    

    Se preferir, posso enviar o script completo novamente com essa função atualizada embutida.

    Quer que eu faça isso?

  9. User

    sim

  10. Assistant

    Perfeito! Aqui está o script completo atualizado com a correção para evitar o erro KeyError ao configurar o material Pixar, garantindo compatibilidade com versões que não possuem os sockets "Subsurface" e "Subsurface Color":

    import bpy
    from mathutils import Vector
    import math
    
    # --- Parâmetros ---
    num_cylinders = 10
    distance = 3
    total_frames = 500  # ampliado para conter ida + volta
    
    frames_per_impact = 7  # intervalo entre impactos na animação
    impact_duration = 15  # duração do "afundar"
    z_scale_min = 0.2  # escala mínima no Z
    
    impact_start_frame = 20  # frame em que martelo bate no primeiro cilindro
    
    # --- Limpar objetos antigos (incluindo luz e câmeras) ---
    for obj in bpy.data.objects:
        if obj.name.startswith("Cylinder") or obj.name == "Martelo" or obj.name.startswith("Light") or obj.name.startswith("Wall") or obj.name == "Ground" or obj.name == "Camera":
            bpy.data.objects.remove(obj, do_unlink=True)
    
    for mesh in bpy.data.meshes:
        if not mesh.users:
            bpy.data.meshes.remove(mesh)
    
    for mat in bpy.data.materials:
        if not mat.users:
            bpy.data.materials.remove(mat)
    
    # --- Ajustar render para Eevee Next ---
    scene = bpy.context.scene
    scene.render.engine = 'BLENDER_EEVEE_NEXT'
    
    # --- Função para criar material estilo Pixar com proteção contra erro KeyError ---
    def create_pixar_material(name, base_color):
        mat = bpy.data.materials.new(name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        links = mat.node_tree.links
        nodes.clear()
        output = nodes.new(type='ShaderNodeOutputMaterial')
        principled = nodes.new(type='ShaderNodeBsdfPrincipled')
        
        principled.location = (-200, 0)
        output.location = (200, 0)
        
        principled.inputs['Base Color'].default_value = base_color
        
        # Conferir se sockets existem antes de definir
        if 'Subsurface' in principled.inputs:
            principled.inputs['Subsurface'].default_value = 0.1
        if 'Subsurface Color' in principled.inputs:
            principled.inputs['Subsurface Color'].default_value = base_color
            
        principled.inputs['Specular'].default_value = 0.5
        principled.inputs['Roughness'].default_value = 0.3
        
        links.new(principled.outputs[0], output.inputs[0])
        return mat
    
    # --- Criar chão ---
    bpy.ops.mesh.primitive_plane_add(size=30, location=(distance*(num_cylinders-1)/2, 0, 0))
    ground = bpy.context.object
    ground.name = "Ground"
    ground_mat = create_pixar_material("GroundMat", (0.8, 0.7, 0.5, 1))
    ground.data.materials.append(ground_mat)
    ground.location.z = -0.01
    
    # --- Criar parede curva ---
    bpy.ops.mesh.primitive_plane_add(size=15, location=(distance*(num_cylinders-1)/2, 1.6, 7))
    wall = bpy.context.object
    wall.name = "Wall"
    wall.scale.x = 3.0
    wall.scale.y = 0.1
    wall.scale.z = 1.5
    
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.subdivide(number_cuts=30)
    bpy.ops.object.mode_set(mode='OBJECT')
    
    mod_warp = wall.modifiers.new("WarpCurve", type='SIMPLE_DEFORM')
    mod_warp.deform_method = 'BEND'
    mod_warp.deform_axis = 'X'
    mod_warp.angle = math.radians(70)
    
    wall_mat = create_pixar_material("WallMat", (0.9, 0.75, 0.8, 1))
    wall.data.materials.append(wall_mat)
    
    # --- Luzes estilo Pixar ---
    
    # Luz principal (key light)
    key_light_data = bpy.data.lights.new(name="KeyLight", type='AREA')
    key_light_data.energy = 1000
    key_light_data.color = (1.0, 0.9, 0.8)
    key_light_data.size = 5
    key_light = bpy.data.objects.new(name="KeyLight", object_data=key_light_data)
    bpy.context.collection.objects.link(key_light)
    key_light.location = (distance*(num_cylinders-1)/2 + 5, -7, 10)
    key_light.rotation_euler = (math.radians(60), 0, math.radians(-25))
    
    # Luz de preenchimento (fill light)
    fill_light_data = bpy.data.lights.new(name="FillLight", type='AREA')
    fill_light_data.energy = 300
    fill_light_data.color = (0.6, 0.7, 1.0)
    fill_light_data.size = 7
    fill_light = bpy.data.objects.new(name="FillLight", object_data=fill_light_data)
    bpy.context.collection.objects.link(fill_light)
    fill_light.location = (distance*(num_cylinders-1)/2 - 10, 3, 5)
    fill_light.rotation_euler = (math.radians(45), 0, math.radians(30))
    
    # Luz de contorno (rim light)
    rim_light_data = bpy.data.lights.new(name="RimLight", type='SPOT')
    rim_light_data.energy = 400
    rim_light_data.color = (1, 0.9, 0.7)
    rim_light_data.spot_size = math.radians(45)
    rim_light_data.use_shadow = True
    rim_light = bpy.data.objects.new(name="RimLight", object_data=rim_light_data)
    bpy.context.collection.objects.link(rim_light)
    rim_light.location = (distance*(num_cylinders-1)/2, -10, 8)
    rim_light.rotation_euler = (math.radians(75), 0, 0)
    
    # --- Câmera ---
    cam_data = bpy.data.cameras.new("Camera")
    cam = bpy.data.objects.new("Camera", cam_data)
    bpy.context.collection.objects.link(cam)
    scene.camera = cam
    cam.location = (distance*(num_cylinders-1)/2, -15, 7)
    cam.rotation_euler = (math.radians(70), 0, 0)
    
    # --- Função para criar cilindros com origem na base ---
    def add_cylinder_with_base_origin(radius=1, depth=2, location=(0,0,0), name="Cylinder"):
        bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=location)
        obj = bpy.context.object
        obj.name = name
        bpy.ops.object.mode_set(mode='OBJECT')
        bpy.context.view_layer.objects.active = obj
        obj.location.z += depth / 2
        bpy.ops.object.transform_apply(location=True, rotation=False, scale=False)
        return obj
    
    # --- Criar cilindros ---
    cylinders = []
    pixar_colors = [
        (0.8,0.3,0.3,1),
        (0.3,0.8,0.3,1),
        (0.3,0.3,0.8,1),
        (0.8,0.8,0.3,1),
        (0.8,0.3,0.8,1),
        (0.3,0.8,0.8,1),
        (0.6,0.4,0.2,1),
        (0.4,0.6,0.7,1),
        (0.7,0.4,0.6,1),
        (0.5,0.5,0.5,1)
    ]
    
    for i in range(num_cylinders):
        pos = (i*distance, 0, 0)
        c = add_cylinder_with_base_origin(radius=1, depth=2, location=pos, name=f"Cylinder.{str(i+1).zfill(3)}")
        cylinders.append(c)
        
        if c.animation_data:
            c.animation_data_clear()
        
        mat = create_pixar_material(f'CylinderMat{i}', pixar_colors[i % len(pixar_colors)])
        c.data.materials.append(mat)
    
    # --- Martelo ---
    bpy.ops.mesh.primitive_cube_add(size=1.5, location=(-distance, 0, 1.5))
    martelo = bpy.context.object
    martelo.name = "Martelo"
    
    if martelo.animation_data:
        martelo.animation_data_clear()
    
    martelo_mat = create_pixar_material("MarteloMat", (0.8, 0.5, 0.3, 1))
    martelo.data.materials.append(martelo_mat)
    
    # --- Animação do martelo ---
    hammer_back_frame = impact_start_frame - 10
    
    martelo.location = (-distance, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=hammer_back_frame)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=hammer_back_frame)
    
    martelo.location = (0, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=impact_start_frame)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame)
    
    martelo.location = (-distance, 0, 1.5)
    martelo.keyframe_insert(data_path="location", frame=impact_start_frame + 15)
    martelo.rotation_euler = (0, 0, 0)
    martelo.keyframe_insert(data_path="rotation_euler", frame=impact_start_frame + 15)
    
    # --- Função para animar o efeito "afundar" ---
    def animate_sink(obj, start_frame, duration, scale_min):
        obj.scale = (1, 1, 1)
        obj.keyframe_insert(data_path="scale", frame=start_frame)
        peak_frame = start_frame + duration // 2
        obj.scale = (1, 1, scale_min)
        obj.keyframe_insert(data_path="scale", frame=peak_frame)
        end_frame = start_frame + duration
        obj.scale = (1, 1, 1)
        obj.keyframe_insert(data_path="scale", frame=end_frame)
    
    # --- Animação ida ---
    for i, c in enumerate(cylinders):
        start = impact_start_frame + i * frames_per_impact
        animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
    
    ida_end_frame = impact_start_frame + (num_cylinders - 1) * frames_per_impact + impact_duration
    volta_start_delay = -7  # frames de pausa entre ida e volta
    
    # --- Animação volta ---
    for i, c in enumerate(reversed(cylinders)):
        start = ida_end_frame + volta_start_delay + i * frames_per_impact
        animate_sink(c, start_frame=start, duration=impact_duration, scale_min=z_scale_min)
    
    # --- Ajustar timeline ---
    scene.frame_start = 1
    scene.frame_end = ida_end_frame + volta_start_delay + (num_cylinders - 1) * frames_per_impact + impact_duration + 20
    
    print("Animação com ida e volta do efeito afundar criada, com cenário Pixar estilo Eevee Next!")
    

    Observações finais:

    • A função create_pixar_material agora verifica se os sockets Subsurface e Subsurface Color existem antes de definir seus valores, evitando erros em versões mais antigas/alteradas do Blender/UPBGE.
    • Se quiser ativar efeitos como Bloom (é ótimo para o estilo Pixar no Eevee Next), pode ativar clicando na aba Render Properties > Bloom no Blender.
    • Se surgir outro erro ou dúvida sobre o cenário, materiais, ou animação, só avisar!

    Boa sorte com sua animação e cenário estilo Pixar! ✨🛠️