def borderEdge(*args):
    if(cmds.polyOptions(q=True, db=True)[0]):
        cmds.polyOptions(db=False)
        print'Border Edges Off'
    else:
        cmds.polyOptions(db=True)
        print'Border Edges On'
Example #2
0
	def displayCB(self, args) :
		state = cmds.checkBox(self.window+'DisplayCheck', q=True, v=True)
		mesh = cmds.sets(self.objectSet, q=True)
		for m in mesh :
			if cmds.objectType(m) != 'mesh' :
				continue
			cmds.polyOptions(m, colorShadedDisplay=bool(state))
Example #3
0
def dynamic_compare(mesh, target, clamp=1, saturation=1):
    """
    Compares two meshes dynamically.
    This requires that the meshCompare plugin be compiled and available in the plugin path.

    :param mesh: The mesh you want to view the changes on.
    :param target: The mesh you are comparing against
    :param clamp: The value to clamp against. All values be scaled accordingly.
                  i.e if you clamp at 10, absolute red will be 10 units
    :param saturation: The maximum saturation value to use
    """

    loaded = mc.pluginInfo('meshCompare', query=True, loaded=True)
    if not loaded:
        try:
            mc.loadPlugin('meshCompare')
        except:
            mc.error("Could not load meshCompare plugin."
                     "Please make sure it is compiled and in your plugin path")

    mesh = get_shape(mesh)
    target = get_shape(target)

    mesh_path = mesh.fullPathName()
    target_path = target.fullPathName()

    mc.polyOptions(mesh_path, colorShadedDisplay=True)
    deformer = mc.deformer(mesh_path, type='meshCompare')[0]
    mc.polyOptions(mesh_path, colorShadedDisplay=True)

    mc.connectAttr('%s.outMesh' % target_path, '%s.target' % deformer)

    mc.setAttr('%s.saturation' % deformer, saturation)
    mc.setAttr('%s.clamp' % deformer, clamp)
Example #4
0
def fxCombine(merge=False):
    targets = m.ls(sl=True, l=True)

    if not targets:
        return

    parent = m.listRelatives(targets[0], p=True, pa=True)

    try:
        combineResult = m.polyUnite(targets)
    except RuntimeError:
        m.error('Invalid selection for combine operation.')
        return

    if parent:
        combineResult = m.parent(combineResult[0], parent[0])

    m.delete(combineResult[0], ch=True)

    for t in targets:
        if m.objExists(t):
            m.delete(t)

    finalObject = m.rename(combineResult[0], getShortName(targets[0]))
    m.select(finalObject)

    if merge:
        meval('performPolyMerge 0')
        m.polyOptions(finalObject, displayBorder=True, sizeBorder=4)
        m.select(finalObject)
Example #5
0
    def restoreDisplay(self):
        m.polyOptions(self.mesh, colorShadedDisplay=self.vcDisplay)
        m.polyOptions(self.mesh, colorMaterialChannel=self.vcColorChannel)

        m.polyOptions(self.mesh, displayNormal=self.normalDisplay[0], facet=self.normalDisplay[1])
        m.polyOptions(self.mesh, displayNormal=self.normalDisplay[0], point=self.normalDisplay[2])
        m.polyOptions(self.mesh, displayNormal=self.normalDisplay[0], pointFacet=self.normalDisplay[3])
Example #6
0
def display_edges(show_hard=True):
    edge = {"hardEdge": True} if show_hard else {"softEdge": True}
    is_hard_edge = cmds.polyOptions(gl=True, q=True, **edge)
    if not all(is_hard_edge):
        cmds.polyOptions(gl=True, **edge)
    else:
        cmds.polyOptions(gl=True, allEdges=True)
def normals(*args):
    if(cmds.polyOptions(q=True, dn=True)[0]):
        cmds.polyOptions(dn=False)
        print'Normals Off'
    else:
        cmds.polyOptions(dn=True)
        print'Normals On'
Example #8
0
def make_scene():
    cmds.file(new=True, f=True)
    cmds.polyCube(name='cube')
    cmds.polyOptions(displayNormal=True)
    mel.eval('displayStyle -textured;')
    mel.eval('displayStyle -wireframeOnShaded;')
    cmds.file(rename='D:\\CubeMesh.ma')
    cmds.file(type='mayaAscii', save=True)
def make_scene():
    cmds.file(new=True, f=True)
    cmds.polyPlane(w=5, sw=2, h=5, sh=1, name='square')
    mel.eval("displayStyle -textured")
    mel.eval("displayStyle -wireframeOnShaded")
    cmds.file(rename='TwoPolygonMesh.ma')
    cmds.file(type='mayaAscii', save=True)
    cmds.polyOptions(colorShadedDisplay=True, colorMaterialChannel='none')
