예제 #1
0
파일: Prey.py 프로젝트: McBainC/Portfolio
    def __init__( self, *args, **kwargs ):

        # Call animal constructor
        Animal.__init__( self, *args, **kwargs )

        # Define weightings #
        # Flocking weights are averaged
        self.separationWeight = 0.33333
        self.cohesionWeight = 0.33333
        self.alignmentWeight = 0.33333

        # Threat initialized to zero
        self.threatWeight = 0.0

        # Create Awareness State and initialize to Grazing
        self.state = AwarenessState.grazing

        # Set leader flag
        self.isLeader = kwargs.setdefault( "leader" )

        # Set alerted flag
        self.isAlerted = False

        # Select then change the cones colour to green
        cmds.select( self.animalName, visible = True )

        # Set initial prey colour
        if self.isLeader is False:

            cmds.polyColorPerVertex( colorRGB = [ 0, 1, 0 ], colorDisplayOption = True )

        else:

            cmds.polyColorPerVertex( colorRGB = [ 0, 0.5, 0 ], colorDisplayOption = True )
예제 #2
0
 def setValue(vertNum,value):
     '''
     this gets called by MEL procedures
     '''
     PaintContext.vertValues[vertNum] = value
     r,g,b = PaintContext.mapWeightToValue(value) 
     cmds.polyColorPerVertex('pTorusShape1.vtx[%d]'%vertNum,r=r,g=g,b=b);
예제 #3
0
    def __init__( self, *args, **kwargs ):

        # Call animal constructor
        Animal.__init__( self, *args, **kwargs )

        # Flag for center or wing
        self.isCenter = kwargs.setdefault( "center" )

        # Create Awareness State and initialize to Grazing
        self.state = HuntingState.prowling

        # Has a target prey flag
        self.hasTarget = False

        # Target prey - this will hold a <Prey> object once set, still dont know about this dynamic typing...
        self.target = 0

        # Wing angle of attack
        self.wingAngle = 0

        # Select then change the cones colour to orange
        cmds.select( self.animalName, visible = True )
        cmds.polyColorPerVertex( colorRGB = [ 1, 1, 0 ], colorDisplayOption = True )

        # Scale polyCone by 150% for Predator
        cmds.setAttr( self.animalName+".scaleX", 1.5 )
        cmds.setAttr( self.animalName+".scaleY", 1.5 )
        cmds.setAttr( self.animalName+".scaleZ", 1.5 )
 def createCollisionSphereGuide(self, name):
     shpere = cmds.polySphere(name=n_collisionSphere, sx=6, sy=6)
     cmds.polyColorPerVertex(shpere[0],  rgb=(0.75,0.75,0))
     cmds.polyColorPerVertex(shpere[0], colorDisplayOption=1)
     self.setAttr(shpere[0],'overrideEnabled', 1)
     self.setAttr(shpere[0],'overrideDisplayType', 2)
     return shpere
예제 #5
0
파일: Animal.py 프로젝트: McBainC/Portfolio
    def change_shape_colour( self, red, green, blue ):

        # Select then change the objects cone colour
        cmds.select( self.animalName, visible = True )
        cmds.polyColorPerVertex( colorRGB = [ red, green, blue ], colorDisplayOption = True )

        # Deselect 
        cmds.select( clear = True )
예제 #6
0
def Lab_coordinates_system_representation():
    """
    Creates a *CIE L\\*a\\*b\\** coordinates system representation.

    Returns
    -------
    bool
        Definition success.
    """

    group = cmds.createNode('transform')

    cube = cmds.polyCube(w=600, h=100, d=600, sx=12, sy=2, sz=12, ch=False)[0]
    set_attributes({'{0}.translateY'.format(cube): 50,
                    '{0}.overrideEnabled'.format(cube): True,
                    '{0}.overrideDisplayType'.format(cube): 2,
                    '{0}.overrideShading'.format(cube): False})
    cmds.makeIdentity(cube, apply=True, t=True, r=True, s=True)
    cmds.select(['{0}.f[0:167]'.format(cube), '{0}.f[336:359]'.format(cube)])
    cmds.delete()

    cmds.nurbsToPolygonsPref(polyType=1, chordHeightRatio=0.975)

    for label, position, name in (('-a*', (-350, 0), 'minus_a'),
                                  ('+a*', (350, 0), 'plus_a'),
                                  ('-b*', (0, 350), 'minus_b'),
                                  ('+b*', (0, -350), 'plus_b')):
        curves = cmds.listRelatives(
            cmds.textCurves(f='Arial Black Bold', t=label)[0])
        mesh = cmds.polyUnite(*[cmds.planarSrf(x,
                                               ch=False,
                                               o=True,
                                               po=1)
                                for x in curves],
                              ch=False)[0]
        cmds.xform(mesh, cp=True)
        cmds.xform(mesh, translation=(0, 0, 0), absolute=True)
        cmds.makeIdentity(cube, apply=True, t=True, r=True, s=True)
        cmds.select(mesh)
        cmds.polyColorPerVertex(rgb=(0, 0, 0), cdo=True)
        set_attributes({'{0}.translateX'.format(mesh): position[0],
                        '{0}.translateZ'.format(mesh): position[1],
                        '{0}.rotateX'.format(mesh): -90,
                        '{0}.scaleX'.format(mesh): 50,
                        '{0}.scaleY'.format(mesh): 50,
                        '{0}.scaleY'.format(mesh): 50,
                        '{0}.overrideEnabled'.format(mesh): True,
                        '{0}.overrideDisplayType'.format(mesh): 2})
        cmds.delete(cmds.listRelatives(curves, parent=True))
        cmds.makeIdentity(mesh, apply=True, t=True, r=True, s=True)
        mesh = cmds.rename(mesh, name)
        cmds.parent(mesh, group)

    cube = cmds.rename(cube, 'grid')
    cmds.parent(cube, group)
    cmds.rename(group, 'Lab_coordinates_system_representation')

    return True
