Python mathutils.Matrix.Identity() Examples

The following are 24 code examples of mathutils.Matrix.Identity(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mathutils.Matrix , or try the search function .
Example #1
Source File: internal.py    From curve_cad with GNU General Public License v3.0 6 votes vote down vote up
def circleOfTriangle(a, b, c):
    # https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_from_cross-_and_dot-products
    dirBA = a-b
    dirCB = b-c
    dirAC = c-a
    normal = dirBA.cross(dirCB)
    lengthBA = dirBA.length
    lengthCB = dirCB.length
    lengthAC = dirAC.length
    lengthN = normal.length
    if lengthN == 0:
        return None
    factor = -1/(2*lengthN*lengthN)
    alpha = (dirBA@dirAC)*(lengthCB*lengthCB*factor)
    beta = (dirBA@dirCB)*(lengthAC*lengthAC*factor)
    gamma = (dirAC@dirCB)*(lengthBA*lengthBA*factor)
    center = a*alpha+b*beta+c*gamma
    radius = (lengthBA*lengthCB*lengthAC)/(2*lengthN)
    tangent = (a-center).normalized()
    orientation = Matrix.Identity(3)
    orientation.col[2] = normal/lengthN
    orientation.col[1] = (a-center).normalized()
    orientation.col[0] = orientation.col[1].xyz.cross(orientation.col[2].xyz)
    return Circle(orientation=orientation, center=center, radius=radius) 
Example #2
Source File: internal.py    From curve_cad with GNU General Public License v3.0 6 votes vote down vote up
def bezierArcAt(tangent, normal, center, radius, angle, tollerance=0.99999):
    transform = Matrix.Identity(4)
    transform.col[0].xyz = tangent.cross(normal)*radius
    transform.col[1].xyz = tangent*radius
    transform.col[2].xyz = normal*radius
    transform.col[3].xyz = center
    segments = []
    segment_count = math.ceil(abs(angle)/(math.pi*0.5)*tollerance)
    angle /= segment_count
    x0 = math.cos(angle*0.5)
    y0 = math.sin(angle*0.5)
    x1 = (4.0-x0)/3.0
    y1 = (1.0-x0)*(3.0-x0)/(3.0*y0)
    points = [
        Vector((x0, -y0, 0)),
        Vector((x1, -y1, 0)),
        Vector((x1, y1, 0)),
        Vector((x0, y0, 0))
    ]
    for i in range(0, segment_count):
        rotation = Matrix.Rotation((i+0.5)*angle, 4, 'Z')
        segments.append(list(map(lambda v: transform@(rotation@v), points)))
    return segments 
Example #3
Source File: exporter.py    From leadwerks-blender-exporter with GNU General Public License v3.0 6 votes vote down vote up
def format_mesh(self, exportable, matrix):

        m = Mesh(exportable['object'])
        surfaces = m.surfaces
        num_kids = len(surfaces)+len(exportable['children'])+1

        bones = ''
        arm = m.armature
        if arm and CONFIG.export_animation:
            bones = utils.join_map(self.format_bone, arm.bones)
            if bones:
                num_kids += len(arm.bones)
            matrix = Matrix.Identity(4)

        context = {
            'code': constants.MDL_MESH,
            'num_kids': num_kids,
            'matrix': utils.format_floats_box(matrix),
            'props': self.format_props([['name', m.name]]),
            'surfaces': utils.join_map(self.format_surface, surfaces),
            'bones': bones,
            'childs': utils.join_map(self.format_block, exportable['children'])
        }

        return templates.render('MESH', context) 
Example #4
Source File: pia.py    From BlenderTools with GNU General Public License v2.0 6 votes vote down vote up
def _get_delta_matrix(bone_rest_matrix_scs, parent_bone_rest_matrix_scs, bone_animation_matrix_scs, import_scale):
    """."""
    scale_matrix = Matrix.Scale(import_scale, 4)

    # NOTE: apply scaling bone rest matrix, because it's subtracted by bone rest matrix inverse
    loc, rot, sca = bone_rest_matrix_scs.decompose()
    scale = Matrix.Identity(4)
    scale[0] = (sca[0], 0, 0, 0)
    scale[1] = (0, sca[1], 0, 0)
    scale[2] = (0, 0, sca[2], 0)

    return (scale_matrix @
            scale @
            bone_rest_matrix_scs.inverted() @
            parent_bone_rest_matrix_scs @
            bone_animation_matrix_scs) 
Example #5
Source File: exporter.py    From cats-blender-plugin with MIT License 6 votes vote down vote up
def __exportBones(self, armObj, converters=None, matrix_basis_map=None):
        if armObj is None:
            return None

        pose_bones = armObj.pose.bones
        if converters is None:
            converters = self.__getConverters(pose_bones)

        if matrix_basis_map is None:
            matrix_basis_map = {}

        matrix_identity = Matrix.Identity(4)
        vpd_bones = []
        for b in pose_bones:
            if b.is_mmd_shadow_bone:
                continue
            if b.matrix_basis == matrix_basis_map.get(b, matrix_identity):
                continue
            bone_name = b.mmd_bone.name_j or b.name
            converter = converters[b]
            location = converter.convert_location(b.location)
            w, x, y, z = b.matrix_basis.to_quaternion()
            w, x, y, z = converter.convert_rotation([x, y, z, w])
            vpd_bones.append(vpd.VpdBone(bone_name, location, [x, y, z, w]))
        return vpd_bones 
Example #6
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 6 votes vote down vote up
def transform(v: typing.Union[Vector, Quaternion], data_path: str, transform: Matrix = Matrix.Identity(4)) -> typing \
        .Union[Vector, Quaternion]:
    """Manage transformations."""
    target = get_target_property_name(data_path)
    transform_func = {
        "delta_location": transform_location,
        "delta_rotation_euler": transform_rotation,
        "location": transform_location,
        "rotation_axis_angle": transform_rotation,
        "rotation_euler": transform_rotation,
        "rotation_quaternion": transform_rotation,
        "scale": transform_scale,
        "value": transform_value
    }.get(target)

    if transform_func is None:
        raise RuntimeError("Cannot transform values at {}".format(data_path))

    return transform_func(v, transform) 
Example #7
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def transform_rotation(rotation: Quaternion, transform: Matrix = Matrix.Identity(4)) -> Quaternion:
    """Transform rotation."""
    rotation.normalize()
    m = rotation.to_matrix().to_4x4()
    m = multiply(transform, m)
    return m.to_quaternion() 
Example #8
Source File: transform.py    From object_alignment with GNU General Public License v3.0 5 votes vote down vote up
def apply_transform(obj:Object, location:bool=True, rotation:bool=True, scale:bool=True):
    """ apply object transformation to mesh """
    loc, rot, scale = obj.matrix_world.decompose()
    obj.matrix_world = Matrix.Identity(4)
    m = obj.data
    s_mat_x = Matrix.Scale(scale.x, 4, Vector((1, 0, 0)))
    s_mat_y = Matrix.Scale(scale.y, 4, Vector((0, 1, 0)))
    s_mat_z = Matrix.Scale(scale.z, 4, Vector((0, 0, 1)))
    if scale:    m.transform(mathutils_mult(s_mat_x, s_mat_y, s_mat_z))
    else:        obj.scale = scale
    if rotation: m.transform(rot.to_matrix().to_4x4())
    else:        obj.rotation_euler = rot.to_euler()
    if location: m.transform(Matrix.Translation(loc))
    else:        obj.location = loc 
Example #9
Source File: icp_align_feedback.py    From object_alignment with GNU General Public License v3.0 5 votes vote down vote up
def iterate(self,context):

        (A, B, self.d_stats) = make_pairs(self.align_obj, self.base_obj, self.base_bvh, self.vlist, self.thresh, self.sample_factor, calc_stats = self.use_target)


        if self.align_meth == '0': #rigid transform
            M = affine_matrix_from_points(A, B, shear=False, scale=False, usesvd=True)
        elif self.align_meth == '1': # rot, loc, scale
            M = affine_matrix_from_points(A, B, shear=False, scale=True, usesvd=True)

        new_mat = Matrix.Identity(4)
        for y in range(0,4):
            for z in range(0,4):
                new_mat[y][z] = M[y][z]

        self.align_obj.matrix_world = self.align_obj.matrix_world * new_mat
        trans = new_mat.to_translation()
        quat = new_mat.to_quaternion()

        self.align_obj.update_tag()
        if self.d_stats:
            i = int(fmod(self.total_iters,5))
            self.conv_t_list[i] = trans.length
            self.conv_r_list[i] = abs(quat.angle)

            if all(d < self.target_d for d in self.conv_t_list):
                self.converged = True

                print('Converged in %s iterations' % str(self.total_iters+1))
                print('Final Translation: %f ' % self.conv_t_list[i])
                print('Final Avg Dist: %f' % self.d_stats[0])
                print('Final St Dev %f' % self.d_stats[1])
                print('Avg last 5 rotation angle: %f' % np.mean(self.conv_r_list)) 
Example #10
Source File: tools_painclones.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generateRotationMatrix(direction, guide, trackAxis = "Z", guideAxis = "X"):
    '''
    trackAxis in ("X", "Y", "Z", "-X", "-Y", "-Z")
    guideAxis in ("X", "Y", "Z")
    '''

    matrix = Matrix.Identity(4)

    if guideAxis[-1:] == trackAxis[-1:]:
        return matrix

    if direction == zero:
        return matrix

    z = direction.normalized()
    y = z.cross(guide.normalized())
    if y == zero:
        if guideAxis == "X":
            if z.cross(xAxis) != zero: y = z.cross(xAxis)
            else: y = zAxis
        elif guideAxis == "Y":
            if z.cross(yAxis) != zero: y = z.cross(yAxis)
            else: y = zAxis
        elif guideAxis == "Z":
            if z.cross(zAxis) != zero: y = z.cross(zAxis)
            else: y = yAxis

    x = y.cross(z)

    mx, my, mz = changeAxesDict[(trackAxis, guideAxis)](x, y, z)
    matrix.col[0][:3] = mx
    matrix.col[1][:3] = my
    matrix.col[2][:3] = mz
    return matrix 
Example #11
Source File: vnode.py    From gltf-blender-importer with MIT License 5 votes vote down vote up
def __init__(self):
        # The ID of the glTF node this vnode was created from, or None if there
        # wasn't one
        self.node_id = None
        # List of child vnodes
        self.children = []
        # Parent vnode, or None for the root
        self.parent = None
        # (Vector, Quaternion, Vector) triple of the local-to-parent TRS transform
        self.trs = (Vector((0, 0, 0)), Quaternion((1, 0, 0, 0)), Vector((1, 1, 1)))

        # What type of Blender object will be created for this vnode: one of
        # OBJECT, ARMATURE, BONE, or ROOT (for the special vnode that we use the
        # turn the forest into a tree to make things easier to process).
        self.type = 'OBJECT'

        # Dicts of instance data
        self.mesh = None
        self.camera = None
        self.light = None
        # If this node had an instance in glTF but we moved it to another node,
        # we record where we put it here
        self.mesh_moved_to = None
        self.camera_moved_to = None
        self.light_moved_to = None

        # These will be filled out after realization with the Blender data
        # created for this vnode.
        self.blender_object = None
        self.blender_armature = None
        self.blender_editbone = None
        self.blender_name = None

        # The editbone's (Translation, Rotation)
        self.editbone_tr = None
        self.posebone_s = None
        self.editbone_local_to_armature = Matrix.Identity(4)
        self.bone_length = 0
        # Correction to apply to the original TRS to get the editbone TR
        self.correction_rotation = Quaternion((1, 0, 0, 0))
        self.correction_homscale = 1 
Example #12
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def transform_value(value: Vector, _: Matrix = Matrix.Identity(4)) -> Vector:
    """Transform value."""
    return value 
Example #13
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def transform_location(location: Vector, transform: Matrix = Matrix.Identity(4)) -> Vector:
    """Transform location."""
    m = Matrix.Translation(location)
    m = multiply(transform, m)
    return m.to_translation() 
Example #14
Source File: gltf2_blender_vnode.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def calc_bone_matrices(gltf):
    """
    Calculate the transformations from bone space to arma space in the bind
    pose and in the edit bone pose.
    """
    def visit(vnode_id):  # Depth-first walk
        vnode = gltf.vnodes[vnode_id]
        if vnode.type == VNode.Bone:
            if gltf.vnodes[vnode.parent].type == VNode.Bone:
                parent_bind_mat = gltf.vnodes[vnode.parent].bind_arma_mat
                parent_editbone_mat = gltf.vnodes[vnode.parent].editbone_arma_mat
            else:
                parent_bind_mat = Matrix.Identity(4)
                parent_editbone_mat = Matrix.Identity(4)

            t, r = vnode.bind_trans, vnode.bind_rot
            local_to_parent = Matrix.Translation(t) @ Quaternion(r).to_matrix().to_4x4()
            vnode.bind_arma_mat = parent_bind_mat @ local_to_parent

            t, r = vnode.editbone_trans, vnode.editbone_rot
            local_to_parent = Matrix.Translation(t) @ Quaternion(r).to_matrix().to_4x4()
            vnode.editbone_arma_mat = parent_editbone_mat @ local_to_parent

        for child in vnode.children:
            visit(child)

    visit('root') 
Example #15
Source File: SuncgLoader.py    From BlenderProc with GNU General Public License v3.0 5 votes vote down vote up
def _load_box(self, node, material_adjustments, transform, parent):
        """ Creates a cube inside blender which follows the specifications of the given node.

        :param node: The node dict which contains information from house.json..
        :param material_adjustments: Adjustments to the materials which were specified inside house.json.
        :param transform: The transformation that should be applied to the loaded objects.
        :param parent: The parent object to which the ground should be linked
        """
        bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
        box = bpy.context.object
        box.name = "Box#" + node["id"]
        box.matrix_world = Matrix.Identity(4)
        # Scale the cube to the required dimensions
        box.matrix_world @= Matrix.Scale(node["dimensions"][0] / 2, 4, (1.0, 0.0, 0.0)) @ Matrix.Scale(node["dimensions"][1] / 2, 4, (0.0, 1.0, 0.0)) @ Matrix.Scale(node["dimensions"][2] / 2, 4, (0.0, 0.0, 1.0))

        # Create UV mapping (beforehand we apply the scaling from the previous step, such that the resulting uv mapping has the correct aspect)
        bpy.ops.object.transform_apply(scale=True)
        bpy.ops.object.editmode_toggle()
        bpy.ops.uv.cube_project()
        bpy.ops.object.editmode_toggle()

        # Create an empty material which is filled in the next step
        mat = bpy.data.materials.new(name="material_0")
        mat.use_nodes = True
        box.data.materials.append(mat)

        self._transform_and_colorize_object(box, material_adjustments, transform, parent)
        # set class to void
        box["category_id"] = LabelIdMapping.label_id_map["void"]
        # Rotate cube to match objects loaded from .obj, has to be done after transformations have been applied
        box.matrix_world = Matrix.Rotation(math.radians(90), 4, "X") @ box.matrix_world

        # Set the physics property of all imported boxes
        self._set_properties(bpy.context.selected_objects) 
Example #16
Source File: space_view3d_enhanced_3d_cursor.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def MatrixCompose(*args):
    size = len(args)
    m = Matrix.Identity(size)
    axes = m.col # m.row

    if size == 2:
        for i in (0, 1):
            c = args[i]
            if isinstance(c, Vector):
                axes[i] = c.to_2d()
            elif hasattr(c, "__iter__"):
                axes[i] = Vector(c).to_2d()
            else:
                axes[i][i] = c
    else:
        for i in (0, 1, 2):
            c = args[i]
            if isinstance(c, Vector):
                axes[i][:3] = c.to_3d()
            elif hasattr(c, "__iter__"):
                axes[i][:3] = Vector(c).to_3d()
            else:
                axes[i][i] = c

        if size == 4:
            c = args[3]
            if isinstance(c, Vector):
                m.translation = c.to_3d()
            elif hasattr(c, "__iter__"):
                m.translation = Vector(c).to_3d()

    return m 
Example #17
Source File: clip.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, context):
        from bpy_extras.io_utils import unpack_list

        sc = context.space_data
        clip = sc.clip
        tracking_object = clip.tracking.objects.active

        new_verts = []

        scene = context.scene
        camera = scene.camera
        matrix = Matrix.Identity(4)
        if camera:
            reconstruction = tracking_object.reconstruction
            framenr = scene.frame_current - clip.frame_start + 1
            reconstructed_matrix = reconstruction.cameras.matrix_from_frame(framenr)
            matrix = camera.matrix_world * reconstructed_matrix.inverted()

        mesh = bpy.data.meshes.new(name="Tracks")
        for track in tracking_object.tracks:
            if track.has_bundle:
                new_verts.append(track.bundle)

        if new_verts:
            mesh.vertices.add(len(new_verts))
            mesh.vertices.foreach_set("co", unpack_list(new_verts))

        ob = bpy.data.objects.new(name="Tracks", object_data=mesh)

        ob.matrix_world = matrix

        context.scene.objects.link(ob)

        return {'FINISHED'} 
