Example #1
0
    def displayConnect(self, obj):
        # Create curve for display, between selected objects
        # Return [curve, locator1, locator2]
        if len(obj) == 0:
            obj = pm.ls(transforms=1, sl=1)

        if len(obj) < 2:
            pm.error(u"KH_curve_Connect : 선택된 오브젝트가 없습니다.")

        pointA = obj[0]
        pointB = obj[1]

        curve = pm.curve(p=[(0, 0, 0), (0, 0, 0)], k=[0, 1], d=1)
        pointCurveConstraint1 = pm.pointCurveConstraint(curve + ".ep[0]",
                                                        ch=True)
        pointCurveConstraint2 = pm.pointCurveConstraint(curve + ".ep[1]",
                                                        ch=True)

        pointCostraint1 = pm.pointConstraint(pointA, pointCurveConstraint1[0])
        pointCostraint2 = pm.pointConstraint(pointB, pointCurveConstraint2[0])

        locShape1 = pm.listRelatives(pointCurveConstraint1[0], s=1)
        locShape2 = pm.listRelatives(pointCurveConstraint2[0], s=1)
        pm.setAttr(locShape1[0] + ".visibility", 0)
        pm.setAttr(locShape2[0] + ".visibility", 0)

        return [
            curve,
            pm.PyNode(pointCurveConstraint1[0]),
            pm.PyNode(pointCurveConstraint2[0]), pointCostraint1,
            pointCostraint2
        ]
def main():
    sel = pm.ls(os=True, fl=True)
    if len(sel) != 3:
        pm.warning("Select 3 vertices in order of origin, x, and y")
        return
    shape = pm.listRelatives(sel[0], parent=True)[0]
    transformNode = pm.listRelatives(shape, parent=True)[0]
    piv = pm.xform(transformNode, q=True, ws=True, rp=True)
    p0 = sel[0].getPosition()
    p1 = sel[1].getPosition()
    p2 = sel[2].getPosition()
    X = p1 - p0  # X-axis
    Y = p2 - p0  # Y-axis
    Z = X ^ Y  # Z-axis
    P = pm.datatypes.Point(piv[0], piv[1], piv[2])
    X.normalize()
    Y.normalize()
    Z.normalize()
    M = pm.datatypes.Matrix(
        X.x, X.y, X.z, 0,
        Y.x, Y.y, Y.z, 0,
        Z.x, Z.y, Z.z, 0,
        P.x, P.y, P.z, 1)
 
    pm.xform(transformNode, matrix=M.inverse())
    pm.select(transformNode, r=True)
    pm.makeIdentity(apply=True, t=True, r=True, s=False, n=False)
    pm.xform(transformNode, ws=True, piv=(0, 0, 0))
    pm.xform(transformNode, matrix=M)
Example #3
0
def ins_jnt(**kwargs):
    num = kwargs.get("num_jts", 1)
    sel = pm.ls(selection=True)
    chld = pm.listRelatives(sel[0], children=True)
    if not chld[0].type() == "joint":
        print "end joint reached"
        return None
    #position_lst = []
    pos1 = pm.xform(sel[0], query=True, worldSpace=True, translation=True)
    pos2 = pm.xform(chld, query=True, worldSpace=True, translation=True)
    len_vec1 = OpenMaya.MVector(pos1[0], pos1[1], pos1[2])
    len_vec2 = OpenMaya.MVector(pos2[0], pos2[1], pos2[2])
    len_vec = len_vec2 - len_vec1
    print len_vec.x, len_vec.y, len_vec.z
    part_vec = len_vec / (num + 1)
    pos_vec = len_vec1 + len_vec / (num + 1)
    cur_jnt = sel[0]
    for i in range(num):
        new_position = [pos_vec.x, pos_vec.y, pos_vec.z]
        #print new_position
        new_joint = pm.insertJoint(cur_jnt)
        pm.joint(new_joint, edit=True, component=True, position=new_position)
        #pm.xform(new_joint, translation=new_position)
        pos_vec += part_vec
        cur_jnt = new_joint
    return None
