Exemplo n.º 1
0
 def checkSoftSelect(*args):
     # checks if symmetry is on
     softSelect = mc.softSelect(query=True, softSelectEnabled=True)
     # print("softSelect: {0}".format(softSelect))
     if softSelect != 0:
         mc.softSelect(softSelectEnabled=0)
     return softSelect
Exemplo n.º 2
0
def adjustDrop(newDrop, newRadius):
	global balloonDrop
	mc.softSelect(softSelectEnabled = False)
	mc.select( "balloonLattice.pt[0:1][0][0]", "balloonLattice.pt[0:1][0][1]", r = True ) 
	newDrop = (newDrop * newRadius)
	mc.move( (-1 * (newRadius + newDrop)), a = True, y = True)
	return
Exemplo n.º 3
0
    def testSoftSelection(self):
        # open maya file
        mayaFile = os.path.abspath('UsdReferenceAssemblySelectionTest.ma')
        cmds.file(mayaFile, open=True, force=True)

        # load all the assemblies
        self._LoadAll('Collapsed')

        # enable soft select with a medium radius
        OBJECT_MODE = 3
        cmds.softSelect(softSelectEnabled=1, softSelectFalloff=OBJECT_MODE,
            softSelectDistance=4.0)

        centerCube = 'Cube_49'
        neighborCube = 'Cube_48'

        neighborFullName = cmds.ls(neighborCube, long=True)[0]
        cmds.select(centerCube)

        # make sure more than 1 thing was selected
        softSel = self._GetSoftSelection()
        self.assertEqual(len(softSel), 9)
        self.assertTrue(self._ContainsAssembly(neighborFullName, softSel))

        # clear the selection
        cmds.select([])

        # set one of the things nearby and make it expanded
        cmds.assembly(neighborCube, edit=True, active='Expanded')

        # select thing again.  It should no longer include the thing that we've
        # made expanded.
        cmds.select(centerCube)
        softSel = self._GetSoftSelection()
        self.assertFalse(self._ContainsAssembly(neighborFullName, softSel))
Exemplo n.º 4
0
def makeTree(shaders):
    '''
    Creates a tree.
    
    shaders: A list of shaders for the tree crown.
    On exit: A tree has been modeled, and is returned as a tuple 
             containing the object name and the node name. Some of the
             variables are chosen randomly to create different results.
    '''
    height = random.uniform(0.3,1.5)
    trunk = cmds.polyCylinder(name = "trunk", h = height, r = 0.07)
    cmds.sets(trunk[0], edit=True, forceElement="trunkMaterialGroup")
    cmds.xform(trunk, translation = (0,height/2.0 + 0.2,0))
    crown = cmds.polySphere(name = "crown", r = 0.5)
    cmds.xform(crown, translation = (0,height + 0.6,0))
    cmds.softSelect(sse = True, ssd = 0.86)
    cmds.select(crown[0] + ".vtx[381]")
    translation = random.uniform(0.3,1.5)
    cmds.move(translation, y = True, r = True)
    cmds.softSelect(sse = False)
    shader = random.choice(shaders)
    scale_ = random.uniform(0.7,1.8)
    cmds.select(crown)
    cmds.scale(scale_, scale_, scale_, pivot = (0,height,0))
    cmds.sets(crown[0], edit=True, forceElement= shader[1])
    tree = cmds.polyUnite(trunk[0],crown[0])
    cmds.delete(tree[0], ch = True)
    return tree
def testGeoSampler():
    sel = cmd.ls(sl=True)
    if len(sel) == 0:
        raise Exception("Selezionare il piano!")
    print '--------- Selection is: ' + sel[0] + ' ---------'
    cmd.selectMode(component=True)
    cmd.select(sel[0] + '.vtx[:]')

    cmd.polyGeoSampler(cs=False, cdo=False, dg=False, ac=True, bf=False)

    vtxNumber = len(cmd.getAttr(sel[0] + '.vtx[:]'))
    # cmd.softSelect(sse=1, ssd=1)
    for i in range(0, vtxNumber):
        v = sel[0] + '.vtx[%d]' % i
        cmd.select(v, r=True)
        vColor = cmd.polyColorPerVertex(query=True, r=True, g=True, b=True)
        r = vColor[0]
        g = vColor[1]
        b = vColor[2]

        h = colorToElevation(r, g, b)
        cmd.move(h, y=True, r=True)

    cmd.softSelect(sse=0)
    cmd.selectMode(object=True)
def LoadDelta(Args):

    global adress    
    # Open dialog window to choose directory to load delta        
    folder = cmds.fileDialog2( cap='Choose directory to load Delta', fm=3, dialogStyle=1 )
    adress = folder[0]+"\\"
    pathList_cleared = []    
    targetBlendDict = {}
    named_targetBlendDict = {}
    print "Loading Delta :)"
    # Getting .bsp files from choosen folder
    pathList = os.listdir( adress )
    if len(pathList) == 0:
        print "Folder is empty"
    for element in pathList:
        if '.bsp' in element:
            pathList_cleared.append( element )
        else:
            print 'wrong type - ', element
    pathList = pathList_cleared
    
    headObj = cmds.ls( sl=True )
    object_qnty_check(headObj)
    headObject = headObj[0]
    
    step = 25
    for i in range( len(pathList) ):
        start_time = timeit.default_timer()
        named_targetBlendDict.clear()
        path_name = open( adress+pathList[i],'r' )
        DeltaDict = pickle.load( path_name )
        targetBlendDict.clear()
        new_name = pathList[i].split('.')[0]
        cmds.duplicate( headObj[0], n=headObject+'_' + new_name )
        cmds.select( headObject+'_'+new_name )
        cmds.move( step, 0, 0 )
        step += 25
        for key in compOpacities:
            weight = compOpacities.get(key)
            x =  baseVertDict[key][0] + (DeltaDict[key][0] * weight)
            y =  baseVertDict[key][1] + (DeltaDict[key][1] * weight)
            z =  baseVertDict[key][2] + (DeltaDict[key][2] * weight)
            targetBlendDict[key] = [x, y, z]
        copy_headObj = cmds.ls( sl=True )
        for head in copy_headObj:
            for i in targetBlendDict:
                 named_targetBlendDict[head+'.vtx' + str(i)] = targetBlendDict[i]
        for head in copy_headObj:
           for vert, value in named_targetBlendDict.iteritems():
               cmds.xform( vert, t=value )
        print "Loading time - ", head, ( timeit.default_timer() - start_time )
    cmds.softSelect( sse=1 )
    names = cmds.listAttr( "blendShape1", m=True, k=True )[1:]
    fullNames = []
    for i in names:
    	fullNames.append( headObj[0] + '_' + i )
    cmds.blendShape( fullNames, headObj )
    cmds.delete( fullNames )

    return adress
Exemplo n.º 7
0
def CL_Displace_noShape(height, sse=0, ssd=0):
	curves = cmd.ls(type='nurbsCurve')
	checkClosed(curves)
	checkPlanar(curves)
	checkIntersection(curves)

	sel = cmd.ls(sl=True)
	if len(sel) == 0:
		raise Exception("Selezionare il piano!")
	print '--------- Selection is: ' + sel[0] + ' ---------'

	cmd.selectMode(component=True)
	cmd.softSelect(sse=sse, ssd=ssd)
	count = 1
	for c in curves:
		vtxNumber = len(cmd.getAttr(sel[0]+'.vtx[:]'))
		for i in range(0, vtxNumber):
			v = sel[0]+'.vtx[%d]' % i
			vPosition = cmd.xform(v, query=True, translation=True, worldSpace=True)
			if testIfInsideCurve(vPosition, c, (1, 0, 0)):
				cmd.move(height, v, y=True, r=True)

		print "Terminato displacement livello " + str(count)
		count += 1

	cmd.softSelect(sse=0)
	cmd.selectMode(o=True)
	cmd.polyTriangulate(sel[0])
Exemplo n.º 8
0
def displacePointsInsideMesh(plane, mesh, height, sse, ssd):
	"""
	Select vertices of plane that are inside mesh and displace those vertices
	(with amount height)

	:param plane: object to displace
	:param mesh: shape for select vertices to displace
	:param height: height of displacement
	:param sse: enable soft selection 0 False 1 True
	:param ssd: soft select distance
	:return: None
	"""
	cmd.selectMode(component=True)
	cmd.softSelect(sse=sse, ssd=ssd)

	vtxNumber = len(cmd.getAttr(plane+'.vtx[:]'))
	for i in range(0, vtxNumber):
		v = plane+'.vtx[%d]' % i
		cmd.select(v, r=True)
		vPosition = cmd.xform(v, query=True, translation=True, worldSpace=True)
		if test_if_inside_mesh(mesh, vPosition):
			cmd.move(height, y=True, r=True)

	cmd.softSelect(sse=0)
	cmd.selectMode(o=True)
Exemplo n.º 9
0
def main():
    cmds.softSelect(sse=1, ssd=85.0, ssf=2)
    lines, dimensions = read_in_lines()
    print(dimensions)
    x = dimensions[0]
    y = dimensions[1]
    cmds.polyPlane(width=x, height=y, sx=x, sy=y)
    raise_points(lines, dimensions, 15)
Exemplo n.º 10
0
 def setDefaultFalloffCurve(self):
     """"""
     cmds.optionVar( clearArray='falloffCurveOptionVar' )
     cmds.optionVar(stringValueAppend=[ 'falloffCurveOptionVar', '0,1,2'])
     cmds.optionVar(stringValueAppend=[ 'falloffCurveOptionVar', '1,0,2'])
     cmds.gradientControlNoAttr( self.gradient, e=True, optionVar='falloffCurveOptionVar' )
     cmds.gradientControlNoAttr( self.gradient, e=True, asString='0,1,2,1,0,2' )
     cmds.softSelect(e=1, ssc='0,1,2,1,0,2')
Exemplo n.º 11
0
 def applysettings(self):
     cmds.softSelect(softSelectEnabled=self.enabled,
                     softSelectDistance=self.distance,
                     softSelectCurve=self.curve,
                     softSelectColorCurve=self.colorcurve,
                     softSelectFalloff=self.falloff,
                     enableFalseColor=self.falsecolorenabled,
                     compressUndo=self.undocompressed)
