This Python script is designed to be run within Blender's scripting environment using the bpy module, which provides access to Blender's internal API. The script automates the process of setting up a simple animation for a logo image. Here's a detailed breakdown of what each part of the script does:
1. Imports and Initialization
import bpy
import json
import os
import math
from mathutils import Vector
- bpy: Blender's Python API for scripting.
- json, os, math: Standard Python libraries for handling JSON data, interacting with the operating system, and performing mathematical operations.
- Vector: A utility from Blender's math utilities for vector operations (though not directly used in the script).
2. LogoAnimator Class
The LogoAnimator class encapsulates all the functionality required to set up, animate, and render the logo.
a. Constructor
def __init__(self, project_dir):
self.project_dir = project_dir
self.logo_path = os.path.join(project_dir, "logo.png")
self.config_path = os.path.join(project_dir, "config.json")
- project_dir: Directory where the project files (
logo.png and config.json) are located.
- logo_path: Path to the logo image.
- config_path: Path to the configuration file that specifies animation settings.
b. Setting Up the Scene
def setup_scene(self):
# Clear existing scene
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
# Set up render settings
bpy.context.scene.render.resolution_x = 1024
bpy.context.scene.render.resolution_y = 1024
bpy.context.scene.render.film_transparent = True
bpy.context.scene.render.image_settings.file_format = 'PNG'
bpy.context.scene.render.image_settings.color_mode = 'RGBA'
# Set up animation settings
bpy.context.scene.frame_start = 0
bpy.context.scene.frame_end = 60 # Default 60 frames, can be overridden by config
- Clears the current Blender scene to ensure a fresh start.
- Configures render settings:
- Resolution: 1024x1024 pixels.
- Transparent background.
- Output format: PNG with RGBA channels.
- Sets animation frame range: Starts at frame 0 and ends at frame 60 by default.
c. Creating the Logo Plane
def create_logo_plane(self):
# Create plane
bpy.ops.mesh.primitive_plane_add(size=2)
logo_plane = bpy.context.active_object
# Add material with logo texture
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
# Clear default nodes
nodes.clear()
# Create nodes
texture_coord = nodes.new('ShaderNodeTexCoord')
mapping = nodes.new('ShaderNodeMapping')
image_tex = nodes.new('ShaderNodeTexImage')
transparent = nodes.new('ShaderNodeBsdfTransparent')
mix = nodes.new('ShaderNodeMixShader')
output = nodes.new('ShaderNodeOutputMaterial')
# Load and assign image
image_tex.image = bpy.data.images.load(self.logo_path)
# Connect nodes
links = mat.node_tree.links
links.new(texture_coord.outputs['UV'], mapping.inputs['Vector'])
links.new(mapping.outputs['Vector'], image_tex.inputs['Vector'])
links.new(image_tex.outputs['Color'], mix.inputs[2])
links.new(image_tex.outputs['Alpha'], mix.inputs['Fac'])
links.new(transparent.outputs['BSDF'], mix.inputs[1])
links.new(mix.outputs['Shader'], output.inputs['Surface'])
# Assign material to plane
logo_plane.data.materials.append(mat)
return logo_plane
- Creates a plane in the Blender scene to serve as the canvas for the logo.
- Creates and configures a material with nodes to apply the logo image as a texture:
- Shader Nodes:
- Texture Coordinate and Mapping: Control the placement and scaling of the texture.
- Image Texture: Loads the logo image (
logo.png).
- Transparent BSDF and Mix Shader: Handle transparency based on the image's alpha channel.
- Material Output: Outputs the final shader.
- Assigns the material to the created plane.
- Returns the plane object for further manipulation.
d. Loading Configuration
def load_config(self):
with open(self.config_path, 'r') as f:
return json.load(f)
- Loads the
config.json file which contains animation settings, such as effect type, duration, and parameters.
e. Setting Up Output Path
def setup_output(self, output_path):
# Set output path
bpy.context.scene.render.filepath = output_path
- Configures where the rendered animation will be saved.
f. Rendering the Animation
def render_animation(self):
bpy.ops.render.render(animation=True)
- Initiates the rendering process for the entire animation based on the configured frame range and settings.
g. Applying Effects
def apply_effect(self, logo_object, effect_config):
# This will be expanded based on config.json structure
# Example structure in config.json:
# {
# "effect_type": "rotate",
# "duration_frames": 60,
# "parameters": {
# "rotation_axis": "Z",
# "rotation_amount": 360
# }
# }
effect_type = effect_config.get("effect_type", "none")
if effect_type == "rotate":
self.apply_rotation_effect(logo_object, effect_config["parameters"])
# Add more effects as needed
- Determines the type of effect to apply based on
config.json.
- Currently supports rotation. Additional effects can be added as needed.
h. Applying Rotation Effect
def apply_rotation_effect(self, obj, params):
# Example rotation effect
axis = params.get("rotation_axis", "Z")
amount = params.get("rotation_amount", 360)
duration = params.get("duration_frames", 60)
# Set keyframes
bpy.context.scene.frame_set(0)
if axis == "Z":
obj.rotation_euler.z = 0
obj.keyframe_insert(data_path="rotation_euler", frame=0)
bpy.context.scene.frame_set(duration)
obj.rotation_euler.z = math.radians(amount)
obj.keyframe_insert(data_path="rotation_euler", frame=duration)
elif axis == "X":
obj.rotation_euler.x = 0
obj.keyframe_insert(data_path="rotation_euler", frame=0)
bpy.context.scene.frame_set(duration)
obj.rotation_euler.x = math.radians(amount)
obj.keyframe_insert(data_path="rotation_euler", frame=duration)
elif axis == "Y":
obj.rotation_euler.y = 0
obj.keyframe_insert(data_path="rotation_euler", frame=0)
bpy.context.scene.frame_set(duration)
obj.rotation_euler.y = math.radians(amount)
obj.keyframe_insert(data_path="rotation_euler", frame=duration)
- Handles the rotation animation based on parameters:
- rotation_axis: Axis around which the logo will rotate (
X, Y, or Z).
- rotation_amount: Total rotation in degrees.
- duration_frames: Number of frames over which the rotation occurs.
- Sets keyframes at the start and end frames to animate the rotation.
3. Main Function
def main():
project_dir = r"/mnt/c/Users/Jeff/logo"
animator = LogoAnimator(project_dir)
# Setup scene
animator.setup_scene()
# Create logo plane
logo_obj = animator.create_logo_plane()
# Load and apply effects from config
try:
config = animator.load_config()
animator.apply_effect(logo_obj, config)
except FileNotFoundError:
print("No config.json found. Creating basic setup only.")
# Setup output
animator.setup_output(os.path.join(project_dir, "output"))
# Render
animator.render_animation()
if __name__ == "__main__":
main()
- Defines the project directory where
logo.png and config.json are located.
- Creates an instance of
LogoAnimator.
- Sets up the Blender scene, creates the logo plane, and applies any effects specified in
config.json.
- Handles the case where
config.json is missing by proceeding with a basic setup without effects.
- Specifies the output directory for the rendered animation.
- Starts the rendering process to generate the animation.
4. Configuration File (config.json)
The script expects a config.json file in the project directory to specify animation parameters. An example structure is provided in the comments:
{
"effect_type": "rotate",
"duration_frames": 60,
"parameters": {
"rotation_axis": "Z",
"rotation_amount": 360
}
}
- effect_type: Type of animation effect (e.g., "rotate").
- duration_frames: Number of frames the effect should take.
- parameters: Specific settings related to the effect (e.g., axis and amount for rotation).
Summary
This script automates the creation and animation of a logo within Blender by:
- Clearing the existing scene.
- Setting up render and animation settings.
- Creating a plane with the logo image as a textured material, handling transparency.
- Loading animation effects from a configuration file (
config.json) and applying them (currently supports rotation).
- Setting the output path for the rendered animation.
- Rendering the animation based on the defined settings and effects.
This setup allows for a flexible and automated workflow to generate simple logo animations in Blender, which can be customized further by modifying the configuration file or extending the LogoAnimator class with additional effects.