Example #1
0
def _importConfiguration(configDict):
    with pm.UndoChunk():
        for sm in configDict["softMods"]:
            smConfig = configDict[sm]
            targets = []
            for t in smConfig["affected"]:
                try:
                    targets.append(pm.PyNode(t))
                except pm.MayaNodeError:
                    pm.displayWarning("{}: has not been found in the scene "
                                      "and will be skipped".format(t))

            name = smConfig["name"]
            parent = smConfig["rootParent"]
            size = smConfig["iconSize"]
            grp = smConfig["grpName"]
            rootMatrix = datatypes.Matrix(smConfig["rootMatrix"])
            softModNode, baseCtl, tweakCtl = createSoftTweak(name,
                                                             targets=targets,
                                                             parent=parent,
                                                             t=rootMatrix,
                                                             grp=grp,
                                                             size=size)
            if softModNode:
                ctlBaseMatrix = datatypes.Matrix(smConfig["baseCtlMatrix"])
                ctlMatrix = datatypes.Matrix(smConfig["ctlMatrix"])
                baseCtl.setMatrix(ctlBaseMatrix, objectSpace=True)
                tweakCtl.setMatrix(ctlMatrix, objectSpace=True)
                tweakCtl.falloff.set(smConfig["falloff"])
                # we have to set the matrix again on the root because is stored
                # in local space
                baseCtl.getParent().setMatrix(rootMatrix, objectSpace=True)
Example #2
0
    def refactor_operators_meta_data_from_json_import(json_data):
        """
        Refactor back all needed PyMel objects in json dictionary.

        Args:
            json_data(dic): Th imported json data dic.

        Returns:
            Dictionary: The refactored dictionary.

        """
        operators_meta_data = json_data.get("operators_meta_data")
        for dic in operators_meta_data:
            meta_data = dic.get(constants.META_DATA_DIC_ITEM_1)
            for data in meta_data:
                # Find all world matrix lists.
                main_op_nd_ws_matrix = data.get(
                    constants.META_MAIN_OP_ND_WS_MATRIX_STR)
                sub_op_nd_ws_matrix = data.get(
                    constants.META_SUB_OP_ND_WS_MATRIX_STR)
                # Refactor all ws matrix lists to a PyMel Matrix object.
                if main_op_nd_ws_matrix:
                    data[constants.META_MAIN_OP_ND_WS_MATRIX_STR] = dt.Matrix(
                        main_op_nd_ws_matrix)
                if sub_op_nd_ws_matrix:
                    data[constants.META_SUB_OP_ND_WS_MATRIX_STR] = [
                        dt.Matrix(sub) for sub in sub_op_nd_ws_matrix
                    ]
        json_data["operators_meta_data"] = operators_meta_data
        return json_data
Example #3
0
def createCTL(type="square", child=False, *args):
    """Create a control for each selected object.

    The newly create control can be parent or child of the object.

    Args:
        type (str): The shape of the control.
        child (bool): if True, the control will be created as a
            child of the object.

    """
    iconList = []
    if child:
        if len(pm.selected()) > 0:
            for x in pm.selected():
                oChilds = [
                    item for item in x.listRelatives(ad=True, type="transform")
                    if item.longName().split("|")[-2] == x.name()
                ]

                o_icon = icon.create(None,
                                     x.name() + "_ctl", None, [1, 0, 0], type)
                iconList.append(o_icon)
                o_icon.setTransformation(x.getMatrix(worldSpace=True))
                pm.parent(o_icon, x)
                for child in oChilds:

                    pm.parent(child, o_icon)
        else:

            o_icon = icon.create(None, type + "_ctl", datatypes.Matrix(),
                                 [1, 0, 0], type)
            iconList.append(o_icon)
    else:
        if len(pm.selected()) > 0:
            for x in pm.selected():
                oParent = x.getParent()
                o_icon = icon.create(oParent,
                                     x.name() + "_ctl", x.getMatrix(),
                                     [1, 0, 0], type)
                iconList.append(o_icon)
                o_icon.setTransformation(x.getMatrix())
                pm.parent(x, o_icon)
        else:

            o_icon = icon.create(None, type + "_ctl", datatypes.Matrix(),
                                 [1, 0, 0], type)
            iconList.append(o_icon)

    for ico in iconList:
        attribute.addAttribute(ico, "isCtl", "bool", keyable=False)

    try:
        defSet = pm.PyNode("rig_controllers_grp")
        for ico in iconList:
            pm.sets(defSet, add=ico)
    except TypeError:
        print("No rig_controllers_grp found")
        pass