예제 #7
0
 def setColour(s, selection=None, colour=None):
     """
     Colour the mesh for visual feedback.
     This step slows down the process a bit.
     """
     for mesh in s.meshes:
         cmds.polyColorPerVertex("%s.vtx[0:]" % mesh, rgb=(0.5,0.5,0.5))
         if colour:
             cmds.setAttr("%s.displayColors" % mesh, 1)
         else:
             cmds.setAttr("%s.displayColors" % mesh, 0)
     if selection and colour:
         cmds.polyColorPerVertex(selection, rgb=colour)
         s.turnOffColours = True # There is colour to be turned off
예제 #8
0
파일: Prey.py 프로젝트: McBainC/Portfolio
    def __init__( self, *args, **kwargs ):

        self.targetName = kwargs.setdefault( "targetName" )

        # Create a cube to represent the target
        self.cube = cmds.polyCube( name = self.targetName, axis = [ 0, 1, 0 ], height = 2, width = 2, depth = 2 )

        # Set an initial position
        cmds.setAttr( self.targetName+".translateX", kwargs.setdefault( "x" ) )
        cmds.setAttr( self.targetName+".translateY", kwargs.setdefault( "y" ), lock = True )
        cmds.setAttr( self.targetName+".translateZ", kwargs.setdefault( "z" ) )

        # Purple cube
        cmds.select( self.targetName, visible = True )
        cmds.polyColorPerVertex( colorRGB = [ 1, 0, 1 ], colorDisplayOption = True )
예제 #9
0
 def _populateVertColorData(self):
     '''Populates a dictionary of color/alpha key -> vtxFace list'''
     rgbaDict = dict()
     if cmds.listRelatives(self.object,s=1) :
         for vtxFace in self.getVtxFaceList() :
             try:
                 colorList = cmds.polyColorPerVertex(vtxFace,q=1,rgb=1)
             except:
                 cmds.polyColorPerVertex(self.object,rgb=[0,0,0],a=1)
                 colorList = cmds.polyColorPerVertex(vtxFace,q=1,rgb=1)
             alpha = cmds.polyColorPerVertex(vtxFace,q=1,a=1)
             rgba = (colorList[0],colorList[1],colorList[2],alpha[0])
             if rgba not in rgbaDict :
                 rgbaDict[rgba] = []
             rgbaDict[rgba].append(vtxFace)
     self.setVtxFaceColorData(rgbaDict)
예제 #10
0
	def main(self, *args):

		'''

		This method will be the main function of the tool letting the
		user generate random values for the color set 2.

		'''

		selected_obj = cmds.ls(selection=True)

		#Warning message for no selection
		if not selected_obj:

			cmds.confirmDialog(
									title="Error Message",
									message="No objects selected. Must select one object!",
									button="Accept"
								)
			return False

		color_sets = cmds.polyColorSet(query=True, allColorSets=True)

		#Warning message for no current color sets
		if not color_sets:

			cmds.confirmDialog(
									title="Error Message",
									message="Must create color set two!",
									button="Accept"
								)
			return False

		#If statement generates random values based on the users input for Minimum and Maximum sliders
		if "colorSet2" in color_sets:

			for index in xrange(cmds.polyEvaluate(selected_obj[0], vertex=True)):

				#slider values
				min_value = cmds.intSliderGrp("minimum", query=True, value=True)
				max_value = cmds.intSliderGrp("maximum", query=True, value=True)

				generate_value = rand.randint(min_value, max_value)
				color_value = generate_value/100.00

				color_set = cmds.polyColorPerVertex(
														"{object}.vtx[{number}]".format(object=selected_obj[0], number=index),
														rgb=( color_value, color_value, color_value)
													)
		#Error Message if colorSet2 does not exist
		else:

			cmds.confirmDialog(
									title="Error Message",
									message="Must create color set two!",
									button="Accept"
								)
			return False
    def applyBtnCmd(self, *args):
            """
            Overridden from base class
            """
            # determine the type of object to create from radio button index
            self.objIndAsCmd = {1:cmds.polyCube, 2:cmds.polyCone, 
                                3:cmds.polyCylinder, 4:cmds.polySphere}
            # determine the selected radio button from radioButtonGrp self.objType
            objIndex = cmds.radioButtonGrp(self.objType, query=True, select=True)
            # create the selected new poly object
            newObject = self.objIndAsCmd[objIndex]()
            # From this point, you can apply transformation using the float field
            # in an absolute (relative to parent) or as initial transformation at creation

            # Absolute transformation
            # Connecting the translates
            # index 1 is the label, so it begins from index=2
            cmds.connectControl(self.position, '%s.translateX' % newObject[0], index=2) 
            cmds.connectControl(self.position, '%s.translateY' % newObject[0], index=3)
            cmds.connectControl(self.position, '%s.translateZ' % newObject[0], index=4)
            # Connecting the rotations
            cmds.connectControl(self.rotation, '%s.rotateX' % newObject[0], index=2) 
            cmds.connectControl(self.rotation, '%s.rotateY' % newObject[0], index=3)
            cmds.connectControl(self.rotation, '%s.rotateZ' % newObject[0], index=4)
            # Connecting the scales
            cmds.connectControl(self.scale, '%s.scaleX' % newObject[0], index=2) 
            cmds.connectControl(self.scale, '%s.scaleY' % newObject[0], index=3)
            cmds.connectControl(self.scale, '%s.scaleZ' % newObject[0], index=4)
            
            # Initial transformation