Example #18
Source File: armature.py    From leadwerks-blender-exporter with GNU General Public License v3.0 5 votes vote down vote up
def __fake_keyframe(self):
        return Matrix.Identity(4) 
Example #19
Source File: hair.py    From BlendLuxCore with GNU General Public License v3.0 5 votes vote down vote up
def set_hair_props(scene_props, lux_obj, lux_shape, lux_mat, visible_to_camera,
                   is_for_duplication, instance_matrix_world, use_instancing):
    prefix = "scene.objects." + lux_obj + "."

    scene_props.Set(pyluxcore.Property(prefix + "material", lux_mat))
    scene_props.Set(pyluxcore.Property(prefix + "shape", lux_shape))
    scene_props.Set(pyluxcore.Property(prefix + "camerainvisible", not visible_to_camera))

    if is_for_duplication:
        scene_props.Set(pyluxcore.Property(prefix + "transformation", utils.matrix_to_list(instance_matrix_world)))
    elif use_instancing:
        # We don't actually need to transform anything, just set an identity matrix so the mesh is instanced
        identity_matrix = utils.matrix_to_list(Matrix.Identity(4))
        scene_props.Set(pyluxcore.Property(prefix + "transformation", identity_matrix)) 
Example #20
Source File: gltf2_blender_gather_nodes.py    From glTF-Blender-IO with Apache License 2.0 4 votes vote down vote up
def __gather_trans_rot_scale(blender_object, export_settings):
    if blender_object.matrix_parent_inverse == Matrix.Identity(4):
        trans = blender_object.location

        if blender_object.rotation_mode in ['QUATERNION', 'AXIS_ANGLE']:
            rot = blender_object.rotation_quaternion
        else:
            rot = blender_object.rotation_euler.to_quaternion()

        sca = blender_object.scale
    else:
        # matrix_local = matrix_parent_inverse*location*rotation*scale
        # Decomposing matrix_local gives less accuracy, but is needed if matrix_parent_inverse is not the identity.


        if blender_object.matrix_local[3][3] != 0.0:
            trans, rot, sca = gltf2_blender_extract.decompose_transition(blender_object.matrix_local, export_settings)
        else:
            # Some really weird cases, scale is null (if parent is null when evaluation is done)
            print_console('WARNING', 'Some nodes are 0 scaled during evaluation. Result can be wrong')
            trans = blender_object.location
            if blender_object.rotation_mode in ['QUATERNION', 'AXIS_ANGLE']:
                rot = blender_object.rotation_quaternion
            else:
                rot = blender_object.rotation_euler.to_quaternion()
            sca = blender_object.scale

    # make sure the rotation is normalized
    rot.normalize()

    trans = gltf2_blender_extract.convert_swizzle_location(trans, None, None, export_settings)
    rot = gltf2_blender_extract.convert_swizzle_rotation(rot, export_settings)
    sca = gltf2_blender_extract.convert_swizzle_scale(sca, export_settings)

    if blender_object.instance_type == 'COLLECTION' and blender_object.instance_collection:
        trans -= gltf2_blender_extract.convert_swizzle_location(
            blender_object.instance_collection.instance_offset, None, None, export_settings)
    translation, rotation, scale = (None, None, None)
    trans[0], trans[1], trans[2] = gltf2_blender_math.round_if_near(trans[0], 0.0), gltf2_blender_math.round_if_near(trans[1], 0.0), \
                                   gltf2_blender_math.round_if_near(trans[2], 0.0)
    rot[0], rot[1], rot[2], rot[3] = gltf2_blender_math.round_if_near(rot[0], 1.0), gltf2_blender_math.round_if_near(rot[1], 0.0), \
                                     gltf2_blender_math.round_if_near(rot[2], 0.0), gltf2_blender_math.round_if_near(rot[3], 0.0)
    sca[0], sca[1], sca[2] = gltf2_blender_math.round_if_near(sca[0], 1.0), gltf2_blender_math.round_if_near(sca[1], 1.0), \
                             gltf2_blender_math.round_if_near(sca[2], 1.0)
    if trans[0] != 0.0 or trans[1] != 0.0 or trans[2] != 0.0:
        translation = [trans[0], trans[1], trans[2]]
    if rot[0] != 1.0 or rot[1] != 0.0 or rot[2] != 0.0 or rot[3] != 0.0:
        rotation = [rot[1], rot[2], rot[3], rot[0]]
    if sca[0] != 1.0 or sca[1] != 1.0 or sca[2] != 1.0:
        scale = [sca[0], sca[1], sca[2]]
    return translation, rotation, scale 