Exemplo n.º 12
0
 def setDefaultFalloffCurve(self):
     """"""
     cmds.optionVar( clearArray='falloffCurveOptionVar' )
     cmds.optionVar(stringValueAppend=[ 'falloffCurveOptionVar', '0,1,2'])
     cmds.optionVar(stringValueAppend=[ 'falloffCurveOptionVar', '1,0,2'])
     cmds.gradientControlNoAttr( self.gradient, e=True, optionVar='falloffCurveOptionVar' )
     cmds.gradientControlNoAttr( self.gradient, e=True, asString='0,1,2,1,0,2' )
     cmds.softSelect(e=1, ssc='0,1,2,1,0,2')
Exemplo n.º 13
0
def createCluster(selection_list):
    target_point_weight = {}
    for dag_path, point_weight_list in selection_list.items():
        _getConvertedData(dag_path, point_weight_list, target_point_weight)
    cmds.softSelect(e=True, sse=False)
    cmds.select(target_point_weight.keys())
    cluster_node = cmds.cluster()
    for point, weight in target_point_weight.items():
        cmds.percent(cluster_node[0], point, v=weight)
Exemplo n.º 14
0
    def value_noise(self):
        """
        This function modifies the grid by using an implementation of value Noise
        """
        logger.debug("Starting deformation with value noise")

        if not self.check_terrain():
            return

        # Disable softSelection to avoid errors in other functions
        cmds.softSelect(sse=False)

        self.noise_seed = rand(0, 1) * 10000

        logger.debug("Random seed is: {}".format(self.noise_seed))

        # List of every vertex on the object
        vertices = cmds.ls(self.gridObject + ".vtx[*]", flatten=True)

        # Multiplier to scale deformation according to the selected size.
        height_multiplier = self.gridDimensions / 100.0

        # Set the max Y value for the points.
        # Multiply by 3 because this generates smaller values than soft selection
        height_limit = self.maxHeight * height_multiplier * 3.0

        # Nested for loops to get "coordinates" of each vertex
        for x in range(0, self.gridSubdivisions + 1):
            for y in range(0, self.gridSubdivisions + 1):

                # Normalize x and y coordinates to fit range 0-1
                normalized_x = x * 1.0 / self.gridSubdivisions
                normalized_y = y * 1.0 / self.gridSubdivisions

                # Store evaluated noise from each coordinate multiplied by a scale
                # Add octaves together and return to 0 to 1 range
                value = smooth_noise(normalized_x * 4.0, normalized_y * 4.0,
                                     self.noise_seed)
                value += smooth_noise(normalized_x * 8.0, normalized_y * 8.0,
                                      self.noise_seed) * .5
                value += smooth_noise(normalized_x * 16.0, normalized_y * 16.0,
                                      self.noise_seed) * .25
                value += smooth_noise(normalized_x * 32.0, normalized_y * 32.0,
                                      self.noise_seed) * .125
                value /= (1 + .5 + .25 + .125)

                # Calculate vertex index on the object using x and y
                index = x * (self.gridSubdivisions + 1) + y

                # Move the vertex on Y with the noise value
                cmds.move(0, value * height_limit, 0, vertices[index], r=True)
Exemplo n.º 15
0
    def createStone(self):
        """ This method creates the form of stone. """

        # create a sphere
        subdivisionsX = 40
        subdivisionsY = 50
        if self.typeStone == 'small':
            size = 6.
        if self.typeStone == 'big':
            size = 9.
        self.currentStone = mc.polySphere(sx=subdivisionsX,
                                          sy=subdivisionsY,
                                          r=size)

        # change its form
        mc.scale(1, 0.5, 0.6, r=True)
        mc.move(0, size / 3.4, 0, r=True)
        stoneRY = random.randrange(0, 360)
        mc.rotate(0, stoneRY, 0, r=True, os=True)

        mc.softSelect(softSelectEnabled=True, ssd=4, sud=0.5)
        #mc.softSelect( ssd=0.6, sud=0.3 )

        for i in range(20):
            vertexNumber = random.randrange(
                0, self.totalNumberVertexSphere(subdivisionsX, subdivisionsY))
            moveX = size / 200 * random.randrange(10, 20)
            moveY = size / 200 * random.randrange(5, 20)
            moveZ = size / 200 * random.randrange(5, 20)
            mc.select(self.currentStone[0] + '.vtx[' + str(vertexNumber) + ']')
            mc.move(moveX, moveY, moveZ, r=True)

        mc.softSelect(softSelectEnabled=False)
        mc.displaySmoothness(divisionsU=3,
                             divisionsV=3,
                             pointsWire=16,
                             pointsShaded=4,
                             polygonObject=3)

        # Modify -> Freeze Transformation
        mc.select(self.currentStone[0])
        mc.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)

        # delete history
        maya.mel.eval("DeleteHistory")

        mc.select(clear=True)

        return self.currentStone[0]
Exemplo n.º 16
0
def polytocurve():
    poly = cm.ls(sl=True)
    vtxTotal = cm.polyEvaluate(v=True)
    vtxCoordList = []
    
    for i in range(0, vtxTotal, 2):
        cm.select(poly[0]+'.vtx['+str(i)+']', add=True)
        
    for i in range(1, vtxTotal, 2):
        cm.select(poly[0]+'.vtx['+str(i)+']', add=True)
    
    for i in range(1, vtxTotal, 2):
        cm.select(deselect=True)
        cm.select(poly[0]+'.vtx['+str(i)+']', add=True)
        vtxCoord = cm.xform(q=True, t=True, ws=True) 
        vtxCoordList.append(vtxCoord)
    print vtxCoordList
    cm.softSelect(sse=0)
    cm.curve(d=1, p=vtxCoordList, n='hairStrand' )      #cm.insertKnotCurve( 'hairStrand', ch=True, p=0.3, nk=2 )
def surfaceVertSelector(startElement, *args):
    count = args[0]
    #print count
    vertCount = 0
    startDist = 0
    cmds.select(startElement)

    # Find all of the verts on the selected mesh and see if they are less than count.  If they are then set count to be all verts.
    allVerts = cmds.polyEvaluate(v=True)
    #print allVerts
    if count > allVerts:
        count = allVerts
    #print args[0]
        
    # Run through the mesh and using soft select to traverse out and find verts until we reach the count value.
    while vertCount < count:
        startDist = startDist+0.1
        #print "startDist: ", startDist
        cmds.softSelect(softSelectEnabled=True, ssf=1, ssd=startDist)
        selection = om.MSelectionList()
        surfaceVertSelector = om.MRichSelection()
        om.MGlobal.getRichSelection(surfaceVertSelector)
        surfaceVertSelector.getSelection(selection)

        dagPath = om.MDagPath()
        component = om.MObject()

        iter = om.MItSelectionList( selection,om.MFn.kMeshVertComponent )
        elements = []
        while not iter.isDone():
            iter.getDagPath( dagPath, component )
            dagPath.pop()
            node = dagPath.fullPathName()
            fnComp = om.MFnSingleIndexedComponent(component)

            for i in range(fnComp.elementCount()):
                elements.append('%s.vtx[%i]' % (node, fnComp.element(i)))
            iter.next()
        vertCount = len(elements)
        #print "vertCount: ", vertCount
    cmds.softSelect(softSelectEnabled=False)
    cmds.select(elements)
Exemplo n.º 18
0
 def createStone(self):
     """ This method creates the form of stone. """
     
     # create a sphere
     subdivisionsX = 40
     subdivisionsY = 50
     if self.typeStone == 'small':
         size = 6.
     if self.typeStone == 'big':
         size = 9.
     self.currentStone = mc.polySphere(sx=subdivisionsX, sy=subdivisionsY, r=size)
     
     # change its form
     mc.scale( 1, 0.5, 0.6, r=True )
     mc.move( 0, size/3.4, 0, r=True )
     stoneRY = random.randrange ( 0, 360 )
     mc.rotate( 0, stoneRY, 0, r=True, os=True )
     
     mc.softSelect( softSelectEnabled=True, ssd=4, sud=0.5 )
     #mc.softSelect( ssd=0.6, sud=0.3 )
     
     for i in range(20):
         vertexNumber = random.randrange(0, self.totalNumberVertexSphere(subdivisionsX, subdivisionsY))
         moveX = size/200 * random.randrange ( 10, 20 )
         moveY = size/200 * random.randrange ( 5, 20 )
         moveZ = size/200 * random.randrange ( 5, 20 )
         mc.select (self.currentStone[0] + '.vtx[' + str(vertexNumber) + ']')
         mc.move( moveX, moveY, moveZ, r=True)
         
     mc.softSelect( softSelectEnabled=False )
     mc.displaySmoothness( divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3 )
     
     # Modify -> Freeze Transformation
     mc.select( self.currentStone[0] )
     mc.makeIdentity( apply=True, t=1, r=1, s=1, n=0, pn=1 )
     
     # delete history
     maya.mel.eval( "DeleteHistory" )
     
     mc.select( clear=True )
     
     return self.currentStone[0]
Exemplo n.º 19
0
 def querysettings(self, name=''):
     self.presetname = name
     self.enabled = cmds.softSelect(q=True, softSelectEnabled=True)
     self.distance = cmds.softSelect(q=True, softSelectDistance=True)
     self.curve = cmds.softSelect(q=True, softSelectCurve=True)
     self.colorcurve = cmds.softSelect(q=True, softSelectColorCurve=True)
     self.falloff = cmds.softSelect(q=True, softSelectFalloff=True)
     self.falsecolorenabled = cmds.softSelect(q=True, enableFalseColor=True)
     self.undocompressed = cmds.softSelect(q=True, compressUndo=True)
Exemplo n.º 20
0
def polytocurve():
    poly = cm.ls(sl=True)
    vtxTotal = cm.polyEvaluate(v=True)
    vtxCoordList = []

    for i in range(0, vtxTotal, 2):
        cm.select(poly[0] + '.vtx[' + str(i) + ']', add=True)

    for i in range(1, vtxTotal, 2):
        cm.select(poly[0] + '.vtx[' + str(i) + ']', add=True)

    for i in range(1, vtxTotal, 2):
        cm.select(deselect=True)
        cm.select(poly[0] + '.vtx[' + str(i) + ']', add=True)
        vtxCoord = cm.xform(q=True, t=True, ws=True)
        vtxCoordList.append(vtxCoord)
    print vtxCoordList
    cm.softSelect(sse=0)
    cm.curve(d=1, p=vtxCoordList, n='hairStrand'
             )  #cm.insertKnotCurve( 'hairStrand', ch=True, p=0.3, nk=2 )