#            # Query the values from the fields
#            pos = cmds.floatFieldGrp(self.position, query=True, value=True)
#            rot = cmds.floatFieldGrp(self.rotation, query=True, value=True)
#            scale = cmds.floatFieldGrp(self.scale, query=True, value=True)
#            # apply the transformation
#            cmds.xform(newObject[0], translation=pos, rotation=rot, scale=scale)
            
            # apply vertex colours to the new object, from the color picker of 
            # colorSliderGrp, self.color
            # First, query the colour from self.color
            col = cmds.colorSliderGrp(self.color, query=True, rgbValue=True)
            # Then apply the color to the new object. 
            cmds.polyColorPerVertex(newObject[0], colorRGB=col, 
                                    # enable the mesh to display vertex colors
                                    colorDisplayOption=True)
예제 #12
0
def getVertexColor():
    selection = cmds.ls(sl=True)
    colors = {}
    for obj in selection:
        colors[obj] = {}
        for v in range(cmds.polyEvaluate(v=True)):
            cmds.select(obj+'.vtx['+str(v)+']', r=True)
            colors[obj][v] = cmds.polyColorPerVertex(query=True, g=True, b=True)
    return colors
예제 #13
0
 def createMarker(s, target, name, shape=None, colour=None):
     sel = cmds.ls(sl=True)
     name = "%s_marker" % name
     if cmds.objExists(name):
         cmds.delete(name)
     if shape == "square":
         name = cmds.polyCube(name=name)[0]
     elif shape == "cone" :
         name = cmds.polyCone(name=name)[0]
     elif shape == "cylinder":
         name = cmds.polyCylinder(name=name)[0]
     else:
         name = cmds.polySphere(name=name)[0]
     cmds.parent(name, s.baseName)
     for at in [".sx", ".sy", ".sz"]:
         cmds.connectAttr("%s.markerSize" % s.baseName, name + at, f=True)
     cmds.parentConstraint(target, name)
     cmds.setAttr("%s.overrideEnabled" % name, 1)
     cmds.setAttr("%s.overrideDisplayType" % name, 2)
     cmds.polyColorPerVertex(name, rgb=colour or [1,1,0], cdo=True)
     cmds.select(sel, r=True)
예제 #14
0
 def getColors(self, selection):
     colors = {}
     for obj in selection:
         try:
             colors[obj] = {}
             for v in range(cmds.polyEvaluate(obj, v=True)):
                 cmds.select(obj+'.vtx['+str(v)+']', r=True)
                 colors[obj][v] = cmds.polyColorPerVertex(query=True,
                                                          r=True,
                                                          g=True,
                                                          b=True)
         except:
             pass 
     cmds.select(selection, r=True)
     
     return colors
예제 #15
0
def parseMeshVertexColour(name):
    global accuracy
    # Clamp accuracy
    if accuracy > 1.0: accuracy = 1.0
    itervtx = ['%s.vtx[%i]'%(name,i) for i in xrange(cmds.polyEvaluate(name, v=True)) ]
    vertCol = [cmds.polyColorPerVertex(v, query=True, rgb=True) for v in itervtx ]

    stepTotal = int(1/accuracy)
    layers = [ [] for i in xrange(0, stepTotal) ]

    for vtx, col in enumerate(vertCol):
        for i in xrange(len(layers)):
            minColour = [i*accuracy, i*accuracy, i*accuracy]
            maxColour = [(i+1)*accuracy, (i+1)*accuracy, (i+1)*accuracy]
            if (minColour < col <= maxColour):
                    layers[i].append(vtx)

    return layers
예제 #16
0

#data container
mc.createNode("arrayDataContainer")
mc.createNode("arrayToPointColor")


print mc.ls(type="attributeTransfer")


import maya.cmds as mc
mc.select(cl=True)
for i in range(0, mc.polyEvaluate("polySurfaceShape1", v=True)):
    if i == 50:
        mc.select("polySurfaceShape1.vtx["+str(i)+"]", add=True)
        mc.polyColorPerVertex( rgb=(0, 0, 1) )







import maya.cmds as mc
EXBAND_RANGE = 2
#selVerts = mc.ls(sl=True)
#print selVert
#comp = mc.polyListComponentConversion(selVerts, fv=True, tf=True)
for t in range(0,EXBAND_RANGE):
    selVerts = mc.ls(sl=True)
    comp = mc.polyListComponentConversion(selVerts, fv=True, tf=True)
예제 #17
0
import maya.cmds as cmds
import maya.OpenMaya as OpenMaya

if __name__ == '__main__':

    meshA, meshB = "pSphere1", "pSphere2"

    #Add MSelection.
    mSel = OpenMaya.MSelectionList()
    mSel.add(meshA)
    mSel.add(meshB)

    cmds.polyColorPerVertex(
        meshA, colorRGB=[0.0, 0.0, 1.0], alpha=1.0, colorDisplayOption=True)

    #Set Mesh.
    source_mDagPath = OpenMaya.MDagPath()
    collider_mDagPath = OpenMaya.MDagPath()

    # Get DagPath and extend to shape.
    mSel.getDagPath(0, source_mDagPath)
    source_mDagPath.extendToShape()

    # Get DagPath and extend to shape.
    mSel.getDagPath(1, collider_mDagPath)
    collider_mDagPath.extendToShape()

    #Get points.
    collider_MfnMesh = OpenMaya.MFnMesh(collider_mDagPath)
    collider_Pnts = OpenMaya.MFloatPointArray()
    collider_MfnMesh.getPoints(collider_Pnts, OpenMaya.MSpace.kObject)
