예제 #1
0
def convertToPointOnPolyConstraint(mesh, oldLoc, name=None, inMesh=None):
    '''
    convert surf attach transform to pointOnPoly
    '''
        
    pyMesh = pm.PyNode(mesh)
    pos = mc.xform(oldLoc, t=True, q=True, ws=True)
    
    # get UVs
    u, v = pyMesh.getUVAtPoint(pos, space='world')
    
    # delete surfAttachShape
    surfAttachShape = mc.listRelatives(oldLoc, c=True, type='cMuscleSurfAttach')[0]
    mc.delete(surfAttachShape)
    
    # constraint to mesh
    cons = mc.pointOnPolyConstraint(mesh, oldLoc)[0]
    # set UVs
    tl = mc.pointOnPolyConstraint(cons, q=True, tl=True)[0]
    # U and V aliases
    mc.setAttr(cons+'.'+tl+'U0', u)
    mc.setAttr(cons+'.'+tl+'V0', v)
    
    # swap the inMesh, if required
    if inMesh:
        mc.connectAttr(inMesh, cons+'.target[0].targetMesh', f=True)
예제 #2
0
def convertToPointOnPolyConstraint(mesh, oldLoc, name=None, inMesh=None):
    '''
    convert surf attach transform to pointOnPoly
    '''

    pyMesh = pm.PyNode(mesh)
    pos = mc.xform(oldLoc, t=True, q=True, ws=True)

    # get UVs
    u, v = pyMesh.getUVAtPoint(pos, space='world')

    # delete surfAttachShape
    surfAttachShape = mc.listRelatives(oldLoc,
                                       c=True,
                                       type='cMuscleSurfAttach')[0]
    mc.delete(surfAttachShape)

    # constraint to mesh
    cons = mc.pointOnPolyConstraint(mesh, oldLoc)[0]
    # set UVs
    tl = mc.pointOnPolyConstraint(cons, q=True, tl=True)[0]
    # U and V aliases
    mc.setAttr(cons + '.' + tl + 'U0', u)
    mc.setAttr(cons + '.' + tl + 'V0', v)

    # swap the inMesh, if required
    if inMesh:
        mc.connectAttr(inMesh, cons + '.target[0].targetMesh', f=True)
예제 #3
0
def makePointOnMesh(objectOne,objectTwo,type='follicle'):

    closestUV_point = mesh.get_closest_uv_on_mesh(objectTwo, cmds.xform(objectOne, t=True, q=True, ws=True))
    closestUV = [closestUV_point[0], closestUV_point[1]]

    if type == "pointOnPoly":
        # Create Null to attach to surface.
        anchorPoint = cmds.group(em=1,n="{}_polyAnchor".format(objectOne))
        # Create constraint between input object and mesh.
        polyConstraint = cmds.pointOnPolyConstraint(objectTwo,anchorPoint)
        
        # Set constraint UV value to closest UV value stored previously.
        cmds.setAttr( '{}.{}U0'.format(polyConstraint[0],objectTwo), closestUV[0] )

        cmds.setAttr('{}.{}V0'.format(polyConstraint[0],objectTwo), closestUV[1] )

        return anchorPoint

    elif type == "follicle":
        anchorPoint = cmds.createNode("follicle",n='{}_polyAnchorShape'.format(objectOne))

        anchorParent = cmds.listRelatives(anchorPoint,p=1)
        cmds.rename(anchorParent,str(objectOne)+"_polyAnchor")
        inputMeshShape = cmds.listRelatives(objectTwo,type="shape")
        cmds.connectAttr("{}.outMesh".format(inputMeshShape[0]), "{}.inputMesh".format(anchorPoint))
        cmds.connectAttr("{}.worldMatrix[0]".format(objectTwo),"{}.inputWorldMatrix".format(anchorPoint))
        cmds.connectAttr("{}.outRotate".format(anchorPoint),"{}.rotate".format(anchorParent[0]))
        cmds.connectAttr("{}.outTranslate".format(anchorPoint),"{}.translate".format(anchorParent[0]))
        cmds.setAttr("{}.parameterU".format(anchorPoint), closestUV[0] )
        cmds.setAttr("{}.parameterV".format(anchorPoint), closestUV[1] )
        return anchorParent
예제 #4
0
def creatConstrainPlane():
    objs=ConstrainObjs+[RefrencePlane]
    num=len(objs)
    lastObjShape=mc.listRelatives(objs[-1],s=1)[0]
    shapeType=mc.nodeType(lastObjShape)
    if num<2:
        mc.error('This command requires at least 2 arguments to be selected;  found %d.'%num)
    if shapeType != 'mesh':
        mc.error('The last selected object must be a mesh.')
    for i in range(num-1):
        BBox=mc.xform(objs[i],q=1,bb=1)
        size=(BBox[3]+BBox[4]+BBox[5]-BBox[0]-BBox[1]-BBox[2])/3
        pos=mc.xform(objs[i],q=1,ws=1,rp=1)
        rot=mc.xform(objs[i],q=1,ws=1,ro=1)
        Plane=mc.polyPlane(sx=2,sy=2,ax=[0,1,0],h=size,w=size,n=objs[i]+'_SkinPlane',ch=0)
        locator=mc.spaceLocator(p=[0,0,0],n=objs[i]+'_Loc')
        mc.hide(locator)
        Constraint=mc.pointOnPolyConstraint(Plane[0]+'.vtx[4]',locator[0])[0]
        mc.setAttr(Constraint+'.%sU0'%Plane[0],0.5)
        mc.setAttr(Constraint+'.%sV0'%Plane[0],0.5)
        mc.xform(Plane,t=pos,ro=rot)
        closestPointNode=mc.createNode("closestPointOnMesh")
        mc.connectAttr(objs[-1]+'.worldMesh[0]',closestPointNode+'.inMesh')
        mc.connectAttr(objs[-1]+'.worldMatrix[0]',closestPointNode+'.inputMatrix')
        mc.setAttr(closestPointNode+'.inPositionX',pos[0])
        mc.setAttr(closestPointNode+'.inPositionY',pos[1])
        mc.setAttr(closestPointNode+'.inPositionZ',pos[2])
        Constraint=mc.normalConstraint(objs[-1],Plane,aim=[0,1,0],u=[0,0,1])
        mc.delete(Constraint,closestPointNode)
        mc.parentConstraint(locator,objs[i],mo=1)
    if CBValue:
        ScaleConstrain()