Exemplo n.º 21
0
def softCluster():
    selectionVrts = cmds.ls(selection=True, flatten=True)
    if selectionVrts:
        posVtx = _getAverage(selectionVrts)
        cmds.softSelect(sse=True)
        softElementData = _softSelection()
        selection = ["%s.vtx[%d]" % (el[0], el[1]) for el in softElementData]
        model = selectionVrts[0].split('.')[0]
        cmds.select(model, r=True)
        cluster = cmds.cluster(name='%s_cls' % model,
                               relative=False,
                               bindState=True)
        clusterGrp = cmds.createNode('transform', name='%s_grp' % cluster[1])
        cmds.xform(cluster,
                   rotatePivot=posVtx,
                   scalePivot=posVtx,
                   objectSpace=True)
        cmds.xform(clusterGrp,
                   rotatePivot=posVtx,
                   scalePivot=posVtx,
                   objectSpace=True)
        cmds.parent(cluster[1], clusterGrp)
        cmds.connectAttr('%s.worldInverseMatrix' % clusterGrp,
                         '%s.bindPreMatrix' % cluster[0])
        weight = [0.0]
        zero = 0.0
        VertexNb = cmds.polyEvaluate(model, v=1) - 1
        for x in range(VertexNb):
            weight.append(zero)
        cmds.setAttr('{0}.weightList[0].weights[0:{1}]'.format(
            cluster[0], VertexNb),
                     *weight,
                     size=len(weight))
        shape = cmds.listRelatives(cluster[1], shapes=True)[0]
        cmds.setAttr('%s.originX' % shape, posVtx[0])
        cmds.setAttr('%s.originY' % shape, posVtx[1])
        cmds.setAttr('%s.originZ' % shape, posVtx[2])
        for i in range(len(softElementData)):
            cmds.percent(cluster[0], selection[i], v=softElementData[i][2])
        cmds.select(cluster[1], r=True)
Exemplo n.º 22
0
    def createBladeOfGrass(self):
        """ This method creates a blade of grass. """

        # random the high of blade
        self.grassHeight = 0.2 * random.randrange(6, 10)

        # create the plane of blade
        mc.polyPlane(axis=(0, 0, 0),
                     subdivisionsX=2,
                     subdivisionsY=6,
                     height=4)
        mc.move(0, 2, 0)
        self.currentBlade = mc.ls(sl=True)

        # create the form of blade
        mc.displaySmoothness(divisionsU=3,
                             divisionsV=3,
                             pointsWire=16,
                             pointsShaded=4,
                             polygonObject=3)
        mc.select(self.currentBlade[0] + ".vtx[18:20]", r=True)
        mc.softSelect(softSelectEnabled=True, ssd=20, sud=0.5)
        mc.scale(0.1, 1, 1, p=(0, 9.86, 0), r=True)
        mc.softSelect(ssd=8.08, sud=0.5)

        # bend the grass
        bendGrassRandom = 15 * (3.0 - random.random())
        mc.rotate(bendGrassRandom, 0, 0, os=True, r=True, p=(0, 9.18, 0))
        mc.select(self.currentBlade)
        extrudeFace = mc.polyExtrudeFacet(self.currentBlade[0] + ".f[0:11]",
                                          constructionHistory=1,
                                          keepFacesTogether=1,
                                          pvx=0,
                                          pvy=4.84,
                                          pvz=0.14,
                                          divisions=1,
                                          twist=0,
                                          taper=1,
                                          off=0,
                                          thickness=0,
                                          smoothingAngle=30)
        mc.setAttr(extrudeFace[0] + ".localTranslate",
                   0,
                   0,
                   0.05,
                   type='double3')
        mc.softSelect(softSelectEnabled=False)

        # scale the blade
        mc.select(self.currentBlade)
        mc.scale(1, self.grassHeight, 1, r=True)

        # delete history
        maya.mel.eval("DeleteHistory")

        # change the position
        self.changePositionBlade()

        return self.currentBlade
Exemplo n.º 23
0
    def setSoftSelectionFromSelection(self):
        """
        Get the current soft selection. If no soft selection is made a 
        RuntimeError will be raised.
        
        :raises RuntimeError: if no soft selection is made
        """
        self.ssActive, self.ssData = api.getSoftSelection()
        self.setSoftSelection.emit()

        # reset values if no soft selection
        if not self.ssData:
            self.ssActive = None
            self.ssData = {}
            self.ssSettings = {}
            raise RuntimeError("No soft selection detected!")

        self.ssSettings = {
            "ssc": cmds.softSelect(query=True, ssc=True),
            "ssf": cmds.softSelect(query=True, ssf=True),
            "ssd": cmds.softSelect(query=True, ssd=True)
        }
Exemplo n.º 24
0
    def copyFromMayaFalloffCurve(self):
        """"""
        # Read maya's native soft select falloff curve
        curveValue = cmds.softSelect(q=1, ssc=1).split(',')
        curveValue = zip(curveValue[0::3], curveValue[1::3], curveValue[2::3])
        curveValue = [','.join(v) for v in curveValue]
        
        if cmds.optionVar( exists='falloffCurveOptionVar' ):
            cmds.optionVar( clearArray='falloffCurveOptionVar' )

        [cmds.optionVar( stringValueAppend=['falloffCurveOptionVar', v] ) for v in curveValue]
        
        cmds.gradientControlNoAttr( self.gradient, e=True, optionVar='falloffCurveOptionVar' )
Exemplo n.º 25
0
def music_displace(songInfo, terrainHeight, pObject, vtxDire='n', 
                   sSelect=False, sSelectCurve=None, sSelectMode=0,
                   sSelectRadius=5, dips=False, seprAxisMv=False, 
                   reverse=False, refresh=True, queue=None):
    '''Used to gather the song values from the songInfo 'TerrainWaveFile' 
    class file and then use the values to move the 'pObjects' vertices.
    
    Parameters:
        songInfo [object]      : 'TerrainWaveFile' class object from the 
                                 'terrainWave' file.
        terrainHeight [float]  : The maximum height of the vertex movement and 
                                 the value to which all other values will 
                                 range from.
        pObject [str]          : The name of the poly object in the scene.
        vtxDire [str]          : The vertex direction to which each point will 
                                 be moved in. This can be a single or 
                                 combination of x,y,z,and n with n being 
                                 normal.
        sSelect [bool]         : If True, soft select is enabled with the 
                                 following options:
            
            sSelectCurve [str]    : The soft select falloff curve used for the 
                                    soft select.
            sSelectMode [int]     : The type of falloff mode will have. The 
                                    value used relates to the location in the 
                                    option menu in the soft select options.
            sSelectRadius [float] : The radius of the soft select area from 
                                    which points it will select from the 
                                    centre of the selection.
        
        dips [bool]            : If True, negative values from the 'songInfo' 
                                 will be used. Else, all the values created 
                                 will be positive.
        seprAxisMv [bool]      : If True, each of the axis moves ill be 
                                 seperated and not merged into one move 
                                 command. This doesn't effect the 'n' option 
                                 since this uses a different move command to 
                                 the options x, y, and z.
        reverse [bool]         : If True, the song will be reverse, starting 
                                 from the end rather than the beginning.
        
    On Exit:
        The 'pObject's vertices will be moved in relation to the song's 
        amplitude, in relation to the 'terrainHeight'.
    '''
    nVtx = cmds.polyEvaluate(pObject, v=True)
    if sSelect:
        if sSelectCurve == None:
            cmds.softSelect(sse=1,ssc=mf.SSELECT_CURVES[0], ssf=sSelectMode, 
                            ssd=sSelectRadius)
        else:
            cmds.softSelect(sse=1,ssc=sSelectCurve, ssf=sSelectMode, 
                            ssd=sSelectRadius)
    else:
        cmds.softSelect(sse=0)
    move_vtx_positions(songInfo.createheightvals(nVtx, terrainHeight, dips),
                        pObject, vtxDire, reverse, seprAxisMv, refresh, queue)
    if queue:
        queue.put('Complete')
Exemplo n.º 26
0
    def copyFromMayaFalloffCurve(self):
        """"""
        # Read maya's native soft select falloff curve
        curveValue = cmds.softSelect(q=1, ssc=1).split(',')
        curveValue = zip(curveValue[0::3], curveValue[1::3], curveValue[2::3])
        curveValue = [','.join(v) for v in curveValue]
        
        if cmds.optionVar( exists='falloffCurveOptionVar' ):
            cmds.optionVar( clearArray='falloffCurveOptionVar' )

        [cmds.optionVar( stringValueAppend=['falloffCurveOptionVar', v] ) for v in curveValue]
        
        cmds.gradientControlNoAttr( self.gradient, e=True, optionVar='falloffCurveOptionVar' )
Exemplo n.º 27
0
def create_cluster():
    cluster_name = cmds.textField('UI_cluster_clusterPrefix', q=True, tx=True) + cmds.textField('UI_cluster_clusterName', q=True, tx=True)
    cluster_name = cluster_name.replace (" ", "_")
    
# cluster soft selections
    # Use Weight Set Override
    if cmds.checkBox('UI_useWeights_CheckBox', q=True, value=True) is True:
        elements, weights = use_weight_set()
    else:
        elements, weights = softSelection()
        cmds.softSelect( sse=0)
        mel.eval("polyConvertToShell;")
    vertex_count = cmds.ls(sl=True, fl=True)


    if cmds.objExists("loc_guide_deformer") is True:
        parent_cluster(cluster_name)
    else:
        cmds.cluster (name = cluster_name, bs = True)
    for vertex in vertex_count:
        cmds.percent (cluster_name, vertex, value = 0)
    for x in range(len(elements)):
        cmds.percent (cluster_name, elements[x], value = weights[x])