Example #10
0
def static_compare(mesh, target, clamp=10, world=True):
    """
    Compares two meshes on a given static frame.
    Sets a vertex color value to show the distance values.
    
    :param mesh: The name or path to the mesh to visualize on.
    :param target: The name or path of the mesh we are comparing against.
    :param clamp: The value to clamp against. All values be scaled accordingly.
    :param world: Whether to compare in world space or object space.
    """
    # Get the Dag Paths to the mesh shapes
    mesh = get_shape(mesh)
    target = get_shape(target)

    # Turn on visualization of the vertex colors on the shape
    mesh_path = mesh.fullPathName()
    mc.polyOptions(mesh_path, colorShadedDisplay=True)

    # Get Mesh objects from the shapes.
    mesh_mesh = om.MFnMesh(mesh)
    target_mesh = om.MFnMesh(target)

    # For each mesh, get their points
    space = om.MSpace.kWorld if world else om.MSpace.kObject
    mesh_points = mesh_mesh.getPoints(space)
    target_points = target_mesh.getPoints(space)
    print("mesh points = ", len(mesh_points))
    print("target points = ", len(target_points))

    colors = om.MColorArray()
    ids = []

    # Loop through to calculate the colors
    for i, mpoint in enumerate(mesh_points):
        tpoint = target_points[i]

        # Get the distance between the vertices.
        distance = math.sqrt(((mpoint.x - tpoint.x)**2) +
                             ((mpoint.y - tpoint.y)**2) +
                             ((mpoint.z - tpoint.z)**2))

        # If our distance is not zero, then process it
        if distance:
            # First scale according to the clamp value
            scaled = distance / clamp
            # Then clamp it off at 1
            clamped = min(scaled, 1)
            # Finally we only want half its value since our base color is 50% grey
            distance = clamped / 2.0

        # Start from 50% grey and bias to the red channel as distance grows
        color = om.MColor((0.5 + distance, 0.5 - distance, 0.5 - distance))

        colors.append(color)
        ids.append(i)

    # Apply the colors
    mesh_mesh.setVertexColors(colors, ids)
Example #11
0
def wireframe_backface_culling():
    """
    Toggles backface culling on/off.
    """
    is_wire_culling = cmds.polyOptions(gl=True, q=True, wireBackCulling=True)
    if not all(is_wire_culling):
        cmds.polyOptions(gl=True, wireBackCulling=True)
    else:
        cmds.polyOptions(gl=True, backCulling=True)
Example #12
0
def normDispl(*args):
	chkNorm = cmds.checkBox("normsChck", q=True, v=True)
	
	if (chkNorm==1):
		displ=1
		
	else:
		displ=0
	
	cmds.polyOptions(dn=displ)
Example #13
0
def toggleSoftEdges():

    alreadySoft = cmds.polyOptions(q=True,
                                   allEdges=True)  # Queries edge normals

    # Toggling edges
    if (alreadySoft[0] == True):
        cmds.polyOptions(softEdge=True)
    else:
        cmds.polyOptions(allEdges=True)
Example #14
0
def normDispl(*args):
	chkNorm = cmds.checkBox("normsChck", q=True, v=True)
	
	if (chkNorm==1):
		displ=1
		
	else:
		displ=0
	
	cmds.polyOptions(dn=displ)
Example #15
0
def applyRandomColor(obj):
	'''
	Apply Random Color definition
	'''

	red = random.uniform(0, 1)
	green = random.uniform(0, 1)
	blue = random.uniform(0, 1)
	cmds.polyColorPerVertex(obj, r=red, g=green, b=blue, a=1, cdo=True)
	cmds.polyOptions(obj, colorMaterialChannel='diffuse')