예제 #5
0
def StickObjectToMesh(vertex, mesh):
    #***********   Get parent name ******************

    ObjectParent = cmds.listRelatives(mesh, p=True)
    #***********   Get object position ******************
    position = cmds.xform(vertex, q=True, ws=True, t=True)
    #******* Create a group driven by pointOnPolyContraint **********
    groupName = cmds.group(em=True, name=("grp_ptc_" + mesh))
    cmds.parent(groupName, ObjectParent[0])
    #******* Get the UV map relationed with the vtx **********
    mapList = cmds.polyListComponentConversion(vertex, fv=- True, tuv=True)
    #******* Create a pointOnPolyContraint **********
    contraintNames = cmds.pointOnPolyConstraint(vertex,
                                                groupName,
                                                mo=False,
                                                o=[0, 0, 0],
                                                w=1)
    #*************  Disconnect rotation  chanel  ****************************************
    mel.eval("CBdeleteConnection " + groupName + ".rotateX;")
    mel.eval("CBdeleteConnection " + groupName + ".rotateY;")
    mel.eval("CBdeleteConnection " + groupName + ".rotateZ;")
    #******* Get U and V values from map array **********
    uvvalues = cmds.polyEditUV(mapList, q=True)
    contraintAttr = cmds.listAttr(contraintNames[0], k=True)
    #******* Assign the U and V values respectively from maplist **********
    cmds.setAttr((contraintNames[0] + "." + contraintAttr[10]), uvvalues[0])
    cmds.setAttr((contraintNames[0] + "." + contraintAttr[11]), uvvalues[1])
    groupDrv = _2GrpUp(mesh)
    cmds.parent(groupDrv, groupName)
    GrpSubsTranslation(mesh)
예제 #6
0
def snapPivot(obj, tar):
    isVertex = False
    if '.vtx[' in tar:
        isVertex = True
        loc = cmds.spaceLocator()
        cmds.select(cl=1)
        cmds.select(tar)
        cmds.select(loc, add=1)
        constraint = cmds.pointOnPolyConstraint(mo=0)
        cmds.delete(constraint)
        tar = loc[0]

    objs, SAVE_LIST = utility.unParentToWorld([obj], parentChild=0, save=1, relatedObjs=[obj, tar])
    obj = objs[0]
    tar = objs[1]

    pivotT = cmds.xform(tar, q=1, ws=1, rp=1)

    obj = cmds.parent(obj, tar)

    cmds.makeIdentity(obj, a=1, t=1, r=1, s=1)
    cmds.xform(obj, ws=1, piv=pivotT)
    
    obj = cmds.parent(obj, w=1)

    # reparent
    utility.reparentToOrigin(SAVE_LIST)

    if isVertex:
        cmds.delete(tar)
    
    cmds.select(obj)
예제 #7
0
def ctrlMeshConstraint(ctrl, ctrlRef='', faceAxis='y', faceScale=0.05, prefix=''):
    """
    @param ctrl:
    @param ctrlRef:
    @param faceAxis:
    @param faceScale:
    @param prefix:
    """
    # ==========
    # - Checks -
    # ==========

    if not cmds.objExists(ctrl):
        raise Exception('Control object "' + ctrl + '" does not exist!!')
    if ctrlRef and not cmds.objExists(ctrlRef):
        raise Exception('Control reference object "' + ctrlRef + '" does not exist!!')

    # =======================
    # - Create Control Face -
    # =======================

    ctrlFace = glTools.tools.pointFaceMesh.transformFaceMesh([ctrl], faceAxis, faceScale, False, prefix)[0]

    # ============================
    # - Attach Control Reference -
    # ============================

    if ctrlRef:
        faceLoc = ctrlRef
        faceCon = cmds.pointOnPolyConstraint(ctrlFace, ctrlRef, n=prefix + '_pointOnPolyConstraint')[0]
    else:
        faceLoc = cmds.spaceLocator(n=prefix + '_ctrlFace_loc')[0]
        cmds.setAttr(faceLoc + '.localScale', faceScale, faceScale, faceScale)
        faceCon = cmds.pointOnPolyConstraint(ctrlFace, faceLoc, n=prefix + '_pointOnPolyConstraint')[0]

    cmds.setAttr(faceCon + '.' + ctrlFace + 'U0', 0.5)
    cmds.setAttr(faceCon + '.' + ctrlFace + 'V0', 0.5)

    # =================
    # - Return Result -
    # =================

    result = {}
    result['face'] = ctrlFace
    result['locator'] = faceLoc
    result['pointOnPolyConstraint'] = faceCon
    return result
