Beispiel #1
0
    def create(self):
        #checking if shader exists
        shadExist = 0
        allShaders = cmds.ls(mat=1)
        for shadeCheck in allShaders:
            if (shadeCheck == self.name):
                shadExist = 1

        if (shadExist == 0):
            cmds.sets(renderable=True,
                      noSurfaceShader=True,
                      empty=True,
                      name=self.name + "SG")
            cmds.shadingNode(self.type, asShader=True, name=self.name)
            # 0.0, 0.8, 1.0 color
            cmds.setAttr(self.name + ".color",
                         self.color[0],
                         self.color[1],
                         self.color[2],
                         type='double3')
            #transparency between 0.8 - 0.9 is good
            cmds.setAttr(self.name + ".transparency",
                         self.trans[0],
                         self.trans[1],
                         self.trans[2],
                         type="double3")
            cmds.setAttr(self.name + ".specularColor",
                         self.specClr[0],
                         self.specClr[1],
                         self.specClr[2],
                         type='double3')
            cmds.connectAttr(self.name + ".outColor",
                             self.name + "SG.surfaceShader",
                             f=True)
Beispiel #2
0
 def _handleRoadButton(self):
     exist = cmds.ls('road')
     if(len(exist) != 0):
         cmds.delete('road')
     road=cmds.group(empty=True, name='road')
     transformName = cmds.ls('brick', typ='transform')[0]
     num = int(self.bricksNum.text())
     for i in range(0, num):
         instanceResult = cmds.instance(transformName, name=transformName + '_instance#')
         #print 'instanceResult: ' + str(instanceResult)
         x = random.uniform(-3, 34)
         z = random.uniform(-3,3)
         cmds.move(x, 0, z, instanceResult)
         yRot = random.uniform(0,360)
         cmds.rotate(0, yRot, 0, instanceResult)
         cmds.parent(instanceResult, road)
    def create(self):
        #checking if shader exists
        shadExist = 0
        allShaders = cmds.ls(mat=1)
        for shadeCheck in allShaders:
            if (shadeCheck == self.name + '1'):
                shadExist = 1

        if (shadExist == 0):

            cmds.sets(renderable=True,
                      noSurfaceShader=True,
                      empty=True,
                      name=self.name)
            cmds.shadingNode('mia_material_x', asShader=True, name=self.name)

            self.name = self.name + '1'

            cmds.setAttr(self.name + ".diffuse", self.diffuse[0],
                         self.diffuse[1], self.diffuse[2])
            cmds.setAttr(self.name + ".refl_color", self.refl_color[0],
                         self.refl_color[1], self.refl_color[2])
            cmds.setAttr(self.name + ".transparency", self.trans)
            cmds.setAttr(self.name + ".refr_color", self.refr_color[0],
                         self.refr_color[1], self.refr_color[2])
            cmds.setAttr(self.name + ".refr_trans_color",
                         self.refr_trans_color[0], self.refr_trans_color[1],
                         self.refr_trans_color[2])
            cmds.setAttr(self.name + ".refl_gloss", self.refl_gloss)
            cmds.setAttr(self.name + ".refr_gloss", self.refr_gloss)
            cmds.setAttr(self.name + ".refr_ior", self.refr_ior)
            cmds.setAttr(self.name + ".refr_trans_weight",
                         self.refr_trans_weight)
Beispiel #4
0
def spawnAliens(num_aliens):
    #----------------------Generate X-amount of aliens-------------------
    #---make gravity field if it doesn't already exist
    gravName = cmds.ls( 'alienGrav*' )
    print gravName
    if gravName == []:
        print "make grav"
        cmds.gravity(n="alienGrav", pos = (0, 0, 0), m=980, att=0, dx=0, dy=-1, dz=0, mxd=-1, vsh="none", vex=0, vof=(0, 0, 0), vsw=360, tsr=0.5)

    for i in range(0, num_aliens):

        #Give each a unique name
        curName = "alien"
        curName = curName+str(i)
        cmds.duplicate('alien', n=curName)

        #---Place in random location
        cmds.setAttr(curName+".translateX", random.randrange(-MAX_DIST, MAX_DIST))
        cmds.setAttr(curName+".translateY", 200)
        cmds.setAttr(curName+".translateZ", random.randrange(-MAX_DIST, MAX_DIST))

        #Random orientation
        cmds.setAttr(curName+".rotateX", random.randrange(360))
        cmds.setAttr(curName+".rotateY", random.randrange(360))
        cmds.setAttr(curName+".rotateZ", random.randrange(360))

        #Connect up to gravity
        cmds.connectDynamic(curName, f="alienGrav")
    #Connect up to gravity
    cmds.connectDynamic("alien", f="alienGrav")
    def _handlePerturb(self):
        """
        This perturbs the selected object.

        """

        selectedObjects = cmds.ls(selection=True, long=True)

        vertsList = []
        for object in selectedObjects:
            totalVerts = cmds.polyEvaluate(object, vertex=True)

            for number in range(totalVerts):
                vertsList.append(object +
                                 '.vtx[{number}]'.format(number=number))

        for vert in vertsList:
            min = float(self.minInput.displayText())
            max = float(self.maxInput.displayText())
            randNumX = random.uniform(min, max)
            randNumY = random.uniform(min, max)
            randNumZ = random.uniform(min, max)
            cmds.select(vert, replace=True)
            cmds.move(randNumX, randNumY, randNumZ, relative=True)
            cmds.select(selectedObjects, replace=True)
Beispiel #6
0
    def getTrackSetNode(cls):
        """ Get the TrackSet from the Maya scene so we can map from UID to track
            nodes """

        for node in cmds.ls(exactType='objectSet'):
            if node == CadenceConfigs.TRACKWAY_SET_NODE_NAME:
                return node
        return None
 def get_ball_from_current_selection(self):
     selection = cmds.ls(selection=True)
     ball = ''
     for item in selection:
         match = re.search("(ball.*)\|*?", item)
         if match:
             ball = match.group(1)
     return ball