Example #16
0
def applyToSelection(value, *args):
    sel = cmds.ls(sl=True, l=True)
    if len(sel) < 1:
        cmds.warning('Nothing is selected.')
    else:
        for s in sel:

            if value == 'diffuse_color':

                colorFromUI = cmds.colorInputWidgetGrp("prman_color_widget",
                                                       rgb=True,
                                                       q=True)

                if cmds.attributeQuery("rmanCdiffuse_color", n=s,
                                       exists=True) == 0:
                    cmds.addAttr(s, ln="rmanCdiffuse_color", at="float3")
                    cmds.addAttr(s,
                                 ln="rmanCdiffuse_colorR",
                                 at="float",
                                 p="rmanCdiffuse_color")
                    cmds.addAttr(s,
                                 ln="rmanCdiffuse_colorG",
                                 at="float",
                                 p="rmanCdiffuse_color")
                    cmds.addAttr(s,
                                 ln="rmanCdiffuse_colorB",
                                 at="float",
                                 p="rmanCdiffuse_color")

                cmds.setAttr(s + ".rmanCdiffuse_color",
                             colorFromUI[0],
                             colorFromUI[1],
                             colorFromUI[2],
                             type="double3")

                if cmds.checkBox("applyVertexColor_checkbox", v=True,
                                 q=True) == 1:
                    cmds.polyColorPerVertex(s,
                                            r=colorFromUI[0],
                                            g=colorFromUI[1],
                                            b=colorFromUI[2],
                                            a=1,
                                            cdo=True)
                    cmds.polyOptions(s, colorMaterialChannel='diffuse')

            else:

                valueFromUI = cmds.floatSliderGrp('floatSliderGrp_' + value,
                                                  value=True,
                                                  q=True)

                if cmds.attributeQuery("rmanF" + value, n=s, exists=True) == 0:
                    cmds.addAttr(s, ln="rmanF" + value, at="float", dv=0)

                cmds.setAttr(s + ".rmanF" + value, valueFromUI)
Example #17
0
	def addObject(self, args) :
		self.saveSelection()
		if len(self.selected) == 0 :
			return
		cmds.select(hi=True)
		mesh = cmds.ls(sl=True, type='mesh')
		if len(mesh) > 0 :
			cmds.sets(mesh, e=True, addElement=self.objectSet)
		self.refreshObjectList()
		state = cmds.checkBox(self.window+'DisplayCheck', q=True, v=True)
		cmds.polyOptions(mesh, colorShadedDisplay=bool(state))
		self.revertSelection()
Example #18
0
    def restoreDisplay(self):
        m.polyOptions(self.mesh, colorShadedDisplay=self.vcDisplay)
        m.polyOptions(self.mesh, colorMaterialChannel=self.vcColorChannel)

        m.polyOptions(self.mesh,
                      displayNormal=self.normalDisplay[0],
                      facet=self.normalDisplay[1])
        m.polyOptions(self.mesh,
                      displayNormal=self.normalDisplay[0],
                      point=self.normalDisplay[2])
        m.polyOptions(self.mesh,
                      displayNormal=self.normalDisplay[0],
                      pointFacet=self.normalDisplay[3])
Example #19
0
    def closeEvent(self, event):
        # 他のオブジェクトを選択している可能性もあるのでそのリストを取得しておき、
        # 選択をターゲットに置き換えておく
        selList = mc.ls(sl=True)
        mc.select(self.targetObj.fullPathName(), replace=True)

        # ウィンドウのインスタンスをdeleteすることで登録したscriptJobもまとめて解除しておく
        self.deleteInstances()

        # ノード名変更のコールバックを削除
        if self.callbackID_nameChanged:
            om2.MNodeMessage.removeCallback(self.callbackID_nameChanged)
            self.callbackID_nameChanged = None

        # ターゲットオブジェクトの全colorSetリストを取得
        allColorSetList = self.targetObjMesh.getColorSetNames()

        # tmpColorSetを削除する
        if "tmpColorSet_R" in allColorSetList:
            mc.polyColorSet(delete=True, colorSet="tmpColorSet_R")

        if "tmpColorSet_G" in allColorSetList:
            mc.polyColorSet(delete=True, colorSet="tmpColorSet_G")

        if "tmpColorSet_B" in allColorSetList:
            mc.polyColorSet(delete=True, colorSet="tmpColorSet_B")

        if "tmpColorSet_A" in allColorSetList:
            mc.polyColorSet(delete=True, colorSet="tmpColorSet_A")

        # displayColorsを元に戻しておく
        mc.setAttr("%s.displayColors" % self.targetObjMesh.fullPathName(),
                   self.attrDispColor)

        # colorMaterialChannelとmaterialBlendを元に戻しておく
        mc.polyOptions(colorMaterialChannel=self.pOption_matChl, gl=False)
        mc.polyOptions(materialBlend=self.pOption_matBld, gl=False)

        # 最後にヒストリもきれいにしておく
        historyDelete(self.targetObj.fullPathName(), False)

        # 選択を戻す
        mc.select(selList, replace=True)