예제 #8
0
 def surfCts(name, vertSets):
     '''
     jntsIks[0] = lists of 3 joint sets
     jntsIks[1] = list of ik handles, one for each three joint set
     '''
     #controllers, constraints
     geoParent = []
     j = 0
     for vSet in vertSets:
         i = 0
         setName = ["", "_aim", "_up"]
         rootCtGp = None
         aimCt = None
         upCt = None
         for point in vSet:
             if i < 3:
                 # controller
                 diamond = place.Controller(name + '_' + str(('%0' + str(2) + 'd') % (j)) + setName[i], point, False, 'diamond_ctrl', 5, 12, 8, 1, (0, 0, 1), True, True)
                 DiamondCt = diamond.createController()
                 place.cleanUp(DiamondCt[0], Ctrl=True)
                 cnst = cmds.pointOnPolyConstraint(point, DiamondCt[0])[0]
                 # convert vertex to uv
                 uv = cmds.polyListComponentConversion(point, fv=True, tuv=True)
                 # get uv space
                 space = cmds.polyEditUV(uv, q=True)
                 # set uv attrs on constraint
                 cmds.setAttr(cnst + '.' + point.rsplit('.')[0] + 'U0', space[0])
                 cmds.setAttr(cnst + '.' + point.rsplit('.')[0] + 'V0', space[1])
                 # append geoParent
                 if i == 0:
                     geoParent.append(DiamondCt[4])
                     rootCtGp = DiamondCt[1]
                 elif i == 1:
                     aimCt = DiamondCt[4]
                     cmds.setAttr(DiamondCt[0] + '.visibility', False)
                 elif i == 2:
                     upCt = DiamondCt[4]
                     cmds.setAttr(DiamondCt[0] + '.visibility', False)
                 # constraint
                 '''
                 if i==1:
                     ##ik
                     cmds.pointConstraint(DiamondCt[4], jntsIks[1][j])
                 else:
                     ##joint
                     cmds.pointConstraint(DiamondCt[4], jntsIks[0][j][i])
                     '''
             else:
                 # constrain joint to first controller of vert set list
                 cmds.parentConstraint(geoParent[j], point, mo=True)
             i = i + 1
         # aim constraint
         cmds.aimConstraint(aimCt, rootCtGp, mo=True,
                            aimVector=(0, 0, 1), upVector=(0, 1, 0),
                            worldUpType='object', worldUpObject=upCt)
         j = j + 1
     return geoParent
예제 #9
0
def addPointOnPolyNormalAttach(obj, mesh):
    from cgm.lib import (distance, nodes, attributes)
    mi_obj = cgmMeta.validateObjArg(obj, cgmMeta.cgmObject)
    mi_mesh = cgmMeta.validateObjArg(mesh, mayaType='mesh')

    #create group
    mi_attachPoint = mi_obj.doLoc()
    mc.pointOnPolyConstraint(mi_mesh.mNode,
                             mi_attachPoint.mNode,
                             maintainOffset=True)
    mc.normalConstraint(mi_mesh.mNode,
                        mi_attachPoint.mNode,
                        maintainOffset=True)

    #parent constrain
    mc.parentConstraint(mi_attachPoint.mNode,
                        mi_obj.mNode,
                        maintainOffset=True)
예제 #10
0
def ctrlMeshConstraint(ctrl,ctrlRef='',faceAxis='y',faceScale=0.05,prefix=''):
	'''
	'''
	# ==========
	# - Checks -
	# ==========

	if not mc.objExists(ctrl):
		raise Exception('Control object "'+ctrl+'" does not exist!!')
	if ctrlRef and not mc.objExists(ctrlRef):
		raise Exception('Control reference object "'+ctrlRef+'" does not exist!!')

	# =======================
	# - Create Control Face -
	# =======================

	ctrlFace = glTools.tools.pointFaceMesh.transformFaceMesh([ctrl],faceAxis,faceScale,False,prefix)[0]

	# ============================
	# - Attach Control Reference -
	# ============================

	if ctrlRef:
		faceLoc = ctrlRef
		faceCon = mc.pointOnPolyConstraint(ctrlFace,ctrlRef,n=prefix+'_pointOnPolyConstraint')[0]
	else:
		faceLoc = mc.spaceLocator(n=prefix+'_ctrlFace_loc')[0]
		mc.setAttr(faceLoc+'.localScale',faceScale,faceScale,faceScale)
		faceCon = mc.pointOnPolyConstraint(ctrlFace,faceLoc,n=prefix+'_pointOnPolyConstraint')[0]

	mc.setAttr(faceCon+'.'+ctrlFace+'U0',0.5)
	mc.setAttr(faceCon+'.'+ctrlFace+'V0',0.5)

	# =================
	# - Return Result -
	# =================

	result = {}
	result['face'] = ctrlFace
	result['locator'] = faceLoc
	result['pointOnPolyConstraint'] = faceCon
	return result
예제 #11
0
def snapTransform(obj, tar):
    if '.vtx[' in tar:
        cmds.select(cl=1)
        cmds.select(tar)
        cmds.select(obj, add=1)
        constraint = cmds.pointOnPolyConstraint(mo=0)
        cmds.delete(constraint)
    else:
        cmds.matchTransform(obj, tar)
    
    cmds.select(obj)
예제 #12
0
def placeInstance(instanceName,
                  position,
                  size,
                  face,
                  randRotation,
                  animatedParentGroup=None):
    ''' Instantiate an object and place, scale and rotate it at the desired position.

    - instanceName: name of the object to be instantiated
    - position: where to place the instance
    - size: how big should the instance be
    - face: polygon the instance is to be placed on
    - randRotation: if the instance should receive a random rotation on the local Y axis
    - animatedParentGroup: if the instance should be parented to something (required in the case of an animated base mesh) '''
    faceNormal = getNormal(face)

    psi = mc.angleBetween(euler=True,
                          v1=(0.0, 1.0, 0.0),
                          v2=(faceNormal.x, faceNormal.y, faceNormal.z))

    objectInstance = mc.instance(instanceName)

    mc.move(position[0], position[1], position[2], objectInstance)
    mc.rotate(psi[0], psi[1], psi[2], objectInstance)
    if randRotation:
        mc.rotate(0,
                  rand.uniform(-180, 180),
                  0,
                  objectInstance,
                  r=True,
                  os=True)

    mc.scale(size, size, size, objectInstance)

    if animatedParentGroup != None:
        mc.select(face, r=True)
        mc.pointOnPolyConstraint(face, animatedParentGroup, mo=False)
        mc.parent(objectInstance, animatedParentGroup)
        mc.parent(animatedParentGroup, groupName)
    else:
        mc.parent(objectInstance, groupName)