Beispiel #8
0
    def setAllLayersVisible(self, visible):
        """ This sets all layers visible, as the name suggests. """

        layers = cmds.ls( type='displayLayer')

        for layer in layers:
            if layer.endswith(self.LAYER_SUFFIX):
                cmds.setAttr('%s.visibility' % layer, visible)
Beispiel #9
0
    def _generateTerrain(self):
        cmds.polyPlane(n='terrain',
                       sx=self.size - 1,
                       sy=self.size - 1,
                       w=self.size,
                       h=self.size)
        shapes = cmds.ls("terrain", sl=True, fl=True)
        self.terrain = shapes[0]

        offset_magnitude = int(self.magnitude)
        self.setVertexHeight((0, 0),
                             randint(-offset_magnitude, offset_magnitude))
        self.setVertexHeight((self.size - 1, 0),
                             randint(-offset_magnitude, offset_magnitude))
        self.setVertexHeight((0, self.size - 1),
                             randint(-offset_magnitude, offset_magnitude))
        self.setVertexHeight((self.size - 1, self.size - 1),
                             randint(-offset_magnitude, offset_magnitude))

        length = self.size - 1
        while length >= 1:
            half_length = length / 2
            for x in range(0, self.size - 1, length):
                for y in range(0, self.size - 1, length):
                    bottom_left = self.getVertexHeight((x, y))
                    bottom_right = self.getVertexHeight((x + length, y))
                    top_left = self.getVertexHeight((x, y + length))
                    top_right = self.getVertexHeight((x + length, y + length))
                    average = (top_left + top_right + bottom_left +
                               bottom_right) / 4.0
                    offset = randint(int(-offset_magnitude),
                                     int(offset_magnitude))
                    point = (x + half_length, y + half_length)
                    flat_index = self.getFlatIndex(point)
                    if 0 <= flat_index <= self.size * self.size:
                        self.setVertexHeight(point, average + offset)

            for x in range(0, self.size - 1, half_length):
                for y in range((x + half_length) % length, self.size - 1,
                               length):
                    left = self.getVertexHeight(
                        ((x - half_length + self.size) % self.size, y))
                    right = self.getVertexHeight(
                        ((x + half_length) % self.size, y))
                    top = self.getVertexHeight(
                        (x, (y + half_length + self.size) % self.size))
                    bottom = self.getVertexHeight(
                        (x, (y - half_length) % self.size))
                    average = (left + right + top + bottom) / 4
                    offset = randint(int(-offset_magnitude),
                                     int(offset_magnitude))
                    point = (x, y)
                    flat_index = self.getFlatIndex(point)
                    if 0 <= flat_index <= self.size * self.size:
                        self.setVertexHeight((x, y), average + offset)
            offset_magnitude /= 2.0
            length /= 2
        print "DONE!"
