本文整理汇总了Python中mathutils.Matrix.invert方法的典型用法代码示例。如果您正苦于以下问题:Python Matrix.invert方法的具体用法?Python Matrix.invert怎么用?Python Matrix.invert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mathutils.Matrix
的用法示例。
在下文中一共展示了Matrix.invert方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DefQuickParent
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def DefQuickParent(inf, out):
ob = bpy.context.object
if ob.type == "ARMATURE":
target = [object for object in bpy.context.selected_objects if object != ob][0]
ob = bpy.context.active_pose_bone if bpy.context.object.type == 'ARMATURE' else bpy.context.object
target.select = False
bpy.context.scene.frame_set(frame=bpy.context.scene.quick_animation_in)
a = Matrix(target.matrix_world)
a.invert()
i = Matrix(ob.matrix)
for frame in range(inf, out):
bpy.context.scene.frame_set(frame=frame)
ob.matrix = target.matrix_world * a * i
bpy.ops.anim.keyframe_insert(type="LocRotScale")
else:
target = [object for object in bpy.context.selected_objects if object != ob][0]
ob = bpy.context.active_pose_bone if bpy.context.object.type == 'ARMATURE' else bpy.context.object
target.select = False
bpy.context.scene.frame_set(frame=bpy.context.scene.quick_animation_in)
a = Matrix(target.matrix_world)
a.invert()
i = Matrix(ob.matrix_world)
for frame in range(inf, out):
bpy.context.scene.frame_set(frame=frame)
ob.matrix_world = target.matrix_world * a * i
bpy.ops.anim.keyframe_insert(type="LocRotScale")
示例2: AnimateBone
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def AnimateBone(name,pose,motions,num_frames,armature,armOb,version):
if name not in armature.bones.keys():
log ('%s not found in armature' % name)
return
motion = motions[name]
bone = armature.bones[name]
bone_rest_matrix = Matrix(bone.matrix_local)
if bone.parent is not None:
parent_bone = bone.parent
parent_rest_bone_matrix = Matrix(parent_bone.matrix_local)
parent_rest_bone_matrix.invert()
bone_rest_matrix = parent_rest_bone_matrix * bone_rest_matrix
bone_rest_matrix_inv = Matrix(bone_rest_matrix)
bone_rest_matrix_inv.invert()
pbone = pose.bones[name]
prev_euler = Euler()
for i in range(0, num_frames):
transform,size = getTransformMatrix(motions,bone,i,version)
transform = bone_rest_matrix_inv * transform
pbone.rotation_quaternion = transform.to_quaternion()
pbone.location = (transform).to_translation()
pbone.keyframe_insert(data_path='rotation_quaternion',frame=i)
pbone.keyframe_insert(data_path='location',frame=i)
示例3: calculate_best_plane
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def calculate_best_plane(locs):
# calculating the center of masss
com = Vector()
for loc in locs:
com += loc
com /= len(locs)
x, y, z = com
# creating the covariance matrix
mat = Matrix(((0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
))
for loc in locs:
mat[0][0] += (loc[0]-x)**2
mat[1][0] += (loc[0]-x)*(loc[1]-y)
mat[2][0] += (loc[0]-x)*(loc[2]-z)
mat[0][1] += (loc[1]-y)*(loc[0]-x)
mat[1][1] += (loc[1]-y)**2
mat[2][1] += (loc[1]-y)*(loc[2]-z)
mat[0][2] += (loc[2]-z)*(loc[0]-x)
mat[1][2] += (loc[2]-z)*(loc[1]-y)
mat[2][2] += (loc[2]-z)**2
# calculating the normal to the plane
normal = False
try:
mat.invert()
except:
if sum(mat[0]) == 0.0:
normal = Vector((1.0, 0.0, 0.0))
elif sum(mat[1]) == 0.0:
normal = Vector((0.0, 1.0, 0.0))
elif sum(mat[2]) == 0.0:
normal = Vector((0.0, 0.0, 1.0))
if not normal:
# warning! this is different from .normalize()
itermax = 500
iter = 0
vec = Vector((1.0, 1.0, 1.0))
vec2 = (mat * vec)/(mat * vec).length
while vec != vec2 and iter<itermax:
iter+=1
vec = vec2
vec2 = mat * vec
if vec2.length != 0:
vec2 /= vec2.length
if vec2.length == 0:
vec2 = Vector((1.0, 1.0, 1.0))
normal = vec2
return(com, normal)
示例4: pointInTri2D
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def pointInTri2D(v, v1, v2, v3):
global dict_matrix
key = v1.x, v1.y, v2.x, v2.y, v3.x, v3.y
# Commented because its slower to do teh bounds check, we should realy cache the bounds info for each face.
'''
# BOUNDS CHECK
xmin= 1000000
ymin= 1000000
xmax= -1000000
ymax= -1000000
for i in (0,2,4):
x= key[i]
y= key[i+1]
if xmax<x: xmax= x
if ymax<y: ymax= y
if xmin>x: xmin= x
if ymin>y: ymin= y
x= v.x
y= v.y
if x<xmin or x>xmax or y < ymin or y > ymax:
return False
# Done with bounds check
'''
try:
mtx = dict_matrix[key]
if not mtx:
return False
except:
side1 = v2 - v1
side2 = v3 - v1
nor = side1.cross(side2)
mtx = Matrix((side1, side2, nor))
# Zero area 2d tri, even tho we throw away zerop area faces
# the projection UV can result in a zero area UV.
if not mtx.determinant():
dict_matrix[key] = None
return False
mtx.invert()
dict_matrix[key] = mtx
uvw = (v - v1) * mtx
return 0 <= uvw[0] and 0 <= uvw[1] and uvw[0] + uvw[1] <= 1
示例5: execute
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def execute(self, context):
print("Executing...")
# blendseg_instance needs to qualified *explicitly*
# the first time, otherwise a member variable is
# created instead, masking the static class var
ob = context.object
image_orientation=[]
# Apply affine transform specified by this dude's matrix
transform = Matrix([[ob.affine_tx_00, ob.affine_tx_01, ob.affine_tx_02, ob.affine_tx_03],
[ob.affine_tx_10, ob.affine_tx_11, ob.affine_tx_12, ob.affine_tx_13],
[ob.affine_tx_20, ob.affine_tx_21, ob.affine_tx_22, ob.affine_tx_23],
[ob.affine_tx_30, ob.affine_tx_31, ob.affine_tx_32, ob.affine_tx_33]])
# print ('Affine')
# print (transform)
transform.transpose()
transform.invert()
# print ('Inverse')
# print (transform)
print ("Applying pre-transform!")
print (ob.affine_after_voxel_spacing)
print (ob.affine_after_origin)
for vert in ob.data.vertices:
txd = vert.co*transform
txd[0] = txd[0]*ob.affine_after_voxel_spacing[0] + ob.affine_after_origin[0]
txd[1] = txd[1]*ob.affine_after_voxel_spacing[1] + ob.affine_after_origin[1]
txd[2] = txd[2]*ob.affine_after_voxel_spacing[2] + ob.affine_after_origin[2]
vert.co = txd
return {'FINISHED'}
示例6: bvh_node_dict2armature
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
#.........这里部分代码省略.........
pose_bone["zero"] = True
pose_bone.rotation_mode = bvh_node.rot_order_str
elif rotate_mode != 'QUATERNION':
for pose_bone in pose_bones:
pose_bone.rotation_mode = rotate_mode
else:
# Quats default
pass
context.scene.update()
if rig_only:
# fix this to have action part too.
arm_ob.matrix_world = global_matrix
bpy.ops.object.transform_apply(rotation=True)
return arm_ob
arm_ob.animation_data_create()
action = bpy.data.actions.new(name=bvh_name)
arm_ob.animation_data.action = action
# Replace the bvh_node.temp (currently an editbone)
# With a tuple (pose_bone, armature_bone, bone_rest_matrix, bone_rest_matrix_inv)
num_frame = 0
for bvh_node in bvh_nodes_list:
bone_name = bvh_node.temp # may not be the same name as the bvh_node, could have been shortened.
pose_bone = pose_bones[bone_name]
rest_bone = arm_data.bones[bone_name]
bone_rest_matrix = rest_bone.matrix_local.to_3x3()
bone_rest_matrix_inv = Matrix(bone_rest_matrix)
bone_rest_matrix_inv.invert()
bone_rest_matrix_inv.resize_4x4()
bone_rest_matrix.resize_4x4()
#XXXX bone removed from bvh_node.temp
bvh_node.temp = (pose_bone, bone_rest_matrix, bone_rest_matrix_inv)
if 0 == num_frame:
num_frame = len(bvh_node.anim_data)
# Choose to skip some frames at the beginning. Frame 0 is the rest pose
# used internally by this importer. Frame 1, by convention, is also often
# the rest pose of the skeleton exported by the motion capture system.
bt = 1.0 / context.scene.render.fps
print("FT, BT", bvh_frame_time, bt, floor(bt / bvh_frame_time))
sub_frame_step = 1
if use_frame_step:
sub_frame_step = floor(bt / bvh_frame_time)
if sub_frame_step == 0:
sub_frame_step = 1
skip_frame = 1
if num_frame > skip_frame:
num_frame = num_frame - skip_frame
# Create a shared time axis for all animation curves.
time = [float(frame_start)] * num_frame
dt = 0.0
if use_fps_scale:
dt = scene.render.fps * bvh_frame_time
for frame_i in range(1, num_frame):
time[frame_i] += float(frame_i) * dt
else:
sub_frame_step = 1
示例7: draw
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def draw(self, context):
layout = self.layout
sce = context.scene
# Get a single selected object (or nothing).
obj = getSingleObject(context)
drawTansformButtons = 1
if (context.mode == 'EDIT_MESH'):
obj = context.active_object
if (obj and obj.type == 'MESH' and obj.data):
# "Note: a Mesh will return the selection state of the mesh
# when EditMode was last exited. A Python script operating
# in EditMode must exit EditMode before getting the current
# selection state of the mesh."
# http://www.blender.org/documentation/249PythonDoc/
# /Mesh.MVert-class.html#sel
# We can only provide this by existing & re-entering EditMode.
# @todo: Better way to do this?
# Get mesh data from Object.
mesh = obj.data
# Get transformation matrix from object.
ob_mat = obj.matrix_world
# Also make an inversed copy! of the matrix.
ob_mat_inv = ob_mat.copy()
Matrix.invert(ob_mat_inv)
# Get the selected vertices.
# @todo: Better (more efficient) way to do this?
verts_selected = [v for v in mesh.vertices if v.select == 1]
if len(verts_selected) == 0:
# Nothing selected.
# We measure the distance from...
# local ... the object center to the 3D cursor.
# global ... the origin to the 3D cursor.
box = layout.box()
row = box.row()
row.prop(sce, "measure_panel_dist")
row = box.row()
row.label(text="", icon='CURSOR')
row.label(text="", icon='ARROW_LEFTRIGHT')
if measureLocal(sce):
row.label(text="Obj. Center")
else:
row.label(text="Origin [0,0,0]")
row = layout.row()
row.operator("view3d.reenter_editmode",
text="Update selection & distance")
# @todo
# description="The surface area value can" \
# " not be updated in mesh edit mode" \
# " automatically. Press this button" \
# " to do this manually, after you changed" \
# " the selection")
elif len(verts_selected) == 1:
# One vertex selected.
# We measure the distance from the
# selected vertex object to the 3D cursor.
box = layout.box()
row = box.row()
row.prop(sce, "measure_panel_dist")
row = box.row()
row.label(text="", icon='CURSOR')
row.label(text="", icon='ARROW_LEFTRIGHT')
row.label(text="", icon='VERTEXSEL')
row = layout.row()
row.operator("view3d.reenter_editmode",
text="Update selection & distance")
elif len(verts_selected) == 2:
# Two vertices selected.
# We measure the distance between the
# two selected vertices.
box = layout.box()
row = box.row()
row.prop(sce, "measure_panel_dist")
row = box.row()
row.label(text="", icon='VERTEXSEL')
row.label(text="", icon='ARROW_LEFTRIGHT')
row.label(text="", icon='VERTEXSEL')
row = layout.row()
row.operator("view3d.reenter_editmode",
text="Update selection & distance")
else:
#.........这里部分代码省略.........
示例8: draw_measurements_callback
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
#.........这里部分代码省略.........
blf.position(0, loc_x, loc_y, 0)
blf.draw(0, text)
blf.position(0, loc_x + OFFSET_VALUE, loc_y, 0)
blf.draw(0, value)
loc_y -= OFFSET_Y
# Handle mesh surface area calulations
if (sce.measure_panel_calc_area):
# Get a single selected object (or nothing).
obj = getSingleObject(context)
if (context.mode == 'EDIT_MESH'):
obj = context.active_object
if (obj and obj.type == 'MESH' and obj.data):
# "Note: a Mesh will return the selection state of the mesh
# when EditMode was last exited. A Python script operating
# in EditMode must exit EditMode before getting the current
# selection state of the mesh."
# http://www.blender.org/documentation/249PythonDoc/
# /Mesh.MVert-class.html#sel
# We can only provide this by existing & re-entering EditMode.
# @todo: Better way to do this?
# Get mesh data from Object.
mesh = obj.data
# Get transformation matrix from object.
ob_mat = obj.matrix_world
# Also make an inversed copy! of the matrix.
ob_mat_inv = ob_mat.copy()
Matrix.invert(ob_mat_inv)
# Get the selected vertices.
# @todo: Better (more efficient) way to do this?
verts_selected = [v for v in mesh.vertices if v.select == 1]
if len(verts_selected) >= 3:
# Get selected faces
# @todo: Better (more efficient) way to do this?
faces_selected = [f for f in mesh.faces
if f.select == 1]
if len(faces_selected) > 0:
area, normal = objectSurfaceArea(obj, True,
measureGlobal(sce))
if (area >= 0):
sce.measure_panel_area1 = area
sce.measure_panel_normal1 = normal
elif (context.mode == 'OBJECT'):
# We are working in object mode.
if len(context.selected_objects) > 2:
return
# @todo Make this work again.
# # We have more that 2 objects selected...
#
# mesh_objects = [o for o in context.selected_objects
# if (o.type == 'MESH')]
# if (len(mesh_objects) > 0):
# # ... and at least one of them is a mesh.
#
示例9: unposeMesh
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def unposeMesh(meshObToUnpose, meshObToUnposeWeightSrc, armatureOb):
psdMeshData = meshObToUnpose
psdMesh = psdMeshData
I = Matrix() # identity matrix
meshData = meshObToUnposeWeightSrc.data
mesh = meshData
armData = armatureOb.data
pose = armatureOb.pose
pbones = pose.bones
for index, v in enumerate(mesh.vertices):
# above is python shortcut for:index goes up from 0 to tot num of
# verts in mesh, with index incrementing by 1 each iteration
psdMeshVert = psdMesh[index]
listOfBoneNameWeightPairs = []
for n in mesh.vertices[index].groups:
try:
name = meshObToUnposeWeightSrc.vertex_groups[n.group].name
weight = n.weight
is_bone = False
for i in armData.bones:
if i.name == name:
is_bone = True
break
# ignore non-bone vertex groups
if is_bone:
listOfBoneNameWeightPairs.append([name, weight])
except:
print('error')
pass
weightedAverageDictionary = {}
totalWeight = 0
for pair in listOfBoneNameWeightPairs:
totalWeight += pair[1]
for pair in listOfBoneNameWeightPairs:
if totalWeight > 0: # avoid divide by zero!
weightedAverageDictionary[pair[0]] = pair[1] / totalWeight
else:
weightedAverageDictionary[pair[0]] = 0
# Matrix filled with zeros
sigma = Matrix()
sigma.zero()
list = []
for n in pbones:
list.append(n)
list.reverse()
for pbone in list:
if pbone.name in weightedAverageDictionary:
#~ print("found key %s", pbone.name)
vertexWeight = weightedAverageDictionary[pbone.name]
m = pbone.matrix_channel.copy()
#m.transpose()
sigma += (m - I) * vertexWeight
else:
pass
#~ print("no key for bone " + pbone.name)
sigma = I + sigma
sigma.invert()
psdMeshVert.co = psdMeshVert.co * sigma
示例10: bvh_node_dict2armature
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
#.........这里部分代码省略.........
# Now Apply the animation to the armature
# Get armature animation data
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
pose = arm_ob.pose
pose_bones = pose.bones
if rotate_mode == 'NATIVE':
for bvh_node in bvh_nodes.values():
bone_name = bvh_node.temp # may not be the same name as the bvh_node, could have been shortened.
pose_bone = pose_bones[bone_name]
pose_bone.rotation_mode = bvh_node.rot_order_str
elif rotate_mode != 'QUATERNION':
for pose_bone in pose_bones:
pose_bone.rotation_mode = rotate_mode
else:
# Quats default
pass
context.scene.update()
arm_ob.animation_data_create()
action = bpy.data.actions.new(name=bvh_name)
arm_ob.animation_data.action = action
# Replace the bvh_node.temp (currently an editbone)
# With a tuple (pose_bone, armature_bone, bone_rest_matrix, bone_rest_matrix_inv)
for bvh_node in bvh_nodes.values():
bone_name = bvh_node.temp # may not be the same name as the bvh_node, could have been shortened.
pose_bone = pose_bones[bone_name]
rest_bone = arm_data.bones[bone_name]
bone_rest_matrix = rest_bone.matrix_local.to_3x3()
bone_rest_matrix_inv = Matrix(bone_rest_matrix)
bone_rest_matrix_inv.invert()
bone_rest_matrix_inv.resize_4x4()
bone_rest_matrix.resize_4x4()
bvh_node.temp = (pose_bone, bone, bone_rest_matrix, bone_rest_matrix_inv)
# Make a dict for fast access without rebuilding a list all the time.
# KEYFRAME METHOD, SLOW, USE IPOS DIRECT
# TODO: use f-point samples instead (Aligorith)
if rotate_mode != 'QUATERNION':
prev_euler = [Euler() for i in range(len(bvh_nodes))]
# Animate the data, the last used bvh_node will do since they all have the same number of frames
for frame_current in range(len(bvh_node.anim_data) - 1): # skip the first frame (rest frame)
# print frame_current
# if frame_current==40: # debugging
# break
scene.frame_set(frame_start + frame_current)
# Dont neet to set the current frame
for i, bvh_node in enumerate(bvh_nodes.values()):
pose_bone, bone, bone_rest_matrix, bone_rest_matrix_inv = bvh_node.temp
lx, ly, lz, rx, ry, rz = bvh_node.anim_data[frame_current + 1]
if bvh_node.has_rot:
# apply rotation order and convert to XYZ
# note that the rot_order_str is reversed.
bone_rotation_matrix = Euler((rx, ry, rz), bvh_node.rot_order_str[::-1]).to_matrix().to_4x4()
bone_rotation_matrix = bone_rest_matrix_inv * bone_rotation_matrix * bone_rest_matrix
if rotate_mode == 'QUATERNION':
pose_bone.rotation_quaternion = bone_rotation_matrix.to_quaternion()
else:
euler = bone_rotation_matrix.to_euler(pose_bone.rotation_mode, prev_euler[i])
pose_bone.rotation_euler = euler
prev_euler[i] = euler
if bvh_node.has_loc:
pose_bone.location = (bone_rest_matrix_inv * Matrix.Translation(Vector((lx, ly, lz)) - bvh_node.rest_head_local)).to_translation()
if bvh_node.has_loc:
pose_bone.keyframe_insert("location")
if bvh_node.has_rot:
if rotate_mode == 'QUATERNION':
pose_bone.keyframe_insert("rotation_quaternion")
else:
pose_bone.keyframe_insert("rotation_euler")
for cu in action.fcurves:
if IMPORT_LOOP:
pass # 2.5 doenst have cyclic now?
for bez in cu.keyframe_points:
bez.interpolation = 'LINEAR'
# finally apply matrix
arm_ob.matrix_world = global_matrix
bpy.ops.object.transform_apply(rotation=True)
return arm_ob
示例11: do_export
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def do_export(context, filename):
print ("Start BR2 Export...")
file = open( filename, 'w')
scene = context.scene
filedata = "// Nexus Buddy BR2 - Exported from Blender for import to Nexus Buddy 2\n"
modelObs = {}
modelMeshes = {}
boneIds = {}
for object in bpy.data.objects:
if object.type == 'ARMATURE':
modelObs[object.name] = object
if object.type == 'MESH':
print ("Getting parent for mesh: %s" % object.name)
parentArmOb = object.modifiers[0].object
if not parentArmOb.name in modelMeshes:
modelMeshes[parentArmOb.name] = []
modelMeshes[parentArmOb.name].append(object)
for modelObName in modelObs.keys():
# Write Skeleton
filedata += "skeleton\n"
armOb = modelObs[modelObName]
armature = armOb.data
# Calc bone depths and sort
boneDepths = []
for bone in armature.bones.values():
boneDepth = getBoneTreeDepth(bone, 0)
boneDepths.append((bone, boneDepth))
boneDepths = sorted(boneDepths, key=lambda k: k[0].name)
boneDepths = sorted(boneDepths, key=lambda k: k[1])
sortedBones = boneDepths
for boneid, boneTuple in enumerate(sortedBones):
boneIds[boneTuple[0].name] = boneid
# Write World Bone
filedata += '%d "%s" %d ' % (0, armOb.name, -1)
filedata += '%.8f %.8f %.8f ' % (0.0, 0.0, 0.0)
filedata += '%.8f %.8f %.8f %.8f ' % (0.0, 0.0, 0.0, 1.0)
filedata += '%.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f\n' % (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
for boneid, boneTuple in enumerate(sortedBones):
bone = boneTuple[0]
boneDepth = boneTuple[1]
position, orientationQuat = getTranslationOrientation(bone, file)
# Get Inverse World Matrix for bone
x = bone.matrix_local.copy()
x.transpose()
t = Matrix([[-x[2][0], -x[2][1], -x[2][2], -x[2][3]],
[x[1][0], x[1][1], x[1][2], x[1][3]],
[x[0][0], x[0][1], x[0][2], x[0][3]],
[x[3][0], x[3][1], x[3][2], x[3][3]]])
t.invert()
invWorldMatrix = Matrix([[t[0][1], -t[0][0], t[0][2], t[0][3]],
[t[1][1], -t[1][0], t[1][2], t[1][3]],
[t[2][1], -t[2][0], t[2][2], t[2][3]],
[t[3][1], -t[3][0], t[3][2], t[3][3]]])
outputBoneName = bone.name
filedata += '%d "%s" ' % (boneid + 1, outputBoneName) # Adjust bone ids + 1 as zero is the World Bone
parentBoneId = 0
if bone.parent:
parentBoneId = boneIds[bone.parent.name] + 1 # Adjust bone ids + 1 as zero is the World Bone
filedata += '%d ' % parentBoneId
filedata +='%.8f %.8f %.8f ' % (position[0], position[1], position[2])
filedata +='%.8f %.8f %.8f %.8f ' % (orientationQuat[1], orientationQuat[2], orientationQuat[3], orientationQuat[0]) # GR2 uses x,y,z,w for Quaternions rather than w,x,y,z
filedata += '%.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f %.8f' % (invWorldMatrix[0][0], invWorldMatrix[0][1], invWorldMatrix[0][2], invWorldMatrix[0][3],
invWorldMatrix[1][0], invWorldMatrix[1][1], invWorldMatrix[1][2], invWorldMatrix[1][3],
invWorldMatrix[2][0], invWorldMatrix[2][1], invWorldMatrix[2][2], invWorldMatrix[2][3],
invWorldMatrix[3][0], invWorldMatrix[3][1], invWorldMatrix[3][2], invWorldMatrix[3][3])
#End of bone line
filedata += "\n"
filedata += 'meshes:%d\n' % len(modelMeshes[modelObName])
for meshObject in modelMeshes[modelObName]:
mesh = meshObject.data
meshName = meshObject.name
filedata += 'mesh:"%s"\n' % meshName
parentArmOb = meshObject.modifiers[0].object
weights = meshNormalizedWeights(meshObject, mesh)
vertexBoneWeights = {}
#.........这里部分代码省略.........
示例12: buildANM
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def buildANM(filename=None, armObj=None):
import bpy
from mathutils import Quaternion, Vector, Matrix
from time import sleep
armObj = bpy.data.objects['lolArmature']
filename =\
'/var/tmp/downloads/lol/Characters/Wolfman/Animations/Wolfman_Attack1.anm'
#'/Users/zac/Desktop/LoL Modeling/Characters/Wolfman/Animations/Wolfman_attack1.anm'
header, animation = importANM(filename)
#bpy.ops.object.mode_set(mode='EDIT')
#bpy.ops.object.select_all()
#bpy.ops.armature.parent_clear('DISCONNECT')
#Generate keyframes
#for f in range(header['numFrames']):
#bpy.ops.anim.change_frame(frame = f)
#set frame = f
#create keyframe
#generate boneIdx:{name, pos} dictionary
#Animations appear to be prerotated -90x?
restPose = {}
for bone in armObj.data.bones:
rotationMatrix = bone.matrix.rotation_part()
quat = rotationMatrix.to_quat()
rotationMatrixInv = Matrix(rotationMatrix)
rotationMatrixInv = rotationMatrixInv.invert()
restPose[bone.name] = {'pos':bone.tail,
'rotMatrix':rotationMatrix.resize4x4(),
'rotMatrixInv':rotationMatrixInv.resize4x4(),
'quat':quat}
#redo animation list
#Go into pose mode
bpy.ops.object.mode_set(mode='POSE', toggle=False)
#For each frame, loop through bones:
#for f in range(header['numFrames']):
#Create heirarchy
rootBone = armObj.data.bones[0]
boneLevelHeirary = buildBoneHeirarchy(rootBone)
#for f in range(header['numFrames']):
for f in range(1):
#Change to frame # f
bpy.ops.anim.change_frame(frame=f)
k=0
for boneLevel in boneLevelHeirary:#[:1]:
for bone in boneLevel:
boneName = bone.name
pBone = armObj.pose.bones[boneName]
aBone = armObj.data.bones[boneName]
#Check if this bone has animation data for it, skip if it
#doesn't
if boneName not in animation.keys():
print('Couldn\'t find bone %s in animation data'%
(boneName,))
continue
#Get new location
newLoc = Vector(animation[boneName]['pos'][f])# - \
#restPose[boneName]['pos']
#Get new Quaternion
'''
newQ = Quaternion()
newQ.x = animation[boneName]['quat'][f][1]
newQ.y = animation[boneName]['quat'][f][2]
newQ.z = animation[boneName]['quat'][f][3]
newQ.angle = animation[boneName]['quat'][f][0]# * 3.14159/180.0
'''
w,x,y,z = animation[boneName]['quat'][f][:]
frameQ = Quaternion((w,x,y,z))
#oldQ = pBone.rotation_quaternion
oldQ = aBone.matrix.to_quat()
print(oldQ)
#newQ = oldQ.inverse() * frameQ*oldQ
newQ = frameQ
#newQ = Quaternion(animation[boneName]['quat'][f]) #- \
# restPose[boneName]['quat']
if boneName == 'ROOT':
print(restPose[boneName]['quat'])
print(animation[boneName]['quat'][f])
print(newQ)
print('\n')
print(restPose[boneName]['pos'])
print(newLoc)
print('\n')
'''
#From io_anim_bvh.py
frameLoc = Vector(animation[boneName]['pos'][f])
transVec = frameLoc - restPose[boneName]['pos']
#.........这里部分代码省略.........
示例13: writeChunkAnimationSkeletal
# 需要导入模块: from mathutils import Matrix [as 别名]
# 或者: from mathutils.Matrix import invert [as 别名]
def writeChunkAnimationSkeletal(self, obj):
# Get armature
armature = self.getArmature(obj)
if not armature:
return
armatureAction = armature.animation_data.action
# Get armature transformation matrix
baseMatrix, armatureMatrix = self.getArmatureMatrix(obj)
# Write animation basics
self.file.writeString(armature.name) # Animation name
# Get animation infos
scene = self.context.scene
firstFrame = int(armatureAction.frame_range[0])
lastFrame = int(armatureAction.frame_range[1])
#frameCount = (lastFrame - firstFrame) + 1
prevFrame = scene.frame_current
scene.frame_set(firstFrame)
# Create joint list
animJoints = []
jointCount = 0
for bone in armature.data.bones:
# Create new animation joint
animJoint = AnimationJoint()
# Setup bone basics
animJoint.name = bone.name
animJoint.index = jointCount
animJoint.parent = -1
# Setup bone transformation
boneMatrix = Matrix(bone.matrix_local)
if bone.parent:
parentMatrix = Matrix(bone.parent.matrix_local).to_4x4()
parentMatrix.invert()
boneMatrix = parentMatrix * boneMatrix
else:
boneMatrix = armatureMatrix * boneMatrix
animJoint.transformation.extract(boneMatrix)
# Setup parnet bone index
if bone.parent:
otherBoneIndex = 0
for otherBone in armature.data.bones:
if bone.parent == otherBone:
animJoint.parent = otherBoneIndex
break
otherBoneIndex += 1
# Setup vertex weights
for vert in self.surfaceVertices:
for group in vert.vertex.groups:
if obj.vertex_groups[group.group].name == bone.name and group.weight > EPSILON:
animJoint.vertices.append(JointVertexWeight(vert.surface, vert.index, group.weight))
# Add joint to the list
animJoints.append(animJoint)
jointCount += 1
# Setup all keyframes
frame = firstFrame
while frame <= lastFrame:
# Setup current scene frame
scene.frame_set(frame)
armatureMatrix = baseMatrix * armature.matrix_world
# Setup current keyframe for each bone
i = 0
for bone in armature.data.bones:
# Get animation joint
animJoint = animJoints[i]
i += 1
# Setup bone transformation
boneMatrix = armature.pose.bones[bone.name].matrix
if bone.parent:
parentMatrix = Matrix(armature.pose.bones[bone.parent.name].matrix).to_4x4()
parentMatrix.invert()
boneMatrix = parentMatrix * boneMatrix
else:
boneMatrix = armatureMatrix * boneMatrix
# Get keyframe transformation
transformation = KeyframeTransformation()
transformation.extract(boneMatrix)
#.........这里部分代码省略.........