예제 #13
0
    def create_cornerpin(self, *args):
        sel = cmds.ls(sl=True)
        if sel:
            if not len(sel) == 1:
                raise RuntimeError(
                    'Selection not valid, please select one face only')
        else:
            raise RuntimeError('Selection not valid, please select a face')

        if sel[0].split('.')[1].find('f[') == -1:
            raise RuntimeError('Selection not valid, please select a face')

        #get ui data
        cam = cmds.optionMenu('camera_option', q=True, v=True)
        tag = cmds.textField('cornerpin_tag_text', q=True, text=True)

        # get vertices
        face = sel[0]
        vertices = cmds.ls(cmds.polyListComponentConversion(face,
                                                            ff=True,
                                                            tv=True),
                           flatten=True)

        # get axis
        xy_rb = cmds.radioButton('xy_radio', q=True, sl=True)
        xz_rb = cmds.radioButton('xz_radio', q=True, sl=True)
        zy_rb = cmds.radioButton('zy_radio', q=True, sl=True)
        #get cornerpin order
        cornerpin_vertex = list()
        if xy_rb:
            print 'Using XY axis'
            y_sort = sortVertex(vertices, (0, 1, 0))
            x_sort = sortVertex(vertices, (1, 0, 0))

            cornerpin_vertex = list()

            for i in y_sort[2:]:
                if i in x_sort[:2]:
                    cornerpin_vertex.append(i)

            for i in y_sort[2:]:
                if i in x_sort[2:]:
                    cornerpin_vertex.append(i)

            for i in y_sort[:2]:
                if i in x_sort[:2]:
                    cornerpin_vertex.append(i)

            for i in y_sort[:2]:
                if i in x_sort[2:]:
                    cornerpin_vertex.append(i)

        if xz_rb:
            print 'Using XY axis'
            x_sort = sortVertex(vertices, (1, 0, 0))
            z_sort = sortVertex(vertices, (0, 0, 1))

            cornerpin_vertex = list()

            for i in z_sort[:2]:
                if i in x_sort[:2]:
                    cornerpin_vertex.append(i)

            for i in z_sort[:2]:
                if i in x_sort[2:]:
                    cornerpin_vertex.append(i)

            for i in z_sort[2:]:
                if i in x_sort[:2]:
                    cornerpin_vertex.append(i)

            for i in z_sort[2:]:
                if i in x_sort[2:]:
                    cornerpin_vertex.append(i)

        elif zy_rb:
            print 'Using ZY axis'
            y_sort = sortVertex(vertices, (0, 1, 0))
            z_sort = sortVertex(vertices, (0, 0, 1))

            cornerpin_vertex = list()

            for i in y_sort[2:]:
                if i in z_sort[2:]:
                    cornerpin_vertex.append(i)

            for i in y_sort[2:]:
                if i in z_sort[:2]:
                    cornerpin_vertex.append(i)

            for i in y_sort[:2]:
                if i in z_sort[2:]:
                    cornerpin_vertex.append(i)

            for i in y_sort[:2]:
                if i in z_sort[:2]:
                    cornerpin_vertex.append(i)

        print 'Sort to cornerpin order:'
        print cornerpin_vertex

        #create cornerpin_group
        cornerpin_grp = cmds.createNode('transform',
                                        name=tag + '_cornerpin_grp')

        #create 2d locators
        for i, v in enumerate(cornerpin_vertex):
            locator_tag = tag + '_cv' + str(i + 1)
            loc = createSSLocator(tag=locator_tag, camera=cam)
            pos = cmds.xform(v, q=True, ws=True, t=True)
            m = v.split('.')[0]
            cmds.xform(loc, ws=True, t=pos)
            #calculate uv
            uv = closestUV(mesh=m, transform=loc)
            #create point on poly constraint
            pop = cmds.pointOnPolyConstraint(v, loc)[0]
            cmds.setAttr(pop + '.' + m + 'U0', uv[0])
            cmds.setAttr(pop + '.' + m + 'V0', uv[1])
            cmds.parent(loc, cornerpin_grp)