Example #21
Source File: opengl_utils.py    From Blender-Addon-Photogrammetry-Importer with MIT License 4 votes vote down vote up
def render_opengl_image(image_name, cam, point_size):
    draw_manager = DrawManager.get_singleton()
    coords, colors = draw_manager.get_coords_and_colors()

    scene = bpy.context.scene
    render = bpy.context.scene.render

    width = render.resolution_x
    height = render.resolution_y
    # TODO Provide an option to render from the 3D view perspective
    # width = bpy.context.region.width
    # height = bpy.context.region.height

    offscreen = gpu.types.GPUOffScreen(width, height)
    with offscreen.bind():

        bgl.glPointSize(point_size)
        #bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
        #bgl.glClear(bgl.GL_DEPTH_BUFFER_BIT)

        view_matrix = cam.matrix_world.inverted()
        projection_matrix = cam.calc_matrix_camera(
            bpy.context.evaluated_depsgraph_get(), 
            x=width,
            y=height)
        perspective_matrix = projection_matrix @ view_matrix

        gpu.matrix.load_matrix(perspective_matrix)
        gpu.matrix.load_projection_matrix(Matrix.Identity(4))
        
        shader = gpu.shader.from_builtin('3D_FLAT_COLOR')
        shader.bind()
        batch = batch_for_shader(shader, "POINTS", {"pos": coords, "color": colors})
        batch.draw(shader)
        
        buffer = bgl.Buffer(bgl.GL_BYTE, width * height * 4)
        bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, buffer)

    offscreen.free()

    image = create_image_lazy(image_name, width, height)
    copy_buffer_to_pixel(buffer, image) 
