Skip to content

Instantly share code, notes, and snippets.

@zach-capalbo
Last active June 23, 2024 14:45
Show Gist options
  • Save zach-capalbo/dd95055a8d6ac6441a1a11c168b3def6 to your computer and use it in GitHub Desktop.
Save zach-capalbo/dd95055a8d6ac6441a1a11c168b3def6 to your computer and use it in GitHub Desktop.
# Blender Python script for directing characters with a script.
# See example at bottom for usage
# Author: Zach Capalbo (zachcapalbo.com)
# Copyright (c) 2024 Zach Capalbo
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import bpy
import math
import mathutils
class SpeechText:
speeches = []
def __init__(self, text, start, duration):
self.range = range(start, start + duration)
self.text = text
SpeechText.speeches.append(self)
def handle_frame_change(dummy):
frame = bpy.context.scene.frame_current
bpy.data.objects["Speech"].data.body = "\n".join(speech.text for speech in SpeechText.speeches if frame in speech.range)
class Character:
all = []
manequin = False
def __init__(self, actor_name, manequin = None):
if manequin is None:
manequin = Character.manequin
self.real_actor_name = actor_name
if manequin:
if not f"simple_{actor_name}" in bpy.data.objects:
bpy.ops.object.armature_basic_human_metarig_add()
bpy.context.active_object.name = f"simple_{actor_name}"
self.actor = bpy.data.objects[f"simple_{actor_name}"]
else:
self.actor = bpy.data.objects[actor_name]
self.next_action_frame = 0
self.actor.animation_data_clear()
self.actor.animation_data_create()
self.chill_track = self.actor.animation_data.nla_tracks.new()
self.chill_track.name = "Chill"
chill_strip = self.chill_track.strips.new("chill", 1, bpy.data.actions["Chill"])
self.walk_anim_track = self.actor.animation_data.nla_tracks.new()
self.walk_anim_track.name = "Walking"
self.walk_location_track = self.actor.animation_data.nla_tracks.new()
self.walk_location_track.name = "Location"
self.walking = bpy.data.actions['Walk']
self.speed = 0.1
self.walking_rate = 1
self.actor.rotation_mode = 'QUATERNION'
Character.all.append(self)
def select(self):
bpy.ops.object.select_all(action='DESELECT')
bpy.context.view_layer.objects.active = self.actor
self.actor.select_set(True)
def at(self, frame):
self.next_action_frame = frame
return self
def wait_for(self, character):
self.at(character.next_action_frame)
return self
def start_from(self, object):
start_frame = self.next_action_frame
bpy.context.scene.frame_set(start_frame)
self.actor.location = bpy.data.objects[object].location
self.actor.keyframe_insert(data_path="location", frame=start_frame)
return self
def _walk_to_location(self, end_location, duration = None):
self.select()
start_frame = self.next_action_frame
bpy.context.scene.frame_set(start_frame)
self.actor.keyframe_insert(data_path="location", frame=start_frame)
if duration is None:
duration = round(math.dist(self.actor.location, end_location) / self.speed)
end_frame = self.next_action_frame + duration
bpy.context.scene.frame_set(end_frame)
self.actor.location = end_location
self.actor.keyframe_insert(data_path="location", frame=end_frame)
walk_strip = self.walk_anim_track.strips.new("walk", start_frame, self.walking)
walk_strip.extrapolation = 'NOTHING'
walk_strip.repeat = (end_frame - start_frame) / (self.walking.frame_range[1] - self.walking.frame_range[0]) * self.walking_rate
walk_strip.scale = 1.0 / self.walking_rate
self.next_action_frame = end_frame
return self
def walk_to(self, target, duration = None, offset = None, factor = None):
self.look_at(target)
start_frame = self.next_action_frame
bpy.context.scene.frame_set(start_frame)
end_location = bpy.data.objects[target].location
if offset is not None:
end_location = end_location + offset
if factor is not None:
end_location = self.actor.location.lerp(end_location, factor)
self._walk_to_location(end_location, duration)
return self
def walk_forward(self, distance, duration = None, offset = None):
self._walk_to_location(self.actor.location + distance * (self.actor.rotation_quaternion @ mathutils.Vector((0, -1, 0))))
return self
def look_at(self, target, duration = None):
self.select()
start_frame = self.next_action_frame
bpy.context.scene.frame_set(start_frame)
self.actor.keyframe_insert(data_path="rotation_quaternion", frame=start_frame)
if duration is None:
duration = 4
end_frame = self.next_action_frame + duration
bpy.context.scene.frame_set(end_frame)
self.actor.rotation_quaternion = (bpy.data.objects[target].location - self.actor.location).to_track_quat('-Y', 'Z')
self.actor.keyframe_insert(data_path="rotation_quaternion", frame=end_frame)
return self
def wait(self, duration):
self.next_action_frame += duration
return self
def set_speed(self, speed):
self.speed = speed
return self
def play(self, action_name, duration = None, extrapolation='NOTHING', parallel=False):
action = bpy.data.actions[action_name]
if duration is None:
duration = action.frame_range[1] - action.frame_range[0]
start_frame = self.next_action_frame
end_frame = round(self.next_action_frame + duration)
strip = self.walk_anim_track.strips.new(action_name, start_frame, action)
strip.extrapolation = extrapolation
strip.repeat = (duration) / max(1, (action.frame_range[1] - action.frame_range[0]))
if not parallel:
self.next_action_frame = end_frame
return self
def start(self, action_name, duration = None):
return self.play(action_name, duration=duration, extrapolation='HOLD_FORWARD', parallel=True)
def say(self, text, duration = 100):
SpeechText(text, self.next_action_frame, duration)
return self
def bake(self):
self.select()
bpy.ops.nla.bake(frame_start=1, frame_end=self.next_action_frame, only_selected=False, bake_types={'POSE', 'OBJECT'})
self.actor.animation_data.nla_tracks.remove(self.walk_anim_track)
self.actor.animation_data.nla_tracks.remove(self.chill_track)
self.actor.animation_data.nla_tracks.remove(self.walk_location_track)
def sync():
last_action = max(c.next_action_frame for c in Character.all)
for c in Character.all:
c.next_action_frame = last_action
def apply_manequin(self):
if self.real_actor_name == self.actor.name:
return
bpy.ops.object.select_all(action='DESELECT')
bpy.data.objects[self.real_actor_name].select_set(True)
bpy.context.view_layer.objects.active = self.actor
bpy.ops.object.make_links_data(type='ANIMATION')
bpy.data.objects[self.real_actor_name].select_set(False)
self.actor.select_set(False)
def apply_manequins():
for c in Character.all:
c.apply_manequin()
# Uncomment and add a text object named "Speech" to enable the say method
#bpy.app.handlers.frame_change_pre.clear()
#bpy.app.handlers.frame_change_pre.append(SpeechText.handle_frame_change)
# Example:
# Here's a simple exmple showing general usage.
# This example assumes a scene with rigged character armatures named "Bob" and "Joe",
# and empties named "Entrance" "StageLeft", "Audience", "ASpecificSpot", and an action named "JumpingJack"
#
# An action named "Walk" is required for the walk_to method.
bob = Character("Bob")
(bob.starting_from("Entrance")
.walk_to("StageLeft")
.look_at("Audience"))
joe = Character("Joe")
(joe.starting_from("Entrance")
.walk_to("ASpecificSpot")
.look_at("StageLeft")
.wait(20)
.play("JumpingJack"))
(bob.wait_for(joe)
.play("JumpingJack")
.walk_to("Entrance"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment