[Blender] glb, gltf 파일 Alpha 애니메이션 자동화 스크립트

2024. 9. 27. 12:28Blender

728x90
반응형

 

 


 

 

개요

Blender에서 glb 파일 포맷으로 export 할 때, Material 관련 애니메이션은 사용할 수 없다. 예전부터 제기되어 왔던 주제인데 아직 적용되지 않고 있는 듯 하다.

Material 애니메이션 중에 가장 잘 쓸 수 있는 부분은 Alpha FadeOut 효과로, 특정 오브젝트를 투명하게 서서히 사라지게 만든다. glb/gltf 포맷에서도 마찬가지로 사용하기 위해서는 조금의 트릭이 필요하다.

 

 

Alpha Fadeout을 적용하고 싶은 오브젝트를 프레임 단위로 복제하여 각각에 다른 Alpha 값을 부여하면 된다. 오브젝트를 복제한다는 것이 복잡한 오브젝트에 대해서는 꽤나 부하를 가져올 것 같은 생각이 든다. 이 부분에 대해서 Collection Instance를 테스트로 적용해보았지만 결국 오브젝트마다 다른 Alpha를 적용하기 위해서는 일반적인 Duplicate Object 방식으로 진행해야 한다는 부분을 경험했다.

 

 


 

 

AlphaFadeout 오브젝트 복제 스크립트

import bpy

# Define the number of duplicates
Num = 10  # Change this value to adjust the number of duplicates

# Enable Backface Culling and set Alpha Blend for the selected object
def set_backface_culling_and_alpha_blend(obj):
    if obj.active_material:
        mat = obj.active_material
        # Enable Backface Culling
        mat.use_backface_culling = True
        # Set Alpha Blend
        mat.blend_method = 'BLEND'
        return mat
    else:
        print(f"Object {obj.name} has no active material.")
        return None

# Duplicate the selected object and unlink materials
def duplicate_object(obj, num):
    new_objects = []
    for i in range(num):
        # Duplicate the object
        bpy.ops.object.duplicate(linked=False)
        new_obj = bpy.context.object
        new_objects.append(new_obj)
        
        # Unlink the material (create a unique material for each object)
        if new_obj.active_material:
            new_material = new_obj.active_material.copy()
            new_obj.active_material = new_material

    return new_objects

# Set the Alpha value of the object's material
def set_alpha_value(obj, alpha_value):
    if obj.active_material and obj.active_material.node_tree:
        nodes = obj.active_material.node_tree.nodes
        if 'Principled BSDF' in nodes:
            # Access Principled BSDF node
            bsdf_node = nodes.get('Principled BSDF')
            bsdf_node.inputs['Alpha'].default_value = alpha_value

# Main function to run the script
def main():
    # Get the selected object
    selected_obj = bpy.context.active_object
    if not selected_obj:
        print("No object selected.")
        return

    # Set Backface Culling and Alpha Blend for the original object
    original_material = set_backface_culling_and_alpha_blend(selected_obj)
    if not original_material:
        print("Selected object has no material, stopping script.")
        return

    # Duplicate the object for the number of times specified by 'Num'
    duplicated_objects = duplicate_object(selected_obj, Num)

    # Set the Alpha value for each duplicated object and keep them at the same position (0, 0, 0)
    for i, obj in enumerate([selected_obj] + duplicated_objects):
        alpha_value = 1 - (1/Num) * i
        set_alpha_value(obj, alpha_value)

        # Set position to (0, 0, 0)
        obj.location = (0, 0, 0)

        print(f"Object: {obj.name}, Alpha: {alpha_value}")

if __name__ == "__main__":
    main()

최상단의 Num 변수에 복제할 만큼의 수를 넣는다. 이후 복제하고자 하는 오브젝트를 선택한 후 스크립트를 실행한다. 선택한 기준 오브젝트의 메테리얼은 Alpha Blend가 되고 Backface Culling 옵션도 활성화했다. 이후 Num 변수 크기만큼 오브젝트가 복제되고 Num의 개수에 따라서 Alpha 값이 점점 작아진다. 예를 들어 Num이 10이면 Alpha 값은 0.1씩, Num이 20이면 Alpha 값은 0.05씩 줄어들게 된다. 마지막에 Alpha가 0이 될 때까지.

 

 


 

 

 