def vertColorAction(action='apply',rgba=[1,1,1,1],channelMatrix=[],blendMix=None,sel=None):
    '''Wrapper Function to aid in vertex color actions - handles selection data for you to get around memory leak'''

    #cmds.progressWindow( title='Coloring Verts',progress=0,	status='Processing:',isInterruptable=False )
    cmds.undoInfo(openChunk=True)
    if sel == None :
        sel = selection()
    try:
        for obj in list(sel.selection.keys()):
            vertDict = sel.selection[obj][5]
            cmds.polyOptions(obj, cs=1, cm='none')
            progressCount = 1
            #Added the plus one so the dialogue to the user never reaches full  -  its a perception thing
            #cmds.progressWindow(edit=True,max=len(vertDict.keys())+1)
            for colorKey, vertFaceList in list(vertDict.items()):
                #cmds.progressWindow( edit=True, progress=progressCount, status=('Processing - ' + str(len(vertFaceList)) + ' - Vertex Faces'))
                if action == 'apply':
                    vertexColorApply(vertFaceList,rgba[0],rgba[1],rgba[2],rgba[3])
                if action == 'add':
                    vertexColorAdd(vertFaceList,colorKey,rgba[0],rgba[1],rgba[2])
                if action == 'tint':
                    vertexColorTint(vertFaceList,colorKey,rgba[0],rgba[1],rgba[2],rgba[3])
                if action == 'gamma':
                    vertexColorGamma(vertFaceList,colorKey,rgba[0],rgba[1],rgba[2])
                if action == 'blend':
                    if blendMix == None:
                        blendMix = cmds.floatSliderGrp('blendMixSlider',q=1,v=1)
                    vertexColorBlend(vertFaceList,colorKey,rgba[0],rgba[1],rgba[2],blendMix)
                if action == 'average':
                    vertexColorAvg(vertFaceList,colorKey,list(vertDict.keys()))
                if action == 'channel':
                    vertexColorChannelMix(vertFaceList,colorKey,channelMatrix)
                if action == 'channelAlpha':
                    vertexColorChannelMixAlpha(vertFaceList,colorKey,channelMatrix)

                progressCount = progressCount + 1

            cmds.delete(obj,ch=1)
    except Exception:
        traceback.print_exc()
    finally:
        cmds.undoInfo(closeChunk=True)
Example #21
0
    def backupDisplay(self):
        self.vcDisplay = m.polyOptions(q=True, colorShadedDisplay=True)[0]
        self.vcColorChannel = m.polyOptions(q=True, colorMaterialChannel=True)[0]

        self.normalDisplay = (
            m.polyOptions(self.mesh, q=True, displayNormal=True)[0],
            m.polyOptions(self.mesh, q=True, facet=True)[0],
            m.polyOptions(self.mesh, q=True, point=True)[0],
            m.polyOptions(self.mesh, q=True, pointFacet=True)[0],
        )
Example #22
0
    def backupDisplay(self):
        self.vcDisplay = m.polyOptions(q=True, colorShadedDisplay=True)[0]
        self.vcColorChannel = m.polyOptions(q=True,
                                            colorMaterialChannel=True)[0]

        self.normalDisplay = (
            m.polyOptions(self.mesh, q=True, displayNormal=True)[0],
            m.polyOptions(self.mesh, q=True, facet=True)[0],
            m.polyOptions(self.mesh, q=True, point=True)[0],
            m.polyOptions(self.mesh, q=True, pointFacet=True)[0],
        )
Example #23
0
    def processDisplay(self):
        if not self.params.dispCurve:
            return

        m.polyOptions(self.meshTransform, colorShadedDisplay=True)
        m.polyOptions(self.meshTransform, colorMaterialChannel='none')
        m.polyOptions(self.meshTransform, displayNormal=True, point=True)

        colors = []
        verticesIds = []
        for v in self.vertices:
            scaledAbsCurvature = v.absCurvature / self.params.curveScale
            color = om.MColor((scaledAbsCurvature, scaledAbsCurvature, scaledAbsCurvature)) if v.isRougher(self.params.curveThresh) else om.MColor((0.0, 1.0, 0.0))
            colors.append(color)
            verticesIds.append(v.id)

        self.meshFn.setVertexColors(colors, verticesIds)
Example #24
0
    def processDisplay(self):
        if not self.params.dispCurve:
            return

        m.polyOptions(self.meshTransform, colorShadedDisplay=True)
        m.polyOptions(self.meshTransform, colorMaterialChannel='none')
        m.polyOptions(self.meshTransform, displayNormal=True, point=True)

        colors = []
        verticesIds = []
        for v in self.vertices:
            scaledAbsCurvature = v.absCurvature / self.params.curveScale
            color = om.MColor((scaledAbsCurvature, scaledAbsCurvature,
                               scaledAbsCurvature)) if v.isRougher(
                                   self.params.curveThresh) else om.MColor(
                                       (0.0, 1.0, 0.0))
            colors.append(color)
            verticesIds.append(v.id)

        self.meshFn.setVertexColors(colors, verticesIds)
#Mike Marra
#Intial Maya Setup for UDK Script
#Sets up the preferences commonly used in maya for working with UDK
'''Run this script on a new scene'''