Beispiel #10
0
    def createShaders(self):
        shader, shaderEngine = self.createShader('HindPrint_Blinn')
        cmds.setAttr(shader + '.color', 0.618, 0.551421, 0.368328, type='double3')
        cmds.select(
            cmds.ls(self.group + '|left_hind_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        cmds.select(
            cmds.ls(self.group + '|right_hind_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('ForePrint_Blinn')
        cmds.setAttr(shader + '.color', 0.309, 0.8618, 1.0, type='double3')
        cmds.select(
            cmds.ls(self.group + '|left_fore_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        cmds.select(
            cmds.ls(self.group + '|right_fore_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('HindFoot_Blinn')
        cmds.setAttr(shader + '.color', 0.792, 0.383566, 0.338184, type='double3')
        cmds.select([self.leftHind, self.rightHind])
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('ForeFoot_Blinn')
        cmds.setAttr(shader + '.color', 0.287, 0.762333, 1.0, type='double3')
        cmds.select([self.leftFore, self.rightFore])
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('Hips_Blinn')
        cmds.setAttr(shader + '.color', 1.0, 0.376, 0.376, type='double3')
        cmds.select([self.hips])
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('Pecs_Blinn')
        cmds.setAttr(shader + '.color', 0.629483, 1.0, 0.483, type='double3')
        cmds.select([self.pecs])
        cmds.sets(forceElement=shaderEngine)
Beispiel #11
0
    def getTrackSetNode(cls, createIfMissing =False):
        for node in cmds.ls(exactType='objectSet'):
            if node == CadenceConfigs.TRACKWAY_SET_NODE_NAME:
                return node

        if createIfMissing:
            return cmds.sets(
                name=CadenceConfigs.TRACKWAY_SET_NODE_NAME, empty=True)

        return None
def findName(nameish):

    objs = mc.ls()
    bodyName = ""
    for nm in objs:
        if nameish in nm:
            bodyName = nm
            break
    print(bodyName)
    return bodyName
Beispiel #13
0
    def getTargets(cls, minCount =0):
        targets = cmds.ls(selection=True, exactType='transform')
        if minCount and len(targets) < minCount:
            print 'INVALID SELECTION: You must select at least %s footprint%s.' \
                  % (str(minCount), 's' if minCount > 1 else '')
            return []

        if not targets:
            return []

        return targets
Beispiel #14
0
 def _handleDuplicatedButton(self):
     random.seed(1234)
     exist = cmds.ls('dust')
     if(len(exist) != 0):
         cmds.delete('dust')
     dust=cmds.group(empty=True, name='dust')
     transformName = cmds.ls('pie', typ='transform')[0]
     num = int(self.dustNum.text())
     for i in range(0, num):
         instanceResult = cmds.instance(transformName, name=transformName + '_instance#')
         #print 'instanceResult: ' + str(instanceResult)
         x = random.uniform(-3, 34)
         y = random.uniform(0,4)
         z = random.uniform(-3,3)
         cmds.move(x, y, z, instanceResult)
         xRot = random.uniform(0,360)
         yRot = random.uniform(0,360)
         zRot = random.uniform(0,360)
         cmds.rotate(xRot, yRot, zRot, instanceResult)
         cmds.parent(instanceResult, dust)
Beispiel #15
0
def assignPlasticShader(name):
    selected = cmds.ls(sl=True)[0].encode('ascii', 'ignore')
    print(selected)
    cmds.sets(name='plasticMaterialGroup', renderable=True, empty=True)
    cmds.shadingNode('blinn', name='plasticShader', asShader=True)
    cmds.setAttr('plasticShader.color', .667628, 0., 1., type='double3')
    cmds.setAttr('plasticShader.diffuse', .5)
    cmds.setAttr('plasticShader.eccentricity', .5)
    cmds.surfaceShaderList('plasticShader', add='plasticMaterialGroup')
    cmds.sets(selected, e=True, forceElement='plasticMaterialGroup')
    return name
Beispiel #16
0
    def selectAllTracks(self):
        """ All tracks are selected, by accumulating a list of all track nodes
            in the trackway layers. """

        layers = cmds.ls( type='displayLayer')
        nodes  = list()
        for layer in layers:
            if layer.endswith(self.LAYER_SUFFIX):
               nodes.extend(cmds.editDisplayLayerMembers(
                   layer, query=True, noRecurse=True))
        cmds.select(nodes)
Beispiel #17
0
    def _handleDeleteAllButton(self):
        """
        This callback creates a polygonal cylinder in the Maya scene.

        """
        allObj = cmds.ls("molecule*", assemblies=True)
        for i in allObj:
            cmds.delete(i)
        cmds.delete("redBlinnSG")
        cmds.delete("whiteBlinnSG")
        cmds.delete("redBlinn")
        cmds.delete("whiteBlinn")
        self.spawnButton.setText("Spawn Molecules")
Beispiel #18
0
    def _handleDeleteAllButton(self):
        """
        This callback creates a polygonal cylinder in the Maya scene.

        """
        allObj = cmds.ls('molecule*', assemblies=True)
        for i in allObj:
            cmds.delete(i)
        cmds.delete("redBlinnSG")
        cmds.delete("whiteBlinnSG")
        cmds.delete("redBlinn")
        cmds.delete("whiteBlinn")
        self.spawnButton.setText("Spawn Molecules")
        def MoveVertex(min, max):
            cmds.select(ado=True)
            selected = cmds.ls(selection=True, long=True)

            for object in selected:
                total = cmds.polyEvaluate(object, vertex=True)
                for i in range(total):

                    randNumX = random.uniform(min, max)
                    randNumY = random.uniform(min, max)
                    randNumZ = random.uniform(min, max)
                    vertex = object+'.vtx['+str(i)+']'
                    cmds.select(vertex)
                    cmds.move(randNumX, randNumY, randNumZ, relative=True)
Beispiel #20
0
    def _handleGoButton(self):
        start = self.rangeStartSlide.value()    #get user-def range start
        end = self.rangeEndSlide.value()        #get user-def range end
        selObj = cmds.ls(sl=True)[0]            #Get selected object
        numVerts = cmds.polyEvaluate(selObj, v=True)

        #-----For each vertex...------
        for i in range(numVerts):
            pos = cmds.pointPosition(selObj+'.vtx['+str(i)+']')
            randX = random.randrange(start,end)
            randY = random.randrange(start,end)
            randZ = random.randrange(start,end)
            cmds.move(randX, randY, randZ, selObj+'.vtx['+str(i)+']', r=True)
            print cmds.pointPosition(selObj+'.vtx['+str(i)+']')
Beispiel #21
0
    def run(self):
        selectedNodes = cmds.ls(selection=True, exactType='transform')
        tracks = list()

        for n in selectedNodes:
            if self.isTrackNode(n):
                tracks.append(Track(n))

        print "number tracks = %s" % len(tracks)

        dicts = list()
        for t in tracks:
            dicts.append(t.getProperties())
        self.put('dictionaryList', dicts)
Beispiel #22
0
    def getAllShaded(cls, shaderConfig):
        """ Returns the list of transform nodes that have a geometry nodeName shaded by the
            specified shader configuration data. """

        engine = cls.createShaderFromConfig(shaderConfig)[1]
        geos   = cmds.ls(geometry=True)
        out    = []

        for geo in geos:
            if engine in cmds.listSets(type=1, object=geo):
                transforms = cmds.listRelatives([geo], allParents=True, type='transform')
                out       += transforms

        return out
        def MoveVertex(min, max):
            cmds.select(ado=True)
            selected = cmds.ls(selection=True, long=True)

            for object in selected:
                total = cmds.polyEvaluate(object, vertex=True)
                for i in range(total):

                    randNumX = random.uniform(min, max)
                    randNumY = random.uniform(min, max)
                    randNumZ = random.uniform(min, max)
                    vertex = object + '.vtx[' + str(i) + ']'
                    cmds.select(vertex)
                    cmds.move(randNumX, randNumY, randNumZ, relative=True)
Beispiel #24
0
    def run(self, *args, **kwargs):
        selectedNodes = cmds.ls(selection=True, exactType='transform')

        selectedUidList = list()

        if len(selectedNodes) == 0:
            self.puts(success=False, selectedUidList=selectedUidList)
            return

        for n in selectedNodes:
            uid = TrackSceneUtils.getUid(n)
            if uid is not None:
                selectedUidList.append(uid)
        self.puts(success=True, selectedUidList=selectedUidList)
        return
Beispiel #25
0
    def _handleSpawnButton(self):
        """
        This callback creates a polygonal cylinder in the Maya scene.

        """
        # Grab the names of all molecules in a scene
        allObj = cmds.ls("molecule*", assemblies=True)
        # If there aren't any molecules yet, make them
        if not allObj:
            numMolec = self.numMolecSpin.value()
            MoleculeSpawn.spawnMolecules(numMolec)
            response = nimble.createRemoteResponse(globals())
        # Otherwise, tell user to delete all before making more
        else:
            self.spawnButton.setText("Please delete before making more molecules")
Beispiel #26
0
    def _handleSpawnButton(self):
        """
        This callback creates a polygonal cylinder in the Maya scene.

        """
        #Grab the names of all molecules in a scene
        allObj = cmds.ls('molecule*', assemblies=True)
        #If there aren't any molecules yet, make them
        if not allObj:
            numMolec = self.numMolecSpin.value()
            MoleculeSpawn.spawnMolecules(numMolec)
            response = nimble.createRemoteResponse(globals())
        # Otherwise, tell user to delete all before making more
        else:
            self.spawnButton.setText(
                "Please delete before making more molecules")
Beispiel #27
0
def assignGoldShader(name):
    selected = cmds.ls(sl=True)[0].encode('ascii', 'ignore')
    print(selected)
    cmds.sets(name='goldMaterialGroup', renderable=True, empty=True)
    cmds.shadingNode('anisotropic', name='goldShader', asShader=True)
    cmds.setAttr('goldShader.color', 1, .775814, 0, type='double3')
    cmds.setAttr('goldShader.specularColor', 1, 1, 1, type='double3')
    cmds.setAttr('goldShader.diffuse', .475)
    cmds.setAttr('goldShader.translucence', .263)
    cmds.setAttr('goldShader.translucenceFocus', .869)
    cmds.setAttr('goldShader.spreadX', 5)
    cmds.setAttr('goldShader.spreadY', 24)
    cmds.setAttr('goldShader.roughness', .75)
    cmds.setAttr('goldShader.fresnelRefractiveIndex', 9.227)
    cmds.surfaceShaderList('goldShader', add='goldMaterialGroup')
    cmds.sets(selected, e=True, forceElement='goldMaterialGroup')
    return name
Beispiel #28
0
    def getNext(cls, target=None):
        if not target:
            target = cmds.ls(selection=True, exactType='transform')[0]

        conns = cmds.listConnections(
            target + '.message',
            destination=True,
            plugs=True
        )
        nexts = []
        if conns:
            for c in conns:
                if c.endswith('.' + cls._PREVIOUS_PRINT_ATTR):
                    nexts.append(c.split('.')[0])
            return nexts

        return []
Beispiel #29
0
def spawnAliens(num_aliens):
    #----------------------Generate X-amount of aliens-------------------
    #---make gravity field if it doesn't already exist
    gravName = cmds.ls('alienGrav*')
    print gravName
    if gravName == []:
        print "make grav"
        cmds.gravity(n="alienGrav",
                     pos=(0, 0, 0),
                     m=980,
                     att=0,
                     dx=0,
                     dy=-1,
                     dz=0,
                     mxd=-1,
                     vsh="none",
                     vex=0,
                     vof=(0, 0, 0),
                     vsw=360,
                     tsr=0.5)

    for i in range(0, num_aliens):

        #Give each a unique name
        curName = "alien"
        curName = curName + str(i)
        cmds.duplicate('alien', n=curName)

        #---Place in random location
        cmds.setAttr(curName + ".translateX",
                     random.randrange(-MAX_DIST, MAX_DIST))
        cmds.setAttr(curName + ".translateY", 200)
        cmds.setAttr(curName + ".translateZ",
                     random.randrange(-MAX_DIST, MAX_DIST))

        #Random orientation
        cmds.setAttr(curName + ".rotateX", random.randrange(360))
        cmds.setAttr(curName + ".rotateY", random.randrange(360))
        cmds.setAttr(curName + ".rotateZ", random.randrange(360))

        #Connect up to gravity
        cmds.connectDynamic(curName, f="alienGrav")
    #Connect up to gravity
    cmds.connectDynamic("alien", f="alienGrav")
Beispiel #30
0
    def initializeLayers(self):
        """ Creates a new layer for each trackway in this site and level based
            on the first UID found (returned by getUidList).  It is important to
            load into the Maya scene only trackways from a common combination of
            site, level, and sector, since a given trackway may be redundantly
            defined in different sectors for a given site and level. The list of
            trackway names is returned for the TrackwayManagerWidget to populate
            a combo box. """

        # first delete any current display layers
        layers = cmds.ls( type='displayLayer')
        for layer in layers:
            if (layer.endswith(self.LAYER_SUFFIX)):
                cmds.delete(layer)

        # get the current UID list so we can extract the site, year, sector, and
        # level information
        uidList = self.getUidList()

        if not uidList:
            return

        # we'll use the first track as representative of the site and level,
        # presumed to be in common with all tracks in this scene.
        track         = self.getTrackByUid(uidList[0])
        trackwayNames = self.getTrackwayNames(track.site, track.level)

        # then for each trackway name (such as 'S1') create a corresponding
        # layer with the LAYER_SUFFIX, then populate it with the track nodes of
        # the tracks comprising that trackway
        for trackwayName in trackwayNames:
            layer = '%s%s' % (trackwayName, self.LAYER_SUFFIX)

            # then make the layer
            self.createLayer(layer)

            # get a list of tracks for this trackway (filtering on site, level,
            # sector and name)
            trackway = self.getTrackway(trackwayName, uidList)
            if trackway and len(trackway) > 0:
                self.addTrackwayToLayer(layer, trackway)

        return trackwayNames
    def _generateTerrain(self):
        cmds.polyPlane(n='terrain', sx=self.size-1, sy=self.size-1, w=self.size, h=self.size)
        shapes = cmds.ls("terrain", sl=True, fl=True)
        self.terrain = shapes[0]

        offset_magnitude = int(self.magnitude)
        self.setVertexHeight((0, 0), randint(-offset_magnitude, offset_magnitude))
        self.setVertexHeight((self.size - 1, 0), randint(-offset_magnitude, offset_magnitude))
        self.setVertexHeight((0, self.size - 1), randint(-offset_magnitude, offset_magnitude))
        self.setVertexHeight((self.size - 1, self.size - 1), randint(-offset_magnitude, offset_magnitude))

        length = self.size - 1
        while length >= 1:
            half_length = length / 2
            for x in range(0, self.size - 1, length):
                for y in range(0, self.size - 1, length):
                    bottom_left = self.getVertexHeight((x, y))
                    bottom_right = self.getVertexHeight((x + length, y))
                    top_left = self.getVertexHeight((x, y + length))
                    top_right = self.getVertexHeight((x + length, y + length))
                    average = (top_left + top_right + bottom_left + bottom_right) / 4.0
                    offset = randint(int(-offset_magnitude), int(offset_magnitude))
                    point = (x + half_length, y + half_length)
                    flat_index = self.getFlatIndex(point)
                    if 0 <= flat_index <= self.size * self.size:
                        self.setVertexHeight(point, average + offset)

            for x in range(0, self.size - 1, half_length):
                for y in range((x + half_length) % length, self.size-1, length):
                    left = self.getVertexHeight(((x - half_length + self.size) % self.size, y))
                    right = self.getVertexHeight(((x + half_length) % self.size, y))
                    top = self.getVertexHeight((x, (y + half_length + self.size) % self.size))
                    bottom = self.getVertexHeight((x, (y - half_length) % self.size))
                    average = (left + right + top + bottom) / 4
                    offset = randint(int(-offset_magnitude), int(offset_magnitude))
                    point = (x, y)
                    flat_index = self.getFlatIndex(point)
                    if 0 <= flat_index <= self.size * self.size:
                        self.setVertexHeight((x, y), average + offset)
            offset_magnitude /= 2.0
            length /= 2
        print "DONE!"
Beispiel #32
0
    def run(self, *args, **kwargs):
        """ Fetches the nodes in the current trackSetNode, then for each such
            node, those that start with 'Token' are deleted. """

        setNode = TrackSceneUtils.getTrackSetNode()
        nodes   = cmds.sets(setNode, q=True)

        if len(nodes) == 0:
            self.puts(success=False, uidList=[])
            return

        for node in nodes:
            if node.startswith('Token'):
                cmds.delete(node)

        # and remove the annotations (objects with name starting with 'Token'
        objects = cmds.ls(transforms=True)
        for object in objects:
            if object.startswith('Token'):
                cmds.delete(object)
        return
Beispiel #33
0
    def run(self):
        """Doc..."""
        self.x = self.fetch('x', None)
        self.y = self.fetch('y', None)
        self.z = self.fetch('z', None)
        self.grow = self.fetch('grow', False)

        if self.x is None and self.y is None and self.z is None:
            return

        selection = cmds.ls(selection=True, type='transform')
        if not selection:
            return

        out = dict()
        for item in selection:
            scale = self._scaleItem(item)
            if scale is not None:
                out[item] = scale

        if len(list(out.keys())) > 0:
            self.put('changes', out)
Beispiel #34
0
    def run(self):
        """Doc..."""
        self.x = self.fetch('x', None)
        self.y = self.fetch('y', None)
        self.z = self.fetch('z', None)
        self.grow = self.fetch('grow', False)

        if self.x is None and self.y is None and self.z is None:
            return

        selection = cmds.ls(selection=True, type='transform')
        if not selection:
            return

        out = dict()
        for item in selection:
            scale = self._scaleItem(item)
            if scale is not None:
                out[item] = scale

        if len(list(out.keys())) > 0:
            self.put('changes', out)
    def _handlePerturb(self):
        """
        This perturbs the selected object.

        """

        selectedObjects = cmds.ls(selection=True, long=True)

        vertsList = []
        for object in selectedObjects:
            totalVerts = cmds.polyEvaluate(object, vertex=True)

            for number in range(totalVerts):
                vertsList.append(object+'.vtx[{number}]'.format(number=number))

        for vert in vertsList:
            min = float(self.minInput.displayText())
            max = float(self.maxInput.displayText())
            randNumX = random.uniform(min, max)
            randNumY = random.uniform(min, max)
            randNumZ = random.uniform(min, max)
            cmds.select(vert, replace=True)
            cmds.move(randNumX, randNumY, randNumZ, relative=True)
            cmds.select(selectedObjects, replace=True)
Beispiel #36
0
    def _handleExampleButton(self):
        """
        This callback creates a polygonal cylinder in the Maya scene.

        """

        random.seed(1234)

        #check
        sphereList = cmds.ls('hydrogen1', 'hydrogen2', 'oxygen', 'H2O')

        if len(sphereList) > 0:
            cmds.delete(sphereList)

        #create 2 hydrogen and oxygen
        h1 = cmds.polySphere(r=12.0, name='hydrogen1')
        h2 = cmds.polySphere(r=12.0, name='hydrogen2')
        oxygen = cmds.polySphere(r=15.0, name='oxygen')

        #move
        cmds.move(-15, 0, 0, h1)
        cmds.move(15, 0, 0, h2)
        cmds.xform(h1, piv=[0, 0, 0], ws=True)
        cmds.xform(h2, piv=[0, 0, 0], ws=True)
        cmds.rotate(0, '75', 0, h1)

        #group hydrogen and oxygen together
        H2O = cmds.group(empty=True, name='H2O#')
        cmds.parent('hydrogen1', 'hydrogen2', 'oxygen', 'H2O1')

        #add color
        def createMaterial(name, color, type):
            cmds.sets(renderable=True,
                      noSurfaceShader=True,
                      empty=True,
                      name=name + 'SG')
            cmds.shadingNode(type, asShader=True, name=name)
            cmds.setAttr(name + '.color',
                         color[0],
                         color[1],
                         color[2],
                         type='double3')
            cmds.connectAttr(name + '.outColor', name + 'SG.surfaceShader')

        def assignMaterial(name, object):
            cmds.sets(object, edit=True, forceElement=name + 'SG')

        def assignNewMaterial(name, color, type, object):
            createMaterial(name, color, type)
            assignMaterial(name, object)

        #H is white and O is red
        assignNewMaterial('Red', (1, 0, 0), 'lambert', 'oxygen')
        assignNewMaterial('White', (1, 1, 1), 'lambert', 'hydrogen1')
        assignMaterial('White', 'hydrogen2')

        #key frame
        def keyFullRotation(pObjectName, pStartTime, pEndTime,
                            pTargetAttribute, pValueStart, pvalueEnd):
            keyt = (pStartTime[0], pStartTime[0])
            cmds.cutKey(pObjectName,
                        time=(keyt, keyt),
                        attribute=pTargetAttribute)
            cmds.setKeyframe(pObjectName,
                             time=pStartTime,
                             attribute=pTargetAttribute,
                             value=pValueStart)
            cmds.setKeyframe(pObjectName,
                             time=pEndTime,
                             attribute=pTargetAttribute,
                             value=pvalueEnd)
            #cmds.selectKey( pObjectName, time=(pStartTime, [pEndTime]), attribute=pTargetAttribute, keyframe=True )

        #duplicate H2O
        for i in range(1, 52):
            cmds.duplicate(H2O)
            #get random coord
            x = random.uniform(-200, 200)
            y = random.uniform(0, 300)
            z = random.uniform(-200, 200)

            cmds.move(x, y, z, H2O)

            xRot = random.uniform(0, 360)
            yRot = random.uniform(0, 360)
            zRot = random.uniform(0, 360)

            cmds.rotate(xRot, yRot, zRot, H2O)

            startTime = cmds.playbackOptions(minTime=1)
            endTime = cmds.playbackOptions(maxTime=30)

            h2o = "H2O" + str(i)

            for y in range(3):
                coordsX = cmds.getAttr(h2o + '.translateX')
                coordsY = cmds.getAttr(h2o + '.translateY')
                coordsZ = cmds.getAttr(h2o + '.translateZ')

                ranStartX = int(random.uniform(0, 15))
                ranStartY = int(random.uniform(0, 15))
                ranStartZ = int(random.uniform(0, 15))

                ranEndX = int(random.uniform(15, 30))
                ranEndY = int(random.uniform(15, 30))
                ranEndZ = int(random.uniform(15, 30))

                x = random.uniform(coordsX - 50, coordsX + 50)
                y = random.uniform(coordsY, coordsY + 50)
                z = random.uniform(coordsZ - 50, coordsZ + 50)
                #print x,y,z

                keyFullRotation(h2o, ranStartZ, 15, 'translateZ', coordsZ, z)
                keyFullRotation(h2o, ranStartX, 15, 'translateX', coordsX, x)
                keyFullRotation(h2o, ranStartY, 15, 'translateY', coordsY, y)

                keyFullRotation(h2o, 15, ranEndZ, 'translateZ', z, coordsZ)
                keyFullRotation(h2o, 15, ranEndX, 'translateX', x, coordsX)
                keyFullRotation(h2o, 15, ranEndY, 'translateY', y, coordsY)

                RcoordsX = cmds.getAttr(h2o + '.rotateX')
                RcoordsY = cmds.getAttr(h2o + '.rotateY')
                RcoordsZ = cmds.getAttr(h2o + '.rotateZ')

                xRot = random.uniform(0, 360)
                yRot = random.uniform(0, 360)
                zRot = random.uniform(0, 360)

                keyFullRotation(h2o, ranStartZ, 15, 'rotateZ', RcoordsZ, zRot)
                keyFullRotation(h2o, ranStartX, 15, 'rotateX', RcoordsX, xRot)
                keyFullRotation(h2o, ranStartY, 15, 'rotateY', RcoordsY, zRot)

                keyFullRotation(h2o, 15, ranEndZ, 'rotateZ', zRot, RcoordsZ)
                keyFullRotation(h2o, 15, ranEndX, 'rotateX', xRot, RcoordsX)
                keyFullRotation(h2o, 15, ranEndY, 'rotateY', zRot, RcoordsY)

        print 'done'
        cmds.delete('H2O52')
Beispiel #37
0
    def run(self):
        """Doc..."""

        self.saveSelection()

        count = self.fetch('count', 1000)
        self._size = self.fetch('size', 0.1)
        self._padding = self.fetch('padding', 0.0)

        transforms = cmds.ls(selection=True, type='transform')
        if not transforms:
            self._cleanup()
            self.putErrorResult(u'ERROR: No transforms selected')
            return

        shapes = []
        totalVolume = 0.0
        shapeCount = 0
        for transform in transforms:
            shapeNames = cmds.listRelatives(transforms, shapes=True)
            if not shapeNames:
                continue

            for shape in shapeNames:
                try:
                    box = TransformUtils.getBoundingBox(shape)
                    cmds.select(shape, replace=True)
                    shapeVolume = nimble.executeMelCommand('computePolysetVolume')
                    totalVolume += shapeVolume
                    shapes.append(dict(
                        transform=transform,
                        name=shape,
                        box=box,
                        weight=float(shapeVolume)) )
                    shapeCount += 1
                except Exception as err:
                    self._cleanup()
                    NimbleEnvironment.logError(u'ERROR: Shape processing', err)

                    self.putErrorResult(
                        u'ERROR: Unable to process selection item %s -> %s' % (transform, shape) )
                    return

        if shapeCount == 0:
            self._cleanup()
            self.putErrorResult(u'ERROR: No polygon transforms found in selection')
            return

        try:
            for shape in shapes:
                if not self._createMeshPointNode(shape):
                    self._cleanup()
                    print(u'ERROR: Creation failure')
                    self.putErrorResult(u'ERROR: Unable to create point test node')

                shape['weight'] /= totalVolume
                shapeCount = int(round(float(count)*shape['weight']))
                for i in range(shapeCount):
                    self._create(shape)

                self._removeMeshPointNode()
        except Exception as err:
            self._cleanup()
            print(Logger.createErrorMessage(u'ERROR: Creation failure', err))
            self.putErrorResult(u'ERROR: Unable to create random box')
            return

        self._cleanup()
def findName(namelike):
    objs = mc.ls()
    bodyName = ""
	compareScore = 0
	newScore = 0
Beispiel #39
0
    def run(self):
        """Doc..."""

        #-------------------------------------------------------------------------------------------
        # GET SELECTED OBJECTS
        #       Get a list of select objects. If no objects are selected then return an error.
        #       Because objects are list based on components, shape nodes are generally returned
        #       instead of transform nodes. In those cases the transform node must be found from
        #       the shape node name
        objectSelection = cmds.ls(selection=True, objectsOnly=True)
        if not objectSelection:
            self.putErrorResult(u'Nothing selected')
            return

        targets = dict()
        for obj in objectSelection:

            # Check for shape nodes, and get transform node name if a shape is found
            nodeTypes = cmds.nodeType(obj, inherited=True)
            if u'shape' in nodeTypes:
                obj = obj.rsplit(u'|', 1)[0]

            targets[obj] = []

        #-------------------------------------------------------------------------------------------
        # SORT SELECTED FACES
        #       Use a component selection to get the selected faces and add them to the target
        #       list for their object.
        for comp in cmds.ls(selection=True, flatten=True):
            parts = comp.split(u'.')
            if len(parts) < 2 or parts[0] not in targets:
                continue

            targets[parts[0]].append(int(parts[1].lstrip(u'f[').rstrip(u']')))

        #-------------------------------------------------------------------------------------------
        # EXTRACT & SEPARATE
        #       For each object in the targets list extract the selected faces by chipping them off
        #       and then separating the mesh into the separated pieces.
        results = dict()
        selects = []
        for obj, faces in DictUtils.iter(targets):
            if not faces:
                continue

            faces.sort()
            comps = []
            for f in faces:
                comps.append(u'%s.f[%s]' % (obj, f))

            cmds.polyChipOff(*comps, duplicate=False, keepFacesTogether=True)
            separateOut = cmds.polySeparate(obj)
            out = []
            for node in separateOut:
                if MayaNodeUtils.isTransformNode(node):
                    out.append(node)
                    selects.append(node)

            results[obj] = out

        cmds.select(*selects, replace=True)
        self.put('extracts', results)
Beispiel #40
0
 def _handleAimedButton(self):
     targetName = cmds.ls('ball')[0]
     dust = cmds.ls("pie_instance*")
     if(targetName != None and dust != None):
         for objectName in dust:
             cmds.aimConstraint(targetName, objectName, aimVector = [0,1,0], name='pie_aimConstraint#')
Beispiel #41
0
 def _handleRotateButton(self):
     dust = cmds.ls("pie_instance*")
     startTime=cmds.playbackOptions(query=True, minTime=True)
     endTime=cmds.playbackOptions(query=True, maxTime=True)
     for obj in dust:
         self._keyRot(obj, startTime, endTime, 'rotateX')
    def _handleExampleButton(self):
        """
        This callback creates a polygonal cylinder in the Maya scene.

        """

        random.seed(1234)

        #check
        sphereList = cmds.ls('hydrogen1','hydrogen2', 'oxygen','H2O')

        if len(sphereList)>0:
            cmds.delete(sphereList)

        #create 2 hydrogen and oxygen
        h1 = cmds.polySphere(r=12.0, name='hydrogen1')
        h2 = cmds.polySphere(r=12.0, name='hydrogen2')
        oxygen = cmds.polySphere(r=15.0, name='oxygen')


        #move
        cmds.move(-15,0,0,h1)
        cmds.move(15,0,0,h2)
        cmds.xform(h1, piv=[0,0,0],ws=True)
        cmds.xform(h2, piv=[0,0,0],ws=True)
        cmds.rotate(0,'75',0,h1)

        #group hydrogen and oxygen together
        H2O = cmds.group(empty=True, name='H2O#')
        cmds.parent('hydrogen1','hydrogen2','oxygen','H2O1')

        #add color
        def createMaterial( name, color, type ):
            cmds.sets( renderable=True, noSurfaceShader=True, empty=True, name=name + 'SG' )
            cmds.shadingNode( type, asShader=True, name=name )
            cmds.setAttr( name+'.color', color[0], color[1], color[2], type='double3')
            cmds.connectAttr(name+'.outColor', name+'SG.surfaceShader')

        def assignMaterial (name, object):
            cmds.sets(object, edit=True, forceElement=name+'SG')

        def assignNewMaterial( name, color, type, object):
            createMaterial (name, color, type)
            assignMaterial (name, object)

        #H is white and O is red
        assignNewMaterial('Red', (1,0,0), 'lambert', 'oxygen');
        assignNewMaterial('White',(1,1,1),'lambert', 'hydrogen1');
        assignMaterial('White', 'hydrogen2');

        #key frame
        def keyFullRotation( pObjectName, pStartTime, pEndTime, pTargetAttribute,pValueStart, pvalueEnd ):
            keyt = (pStartTime[0], pStartTime[0])
            cmds.cutKey( pObjectName, time=(keyt, keyt), attribute=pTargetAttribute )
            cmds.setKeyframe( pObjectName, time=pStartTime, attribute=pTargetAttribute, value=pValueStart )
            cmds.setKeyframe( pObjectName, time=pEndTime, attribute=pTargetAttribute, value=pvalueEnd )
            #cmds.selectKey( pObjectName, time=(pStartTime, [pEndTime]), attribute=pTargetAttribute, keyframe=True )

        #duplicate H2O
        for i in range(1,52):
            cmds.duplicate(H2O)
            #get random coord
            x = random.uniform(-200,200)
            y = random.uniform(0,300)
            z = random.uniform(-200,200)

            cmds.move(x,y,z, H2O)


            xRot = random.uniform(0,360)
            yRot = random.uniform(0,360)
            zRot = random.uniform(0,360)

            cmds.rotate(xRot,yRot,zRot,H2O)

            startTime = cmds.playbackOptions(minTime=1 )
            endTime = cmds.playbackOptions( maxTime=30 )

            h2o = "H2O"+str(i)

            for y in range(3):
                coordsX = cmds.getAttr( h2o+'.translateX' )
                coordsY = cmds.getAttr( h2o+'.translateY' )
                coordsZ = cmds.getAttr( h2o+'.translateZ' )

                ranStartX = int(random.uniform(0,15))
                ranStartY = int(random.uniform(0,15))
                ranStartZ = int(random.uniform(0,15))

                ranEndX = int(random.uniform(15,30))
                ranEndY = int(random.uniform(15,30))
                ranEndZ = int(random.uniform(15,30))

                x = random.uniform(coordsX-50,coordsX+50)
                y = random.uniform(coordsY,coordsY+50)
                z = random.uniform(coordsZ-50,coordsZ+50)
                #print x,y,z

                keyFullRotation( h2o, ranStartZ, 15, 'translateZ',coordsZ,z)
                keyFullRotation( h2o, ranStartX, 15, 'translateX', coordsX,x)
                keyFullRotation( h2o, ranStartY, 15, 'translateY', coordsY,y)

                keyFullRotation( h2o, 15, ranEndZ, 'translateZ',z,coordsZ)
                keyFullRotation( h2o, 15, ranEndX, 'translateX', x,coordsX)
                keyFullRotation( h2o, 15, ranEndY, 'translateY', y,coordsY)

                RcoordsX = cmds.getAttr( h2o+'.rotateX' )
                RcoordsY = cmds.getAttr( h2o+'.rotateY' )
                RcoordsZ = cmds.getAttr( h2o+'.rotateZ' )

                xRot = random.uniform(0,360)
                yRot = random.uniform(0,360)
                zRot = random.uniform(0,360)

                keyFullRotation( h2o, ranStartZ, 15, 'rotateZ',RcoordsZ,zRot)
                keyFullRotation( h2o, ranStartX, 15, 'rotateX', RcoordsX,xRot)
                keyFullRotation( h2o, ranStartY, 15, 'rotateY', RcoordsY,zRot)

                keyFullRotation( h2o, 15, ranEndZ, 'rotateZ',zRot,RcoordsZ)
                keyFullRotation( h2o, 15, ranEndX, 'rotateX', xRot,RcoordsX)
                keyFullRotation( h2o, 15, ranEndY, 'rotateY', zRot,RcoordsY)

        print 'done'
        cmds.delete('H2O52')
Beispiel #43
0
    def run(self):
        """Doc..."""

        self.saveSelection()

        count = self.fetch('count', 1000)
        self._size = self.fetch('size', 0.1)
        self._padding = self.fetch('padding', 0.0)

        transforms = cmds.ls(selection=True, type='transform')
        if not transforms:
            self._cleanup()
            self.putErrorResult(u'ERROR: No transforms selected')
            return

        shapes = []
        totalVolume = 0.0
        shapeCount = 0
        for transform in transforms:
            shapeNames = cmds.listRelatives(transforms, shapes=True)
            if not shapeNames:
                continue

            for shape in shapeNames:
                try:
                    box = TransformUtils.getBoundingBox(shape)
                    cmds.select(shape, replace=True)
                    shapeVolume = nimble.executeMelCommand('computePolysetVolume')
                    totalVolume += shapeVolume
                    shapes.append(dict(
                        transform=transform,
                        name=shape,
                        box=box,
                        weight=float(shapeVolume)) )
                    shapeCount += 1
                except Exception as err:
                    self._cleanup()
                    NimbleEnvironment.logError(u'ERROR: Shape processing', err)

                    self.putErrorResult(
                        u'ERROR: Unable to process selection item %s -> %s' % (transform, shape) )
                    return

        if shapeCount == 0:
            self._cleanup()
            self.putErrorResult(u'ERROR: No polygon transforms found in selection')
            return

        try:
            for shape in shapes:
                if not self._createMeshPointNode(shape):
                    self._cleanup()
                    print(u'ERROR: Creation failure')
                    self.putErrorResult(u'ERROR: Unable to create point test node')

                shape['weight'] /= totalVolume
                shapeCount = int(round(float(count)*shape['weight']))
                for i in range(shapeCount):
                    self._create(shape)

                self._removeMeshPointNode()
        except Exception as err:
            self._cleanup()
            print(Logger.createErrorMessage(u'ERROR: Creation failure', err))
            self.putErrorResult(u'ERROR: Unable to create random box')
            return

        self._cleanup()
 def _clearKeys(self):
     totalTime = float(self.AnimationTime.text()) * 24
     cmds.select(ado=True)
     mySel = cmds.ls(sl=1)
     cmds.cutKey(mySel, clear=True)
Beispiel #45
0
    def run(self):
        """Doc..."""

        #-------------------------------------------------------------------------------------------
        # GET SELECTED OBJECTS
        #       Get a list of select objects. If no objects are selected then return an error.
        #       Because objects are list based on components, shape nodes are generally returned
        #       instead of transform nodes. In those cases the transform node must be found from
        #       the shape node name
        objectSelection = cmds.ls(selection=True, objectsOnly=True)
        if not objectSelection:
            self.putErrorResult(u'Nothing selected')
            return

        targets = dict()
        for obj in objectSelection:

            # Check for shape nodes, and get transform node name if a shape is found
            nodeTypes = cmds.nodeType(obj, inherited=True)
            if u'shape' in nodeTypes:
                obj = obj.rsplit(u'|', 1)[0]

            targets[obj] = []

        #-------------------------------------------------------------------------------------------
        # SORT SELECTED FACES
        #       Use a component selection to get the selected faces and add them to the target
        #       list for their object.
        for comp in cmds.ls(selection=True, flatten=True):
            parts = comp.split(u'.')
            if len(parts) < 2 or parts[0] not in targets:
                continue

            targets[parts[0]].append(int(parts[1].lstrip(u'f[').rstrip(u']')))

        #-------------------------------------------------------------------------------------------
        # EXTRACT & SEPARATE
        #       For each object in the targets list extract the selected faces by chipping them off
        #       and then separating the mesh into the separated pieces.
        results = dict()
        selects = []
        for obj,faces in DictUtils.iter(targets):
            if not faces:
                continue

            faces.sort()
            comps = []
            for f in faces:
                comps.append(u'%s.f[%s]' % (obj, f))

            cmds.polyChipOff(*comps, duplicate=False, keepFacesTogether=True)
            separateOut = cmds.polySeparate(obj)
            out = []
            for node in separateOut:
                if MayaNodeUtils.isTransformNode(node):
                    out.append(node)
                    selects.append(node)

            results[obj] = out

        cmds.select(*selects, replace=True)
        self.put('extracts', results)
Beispiel #46
0
 def _clearKeys(self):
     totalTime = float(self.AnimationTime.text()) * 24
     cmds.select(ado=True)
     mySel = cmds.ls(sl=1)
     cmds.cutKey(mySel, clear=True)