Example #4
0
def createController(object):
    # object = pma.ls(sl=True)
    pivotObj = pma.xform(object, query=True, t=True, worldSpace=True)
    edges = pma.filterExpand(pma.polyListComponentConversion(te=1), sm=32,
                             ex=1)  # convert edges to curve ancd create one object
    for edge in edges:
        vtx = pma.ls(pma.polyListComponentConversion(edge, fe=1, tv=1), fl=1)
        p1 = pma.pointPosition(vtx[0])
        p2 = pma.pointPosition(vtx[1])
        curves = pma.curve(n="line_ctrl_curve", d=1, p=(p1, p2))

    ctrl = pma.curve(n="bool_ctrl", d=1, ws=True, p=pivotObj)
    pma.xform(centerPivots=True)
    for curveEdge in pma.ls("line_ctrl*"):
        pma.parent(curveEdge, ctrl, s=1, r=1)
        pma.rename(curveEdge, "shapeunused")

    transforms = pma.ls(type='transform')
    deleteList = []
    for tran in transforms:
        if pma.nodeType(tran) == 'transform':
            children = pma.listRelatives(tran, c=True)
            if children is None:
                # print '%s, has no childred' %(tran)
                deleteList.append(tran)

    if not deleteList:
        pma.delete(deleteList)
    return ctrl
Example #5
0
def get_loop_from_edge():
    sel = pm.ls(orderedSelection=True)
    mid_pos = []
    pm.select(clear=True)
    for edg in sel:
        obj_sh_name = str(edg).split(".")[0]
        obj_name = pm.listRelatives(obj_sh_name, parent=True)
        edg_num = int((edg.split("[")[1]).replace("]", ""))
        pm.polySelect(obj_name, edgeLoopOrBorder=edg_num)
        edg_sel = pm.ls(selection=True)
        mid_pos.append(CustomScripts.midPos(selected_items=edg_sel))
        pm.select(clear=True)
    pm.select(clear=True)
    jnts = []
    for pos in mid_pos:
        cur_jnt = pm.joint(position=pos)
        jnts.append(cur_jnt)
        index = mid_pos.index(pos)
        if index > 0:
            pm.joint(jnts[index - 1],
                     edit=True,
                     orientJoint="xyz",
                     secondaryAxisOrient="yup",
                     children=True,
                     zeroScaleOrient=True)
    pm.select(clear=True)
    pm.select(jnts[-2], jnts[-1])
    CustomScripts.CopyJntOri()
    pm.select(clear=True)
    pm.select(jnts[-1])
    return None
Example #6
0
def copyObjects(**kwargs):
    """
        Input object to be copied
        select positions where the objects needs be copied and run the script
        the copied object constraints the position objects if options are selected
    """
    print "TEST"
    obj = kwargs.get("obj", "")
    prFlg = kwargs.get("prFlg", False)
    scFlg = kwargs.get("scFlg", False)
    sel = pm.ls(selection=True, flatten=True)
    ch = None
    for comp in sel:
        pos = pm.xform(comp, query=True, worldSpace=True, translation=True)
        new_obj = pm.duplicate(obj)
        pm.xform(new_obj, worldSpace=True, translation=pos)
        if prFlg or scFlg:
            typ = str(pm.nodeType(comp))
            if typ == "transform":
                ch = comp
            else:
                shp = pm.ls(comp, objectsOnly=True)[0]
                trn = pm.listRelatives(shp, parent=True)[0]
                ch = trn
            if prFlg:
                pm.parentConstraint(new_obj, ch, maintainOffset=True)
            if scFlg:
                pm.scaleConstraint(new_obj, ch, maintainOffset=True)
    return None
Example #7
0
 def get_children_lists(sel, dist):
     if not sel:
         return
     selection_list = []
     for o in sel:
         ch = pm.listRelatives(o, children=True)
         [selection_list.append(o) for o in ch if type(o) == pm.Transform]
     # pprint(selection_list)
     # pprint(dist)
     get_children_lists(selection_list, (dist * 0.5))
Example #8
0
def _if_mesh_move_up(sel):
    """
    Checks to see if selection is a mesh object, if it is it will select its transform.
    :param sel: The object in question.
    :return: Transform
    """
    if sel.type() == 'mesh':
        obj = pm.listRelatives(sel, parent=True)[0]
    else:
        obj = sel

    return obj