import maya.cmds as cmds
# Enables polygon borders and sets the edge width to 4 #
cmds.polyOptions(np=True, db=True, sb=4)
# Sets Undo amount to infinite #
cmds.undoInfo(infinity=True)
# Makes the viewcube visible #
cmds.viewManip(visible=True)
cmds.optionVar(iv=('viewCubeShowCube', 1))
# Sets the Z axis to be up #
cmds.upAxis(ax='z', rv=True)
# Sets the near and far clip for the persp view camera #
cmds.setAttr('perspShape.nearClipPlane', 1)
cmds.setAttr('perspShape.farClipPlane', 100000)
# Sets the near and far clip for the top view camera #
cmds.setAttr('topShape.nearClipPlane', 1)
cmds.setAttr('topShape.farClipPlane', 100000)
# Sets the near and far clip for the front view camera #
cmds.setAttr('frontShape.nearClipPlane', 1)
cmds.setAttr('frontShape.farClipPlane', 100000)
# Sets the near and far clip for the side view camera #
cmds.setAttr('sideShape.nearClipPlane', 1)
cmds.setAttr('sideShape.farClipPlane', 100000)
# To change the grid spacing and subdivisions #
cmds.grid(spacing=16, d=1)
# To change the grid length and width #
cmds.grid(size=512)
	def NorLenSub(self):
		cmds.polyOptions( r=True, sn=0.70710678118 )
	def ToggleNorShow(self):
		if cmds.polyOptions(q=True, dn=True )[0]:
			cmds.polyOptions( dn=False,pt=True )
		else:
			cmds.polyOptions( dn=True,pt=True )
Example #28
0
def static_compare(mesh, target, clamp=1, world=False, saturation=0.8):
    """
    Compares two meshes on a given static frame.
    Sets a vertex color value to show the distance values.
    Colors will go from green at the least to red at the point of clamping.
    
    :param mesh: The name or path to the mesh to visualize on.
    :param target: The name or path of the mesh we are comparing against.
    :param clamp: The value to clamp against. All values be scaled accordingly.
                  i.e if you clamp at 10, absolute red will be 10 units
    :param world: Whether to compare in world space or object space.
    :param saturation: The maximum saturation value to use
    """
    # Get the Dag Paths to the mesh shapes
    mesh = get_shape(mesh)
    target = get_shape(target)

    # Turn on visualization of the vertex colors on the shape
    mesh_path = mesh.fullPathName()
    mc.polyOptions(mesh_path, colorShadedDisplay=True)

    # Get Mesh objects from the shapes.
    mesh_mesh = om.MFnMesh(mesh)
    target_mesh = om.MFnMesh(target)

    # For each mesh, get their points
    space = om.MSpace.kWorld if world else om.MSpace.kObject
    mesh_points = mesh_mesh.getPoints(space)
    target_points = target_mesh.getPoints(space)

    if len(mesh_points) != len(target_points):
        raise RuntimeError("Meshes do not have the same vertex count")

    colors = om.MColorArray()
    ids = []

    # Loop through to calculate the colors
    for i, mpoint in enumerate(mesh_points):
        tpoint = target_points[i]

        # Get the distance between the vertices.
        distance = math.sqrt(((mpoint.x - tpoint.x)**2) +
                             ((mpoint.y - tpoint.y)**2) +
                             ((mpoint.z - tpoint.z)**2))

        hue = 0
        sat = 0
        val = 0.5
        # If our distance is not zero, then process it
        if distance:
            sat = saturation
            val = 1
            # First scale according to the clamp value
            scaled = distance / clamp
            # Then clamp it off at 1
            clamped = min(scaled, 1)
            hue = 180 - ((360 * clamped) / 2)

        # Start from 50% grey and bias to the red channel as distance grows
        color = om.MColor((hue, sat, val), om.MColor.kHSV)

        colors.append(color)
        ids.append(i)

    # Apply the colors
    mesh_mesh.setVertexColors(colors, ids)
Example #29
0
def display_vertex():
    is_vertex_visible = cmds.polyOptions(gl=True, q=True, displayVertex=True)
    if not all(is_vertex_visible):
        cmds.polyOptions(gl=True, displayVertex=True)
    else:
        cmds.polyOptions(gl=True, displayVertex=False)
def normalResize(*args):
    normalResizer=cmds.floatSliderGrp(normalSize,q=True, v=True)
    cmds.polyOptions(sn=normalResizer)
Example #31
0
def display_border_edges():
    is_border_edge_visible = cmds.polyOptions(gl=True, q=True, displayBorder=True)
    if not all(is_border_edge_visible):
        cmds.polyOptions(gl=True, displayBorder=True)
    else:
        cmds.polyOptions(gl=True, displayBorder=False)