Exemplo n.º 28
0
    def deform_rock(self, sphere, radius):
        """
        This function takes a sphere with its radius and deforms it.
            Parameters:
                sphere (str): The sphere that is going to be modified.
                radius (float): The radius of the sphere.
        """
        logger.debug("Deforming a rock: {}".format(sphere))

        # Random radius used for soft selection
        soft_select_radius = rand(-.1, .1) * radius

        # Smooth curve used for selection
        rock_falloff = "1,0,2,0,1,2"

        # Move random range far from 0
        # If radius was greater than 0, add 1. Else substract 1
        soft_select_radius = (soft_select_radius + 1 * radius) \
            if soft_select_radius >= 0 \
            else (soft_select_radius - 1 * radius)

        # List of every vertex on the object
        vertices = cmds.ls(sphere + ".vtx[*]", flatten=True)

        # Enable soft selection with generated radius
        cmds.softSelect(sse=True,
                        ssd=3 * abs(soft_select_radius),
                        ssc=rock_falloff)

        # Select and scale base of sphere to create planar base
        cmds.select(vertices[-2])
        cmds.scale(1, .00005 * radius, 1, pivot=(0, -1 * radius, 0), r=True)

        # Change selection radius
        cmds.softSelect(sse=True,
                        ssd=1.5 * abs(soft_select_radius),
                        ssc=rock_falloff)

        # Select and move a vertex in the middle of the sphere
        cmds.select(vertices[len(vertices) / 2])
        cmds.move(0.8 * radius, 0, 0, r=True, cs=True, ls=True, wd=True)

        # Select and move the top of the sphere
        cmds.select(vertices[-1])
        cmds.move(0.4 * radius, 0, 0, r=True, cs=True, ls=True, wd=True)

        # Disable softSelection to avoid errors in other functions
        cmds.softSelect(sse=False)

        # Move pivot down to base of the sphere
        cmds.move(0, -.95 * radius, 0, sphere + ".scalePivot", r=True)
        cmds.move(0, -.95 * radius, 0, sphere + ".rotatePivot", r=True)
Exemplo n.º 29
0
    def get_soft_selected_data(self):
        compOpacities = {}
        if not cmds.softSelect(q=True, sse=True):
            print "Soft Selection is turned off"
            return
        if not cmds.ls(sl=True):
            print 'Nothing Selected for Blend'
            return
        if cmds.objectType(cmds.ls(sl=True)[0]) != 'mesh':
            print 'Vertices Not Selected for Blend'
            return
        richSel = OpenMaya.MRichSelection()
        try:
            # get currently active soft selection
            OpenMaya.MGlobal.getRichSelection(richSel)
        except RuntimeError:
            print "Verts are not selected"
            return
        richSelList = OpenMaya.MSelectionList()
        richSel.getSelection(richSelList)
        selCount = richSelList.length()
        for x in xrange(selCount):
            shapeDag = OpenMaya.MDagPath()
            shapeComp = OpenMaya.MObject()
            try:
                richSelList.getDagPath(x, shapeDag, shapeComp)
            except RuntimeError:
                # nodes like multiplyDivides will error
                continue

            compFn = OpenMaya.MFnSingleIndexedComponent(shapeComp)
            try:
                # get the secret hidden opacity value for each component (vert, cv, etc)
                for i in xrange(compFn.elementCount()):
                    weight = compFn.weight(i)
                    compOpacities[compFn.element(i)] = weight.influence()
            except Exception, e:
                print e.__str__()
                print 'Soft selection appears invalid, skipping for shape "%s".' % shapeDag.partialPathName(
                )
def SaveSoftSelected(*Args):
    global compOpacities
    compOpacities.clear()
    global vertListCompOKeys
    global baseVertDict
    baseVertDict.clear()
    targetVertDict.clear()
    set_BS_to_0()    
    # Get dict with Soft Selected verts and their weight
    opacityMult = 1.0
    if cmds.softSelect(q=True, sse=True):
        richSel = OpenMaya.MRichSelection()
        try:
            # get currently active soft selection
            OpenMaya.MGlobal.getRichSelection(richSel)
        except RuntimeError:
            print "Verts are not selected"
            sys.exit()
        richSelList = OpenMaya.MSelectionList()
        richSel.getSelection(richSelList)
        selCount = richSelList.length()
        for x in xrange(selCount):
            shapeDag = OpenMaya.MDagPath()
            shapeComp = OpenMaya.MObject()
            try:
                richSelList.getDagPath(x, shapeDag, shapeComp)
            except RuntimeError:
	    	    # nodes like multiplyDivides will error
                continue
	    	
            compFn = OpenMaya.MFnSingleIndexedComponent(shapeComp)
            try:
                # get the secret hidden opacity value for each component (vert, cv, etc)
                for i in xrange(compFn.elementCount()):
                    weight = compFn.weight(i)
                    compOpacities['['+str(compFn.element(i))+']'] = weight.influence() * opacityMult
            except Exception, e:
                print e.__str__()
                print 'Soft selection appears invalid, skipping for shape "%s".' % shapeDag.partialPathName()
Exemplo n.º 31
0
 def makePlanIrregular(self, myGround):
     """ This method makes the plan irregular. """
     
     # set the softSelect on and give it the size range
     mc.softSelect ( softSelectEnabled=True )
     mc.softSelect ( ssd=350, sud=0.5 )
     
     for i in range(5):
         # select a random vertexes
         vertexRandom = random.randrange( 0, self.getTotalNumberVertex() )
         
         # select a random value for moving the vertex
         vertexMove = random.randrange( -30, 70 )
         
         # select the vertexes and move it
         mc.select ( myGround + '.vtx[' + str(vertexRandom) + ']', replace=True )
         mc.move ( 0, vertexMove, 0, relative=True )
     
     # set the softSelect off
     mc.softSelect ( softSelectEnabled=False )
     
     mc.select( clear=True )
Exemplo n.º 32
0
 def createBladeOfGrass(self):
     """ This method creates a blade of grass. """
     
     # random the high of blade
     self.grassHeight = 0.2 * random.randrange ( 6, 10 );
     
     # create the plane of blade
     mc.polyPlane( axis=(0, 0, 0), subdivisionsX=2, subdivisionsY=6, height=4 );
     mc.move( 0, 2, 0 )
     self.currentBlade = mc.ls( sl=True );
     
     # create the form of blade
     mc.displaySmoothness( divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3 );
     mc.select( self.currentBlade[0] + ".vtx[18:20]", r=True ) ;
     mc.softSelect( softSelectEnabled=True, ssd=20, sud=0.5 );
     mc.scale( 0.1, 1, 1, p=(0, 9.86, 0), r=True );
     mc.softSelect( ssd=8.08, sud=0.5 );
     
     # bend the grass
     bendGrassRandom = 15 * (3.0 - random.random())
     mc.rotate( bendGrassRandom, 0, 0, os=True, r=True, p=(0, 9.18, 0) );
     mc.select( self.currentBlade )
     extrudeFace = mc.polyExtrudeFacet( self.currentBlade[0] + ".f[0:11]", constructionHistory=1, keepFacesTogether=1, pvx=0, pvy=4.84, pvz=0.14, divisions=1, twist=0, taper=1, off=0, thickness=0, smoothingAngle=30 );
     mc.setAttr( extrudeFace[0] + ".localTranslate", 0, 0, 0.05, type='double3' );
     mc.softSelect( softSelectEnabled=False )
     
     # scale the blade
     mc.select( self.currentBlade )
     mc.scale( 1, self.grassHeight, 1, r=True )
     
     # delete history
     maya.mel.eval( "DeleteHistory" )
     
     # change the position
     self.changePositionBlade()
     
     return self.currentBlade
def surfaceVertSelector(startElement, *args):

    count = args[0]

    #print count

    vertCount = 0

    startDist = 0

    cmds.select(startElement)

    # Find all of the verts on the selected mesh and see if they are less than count.  If they are then set count to be all verts.

    allVerts = cmds.polyEvaluate(v=True)

    #print allVerts

    if count > allVerts:

        count = allVerts

    #print args[0]

    # Run through the mesh and using soft select to traverse out and find verts until we reach the count value.

    while vertCount < count:

        startDist = startDist + 0.1

        #print "startDist: ", startDist

        cmds.softSelect(softSelectEnabled=True, ssf=1, ssd=startDist)

        selection = om.MSelectionList()

        surfaceVertSelector = om.MRichSelection()

        om.MGlobal.getRichSelection(surfaceVertSelector)

        surfaceVertSelector.getSelection(selection)

        dagPath = om.MDagPath()

        component = om.MObject()

        iter = om.MItSelectionList(selection, om.MFn.kMeshVertComponent)

        elements = []

        while not iter.isDone():

            iter.getDagPath(dagPath, component)

            dagPath.pop()

            node = dagPath.fullPathName()

            fnComp = om.MFnSingleIndexedComponent(component)

            for i in range(fnComp.elementCount()):

                elements.append('%s.vtx[%i]' % (node, fnComp.element(i)))

            iter.next()

        vertCount = len(elements)

        #print "vertCount: ", vertCount

    cmds.softSelect(softSelectEnabled=False)

    cmds.select(elements)
Exemplo n.º 34
0
 def setDefaultFalloffMode(self):
     """"""
     cmds.optionMenuGrp(self.falloffModeOption, e=1, sl=2)
     cmds.softSelect(ssf=1)