Example #22
Source File: align_pick_points.py    From object_alignment with GNU General Public License v3.0 4 votes vote down vote up
def align_obj(self,context):

        if len(self.align_points) != len(self.base_points):
            if len(self.align_points) < len(self.base_points):

                self.base_points = self.base_points[0:len(self.align_points)]
            else:
                self.align_points = self.align_points[0:len(self.base_points)]

        A = np.zeros(shape = [3,len(self.base_points)])
        B = np.zeros(shape = [3,len(self.base_points)])

        for i in range(0,len(self.base_points)):
            V1 = self.align_points[i]
            V2 = self.base_points[i]

            A[0][i], A[1][i], A[2][i] = V1[0], V1[1], V1[2]
            B[0][i], B[1][i], B[2][i] = V2[0], V2[1], V2[2]


        #test new method
        settings = get_addon_preferences()
        align_meth = settings.align_meth

        if align_meth == '0': #rigid transform
            M = affine_matrix_from_points(A, B, shear=False, scale=False, usesvd=True)
        elif align_meth == '1': # rot, loc, scale
            M = affine_matrix_from_points(A, B, shear=False, scale=True, usesvd=True)
        #else: #affine
            #M = affine_matrix_from_points(A, B, shear=True, scale=True, usesvd=True)


        new_mat = Matrix.Identity(4)
        for n in range(0,4):
            for m in range(0,4):
                new_mat[n][m] = M[n][m]

        #because we calced transform in local space
        #it's this easy to update the obj...
        self.obj_align.matrix_world = self.obj_align.matrix_world * new_mat

        self.obj_align.update_tag()
        context.scene.update() 
