Python mathutils.Quaternion() Examples

The following are 30 code examples of mathutils.Quaternion(). 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 , or try the search function .
Example #1
Source File: pdt_view.py    From Precision-Drawing-Tools with GNU General Public License v3.0 6 votes vote down vote up
def execute(self, context):
        """Set Isometric View.

        Note:
            Set view orientation to Orthographic Isometric

        Args:
            context: Blender bpy.context instance.

        Returns:
            Status Set.
        """

        # Rotate view 45 degrees about Z then 32.2644 about X
        context.region_data.view_rotation = Quaternion((0.8205, 0.4247, -0.1759, -0.3399))
        context.region_data.view_perspective = "ORTHO"
        return {"FINISHED"} 
Example #2
Source File: genFunctions.py    From W_Mesh_28x with GNU General Public License v3.0 6 votes vote down vote up
def circleVerts(radius: float, seg: int, IDs_Offset: int):
    verts = []
    vertIDs = []

    if radius <= 0:
        return [Vector((0, 0, 0))], [IDs_Offset]

    if seg < 3:
        seg = 3

    stepAngle = (2 * pi) / seg

    for i in range(seg):
        vertIDs.append(i + IDs_Offset)
        quat = Quaternion((0, 0, 1), i * stepAngle)
        verts.append(quat @ Vector((radius, 0.0, 0.0)))

    return verts, vertIDs 
Example #3
Source File: railing.py    From building_tools with MIT License 6 votes vote down vote up
def create_railing_top(bm, top_edge, prop):
    ret = bmesh.ops.duplicate(bm, geom=[top_edge])
    top_dup_edge = filter_geom(ret["geom"], BMEdge)[0]
    vec = edge_vector(top_dup_edge)

    up = vec.copy()
    horizon = vec.cross(Vector((0., 0., 1.)))
    up.rotate(Quaternion(horizon, math.pi/2).to_euler())

    sloped = edge_is_sloped(top_dup_edge)
    cylinder = edge_to_cylinder(bm, top_dup_edge, prop.corner_post_width/2, up)
    if sloped:
        rotate_sloped_rail_bounds(bm, cylinder, vec)

    bmesh.ops.translate(bm, verts=top_edge.verts, vec=Vector((0., 0., -1.))*prop.corner_post_width/2)
    return list({f for v in cylinder for f in v.link_faces}) 
Example #4
Source File: _common.py    From Blender-AnimeHairSupporter with Apache License 2.0 6 votes vote down vote up
def relocation_taper_and_bevel(main_ob, sub_ob, is_taper):
	# 位置変更
	if len(main_ob.data.splines):
		if len(main_ob.data.splines[0].points):
			end_co = main_ob.matrix_world * mathutils.Vector(main_ob.data.splines[0].points[-1].co[:3])
			sub_ob.location = end_co.copy()
	
	# 回転変更
	if len(main_ob.data.splines):
		spline = main_ob.data.splines[0]
		if 2 <= len(spline.points):
			# 最後の辺をトラック
			sub_ob.rotation_mode = 'QUATERNION'
			last_direction = main_ob.matrix_world * mathutils.Vector(spline.points[-2].co[:3]) - main_ob.matrix_world * mathutils.Vector(spline.points[-1].co[:3])
			up_direction = mathutils.Vector((0, 0, 1))
			sub_ob.rotation_quaternion = up_direction.rotation_difference(last_direction)
			# Z回転
			diff_co = main_ob.matrix_world * mathutils.Vector(spline.points[-1].co[:3]) - main_ob.matrix_world * mathutils.Vector(spline.points[0].co[:3])
			rotation_z = math.atan2(diff_co.y, diff_co.x) - spline.points[-1].tilt
			if is_taper: sub_ob.rotation_quaternion *= mathutils.Quaternion((0, 0, 1), rotation_z)
			else       : sub_ob.rotation_quaternion *= mathutils.Quaternion((0, 0, 1), rotation_z - math.radians(90)) 