Example #32
0
def Voronoi(uvs, selection):
    try:
        originalName = selection
        mcSelection = getSelectionSurface(selection)[0]
        surface = getSelectionSurface(selection)[1]

    except (IndexError):
        return
    centers = [
        WS_from_UV(uv, surface) for uv in uvs if WS_from_UV(uv, surface)[0]
    ]
    newFaces = []

    #create progress bar
    progressBarWindow = utils.pyside.SimpleProgressBar(
        "Voronoi Cells", "Dividing 0/{0}".format(len(centers)))
    progressBarWindow.show()
    #setting cursor to wait cursor
    utils.pyside.qw.QApplication.setOverrideCursor(
        utils.pyside.qc.Qt.WaitCursor)

    for i, from_point in enumerate(centers):
        working_geom = mc.duplicate(mcSelection)
        for to_point in centers:
            if from_point != to_point:
                print "**** Cut "

                locator = mc.spaceLocator()
                mc.move(from_point[0], from_point[1], from_point[2])
                mc.parent(locator, working_geom)

                center_point = [(e1 + e2) / 2
                                for (e1, e2) in zip(to_point, from_point)]
                n = [(e1 - e2) for (e1, e2) in zip(from_point, to_point)]

                es = mc.angleBetween(euler=True, v1=[0, 0, 1], v2=n)

                mc.polyCut(working_geom,
                           deleteFaces=True,
                           cutPlaneCenter=center_point,
                           cutPlaneRotate=es)

                # RandomColors
                mc.setAttr(working_geom[0] + '.displayColors', 1)
                mc.polyOptions(working_geom[0], cm='diffuse')
                mc.polyColorPerVertex(working_geom[0],
                                      rgb=utils.geo.random_color(i))

                newFaces.append(working_geom[0])

                #update progressbar
                progressBarWindow.updateLabel("Dividing {0}/{1}".format(
                    i, len(centers)))
                progressBarWindow.updateProgress(
                    len(centers) / (i + 1.0) * 100.0)

    #removing progressbar
    utils.pyside.qw.QApplication.restoreOverrideCursor()
    progressBarWindow.hide()
    progressBarWindow.deleteLater()

    mc.delete(mcSelection)
    scalp = mc.polyUnite(newFaces, n=originalName)
    mc.polyMergeVertex(scalp, d=0.25)
def bakeDiffuseToVertexColor(**kwargs):

    bOnRefs = kwargs.pop("onReferences", kwargs.pop("onRefs", False))
    fAmbient = kwargs.pop("ambient", 1.0)

    sCamShape = ""
    if mc.about(batch=True):
        sCamShape = kwargs["camera"]

    if "meshes" not in kwargs:
        sMeshList = lsNodes(sl=True, dag=True, ni=True, type="mesh",
                            not_referencedNodes=not bOnRefs, nodeNames=True)
        if not sMeshList:
            logMsg("No meshes found in selection !" , warning=True)
            return False
    else:
        sMeshList = kwargs.pop("meshes")
        if not sMeshList:
            return False

    mc.polyOptions(sMeshList, colorShadedDisplay=False)

    sLightList = tuple(sLight for sLight in mc.ls(type=mc.listNodeTypes('light'))
                                    if myapi.getDagPath(sLight).isVisible())
    for sLight in sLightList:
        try:
            mc.setAttr(sLight + ".visibility", False)
        except RuntimeError as e:
            pm.displayWarning(e)

    ambLight = pm.shadingNode("ambientLight", asLight=True)
    ambLight.setAttr("intensity", fAmbient)
    ambLight.setAmbientShade(0.0)
    ambLight.setAttr("color", (1.0, 1.0, 1.0))
    ambLight.setAttr("shadowColor", (0.0, 0.0, 0.0))
    ambLight.setAttr("useRayTraceShadows", False)

    pm.refresh()

    ##Storing if exist, reflectivity connection or value before applying the bakeTexture,
    ##as it could affects the "rendering/baking" aspect of the object.
    ##After bake, reapply the value.
    oReflDct = {}
    for oMat in lsNodes(type=mc.listNodeTypes('shader', ex="texture"), not_referencedNodes=not bOnRefs):
        if oMat.hasAttr("reflectivity"):
            oReflAttr = oMat.attr("reflectivity")
            oInputs = oReflAttr.inputs(sourceFirst=True, c=True, plugs=True)
            if oInputs:
                oReflDct[oMat] = dict(oInputs)
                pm.disconnectAttr(*oInputs)
            else:
                try:
                    value = oReflAttr.get()
                except RuntimeError as e:
                    pm.displayInfo(u"{}: {}".format(e.message.strip(), oReflAttr))
                    continue
                oReflDct[oMat] = value

            oReflAttr.set(0.0)


    if sCamShape:
        sMeshList.append(sCamShape)

    try:
        mc.polyGeoSampler(sMeshList,
                          ignoreDoubleSided=True,
                          scaleFactor=1.0,
                          shareUV=True,
                          colorDisplayOption=True,
                          colorBlend="overwrite",
                          alphaBlend="overwrite",
                          flatShading=False,
                          lightingOnly=False,
                          averageColor=True,
                          clampAlphaMin=1.0,
                          clampAlphaMax=1.0)

        mc.polyOptions(sMeshList, colorMaterialChannel="ambientDiffuse")

    finally:

        for sLight in sLightList:
            try:
                mc.setAttr(sLight + ".visibility", True)
            except RuntimeError as e:
                pm.displayWarning(e)

        for oMat, oValues in oReflDct.items():
            if isinstance(oValues, dict):
                for k, v in oValues.items():
                    pm.connectAttr(k, v)
            else:
                oMat.setAttr("reflectivity", oValues)

        if ambLight:
            pm.delete(ambLight)

    return True