사용 방법

  • 오브젝트를 하나 생성하고 원하는 메테리얼을 적용한다.

 

  • 오브젝트를 선택한 후 스크립트를 실행하면 오브젝트가 복제된다.

 

 


 

 

Particle System 생성 스크립트

import bpy

# Number of particle systems you want to create
num_particle_systems = 21

# Define the base name of the objects to be used as particle instances
object_name_base = "Suzanne"  # Replace "abc" with your desired base name for particle objects

# Object names to be used as the instance for each particle system
# e.g., "abc", "abc.001", "abc.002", ...
instance_objects = [f"{object_name_base}{'' if i == 0 else f'.{str(i).zfill(3)}'}" for i in range(num_particle_systems)]
print(f"Instance objects list: {instance_objects}")

# Get the selected object
selected_obj = bpy.context.active_object

# Check if an object is selected
if selected_obj is None:
    raise Exception("No object selected. Please select an object in the scene.")

# Main function to add particle systems to the selected object
def create_particle_systems(obj, num_systems):
    for i in range(num_systems):
        # Create a new particle system
        particle_sys = obj.modifiers.new(name=f"ParticleSystem_{i+1}", type='PARTICLE_SYSTEM')
        psys = obj.particle_systems[-1]
        
        # Set the particle system's settings
        psettings = psys.settings
        psettings.count = 1  # Number of particles
        psettings.frame_start = i + 1  # Frame start increases
        psettings.frame_end = i + 1  # Frame end equals frame start
        psettings.lifetime = 1  # Particle lifetime set to 1
        psettings.emit_from = 'FACE'  # Emit from faces
        psettings.use_emit_random = False  # Emit from exactly one face
        psettings.userjit = 1
        psettings.normal_factor = 0  # Set velocity normal to 0
        psettings.render_type = 'OBJECT'  # Render as object
        
        # Set the instance object for each particle system using the name list
        instance_obj = bpy.data.objects.get(instance_objects[i])
        if instance_obj:
            psettings.instance_object = instance_obj
        else:
            print(f"Warning: {instance_objects[i]} not found. Skipping particle system {i + 1}.")
        
        psettings.particle_size = 1.0  # Set render scale to 1.0
        psettings.use_rotation_instance = True  # Use object rotation
        psettings.effector_weights.gravity = 0  # Disable gravity

# Run the function to create particle systems on the selected object
create_particle_systems(selected_obj, num_particle_systems)

print(f"Created {num_particle_systems} particle systems on {selected_obj.name}")

최상단 num_particle_systems 변수에는 복제한 오브젝트 만큼의 수에 1을 더한 값을 넣는다.

object_name_base 변수에는 복제할 기준 오브젝트의 이름을 큰따옴표를 이용하여 string 형태로 입력한다.

 

 


 

 

사용 방법

Emitter가 될 오브젝트를 하나 만든다. Plane 생성

 

 

Emitter가 될 오브젝트를 선택한 후 스크립트를 실행하면 Particle System이 생성되는 것을 볼 수 있다.

 

 

이미 각 프레임마다 Alpha 값이 설정된 상태이기 때문에 Timeline을 실행하면 Alpha 애니메이션이 잘 작동하는 것을 볼 수 있다.

 

 


 

 

glb 포맷으로 Export

이제 Govie Tools를 이용해서 각 프레임마다 생성되는 Particle을 export 하면 된다.

export 과정은 이전 글에 썼던 내용과 완전히 동일하기 때문에 참고하면 된다.

 

[Blender] 블렌더에서 플립북 텍스쳐(FlipBook Texture) 스크립트 자동화 적용

이전 글에서 Flipbook 형태로 되어있는 텍스쳐를 사용하여 애니메이션을 만들어 보았다. 이 작업을 스크립트를 사용하여 자동화 해보았다. [Blender] 블렌더에서 플립북 텍스쳐(FlipBook Texture) 사용하

lightbakery.tistory.com

 

 

728x90
반응형