Example #5
Source File: gen_func.py    From Wonder_Mesh with GNU General Public License v3.0 6 votes vote down vote up
def circleVerts(radius: float, seg: int, IDs_Offset: int):
    verts = []
    vertIDs = []

    if radius <= 0:
        return [Vector((0, 0, 0))], [IDs_Offset]

    if seg < 3:
        seg = 3

    stepAngle = (2 * pi) / seg

    for i in range(seg):
        vertIDs.append(i + IDs_Offset)
        quat = Quaternion((0, 0, 1), i * stepAngle)
        verts.append(quat * Vector((radius, 0.0, 0.0)))

    return verts, vertIDs 
Example #6
Source File: gltf2_blender_vnode.py    From glTF-Blender-IO with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self.name = None
        self.default_name = 'Node'  # fallback when no name
        self.children = []
        self.parent = None
        self.type = VNode.Object
        self.is_arma = False
        self.base_trs = (
            Vector((0, 0, 0)),
            Quaternion((1, 0, 0, 0)),
            Vector((1, 1, 1)),
        )
        # Additional rotations before/after the base TRS.
        # Allows per-vnode axis adjustment. See local_rotation.
        self.rotation_after = Quaternion((1, 0, 0, 0))
        self.rotation_before = Quaternion((1, 0, 0, 0))

        # Indices of the glTF node where the mesh, etc. came from.
        # (They can get moved around.)
        self.mesh_node_idx = None
        self.camera_node_idx = None
        self.light_node_idx = None 
Example #7
Source File: __init__.py    From retopology-polystrips with GNU General Public License v2.0 6 votes vote down vote up
def rotate_tool_gvert_neighbors(self, command, eventd):
        if command == 'init':
            self.footer = 'Rotating GVerts'
            self.tool_data = [(gv,Vector(gv.position)) for gv in self.sel_gvert.get_inner_gverts()]
        elif command == 'commit':
            pass
        elif command == 'undo':
            for gv,p in self.tool_data:
                gv.position = p
                gv.update()
        else:
            ang = command
            q = Quaternion(self.sel_gvert.snap_norm, ang)
            p = self.sel_gvert.position
            for gv,up in self.tool_data:
                gv.position = p+q*(up-p)
                gv.update() 
Example #8
Source File: morph.py    From cats-blender-plugin with MIT License 6 votes vote down vote up
def execute(self, context):
        obj = context.active_object
        root = mmd_model.Model.findRoot(obj)
        rig = mmd_model.Model(root)
        armature = rig.armature()
        mmd_root = root.mmd_root
        morph = mmd_root.bone_morphs[mmd_root.active_morph]
        morph.data.clear()
        morph.active_data = 0
        def_loc = Vector((0,0,0))
        def_rot = Quaternion((1,0,0,0))
        for p_bone in armature.pose.bones:
            if p_bone.location != def_loc or p_bone.rotation_quaternion != def_rot:
                item = morph.data.add()
                item.bone = p_bone.name
                item.location = p_bone.location
                item.rotation = p_bone.rotation_quaternion
                p_bone.bone.select = True
            else:
                p_bone.bone.select = False
        return { 'FINISHED' } 
Example #9
Source File: pdt_view.py    From Precision-Drawing-Tools with GNU General Public License v3.0 6 votes vote down vote up
def execute(self, context):
        """View Rotation by Absolute Values.

        Note:
            Rotations are converted to 3x3 Quaternion Rotation Matrix.
            This is an Absolute Rotation, not an Incremental Orbit.
            Uses pg.rotation_coords scene variable

        Args:
            context: Blender bpy.context instance.

        Returns:
            Status Set.
        """

        scene = context.scene
        pg = scene.pdt_pg
        roll_value = euler_to_quaternion(
            pg.rotation_coords.x * pi / 180,
            pg.rotation_coords.y * pi / 180,
            pg.rotation_coords.z * pi / 180,
        )
        context.region_data.view_rotation = roll_value
        return {"FINISHED"} 