Example #4
0
 def MConst(self):
     item_, target_ = self.ConnectionMode()
     if self.ui.PivotCKB.isChecked():
         piv_=1
     else:
         piv_=0
     undoInfo(openChunk=True)
     try:
         for i, tgt in enumerate(target_):
             if self.ui.OneToNRB.isChecked():
                 i = 0
             elif self.ui.NToNRB.isChecked():
                 i = i
             mm=createNode('multMatrix',n='%sMM'% tgt)
             dm=createNode('decomposeMatrix',n='%sDM'% tgt)
             if piv_ == 1 :
                 tgScalePivotMtx=dt.Matrix()
                 tgScalePivotMtx[3]=tgt.getScalePivot(space='transform')
                 mm.i[0].set( tgScalePivotMtx )
                 mm.i[1].set( tgt.getMatrix(worldSpace=1) )
                 mm.i[2].set( item_[i].getMatrix(worldSpace=1).inverse() )
                 item_[i].wm >> mm.i[3]
                 tgt.pim >> mm.i[4]
                 tgTMRPM=dt.Matrix()
                 tgTMRPM[3]=tgt.transMinusRotatePivot.get()
                 mm.i[5].set(tgTMRPM)
             else:
                 mm.i[0].set( tgt.getMatrix(worldSpace=1) )
                 mm.i[1].set( item_[i].getMatrix(worldSpace=1).inverse() )
                 item_[i].wm >> mm.i[2]
                 tgt.pim >> mm.i[3]
             mm.o >> dm.imat
             if self.ui.AllCKB.isChecked() or self.ui.TransCKB.isChecked():
                 dm.ot >> tgt.t
             if self.ui.AllCKB.isChecked() or self.ui.RotCKB.isChecked():
                 if tgt.nodeType()=='joint':
                     eq=createNode('eulerToQuat', n='%sEQ'%tgt)
                     qi=createNode('quatInvert', n='%sQI'%tgt)
                     qp=createNode('quatProd', n='%sQP'%tgt)
                     qe=createNode('quatToEuler', n='%sQE'%tgt)
                     tgt.jo >> eq.irt
                     eq.oq >> qi.iq
                     dm.oq >> qp.iq1
                     qi.oq >> qp.iq2
                     qp.oq >> qe.iq
                     qe.ort >> tgt.r
                 else:
                     dm.attr('or') >> tgt.r
             if  self.ui.AllCKB.isChecked() or self.ui.ScaleCKB.isChecked():
                 dm.os >> tgt.s
             if self.ui.AllCKB.isChecked() or self.ui.ShearCKB.isChecked():
                 dm.osh >> tgt.sh
     finally:
         undoInfo(closeChunk=True)
def create_locator(PDX_locator, PDX_bone_dict):
    """
        Creates a Maya Locator object.

    :param pdx_data.PDXData PDX_locator:
    :param dict PDX_bone_dict:
    """
    # create locator
    new_loc = pmc.spaceLocator()
    pmc.select(new_loc)
    pmc.rename(new_loc, PDX_locator.name)

    # parent locator to scene bone, or apply parents transform
    parent = getattr(PDX_locator, 'pa', None)
    parent_Xform = pmdt.Matrix()

    if parent is not None:
        parent_bone = pmc.ls(parent[0], type='joint')
        if parent_bone:
            pmc.parent(new_loc, parent_bone[0])
        else:
            # parent bone doesn't exist in scene, build its transform
            if parent[0] in PDX_bone_dict:
                transform = PDX_bone_dict[parent[0]]
                parent_Xform = pmdt.Matrix(
                    transform[0], transform[1], transform[2], 0.0,
                    transform[3], transform[4], transform[5], 0.0,
                    transform[6], transform[7], transform[8], 0.0,
                    transform[9], transform[10], transform[11], 1.0
                )
            else:
                print "[io_pdx_mesh] ERROR! unable to create locator '{}' (missing parent '{}' in file data)".format(
                    PDX_locator.name, parent[0]
                )
                pmc.delete(new_loc)
                return

    # set attributes
    loc_obj = get_MObject(new_loc.name())
    mFn_Xform = OpenMaya.MFnTransform(loc_obj)

    # rotation
    mFn_Xform.setRotationQuaternion(PDX_locator.q[0], PDX_locator.q[1], PDX_locator.q[2], PDX_locator.q[3])
    # translation
    vector = OpenMaya.MVector(PDX_locator.p[0], PDX_locator.p[1], PDX_locator.p[2])
    space = OpenMaya.MSpace.kTransform
    mFn_Xform.setTranslation(vector, space)

    # apply parent transform
    new_loc.setMatrix(new_loc.getMatrix() * parent_Xform.inverse())

    # convert to Maya space
    new_loc.setMatrix(swap_coord_space(new_loc.getMatrix()))