def instanceIteration(RotationRangeField, ScaleRangeEndField,
                      ScaleRangeStartField, PlacementAmountField, OffsetField,
                      WeightField, *pArgs):

    #Takes user input from the gui and stores them into variables
    XRotationRange = cmds.floatFieldGrp(RotationRangeField,
                                        query=True,
                                        value1=True)
    YRotationRange = cmds.floatFieldGrp(RotationRangeField,
                                        query=True,
                                        value2=True)
    ZRotationRange = cmds.floatFieldGrp(RotationRangeField,
                                        query=True,
                                        value3=True)
    RotationRange = [XRotationRange, YRotationRange, ZRotationRange]

    XScaleRangeEnd = cmds.floatFieldGrp(ScaleRangeEndField,
                                        query=True,
                                        value1=True)
    YScaleRangeEnd = cmds.floatFieldGrp(ScaleRangeEndField,
                                        query=True,
                                        value2=True)
    ZScaleRangeEnd = cmds.floatFieldGrp(ScaleRangeEndField,
                                        query=True,
                                        value3=True)
    ScaleRangeEnd = [XScaleRangeEnd, YScaleRangeEnd, ZScaleRangeEnd]

    XScaleRangeStart = cmds.floatFieldGrp(ScaleRangeStartField,
                                          query=True,
                                          value1=True)
    YScaleRangeStart = cmds.floatFieldGrp(ScaleRangeStartField,
                                          query=True,
                                          value2=True)
    ZScaleRangeStart = cmds.floatFieldGrp(ScaleRangeStartField,
                                          query=True,
                                          value3=True)
    ScaleRangeStart = [XScaleRangeStart, YScaleRangeStart, ZScaleRangeStart]

    PlacementAmountFactor = cmds.floatField(PlacementAmountField,
                                            query=True,
                                            value=True)

    Xoffsetamount = cmds.floatFieldGrp(OffsetField, query=True, value1=True)
    Yoffsetamount = cmds.floatFieldGrp(OffsetField, query=True, value2=True)
    Zoffsetamount = cmds.floatFieldGrp(OffsetField, query=True, value3=True)

    weightAmount = cmds.floatSliderGrp(WeightField, query=True, value=True)

    #get all the components to instance over
    #gets faces, edges and vertices
    components = cmds.filterExpand(selectionMask=(31, 34, 32))

    #get object that will be instanced
    objectlist = cmds.ls(selection=True, dagObjects=True, exactType="mesh")
    object = objectlist[0]

    #Optional parameter that randomizes component placement
    if PlacementAmountFactor != 1:
        PlacementAmount = int((len(components)) * (PlacementAmountFactor))
        components = random.sample(components, k=PlacementAmount)

    #iterate over each vertex, creating rivet and instance
    instanceGroupName = cmds.group(empty=True, name=object + "_instance_grp#")

    for component in components:
        cmds.select(deselect=True)
        currentInstance = cmds.instance(object, name=object + "_instance#")
        cmds.parent(currentInstance, instanceGroupName)
        cmds.select(component, currentInstance, add=True)
        cmds.pointOnPolyConstraint(
            component,
            currentInstance,
            offset=[Xoffsetamount, Yoffsetamount, Zoffsetamount],
            weight=weightAmount)
        # calls function to randoimize instance if requested
        instanceRandomizer(currentInstance, RotationRange, ScaleRangeEnd,
                           ScaleRangeStart, PlacementAmountFactor)
예제 #15
0
def create(name, positionList):
    '''
    This will create a bindmesh based on the give N amount of positions. 
    .. note::
        Bindmesh is a bunch of polygon plane's that are combined with rivets at the center
        of each of them.

    :param positionList: An N amount array of 3 point array's.
    :type positionList: tuple | list

    :return: The bindmesh and the follicle information 
    :trype: tuple
    '''
    # Check if the bindmesh has already been created.
    # If it exists return existing bindmesh and follicle names
    #
    newGeoName = "{0}_bindmesh".format(name)
    if mc.objExists(newGeoName):
        follicleNameList = list()
        for i in xrange(len(positionList)):
            follicleName = "{0}_{1}_follicle".format(name, i)
            follicleNameList.append(follicleName)
        return newGeoName, follicleNameList

    # define variables we will be mutating
    geoList = list()
    follicleList = list()
    pointList = list()
    # iterate through the cvList and create the plane's and follicles for each plane.
    for i, position in enumerate(positionList):
        geo, createNode = mc.polyPlane()
        for attr in ["subdivisionsHeight", "subdivisionsWidth"]:
            mc.setAttr("{0}.{1}".format(createNode, attr), 1)
        for attr in ["height", "width"]:
            mc.setAttr("{0}.{1}".format(createNode, attr), .02)
        mc.xform(geo, ws=True, t=position)
        geoList.append(geo)
        pointList.append(om.MPoint(*position))

        mc.select(cl=True)

    # combine the plane's into one piece of geometry.
    newGeo = mc.polyUnite(geoList, ch=False, n="{0}_bindmesh".format(name))[0]
    newGeoFaces = mc.ls("{0}.f[*]".format(newGeo))
    mc.polyAutoProjection(newGeoFaces,
                          ch=False,
                          lm=False,
                          pb=False,
                          ibd=True,
                          cm=False,
                          l=2,
                          sc=1,
                          o=1,
                          p=6,
                          ps=0.2,
                          ws=0)
    mc.select(newGeo, r=True)
    selList = om.MGlobal.getActiveSelectionList()
    newGeoDagPath = selList.getDagPath(0)
    newGeoFn = om.MFnMesh(newGeoDagPath)
    newGeoShape = mc.listRelatives(newGeo, c=True, shapes=True)[0]
    # iterate through the cv points and connect the follictles to the bindmesh.
    for i, point in enumerate(pointList):
        uPosition, vPosition = newGeoFn.getUVAtPoint(point)[:-1]
        follicle = mc.createNode("transform",
                                 n="{0}_{1}_follicle".format(name, i))
        constraint = mc.pointOnPolyConstraint(newGeoDagPath.fullPathName(),
                                              follicle)[0]
        u, v, id = newGeoFn.getUVAtPoint(point, om.MSpace.kWorld)
        mc.setAttr(
            "{}.{}U0".format(constraint, newGeoDagPath.partialPathName()), u)
        mc.setAttr(
            "{}.{}V0".format(constraint, newGeoDagPath.partialPathName()), v)
        follicleList.append(follicle)
    # return the bindmesh
    return newGeo, follicleList