Example #10
Source File: pdt_functions.py    From Precision-Drawing-Tools with GNU General Public License v3.0 6 votes vote down vote up
def euler_to_quaternion(roll, pitch, yaw):
    """Converts Euler Rotation to Quaternion Rotation.

    Args:
        roll: Roll in Euler rotation
        pitch: Pitch in Euler rotation
        yaw: Yaw in Euler rotation

    Returns:
        Quaternion Rotation.
    """

    # fmt: off
    quat_x = (np.sin(roll/2) * np.cos(pitch/2) * np.cos(yaw/2)
              - np.cos(roll/2) * np.sin(pitch/2) * np.sin(yaw/2))
    quat_y = (np.cos(roll/2) * np.sin(pitch/2) * np.cos(yaw/2)
              + np.sin(roll/2) * np.cos(pitch/2) * np.sin(yaw/2))
    quat_z = (np.cos(roll/2) * np.cos(pitch/2) * np.sin(yaw/2)
              - np.sin(roll/2) * np.sin(pitch/2) * np.cos(yaw/2))
    quat_w = (np.cos(roll/2) * np.cos(pitch/2) * np.cos(yaw/2)
              + np.sin(roll/2) * np.sin(pitch/2) * np.sin(yaw/2))
    # fmt: on
    return Quaternion((quat_w, quat_x, quat_y, quat_z)) 
Example #11
Source File: vnode.py    From gltf-blender-importer with MIT License 6 votes vote down vote up
def get_node_trs(op, node):
    """Gets the TRS proerties from a glTF node JSON object."""
    if 'matrix' in node:
        m = node['matrix']
        # column-major to row-major
        m = Matrix([m[0:4], m[4:8], m[8:12], m[12:16]])
        m.transpose()
        loc, rot, sca = m.decompose()
        # wxyz -> xyzw
        # convert_rotation will switch back
        rot = [rot[1], rot[2], rot[3], rot[0]]

    else:
        sca = node.get('scale', [1.0, 1.0, 1.0])
        rot = node.get('rotation', [0.0, 0.0, 0.0, 1.0])
        loc = node.get('translation', [0.0, 0.0, 0.0])

    # Switch glTF coordinates to Blender coordinates
    sca = op.convert_scale(sca)
    rot = op.convert_rotation(rot)
    loc = op.convert_translation(loc)

    return [Vector(loc), Quaternion(rot), Vector(sca)] 
Example #12
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 6 votes vote down vote up
def list_to_mathutils(values: typing.List[float], data_path: str) -> typing.Union[Vector, Quaternion, Euler]:
    """Transform a list to blender py object."""
    target = get_target_property_name(data_path)

    if target == 'delta_location':
        return Vector(values)  # TODO Should be Vector(values) - Vector(something)?
    elif target == 'delta_rotation_euler':
        return Euler(values).to_quaternion()  # TODO Should be multiply(Euler(values).to_quaternion(), something)?
    elif target == 'location':
        return Vector(values)
    elif target == 'rotation_axis_angle':
        angle = values[0]
        axis = values[1:]
        return Quaternion(axis, math.radians(angle))
    elif target == 'rotation_euler':
        return Euler(values).to_quaternion()
    elif target == 'rotation_quaternion':
        return Quaternion(values)
    elif target == 'scale':
        return Vector(values)
    elif target == 'value':
        return Vector(values)

    return values 