예제 #18
0
def doit():
  global voxelSize, cubeSize, cubeDict, allLights, amb, useAmbient, useShadows, disableUndos, showCommands, useVoxCtrl, useCubeCtrl, frameRange, verboseOutput, xmin, xmax, ymin, ymax, zmin, zmax, xLocs, yLocs, zLocs

  cubeDict = {}
  shaderDict = {}
  SGDict = {}

  if useAmbient:
      # disable and store all existing lights
      allLights = cmds.sets("defaultLightSet", q=1)
      cmds.sets(clear="defaultLightSet")
      # make an ambient light
      amb = cmds.ambientLight(i=True, ambientShade=0)
  else: allLights = None

  # identify control objects
  sel = cmds.ls(sl=True)
  if len(sel) > 0:
    # filter for polymeshes
    ctrl = cmds.filterExpand(sel, fullPath=0, selectionMask=12)
    cmds.select(cl=1)
    sel = []
    if ctrl == None:
      print "No meshes found in selection, checking scene..."
      # check for object or group named "voxelGeo"
      if cmds.objExists("voxelGeo"):
        cmds.select("voxelGeo")
        sel = cmds.ls(sl=1)
  if len(sel) == 0: # select all dag objects
    cmds.select(ado=True)
    sel = cmds.ls(sl=True)
  if sel == None or sel == []:
    cmds.confirmDialog( title='Mesh selection', message= 'No meshes found in scene.', button=['OK'])
    return 0
  else: # filter for polymeshes
    ctrl = cmds.filterExpand(sel, fullPath=0, selectionMask=12)
    if ctrl == None:
      cmds.confirmDialog( title='Mesh selection', message= 'No meshes found in scene.', button=['OK'])
      return 0

  if disableUndos: cmds.undoInfo(state=False)
  if not showCommands: cmds.scriptEditorInfo(sr=True, sw=True, si=True)
  firstFrame = frameRange[0]
  lastFrame = frameRange[1]
  duration = abs(int(lastFrame-firstFrame))+1

  # deal with backwards frame ranges
  if lastFrame < firstFrame:
    lastFrame -= 1
    frameStep = -1
  else:
    lastFrame += 1
    frameStep = 1

  startTime= cmds.timerX()
  makeProgBar(duration*len(ctrl))
  cmds.progressBar(gMainProgressBar, edit=True, beginProgress=True)
  s = "s" if duration > 1 else ""
  print "Voxelizer animating over", duration, "frame%s..."%s
  print "Press ESC to cancel"

  resetList = []
  directions = [(-1.0, 0.0, 0,0), (0.0, -1.0, 0,0), (0.0, 0.0, -1.0)]
  cubegroup = cmds.group(em=True, n='cubes')
  cmds.select(cl=1)

  #for f in range(firstFrame,lastFrame,frameStep): # for each frame
  for f in range(int(firstFrame),int(lastFrame),int(frameStep)): # for each frame
    stepTime= cmds.timerX()
    if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ):
      return docancel()
    cmds.currentTime(f, edit=True, update=True)

    # get sizes from control objects, if available
    if useVoxCtrl:
      voxelSize = round(cmds.getAttr('voxelScaleCtrl.scaleX'), 3)
    if useCubeCtrl:
      cubeSize = round(cmds.getAttr('cubeScaleCtrl.scaleX'), 3)

    # hide visible cubes
    for x in resetList:
      cmds.setKeyframe(x, at="scale", v=0, t=f)
    resetList = []

    # for every target control object:
    for c in ctrl:
      if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ):
        return docancel()
      cmds.progressBar(gMainProgressBar, edit=True, step=True)
      # if ctrl object is invisible, skip to the next one
      if objIsVisible(c) == 0:
        continue

      # bake textures into verts
      cmds.select(c)
      cmds.polyGeoSampler(sampleByFace=True, computeShadows=useShadows, rs=useShadows)
      
      # set ray starting points
      setLocs(c)
      locArrays = [xLocs, yLocs, zLocs]

      # for each axis:
      for i in range(3):
        # for every gridpoint:
        for loc in locArrays[i]:
          hits = []
          # zap a ray through the object
          rayInt = rayIntersect(c, loc, directions[i])
          hits = rayInt[0]
          hfaces =  rayInt[1]
          for j, x in enumerate(hits):
            # snap hit locations to cubegrid
            x = (roundToFraction(x[0], voxelSize), roundToFraction(x[1], voxelSize), roundToFraction(x[2], voxelSize) )

            # if location isn't in cubeDict: make a new cube
            if x not in cubeDict:
              # add location and new cube to cubeDict
              cubeDict[x] = cmds.polyCube(sz=1, sy=1, sx=1, cuv=4, d=1, h=1, w=1, ch=1)[0]
              cube = cubeDict[x]
              if useShadows:
                # prevent cubes from casting shadows onto the ctrl objs
                cmds.setAttr(cube+".castsShadows", 0)
              cmds.parent(cube, cubegroup)
              # move cube to location
              cmds.xform(cube, t=x)

              # shader coloring method: uses one shader per cube
              shader = cmds.shadingNode("lambert", asShader=1)
              # create a shading group
              shaderSG = cmds.sets(renderable=True, noSurfaceShader=True, empty=True, name=shader+"SG")
              # connect the shader to the shading group
              cmds.connectAttr('%s.outColor'%shader, '%s.surfaceShader'%shaderSG, f=True)
              # add cube to the shaderSG
              shape = cmds.listRelatives(cube, shapes=1)[0]
              cmds.sets('%s'%shape, e=True, fe='%s'%shaderSG)

              shaderDict[cube] = shader
              SGDict[cube] = shaderSG

              # set scale key of 0 on the previous frame
              cmds.setKeyframe(cube, at="scale", v=0, t=(f-1))

            cube = cubeDict[x]
            cubeshape = cmds.listRelatives(cube, shapes=1)[0]

            # add cube to resetList
            resetList.append(cube)

            if len(hfaces) > 0:
              # check the alpha of the face
              alpha = cmds.polyColorPerVertex(c+'.f['+str(hfaces[j])+']', q=True, a=True, cdo=True)
              
              if alpha[0] > 0.5: # if more than half opaque
                # get the color of the face
                fcolor = cmds.polyColorPerVertex(c+'.f['+str(hfaces[j])+']', q=True, rgb=True, cdo=True, nun=True)
                cmds.setKeyframe(shaderDict[cube]+'.colorR', v=fcolor[0])
                cmds.setKeyframe(shaderDict[cube]+'.colorG', v=fcolor[1])
                cmds.setKeyframe(shaderDict[cube]+'.colorB', v=fcolor[2])

                # set a scale key
                cmds.setKeyframe(cube, at="scale", v=cubeSize, t=f, breakdown=0, hierarchy="none", controlPoints=0, shape=0)

                # if previous frame didn't have a scale key, set it to 0
                tempCurTime = cmds.currentTime(q=True)-1
                lastKey = cmds.keyframe(cube, at="scale", q=True, t=(tempCurTime,tempCurTime), valueChange=True)
                if lastKey == None:
                  cmds.setKeyframe(cube, at="scale", v=0, t=(f-1))

    if verboseOutput:
      stepTime = cmds.timerX(st=stepTime)
      totalTime = cmds.timerX(st=startTime)
      print "frame:", cmds.currentTime(q=True), "\tkeyed cubes:", len(resetList), "\ttotal cubes:", len(cubeDict)
      cps = "inf" if stepTime == 0 else round(len(resetList)/stepTime, 2)
      if useVoxCtrl or useCubeCtrl:
        print "\t\tvoxelSize:", voxelSize, "\tcubeSize: ", cubeSize
      print "\t\tstepTime:", round(stepTime, 2), "\ttotal time:", round(totalTime, 2), "\tcubes per second:", cps

  # restore scene state
  if useAmbient:
    if cmds.objExists(amb): cmds.delete(cmds.listRelatives(amb, parent=True)[0])
    cmds.sets(allLights, add="defaultLightSet")
  elif useShadows:
    # turn the cubes' shadows back on
    for x in cubeDict:
      cmds.setAttr(cubeDict[x]+".castsShadows", 1)
  if not showCommands: cmds.scriptEditorInfo(sr=srState, sw=swState, si=siState)
  if disableUndos: cmds.undoInfo(state=True)

  cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
  totalTime = cmds.timerX(st=startTime)
  print("Voxelizer finished: "+str(round(totalTime, 2))+ " seconds ("+str(round(totalTime/60, 2)) + " minutes)")