예제 #16
0
def mit(self):
    import maya.cmds as mc
    global LocCount

    # Empty list to append the object going to be measured.
    hero = []

    # Getting the name of the selected object in the following 2 lines.
    selection = mc.ls(sl=True)
    myObjectName = selection[0]

    # Adding selected object to the "hero" list.
    hero.append(myObjectName)

    # Creating a bounding box that selected object fits perfectly
    bbox = mc.exactWorldBoundingBox(myObjectName)

    temp = mc.ls('locator_*')
    if len(temp) == 0:
        LocCount = 0

    # Items exist in the scene before this script has been runned.
    scene_before = cmds.ls(l=True, transforms=True)

    bBoxCube = mc.polyCube(n='bBoxCube_{index}'.format(index=LocCount), w=bbox[3] - bbox[0], h=bbox[4] - bbox[1],
                           d=bbox[5] - bbox[2])
    mc.xform(bBoxCube, t=((bbox[3] + bbox[0]) / 2, (bbox[4] + bbox[1]) / 2, (bbox[5] + bbox[2]) / 2))

    heroPivotX = mc.getAttr(hero[0] + '.scalePivotX')
    heroPivotY = mc.getAttr(hero[0] + '.scalePivotY')
    heroPivotZ = mc.getAttr(hero[0] + '.scalePivotZ')

    mc.move(heroPivotX, heroPivotY, heroPivotZ, "bBoxCube_{index}.scalePivot".format(index=LocCount),
            "bBoxCube_{index}.rotatePivot".format(index=LocCount), absolute=True)

    xList = []
    xListSt = []
    xListSt2 = []

    yList = []
    yListSt = []
    yListSt2 = []

    zList = []
    zListSt = []
    zListSt2 = []

    vertPos = []
    vertPosList = []

    selection = mc.ls(sl=True)
    myObjectName = selection[0]

    for i in range(0, mc.polyEvaluate(v=True)):
        vertPos = mc.pointPosition(myObjectName + '.vtx[{index}]'.format(index=i))

        vertPosList.append(vertPos)
        xListSt.append(vertPos)
        yListSt.append(vertPos)
        zListSt.append(vertPos)

        xListSt2.append(vertPos)
        yListSt2.append(vertPos)
        zListSt2.append(vertPos)

    # Genişlik: +z,-y
    xListSt.sort(key=lambda x: (x[0], -x[2], x[1]))
    xListSt2.sort(key=lambda x: (-x[2], x[1], -x[0]))

    # Yükseklik: -z,+x
    yListSt.sort(key=lambda x: (x[2], -x[0], x[1]))
    yListSt2.sort(key=lambda x: (x[2], -x[0], -x[1]))

    # Derinlik: -x,-y
    zListSt.sort(key=lambda x: (x[0], x[1], x[2]))
    zListSt2.sort(key=lambda x: (x[0], x[1], -x[2]))

    posList = [xListSt, xListSt2, yListSt, yListSt2, zListSt, zListSt2]

    mc.hide('bBoxCube_{index}'.format(index=LocCount))

    mc.scaleConstraint(hero[0], 'bBoxCube_{index}'.format(index=LocCount), mo=True, w=1)
    mc.parentConstraint(hero[0], 'bBoxCube_{index}'.format(index=LocCount), mo=True, w=1)

    for i in posList:
        LocCount += 1
        mc.spaceLocator(n='locator_#')
        mc.move(i[0][0], i[0][1], i[0][2])
        mc.select(myObjectName + '.vtx[{index}]'.format(index=vertPosList.index(i[0])))
        mc.pointOnPolyConstraint(myObjectName + '.vtx[{index}]'.format(index=vertPosList.index(i[0])),
                                 'locator_{index}'.format(index=LocCount))
        if (LocCount % 2) == 0:
            mc.distanceDimension('locator_{index}'.format(index=LocCount - 1), 'locator_{index}'.format(index=LocCount))

    # Items exist in the scene after this script has been runned.
    scene_after = cmds.ls(l=True, transforms=True)

    # Last created items/Difference between scene_before - scene_after
    new_objs = list(set(scene_after).difference(scene_before))

    mc.group(new_objs, n=hero[0] + '_Dim_01')
예제 #17
0
def meshVertexConstraint(vertex='', transform='', orient=True, prefix=''):
    """
    """
    # ==========
    # - Checks -
    # ==========

    if not prefix: prefix = 'meshVertexConstraint'

    if not vertex:
        vtxList = cmds.filterExpand(sm=31)
        if not vtxList:
            raise Exception('No mesh vertex specified for constraint!')
        vertex = vtxList[0]
    if not transform:
        transformList = cmds.ls(sl=True, type='transform')
        if not transformList:
            transformList = cmds.spaceLocator(n=prefix + '_locator')
        transform = transformList[0]

    # =================
    # - Get Vertex UV -
    # =================

    # Get Vertex Details
    mesh = cmds.ls(vertex, o=True)[0]
    vtxId = glTools.utils.component.index(vertex)

    # Get Mesh Vertex Function Set
    uArray = OpenMaya.MFloatArray()
    vArray = OpenMaya.MFloatArray()
    faceArray = OpenMaya.MIntArray()
    vtxIdUtil = OpenMaya.MScriptUtil()
    vtxIdUtil.createFromInt(0)
    vtxIdPtr = vtxIdUtil.asIntPtr()
    vtxIt = glTools.utils.mesh.getMeshVertexIter(mesh)
    vtxIt.setIndex(vtxId, vtxIdPtr)

    # Get UV Center
    uvSet = cmds.polyUVSet(mesh, q=True, cuv=True)
    vtxIt.getUVs(uArray, vArray, faceArray)
    uArray = list(uArray)
    vArray = list(vArray)
    u = uArray[0]
    v = vArray[0]

    # =====================
    # - Create Constraint -
    # =====================

    r = cmds.getAttr(transform + '.r')[0]

    meshCon = cmds.pointOnPolyConstraint(mesh,
                                         transform,
                                         n=prefix +
                                         '_pointOnPolyConstraint')[0]
    wtAlias = cmds.pointOnPolyConstraint(meshCon, q=True, wal=True)[0]
    cmds.setAttr(meshCon + '.' + wtAlias.replace('W0', 'U0'), u)
    cmds.setAttr(meshCon + '.' + wtAlias.replace('W0', 'V0'), v)

    # Orient
    if not orient:
        rxConn = cmds.listConnections(transform + '.rx',
                                      s=True,
                                      d=False,
                                      p=True)[0]
        cmds.disconnectAttr(rxConn, transform + '.rx')
        ryConn = cmds.listConnections(transform + '.ry',
                                      s=True,
                                      d=False,
                                      p=True)[0]
        cmds.disconnectAttr(ryConn, transform + '.ry')
        rzConn = cmds.listConnections(transform + '.rz',
                                      s=True,
                                      d=False,
                                      p=True)[0]
        cmds.disconnectAttr(rzConn, transform + '.rz')
        cmds.setAttr(transform + '.r', *r)

    # =================
    # - Return Result -
    # =================

    return meshCon