Example #13
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 6 votes vote down vote up
def swizzle_yup(v: typing.Union[Vector, Quaternion], data_path: str) -> typing.Union[Vector, Quaternion]:
    """Manage Yup."""
    target = get_target_property_name(data_path)
    swizzle_func = {
        "delta_location": swizzle_yup_location,
        "delta_rotation_euler": swizzle_yup_rotation,
        "location": swizzle_yup_location,
        "rotation_axis_angle": swizzle_yup_rotation,
        "rotation_euler": swizzle_yup_rotation,
        "rotation_quaternion": swizzle_yup_rotation,
        "scale": swizzle_yup_scale,
        "value": swizzle_yup_value
    }.get(target)

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

    return swizzle_func(v) 
Example #14
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 #15
Source File: ksparser.py    From io_kspblender with GNU General Public License v2.0 5 votes vote down vote up
def zup_eul(line):
    """changes from Unity Y-up Left-Handed Quaternion to Blender Z-up Right-Handed Euler"""
    zup = [float(i) for i in line.split(" ")[-1].split(",")]
    zup = mathutils.Quaternion([0-zup[3], zup[0], zup[2], zup[1]])
    return (mathutils.Quaternion.to_euler(zup).x, mathutils.Quaternion.to_euler(zup).y, mathutils.Quaternion.to_euler(zup).z) 
Example #16
Source File: importer.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def _convert_rotation(self, rotation_xyzw):
        rot = Quaternion()
        rot.x, rot.y, rot.z, rot.w = rotation_xyzw
        rot = Quaternion(matmul(self.__mat, rot.axis) * -1, rot.angle)
        return matmul(self.__mat_rot, rot.to_matrix()).to_quaternion() 
Example #17
Source File: importer.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def convert_rotation(self, rotation_xyzw):
        rot = Quaternion()
        rot.x, rot.y, rot.z, rot.w = rotation_xyzw
        return Quaternion(matmul(self.__mat, rot.axis) * -1, rot.angle).normalized() 
Example #18
Source File: gltf2_extract.py    From glTF-Blender-Exporter with Apache License 2.0 5 votes vote down vote up
def convert_swizzle_rotation(rot, export_settings):
    """
    Converts a quaternion rotation from Blender coordinate system to glTF coordinate system.
    'w' is still at first position.
    """
    if export_settings['gltf_yup']:
        return mathutils.Quaternion((rot[0], rot[1], rot[3], -rot[2]))
    else:
        return mathutils.Quaternion((rot[0], rot[1], rot[2], rot[3])) 
Example #19
Source File: exporter.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def __xyzw_from_rotation_mode(mode):
        if mode == 'QUATERNION':
            return lambda xyzw: xyzw

        if mode == 'AXIS_ANGLE':
            def __xyzw_from_axis_angle(xyzw):
                q = mathutils.Quaternion(xyzw[:3], xyzw[3])
                return [q.x, q.y, q.z, q.w]
            return __xyzw_from_axis_angle

        def __xyzw_from_euler(xyzw):
            q = mathutils.Euler(xyzw[:3], xyzw[3]).to_quaternion()
            return [q.x, q.y, q.z, q.w]
        return __xyzw_from_euler 
Example #20
Source File: gltf2_extract.py    From glTF-Blender-Exporter with Apache License 2.0 5 votes vote down vote up
def decompose_transition(matrix, context, export_settings):
    translation, rotation, scale = matrix.decompose()
    """
    Decompose a matrix depending if it is associated to a joint or node.
    """

    if context == 'NODE':
        translation = convert_swizzle_location(translation, export_settings)
        rotation = convert_swizzle_rotation(rotation, export_settings)
        scale = convert_swizzle_scale(scale, export_settings)
    
    # Put w at the end.    
    rotation = mathutils.Quaternion((rotation[1], rotation[2], rotation[3], rotation[0]))
    
    return translation, rotation, scale 
Example #21
Source File: genFunctions.py    From W_Mesh_28x with GNU General Public License v3.0 5 votes vote down vote up
def rotateVerts(
            verts: List[Vector],
            axis: Quaternion):

    for i, vel in enumerate(verts):
        verts[i] = axis @ vel 