#promptSetup()

### End Voxelizer 1.0 ###
예제 #19
0
파일: modeling.py 프로젝트: vondras/pymel
def polyColorPerVertex(*args, **kwargs):
    res = cmds.polyColorPerVertex(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    return res
#         - assigns random colors to selected objects
#         - removes colors from selected objects

# Basic Command
# =============================================================================
# import maya.cmds as cmds
# cmds.polyColorPerVertex(colorRGB=[0.8,0.2,0.2], colorDisplayOption=True)

# =============================================================================

import maya.cmds as cmds
import random

myObj = cmds.ls(sl=True)[0]

faceCount = cmds.getAttr(myObj+'.face', size=1)
for face in range(faceCount):
    # cmds.currentTime(face)
    cmds.select(myObj+'.f[%d]' % face)
    myColor = [float(random.random()), float(random.random()), float(random.random())]
    cmds.polyColorPerVertex(colorRGB=myColor, colorDisplayOption=True)

cmds.select(myObj)

# Removing the colors
# =============================================================================

myObjShapes = cmds.ls(sl=True, dag=True, type='mesh')

for myShape in myObjShapes:
    cmds.setAttr(myShape+'.displayColors', 0)
예제 #21
0
파일: cityGen.py 프로젝트: i7677181/scripts
def house(_name, _area, _gap):
    cmds.scale((_area + _gap - 0.5) / 1.5, 4 / 1.8, 6 / 1.8, _name)
    cmds.polyExtrudeFacet(_name + '.f[1]', translateY=3 / 1.8)
    cmds.scale(1, 1, 0, _name + '.f[1]')
    cmds.polyColorPerVertex(r=0.6, g=0.1, b=0.2, a=1, colorDisplayOption=True)
예제 #22
0
def initMesh(name, stepAccuracy = 0.1):
    global accuracy
    accuracy = stepAccuracy
    cmds.polyColorSet(name, colorSet="meshDensitySet_#", clamped=1, rpt='RGB')
    cmds.polyColorPerVertex(name, r = 0.0, g = 0.0, b = 0.0)
예제 #23
0
파일: cityGen.py 프로젝트: i7677181/scripts
def tree(_name, _rgb):
    _height = random.uniform(2, 5)
    trunk(_name, _height, _rgb)
    canopy(_name, _height)
    cmds.polyColorPerVertex(r=0, g=1, b=0, a=1, colorDisplayOption=True)
    delta_z = (z - prev_z) / 3.

    cmds.setAttr(target + ".scaleY", 3. + (delta_y * punch_scale_amount) * 2.)
    cmds.setKeyframe(target + ".scaleY")

    cmds.setAttr(target + ".scaleX", 3. - (delta_y * punch_scale_amount))
    cmds.setKeyframe(target + ".scaleX")

    cmds.setAttr(target + ".scaleZ", 3. - (delta_y * punch_scale_amount))
    cmds.setKeyframe(target + ".scaleZ")

    prev_x = x
    prev_y = y
    prev_z = z

    y_pop *= y_pop_decay
    radius *= radius_decay

    for i in range(vtx_count):
        vtx_id = target + ".vtx[{}]".format(i)
        xyz = cmds.xform(vtx_id, translation=True, worldSpace=True, query=True)
        cmds.polyColorPerVertex(vtx_id, rgb=xyz)
    break

# debug
cmds.currentTime(1, edit=True)
cmds.play()

# clear selection
cmds.select(clear=True)
예제 #25
0
파일: skinFix.py 프로젝트: skarone/PipeL
def createFix():

	updateUser("write")
	
	if len(mc.ls(sl=True)) == 0:
		errorWindow(4)
		return
		
	fromFrame=mc.textField("fromField", q=True, tx=True)
	toFrame=mc.textField("toField", q=True, tx=True)
	fixDescription=mc.textField("fixDescriptionField", q=True, tx=True)
	if 'fix' in fixDescription:
		ftb_skf_benjaminButtons.errorWindow(8)
		return
	if 'FIX' in fixDescription:
		errorWindow(8)
		return
	if 'Fix' in fixDescription:
		errorWindow(8)
		return
	
	try:
		selectedMesh = (mc.ls(sl=True))[0]
	except:
		errorWindow(1)
		return
	
	if '_fix' in selectedMesh: 
		errorWindow(2)
		return

	selectedMeshNNS = selectedMesh.split(':')[1]

	cTime = mc.currentTime(q=True)
	
	if mc.objExists(selectedMesh+'_goalFix'):
		fixGroup = selectedMesh+'_fixBlends_GRP'
		goalFix = selectedMesh+'_goalFix'
		allFixes = mc.ls('*:*_fix*', typ = 'transform')
		fixList = []
		for fix in allFixes:
			if 'Inverted' not in fix:
				if 'SH' not in fix:
					if 'GRP' not in fix:
						if 'fixed' not in fix:
							if '_grp' not in fix:
								if '_f_' not in fix:
									fixList.append(int(fix.split('fix')[1]))
		bsCount = max(fixList)
	
	else: bsCount = 0
	
	#Desactiva temporalmente los fixes previos, y crea el newFix
	
	try:
		mc.setAttr(selectedMesh+'_goalFixBS'+'.'+selectedMeshNNS+'_goalFix', 0)
	except: 0
		
	newFix = mc.duplicate(selectedMesh, n=selectedMesh+'_'+formatText(fixDescription)+'_fix'+str(bsCount+1))[0]
	mc.polyColorPerVertex(newFix, r=0.3376, g=0.3674, b=0.6203, a=1, cdo=True)
	newFixInverted = cvShapeInverter.invert(selectedMesh, newFix, newFix+'Inverted')
	newFixInvertedNNS = newFixInverted.split(':')[1]
	mc.setAttr(newFixInverted+'.visibility', 0)
	
	mc.select(newFix, r=True)
	mc.addAttr(ln="fixDescription", dt='string')
	mc.addAttr(ln="fixFrame")
	mc.setAttr(newFix+'.fixDescription', fixDescription, type='string')
	mc.setAttr(newFix+'.fixFrame', cTime)
	
	try: 
		mc.setAttr(selectedMesh+'_goalFixBS'+'.'+selectedMeshNNS+'_goalFix', 1)
	except: 0
	
	#Prueba si existe el mesh goalFix. Si existe, agrega el newFixInverted al nodo blendshape existente. Si no existe, lo crea, crea el nodo blendshape con el newFixInverted.
	if mc.objExists(selectedMesh+'_goalFix'):
		fixGroup = selectedMesh+'_fixBlends_GRP'
		goalFix = selectedMesh+'_goalFix'
		allFixes = mc.ls('*:*_fix*',typ = 'transform')
		fixList = []
		for fix in allFixes:
			if 'Inverted' not in fix:
				if 'SH' not in fix:
					if 'GRP' not in fix:
						if 'fixed' not in fix:
							if '_grp' not in fix:
								if '_f_' not in fix:
									fixList.append(int(fix.split('fix')[1]))
		bsCount = max(fixList)
		mc.blendShape(selectedMesh+'FixesBS', edit=True, t=(goalFix, bsCount+1, newFixInverted, 1.0))
 
	else:
		goalFix = mc.duplicate(newFixInverted, n=selectedMesh+'_goalFix')[0]
		
		if mc.objExists(selectedMesh+'_goalFixBS') == False:
			mc.select(goalFix, r=True)
			mc.select(selectedMesh, add=True)
			goalFixBS = mc.blendShape(foc=True, n=selectedMesh+'_goalFixBS')[0] 
			mc.setAttr(goalFixBS+'.'+selectedMeshNNS+'_goalFix', 1)
		
		mc.setAttr(selectedMesh+'_goalFix.visibility', 0)
		fixGroup = mc.group(empty=True, name=selectedMesh+'_fixBlends_GRP', parent=selectedMesh)
		mc.parent(fixGroup, world=True)
		mc.parent(selectedMesh+'_goalFix', selectedMesh+'_fixBlends_GRP')
	
		#Crea el nodo blendshape con newFixInverted al goalFix
		mc.select(newFixInverted, r=True)
		mc.select(goalFix, add=True)
		mc.blendShape(foc=True, n=selectedMesh+'FixesBS')

	#Agrega el newFix y el newFixInverted al grupo fixBlends_GRP.
	mc.parent(newFix, fixGroup)
	mc.parent(newFixInverted, fixGroup)
	if mc.checkBox("noBegCheckBox", q=True, value=True) == False: 
		mc.setKeyframe(selectedMesh+'FixesBS', at=newFixInvertedNNS, v=1)
		mc.setKeyframe(selectedMesh+'FixesBS', at=newFixInvertedNNS, t=cTime-int(fromFrame), v=0)
		
	if mc.checkBox("noBegCheckBox", q=True, value=True) == True:
		mc.setKeyframe(selectedMesh+'FixesBS', at=newFixInvertedNNS, v=1)
		
	if mc.checkBox("noEndCheckBox", q=True, value=True) == False: 
		mc.setKeyframe(selectedMesh+'FixesBS', at=newFixInvertedNNS, t=cTime+int(toFrame), v=0)
		
	mc.select(newFix, r=True)
	mc.setAttr(selectedMesh+'.visibility', 0)
예제 #26
0
파일: cityGen.py 프로젝트: i7677181/scripts
def setColor(_rgb):
    shape = cmds.select(all=True)
    shape = cmds.polyColorPerVertex(rgb=_rgb, colorDisplayOption=True)
def ImportToMaya(vertexArray, polygonConnects, uvArray, texturePath, texture):
    global g_Mesh_Index

    printMessage("Creating mesh...")
    polygonCounts = OpenMaya.MIntArray(polygonConnects.length() / 3, 3)
    mesh = OpenMaya.MFnMesh()
    transform = mesh.create(
        vertexArray.length(), polygonCounts.length(), vertexArray,
        polygonCounts, polygonConnects
    )

    printDebug("connects cnt {}".format(polygonConnects.length()))
    printDebug("cnt {}".format(polygonCounts.length()))
    printDebug("u cnt {}".format(uvArray[0].length()))
    printDebug("v cnt {}".format(uvArray[1].length()))

    # UV map.
    printMessage("Mapping UVs...")
    mesh.setUVs(uvArray[0], uvArray[1])

    try:
        mesh.assignUVs(polygonCounts, polygonConnects)
    except RuntimeError:
        printDebug("mesh.assignUVs() failed. Assign manually...")
        for i in range(0, polygonConnects.length()):
            try:
                mesh.assignUV(i / 3, i % 3, polygonConnects[i])
            except RuntimeError:
                printMessage("AssignUV failed: " + 
                            "[{}] = {}".format(i, polygonConnects[i]))

    # Rename mesh.
    printMessage("Renaming mesh...")
    transformDagPath = OpenMaya.MDagPath()
    OpenMaya.MDagPath.getAPathTo(transform, transformDagPath)
    meshName = cmds.rename(
        transformDagPath.fullPathName(), "NinjaMesh_{}".format(g_Mesh_Index)
    )
    g_Mesh_Index = g_Mesh_Index + 1

    # Apply textures.
    printMessage("Applying textures...")
    shader = cmds.shadingNode(
        "lambert", name="NinjaTexture_{}".format(g_Mesh_Index), asShader=True
    )

    cmds.select(meshName)
    cmds.hyperShade(assign=shader)

    colorMap = cmds.shadingNode(
        "file", name="{}_colorMap".format(texture), asTexture=True
    )

    cmds.connectAttr(
        "{}.outColor".format(colorMap), "{}.color".format(shader)
    )
    cmds.setAttr(
        "{}.fileTextureName".format(colorMap),
        "{}/{}".format(texturePath, texture), type='string'
    )

    # Set vertex color to White.
    printMessage("Forcing vertex color to white...")
    cmds.select(meshName)
    cmds.polyColorPerVertex(cdo=True, rgb=[1, 1, 1])

    # Apply transformations.
    printMessage("Applying transformations...")
    cmds.setAttr("{}.rotateX".format(meshName), g_ninjarotX)
    cmds.setAttr("{}.rotateY".format(meshName), g_ninjarotY)
    cmds.setAttr("{}.rotateZ".format(meshName), g_ninjarotZ)
    cmds.setAttr("{}.scaleX".format(meshName), mdlscaler)
    cmds.setAttr("{}.scaleY".format(meshName), mdlscaler)
    cmds.setAttr("{}.scaleZ".format(meshName), mdlscaler)

    # Freeze transformations.
    printMessage("Zeroing new transform values...")
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)

    # Scale UVs.
    printMessage("Scaling UVs...")
    uvs = cmds.polyListComponentConversion(meshName, tuv=True)
    cmds.select(uvs)
    cmds.polyEditUV(su=uvscaler, sv=uvscaler*g_flipUV)

    # Normalize UV.
    if g_normalizeUV:
        printMessage("Normalizing UVs...")
        cmds.polyNormalizeUV(nt=1, pa=True, centerOnTile=True)

    # Merge duplicates.
    printMessage("Removing duplicate vertex...")
    cmds.select(cl=True)
    cmds.select(meshName)
    cmds.polyMergeVertex(d=0.01, am=True, ch=1)
    cmds.polyMergeUV(d=0.01, ch=True)

    # Reverse normals (First met in MWR)
    if g_reverseNormals:
        printMessage("Reversing normals...")
        cmds.select(cl=True)
        cmds.select(meshName)
        cmds.polyNormal(meshName, ch=1)

    cmds.select(cl=True)
    print("Import done for mesh '{}'".format(meshName))
    def testStaticMeshAnimColor(self):
        MayaCmds.currentTime(1)
        MayaCmds.polyPlane(sx=1, sy=1, name='poly')
        MayaCmds.polyColorPerVertex(r=0.0,g=1.0,b=0.0, cdo=True)
        MayaCmds.setKeyframe(["polyColorPerVertex1"])
        MayaCmds.currentTime(10)
        MayaCmds.polyColorPerVertex(r=0.0,g=0.0,b=1.0, cdo=True)
        MayaCmds.setKeyframe(["polyColorPerVertex1"])

        MayaCmds.currentTime(1)
        MayaCmds.polyPlane(sx=1, sy=1, name='subd')
        MayaCmds.select('subdShape')
        MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool',
            defaultValue=True)
        MayaCmds.polyColorPerVertex(r=1.0,g=1.0,b=0.0, cdo=True)
        MayaCmds.setKeyframe(["polyColorPerVertex2"])
        MayaCmds.currentTime(10)
        MayaCmds.polyColorPerVertex(r=1.0,g=0.0,b=0.0, cdo=True)
        MayaCmds.setKeyframe(["polyColorPerVertex2"])

        self.__files.append(util.expandFileName('animColorSets.abc'))
        MayaCmds.AbcExport(j='-fr 1 10 -root poly -root subd -wcs -file ' +
            self.__files[-1])

        MayaCmds.AbcImport(self.__files[-1], mode='open')

        MayaCmds.select('polyShape')
        sel = OpenMaya.MSelectionList()
        OpenMaya.MGlobal.getActiveSelectionList(sel)
        obj = OpenMaya.MObject()
        sel.getDependNode(0, obj)
        fn = OpenMaya.MFnMesh(obj)

        MayaCmds.currentTime(1)
        colArray = OpenMaya.MColorArray()
        fn.getFaceVertexColors(colArray)
        self.failUnless(colArray.length() == 4)
        for x in range(colArray.length()):
            self.failUnlessAlmostEqual(colArray[x].r, 0)
            self.failUnlessAlmostEqual(colArray[x].g, 1)
            self.failUnlessAlmostEqual(colArray[x].b, 0)

        MayaCmds.currentTime(5)
        colArray = OpenMaya.MColorArray()
        fn.getFaceVertexColors(colArray)
        self.failUnless(colArray.length() == 4)
        for x in range(colArray.length()):
            self.failUnless(colArray[x].r == 0)
            self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047)
            self.failUnlessAlmostEqual(colArray[x].b, 0.444444447756)

        MayaCmds.currentTime(10)
        colArray = OpenMaya.MColorArray()
        fn.getFaceVertexColors(colArray)
        self.failUnless(colArray.length() == 4)
        for x in range(colArray.length()):
            self.failUnlessAlmostEqual(colArray[x].r, 0)
            self.failUnlessAlmostEqual(colArray[x].g, 0)
            self.failUnlessAlmostEqual(colArray[x].b, 1)

        self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1)
        MayaCmds.select('subdShape')
        sel = OpenMaya.MSelectionList()
        OpenMaya.MGlobal.getActiveSelectionList(sel)
        obj = OpenMaya.MObject()
        sel.getDependNode(0, obj)
        fn = OpenMaya.MFnMesh(obj)

        MayaCmds.currentTime(1)
        colArray = OpenMaya.MColorArray()
        fn.getFaceVertexColors(colArray)
        self.failUnless(colArray.length() == 4)
        for x in range(colArray.length()):
            self.failUnlessAlmostEqual(colArray[x].r, 1)
            self.failUnlessAlmostEqual(colArray[x].g, 1)
            self.failUnlessAlmostEqual(colArray[x].b, 0)

        MayaCmds.currentTime(5)
        colArray = OpenMaya.MColorArray()
        fn.getFaceVertexColors(colArray)
        self.failUnless(colArray.length() == 4)
        for x in range(colArray.length()):
            self.failUnlessAlmostEqual(colArray[x].r, 1)
            self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047)
            self.failUnlessAlmostEqual(colArray[x].b, 0)

        MayaCmds.currentTime(10)
        colArray = OpenMaya.MColorArray()
        fn.getFaceVertexColors(colArray)
        self.failUnless(colArray.length() == 4)
        for x in range(colArray.length()):
            self.failUnlessAlmostEqual(colArray[x].r, 1)
            self.failUnlessAlmostEqual(colArray[x].g, 0)
            self.failUnlessAlmostEqual(colArray[x].b, 0)