Example #9
0
def _is_group(sel):
    """
    determine if a group is selected or if its a bunch of transforms.
    :param sel: the selection objects.
    :return: new list made up by the children of the selected group, or the original
    selection if selection is not a group.
    """
    new_selection = [
        _if_mesh_move_up(o) for o in pm.listRelatives(sel, children=True)
        if o.type() == 'transform' or 'mesh'
    ]

    return new_selection
    def at_selection(self, **kwargs):
        # get inputs
        setup_name = kwargs.get("name", None)
        path_name = kwargs.get("path", None)
        sample_obj = kwargs.get("sample", None)
        obj_lst = kwargs.get("selection_list", None)
        full_length = pm.arclen(path_name)
        paramVal = []
        uVal = []
        for obj in obj_lst:
            pos = pm.xform(obj, query=True, translation=True, worldSpace=True)
            param = self.getuParamVal(pnt=pos, crv=path_name)
            paramVal.append(param)
        crv_shp = pm.listRelatives(path_name, shapes=True)[0]
        arcLen = pm.arcLengthDimension(crv_shp + ".u[0]")
        for val in paramVal:
            pm.setAttr(str(arcLen) + ".uParamValue", val)
            len_at_pos = pm.getAttr(str(arcLen) + ".arcLength")
            uVal.append(len_at_pos / full_length)
        pm.delete(arcLen)
        path_anim_list = []
        if not self.get_use_selection():
            obj_lst = []
            if sample_obj:
                for i in uVal:
                    obj_lst.append(
                        pm.duplicate(sample_obj,
                                     name=setup_name + str(i + 1) + "_OBJECT"))
            else:
                for i in uVal:
                    pm.select(clear=True)
                    obj_lst.append(
                        pm.joint(name=setup_name + str(i + 1) + "_JNT"))

        index = 0
        for u in uVal:
            pm.select(clear=True)
            pathanim = pm.pathAnimation(obj_lst[index],
                                        curve=path_name,
                                        fractionMode=True,
                                        follow=True,
                                        followAxis="x",
                                        worldUpType="vector",
                                        worldUpVector=(0, 1, 0))
            index += 1
            path_anim_list.append(pathanim)
            pm.setAttr(str(pathanim) + ".uValue", u)
            pm.disconnectAttr(str(pathanim) + ".u")
        return (obj_lst, path_anim_list)
def match_ctrl(jnt, ctrl):
    control_name = ctrl.name(long=None)
    control_shape = ctrl.getShape()

    transform = pm.group(parent=jnt, empty=True)
    transform.zeroTransformPivots()
    pm.parent(transform, world=True)

    pm.parent(control_shape, transform, absolute=True, shape=True)

    new_trans = pm.listRelatives(control_shape, parent=True)

    pm.makeIdentity(new_trans, s=True, r=True, t=True, apply=True)

    pm.parent(control_shape, transform, relative=True, shape=True)

    pm.delete(new_trans, ctrl)

    transform.rename(control_name)

    pm.delete(transform, constructionHistory=True)
Example #12
0
def arsenal_lightControl(arsenal = None, selectionAll = False, value = None):
    if arsenal is None:
        OpenMaya.MGlobal.displayError('[Arsenal ToolBox] Arsenal not found.')
        return 
    selection = list()
    if selectionAll:
        selection = pm.ls(type=pm.listNodeTypes('light'))
    else:
        selectionTMP = pm.ls(sl=True)
        for sel in selectionTMP:
            if pm.objectType(sel) in pm.listNodeTypes('light'):
                selection.append(sel)
            else:
                shape = pm.listRelatives(sel, shapes=True)
                if len(shape) != 0:
                    selection.append(shape[0])

    allAttr = {'shadowRays': value,
     'subdivs': value}
    for attr in allAttr:
        arsenal.setSimpleValue(selection=selection, attribute=attr, value=allAttr[attr], message='Light : value ' + str(allAttr[attr]) + ' setted for attribute ' + attr)