예제 #18
0
def meshFaceConstraint(face='', transform='', orient=True, prefix=''):
    """
    """
    # ==========
    # - Checks -
    # ==========

    if not prefix: prefix = 'meshFaceConstraint'

    if not face:
        faceList = cmds.filterExpand(sm=34)
        if not faceList:
            raise Exception('No mesh face specified for constraint!')
        face = faceList[0]
    if not transform:
        transformList = cmds.ls(sl=True, type='transform')
        if not transformList:
            transformList = cmds.spaceLocator(n=prefix + '_locator')
        transform = transformList[0]

    # ======================
    # - Get Face UV Center -
    # ======================

    # Get Face Details
    mesh = cmds.ls(face, o=True)[0]
    faceId = glTools.utils.component.index(face)

    # Get Mesh Face Function Set
    uArray = OpenMaya.MFloatArray()
    vArray = OpenMaya.MFloatArray()
    faceIdUtil = OpenMaya.MScriptUtil()
    faceIdUtil.createFromInt(0)
    faceIdPtr = faceIdUtil.asIntPtr()
    faceIt = glTools.utils.mesh.getMeshFaceIter(mesh)
    faceIt.setIndex(faceId, faceIdPtr)

    # Get UV Center
    uvSet = cmds.polyUVSet(mesh, q=True, cuv=True)
    faceIt.getUVs(uArray, vArray)
    uArray = list(uArray)
    vArray = list(vArray)
    uvCount = len(uArray)
    u = 0.0
    v = 0.0
    for i in range(uvCount):
        u += (uArray[i] / uvCount)
        v += (vArray[i] / uvCount)

    # =====================
    # - Create Constraint -
    # =====================

    r = cmds.getAttr(transform + '.r')[0]

    meshCon = cmds.pointOnPolyConstraint(mesh,
                                         transform,
                                         n=prefix +
                                         '_pointOnPolyConstraint')[0]
    wtAlias = cmds.pointOnPolyConstraint(meshCon, q=True, wal=True)[0]
    cmds.setAttr(meshCon + '.' + wtAlias.replace('W0', 'U0'), u)
    cmds.setAttr(meshCon + '.' + wtAlias.replace('W0', 'V0'), v)

    # Orient
    if not orient:
        rxConn = cmds.listConnections(transform + '.rx',
                                      s=True,
                                      d=False,
                                      p=True)[0]
        cmds.disconnectAttr(rxConn, transform + '.rx')
        ryConn = cmds.listConnections(transform + '.ry',
                                      s=True,
                                      d=False,
                                      p=True)[0]
        cmds.disconnectAttr(ryConn, transform + '.ry')
        rzConn = cmds.listConnections(transform + '.rz',
                                      s=True,
                                      d=False,
                                      p=True)[0]
        cmds.disconnectAttr(rzConn, transform + '.rz')
        cmds.setAttr(transform + '.r', *r)

    # =================
    # - Return Result -
    # =================

    return meshCon
예제 #19
0
if '.vtx' in objects[0]:
    #***********   Get parent name ******************

    ObjectParent = cmds.listRelatives(objects[1], p=True)
    #***********   Get object position ******************
    position = cmds.xform(objects[0], q=True, ws=True, t=True)
    #******* Create a group driven by pointOnPolyContraint **********
    groupName = cmds.group(em=True, name=("grp_ptc_" + objects[1]))
    cmds.parent(groupName, ObjectParent[0])
    #******* Get the UV map relationed with the vtx **********
    mapList = cmds.polyListComponentConversion(objects[0], fv=- True, tuv=True)
    #******* Create a pointOnPolyContraint **********
    contraintNames = cmds.pointOnPolyConstraint(objects[0],
                                                groupName,
                                                mo=False,
                                                o=[0, 0, 0],
                                                w=1)
    #*************  Disconnect rotation  chanel  ****************************************
    mel.eval("CBdeleteConnection " + groupName + ".rotateX;")
    mel.eval("CBdeleteConnection " + groupName + ".rotateY;")
    mel.eval("CBdeleteConnection " + groupName + ".rotateZ;")
    #******* Get U and V values from map array **********
    uvvalues = cmds.polyEditUV(mapList, q=True)
    contraintAttr = cmds.listAttr(contraintNames[0], k=True)
    #******* Assign the U and V values respectively from maplist **********
    cmds.setAttr((contraintNames[0] + "." + contraintAttr[10]), uvvalues[0])
    cmds.setAttr((contraintNames[0] + "." + contraintAttr[11]), uvvalues[1])
    groupDrv = _2GrpUp(objects[1])
    cmds.parent(groupDrv, groupName)
    GrpSubsTrans(objects[1])