Example #22
Source File: util.py    From blender2ogre with GNU Lesser General Public License v2.1 5 votes vote down vote up
def swap(vec):
    if config.get('SWAP_AXIS') == 'xyz': return vec
    elif config.get('SWAP_AXIS') == 'xzy':
        if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, vec.y] )
        elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, vec.y] )
    elif config.get('SWAP_AXIS') == '-xzy':
        if len(vec) == 3: return mathutils.Vector( [-vec.x, vec.z, vec.y] )
        elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, -vec.x, vec.z, vec.y] )
    elif config.get('SWAP_AXIS') == 'xz-y':
        if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, -vec.y] )
        elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, -vec.y] )
    else:
        logging.warn( 'unknown swap axis mode %s', config.get('SWAP_AXIS') )
        assert 0 
Example #23
Source File: serializer.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def get_quaternion(self):
        """Return the rotation Quaternion"""
        if self.rotation_mode == 'QUATERNION':
            return self.rotation_quaternion
        return self.rotation_euler.to_quaternion() 
Example #24
Source File: serializer.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, rotation_mode='QUATERNION'):
        self.location = mathutils.Vector((0, 0, 0))
        self.scale = mathutils.Vector((1, 1, 1))

        self.rotation_mode = rotation_mode
        self.rotation_euler = mathutils.Euler((0, 0, 0))
        self.rotation_quaternion = mathutils.Quaternion((1.0, 0.0, 0.0, 0.0)) 
Example #25
Source File: UI-mapImportEditSelect.py    From FlowState with GNU General Public License v3.0 5 votes vote down vote up
def convertAsset(gate,assetID):
    unknownAsset = flowState.ASSET_CONE
    asdf = flowState.ASSET_TABLE
    #50=shipping container
    #52=shipping container
    #155=car
    #590=car
    #311=shipping container
    #274=street light
    #248=Tents
    #292=Tent top
    #561=shacks
    #249=goal posts
    #344=total unkown
    idMap = {740:flowState.ASSET_MGP_POLE,150:flowState.ASSET_MGP_GATE,170:flowState.ASSET_MGP_FLAG,275:flowState.ASSET_MGP_HURDLE,247:flowState.ASSET_CONCRETE_BLOCK,344:flowState.ASSET_CONCRETE_BLOCK,326:flowState.ASSET_MGP_FLAG,303:flowState.ASSET_CONE,319:flowState.ASSET_MGP_FLAG,249:flowState.ASSET_MGP_POLE,590:flowState.ASSET_CONCRETE_BLOCK,561:flowState.ASSET_CONCRETE_BLOCK,399:flowState.ASSET_CONCRETE_BLOCK,246:flowState.ASSET_MGP_POLE,292:flowState.ASSET_CONCRETE_BLOCK,248:flowState.ASSET_MGP_POLE,394:flowState.ASSET_CONCRETE_BLOCK,30:flowState.ASSET_PINE_TREE_TALL,18:flowState.ASSET_PINE_TREE_TALL,274:flowState.ASSET_MGP_POLE,311:flowState.ASSET_CONCRETE_BLOCK,261:flowState.ASSET_PINE_TREE_TALL,260:flowState.ASSET_PINE_TREE_TALL,401:flowState.ASSET_CONCRETE_BLOCK,155:flowState.ASSET_CONCRETE_BLOCK,48:flowState.ASSET_CONCRETE_BLOCK,52:flowState.ASSET_CONCRETE_BLOCK,20:flowState.ASSET_PINE_TREE_TALL,70:flowState.ASSET_PINE_TREE_TALL,50:flowState.ASSET_CONCRETE_BLOCK,100:flowState.ASSET_PINE_TREE_TALL,28:flowState.ASSET_PINE_TREE_TALL,108:flowState.ASSET_CHECKPOINT,151:flowState.ASSET_MGP_GATE_HANGING_LARGE,282:flowState.ASSET_MGP_GATE_HIGH_LARGE,279:flowState.ASSET_CONCRETE_BLOCK,285:flowState.ASSET_MGP_GATE_LARGE,357:flowState.ASSET_CONE,279:flowState.ASSET_MGP_GATE,286:flowState.ASSET_MGP_GATE_HANGING_LARGE,88:flowState.ASSET_CHECKPOINT}

    prefab = gate['prefab']
    vdPos = gate['trans']['pos']
    vdOri = gate['trans']['rot']
    vdScale = gate['trans']['scale']
    pos = [vdPos[0]/10,vdPos[2]/10,(vdPos[1]/10)]
    ori = list(mathutils.Quaternion((math.radians(vdOri[0]),math.radians(vdOri[1]), math.radians(vdOri[2]), math.radians(vdOri[3]))).to_euler())
    ori = [math.degrees(-ori[0]),math.degrees(-ori[2]),math.degrees(-ori[1])]
    scale = [vdScale[0]/100,vdScale[2]/100,vdScale[1]/100]
    asset = {}
    if prefab in idMap:
        asset["n"] = idMap[prefab]
    else:
        asset["n"] = unknownAsset
    asset["p"] = pos
    asset["o"] = ori
    #if prefab == 247:
    #    asset['s'] = [2,2,2]
    #else:
    asset["s"] = scale
    asset["m"] = {'id':assetID,'prefab':prefab}
    print(asset)
    return asset 