Example #13
0
def immediateParent(**kwargs):
    """
        Insert an immediate parent node to the selected object with
        the selected object position as reference to parent
    """
    group_name = kwargs.get("name", "null")
    sel_obj = pm.ls(selection=True)
    if not sel_obj:
        pm.group(name=group_name)
        return None
    for obj in sel_obj:
        parent_node = pm.listRelatives(obj, parent=True)
        pm.select(clear=True)
        group_name = str(obj) + "_Znode"
        null = pm.group(name=group_name)
        pm.parentConstraint(obj, null, maintainOffset=False, name="temp_const")
        pm.delete("temp_const")
        if parent_node:
            pm.parent(null, parent_node)
        pm.parent(obj, null)
    return None
    def AddNodeFromLongName(self, longName=""):
        assert (len(longName) > 0)

        # Check unique, return if not
        root = self.invisibleRootItem()
        for i in range(root.childCount()):
            item = root.child(i)
            itemLongName = item.text(1)
            if longName == itemLongName:
                return

        pyNode = pm.PyNode(longName)
        nodeName = longName.rsplit("|", 1)[-1]

        # Return node type
        try:
            shape = pm.listRelatives(pyNode, children=True, s=True)[0]
            nodeType = pm.nodeType(shape, q=True)
        except:
            nodeType = pm.nodeType(pyNode, q=True)

        # Construct item widget
        item = QTreeWidgetItem()
        item.setText(0, nodeName)
        item.setText(1, longName)

        # Set icon
        icon = QIcon()
        if nodeType == u'mesh':
            icon = QIcon(":/mesh.svg")
        elif nodeType == u'transform':
            icon = QIcon(":/transform.svg")
        elif nodeType == u'joint':
            icon = QIcon(":/kinJoint.png")
        elif nodeType == u'locator':
            icon = QIcon(":/locator.svg")
        item.setIcon(0, icon)

        self.addTopLevelItem(item)
Example #15
0
def treadAtPoints(**kwargs):
    #get inputs
    tread_name = kwargs.get("tr_name", "Tread")
    crv = kwargs.get("path_crv", None)
    crv = str(pm.duplicate(crv, name=str(tread_name) + "PathCrv")[0])
    pm.xform(crv, centerPivots=True)
    #obtain curve length
    full_length = pm.arclen(crv)
    paramVal = []
    uVal = []
    # get param value on the curve at each position selected (locators)
    sel_obj = pm.ls(selection=True)
    for obj in sel_obj:
        pos = pm.xform(obj, query=True, translation=True, worldSpace=True)
        param = getuParamVal(pos, crv)
        paramVal.append(param)
    crv_shp = pm.listRelatives(crv, shapes=True)[0]
    # create arc length dimension tool
    arcLen = pm.arcLengthDimension(crv_shp + ".u[0]")
    # for each param value obtained set the arc length tool attribute and
    # store the length of curve at that param value
    # normalize the curve to obtain the motion path U value at each position
    for val in paramVal:
        pm.setAttr(str(arcLen) + ".uParamValue", val)
        len_at_pos = pm.getAttr(str(arcLen) + ".arcLength")
        uVal.append(len_at_pos / full_length)
    pm.delete(arcLen)
    mthPthLst = []
    jntLst = []
    # create joints, assign motion path and set U value obtained
    for u in uVal:
        pm.select(clear=True)
        jnt = pm.joint()
        jntLst.append(jnt)
        pathanim = pm.pathAnimation(jnt,
                                    curve=crv,
                                    fractionMode=True,
                                    follow=True,
                                    followAxis="x",
                                    worldUpType="vector",
                                    worldUpVector=(0, 1, 0))
        mthPthLst.append(pathanim)
        pm.setAttr(str(pathanim) + ".uValue", u)
        pm.disconnectAttr(str(pathanim) + ".u")
        # create up locator at mid point of all joints
    #loc_pos = midPos(selected_items = jntLst)
    #loc_pos = pm.xform(crv, query=True, translation=True, worldSpace=True)
    loc_pos = midPosVec(objects=jntLst)
    loc = pm.spaceLocator()
    pm.xform(loc, translation=loc_pos, worldSpace=True)
    for mtPth in mthPthLst:
        pm.pathAnimation(mtPth,
                         edit=True,
                         worldUpType="object",
                         worldUpObject=loc)
    # create control curve, add run and speed attributes
    control_crv = pm.circle(name=tread_name + "CTRL",
                            normalX=1,
                            normalY=0,
                            normalZ=0)
    pm.xform(control_crv, translation=loc_pos)
    pm.select(clear=True)
    pm.addAttr(control_crv,
               longName="run",
               attributeType="float",
               keyable=True)
    pm.addAttr(control_crv,
               longName="speed",
               attributeType="float",
               keyable=True,
               minValue=0.0,
               defaultValue=0.5)
    # group the tread setup
    pm.parent(crv, control_crv)
    pm.parent(loc, control_crv)
    pm.select(clear=True)
    gp = pm.group(name=tread_name + "GP")
    pm.select(clear=True)
    jnt_gp = pm.group(jntLst, name=tread_name + "JNTGP")
    pm.xform(gp, translation=loc_pos)
    pm.parent(control_crv, gp)
    pm.parent(jnt_gp, gp)
    createTreadExpression(mtnPth=mthPthLst,
                          runAttr=str(control_crv[0]) + ".run",
                          speedAttr=str(control_crv[0]) + ".speed",
                          exp_nm=tread_name)
    return None