예제 #29
0
def run():
    try:
        selection = mc.ls(selection=True)  #list of selected
        for surface in selection:
            print 'working on surface:', surface
            mc.select(surface)
            mc.hyperShade(smn=True)  #find shaders attached to surface
            shaders = mc.ls(selection=True)  #list from selected
            print 'there are ', len(shaders), 'shaders:', shaders
            cmdList = []
            for singleSh in shaders:  #for each shader attach to the surface
                diffClr = singleSh + '.color'
                incClr = singleSh + '.incandescence'
                transClr = singleSh + '.transparency'
                shDiff = mc.getAttr(diffClr)
                shInc = mc.getAttr(incClr)
                shTrans = mc.getAttr(transClr)
                incGain = 1.8  #increased this till the resulting vertex color looked close to the shader
                trans = 0.0  #opaque
                modInc = []

                for foo in range(3):  #goofy tuple data "adjustment"
                    modInc.append((shInc[0][foo] * incGain))
                    if (shTrans[0][foo] > 0.0) or (
                            shTrans[0][foo] > trans
                    ):  #if there is any transparency set to the largest value
                        trans = shTrans[0][foo]

                trans = 1.0 - trans  #flip value for shaders -> vertex alpha
                shColor = ((shDiff[0][0] + modInc[0]),
                           (shDiff[0][1] + modInc[1]),
                           (shDiff[0][2] + modInc[2]))
                print 'working on shader:', singleSh, ' with a final color of :', shColor, " alpha:", trans
                mc.select(singleSh)
                mc.hyperShade(
                    objects=singleSh
                )  #returns a selection of surfaces, can include more than selected surface
                comps = mc.ls(
                    selection=True)  #list of components with singleSh
                print comps
                mc.select(cl=True)  #clear selection
                surfaceOnly = [
                ]  #new var of components on the selected surface ONLY
                for foo in comps:
                    if foo == mc.listRelatives(
                            surface
                    )[0]:  #if the entire surface has this shader, the surface"Shape" is returned from mc.hyperShade
                        surfaceOnly.append(surface)  #add to list
                    elif foo.startswith(
                            surface):  #if part of parent surface, add to list
                        surfaceOnly.append(foo)
                cmdTuple = (
                    shColor, trans, surfaceOnly
                )  #combo of color, transparency, and componets to apply current shader to
                cmdList.append(cmdTuple)
            mc.select(surface)
            mc.hyperShade(
                assign='initialShadingGroup')  #reset surface to lambert1
            for cmd in cmdList:  #apply data to geo
                print 'color to be applied:', cmd[0]
                print 'surfaces and components to be vertpainted', cmd[2]
                mc.select(cmd[2])
                mc.polyColorPerVertex(rgb=cmd[0], a=cmd[1], cdo=True)
    except:
        print 'Error'
    finally:
        print "shader to vertex coloring complete"