예제 #20
0
def meshVertexConstraint(vertex='',transform='',orient=True,prefix=''):
	'''
	'''
	# ==========
	# - Checks -
	# ==========
	
	if not prefix: prefix = 'meshVertexConstraint'
	
	if not vertex:
		vtxList = mc.filterExpand(sm=31)
		if not vtxList: raise Exception('No mesh vertex specified for constraint!')
		vertex = vtxList[0]
	if not transform:
		transformList = mc.ls(sl=True,type='transform')
		if not transformList: transformList = mc.spaceLocator(n=prefix+'_locator')
		transform = transformList[0]
	
	# =================
	# - Get Vertex UV -
	# =================
	
	# Get Vertex Details
	mesh = mc.ls(vertex,o=True)[0]
	vtxId = glTools.utils.component.index(vertex)
	
	# Get Mesh Vertex Function Set
	uArray = OpenMaya.MFloatArray()
	vArray = OpenMaya.MFloatArray()
	faceArray = OpenMaya.MIntArray()
	vtxIdUtil = OpenMaya.MScriptUtil()
	vtxIdUtil.createFromInt(0)
	vtxIdPtr = vtxIdUtil.asIntPtr()
	vtxIt = glTools.utils.mesh.getMeshVertexIter(mesh)
	vtxIt.setIndex(vtxId,vtxIdPtr)
	
	# Get UV Center
	uvSet = mc.polyUVSet(mesh,q=True,cuv=True)
	vtxIt.getUVs(uArray,vArray,faceArray)
	uArray = list(uArray)
	vArray = list(vArray)
	u = uArray[0]
	v = vArray[0]
	
	# =====================
	# - Create Constraint -
	# =====================
	
	r = mc.getAttr(transform+'.r')[0]
	
	meshCon = mc.pointOnPolyConstraint(mesh,transform,n=prefix+'_pointOnPolyConstraint')[0]
	wtAlias = mc.pointOnPolyConstraint(meshCon,q=True,wal=True)[0]
	mc.setAttr(meshCon+'.'+wtAlias.replace('W0','U0'),u)
	mc.setAttr(meshCon+'.'+wtAlias.replace('W0','V0'),v)
	
	# Orient
	if not orient:
		rxConn = mc.listConnections(transform+'.rx',s=True,d=False,p=True)[0]
		mc.disconnectAttr(rxConn,transform+'.rx')
		ryConn = mc.listConnections(transform+'.ry',s=True,d=False,p=True)[0]
		mc.disconnectAttr(ryConn,transform+'.ry')
		rzConn = mc.listConnections(transform+'.rz',s=True,d=False,p=True)[0]
		mc.disconnectAttr(rzConn,transform+'.rz')
		mc.setAttr(transform+'.r',*r)
	
	# =================
	# - Return Result -
	# =================
	
	return meshCon
예제 #21
0
def meshFaceConstraint(face='',transform='',orient=True,prefix=''):
	'''
	'''
	# ==========
	# - Checks -
	# ==========
	
	if not prefix: prefix = 'meshFaceConstraint'
	
	if not face:
		faceList = mc.filterExpand(sm=34)
		if not faceList: raise Exception('No mesh face specified for constraint!')
		face = faceList[0]
	if not transform:
		transformList = mc.ls(sl=True,type='transform')
		if not transformList: transformList = mc.spaceLocator(n=prefix+'_locator')
		transform = transformList[0]
	
	# ======================
	# - Get Face UV Center -
	# ======================
	
	# Get Face Details
	mesh = mc.ls(face,o=True)[0]
	faceId = glTools.utils.component.index(face)
	
	# Get Mesh Face Function Set
	uArray = OpenMaya.MFloatArray()
	vArray = OpenMaya.MFloatArray()
	faceIdUtil = OpenMaya.MScriptUtil()
	faceIdUtil.createFromInt(0)
	faceIdPtr = faceIdUtil.asIntPtr()
	faceIt = glTools.utils.mesh.getMeshFaceIter(mesh)
	faceIt.setIndex(faceId,faceIdPtr)
	
	# Get UV Center
	uvSet = mc.polyUVSet(mesh,q=True,cuv=True)
	faceIt.getUVs(uArray,vArray)
	uArray = list(uArray)
	vArray = list(vArray)
	uvCount = len(uArray)
	u = 0.0
	v = 0.0
	for i in range(uvCount):
		u += (uArray[i] / uvCount)
		v += (vArray[i] / uvCount)
	
	# =====================
	# - Create Constraint -
	# =====================
	
	r = mc.getAttr(transform+'.r')[0]
	
	meshCon = mc.pointOnPolyConstraint(mesh,transform,n=prefix+'_pointOnPolyConstraint')[0]
	wtAlias = mc.pointOnPolyConstraint(meshCon,q=True,wal=True)[0]
	mc.setAttr(meshCon+'.'+wtAlias.replace('W0','U0'),u)
	mc.setAttr(meshCon+'.'+wtAlias.replace('W0','V0'),v)
	
	# Orient
	if not orient:
		rxConn = mc.listConnections(transform+'.rx',s=True,d=False,p=True)[0]
		mc.disconnectAttr(rxConn,transform+'.rx')
		ryConn = mc.listConnections(transform+'.ry',s=True,d=False,p=True)[0]
		mc.disconnectAttr(ryConn,transform+'.ry')
		rzConn = mc.listConnections(transform+'.rz',s=True,d=False,p=True)[0]
		mc.disconnectAttr(rzConn,transform+'.rz')
		mc.setAttr(transform+'.r',*r)
	
	# =================
	# - Return Result -
	# =================
	
	return meshCon