#treadAtPoints(pathCrv = "nurbsCircle1", tr_name = "testTread")
Example #16
0
def split_loop():
    """
        returns individual edge loops anb verices conecting the loop
        from a selection of multiple edge loops
        
        Inputs : None
        
        Returns : (loops, verts)
                  Tuple of 2 lists, first list contains sublists, each sublists
                  contain the edge number of each each edge loops from selection,
                  second list contains sublists containing vertices of respective
                  edges from first list.
    """
    loops = []
    verts = []
    sel = pm.ls(orderedSelection=True, flatten=True)
    for edg in sel:
        if not isinstance(edg, pm.MeshEdge):
            return None
    temp_list = []
    temp_vrt_list = set()
    
    # Extract the first object from selection list to "temp_list" to be later used
    # as reference
    temp_list.append(sel.pop(0))
    
    # Run below loop until the selection list runs out of all remaining items
    while len(sel)>0:
        # Last added edge to the "temp_list" is used as reference
        ref_edg = temp_list[-1]
        # Obtain vertex from the reference edge
        ref_vert = pm.polyInfo(ref_edg, edgeToVertex = True)
        ref_vrt = re.findall("\d+", ref_vert[0])
        ref_vrt = [int(ref_vrt[1]), int(ref_vrt[2])]
        #temp_vrt_list.update(ref_vrt)#   
        shp = pm.ls(ref_edg, objectsOnly=True)
        trn = pm.listRelatives(shp, parent=True)[0]
        # Add vertes of the reference edge to "temp_vrt_list" set
        temp_vrt_list.add(str(trn+".vtx["+str(ref_vrt[0])+"]"))
        temp_vrt_list.add(str(trn+".vtx["+str(ref_vrt[1])+"]"))
        #pdb.set_trace()
        
        # Loop through all objects in selection list after removing the first item 
        # as reference
        for i in range(len(sel)):
            # Get the vertices of currernt edge compared with reference edge
            vert = pm.polyInfo(sel[i], edgeToVertex = True)
            vrt = re.findall("\d+", vert[0])
            vrt = [int(vrt[1]), int(vrt[2])]          
            
            # If the reference and current edge has matching vertices move the
            # current edge to "temp_list" 
            # (the currently moved edge becomes the reference in next iteration)
            if vrt[0] in ref_vrt or vrt[1] in ref_vrt:
                temp_list.append(sel.pop(i))
                #pdb.set_trace()
                break
            
            # If the loop has reached the end with no match, edge loop has been 
            # traversed, append the "temp_list" to "loops" and "temp_vrt_list" 
            # to "verts"
            elif i == len(sel)-1:
                loops.append(temp_list)
                verts.append(list(temp_vrt_list))
                temp_list = [sel.pop(0)]
                temp_vrt_list.clear()
                #pdb.set_trace()
                break
    
    # When selection list has run out of items, get the last appended edge
    # vertices from "temp_list" and append to "temp_vrt_list"
    if len(sel) == 0:
        ref_vert = pm.polyInfo(temp_list[-1], edgeToVertex = True)
        ref_vrt = re.findall("\d+", ref_vert[0])
        ref_vrt = [int(ref_vrt[1]), int(ref_vrt[2])]
        shp = pm.ls(temp_list[-1], objectsOnly=True)
        trn = pm.listRelatives(shp, parent=True)[0]
        temp_vrt_list.add(str(trn+".vtx["+str(ref_vrt[0])+"]"))
        temp_vrt_list.add(str(trn+".vtx["+str(ref_vrt[1])+"]"))
        #pdb.set_trace()
    
    # Append "temp_list" to "loops" and "temp_vert_list" to "verts"
    loops.append(temp_list)
    verts.append(list(temp_vrt_list))
    #pdb.set_trace()
    return loops, verts
Example #17
0
def lodOff():
    sel = pm.ls(selection=True)
    for obj in sel:
        shp = pm.listRelatives(obj, shapes=True)[0]
        shp.lodVisibility.set(0)
    return None