Exemplo n.º 35
0
        def _resetDeltaSelection(base_geometry,
                                 percentage=1.0,
                                 axis='xyz',
                                 positive=False,
                                 worldSpace=False):
            """
            Reset the vertex position between a BASE mesh and a TARGET mesh based on vertex selection

            Arguments:
                base_geometry {str} -- Mesh to which the target is taking vertex position (default Mesh)

            Keyword Arguments:
                percentage {float} -- Amount of % the vertex position is blending. Between 0.0 and 1.0 (default: {1.0})
                axis {str} -- On Which axis the vertex are moving (default: {'xyz'})
                positive {bool} -- The deformation is expanding. False: The deformation is resetting towards the BASE mesh  (default: {False})
            
            #CBB: Optimization could be done, Maybe use OpenMaya.MFnMesh.setPoints() ??
            """
            if _resetDeltaSelection.isInterrupted():
                return

            selectionVtx = mc.ls(sl=1, flatten=1)
            delta_geometry = selectionVtx[0].split('.vtx')[0]
            indexVtxList = [
                int(x.split('[')[-1].split(']')[0]) for x in selectionVtx
            ]

            base_vert_positions = getAllVertexPositions(base_geometry,
                                                        worldSpace=worldSpace)
            self.delta_vert_positions = getAllVertexPositions(
                delta_geometry, worldSpace=worldSpace)

            mSLmesh = om2.MGlobal.getSelectionListByName(
                base_geometry).getDependNode(0)
            dag = om2.MFnDagNode(mSLmesh).getPath()

            vertsIter = om2.MItMeshVertex(dag)

            if mc.softSelect(q=1, sse=1):
                softSelect = self.getSoftSelection()
                softIndex = softSelect.keys()
                indexVtxList = softIndex
            else:
                softIndex = []

            newPosDelta = self.delta_vert_positions.values()[:]
            replacement = {}

            gShowProgress_step = float(100) / vertsIter.count()

            while not vertsIter.isDone():
                actual_pos = vertsIter.position(om2.MSpace.kObject)
                vrtxIndex = vertsIter.index()

                if vrtxIndex in softIndex:
                    vector = om2.MVector(
                        self.delta_vert_positions[vrtxIndex]) - om2.MVector(
                            base_vert_positions[vrtxIndex])
                    vector *= softSelect[vrtxIndex]
                    deltaV = list(
                        om2.MVector(self.delta_vert_positions[vrtxIndex]) -
                        vector)
                    replacement[vrtxIndex] = deltaV
                    # _resetDeltaSelection.step(gShowProgress_step)

                elif vrtxIndex in indexVtxList:
                    replacement[vrtxIndex] = actual_pos
                    # _resetDeltaSelection.step(gShowProgress_step)

                vertsIter.next()

            ## replace index with replacement value
            for (index, replace) in zip(replacement.keys(),
                                        replacement.values()):
                newPosDelta[index] = replace

            if percentage == 0.0:
                return

            if percentage == 1.0:
                if len(axis) > 2:
                    self.setAllVertexPositions(delta_geometry,
                                               newPosDelta,
                                               worldSpace=worldSpace)
                else:
                    if axis == 'x':
                        new_pos = []
                        for b, delta in zip(self.delta_vert_positions.values(),
                                            newPosDelta):
                            pos = (delta[0], b[1], b[2])
                            new_pos.append(pos)
                        self.setAllVertexPositions(delta_geometry,
                                                   new_pos,
                                                   worldSpace=worldSpace)

                    elif axis == 'y':
                        new_pos = []
                        for target, delta in zip(
                                self.delta_vert_positions.values(),
                                newPosDelta):
                            pos = (target[0], delta[1], target[2])
                            new_pos.append(pos)
                        self.setAllVertexPositions(delta_geometry,
                                                   new_pos,
                                                   worldSpace=worldSpace)

                    elif axis == 'z':
                        new_pos = []
                        for target, delta in zip(
                                self.delta_vert_positions.values(),
                                newPosDelta):
                            pos = (target[0], target[1], delta[2])
                            new_pos.append(pos)
                        self.setAllVertexPositions(delta_geometry,
                                                   new_pos,
                                                   worldSpace=worldSpace)
            else:
                percentage = max(min(percentage, 1.0), 0.0)
                if len(axis) > 2:
                    new_pos = []
                    for delta, base in zip(self.delta_vert_positions.values(),
                                           newPosDelta):
                        vector = om2.MVector(delta) - om2.MVector(base)
                        vector *= percentage
                        if positive:
                            deltaV = om2.MVector(delta) + vector
                        else:
                            deltaV = om2.MVector(delta) - vector
                        new_pos.append(deltaV)
                    self.setAllVertexPositions(delta_geometry,
                                               new_pos,
                                               worldSpace=worldSpace)
                else:
                    if axis == 'x':
                        new_pos = []
                        deltaV_pos = []
                        for delta, base in zip(
                                self.delta_vert_positions.values(),
                                newPosDelta):
                            vector = om2.MVector(delta) - om2.MVector(base)
                            vector *= percentage
                            if positive:
                                deltaV = om2.MVector(delta) + vector
                            else:
                                deltaV = om2.MVector(delta) - vector
                            deltaV_pos.append(deltaV)

                        for target, delta in zip(
                                self.delta_vert_positions.values(),
                                deltaV_pos):
                            pos = (delta[0], target[1], target[2])
                            new_pos.append(pos)
                        self.setAllVertexPositions(delta_geometry,
                                                   new_pos,
                                                   worldSpace=worldSpace)

                    if axis == 'y':
                        new_pos = []
                        deltaV_pos = []
                        for delta, base in zip(
                                self.delta_vert_positions.values(),
                                newPosDelta):
                            vector = om2.MVector(delta) - om2.MVector(base)
                            vector *= percentage
                            if positive:
                                deltaV = om2.MVector(delta) + vector
                            else:
                                deltaV = om2.MVector(delta) - vector
                            deltaV_pos.append(deltaV)

                        for target, delta in zip(
                                self.delta_vert_positions.values(),
                                deltaV_pos):
                            pos = (target[0], delta[1], target[2])
                            new_pos.append(pos)
                        self.setAllVertexPositions(delta_geometry,
                                                   new_pos,
                                                   worldSpace=worldSpace)

                    if axis == 'z':
                        new_pos = []
                        deltaV_pos = []
                        for delta, base in zip(
                                self.delta_vert_positions.values(),
                                newPosDelta):
                            vector = om2.MVector(delta) - om2.MVector(base)
                            vector *= percentage
                            if positive:
                                deltaV = om2.MVector(delta) + vector
                            else:
                                deltaV = om2.MVector(delta) - vector
                            deltaV_pos.append(deltaV)

                        for target, delta in zip(
                                self.delta_vert_positions.values(),
                                deltaV_pos):
                            pos = (target[0], target[1], delta[2])
                            new_pos.append(pos)
                        self.setAllVertexPositions(delta_geometry,
                                                   new_pos,
                                                   worldSpace=worldSpace)
Exemplo n.º 36
0
    def doMove(self,**kws):
	if kws:log.debug("Snap.doMove>>> kws: %s"%kws)
	if len(self.l_targets) == 1:
	    #>>> Check our target	    
	    i_target = cgmMeta.cgmNode( self.l_targets[0] )
	    log.debug("i_target: %s"%i_target)
	    targetType = i_target.getMayaType()	    

	    if self.b_snapComponents:
		components = self.i_obj.getComponents()
		if not components:raise StandardError,"This objects has no components to snap: '%s'"%self.i_obj.getShortName()
		#>>>Progress bar
		mayaMainProgressBar = gui.doStartMayaProgressBar(len(components))		
		for c in components:
		    if mc.progressBar(mayaMainProgressBar, query=True, isCancelled=True ) :
			break
		    mc.progressBar(mayaMainProgressBar, edit=True, status = ("Wrapping '%s'"%c), step=1)
		    
		    if targetType in ['mesh','nurbsSurface','nurbsCurve']:
			pos = distance.returnWorldSpacePosition(c)
			targetLoc = mc.spaceLocator()
			mc.move (pos[0],pos[1],pos[2], targetLoc[0])

			closestLoc = locators.locClosest([targetLoc[0]],i_target.mNode)
			if self._posOffset:
			    self.doOrientObjToSurface(i_target.mNode,closestLoc)
			    mc.move (self._posOffset[0],self._posOffset[1],self._posOffset[2], [closestLoc], r=True, rpr = True, os = True, wd = True)								
			position.movePointSnap(c,closestLoc)
			mc.delete([targetLoc[0],closestLoc])
			
		gui.doEndMayaProgressBar(mayaMainProgressBar)#Close out this progress bar    
		
	    else:
		pos = False
		if self.b_snaptoSurface:#>>> If our target is surface we can use
		    if targetType in ['mesh','nurbsCurve','nurbsSurface']:
			i_locObj = self.i_obj.doLoc()#Get our position loc
			i_locTarget = cgmMeta.cgmObject( locators.locClosest([i_locObj.mNode],i_target.mNode) )#Loc closest
			#i_locObj.rename('objLoc')
			#i_locTarget.rename('targetLoc')
			if self._posOffset:
			    try:
				self.doOrientObjToSurface(i_target.mNode,i_locTarget.mNode)
				mc.move (self._posOffset[0],self._posOffset[1],self._posOffset[2], [i_locTarget.mNode], r=True, rpr = True, os = True, wd = True)								
			    except StandardError,error:
				log.warn("self._posOffset failure!")
				log.error(error)
			
			pos = i_locTarget.getPosition(True)
			i_locObj.delete()
			i_locTarget.delete()
		elif self.b_midSurfacePos:
		    log.debug("Snap.move>>> midSurfacePos mode!")
		    if targetType not in ['mesh','nurbsCurve','nurbsSurface']:
			log.warning("Can't do midSurfacPos on targetType: '%s'"%targetType)
			return False
		    #Get the axis info
		    axisToCheck = kws.pop('axisToCheck',False)
		    if not axisToCheck:
			axisToCheck = []		    
			up = dictionary.returnVectorToString(self._upVector) or False
			if not up:
			    raise StandardError,"SnapFactory>>> must have up vector for midSurfaceSnap: %s"%self._upVector
			for a in ['x','y','z']:
			    if a != up[0]:
				axisToCheck.append(a)
			if not axisToCheck:
			    raise StandardError,"SnapFactory>>> couldn't find any axis to do"
		    #i_locObj = self.i_obj.doLoc()#Get our position loc		
		    #log.debug(axisToCheck)
		    pos = RayCast.findMeshMidPointFromObject(i_target.mNode, self.i_obj.mNode, axisToCheck=axisToCheck,**kws)
		    #i_locObj.delete()
		    
		else:
		    pos = i_target.getPosition(True)	    
		if pos:
		    if self.i_obj.isComponent():
			if self.b_softSelection:#Only need to do this if soft select is on
			    mc.softSelect(softSelectEnabled = True)
			    mc.select(self.i_obj.getComponent())
			    mc.move (pos[0],pos[1],pos[2],rpr=True)
			    mc.select(cl=True)
			else:
			    mc.move (pos[0],pos[1],pos[2], self.i_obj.getComponent())	    		    
		    else:
			mc.move (pos[0],pos[1],pos[2], self.i_obj.mNode, rpr=True)	    
Exemplo n.º 37
0
 def changeFalloffMode(self):
     """"""
     selIndex = cmds.optionMenuGrp(self.falloffModeOption, q=1, sl=1) - 1
     cmds.softSelect(ssf=selIndex)