Example #6
0
def transferAnimation(startFrame, endFrame, UIsJoints, UItJoints):
    pm.currentTime(0)

    del sJoints[:]
    del tJoints[:]
    del tOrientations[:]
    del tRotations[:]
    del sRotations[:]
    del sOrientations[:]
    del tJointsFinalMatrix[:]

    rootSource = pm.ls(sl=True, type="joint")[0]
    rootTarget = pm.ls(sl=True, type="joint")[1]

    whileCondition = 0
    keyframeNumber = startFrame
    fixList(rootSource, sRotations, sOrientations, sJoints)
    fixList(rootTarget, tRotations, tOrientations, tJoints)

    for i in range(startFrame, endFrame):
        pm.currentTime(keyframeNumber)
        global index
        index = 0
        sParentMatrix = dt.Matrix()
        tParentMatrix = dt.Matrix()
        tIndex = 0

        sourceTranslation = rootSource.getTranslation()
        rootTarget.setTranslation(sourceTranslation)

        pm.setKeyframe(tJoints[0],
                       v=sourceTranslation[0],
                       at='translateX',
                       t=(keyframeNumber, keyframeNumber))
        pm.setKeyframe(tJoints[0],
                       v=sourceTranslation[1],
                       at='translateY',
                       t=(keyframeNumber, keyframeNumber))
        pm.setKeyframe(tJoints[0],
                       v=sourceTranslation[2],
                       at='translateZ',
                       t=(keyframeNumber, keyframeNumber))

        transferMatrices(tIndex, UIsJoints, UItJoints, keyframeNumber)
        #applyAnimation(keyframeNumber, UIsJoints, UItJoints)

        del tJointsFinalMatrix[:]
        keyframeNumber += 1


#sJointList, tJointList = fixBeforeTransfer()
#transferAnimation(0, 20, sJointList, tJointList)
Example #7
0
def addJoint(parent, name, m=dt.Matrix(), vis=True):
    """
    Create a joint dagNode.

    Note:
        I'm not using the joint() comand because this is parenting
        the newly created joint to current selection which might not be desired

    Args:
        parent (dagNode): The parent for the node.
        name (str): The node name.
        m (matrix): The matrix for the node transformation (optional).
        vis (bool): Set the visibility of the new joint.

    Returns:
        dagNode: The newly created node.

    """
    node = pm.PyNode(pm.createNode("joint", n=name))
    node.setTransformation(m)
    node.setAttr("visibility", vis)

    if parent is not None:
        parent.addChild(node)

    return node