Example #26
Source File: ksparser.py    From io_kspblender with GNU General Public License v2.0 5 votes vote down vote up
def zup_quat(line):
    """changes from Unity Y-up Left-Handed Quaternion to Blender Z-up Right-Handed Quaternion"""
    zup = [float(i) for i in line.split(" ")[-1].split(",")]
    zup = mathutils.Quaternion([0-zup[3], zup[0], zup[2], zup[1]])
    return zup 
Example #27
Source File: railing.py    From building_tools with MIT License 5 votes vote down vote up
def translate_bounds(bm, verts, dir, trans):
    """ Translate the end verts inwards
    """
    if dir.z: # if rail is sloping, make vector horizontal
        left = dir.cross(Vector((0, 0, -1)))
        dir.rotate(Quaternion(left, math.atan(dir.z / dir.xy.length)).to_euler())

    vec = dir.xy*trans
    mid = len(verts) // 2
    vts = sort_verts(verts, dir)
    bmesh.ops.translate(bm, verts=vts[:mid], vec=(vec.x, vec.y, 0.0))
    bmesh.ops.translate(bm, verts=vts[-mid:], vec=(-vec.x, -vec.y, 0.0)) 
Example #28
Source File: gltf2_blender_gather_animation_sampler_keyframes.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def out_tangent(self) -> typing.Union[mathutils.Vector, mathutils.Euler, mathutils.Quaternion, typing.List[float]]:
        if self.__out_tangent is None:
            return None
        if self.target == "value":
            return self.__out_tangent
        return gltf2_blender_math.list_to_mathutils(self.__out_tangent, self.target) 
Example #29
Source File: gltf2_blender_gather_animation_sampler_keyframes.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def in_tangent(self) -> typing.Union[mathutils.Vector, mathutils.Euler, mathutils.Quaternion, typing.List[float]]:
        if self.__in_tangent is None:
            return None
        if self.target == "value":
            return self.__in_tangent
        return gltf2_blender_math.list_to_mathutils(self.__in_tangent, self.target) 
Example #30
Source File: gltf2_blender_gather_animation_sampler_keyframes.py    From glTF-Blender-IO with Apache License 2.0 5 votes vote down vote up
def value(self) -> typing.Union[mathutils.Vector, mathutils.Euler, mathutils.Quaternion, typing.List[float]]:
        if self.target == "value":
            return self.__value
        return gltf2_blender_math.list_to_mathutils(self.__value, self.target)