def makeBarrel(*args):
    #Molding and Shaping first Plank
    cmds.polyCube( sx=8, sy=8, sz=4, h=20 )
    cmds.scale( 1, 1, 0.3 )
    cmds.select('pCube1.e[32:39]', 'pCube1.e[128:135]', 'pCube1.e[420:423]', 'pCube1.e[472:475]')
    cmds.softSelect(ssd=19, sud=0.5)
    cmds.move( 0, 0, -2, relative = True)
    cmds.softSelect(ssd=12.5, sud=0.5)
    cmds.scale(1.4,1,1)
    cmds.softSelect(ssd=5, sud=0.2)
    cmds.select('pCube1.e[56:63]', 'pCube1.e[104:111]', 'pCube1.e[432:435]', 'pCube1.e[484:487]')
    cmds.scale(1.05,1,1)
    cmds.select('pCube1.e[8:15]', 'pCube1.e[152:159]', 'pCube1.e[408:411]', 'pCube1.e[460:463]')
    cmds.scale(1.05,1,1)
    cmds.sets('pCube1', addElement = toBeGrouped)
    
    #Moving WholePlank & Duplication Process
    cmds.select('pCube1.vtx[4]')
    cmds.softSelect(ssd=500, sud=1)
    cmds.move(-cmds.pointPosition('pCube1.vtx[4]')[0], -cmds.pointPosition('pCube1.vtx[4]')[1], -cmds.pointPosition('pCube1.vtx[4]')[2], relative = True)
    cmds.move(0,0,-4, rotatePivotRelative = True, relative = True)
    cmds.select('pCube1')
    cmds.rename('pCube1', 'BarrelPlank1')
    
    i=0
    while (i < 23):
        cmds.duplicate(returnRootsOnly = True)
        cmds.rotate(0,15,0, relative = True)
        i = i+1
        
    #Creates Metal Rings With Variation
    
    #Chance of Top Four Top Rings
    i = 0 
    numbOfTopRings = rand.randint(1,4)
    openLoc = [0,0,0,0]
    while (i < numbOfTopRings):
        location = rand.randint(0,3)
        while (openLoc[location] == 1):
            location = rand.randint(0,3)
        if(location == 0):
            #0
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,19.5,0,relative = True)
            cmds.scale(4.55,45.1,4.55, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        elif(location == 1):
            #1
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,18,0,relative = True)
            cmds.scale(4.83,45.1,4.83, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        elif(location == 2):
            #2
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,16.5,0,relative = True)
            cmds.scale(5.05,60,5.05, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        else:
            #3
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,12.5,0,relative = True)
            cmds.scale(5.45,70,5.45, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.98, 0.98, 0.98, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            
        i += 1   
    
    
    
    #Guarented bottom ring then a change of two others
    #Guarented
    cmds.softSelect(ssd=5, sud=0.2)
    cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
    cmds.move(0,0.45,0,relative = True)
    cmds.scale(4.55,45.1,4.55, relative = True)
    cmds.select('pTorus1.e[120:139]')
    cmds.softSelect(ssd=1.05, sud = 0.2)
    cmds.scale(0.97, 0.97, 0.97, relative = True)
    cmds.sets('pTorus1', addElement = toBeGrouped)
    cmds.rename('pTorus1', 'MetalRing1')
    
    i = 0 
    numbOfTopRings = rand.randint(0,2)
    openLoc = [0,0]
    while (i < numbOfTopRings):
        location = rand.randint(0,1)
        while (openLoc[location] == 1):
            location = rand.randint(0,1)
        if(location == 0):
            #0
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,3.8,0,relative = True)
            cmds.scale(5.12,60,5.12, relative = True)
            cmds.select('pTorus1.e[120:139]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        else:
            #1
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,5.5,0,relative = True)
            cmds.scale(5.38,60,5.38, relative = True)
            cmds.select('pTorus1.e[120:139]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        i += 1 
    
    #Make the lid and bottom
    #Bottom
    cmds.polyCube(sx=2, sy = 1, sz = 1, h = 0.143, d = 8.07)
    cmds.sets('pCube1', addElement = toBeGrouped)
    cmds.move(0,0.143,0)
    #Create planks off of first
    i = 0
    while (i < 4):
        if(i<4):
            cmds.duplicate(returnRootsOnly = True)
            cmds.move(1.01,0,0, relative = True)
            i = i+1
            
    #Shape Planks into rounded bottom
    cmds.softSelect(sse=0)
    def shapeLidPlank(plank,scale1,scale2,scale3): #ScalesPlankEdges
        i = 0
        while (i < 2):
            selectCube = cmds.format('pCube^1s.e', stringArg=(plank))
            cmds.select("{0}[{1}]".format(selectCube,8), "{0}[{1}]".format(selectCube,11), "{0}[{1}]".format(selectCube,14), "{0}[{1}]".format(selectCube,17))
            cmds.scale(1, 1, scale1, relative = True)
            cmds.select("{0}[{1}]".format(selectCube,9), "{0}[{1}]".format(selectCube,12), "{0}[{1}]".format(selectCube,15), "{0}[{1}]".format(selectCube,18))
            cmds.scale(1, 1, scale2, relative = True)
            cmds.select("{0}[{1}]".format(selectCube,10), "{0}[{1}]".format(selectCube,13), "{0}[{1}]".format(selectCube,16), "{0}[{1}]".format(selectCube,19))
            cmds.scale(1, 1, scale3, relative = True)
            i = i+1
    
    shapeLidPlank(2,0.997351,0.98069,0.962469)
    shapeLidPlank(3,0.963,0.925,0.885)
    shapeLidPlank(4,0.8835,0.8,0.7)
    shapeLidPlank(5,0.698,0.4,0.2)
    cmds.select('pCube5.f[1]','pCube5.f[3]','pCube5.f[5]','pCube5.f[7:8]')
    cmds.delete()
    cmds.polyCloseBorder('pCube5.e[5]', 'pCube5.e[7]', 'pCube5.e[9]', 'pCube5.e[11]')
    #mirror half of the lid
    cmds.polyUnite('pCube1','pCube2','pCube3','pCube4','pCube5')
    cmds.delete(ch = True)
    cmds.polyMirrorFace( 'polySurface1', direction=0, mergeMode=1 )
    cmds.sets('polySurface1', addElement = toBeGrouped)
    cmds.rename('polySurface1', 'LidBottom')
    
    #Decide To create top & Where to Place Top
    lidOn = 0
    if(cmds.radioButtonGrp(queryDic['lidControl'], q=True, select=True)==3):
        lidOn = rand.randint(0,4)
    if(cmds.radioButtonGrp(queryDic['lidControl'], q=True, select=True)==1 or lidOn > 0):
        #createTop
        cmds.duplicate(returnRootsOnly = True)
        cmds.polyCube(w = 7.433, h = 0.13)
        cmds.move(0,0,0.973)
        cmds.select('pCube1.e[8:9]')
        cmds.scale(1.07,1,1, relative = True)
        cmds.polyMirrorFace( 'pCube1', direction = 0, mergeMode=1, axis = 2 )
        cmds.polyUnite( 'pCube1', 'LidBottom1', n='Lid' )
        cmds.sets('Lid', addElement = toBeGrouped)
        cmds.rename('Lid', 'LidTop')
        cmds.delete(ch = True)
        cmds.delete('LidBottom1')
        
        lidLocRan = 0
        if(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==4):
            lidLocRan = rand.randint(1,3)
        if(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==1 or lidLocRan==1):
            cmds.move(0,19.5,0)
        elif(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==2 or lidLocRan==2):
            cmds.move(0,19.5,0)
            cmds.rotate(0,rand.random()*359,rand.random()*16, r=True, ws = True)
            cmds.rotate(0,rand.random()*359,0, r=True, ws = True)
        elif(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==3 or lidLocRan==3):
            cmds.rotate(0,rand.random()*359, 98.852097)
            cmds.move(6.2,4.3,0)
            
            
    #Finaly Group everything in the toBeGrouped set and cleanup
    cmds.select( toBeGrouped )
    cmds.group( n='Barrel1' )
    cleanUp()
Exemplo n.º 39
0
 def selectSoftSelection(self):
     """
     Set the stored soft selection.
     """
     cmds.softSelect(sse=1, **self.ssSettings)
     OpenMaya.MGlobal.setActiveSelectionList(self.ssActive)
Exemplo n.º 40
0
    def soft_random(self):
        """
        This function modifies the grid by using Soft Selection
        """
        logger.debug("Starting deformation with soft selection")

        if not self.check_terrain():
            return

        # Multipliers to scale deformation according to the selected size.
        radius_multiplier = self.gridDimensions / 100.0
        height_multiplier = self.gridDimensions / 100.0
        points_multiplier = self.gridSubdivisions / 100.0

        # Scale the limit of the height to modify it after randomizing
        height_limit = self.maxHeight * height_multiplier / 2.0

        # List of every vertex on the object
        vertices = cmds.ls(self.gridObject + ".vtx[*]", flatten=True)

        # Number of vertices that are going to be modified.
        # We add 2 to at least modify 2 vertices
        vertices_to_edit = int(self.maxPoints * points_multiplier + 2)

        logger.debug("About to edit: {} vertices".format(vertices_to_edit))

        # Number of sections to divide the terrain
        # These sections are used to better distribute the deformed vertices
        # If there are not enough vertices, use all of them individually
        section_amount = 8 if vertices_to_edit >= 8 else vertices_to_edit

        # The size that each section should have
        section_size = len(vertices) / section_amount

        # Create a list from index i until the section is full
        # Do that from index 0 in vertices to the end of the list,
        # skipping the number of elements of the section
        vertex_sections = [
            vertices[i:i + section_size]
            for i in range(0, len(vertices), section_size)
        ]

        # Fill a list with numbers from 0 to the number of sections in that the grid is divided
        grid_indexes = [i for i in range(0, section_amount)]

        # Shuffle that so the grids are chosen in a random order
        shuffle(grid_indexes)

        # Loop with through a set number of vertices
        for v in range(vertices_to_edit):
            # Enable soft selection to move smoothly
            cmds.softSelect(sse=True,
                            ssd=self.softSelectRadius * radius_multiplier,
                            ssc=choice(self.curves))

            # Select a random vertex on the grid
            grid_index = v % section_amount

            cmds.select(choice(vertex_sections[grid_indexes[grid_index]]))

            # Randomize movement on that vertex
            random_y = rand(-height_limit, height_limit)

            # Add variation so the range doesn't start in 0
            random_y = random_y + height_limit if random_y >= 0 else random_y - height_limit

            # Apply movement
            cmds.move(0, random_y, 0, r=True)

        # Disable softSelection to avoid errors in other functions
        cmds.softSelect(sse=False)

        # Soften edges
        cmds.polySoftEdge(self.gridObject, a=180, ch=1)
Exemplo n.º 41
0
    def create_rocks(self, rocks_name, rocks_amount, mat_name, color, normal,
                     hue, brightness_range, saturation_range):
        """
        This function creates certain amount of rocks with a set name
            Parameters:
                rocks_name: The name that rocks will have
                rocks_amount: The amount of rocks that are going to be generated
                mat_name: The name for Rocks' Blinn
                color: Color map used by the Blinn
                normal: Normal map used
                hue: The hue selected for the rocks to use in the ambient color
                brightness_range: range given by the user to set the ambient color

        """
        if logger.level == logging.DEBUG:
            start_time = time.time()

        # Disable softSelection to avoid errors in other functions
        cmds.softSelect(sse=False)

        # Get a percentage of the size compared to original rock
        size_multiplier = self.gridDimensions / 100.0

        # Assign a group name based on the name selected
        rocks_group = rocks_name + "_grp"

        # Variable used in for loop to check if there is an existing terrain
        terrain_verification = 1

        # Assign material
        material = create_material(mat_name, color, normal)
        switch_node = cmds.shadingNode("tripleShadingSwitch", asUtility=True)
        cmds.connectAttr("%s.output" % switch_node,
                         "%s.ambientColor" % material)

        # Rock creation
        for i in range(rocks_amount):
            # Set new radius using the multiplier
            sphere_radius = self.sphereStartRadius * size_multiplier

            # Create sphere as base for rocks
            new_sphere = cmds.polySphere(name=rocks_name,
                                         radius=sphere_radius,
                                         subdivisionsAxis=20,
                                         subdivisionsHeight=20)

            # Deform newly created sphere
            self.deform_rock(new_sphere[0], sphere_radius)

            # Disable softSelection to avoid errors in other functions
            cmds.softSelect(sse=False)

            # Select sphere again
            cmds.select(new_sphere)

            # Variations to scale
            random_scale_x = rand(.2, 1)
            random_scale_y = random_scale_x + rand(
                -.1, .1)  # Small variations on other axes
            random_scale_z = random_scale_x + rand(
                -.1, .1)  # Small variations on other axes

            # Scale using variables
            cmds.scale(random_scale_x, random_scale_y, random_scale_z)

            # Freeze transformations
            cmds.makeIdentity(apply=True)

            # Random numbers locations based on terrain size
            random_position_x = rand(-self.gridDimensions / 2,
                                     self.gridDimensions / 2)
            random_position_z = rand(-self.gridDimensions / 2,
                                     self.gridDimensions / 2)

            # Move sphere inside range defined by terrain
            cmds.move(random_position_x, 0, random_position_z)

            # Try to snap rocks to terrain only if there is a terrain
            if terrain_verification > 0:
                try:
                    # Select actual terrain
                    cmds.select(self.gridObject, new_sphere)

                    # Constraint to Terrain's Geometry
                    cmds.geometryConstraint(weight=True)

                    # Constraint to Terrain's normals to make rocks point the right direction
                    cmds.normalConstraint(weight=True,
                                          aimVector=(0, 1, 0),
                                          upVector=(1, 0, 0),
                                          worldUpType=0)

                    # Delete constraints
                    cmds.delete(
                        cmds.listRelatives(new_sphere, children=True)[1:])

                except ValueError:
                    logger.warn(
                        "No terrain was previously created, or got deleted. Spawning rocks randomly..."
                    )
                    terrain_verification -= 1

            # Try to select the group, if its not possible, then create it
            try:
                cmds.select(new_sphere, rocks_group)
            except ValueError:
                cmds.group(name=rocks_group, empty=True)
                cmds.select(new_sphere, rocks_group)

            # Parent rocks to group and save rock's new name
            actual_rock = cmds.parent()

            # Connect shape to switch Node
            sphere_shape = cmds.listRelatives(actual_rock[0], shapes=True)[0]
            cmds.connectAttr("%s.instObjGroups[0]" % sphere_shape,
                             "%s.input[%i].inShape" % (switch_node, i))

            # Create color nodes
            random_brightness = rand(brightness_range[0], brightness_range[1])
            random_saturation = rand(saturation_range[0], saturation_range[1])
            color = colorsys.hsv_to_rgb(hue / 360.0, random_saturation,
                                        random_brightness * 1.0)
            logger.debug("HUE is {}".format(hue))
            logger.debug("Rock is having {} color".format(color))
            color_node = cmds.shadingNode("colorConstant", asUtility=True)
            cmds.setAttr("%s.inColor" % color_node,
                         color[0],
                         color[1],
                         color[2],
                         type="double3")
            cmds.connectAttr("%s.outColor" % color_node,
                             "%s.input[%i].inTriple" % (switch_node, i))

            # Assign material to rock
            cmds.select(actual_rock)
            cmds.hyperShade(assign=material)

        if logger.level == logging.DEBUG:
            logger.debug("--- ROCK CREATION took: {} ---".format(time.time() -
                                                                 start_time))
Exemplo n.º 42
0
    def __init__(self,
                 obj,
                 targets=[],
                 move=True,
                 orient=False,
                 aim=False,
                 pos=[],
                 snapToSurface=False,
                 midSurfacePos=False,
                 posOffset=False,
                 aimVector=[0, 0, 1],
                 upVector=[0, 1, 0],
                 worldUpType='scene',
                 snapComponents=False,
                 softSelection=False,
                 softSelectDistance=20,
                 mode=None,
                 **kws):
        """ 
        Asserts objects existance and that it has a transform. Then initializes. 

        Keyword arguments:
        obj(string/instance)
	targets(list) -- target objects
	
	snapToSurface -- if target is a snappable surface will try to do that
	posOffset
	snapComponents(bool) -- will try to use components if True
	aimVector(vector) -- aim vector for object
	upVector(vector) -- up vector for object (used as lathe axis for midpoint surface snap too)
	midSurfacePos(bool) -- mid point snap with a surface
	worldUpType(string) -- arg for various modes (aim, orient, etc)
	softSelection(bool) -- soft select mode for component objects only
	softSelectDistance(float) -- arg for mc.softSelect
	
	ToDo:
	1) midSurfacePos
        """
        #>>> Check our obj
        log.debug("obj: %s" % obj)
        log.debug("targets: %s" % targets)
        if issubclass(type(obj), cgmMeta.cgmNode):
            self.i_obj = obj
        else:
            i_node = cgmMeta.cgmNode(obj)
            if i_node.isComponent():
                self.i_obj = i_node
            else:
                self.i_obj = cgmMeta.cgmObject(obj)
        assert VALID.is_transform(self.i_obj.mNode) or self.i_obj.isComponent(
        ), "Not a snappable object. Not a transform: '%s" % self.i_obj.getShortName(
        )

        #>>> Pass through args
        self.b_snaptoSurface = snapToSurface
        self.b_midSurfacePos = midSurfacePos
        self.b_snapComponents = snapComponents
        self.b_softSelection = softSelection
        self.b_midSurfacePos = midSurfacePos
        self.b_aim = aim
        self._softSelectionDistance = softSelectDistance,
        self._posOffset = posOffset
        self._aimVector = aimVector
        self._upVector = upVector
        self._worldUpType = worldUpType

        #>>> Check our targets
        if targets and not type(targets) == list: targets = [targets]
        self.l_targets = []
        self.d_targetTypes = {}
        self.d_targetPositions = {}
        for t in targets:
            self.registerTarget(t)

        if not self.l_targets:
            log.error("No existing targets found")
            return

        if self.b_softSelection:
            #Should we save soft select info before changing?
            mc.softSelect(softSelectDistance=softSelectDistance)
            mc.softSelect(softSelectFalloff=0)
        log.debug("targetTypes: %s" % self.d_targetTypes)
        if move:
            log.debug("Moving")
            self.doMove(**kws)
        if orient:
            log.debug("orienting")
            self.doOrient(**kws)
        if aim:
            log.debug("orienting")
            self.doAim(**kws)
Exemplo n.º 43
0
    def doMove(self, **kws):
        if kws: log.debug("Snap.doMove>>> kws: %s" % kws)
        if len(self.l_targets) == 1:
            #>>> Check our target
            i_target = cgmMeta.cgmNode(self.l_targets[0])
            log.debug("i_target: %s" % i_target)
            targetType = i_target.getMayaType()

            if self.b_snapComponents:
                components = self.i_obj.getComponents()
                if not components:
                    raise StandardError, "This objects has no components to snap: '%s'" % self.i_obj.getShortName(
                    )
                #>>>Progress bar
                mayaMainProgressBar = gui.doStartMayaProgressBar(
                    len(components))
                for c in components:
                    if mc.progressBar(mayaMainProgressBar,
                                      query=True,
                                      isCancelled=True):
                        break
                    mc.progressBar(mayaMainProgressBar,
                                   edit=True,
                                   status=("Wrapping '%s'" % c),
                                   step=1)

                    if targetType in ['mesh', 'nurbsSurface', 'nurbsCurve']:
                        pos = distance.returnWorldSpacePosition(c)
                        targetLoc = mc.spaceLocator()
                        mc.move(pos[0], pos[1], pos[2], targetLoc[0])

                        closestLoc = locators.locClosest([targetLoc[0]],
                                                         i_target.mNode)
                        if self._posOffset:
                            self.doOrientObjToSurface(i_target.mNode,
                                                      closestLoc)
                            mc.move(self._posOffset[0],
                                    self._posOffset[1],
                                    self._posOffset[2], [closestLoc],
                                    r=True,
                                    rpr=True,
                                    os=True,
                                    wd=True)
                        position.movePointSnap(c, closestLoc)
                        mc.delete([targetLoc[0], closestLoc])

                gui.doEndMayaProgressBar(
                    mayaMainProgressBar)  #Close out this progress bar

            else:
                pos = False
                if self.b_snaptoSurface:  #>>> If our target is surface we can use
                    if targetType in ['mesh', 'nurbsCurve', 'nurbsSurface']:
                        i_locObj = self.i_obj.doLoc()  #Get our position loc
                        i_locTarget = cgmMeta.cgmObject(
                            locators.locClosest([i_locObj.mNode],
                                                i_target.mNode))  #Loc closest
                        #i_locObj.rename('objLoc')
                        #i_locTarget.rename('targetLoc')
                        if self._posOffset:
                            try:
                                self.doOrientObjToSurface(
                                    i_target.mNode, i_locTarget.mNode)
                                mc.move(self._posOffset[0],
                                        self._posOffset[1],
                                        self._posOffset[2],
                                        [i_locTarget.mNode],
                                        r=True,
                                        rpr=True,
                                        os=True,
                                        wd=True)
                            except StandardError, error:
                                log.warn("self._posOffset failure!")
                                log.error(error)

                        pos = i_locTarget.getPosition(True)
                        i_locObj.delete()
                        i_locTarget.delete()
                elif self.b_midSurfacePos:
                    log.debug("Snap.move>>> midSurfacePos mode!")
                    if targetType not in [
                            'mesh', 'nurbsCurve', 'nurbsSurface'
                    ]:
                        log.warning(
                            "Can't do midSurfacPos on targetType: '%s'" %
                            targetType)
                        return False
                    #Get the axis info
                    axisToCheck = kws.pop('axisToCheck', False)
                    if not axisToCheck:
                        axisToCheck = []
                        up = dictionary.returnVectorToString(
                            self._upVector) or False
                        if not up:
                            raise StandardError, "SnapFactory>>> must have up vector for midSurfaceSnap: %s" % self._upVector
                        for a in ['x', 'y', 'z']:
                            if a != up[0]:
                                axisToCheck.append(a)
                        if not axisToCheck:
                            raise StandardError, "SnapFactory>>> couldn't find any axis to do"
                    #i_locObj = self.i_obj.doLoc()#Get our position loc
                    #log.debug(axisToCheck)
                    pos = RayCast.findMeshMidPointFromObject(
                        i_target.mNode,
                        self.i_obj.mNode,
                        axisToCheck=axisToCheck,
                        **kws)
                    #i_locObj.delete()

                else:
                    pos = i_target.getPosition(True)
                if pos:
                    if self.i_obj.isComponent():
                        if self.b_softSelection:  #Only need to do this if soft select is on
                            mc.softSelect(softSelectEnabled=True)
                            mc.select(self.i_obj.getComponent())
                            mc.move(pos[0], pos[1], pos[2], rpr=True)
                            mc.select(cl=True)
                        else:
                            mc.move(pos[0], pos[1], pos[2],
                                    self.i_obj.getComponent())
                    else:
                        mc.move(pos[0],
                                pos[1],
                                pos[2],
                                self.i_obj.mNode,
                                rpr=True)
            compFn = OpenMaya.MFnSingleIndexedComponent(shapeComp)
            try:
                # get the secret hidden opacity value for each component (vert, cv, etc)
                for i in xrange(compFn.elementCount()):
                    weight = compFn.weight(i)
                    compOpacities['['+str(compFn.element(i))+']'] = weight.influence() * opacityMult
            except Exception, e:
                print e.__str__()
                print 'Soft selection appears invalid, skipping for shape "%s".' % shapeDag.partialPathName()
    # Load SoftSelection from file, if it is turned off
    else:
        ssd = open (cmds.fileDialog2( cap='Choose file with SoftSelected verts', fm=1, dialogStyle=1, ff='.ssd files (*.ssd)' )[0])
        compOpacities = pickle.load (ssd)
    # List of Soft Selected verts
    vertListCompOKeys = compOpacities.keys()
    cmds.softSelect(sse=0)
    # Selecting whole object 
    name = cmds.ls ( sl=True )
    if len(name) == 0:
        print "Object is not selected"
        sys.exit()
    main_name = name[0].split('.')
    cmds.select(main_name[0])

    # Get dict of Soft Selected verts and their coord    
    headObj = cmds.ls(sl=True)
    for head in headObj:
        for vert in vertListCompOKeys:
            head_vert = head + '.vtx' + str(vert)
            vertCoord = cmds.xform(head_vert, q=True, t=True)
            baseVertDict[vert] = vertCoord
m1.getPartNameBase()
m1.modulePuppet.getGeo()
targetObj = mc.ls(sl=True)[0]
distance.returnClosestPointOnSurfaceInfo(targetObj,'test_controlSurface')
distance.returnClosestUV(targetObj,'test_controlSurface')
log.info(a)
nodes.createFollicleOnMesh('spine_controlSurface','test')
locators.locMeClosestUVOnSurface(mc.ls(sl=True)[0], 'test_controlSurface', pivotOnSurfaceOnly = False)


mesh = 'Morphy_Body_GEO'
i_obj = cgmMeta.cgmObject('hips_anim')
mControlFactory.returnBaseControlSize(i_obj, mesh,axis = ['x','y','z-'])
mControlFactory.returnBaseControlSize(i_obj, mesh,axis = ['z-'])

mc.softSelect(softSelectEnabled = True)
mc.softSelect(q = True, softSelectDistance = True)
mc.softSelect(q = True, softSelectUVDistance = True)
mc.softSelect(q = True, softSelectFalloff = 2)
mc.softSelect(softSelectFalloff = 0)
mc.softSelect(softSelectDistance = 20)
mc.softSelect(softSelectUVDistance = 30)



#252ms
m1.isSkeletonized()
mControlFactory.go(obj)
m1.setState('skeleton')
tFactory.returnModuleBaseSize(m2)
m2.rigNull.skinJoints
Exemplo n.º 46
0
 def changeSoftSelectValue(self):
     curveValue = cmds.gradientControlNoAttr(self.gradient, q=1, asString=1)
     cmds.softSelect(e=1, ssc=curveValue)
Exemplo n.º 47
0
 def changeSoftSelectValue(self):
     curveValue = cmds.gradientControlNoAttr(self.gradient, q=1, asString=1)
     cmds.softSelect(e=1, ssc=curveValue)
Exemplo n.º 48
0
 def setDefaultFalloffMode(self):
     """"""
     cmds.optionMenuGrp(self.falloffModeOption, e=1, sl=2)
     cmds.softSelect(ssf=1)
Exemplo n.º 49
0
 def changeFalloffMode(self):
     """"""
     selIndex = cmds.optionMenuGrp(self.falloffModeOption, q=1, sl=1) - 1
     cmds.softSelect(ssf=selIndex)
Exemplo n.º 50
0
    def __init__(self,obj,targets = [],move = True, orient = False, aim = False, pos = [],
                 snapToSurface = False, midSurfacePos = False,
                 posOffset = False,
                 aimVector = [0,0,1],upVector = [0,1,0], worldUpType = 'scene',
                 snapComponents = False,softSelection = False, softSelectDistance = 20,                 
                 mode = None,**kws):
        """ 
        Asserts objects existance and that it has a transform. Then initializes. 

        Keyword arguments:
        obj(string/instance)
	targets(list) -- target objects
	
	snapToSurface -- if target is a snappable surface will try to do that
	posOffset
	snapComponents(bool) -- will try to use components if True
	aimVector(vector) -- aim vector for object
	upVector(vector) -- up vector for object (used as lathe axis for midpoint surface snap too)
	midSurfacePos(bool) -- mid point snap with a surface
	worldUpType(string) -- arg for various modes (aim, orient, etc)
	softSelection(bool) -- soft select mode for component objects only
	softSelectDistance(float) -- arg for mc.softSelect
	
	ToDo:
	1) midSurfacePos
        """
	#>>> Check our obj
	log.debug("obj: %s"%obj)
	log.debug("targets: %s"%targets)
	if issubclass(type(obj),cgmMeta.cgmNode):
	    self.i_obj = obj
	else:
	    i_node = cgmMeta.cgmNode(obj)
	    if i_node.isComponent():
		self.i_obj = i_node		
	    else :
		self.i_obj = cgmMeta.cgmObject(obj)
	assert self.i_obj.isTransform() or self.i_obj.isComponent(),"Not a snappable object. Not a transform: '%s"%self.i_obj.getShortName()      
	
	#>>> Pass through args
	self.b_snaptoSurface = snapToSurface
	self.b_midSurfacePos = midSurfacePos	
	self.b_snapComponents = snapComponents
	self.b_softSelection = softSelection
	self.b_midSurfacePos = midSurfacePos
	self.b_aim = aim		
	self._softSelectionDistance = softSelectDistance,
	self._posOffset = posOffset
	self._aimVector = aimVector
	self._upVector = upVector
	self._worldUpType = worldUpType
	
	#>>> Check our targets
	if targets and not type(targets)==list:targets=[targets]
	self.l_targets = []	
	self.d_targetTypes = {}
	self.d_targetPositions = {}
	for t in targets:
	    self.registerTarget(t)
	    
	if not self.l_targets:
	    log.error("No existing targets found")
	    return
	
	if self.b_softSelection:
	    #Should we save soft select info before changing?
	    mc.softSelect(softSelectDistance = softSelectDistance)
	    mc.softSelect(softSelectFalloff = 0)	    
	log.debug("targetTypes: %s"%self.d_targetTypes)
	if move:
	    log.debug("Moving")
	    self.doMove(**kws)
	if orient:
	    log.debug("orienting")
	    self.doOrient(**kws)
	if aim:
	    log.debug("orienting")
	    self.doAim(**kws)	    
Exemplo n.º 51
0
log.debug(info)
info['processedHits'].get(111)
mShapeCast.limbControlMaker(m1, ['segmentControlsNew', 'hips'])
mShapeCast.limbControlMaker(m1, ['fkSegmentControls', 'ikSegmentControls'])

mShapeCast.limbControlMaker(m1, ['segmentControls', 'hips', 'cog'])

mShapeCast.limbControlMaker(m1, ['segmentControls', 'hips', 'cog'])
mShapeCast.limbControlMaker(m1, ['segmentControlsNEW'])

mesh = 'Morphy_Body_GEO1'
i_obj = cgmMeta.cgmObject('pelvis_templateOrientHelper')
mShapeCast.returnBaseControlSize(i_obj, mesh, axis=['x', 'y', 'z-'])
mShapeCast.returnBaseControlSize(i_obj, mesh, axis=['x'])

mc.softSelect(softSelectEnabled=True)
mc.softSelect(q=True, softSelectDistance=True)
mc.softSelect(q=True, softSelectUVDistance=True)
mc.softSelect(q=True, softSelectFalloff=2)
mc.softSelect(softSelectFalloff=0)
mc.softSelect(softSelectDistance=20)
mc.softSelect(softSelectUVDistance=30)

#252ms
m1.isSkeletonized()
mShapeCast.go(obj)
m1.setState('skeleton')
tFactory.returnModuleBaseSize(m2)
m2.rigNull.skinJoints
m2.moduleParent.rigNull.skinJoints
m2.templateNull.controlObjects