Example #8
0
def create(parent=None, name="icon", m=dt.Matrix(), color=[0,0,0], icon="cube", **kwargs):

    if "w" not in kwargs.keys(): kwargs["w"] = 1
    if "h" not in kwargs.keys(): kwargs["h"] = 1
    if "d" not in kwargs.keys(): kwargs["d"] = 1
    if "po" not in kwargs.keys(): kwargs["po"] = None
    if "ro" not in kwargs.keys(): kwargs["ro"] = None

    if icon == "cube": ctl = cube(parent, name, kwargs["w"], kwargs["h"], kwargs["d"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "pyramid": ctl = pyramid(parent, name, kwargs["w"], kwargs["h"], kwargs["d"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "square": ctl = square(parent, name, kwargs["w"], kwargs["d"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "flower": ctl = flower(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "circle": ctl = circle(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "cylinder": ctl = cylinder(parent, name, kwargs["w"], kwargs["h"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "compas": ctl = compas(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "diamond": ctl = diamond(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "cubewithpeak": ctl = cubewithpeak(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "sphere": ctl = sphere(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "arrow": ctl = arrow(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "crossarrow": ctl = crossarrow(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "cross": ctl = cross(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    elif icon == "null": ctl = null(parent, name, kwargs["w"], color, m, kwargs["po"], kwargs["ro"])
    else:
        mgear.log("invalid type of ico", mgear.sev_error)
        return

    return ctl
Example #9
0
def createInterpolateTransform(objects=None, blend=.5, *args):
    """
    Create space locator and apply gear_intmatrix_op, to interpolate the his pose between 2 selected objects.

    Args:
        objects (None or list of 2 dagNode, optional): The 2 dagNode to interpolate the transform.
        blend (float, optional): The interpolation blend factor.
        *args: Maya's dummy

    Returns:
        pyNode: The new transformation witht the interpolate matrix node applied.
    """
    if objects or len(pm.selected()) >= 2:
        if objects:
            refA = objects[0]
            refB = objects[1]

        else :
            refA = pm.selected()[0]
            refB = pm.selected()[1]

        intMatrix = aop.gear_intmatrix_op(refA.attr("worldMatrix"), refB.attr("worldMatrix"), blend)
        intTrans = pri.addTransform(refA, refA.name()+"_INTER_"+refB.name(), dt.Matrix())
        aop.gear_mulmatrix_op(intMatrix.attr("output"), intTrans.attr("parentInverseMatrix[0]"), intTrans)
        pm.displayInfo("Interpolated Transform: " + intTrans.name() + " created")
    else:
        pm.displayWarning("Please select 2 objects. ")
        return

    return intTrans
Example #10
0
def calculate_matrix_offset_(target, source, target_plug=None):
    """
    Calculate the matrix offset of the source to the target.
    Args:
            target(dagnode): The target node.
            source(dagnode): The source node.
    Return:
            The offset matrix values from target to source.
    """

    if not target_plug:
        tm = dt.Matrix(target.getMatrix(ws=True)).inverse()
    else:
        tm = dt.Matrix(target.attr(target_plug).get()).inverse()
    sm = dt.Matrix(source.getMatrix(ws=True))
    return sm.__mul__(tm)
Example #11
0
def null(parent=None, name="null", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):

    dlen = width * .5

    v0 = dt.Vector(dlen, 0, 0)
    v1 = dt.Vector(-dlen, 0, 0)
    v2 = dt.Vector(0,dlen, 0)
    v3 = dt.Vector(0, -dlen, 0)
    v4 = dt.Vector(0, 0, dlen)
    v5 = dt.Vector(0, 0, -dlen)

    points = getPointArrayWithOffset([v0, v1], pos_offset, rot_offset)
    node = cur.addCurve(parent, name, points, False, 1, m)
    
    points = getPointArrayWithOffset([v2, v3], pos_offset, rot_offset)
    crv_0 = cur.addCurve(parent, name, points, False, 1, m)
    
    points = getPointArrayWithOffset([v4, v5], pos_offset, rot_offset)
    crv_1 = cur.addCurve(parent, name, points, False, 1, m)
    
    for crv in [crv_0, crv_1]:
        for shp in crv.listRelatives(shapes=True):
            node.addChild(shp, add=True, shape=True)
        delete(crv)
    
    setcolor(node, color)
    
    return node
Example #12
0
    def createGroup(self):
        logger.info('creating group')

        root = pm.group(empty=True, n=self.code)

        if self.onSceneParent:
            onSceneParentSearch = pm.ls(self.onSceneParent, r=True)
            if onSceneParentSearch and len(onSceneParentSearch) == 1:
                onSceneParent = onSceneParentSearch[0]
                pm.parent(root, onSceneParent)
            else:
                logger.warn('Found no onSceneParent %s' % onSceneParentSearch)

        if self.xform:
            n = dt.Matrix()
            n.setToIdentity()
            for transform in self.xform.itervalues():
                logger.debug(self.xform)
                logger.debug(transform)
                tempNode = pm.group(empty=True)
                pm.xform(tempNode,
                         m=transform['xform'],
                         rp=transform['rotatePivot'],
                         sp=transform['scalePivot'])
                m = tempNode.getMatrix()
                n = n * m
                pm.delete(tempNode)

            #workaround to transform groupAssets
            root.setTransformation(n)
Example #13
0
    def importToScene(self):
        """
        Import this source to the current file.
        :return:
        """
        item = self.getItem()
        componentPath = item.getPublishPath()
        nodes = pm.importFile(componentPath, defaultNamespace=True)
        root = pm.ls(nodes, assemblies=True)

        if self.xform:
            if root and len(root) == 1:
                n = dt.Matrix()
                n.setToIdentity()
                for transform in self.xform.itervalues():
                    tempNode = pm.group(empty=True)
                    pm.xform(tempNode,
                             m=transform['xform'],
                             rp=transform['rotatePivot'],
                             sp=transform['scalePivot'])
                    m = tempNode.getMatrix()
                    n = n * m
                    pm.delete(tempNode)
                root.setTransformation(n)

        return {}
Example #14
0
def guideBladeIcon(parent=None, name="blade",lenX=1.0, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):
    """
    Create a curve with a BLADE GUIDE shape.

    Note:
        This icon is specially design for **Shifter** blade guides

    Args:
        parent (dagNode): The parent object of the newly created curve.
        name (str): Name of the curve.
        lenX (float): Width of the shape.
        color (int or list of float): The color in index base or RGB.
        m (matrix): The global transformation of the curve.
        pos_offset (vector): The xyz position offset of the curve from its center.
        rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians

    Returns:
        dagNode: The newly created icon.
    """

    v0 = dt.Vector(0 , 0, 0)
    v1 = dt.Vector(lenX , 0, 0)
    v2 = dt.Vector(0, lenX/3, 0)


    points = getPointArrayWithOffset([v0, v1, v2 ], pos_offset, rot_offset)

    bladeIco = cur.addCurve(parent, name, points, True, 1, m)

    setcolor(bladeIco, color)

    att.setNotKeyableAttributes(bladeIco)

    return bladeIco
Example #15
0
def guideRootIcon(parent=None, name="root", width=.5,  color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):
    """
    Create a curve with a ROOT GUIDE shape.

    Note:
        This icon is specially design for **Shifter** root guides

    Args:
        parent (dagNode): The parent object of the newly created curve.
        name (str): Name of the curve.
        width (float): Width of the shape.
        color (int or list of float): The color in index base or RGB.
        m (matrix): The global transformation of the curve.
        pos_offset (vector): The xyz position offset of the curve from its center.
        rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians

    Returns:
        dagNode: The newly created icon.
    """

    rootIco = null(parent, name, width, color, m, pos_offset, rot_offset)
    cubeWidth = width/2.0
    cubeIco = cube(parent, name, cubeWidth, cubeWidth, cubeWidth, color, m, pos_offset, rot_offset)

    for shp in cubeIco.listRelatives(shapes=True):
        rootIco.addChild(shp, add=True, shape=True)
    pm.delete(cubeIco)

    att.setNotKeyableAttributes(rootIco)
    rootIco.addAttr("isGearGuide", at="bool", dv=True)

    return rootIco
Example #16
0
def setMatrixAxis_(matrix_, axis_):
    """Get the FlipAxis from matrix

    Arguments:
        matrix_ (matrix): The input Matrix.
        axis_ (axis): flip axis

    Returns:
        matrix : fliped matrix

    """
    flipMatrix = dt.Matrix()

    if axis_ == 'x':
        matrix_value = [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

    elif axis_ == 'y':
        matrix_value = [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

    elif axis_ == 'z':
        matrix_value = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]

    if matrix_value:
        om.MScriptUtil.createMatrixFromList(matrix_value, flipMatrix)

    return matrix_ * flipMatrix
Example #17
0
def getFilteredTransform(m, translation=True, rotation=True, scaling=True):
    """
    Retrieve a transformation filtered.

    Args:
        m (matrix): the reference matrix
        translation (bool): If true the return matrix will match the translation.
        rotation (bool): If true the return matrix will match the rotation.
        scaling (bool): If true the return matrix will match the scaling.

    Returns:
        matrix : The filtered matrix

    """

    t = dt.Vector(m[3][0],m[3][1],m[3][2])
    x = dt.Vector(m[0][0],m[0][1],m[0][2])
    y = dt.Vector(m[1][0],m[1][1],m[1][2])
    z = dt.Vector(m[2][0],m[2][1],m[2][2])

    out = dt.Matrix()

    if translation:
        out = setMatrixPosition(out, t)

    if rotation and scaling:
        out = setMatrixRotation(out, [x,y,z])
    elif rotation and not scaling:
        out = setMatrixRotation(out, [x.normal(), y.normal(), z.normal()])
    elif not rotation and scaling:
        out = setMatrixRotation(out, [dt.Vector(1,0,0) * x.length(), dt.Vector(0,1,0) * y.length(), dt.Vector(0,0,1) * z.length()])

    return out
Example #18
0
def matrix_normalize_scale(matrix):
    """
    Will normalize the scale in given four by four matrix to 1 or -1.

    Args:
        matrix(dt.Matrix): Four by four matrix.

    Return:
        dt.Matrix: The scale normalized matrix.

    """
    scale = matrix.scale
    tm = dt.TransformationMatrix(matrix)
    if scale[0] > 0:
        scale[0] = 1
    else:
        scale[0] = -1
    if scale[1] > 0:
        scale[1] = 1
    else:
        scale[1] = -1
    if scale[2] > 0:
        scale[2] = 1
    else:
        scale[2] = -1
    tm.setScale(scale, space="world")
    return dt.Matrix(tm)
Example #19
0
def cross(parent=None, name="cross", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):

    width = width * 0.35
    offset1 = width * .5
    offset2 = width * 1.5

    v0 = dt.Vector(width,offset2,0)
    v1 = dt.Vector(offset2,width,0)
    v2 = dt.Vector(offset1,0,0)

    v3 = dt.Vector(offset2,-width,0)
    v4 = dt.Vector(width,-offset2,0)
    v5 = dt.Vector(0,-offset1,0)

    v6 = dt.Vector(-width,-offset2,0)
    v7 = dt.Vector(-offset2,-width,0)
    v8 = dt.Vector(-offset1,0,0)

    v9 = dt.Vector(-offset2,width,0)
    v10 = dt.Vector(-width,offset2,0)
    v11 = dt.Vector(0,offset1,0)

    points = getPointArrayWithOffset([v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11], pos_offset, rot_offset)

    node = cur.addCurve(parent, name, points, True, 1, m)
    
    setcolor(node, color)
    
    return node
Example #20
0
def doritosMagic(mesh, joint, jointBase, parent=None):
    # magic of doritos connection
    skinCluster = skin.getSkinCluster(mesh)
    if not skinCluster:
        if pm.objExists('static_jnt') is not True:
            static_jnt = primitive.addJoint(parent,
                                            "static_jnt",
                                            m=datatypes.Matrix(),
                                            vis=True)
        static_jnt = pm.PyNode("static_jnt")

        # apply initial skincluster
        skinCluster = pm.skinCluster(static_jnt,
                                     mesh,
                                     tsb=True,
                                     nw=2,
                                     n='%s_skinCluster' % mesh.name())
    try:
        # we try to add the joint to the skin cluster. Will fail if is already
        # in the skin cluster
        pm.skinCluster(skinCluster, e=True, ai=joint, lw=True, wt=0)
    except Exception:
        pm.displayInfo("The Joint: %s  is already in the %s." %
                       (joint.name(), skinCluster.name()))
        pass
    cn = joint.listConnections(p=True, type="skinCluster")
    for x in cn:
        if x.type() == "matrix":
            if x.name().split(".")[0] == skinCluster.name():
                # We force to avoid errors in case the joint is already
                # connected
                pm.connectAttr(jointBase + ".worldInverseMatrix[0]",
                               skinCluster + ".bindPreMatrix[" +
                               str(x.index()) + "]",
                               f=True)
Example #21
0
def sphere(parent=None, name="sphere", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):

    dlen = width

    v0 = dt.Vector(0.75*dlen, 0, 0)
    v1 = dt.Vector(0, -.75*dlen, 0)
    v2 = dt.Vector(-.75*dlen, 0, 0)
    v3 = dt.Vector(0, 0.75*dlen, 0)
    v4 = dt.Vector(0.75*dlen, 0, 0)
    v5 = dt.Vector(0, 0, -.75*dlen)
    v6 = dt.Vector(-.75*dlen, 0, 0)
    v7 = dt.Vector(0, 0, 0.75*dlen)
    v8 = dt.Vector(0, 0, 0.75*dlen)
    v9 = dt.Vector(0, -.75*dlen, 0)
    v10 = dt.Vector(0, 0, -.75*dlen)
    v11 = dt.Vector(0, 0.75*dlen, 0)

    points = getPointArrayWithOffset([v0, v1, v2, v3], pos_offset, rot_offset)
    node = cur.addCurve(parent, name, points, True, 3, m)
    
    points = getPointArrayWithOffset([v4, v5, v6, v7], pos_offset, rot_offset)
    crv_0 = cur.addCurve(parent, node+"_0crv", points, True, 3, m)
    
    points = getPointArrayWithOffset([v8, v9, v10, v11], pos_offset, rot_offset)
    crv_1 = cur.addCurve(parent, node+"_1crv", points, True, 3, m)
    
    for crv in [crv_0, crv_1]:
        for shp in crv.listRelatives(shapes=True):
            node.addChild(shp, add=True, shape=True)
        delete(crv)
    
    setcolor(node, color)
    
    return node
Example #22
0
def addCnsCurve(parent, name, centers, degree=1, m=datatypes.Matrix()):
    """Create a curve attached to given centers. One point per center

    Arguments:
        parent (dagNode): Parent object.
        name (str): Name
        centers (list of dagNode): Object that will drive the curve.
        degree (int): 1 for linear curve, 3 for Cubic.

    Returns:
        dagNode: The newly created curve.
    """
    # rebuild list to avoid input list modification
    centers = centers[:]
    if degree == 3:
        if len(centers) == 2:
            centers.insert(0, centers[0])
            centers.append(centers[-1])
        elif len(centers) == 3:
            centers.append(centers[-1])

    points = [datatypes.Vector() for center in centers]

    node = addCurve(parent, name, points, False, degree, m=m)

    applyop.gear_curvecns_op(node, centers)

    return node
Example #23
0
def addCurve(parent,
             name,
             points,
             close=False,
             degree=3,
             m=datatypes.Matrix()):
    """Create a NurbsCurve with a single subcurve.

    Arguments:
        parent (dagNode): Parent object.
        name (str): Name
        positions (list of float): points of the curve in a one dimension array
            [point0X, point0Y, point0Z, 1, point1X, point1Y, point1Z, 1, ...].
        close (bool): True to close the curve.
        degree (bool): 1 for linear curve, 3 for Cubic.
        m (matrix): Global transform.

    Returns:
        dagNode: The newly created curve.
    """
    if close:
        points.extend(points[:degree])
        knots = range(len(points) + degree - 1)
        node = pm.curve(n=name, d=degree, p=points, per=close, k=knots)
    else:
        node = pm.curve(n=name, d=degree, p=points)

    if m is not None:
        node.setTransformation(m)

    if parent is not None:
        parent.addChild(node)

    return node
Example #24
0
def move_to_transform(obj, target, upVector=dt.Vector(0, 1, 0)):
    ''' 
    Moves an inputed object to a target position.
    Orients to the upVector of the target.
    :param obj: The obj transform to transformed
    :param target: The target transform
    :param upVector: The local up vector of the target
    '''

    # The world up vector
    worldUp = dt.Vector(0, 1, 0)

    # The Transformation matrix of the target in world space
    if target:
        targetSpace = target.getMatrix(worldSpace=True)
    else:
        targetSpace = dt.Matrix()

    # The input upVector transformed into target rotation space
    targetUp = upVector.rotateBy(targetSpace)

    # Create a Quaternion  to represent the rotation
    # From the object orientation to the target orientation
    rotation = worldUp.rotateTo(targetUp)

    # Transform the object into the target space
    obj.setMatrix(targetSpace, worldSpace=True)
    obj.setRotation(rotation, space='world')
Example #25
0
def createCurveFromCurve(srcCrv,
                         name,
                         nbPoints,
                         parent=None,
                         m=datatypes.Matrix()):
    """Create a curve from a curve

    Arguments:
        srcCrv (curve): The source curve.
        name (str): The new curve name.
        nbPoints (int): Number of control points for the new curve.
        parent (dagNode): Parent of the new curve.

    Returns:
        dagNode: The newly created curve.
    """
    if isinstance(srcCrv, six.string_types) or isinstance(
            srcCrv, six.text_type):
        srcCrv = pm.PyNode(srcCrv)
    length = srcCrv.length()
    parL = srcCrv.findParamFromLength(length)
    param = []
    increment = parL / (nbPoints - 1)
    p = 0.0
    for x in range(nbPoints):
        # we need to check that the param value never exceed the parL
        if p > parL:
            p = parL
        pos = srcCrv.getPointAtParam(p, space='world')
        param.append(pos)
        p += increment
    crv = addCurve(parent, name, param, close=False, degree=3, m=m)
    return crv
Example #26
0
def guideLocatorIcon(parent=None, name="locator", width=.5, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):
    """
    Create a curve with a LOCATOR GUIDE shape.

    Note:
        This icon is specially design for **Shifter** locator guides

    Args:
        parent (dagNode): The parent object of the newly created curve.
        name (str): Name of the curve.
        width (float): Width of the shape.
        color (int or list of float): The color in index base or RGB.
        m (matrix): The global transformation of the curve.
        pos_offset (vector): The xyz position offset of the curve from its center.
        rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians

    Returns:
        dagNode: The newly created icon.
    """
    rootIco = null(parent, name, width, color, m, pos_offset, rot_offset)
    spheWidth = width/2.0
    sphereIco = sphere(parent, name, spheWidth, color, m, pos_offset, rot_offset)

    for shp in sphereIco.listRelatives(shapes=True):
        rootIco.addChild(shp, add=True, shape=True)
    pm.delete(sphereIco)

    att.setNotKeyableAttributes(rootIco)
    rootIco.addAttr("isGearGuide", at="bool", dv=True)
    # Set the control shapes isHistoricallyInteresting
    for oShape in rootIco.getShapes():
        oShape.isHistoricallyInteresting.set(False)

    return rootIco
Example #27
0
def arrow(parent=None, name="arrow", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):
    """
    Create a curve with a ARROW shape.

    Args:
        parent (dagNode): The parent object of the newly created curve.
        name (str): Name of the curve.
        width (float): Width of the shape.
        color (int or list of float): The color in index base or RGB.
        m (matrix): The global transformation of the curve.
        pos_offset (vector): The xyz position offset of the curve from its center.
        rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians

    Returns:
        dagNode: The newly created icon.
    """

    dlen = width * 0.5

    v0 = dt.Vector(0, 0.3*dlen, -dlen)
    v1 = dt.Vector(0, 0.3*dlen, 0.3*dlen)
    v2 = dt.Vector(0, 0.6*dlen, 0.3*dlen)
    v3 = dt.Vector(0, 0, dlen)
    v4 = dt.Vector(0, -0.6*dlen, 0.3*dlen)
    v5 = dt.Vector(0, -0.3*dlen, 0.3*dlen)
    v6 = dt.Vector(0, -0.3*dlen, -dlen)

    points = getPointArrayWithOffset([v0, v1, v2, v3, v4, v5, v6], pos_offset, rot_offset)

    node = cur.addCurve(parent, name, points, True, 1, m)

    setcolor(node, color)

    return node
Example #28
0
def diamond(parent=None, name="diamond", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):
    """
    Create a curve with a DIAMOND shape.

    Args:
        parent (dagNode): The parent object of the newly created curve.
        name (str): Name of the curve.
        width (float): Width of the shape.
        height (float): Height of the shape.
        depth (float): Depth of the shape.
        color (int or list of float): The color in index base or RGB.
        m (matrix): The global transformation of the curve.
        pos_offset (vector): The xyz position offset of the curve from its center.
        rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians

    Returns:
        dagNode: The newly created icon.
    """

    dlen = width * 0.5

    top = dt.Vector(0,dlen,0)
    pp = dt.Vector(dlen,0,dlen)
    pN = dt.Vector(dlen,0,dlen*-1)
    Np = dt.Vector(dlen*-1,0,dlen)
    NN = dt.Vector(dlen*-1,0,dlen*-1)
    bottom = (0,-dlen,0)

    points = getPointArrayWithOffset([pp,top,pN,pp,Np,top,NN,Np,NN,pN,bottom,NN,bottom,Np,bottom,pp], pos_offset, rot_offset)

    node = cur.addCurve(parent, name, points, False, 1, m)

    setcolor(node, color)

    return node
Example #29
0
def square(parent=None, name="square", width=1, depth=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None):
    """
    Create a curve with a SQUARE shape.

    Args:
        parent (dagNode): The parent object of the newly created curve.
        name (str): Name of the curve.
        width (float): Width of the shape.
        depth (float): Depth of the shape.
        color (int or list of float): The color in index base or RGB.
        m (matrix): The global transformation of the curve.
        pos_offset (vector): The xyz position offset of the curve from its center.
        rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians

    Returns:
        dagNode: The newly created icon.
    """
    lenX = width * 0.5
    lenZ = depth * 0.5

    v0 = dt.Vector(lenX , 0, lenZ)
    v1 = dt.Vector(lenX , 0, lenZ*-1)
    v2 = dt.Vector(lenX*-1, 0, lenZ*-1)
    v3 = dt.Vector(lenX*-1, 0, lenZ)

    points = getPointArrayWithOffset([v0, v1, v2, v3], pos_offset, rot_offset)

    node = cur.addCurve(parent, name, points, True, 1, m)

    setcolor(node, color)

    return node
Example #30
0
    def initialHierarchy(self):

        mgear.log("Initial Hierarchy")

        # --------------------------------------------------
        # Model
        self.model = pri.addTransformFromPos(None, self.options["rig_name"])
        att.lockAttribute(self.model)

        # --------------------------------------------------
        # Global Ctl
        self.global_ctl = self.addCtl(self.model,
                                      "global_C0_ctl",
                                      dt.Matrix(),
                                      self.options["C_color_fk"],
                                      "crossarrow",
                                      w=10)

        # --------------------------------------------------
        # INFOS
        self.isRig_att = att.addAttribute(self.model, "is_rig", "bool", True)
        self.rigName_att = att.addAttribute(self.model, "rig_name", "string",
                                            self.options["rig_name"])
        self.user_att = att.addAttribute(self.model, "user", "string",
                                         getpass.getuser())
        self.isWip_att = att.addAttribute(self.model, "wip", "bool",
                                          self.options["mode"] != 0)
        self.date_att = att.addAttribute(self.model, "date", "string",
                                         str(datetime.datetime.now()))
        self.mayaVersion_att = att.addAttribute(
            self.model, "maya_version", "string",
            str(mel.eval("getApplicationVersionAsFloat")))
        self.gearVersion_att = att.addAttribute(self.model, "gear_version",
                                                "string", mgear.getVersion())
        self.synoptic_att = att.addAttribute(self.model, "synoptic", "string",
                                             str(self.options["synoptic"]))
        self.comments_att = att.addAttribute(self.model, "comments", "string",
                                             str(self.options["comments"]))
        self.ctlVis_att = att.addAttribute(self.model, "ctl_vis", "bool", True)
        self.shdVis_att = att.addAttribute(self.model, "shd_vis", "bool",
                                           False)

        self.qsA_att = att.addAttribute(self.model, "quickselA", "string", "")
        self.qsB_att = att.addAttribute(self.model, "quickselB", "string", "")
        self.qsC_att = att.addAttribute(self.model, "quickselC", "string", "")
        self.qsD_att = att.addAttribute(self.model, "quickselD", "string", "")
        self.qsE_att = att.addAttribute(self.model, "quickselE", "string", "")
        self.qsF_att = att.addAttribute(self.model, "quickselF", "string", "")

        # --------------------------------------------------
        # UI SETUP AND ANIM
        self.oglLevel_att = att.addAttribute(self.model, "ogl_level", "long",
                                             0, None, None, 0, 3)

        # --------------------------------------------------
        # Basic set of null
        if self.options["shadow_rig"]:
            self.shd_org = pri.addTransformFromPos(self.model, "shd_org")
            connectAttr(self.shdVis_att, self.shd_org.attr("visibility"))