Example #23
Source File: gltf2_blender_vnode.py    From glTF-Blender-IO with Apache License 2.0 4 votes vote down vote up
def pick_bind_pose(gltf):
    """
    Pick the bind pose for all bones. Skinned meshes will be retargeted onto
    this bind pose during mesh creation.
    """
    if gltf.import_settings['guess_original_bind_pose']:
        # Record inverse bind matrices. We're going to milk them for information
        # about the original bind pose.
        inv_binds = {'root': Matrix.Identity(4)}
        for skin in gltf.data.skins or []:
            if skin.inverse_bind_matrices is None:
                continue

            # Assume inverse bind matrices are calculated relative to the skeleton
            skel = skin.skeleton
            if skel is not None:
                if skel in skin.joints:
                    skel = gltf.vnodes[skel].parent
                if skel not in inv_binds:
                    inv_binds[skel] = Matrix.Identity(4)

            skin_inv_binds = BinaryData.get_data_from_accessor(gltf, skin.inverse_bind_matrices)
            skin_inv_binds = [gltf.matrix_gltf_to_blender(m) for m in skin_inv_binds]
            for i, joint in enumerate(skin.joints):
                inv_binds[joint] = skin_inv_binds[i]

    for vnode_id in gltf.vnodes:
        vnode = gltf.vnodes[vnode_id]
        if vnode.type == VNode.Bone:
            # Initialize bind pose to default pose (from gltf.data.nodes)
            vnode.bind_trans = Vector(vnode.base_trs[0])
            vnode.bind_rot = Quaternion(vnode.base_trs[1])

            if gltf.import_settings['guess_original_bind_pose']:
                # Try to guess bind pose from inverse bind matrices
                if vnode_id in inv_binds and vnode.parent in inv_binds:
                    # (bind matrix) = (parent bind matrix) (bind local). Solve for bind local...
                    bind_local = inv_binds[vnode.parent] @ inv_binds[vnode_id].inverted_safe()
                    t, r, _s = bind_local.decompose()
                    vnode.bind_trans = t
                    vnode.bind_rot = r

            # Initialize editbones to match bind pose
            vnode.editbone_trans = Vector(vnode.bind_trans)
            vnode.editbone_rot = Quaternion(vnode.bind_rot) 