Example #34
0
def toggleNormals():
    #toggle normals
    cmds.polyOptions(r=True,
                    f=True,
                    dn=not cmds.polyOptions(q=True, dn=True))
    headsUpDisplayMessage('Polygon normal display: '+str(cmds.polyOptions(q=True, dn=True)))
'''
	Toggle wireframe On Shaded
'''

import maya.cmds as cmds
 
#makes P an array. ModelPanel tells getpanel we want the panels that are in sight right now.
p = cmds.getPanel(type='modelPanel')
 
#This is looping through all of the panels we got from our getPanel
for view in p:
	
        # check to see if the view currently has the wireframe shaded
        currentState = cmds.modelEditor(view, q = True, wireframeOnShaded = True)

        # change a panel's wireframe shading to the opposite of what it is currently set to
        cmds.modelEditor(view, edit = True, wireframeOnShaded = not currentState)
	
'''
	Toggle Normals       
'''

import maya.cmds as cmds

selection = cmds.ls(sl= True)

cmds.polyOptions(f=True,r=True, dn=True)
#PolyOptions Changes the global display polygonal attributes(fancydef)
#F flag is Force, R flag is Replace, DN flag is Display Normals
Example #36
0
def display_map_border():
    is_map_border_visible = cmds.polyOptions(gl=True, q=True, displayMapBorder=True)
    if not all(is_map_border_visible):
        cmds.polyOptions(gl=True, displayMapBorder=True)
    else:
        cmds.polyOptions(gl=True, displayMapBorder=False)
#Mike Marra
#Intial Maya Setup for UDK Script
#Sets up the preferences commonly used in Maya for working with UDK

import maya.cmds as cmds
# Enables polygon borders and sets the edge width to 4 #
cmds.polyOptions(np=True, db=True, sb=4)
# Sets Undo amount to infinite #
cmds.undoInfo(infinity=True)
# Makes the viewcube visible #
cmds.viewManip(visible=True)
cmds.optionVar(iv=('viewCubeShowCube', 1))
# Sets the Z axis to be up #
cmds.upAxis(ax='z', rv=True)
# Sets the near and far clip for the persp view camera #
cmds.setAttr('perspShape.nearClipPlane', 1)
cmds.setAttr('perspShape.farClipPlane', 100000)
# Sets the near and far clip for the top view camera #
cmds.setAttr('topShape.nearClipPlane', 1)
cmds.setAttr('topShape.farClipPlane', 100000)
# Sets the near and far clip for the front view camera #
cmds.setAttr('frontShape.nearClipPlane', 1)
cmds.setAttr('frontShape.farClipPlane', 100000)
# Sets the near and far clip for the side view camera #
cmds.setAttr('sideShape.nearClipPlane', 1)
cmds.setAttr('sideShape.farClipPlane', 100000)
# To change the grid spacing and subdivisions #
cmds.grid(spacing=16, d=1)
# To change the grid length and width #
cmds.grid(size=512)
Example #38
0
	def refreshDisplay(self) :
		mesh = cmds.sets(self.objectSet, q=True)
		state = False
		if mesh and len(mesh) > 0 :
			state = cmds.polyOptions(mesh[0], q=True, colorShadedDisplay=True)
			cmds.checkBox(self.window+'DisplayCheck', e=True, v=True)
Example #39
0
def set_polycolor(geo, color):
    mc.setAttr(geo + '.displayColors', 1)
    mc.polyOptions(geo, cm='diffuse')
    mc.polyColorPerVertex(geo, rgb=color)
	def NorLenAdd(self):
		cmds.polyOptions( r=True, sn=1.41421356237 )