Example #24
Source File: __init__.py    From retopology-polystrips with GNU General Public License v2.0 4 votes vote down vote up
def create_mesh(self, context):
        verts,quads = self.polystrips.create_mesh()

        if self.to_bme and self.to_obj:  #EDIT MDOE on Existing Mesh
            bm = self.to_bme
            mx = self.to_obj.matrix_world
            imx = mx.inverted()

            mx2 = self.obj.matrix_world
            imx2 = mx2.inverted()

        else:
            bm = bmesh.new()
            mx2 = Matrix.Identity(4)
            imx = Matrix.Identity(4)

            nm_polystrips = self.obj.name + "_polystrips"

            dest_me  = bpy.data.meshes.new(nm_polystrips)
            dest_obj = bpy.data.objects.new(nm_polystrips, dest_me)

            dest_obj.matrix_world = self.obj.matrix_world
            dest_obj.update_tag()
            dest_obj.show_all_edges = True
            dest_obj.show_wire      = True
            dest_obj.show_x_ray     = True

            context.scene.objects.link(dest_obj)
            dest_obj.select = True
            context.scene.objects.active = dest_obj

        bmverts = [bm.verts.new(imx * mx2 * v) for v in verts]
        bm.verts.index_update()
        for q in quads: 
            bm.faces.new([bmverts[i] for i in q])

        bm.faces.index_update()

        if self.to_bme and self.to_obj:
            bmesh.update_edit_mesh(self.to_obj.data, tessface=False, destructive=True)
            bm.free()
        else: 
            bm.to_mesh(dest_me)
            bm.free()

    ###########################
    # hover functions