def borderEdgeResize(*args):
    borderEdgeResizer=cmds.floatSliderGrp(borderEdgeSize, q=True, v=True)
    cmds.polyOptions(sb=borderEdgeResizer)
Example #42
0
def setUpSVGNetwork(fromPaste = False, fromImport = False, legacy = False):

    svgTool = cmds.createNode( 'svgToPoly', n='svg#' )

    if legacy:
        svgExtruder = cmds.createNode( 'vectorExtrude', n='vectorExtrude#' )
    else:
        svgExtruder = cmds.createNode( 'typeExtrude', n='svgExtrude#' )

    svgTransform = cmds.createNode( 'transform', n='svgMesh#' )
    svgMesh = cmds.createNode( 'mesh', n='svgMeshShape#', p=svgTransform )

    #group ID nodes for the materials
    groupIdCaps = cmds.createNode( 'groupId', n= 'groupid#' )
    groupIdBevels = cmds.createNode( 'groupId', n= 'groupid#' )
    groupIdExtrusion = cmds.createNode( 'groupId', n= 'groupid#' )

    cmds.connectAttr( groupIdCaps+'.groupId', svgExtruder+'.capGroupId' )
    cmds.connectAttr( groupIdBevels+'.groupId', svgExtruder+'.bevelGroupId' )
    cmds.connectAttr( groupIdExtrusion+'.groupId', svgExtruder+'.extrudeGroupId' )

    cmds.connectAttr( svgTool+'.vertsPerChar', svgExtruder+'.vertsPerChar' )
    cmds.connectAttr( svgTool+'.outputMesh', svgExtruder+'.inputMesh' )
    cmds.connectAttr( svgExtruder+'.outputMesh', svgMesh+'.inMesh' )

    #defaults
    cmds.setAttr( svgExtruder+'.extrudeDivisions', 1 )
    cmds.setAttr( svgMesh+'.displayColors', 1 )
    cmds.polyOptions (svgMesh, colorMaterialChannel='diffuse')
    cmds.setAttr( svgTool+'.animationScale', 1,1,1, type="double3" )

    #create a default material
    blinnShader = cmds.shadingNode('blinn', asShader=True, n="svgBlinn#")
    defaultColour = [(1, 1, 1)]
    cmds.setAttr( blinnShader+'.color', defaultColour[0][0], defaultColour[0][1], defaultColour[0][2], type="double3" )
    shadingGroup = cmds.sets(n=blinnShader+'SG', renderable=True,noSurfaceShader=True,empty=True)
    cmds.connectAttr('%s.outColor' %blinnShader ,'%s.surfaceShader' %shadingGroup)

    # Message connections: Direction is important! For nodes downstream of the type node,
    # the source has to be the type node (i.e. the extruder, shell node, and remesh node)
    # This ensures there are no cycles in the graph, which cause "delete history" to skip
    # over the type node. Since the default message attribute on nodes is read-only
    # we create a new message attribute that we can connect as a destination.
    cmds.addAttr( svgExtruder, hidden=True, longName='typeMessage', attributeType='message' )
    cmds.connectAttr( svgTool+'.extrudeMessage', svgExtruder+'.typeMessage' )

    # For nodes outside of the type network (i.e. the transform) the
    # destination needs to be the type node.
    cmds.connectAttr( svgTransform+'.message', svgTool+'.transformMessage' )

    #assign the shader
    cmds.select(svgTransform)
    cmds.hyperShade( assign=blinnShader )

    #adjust deformer
    svgAdjuster = connectSVGAdjustDeformer(svgMesh, svgTransform, svgExtruder, svgTool)

    cmds.evalDeferred('import maya.app.type.svgSetup; maya.app.type.svgSetup.addPolyRemeshNodeType("'+svgTransform+'","'+svgExtruder+'","'+svgTool+'","'+svgMesh+'","'+svgAdjuster+'")', lp=True)

    if (fromImport == True):
        cmds.evalDeferred('import maya.mel as mel; mel.eval(\'AESCGFileBrowser( "", "'+ svgTool +'.svgFilepath ")\')')
    else:
        cmds.setAttr( svgTool+'.svgMode', 2 )

    cmds.setAttr( svgTool+'.useArtboard', 1 )
    #orig node un needed and exposes a problem with the extrude API.
    cmds.delete(svgMesh+"Orig")

    return svgTool
def toggleVertColor():
    '''Util for toggling the vertex color per obj selected'''
    sel = selection()
    for obj in list(sel.selection.keys()):
        cmds.polyOptions(obj,cs=1-cmds.polyOptions(obj,q=1,cs=1)[0],cm='none')