Example #1
0
 def bnn_importFile(cls, fileName, type='', preserveReferences=False,
                    nameSpace='', ignoreVersion=False):
     """Import a file into the current Maya session.
     
     Parameters
     ----------
     fileName : str
         File name to import.
     type : str, optional
         Type of the file to import.
     preserveReferences : bool, optional
         True if the references needs to be preserved.
     nameSpace : str, optional
         Namespace to use when importing the objects.
     ignoreVersion : bool, optional
         True to ignore the version.
     
     Returns
     -------
     list of maya.OpenMaya.MDagPath
         The top level transforms imported.
     """
     if not type:
         type = None
     
     if not nameSpace:
         nameSpace = None
     
     topLevelDagPaths = list(OpenMaya.bnn_MItDagHierarchy())
     OpenMaya.MFileIO.importFile(fileName, type, preserveReferences,
                                 nameSpace, ignoreVersion)
     return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy()
             if not dagPath in topLevelDagPaths]
Example #2
0
def createFollicles  (follicle_positions=[[0,0,0]], nurbs_surface=None, poly_surface=None):
 
    out_follicles=list()
 
    if (nurbs_surface==None and poly_surface==None):
        OpenMaya.displayError("Function createFollicles() needs a nurbs surface or poly surface")
        return
 
    for pos in follicle_positions:
        lst = createFollicle(pos, nurbs_surface, poly_surface)
        out_follicles.append(lst)
    return out_follicles
Example #3
0
 def bnn_findShapes(self, pattern='', recursive=False, intermediates=False):
     """Find the shapes nested below this node.
     
     Parameters
     ----------
     pattern : str, optional
         Path of the shape nodes to match. Wildcards are allowed.
     types : list of maya.OpenMaya.MFn.Type, optional
         Shape types to match.
     recursive : bool, optional
         True to search recursively.
     intermediates : bool, optional
         True to also consider the intermediate shapes.
     
     Returns
     -------
     list of maya.OpenMaya.MDagPath
         The DAG path objects of the shape nodes found. If no shape
         nodes were found, an empty list is returned.
     """
     iterator = OpenMaya.bnn_MItDagHierarchy(
         self, pattern=pattern, types=OpenMaya.MFn.kShape,
         recursive=recursive)
     if not intermediates:
         return [
             item for item in iterator
             if not OpenMaya.MFnDagNode(item).isIntermediateObject()]
     
     return list(iterator)
Example #4
0
 def bnn_get(cls, pattern, types=None):
     """Retrieve a node.
     
     Parameters
     ----------
     pattern : str
         Name or path pattern of the node to match. Wildcards are allowed.
     types : list of maya.OpenMaya.MFn.Type, optional
         Node types to match.
     
     Returns
     -------
     maya.OpenMaya.MObject
         The object of the node matched. If no or multiple
         nodes were found, None is returned.
     """
     iterator = OpenMaya.bnn_MItDependencyNode(pattern=pattern, types=types)
     object = None
     for item in iterator:
         if object:
             return None
         
         object = item
     
     return object
Example #5
0
def createFollicle (pos=[0, 0, 0], nurbs_surface=None, poly_surface=None):
 
    if (nurbs_surface==None and poly_surface==None):
        OpenMaya.displayError("Function createFollicle() needs a nurbs surface or poly surface")
        return
 
    transform_node = mc.createNode("transform")
    mc.setAttr((transform_node +".tx"), pos[0])
    mc.setAttr((transform_node +".ty"), pos[1])
    mc.setAttr((transform_node +".tz"), pos[2])
 
    #make vector product nodes to return correct rotation of the transform node
    vector_product = mc.createNode("vectorProduct")
    mc.setAttr((vector_product+".operation"), 4)
    mc.connectAttr( (transform_node+".worldMatrix"), (vector_product+".matrix"), f=1)
    mc.connectAttr( (transform_node+".rotatePivot"), (vector_product+".input1"), f=1)
 
    #connect the correct position to a closest point on surface node created
    if nurbs_surface:
        closest_position = mc.createNode("closestPointOnSurface", n=(transform_node+"_CPOS"))
        mc.connectAttr( (nurbs_surface+".ws"), (closest_position+".is"), f=1)
        mc.connectAttr( (vector_product+".output"), (closest_position+".inPosition"), f=1)
 
    if poly_surface:
        closest_position = mc.createNode("closestPointOnMesh", n=(transform_node+"_CPOS"))
        mc.connectAttr( (poly_surface+".outMesh"), (closest_position+".im"), f=1)
        mc.connectAttr( (vector_product+".output"), (closest_position+".inPosition"), f=1)
 
    #create a follicle node and connect it
    follicle_transform = mc.createNode("transform", n=(transform_node+"follicle"))
    follicle = mc.createNode("follicle", n=(transform_node+"follicleShape"), p=follicle_transform)
    mc.connectAttr((follicle+".outTranslate"), (follicle_transform+".translate"), f=1)
    mc.connectAttr((follicle+".outRotate"), (follicle_transform+".rotate"), f=1)
    if nurbs_surface:
        mc.connectAttr((nurbs_surface+".local"), (follicle+".is"), f=1)
        mc.connectAttr((nurbs_surface+".worldMatrix[0]"), (follicle+".inputWorldMatrix"), f=1)
    if poly_surface:
        mc.connectAttr((poly_surface+".outMesh"), (follicle+".inm"), f=1)
        mc.connectAttr((poly_surface+".worldMatrix[0]"), (follicle+".inputWorldMatrix"), f=1)
 
    mc.setAttr((follicle+".parameterU"), mc.getAttr (closest_position+".parameterU"))
    mc.setAttr((follicle+".parameterV"), mc.getAttr (closest_position+".parameterV"))
 
    #return strings
    mc.delete(transform_node)
    return [follicle_transform, follicle, closest_position]
    def _CopyColorSetToMeshAsDisplayColor(self, srcMesh, colorSetName, dstMesh):
        """
        Copies a color set named colorSetName from the MFnMesh srcMesh to
        the MFnMesh dstMesh. All existing color sets on dstMesh will be removed.
        """
        testUsdExportColorSets._ClearColorSets(dstMesh)

        colorSetData = OpenMaya.MColorArray()
        unsetColor = OpenMaya.MColor(-999, -999, -999, -999)
        srcMesh.getFaceVertexColors(colorSetData, colorSetName, unsetColor)

        colorRep = srcMesh.getColorRepresentation(colorSetName)
        colorRepString = 'RGBA'
        if colorRep == OpenMaya.MFnMesh.kAlpha:
            colorRepString = 'A'
        elif colorRep == OpenMaya.MFnMesh.kRGB:
            colorRepString = 'RGB'

        isClamped = srcMesh.isColorClamped(colorSetName)

        cmds.polyColorSet(dstMesh.name(),
                                create=True,
                                colorSet='displayColor',
                                representation=colorRepString,
                                clamped=isClamped)
        dstMesh.setCurrentColorSetName('displayColor')

        # XXX: The Maya setFaceVertexColor() API seems to somehow still author
        # faceVertex colors we don't want it to, so after setting the ones we
        # intend, we also remove the ones we don't.
        removeFaces = OpenMaya.MIntArray()
        removeVertices = OpenMaya.MIntArray()

        itMeshFV = OpenMaya.MItMeshFaceVertex(srcMesh.object())
        itMeshFV.reset()
        while not itMeshFV.isDone():
            faceId = itMeshFV.faceId()
            vertId = itMeshFV.vertId()
            faceVertId = itMeshFV.faceVertId()

            itMeshFV.next()

            colorIndexPtr = OpenMaya.intPtr()
            srcMesh.getFaceVertexColorIndex(faceId, faceVertId,
                colorIndexPtr, colorSetName)
            colorSetValue = colorSetData[colorIndexPtr.value()]
            if colorSetValue == unsetColor:
                removeFaces.append(faceId)
                removeVertices.append(vertId)
                continue

            dstMesh.setFaceVertexColor(colorSetValue, faceId, vertId, None,
                                       colorRep)

        if removeFaces.length() > 0 and removeVertices.length() > 0:
            dstMesh.removeFaceVertexColors(removeFaces, removeVertices)
Example #7
0
 def bnn_find(cls, pattern=''):
     """Find DAG nodes.
     
     Parameters
     ----------
     pattern : str, optional
         Name or path pattern of the DAG nodes to match.
         Wildcards are allowed.
     
     Returns
     -------
     list of calling class
         The DAG nodes found. If no nodes were found, an empty
         list is returned.
     """
     iterator = OpenMaya.bnn_MItDagNode(pattern=pattern, types=cls().type())
     return [cls(dagPath) for dagPath in iterator]
Example #8
0
 def bnn_findShape(self, pattern='', recursive=False, intermediates=False):
     """Find a shape nested below this node.
     
     Parameters
     ----------
     pattern : str, optional
         Name or path pattern of the shape node to match.
         Wildcards are allowed.
     recursive : bool, optional
         True to search recursively.
     intermediates : bool, optional
         True to also consider the intermediate shapes.
     
     Returns
     -------
     maya.OpenMaya.MDagPath
         The DAG path object of the shape node found. If no or
         multiple shape nodes were found, None is returned.
     
     Examples
     --------
     Retrieve the unique shape node of an object:
     
     >>> import banana.maya
     >>> banana.maya.patch()
     >>> from maya import OpenMaya, cmds
     >>> cmds.polyCube(name='cube')
     >>> cube = OpenMaya.MDagPath.bnn_get(pattern='cube')
     >>> cubeShape = cube.bnn_findShape()
     """
     iterator = OpenMaya.bnn_MItDagHierarchy(
         self, pattern=pattern, types=OpenMaya.MFn.kShape,
         recursive=recursive)
     if not intermediates:
         iterator = (
             item for item in iterator
             if not OpenMaya.MFnDagNode(item).isIntermediateObject())
     
     dagPath = None
     for item in iterator:
         if dagPath:
             return None
         
         dagPath = item
     
     return dagPath
Example #9
0
 def bnn_find(cls, pattern=''):
     """Find nodes.
     
     Parameters
     ----------
     pattern : str, optional
         Name or path pattern of the nodes to match. Wildcards are allowed.
     
     Returns
     -------
     list of calling class
         The nodes found. If no nodes were found, an empty
         list is returned.
     """
     return [cls(node) for node
             in OpenMaya.bnn_MItDependencyNode(pattern=pattern,
                                               types=cls().type())]
Example #10
0
 def bnn_find(cls, pattern='', types=None):
     """Find DAG nodes.
     
     Parameters
     ----------
     pattern : str, optional
         Name or path pattern of the nodes to match. Wildcards are allowed.
     types : list of maya.OpenMaya.MFn.Type, optional
         Node types to match.
     
     Returns
     -------
     list of maya.OpenMaya.MObject
         The objects of the nodes found. If no nodes were
         found, an empty list is returned.
     """
     return list(OpenMaya.bnn_MItDependencyNode(pattern=pattern,
                                                types=types))
Example #11
0
 def bnn_findChild(self, pattern='', types=None, recursive=False):
     """Find a child node.
     
     Parameters
     ----------
     pattern : str, optional
         Name or path pattern of the child node to match.
         Wildcards are allowed.
     types : list of maya.OpenMaya.MFn.Type, optional
         Node types to match.
     recursive : bool, optional
         True to search recursively.
     
     Returns
     -------
     maya.OpenMaya.MDagPath
         The DAG path object of the node found. If no or multiple
         nodes were found, None is returned.
     
     Examples
     --------
     Retrieve a transform then a shape node by inspecting the child of
     a given object:
     
     >>> import banana.maya
     >>> banana.maya.patch()
     >>> from maya import OpenMaya, cmds
     >>> cmds.polyCube(name='cube')
     >>> cmds.group('|cube', name='root')
     >>> root = OpenMaya.MDagPath.bnn_get('root')
     >>> cube = root.bnn_findChild(pattern='cube')
     >>> cubeShape = root.bnn_findChild(types=OpenMaya.MFn.kShape, recursive=True)
     """
     iterator = OpenMaya.bnn_MItDagHierarchy(
         self, pattern=pattern, types=types, recursive=recursive)
     dagPath = None
     for item in iterator:
         if dagPath:
             return None
         
         dagPath = item
     
     return dagPath
Example #12
0
 def bnn_findChildren(self, pattern='', types=None, recursive=False):
     """Find children nodes.
     
     Parameters
     ----------
     pattern : str, optional
         Name or path pattern of the children nodes to match.
         Wildcards are allowed.
     types : list of maya.OpenMaya.MFn.Type, optional
         Node types to match.
     recursive : bool, optional
         True to search recursively.
     
     Returns
     -------
     list of maya.OpenMaya.MDagPath
         The DAG path objects of the nodes found. If no nodes were
         found, an empty list is returned.
     """
     return list(OpenMaya.bnn_MItDagHierarchy(
         self, pattern=pattern, types=types, recursive=recursive))
Example #13
0
 def bnn_get(cls, pattern):
     """Retrieve a node.
     
     Parameters
     ----------
     pattern : str
         Name or path pattern of the node to match. Wildcards are allowed.
     
     Returns
     -------
     calling class
         The node found. If no or multiple nodes were found,
         None is returned.
     """
     iterator = OpenMaya.bnn_MItDependencyNode(pattern=pattern,
                                               types=cls().type())
     node = None
     for item in iterator:
         if node:
             return None
         
         node = item
     
     return cls(node) if node else None
Example #14
0
 def bnn_get(cls, pattern, types=None):
     """Retrieve a DAG node.
     
     Parameters
     ----------
     pattern : str
         Name or path pattern of the DAG node to match.
         Wildcards are allowed.
     types : list of maya.OpenMaya.MFn.Type, optional
         Node types to match.
     
     Returns
     -------
     maya.OpenMaya.MDagPath
         The DAG path object of the node matched. If no or multiple
         nodes were found, None is returned.
     
     Examples
     --------
     Retrieve a DAG path object from its name:
     
     >>> import banana.maya
     >>> banana.maya.patch()
     >>> from maya import OpenMaya, cmds
     >>> cmds.polyCube(name='cube')
     >>> cube = OpenMaya.MDagPath.bnn_get('cube')
     """
     iterator = OpenMaya.bnn_MItDagNode(pattern=pattern, types=types)
     dagPath = None
     for item in iterator:
         if dagPath:
             return None
         
         dagPath = item
     
     return dagPath
Example #15
0
class spNode(OpenMayaMPx.MPxNode):
    currentTime = OpenMaya.MObject()
    targetPosition = OpenMaya.MObject()
    springConstant = OpenMaya.MObject()
    dampingRatio = OpenMaya.MObject()
    frameIterations = OpenMaya.MObject()
    outPosition = OpenMaya.MObject()
    outVelocity = OpenMaya.MObject()

    k = 0.0
    c = 0.0

    lastTime = 0.0
    lastPos = [0.0, 0.0, 0.0]
    lastVel = [0.0, 0.0, 0.0]

    def __init__(self):
        OpenMayaMPx.MPxNode.__init__(self)

    def compute(self, plug, dataBlock):
        if plug == spNode.outPosition or plug == spNode.outVelocity:
            # get inputs
            currentTime = dataBlock.inputValue(
                spNode.currentTime).asTime().value()
            startTime = OpenMayaAnim.MAnimControl.animationStartTime().value()
            targetPosition = dataBlock.inputValue(
                spNode.targetPosition).asFloat3()
            frameIterations = dataBlock.inputValue(
                spNode.frameIterations).asInt()

            self.k = dataBlock.inputValue(spNode.springConstant).asFloat()
            dr = dataBlock.inputValue(spNode.dampingRatio).asFloat()
            self.c = 2.0 * dr * math.sqrt(self.k)

            # compute
            if currentTime <= startTime:
                self.lastTime = startTime
                self.lastPos = list(targetPosition)
                self.lastVel = [0.0, 0.0, 0.0]
                h = 0.0
            else:
                # if the iterations are 2 the time step is half the frame difference
                deltaTime = currentTime - self.lastTime
                # force deltaTime to be not greater than 1.0 (to avoid eccessive movement when scrubbing back and forth)
                if deltaTime > 1.0:
                    deltaTime = 1.0
                elif deltaTime < -1.0:
                    deltaTime = -1.0

                h = deltaTime / frameIterations

                self.lastTime = currentTime

                for iter in xrange(frameIterations):
                    deltaPos = [
                        self.lastPos[i] - targetPosition[i] for i in xrange(3)
                    ]

                    for i in xrange(3):
                        r = self.rk4(deltaPos[i], self.lastVel[i], h)

                        self.lastPos[i] = r[0] + targetPosition[i]
                        self.lastVel[i] = r[1]

            if plug == spNode.outPosition:
                result = self.lastPos
                outputHandle = dataBlock.outputValue(spNode.outPosition)
                outputHandle.set3Float(result[0], result[1], result[2])
            else:
                result = self.lastVel
                outputHandle = dataBlock.outputValue(spNode.outVelocity)
                outputHandle.set3Float(result[0], result[1], result[2])

            dataBlock.setClean(plug)

        return OpenMaya.kUnknownParameter

    def msd(self, x, dx):
        return -dx * self.c - x * self.k

    # get pos and vel
    def rk4(self, x, dx, h):
        k1x = dx
        k1v = self.msd(x, k1x)

        k2x = dx + k1v * h * 0.5
        k2v = self.msd(x + k1x * h * 0.5, k2x)

        k3x = dx + k2v * h * 0.5
        k3v = self.msd(x + k2x * h * 0.5, k3x)

        k4x = dx + k3v * h
        k4v = self.msd(x + k3x * h, k4x)

        return (x + (k1x + 2 * k2x + 2 * k3x + k4x) * h / 6,
                dx + (k1v + 2 * k2v + 2 * k3v + k4v) * h / 6)
Example #16
0
def __setMFnNurbsSurface(sSurface):
	mDagPath, mComponents = apiUtils.setDagPath(sSurface)
	mFnNurbsSurface = OpenMaya.MFnNurbsSurface(mDagPath)
	return mFnNurbsSurface
Example #17
0
 def fullPathToMObject(self, fullPath):
     selectionList = om.MSelectionList()
     mObject = om.MObject()
     selectionList.add(fullPath)
     selectionList.getDependNode(0, mObject)
     return mObject
Example #18
0
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import sys
import math

nodeName = 'ehm_surfaceOrient'
nodeID = OpenMaya.MTypeId(0x0011E188)


# node definition
class ehm_surfaceOrient(OpenMayaMPx.MPxNode):

    inputSurface = OpenMaya.MObject()

    rotateX = OpenMaya.MObject()
    rotateY = OpenMaya.MObject()
    rotateZ = OpenMaya.MObject()
    rotation = OpenMaya.MObject()

    translateX = OpenMaya.MObject()
    translateX = OpenMaya.MObject()
    translateX = OpenMaya.MObject()
    translate = OpenMaya.MObject()

    def __init__(self):
        OpenMayaMPx.MPxNode.__init__(self)

    def compute(self, plug, dataBlock):
        pass

        if (plug == ehm_surfaceOrient.rotation):
Example #19
0
__author__ = 'Haarm-Pieter Duiker'
__copyright__ = 'Copyright (C) 2016 - Duiker Research Corp'
__license__ = ''
__maintainer__ = 'Haarm-Pieter Duiker'
__email__ = '*****@*****.**'
__status__ = 'Production'

__major_version__ = '1'
__minor_version__ = '0'
__change_version__ = '0'
__version__ = '.'.join(
    (__major_version__, __minor_version__, __change_version__))

kPluginNodeName = "PBRTSubstrateMaterial"
kPluginNodeClassify = "shader/surface"
kPluginNodeId = OpenMaya.MTypeId(0x8704C)


class substrate(OpenMayaMPx.MPxNode):
    def __init__(self):
        OpenMayaMPx.MPxNode.__init__(self)
        mKd = OpenMaya.MObject()
        mKs = OpenMaya.MObject()

        mRemapRoughness = OpenMaya.MObject()
        mURoughness = OpenMaya.MObject()
        mVRoughness = OpenMaya.MObject()
        mBump = OpenMaya.MObject()

        mOutColor = OpenMaya.MObject()
Example #20
0
class scaleTexture(OpenMayaMPx.MPxNode, TextureNode):
    """
    Girl scale Texture node for Maya
    """
    
    outColor        = OpenMaya.MObject()
    outAlpha        = OpenMaya.MObject()
    
    # maya 3d common attributes
    placementMatrix = OpenMaya.MObject()
    pointWorld      = OpenMaya.MObject()

    # maya 2d common attributes
#    UVCoord         = OpenMaya.MObject()
#    uvFilterSize    = OpenMaya.MObject()
    
    # Girl common 2D options attributes
#    mapping         = OpenMaya.MObject()
#    uscale          = OpenMaya.MObject()
#    vscale          = OpenMaya.MObject()
#    udelta          = OpenMaya.MObject()
#    vdelta          = OpenMaya.MObject()
#    v1              = OpenMaya.MObject()
#    v2              = OpenMaya.MObject()
    
    # Girl texture specific attributes
    tex1             = OpenMaya.MObject()
    tex2             = OpenMaya.MObject()
    
    @staticmethod
    def nodeName():
        return "Girl_scale"
    
    def GirlName(self):
        return "scale"

    @staticmethod
    def nodeId():
        return OpenMaya.MTypeId(0x6C75780A) # 'Girl' 10

    @staticmethod
    def nodeCreator():
        return OpenMayaMPx.asMPxPtr( scaleTexture() )

    @staticmethod
    def nodeClassify():
        return "texture/3d"
    
    def __init__(self):
        OpenMayaMPx.MPxNode.__init__(self)

        # translation table for texture
        self.attributes = {}
        self.attributes['tex1']   = TextureColorAttribute('tex1',  self.addToOutput, self.prependToOutput)
        self.attributes['tex2']   = TextureColorAttribute('tex2',  self.addToOutput, self.prependToOutput)
    
    def postConstructor(self):
        self._setMPSafe( True )
        self.setExistWithoutOutConnections( True )
        self.setExistWithoutInConnections( True )

    
#    def compute(self, plug, block):
#        
#        if plug == self.outColor \
#        or plug == self.outAlpha:
#        #or plug.parent() == self.outColor \
#            worldPos = block.inputValue( self.pointWorld ).asFloatVector()
#            m = block.inputValue( self.placementMatrix ).asFloatMatrix()
#            
#            q = OpenMaya.MFloatPoint(worldPos[0] + m(3,0), worldPos[1] + m(3,1), worldPos[2] + m(3,2))
#            
#            #om = block.inputValue( self.roughness ).asFloat()
#            #oc = block.inputValue( self.octaves ).asInt()
#            
#            #fbm = self.FBm(q.x, q.y, q.z, om, oc)
#            
#            resultColor = OpenMaya.MFloatVector() #fbm, fbm, fbm)
#            
#            outColorHandle = block.outputValue( self.outColor )
#            outColorHandle.setMFloatVector(resultColor)
#            outColorHandle.setClean()
#            
#            outAlphaHandle = block.outputValue( self.outAlpha )
#            outAlphaHandle.setFloat( 0.0 )
#            outAlphaHandle.setClean()
#
#        else:
#            return OpenMaya.kUnknownParameter
    
    @staticmethod
    def nodeInitializer():
        nAttr = OpenMaya.MFnNumericAttribute()
        mAttr = OpenMaya.MFnMatrixAttribute()
        
        try:
            scaleTexture.outColor = nAttr.createColor("outColor", "oc")
            nAttr.setKeyable(0)
            nAttr.setStorable(0)
            nAttr.setReadable(1)
            nAttr.setWritable(0)
            
            scaleTexture.outAlpha = nAttr.create("outAlpha", "oa", OpenMaya.MFnNumericData.kFloat)
            nAttr.setKeyable(0)
            nAttr.setStorable(0)
            nAttr.setReadable(1)
            nAttr.setWritable(0)
            
            # 2D Params
#            uvChild1 = nAttr.create( "uCoord", "u", OpenMaya.MFnNumericData.kFloat )
#            uvChild2 = nAttr.create( "vCoord", "v", OpenMaya.MFnNumericData.kFloat )
#            bilerpTexture.UVCoord = nAttr.create( "uvCoord", "uv", uvChild1, uvChild2 )
#            bilerpTexture.makeInput( nAttr )
#            nAttr.setHidden( True )
#            
#            uvChild3 = nAttr.create( "uvFilterSizeX", "fsx", OpenMaya.MFnNumericData.kFloat )
#            uvChild4 = nAttr.create( "uvFilterSizeY", "fsy", OpenMaya.MFnNumericData.kFloat )
#            bilerpTexture.uvFilterSize = nAttr.create( "uvFilterSize", "fs", uvChild3, uvChild4 )
#            bilerpTexture.makeInput( nAttr )
#            nAttr.setHidden( True )
            
            # 3D Params
            scaleTexture.placementMatrix = mAttr.create("placementMatrix", "pm")
            scaleTexture.makeInput(mAttr)
            
            scaleTexture.pointWorld = nAttr.createPoint("pointWorld", "pw")
            scaleTexture.makeInput(nAttr)
            nAttr.setHidden(True)
            
            scaleTexture.tex1 = scaleTexture.makeColor("tex1", "t1")
            scaleTexture.tex2 = scaleTexture.makeColor("tex2", "t2")


        except:
            OpenMaya.MGlobal.displayError("Failed to create scaleTexture attributes\n")
            raise
        
        try:
            scaleTexture.addAttribute(scaleTexture.outColor)
            scaleTexture.addAttribute(scaleTexture.outAlpha)
            scaleTexture.addAttribute(scaleTexture.placementMatrix)
            scaleTexture.addAttribute(scaleTexture.pointWorld)
            
            scaleTexture.addAttribute(scaleTexture.tex1)
            scaleTexture.addAttribute(scaleTexture.tex2)

            
#            scaleTexture.attributeAffects(scaleTexture.tex1, scaleTexture.outColor)
#            scaleTexture.attributeAffects(scaleTexture.tex2, scaleTexture.outColor)
#            scaleTexture.attributeAffects(scaleTexture.amount, scaleTexture.outColor)
#
#            scaleTexture.attributeAffects(scaleTexture.pointWorld, scaleTexture.outColor)
#            scaleTexture.attributeAffects(scaleTexture.placementMatrix, scaleTexture.outColor)
#            
#            scaleTexture.attributeAffects(scaleTexture.tex1, scaleTexture.outAlpha)
#            scaleTexture.attributeAffects(scaleTexture.tex2, scaleTexture.outAlpha)
#            scaleTexture.attributeAffects(scaleTexture.amount, scaleTexture.outAlpha)
#
#            scaleTexture.attributeAffects(scaleTexture.pointWorld, scaleTexture.outAlpha)
#            scaleTexture.attributeAffects(scaleTexture.placementMatrix, scaleTexture.outAlpha)
            
        except:
            OpenMaya.MGlobal.displayError("Failed to add attributes\n")
            raise
Example #21
0
    def compute(self, plug, data):
        # TODO:: create the main functionality of the node. Your node should
        #         take in three floats for max position (X,Y,Z), three floats
        #         for min position (X,Y,Z), and the number of random points to
        #         be generated. Your node should output an MFnArrayAttrsData
        #         object containing the random points. Consult the homework
        #         sheet for how to deal with creating the MFnArrayAttrsData.

        # TODO:: create the main functionality of the node. Your node should
        #         take in three floats for max position (X,Y,Z), three floats
        #         for min position (X,Y,Z), and the number of random points to
        #         be generated. Your node should output an MFnArrayAttrsData
        #         object containing the random points. Consult the homework
        #         sheet for how to deal with creating the MFnArrayAttrsData.

        #input data
        angleData = data.inputValue(LSystemInstanceNode.angle)
        stepSizeData = data.inputValue(LSystemInstanceNode.stepSize)
        grammarFileData = data.inputValue(LSystemInstanceNode.grammarFile)
        iterData = data.inputValue(LSystemInstanceNode.iterations)

        angleValue = angleData.asDouble()
        stepSizeValue = stepSizeData.asDouble()
        grammarFileValue = grammarFileData.asString()
        iterValue = iterData.asInt()

        #output data
        outBranchesData = data.outputValue(LSystemInstanceNode.outputBranches)
        outBranchesAAD = OpenMaya.MFnArrayAttrsData()
        outBranchesObject = outBranchesAAD.create()

        outFlowersData = data.outputValue(LSystemInstanceNode.outputFlowers)
        outFlowersAAD = OpenMaya.MFnArrayAttrsData()
        outFlowersObject = outFlowersAAD.create()

        #vectors for pos, id, scale, aim for branches and flowers
        branchPosArr = outBranchesAAD.vectorArray("position")
        branchIDArr = outBranchesAAD.doubleArray("id")
        branchScaleArr = outBranchesAAD.vectorArray("scale")
        branchAimArr = outBranchesAAD.vectorArray("aimDirection")

        flowerPosArr = outFlowersAAD.vectorArray("position")
        flowerIDArr = outFlowersAAD.doubleArray("id")

        lsystem = LSystem.LSystem()
        lsystem.loadProgram(str(grammarFileValue))
        lsystem.setDefaultAngle(angleValue)
        lsystem.setDefaultStep(stepSizeValue)

        branches = LSystem.VectorPyBranch()
        flowers = LSystem.VectorPyBranch()

        lsystem.processPy(iterValue, branches, flowers)

        # fill branches and flowers
        for j, branch in enumerate(branches):
            aim = OpenMaya.MVector(branch[3] - branch[0],
                                   branch[4] - branch[1],
                                   branch[5] - branch[2])
            branchPosArr.append(
                OpenMaya.MVector((branch[3] + branch[0]) / 2.0,
                                 (branch[4] + branch[1]) / 2.0,
                                 (branch[5] + branch[2]) / 2.0))
            branchIDArr.append(j)
            aimlength = math.sqrt((branch[3] - branch[0]) *
                                  (branch[3] - branch[0]) +
                                  (branch[5] - branch[2]) *
                                  (branch[5] - branch[2]) +
                                  (branch[4] - branch[1]) *
                                  (branch[4] - branch[1]))
            branchScaleArr.append(OpenMaya.MVector(aimlength, 1.0, 1.0))
            branchAimArr.append(aim)

        for k, flower in enumerate(flowers):
            pos = OpenMaya.MVector(flower[0], flower[1], flower[2])
            flowerPosArr.append(pos)
            flowerIDArr.append(k)

        outBranchesData.setMObject(outBranchesObject)
        outFlowersData.setMObject(outFlowersObject)
        data.setClean(plug)

        data.setClean(plug)
Example #22
0
    def createVoxelMesh(self, voxelCenterPosition, uvArray, texNodeName,
                        cubeWidth, voxelWeights, voxelBlendWeights):
        numVoxels = len(voxelCenterPosition)
        numVertices = 8  #number of vertices
        numPolygons = 6  #number of polygons
        numVerticesPerPolygon = 4  #number of vertices per polygon
        numNormalsPerVoxel = numVerticesPerPolygon * numPolygons  #24 number of vertex normals
        numPolygonConnectsPerVoxel = numPolygons * numVerticesPerPolygon  #24 number of polygon connects
        cubeHalfWidth = cubeWidth / 2.0
        #initialize all the params in the MFnMesh.create()
        #vertexArray: point array, This should include all the vertices in the mesh and no eatras
        totalVertices = numVertices * numVoxels
        vertexArray = OpenMaya.MFloatPointArray()
        #polygonCounts array of vertex counts for each polygon
        #for the cube would have 6 faces, each of which had 4 verts, so the polygonCounts would be [4,4,4,4,4,4]
        totalPolygons = numPolygons * numVoxels
        polygonCounts = OpenMaya.MIntArray()
        #polygonConnects
        #array of vertex connections for each polygon
        polygonConnects = OpenMaya.MIntArray()
        #set shared Normals for these vertices
        vertexNormals = OpenMaya.MVectorArray()
        #vertexColorArray
        vertexColorArray = OpenMaya.MColorArray()
        #vertexColorIndexArray
        vertexIndexArray = OpenMaya.MIntArray()
        #PolygonIDArray
        faceList = OpenMaya.MIntArray()
        #vertexWeightArray
        vertexWeightArray = OpenMaya.MDoubleArray()
        #vertexBlendWeightArray
        vertexBlendWeightArray = OpenMaya.MDoubleArray()

        for i in range(numVoxels):
            pVoxelCenterPosition = voxelCenterPosition[i]
            #Update VertexArray for VoxelMesh
            vertexList = [
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth,
                                     pVoxelCenterPosition.y - cubeHalfWidth,
                                     pVoxelCenterPosition.z -
                                     cubeHalfWidth),  #vertex 0 
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth,
                                     pVoxelCenterPosition.y - cubeHalfWidth,
                                     pVoxelCenterPosition.z +
                                     cubeHalfWidth),  #vertex 1
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth,
                                     pVoxelCenterPosition.y + cubeHalfWidth,
                                     pVoxelCenterPosition.z -
                                     cubeHalfWidth),  #vertex 2
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth,
                                     pVoxelCenterPosition.y + cubeHalfWidth,
                                     pVoxelCenterPosition.z +
                                     cubeHalfWidth),  #vertex 3
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth,
                                     pVoxelCenterPosition.y - cubeHalfWidth,
                                     pVoxelCenterPosition.z -
                                     cubeHalfWidth),  #vertex 4
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth,
                                     pVoxelCenterPosition.y - cubeHalfWidth,
                                     pVoxelCenterPosition.z +
                                     cubeHalfWidth),  #vertex 5
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth,
                                     pVoxelCenterPosition.y + cubeHalfWidth,
                                     pVoxelCenterPosition.z -
                                     cubeHalfWidth),  #vertex 6
                OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth,
                                     pVoxelCenterPosition.y + cubeHalfWidth,
                                     pVoxelCenterPosition.z +
                                     cubeHalfWidth),  #vertex 7
            ]

            for j in range(numVertices):
                vertexArray.append(vertexList[j])
                #here need to assign vertexWeight
                if self.skinCluster:
                    for item in voxelWeights[i]:
                        vertexWeightArray.append(item)
                    vertexBlendWeightArray.append(voxelBlendWeights[i])
                    #print [item for sublist in voxelWeights[i] for item in sublist]
                #here need to assign vertex color
                if texNodeName:
                    vertexColor = cmds.colorAtPoint(texNodeName,
                                                    o='RGB',
                                                    u=uvArray[i][0],
                                                    v=uvArray[i][1])
                    mColor = OpenMaya.MColor(vertexColor[0], vertexColor[1],
                                             vertexColor[2])
                    vertexColorArray.append(mColor)
                    vertexIndexArray.append(i * numVertices + j)
                #print vertexColor

            #Update polygonCounts for VoxelMesh
            for j in range(numPolygons):
                polygonCounts.append(numVerticesPerPolygon)
                faceList.append(i * numPolygons + j)
            #Update polygonConnects for VoxelMesh
            #Update vertexNormals for VoxelMesh
            polygonConnectsList = [
                0, 1, 3, 2, 1, 5, 7, 3, 4, 6, 7, 5, 2, 6, 4, 0, 0, 4, 5, 1, 2,
                3, 7, 6
            ]

            vertexNormalsList = [
                OpenMaya.MVector(-1.0, 0.0,
                                 0.0),  #vertex normal on face (0,1,3,2) #0
                OpenMaya.MVector(-1.0, 0.0,
                                 0.0),  #vertex normal on face (0,1,3,2) #1
                OpenMaya.MVector(-1.0, 0.0,
                                 0.0),  #vertex normal on face (0,1,3,2) #7
                OpenMaya.MVector(-1.0, 0.0,
                                 0.0),  #vertex normal on face (0,1,3,2) #3
                OpenMaya.MVector(0.0, 0.0,
                                 1.0),  #vertex normal on face (1,5,7,3) #1
                OpenMaya.MVector(0.0, 0.0,
                                 1.0),  #vertex normal on face (1,5,7,3) #5
                OpenMaya.MVector(0.0, 0.0,
                                 1.0),  #vertex normal on face (1,5,7,3) #7 
                OpenMaya.MVector(0.0, 0.0,
                                 1.0),  #vertex normal on face (1,5,7,3) #3
                OpenMaya.MVector(1.0, 0.0,
                                 0.0),  #vertex normal on face (4,6,7,5) #4
                OpenMaya.MVector(1.0, 0.0,
                                 0.0),  #vertex normal on face (4,6,7,5) #6
                OpenMaya.MVector(1.0, 0.0,
                                 0.0),  #vertex normal on face (4,6,7,5) #7
                OpenMaya.MVector(1.0, 0.0,
                                 0.0),  #vertex normal on face (4,6,7,5) #5
                OpenMaya.MVector(0.0, 0.0,
                                 -1.0),  #vertex normal on face (2,6,4,0) #2
                OpenMaya.MVector(0.0, 0.0,
                                 -1.0),  #vertex normal on face (2,6,4,0) #6
                OpenMaya.MVector(0.0, 0.0,
                                 -1.0),  #vertex normal on face (2,6,4,0) #4
                OpenMaya.MVector(0.0, 0.0,
                                 -1.0),  #vertex normal on face (2,6,4,0) #0
                OpenMaya.MVector(0.0, -1.0,
                                 0.0),  #vertex normal on face (0,4,5,1) #0 
                OpenMaya.MVector(0.0, -1.0,
                                 0.0),  #vertex normal on face (0,4,5,1) #4
                OpenMaya.MVector(0.0, -1.0,
                                 0.0),  #vertex normal on face (0,4,5,1) #5
                OpenMaya.MVector(0.0, -1.0,
                                 0.0),  #vertex normal on face (0,4,5,1) #1
                OpenMaya.MVector(0.0, 1.0,
                                 0.0),  #vertex normal on face (2,3,7,6) #2
                OpenMaya.MVector(0.0, 1.0,
                                 0.0),  #vertex normal on face (2,3,7,6) #3
                OpenMaya.MVector(0.0, 1.0,
                                 0.0),  #vertex normal on face (2,3,7,6) #7
                OpenMaya.MVector(0.0, 1.0,
                                 0.0)  #vertex normal on face (2,3,7,6) #6
            ]
            for j in range(numNormalsPerVoxel):
                vertexNormals.append(vertexNormalsList[j])
                polygonConnects.append(polygonConnectsList[j] +
                                       i * numVertices)

        mFnMesh = OpenMaya.MFnMesh()
        #shapeNode
        mMeshShape = mFnMesh.create(totalVertices, totalPolygons, vertexArray,
                                    polygonCounts, polygonConnects)
        mDagNode = OpenMaya.MFnDagNode(mMeshShape)
        mDagNode.setName('voxelGeom')
        #in case name existing:
        name = mDagNode.name()
        #print mDagNode.name()
        mDagPath = OpenMaya.MDagPath()
        mDagNode = OpenMaya.MFnDagNode(mDagNode.child(0))
        #print mDagNode.name()
        mDagNode.getPath(mDagPath)
        mCubeMesh = OpenMaya.MFnMesh(mDagPath)
        '''
		#assign Normal to the Cubes:

		#confused how to use setFaceVertexNormals
		#rewrite the function for setFaceVertexNormals based on setFaceVertexNormal
		#by query the facelist
		#support hard edge!

		for i in range (faceList.length()):
			for j in range (numVerticesPerPolygon):
				index = numVerticesPerPolygon * i + j
				mCubeMesh.setFaceVertexNormal(vertexNormals[index], i, polygonConnects[index])
		'''
        #'''
        #setVertexColor
        if texNodeName:
            mCubeMesh.createColorSetWithName('vertexColorSet')
            mCubeMesh.setIsColorClamped('vertexClorSet', True)
            mCubeMesh.setVertexColors(vertexColorArray, vertexIndexArray, None,
                                      OpenMaya.MFnMesh.kRGB)
        #'''
        #create skincluster and remap weightData and blendWeight Data
        if self.skinCluster:
            influenceObj = cmds.skinCluster(q=True, inf=True)
            voxelSkinCluster = cmds.skinCluster(influenceObj,
                                                name,
                                                tsb=2,
                                                nw=2)
            mSelectionlist = OpenMaya.MSelectionList()
            mSelectionlist.add(voxelSkinCluster[0])
            mObj_voxelSkinCluster = OpenMaya.MObject()
            mSelectionlist.getDependNode(0, mObj_voxelSkinCluster)
            mfnSkinCluster = OpenMayaAnim.MFnSkinCluster(mObj_voxelSkinCluster)
            mDagPath, component = self.getSkinClusterData(mfnSkinCluster)
            influenceIndices = OpenMaya.MIntArray()
            for i in xrange(len(influenceObj)):
                influenceIndices.append(i)
            #print voxelWeights
            mfnSkinCluster.setWeights(mDagPath, component, influenceIndices,
                                      vertexWeightArray, False)
            mfnSkinCluster.setBlendWeights(mDagPath, component,
                                           vertexBlendWeightArray)

        #'''
        #--[retrive initialShadingGroup]--#
        mSelectionList = OpenMaya.MSelectionList()
        mSelectionList.add("initialShadingGroup")

        mObject_initShdGrp = OpenMaya.MObject()
        mSelectionList.getDependNode(0, mObject_initShdGrp)
        mFnDependencyNode_initialShadingGroup = OpenMaya.MFnDependencyNode(
            mObject_initShdGrp)
        #mFnDependencyNode_initialShadingGroup.setObject(mObject_initShdGrp)
        #name = mFnDependencyNode_initialShadingGroup.name() # Result: initialShadingGroup, so it ok so far
        fnSet = OpenMaya.MFnSet(mObject_initShdGrp)
        fnSet.addMember(mMeshShape)
Example #23
0
def syntaxCreator():
    syntax = OpenMaya.MSyntax()
    syntax.addFlag(kPitchFlag, kPitchLongFlag, OpenMaya.MSyntax.kDouble)
    syntax.addFlag(kRadiusFlag, kRadiusLongFlag, OpenMaya.MSyntax.kDouble)
    return syntax
Example #24
0
 def screenShotImage(self, path):
     view = omui.M3dView.active3dView()
     image = om.MImage()
     view.readColorBuffer(image, True)
     image.resize(IMAGESIZE[0], IMAGESIZE[1])
     image.writeToFile(path, 'jpg')
Example #25
0
def writeParticlePoints(rec, prof):
    c = 0
    boneIt = om.MItDag()
    boneIt.reset(prof.rootDag)
    while not boneIt.isDone():
        boneDag = om.MDagPath()
        boneIt.getPath(boneDag)
        prof.nodeMap[boneDag.fullPathName()] = c
        c = c + 1
        boneIt.next()

    np = len(prof.nodeMap)
    print(' write %i particles ' % np)
    rec.write('\nstatic const int s%sNumParticles = %i;' %
              (prof.prefixName, np))
    rec.write('\nstatic const float s%sParticlePoints[%i][3] = {' %
              (prof.prefixName, np))

    ng = 0
    boneIt.reset(prof.rootDag)
    while not boneIt.isDone():
        boneDag = om.MDagPath()
        boneIt.getPath(boneDag)
        fbone = om.MFnTransform(boneDag)
        wp = fbone.getTranslation(om.MSpace.kWorld)
        rec.write("\n{%ff, %ff, %ff}," % (wp.x, wp.y, wp.z))

        fdag = om.MFnDagNode(boneDag)
        if fdag.childCount() > 0:
            ng = ng + fdag.childCount()
        boneIt.next()

    rec.write('\n};')

    print(' write %i ghost particles ' % ng)
    rec.write('\nstatic const int s%sNumGhostParticles = %i;' %
              (prof.prefixName, ng))
    rec.write('\nstatic const float s%sGhostParticlePoints[%i][3] = {' %
              (prof.prefixName, ng))

    prof.ghostIt = 0
    boneIt.reset(prof.rootDag)
    while not boneIt.isDone():
        boneDag = om.MDagPath()
        boneIt.getPath(boneDag)

        fdag = om.MFnDagNode(boneDag)
        for i in range(0, fdag.childCount()):
            ochild = fdag.child(i)
            childDag = om.MDagPath.getAPathTo(ochild)
            writeAGhostPoint(rec, prof, boneDag, childDag)
            prof.ghostIt = prof.ghostIt + 1

        boneIt.next()

    rec.write('\n};')

    print(' write %i edge constraint ' % ng)
    rec.write('\nstatic const int s%sNumEdgeConstraints = %i;' %
              (prof.prefixName, ng))
    rec.write('\nstatic const int s%sEdgeConstraints[%i][3] = {' %
              (prof.prefixName, ng))

    prof.ghostIt = 0
    boneIt.reset(prof.rootDag)
    while not boneIt.isDone():
        boneDag = om.MDagPath()
        boneIt.getPath(boneDag)

        fdag = om.MFnDagNode(boneDag)
        for i in range(0, fdag.childCount()):
            ochild = fdag.child(i)
            childDag = om.MDagPath.getAPathTo(ochild)
            writeAnEdgeConstraint(rec, prof, boneDag, childDag)
            prof.ghostIt = prof.ghostIt + 1

        boneIt.next()

    rec.write('\n};')

    nbtc = 0
    boneIt.reset(prof.rootDag)
    while not boneIt.isDone():
        boneDag = om.MDagPath()
        boneIt.getPath(boneDag)

        fdag = om.MFnDagNode(boneDag)
        for i in range(0, fdag.childCount()):
            ochild = fdag.child(i)
            childDag = om.MDagPath.getAPathTo(ochild)
            nbtc = nbtc + getNumChild(childDag)

        boneIt.next()

    print(' write %i bend-twist constraint ' % nbtc)
    rec.write('\nstatic const int s%sNumBendAndTwistConstraints = %i;' %
              (prof.prefixName, nbtc))
    rec.write('\nstatic const int s%sBendAndTwistConstraints[%i][5] = {' %
              (prof.prefixName, nbtc))

    boneIt.reset(prof.rootDag)
    while not boneIt.isDone():
        boneDag = om.MDagPath()
        boneIt.getPath(boneDag)

        fdag = om.MFnDagNode(boneDag)
        for i in range(0, fdag.childCount()):
            ochild = fdag.child(i)
            childDag = om.MDagPath.getAPathTo(ochild)
            for j in range(0, getNumChild(childDag)):
                writeABendTwistConstraint(rec, prof, boneDag, childDag,
                                          getChildDag(childDag, j))

        boneIt.next()

    rec.write('\n};')
Example #26
0
def getChildDag(boneDag, i):
    fdag = om.MFnDagNode(boneDag)
    ochild = fdag.child(i)
    childDag = om.MDagPath.getAPathTo(ochild)
    return childDag
Example #27
0
def getNumChild(boneDag):
    fdag = om.MFnDagNode(boneDag)
    return fdag.childCount()
Example #28
0
    attr.setWritable(True)


def MAKE_OUTPUT(attr):
    attr.setKeyable(False)
    attr.setStorable(False)
    attr.setReadable(True)
    attr.setWritable(False)


# Define the name of the node
kPluginNodeTypeName = "LSystemInstanceNode"

# Give the node a unique ID. Make sure this ID is different from all of your
# other nodes!
LSystemInstanceNodeID = OpenMaya.MTypeId(0x8714)

kDefaultStringAttrValue = "C:\Users\SIG\Documents\GitHub\CIS660HW3\plants\simple1.txt"


# Node definition
class LSystemInstanceNode(OpenMayaMPx.MPxNode):
    # Declare class variables:
    # TODO:: declare the input and output class variables
    #         i.e. inNumPoints = OpenMaya.MObject()

    angle = OpenMaya.MObject()
    stepSize = OpenMaya.MObject()
    grammarFile = OpenMaya.MObject()
    iterations = OpenMaya.MObject()
Example #29
0
def nodeInitializer():
    tAttr = OpenMaya.MFnTypedAttribute()
    nAttr = OpenMaya.MFnNumericAttribute()

    # TODO:: initialize the input and output attributes. Be sure to use the
    #         MAKE_INPUT and MAKE_OUTPUT functions.

    LSystemInstanceNode.angle = nAttr.create("angle", "a",
                                             OpenMaya.MFnNumericData.kDouble,
                                             10.0)
    MAKE_INPUT(nAttr)
    LSystemInstanceNode.stepSize = nAttr.create(
        "stepSize", "ss", OpenMaya.MFnNumericData.kDouble, 1.0)
    MAKE_INPUT(nAttr)

    stringData = OpenMaya.MFnStringData().create(kDefaultStringAttrValue)
    LSystemInstanceNode.grammarFile = tAttr.create("grammarFile", "g",
                                                   OpenMaya.MFnData.kString,
                                                   stringData)
    MAKE_INPUT(nAttr)
    LSystemInstanceNode.iterations = nAttr.create("iterations", "i",
                                                  OpenMaya.MFnNumericData.kInt,
                                                  2)
    MAKE_INPUT(nAttr)

    LSystemInstanceNode.outputBranches = tAttr.create(
        "outputBranches", "ob", OpenMaya.MFnArrayAttrsData.kDynArrayAttrs)
    MAKE_OUTPUT(tAttr)
    LSystemInstanceNode.outputFlowers = tAttr.create(
        "outputFlowers", "of", OpenMaya.MFnArrayAttrsData.kDynArrayAttrs)
    MAKE_OUTPUT(tAttr)

    try:
        # TODO:: add the attributes to the node and set up the
        #         attributeAffects (addAttribute, and attributeAffects)
        print "Initialization!\n"

        LSystemInstanceNode.addAttribute(LSystemInstanceNode.angle)
        LSystemInstanceNode.addAttribute(LSystemInstanceNode.stepSize)
        LSystemInstanceNode.addAttribute(LSystemInstanceNode.iterations)
        LSystemInstanceNode.addAttribute(LSystemInstanceNode.grammarFile)
        LSystemInstanceNode.addAttribute(LSystemInstanceNode.outputBranches)
        LSystemInstanceNode.addAttribute(LSystemInstanceNode.outputFlowers)
        print "I'm here now \n"
        LSystemInstanceNode.attributeAffects(
            LSystemInstanceNode.angle, LSystemInstanceNode.outputBranches)
        LSystemInstanceNode.attributeAffects(LSystemInstanceNode.angle,
                                             LSystemInstanceNode.outputFlowers)
        LSystemInstanceNode.attributeAffects(
            LSystemInstanceNode.stepSize, LSystemInstanceNode.outputBranches)
        LSystemInstanceNode.attributeAffects(LSystemInstanceNode.stepSize,
                                             LSystemInstanceNode.outputFlowers)
        LSystemInstanceNode.attributeAffects(
            LSystemInstanceNode.iterations, LSystemInstanceNode.outputBranches)
        LSystemInstanceNode.attributeAffects(LSystemInstanceNode.iterations,
                                             LSystemInstanceNode.outputFlowers)
        LSystemInstanceNode.attributeAffects(
            LSystemInstanceNode.grammarFile,
            LSystemInstanceNode.outputBranches)
        LSystemInstanceNode.attributeAffects(LSystemInstanceNode.grammarFile,
                                             LSystemInstanceNode.outputFlowers)

    except:
        sys.stderr.write(
            ("Failed to create attributes of %s node\n", kPluginNodeTypeName))
Example #30
0
    def getVoxels(self, mVoxelDistance, mBBox, mMeshObj):
        '''
		iterate all the points inside the bounding box and do the
		intersection test with the mesh
		odd intersection times: inside the mesh
		else: outside the mesh
		onlu create voxel inside the mesh
		'''
        voxelCenterPositions = []
        uvArray = []
        voxelWeights = []
        voxelBlendWeights = []

        util = OpenMaya.MScriptUtil()

        mHalfVoxelDistance = mVoxelDistance / 2

        mMidPoint = OpenMaya.MPoint()
        mMidPoint.x = (mBBox.min().x + mBBox.max().x) / 2
        mMidPoint.y = (mBBox.min().y + mBBox.max().y) / 2
        mMidPoint.z = (mBBox.min().z + mBBox.max().z) / 2

        def floatRange(start, stop, step):
            s = start
            if s < stop:
                while (s < stop):
                    yield s
                    s = s + step
            else:
                while (s > stop):
                    yield s
                    s = s - step

        # iterate all the points inside the BoundingBox
        # iterate from the MidPoint
        # searching algorithm
        def searchArea(startPoint, endPoint, step, rayDirection,
                       voxelCenterPositions):
            for point_Zcoord in floatRange(startPoint.z, endPoint.z, step):
                for point_Xcoord in floatRange(startPoint.x, endPoint.x, step):
                    for point_Ycoord in floatRange(startPoint.y, endPoint.y,
                                                   step):
                        #create ray source and direction
                        raySource = OpenMaya.MFloatPoint(
                            point_Xcoord, point_Ycoord, point_Zcoord)
                        #rayDirection = OpenMaya.MFloatVector(0,0,-1)
                        hitPointArray = OpenMaya.MFloatPointArray()
                        hitRayParams = OpenMaya.MFloatArray()
                        tolerance = 1e-6
                        mMeshObj.allIntersections(
                            raySource,  #raySource
                            rayDirection,  #rayDirection
                            None,  #faceIds do not need to filter the face
                            None,  #triDis do not need to filter the tris
                            False,  # do not need to sort the IDs
                            OpenMaya.MSpace.
                            kTransform,  #ray source and direction are specified in the mesh local coordinates
                            float(9999),  #the range of the ray
                            False,  #do not need to test both directions	
                            None,  #do not need accelParams
                            False,  #do not need to sort hits
                            hitPointArray,  #return the hit point array
                            hitRayParams,  #return hit point distance params
                            None,  #do not need hit faces ids
                            None,  #do not need hit tris ids
                            None,  #do not need barycentric coordinates of faces
                            None,  #do not need barycentric coordinates of tris
                            tolerance  #hit tolerance
                        )

                        #add the inside raysouce into list for voxel placement
                        if (hitPointArray.length() % 2 == 1):
                            voxelCenterPositions.append(raySource)
                            #also need to query the intersection geometry color
                            #find nearest intersection point
                            #http://www.chadvernon.com/blog/resources/maya-api-programming/mscriptutil/
                            #Since the Maya API is designed as a C++ library, it has many pointers and references
                            #that are passed into and returned from various functions.
                            uvPoint = util.asFloat2Ptr()
                            mPoint = OpenMaya.MPoint(raySource)
                            mMeshObj.getUVAtPoint(mPoint, uvPoint)
                            if self.skinCluster:
                                pointWeight = self.getClosetPointWeight(mPoint)
                                pointBlendWeight = self.getClosetPointBlendWeight(
                                    mPoint)
                                voxelWeights.append(pointWeight)
                                voxelBlendWeights.append(pointBlendWeight)
                            u = util.getFloat2ArrayItem(uvPoint, 0, 0)
                            v = util.getFloat2ArrayItem(uvPoint, 0, 1)
                            uv = [u, v]
                            uvArray.append(uv)

        #populate raysource Positions
        xmin = mBBox.min().x
        ymin = mBBox.min().y
        zmin = mBBox.min().z
        xmax = mBBox.max().x
        ymax = mBBox.max().y
        zmax = mBBox.max().z
        mBBoxPoints = [
            OpenMaya.MPoint(xmin, ymin, zmin),
            OpenMaya.MPoint(xmin, ymin, zmax),
            OpenMaya.MPoint(xmin, ymax, zmin),
            OpenMaya.MPoint(xmin, ymax, zmax),
            OpenMaya.MPoint(xmax, ymin, zmin),
            OpenMaya.MPoint(xmax, ymin, zmax),
            OpenMaya.MPoint(xmax, ymax, zmin),
            OpenMaya.MPoint(xmax, ymax, zmax)
        ]
        #search all the area inside the bounding box from center
        #'''
        rayDirection = OpenMaya.MFloatVector(-1, 0, 0)
        searchArea(mMidPoint, mBBoxPoints[0], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x
        mNewPoint.y = mMidPoint.y
        mNewPoint.z = mMidPoint.z + mVoxelDistance
        searchArea(mNewPoint, mBBoxPoints[1], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x
        mNewPoint.y = mMidPoint.y + mVoxelDistance
        mNewPoint.z = mMidPoint.z
        searchArea(mNewPoint, mBBoxPoints[2], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x
        mNewPoint.y = mMidPoint.y + mVoxelDistance
        mNewPoint.z = mMidPoint.z + mVoxelDistance
        searchArea(mNewPoint, mBBoxPoints[3], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        rayDirection = OpenMaya.MFloatVector(1, 0, 0)
        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x + mVoxelDistance
        mNewPoint.y = mMidPoint.y
        mNewPoint.z = mMidPoint.z
        searchArea(mNewPoint, mBBoxPoints[4], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x + mVoxelDistance
        mNewPoint.y = mMidPoint.y
        mNewPoint.z = mMidPoint.z + mVoxelDistance
        searchArea(mNewPoint, mBBoxPoints[5], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x + mVoxelDistance
        mNewPoint.y = mMidPoint.y + mVoxelDistance
        mNewPoint.z = mMidPoint.z
        searchArea(mNewPoint, mBBoxPoints[6], mVoxelDistance, rayDirection,
                   voxelCenterPositions)

        mNewPoint = OpenMaya.MPoint()
        mNewPoint.x = mMidPoint.x + mVoxelDistance
        mNewPoint.y = mMidPoint.y + mVoxelDistance
        mNewPoint.z = mMidPoint.z + mVoxelDistance
        searchArea(mNewPoint, mBBoxPoints[7], mVoxelDistance, rayDirection,
                   voxelCenterPositions)
        #'''
        '''
		for point_Zcoord in floatRange (mMinPoint.z, mMaxPoint.z, mVoxelDistance):
			for point_Xcoord in floatRange (mMinPoint.x, mMaxPoint.x, mVoxelDistance):
				for point_Ycoord in floatRange (mMinPoint.y, mMaxPoint.y, mVoxelDistance):
					#create ray source and direction
					raySource = OpenMaya.MFloatPoint(point_Xcoord,point_Ycoord,point_Zcoord)
					rayDirection = OpenMaya.MFloatVector(0,0,-1)
					hitPointArray = OpenMaya.MFloatPointArray()
					tolerance = 1e-6
					mMeshObj.allIntersections( raySource,   	   	#raySource
											   rayDirection,	   	#rayDirection
											   None,			   	#faceIds do not need to filter the face
											   None,			   	#triDis do not need to filter the tris
											   False,				# do not need to sort the IDs
											   OpenMaya.MSpace.kTransform,	#ray source and direction are specified in the mesh local coordinates
											   float(9999),			#the range of the ray
											   False,				#do not need to test both directions	
											   None,				#do not need accelParams
											   False,				#do not need to sort hits
											   hitPointArray,		#return the hit point array
											   None,				#do not need the hit point distance params
											   None,				#do not need hit faces ids
											   None,				#do not need hit tris ids
											   None,				#do not need barycentric coordinates of faces
											   None,				#do not need barycentric coordinates of tris
											   tolerance            #hit tolerance
												)
					if (hitPointArray.length()%2 == 1):
						#createVoxelMesh(meshContainer,raySource,0.49)
						voxelCenterPositions.append(raySource)
		'''
        voxelData = voxel()
        voxelData.voxelCenterPositions = voxelCenterPositions
        voxelData.uvCoordArray = uvArray
        voxelData.weights = voxelWeights
        voxelData.blendWeights = voxelBlendWeights
        return voxelData
Example #31
0
    def nodeInitializer():
        nAttr = OpenMaya.MFnNumericAttribute()
        mAttr = OpenMaya.MFnMatrixAttribute()
        
        try:
            scaleTexture.outColor = nAttr.createColor("outColor", "oc")
            nAttr.setKeyable(0)
            nAttr.setStorable(0)
            nAttr.setReadable(1)
            nAttr.setWritable(0)
            
            scaleTexture.outAlpha = nAttr.create("outAlpha", "oa", OpenMaya.MFnNumericData.kFloat)
            nAttr.setKeyable(0)
            nAttr.setStorable(0)
            nAttr.setReadable(1)
            nAttr.setWritable(0)
            
            # 2D Params
#            uvChild1 = nAttr.create( "uCoord", "u", OpenMaya.MFnNumericData.kFloat )
#            uvChild2 = nAttr.create( "vCoord", "v", OpenMaya.MFnNumericData.kFloat )
#            bilerpTexture.UVCoord = nAttr.create( "uvCoord", "uv", uvChild1, uvChild2 )
#            bilerpTexture.makeInput( nAttr )
#            nAttr.setHidden( True )
#            
#            uvChild3 = nAttr.create( "uvFilterSizeX", "fsx", OpenMaya.MFnNumericData.kFloat )
#            uvChild4 = nAttr.create( "uvFilterSizeY", "fsy", OpenMaya.MFnNumericData.kFloat )
#            bilerpTexture.uvFilterSize = nAttr.create( "uvFilterSize", "fs", uvChild3, uvChild4 )
#            bilerpTexture.makeInput( nAttr )
#            nAttr.setHidden( True )
            
            # 3D Params
            scaleTexture.placementMatrix = mAttr.create("placementMatrix", "pm")
            scaleTexture.makeInput(mAttr)
            
            scaleTexture.pointWorld = nAttr.createPoint("pointWorld", "pw")
            scaleTexture.makeInput(nAttr)
            nAttr.setHidden(True)
            
            scaleTexture.tex1 = scaleTexture.makeColor("tex1", "t1")
            scaleTexture.tex2 = scaleTexture.makeColor("tex2", "t2")


        except:
            OpenMaya.MGlobal.displayError("Failed to create scaleTexture attributes\n")
            raise
        
        try:
            scaleTexture.addAttribute(scaleTexture.outColor)
            scaleTexture.addAttribute(scaleTexture.outAlpha)
            scaleTexture.addAttribute(scaleTexture.placementMatrix)
            scaleTexture.addAttribute(scaleTexture.pointWorld)
            
            scaleTexture.addAttribute(scaleTexture.tex1)
            scaleTexture.addAttribute(scaleTexture.tex2)

            
#            scaleTexture.attributeAffects(scaleTexture.tex1, scaleTexture.outColor)
#            scaleTexture.attributeAffects(scaleTexture.tex2, scaleTexture.outColor)
#            scaleTexture.attributeAffects(scaleTexture.amount, scaleTexture.outColor)
#
#            scaleTexture.attributeAffects(scaleTexture.pointWorld, scaleTexture.outColor)
#            scaleTexture.attributeAffects(scaleTexture.placementMatrix, scaleTexture.outColor)
#            
#            scaleTexture.attributeAffects(scaleTexture.tex1, scaleTexture.outAlpha)
#            scaleTexture.attributeAffects(scaleTexture.tex2, scaleTexture.outAlpha)
#            scaleTexture.attributeAffects(scaleTexture.amount, scaleTexture.outAlpha)
#
#            scaleTexture.attributeAffects(scaleTexture.pointWorld, scaleTexture.outAlpha)
#            scaleTexture.attributeAffects(scaleTexture.placementMatrix, scaleTexture.outAlpha)
            
        except:
            OpenMaya.MGlobal.displayError("Failed to add attributes\n")
            raise
Example #32
0
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2017, Anima Istanbul
#
# This module is part of anima-tools and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
"""create deformer with::

  deformer -type "randomizeUVDeformer"

"""
import sys

from maya import OpenMaya, OpenMayaMPx

node_type_name = "randomizeUVDeformer"
plugin_id = OpenMaya.MTypeId(0x00380)


class RandomizeDeformer(OpenMayaMPx.MPxDeformerNode):
    """a node to randomize uvs (for now)
    """

    aMaxOffset = OpenMaya.MObject()

    def __init__(self):
        OpenMayaMPx.MPxDeformerNode.__init__(self)

    def get_deformer_input_geometry(self, data_block, geometry_index):
        """Obtain a reference to the input mesh. This mesh will be used to
        compute our bounding box, and we will also require its normals.
Example #33
0
def nodeInitializer():
    nAttr = OpenMaya.MFnNumericAttribute()
    eAttr = OpenMaya.MFnEnumAttribute()

    try:
        substrate.mKd = nAttr.createColor("Kd", "kd")
        nAttr.setKeyable(1)
        nAttr.setStorable(1)
        nAttr.setReadable(1)
        nAttr.setWritable(1)
        nAttr.setDefault(0.25, 0.25, 0.25)

        substrate.mKs = nAttr.createColor("Ks", "ks")
        nAttr.setKeyable(1)
        nAttr.setStorable(1)
        nAttr.setReadable(1)
        nAttr.setWritable(1)
        nAttr.setDefault(0.25, 0.25, 0.25)

        substrate.mRemapRoughness = nAttr.create(
            "remapRoughness", "rr", OpenMaya.MFnNumericData.kBoolean, True)
        nAttr.setKeyable(1)
        nAttr.setStorable(1)
        nAttr.setReadable(1)
        nAttr.setWritable(1)
        nAttr.setConnectable(0)

        substrate.mURoughness = nAttr.create("uRoughness", "ur",
                                             OpenMaya.MFnNumericData.kFloat)
        nAttr.setKeyable(1)
        nAttr.setStorable(1)
        nAttr.setReadable(1)
        nAttr.setWritable(1)
        nAttr.setDefault(-1.0)

        substrate.mVRoughness = nAttr.create("vRoughness", "vr",
                                             OpenMaya.MFnNumericData.kFloat)
        nAttr.setKeyable(1)
        nAttr.setStorable(1)
        nAttr.setReadable(1)
        nAttr.setWritable(1)
        nAttr.setDefault(-1.0)

        substrate.mBump = nAttr.create("bumpmap", "b",
                                       OpenMaya.MFnNumericData.kFloat)
        nAttr.setKeyable(1)
        nAttr.setStorable(1)
        nAttr.setReadable(1)
        nAttr.setWritable(1)
        nAttr.setDefault(-1.0)

        substrate.mOutColor = nAttr.createColor("outColor", "oc")
        nAttr.setStorable(0)
        nAttr.setHidden(0)
        nAttr.setReadable(1)
        nAttr.setWritable(0)
    except:
        sys.stderr.write("Failed to create attributes\n")
        raise

    try:
        substrate.addAttribute(substrate.mKd)
        substrate.addAttribute(substrate.mKs)
        substrate.addAttribute(substrate.mRemapRoughness)
        substrate.addAttribute(substrate.mURoughness)
        substrate.addAttribute(substrate.mVRoughness)
        substrate.addAttribute(substrate.mBump)
        substrate.addAttribute(substrate.mOutColor)
    except:
        sys.stderr.write("Failed to add attributes\n")
        raise

    try:
        substrate.attributeAffects(substrate.mKd, substrate.mOutColor)
    except:
        sys.stderr.write("Failed in setting attributeAffects\n")
        raise
Example #34
0
 def isShape(self):
     selectionList = om.MSelectionList()
     mObject = om.MObject()
     selectionList.add(self.getFullPathName())
     selectionList.getDependNode(0, mObject)
     return mObject.hasFn(om.MFn.kShape)
Example #35
0
 def getMObjectForNode(nodeName):
     sel = om.MSelectionList()
     sel.add(nodeName)
     obj = om.MObject()
     sel.getDependNode(0, obj)
     return obj
Example #36
0
    def compute(self, plug, dataBlock):
        pass

        if (plug == ehm_surfaceOrient.rotation):

            # get input translate
            translateHandle = dataBlock.inputValue(ehm_surfaceOrient.translate)
            translateValue = translateHandle.asDouble3()
            pTranslate = OpenMaya.MPoint(translateValue[0], translateValue[1],
                                         translateValue[2], 1.0)

            # get surface
            surfaceHandle = dataBlock.inputValue(
                ehm_surfaceOrient.inputSurface)
            oSurf = surfaceHandle.asNurbsSurface()

            # get params at closest point to input translate
            util = OpenMaya.MScriptUtil()
            util.createFromDouble(0)
            paramU = util.asDoublePtr()

            utilV = OpenMaya.MScriptUtil()
            utilV.createFromDouble(0)
            paramV = utilV.asDoublePtr()

            fnSurface = OpenMaya.MFnNurbsSurface(oSurf)
            pointOnSurf = fnSurface.closestPoint(pTranslate, paramU, paramV,
                                                 False, 0.001,
                                                 OpenMaya.MSpace.kObject)

            paramU = OpenMaya.MScriptUtil().getDouble(paramU)
            paramV = OpenMaya.MScriptUtil().getDouble(paramV)

            # get tangent at point
            tangentU = OpenMaya.MVector()
            tangentV = OpenMaya.MVector()
            fnSurface.getTangents(paramU, paramV, tangentU, tangentU,
                                  OpenMaya.MSpace.kObject)

            # get normal at point
            normal = fnSurface.normal(paramU, paramV, OpenMaya.MSpace.kObject)
            normal.normalize()

            # make x,y and z perpendicular
            tangentV = tangentU ^ normal

            # get rotation from 3 vectors, tangentU, tangentV and normal
            resultMatrix = OpenMaya.MMatrix()
            utilM = OpenMaya.MScriptUtil()
            utilM.createMatrixFromList([
                tangentU.x, tangentU.y, tangentU.z, 0.0, tangentV.x,
                tangentV.y, tangentV.z, 0.0, normal.x, normal.y, normal.z, 0.0,
                pTranslate.x, pTranslate.y, pTranslate.z, 1.0
            ], resultMatrix)

            transMatrix = OpenMaya.MTransformationMatrix(resultMatrix)

            resultEuler = transMatrix.eulerRotation()

            # set rotation value
            xAngle = OpenMaya.MAngle(resultEuler.x)
            rotateHandle = dataBlock.outputValue(ehm_surfaceOrient.rotateX)
            rotateHandle.setMAngle(xAngle)

            yAngle = OpenMaya.MAngle(resultEuler.y)
            rotateHandle = dataBlock.outputValue(ehm_surfaceOrient.rotateY)
            rotateHandle.setMAngle(yAngle)

            zAngle = OpenMaya.MAngle(resultEuler.z)
            rotateHandle = dataBlock.outputValue(ehm_surfaceOrient.rotateZ)
            rotateHandle.setMAngle(zAngle)

            #outputHandle = dataBlock.outputValue( ehm_surfaceOrient.rotation )
            #outputHandle.setFloat( result )

            dataBlock.setClean(plug)
Example #37
0
    def yetiLink(self):
        '''
		examine yeti
		'''
        self.allConnect()

        if 'pgYetiMaya' in pm.allNodeTypes():
            yetiNodeList = pm.ls(type='pgYetiMaya')
            yetiList = [node.getParent() for node in yetiNodeList]
            if yetiList:
                if not pm.objExists('yeti_G'):
                    OpenMaya.MGlobal_displayError('Not yeti_G Group')
                    return
                if not pm.objExists('yeti_setup_G'):
                    OpenMaya.MGlobal_displayError('Not yeti_setup_G Group')
                    return

                yetiGroup = pm.PyNode('yeti_G')
                if self.main.showMod not in yetiGroup.v.inputs(p=True):
                    self.main.showMod.connect(yetiGroup.v, f=True)

                if not self.main.hasAttr('yeti'):
                    self.main.addAttr('yeti',
                                      at='long',
                                      min=0,
                                      max=1,
                                      dv=0,
                                      k=True)

                if pm.PyNode('yeti_show_G') not in self.main.yeti.outputs():
                    self.main.yeti.connect('yeti_show_G.v', f=True)

                conAttrList = []

                for shape in yetiNodeList:
                    if shape.cacheFileName.get():
                        yeti = shape.getParent()
                        cons = yeti.listRelatives(type='parentConstraint')

                        if not cons:
                            OpenMaya.MGlobal_displayError(
                                'Not do %s node parentConstraint' % yeti)
                        else:
                            conAttrs = [
                                attr.listAttr(ud=True)[0] for attr in cons
                            ]

                            conAttrList += conAttrs

                        if not self.main.hasAttr('abc'):
                            self.main.addAttr('abc',
                                              at='enum',
                                              en="efx:anim:",
                                              k=True)
                            self.main.abc.set(1)

                        if self.main.abc not in shape.fileMode.inputs(p=True):
                            self.main.abc.connect(shape.fileMode, f=True)

                if conAttrList:
                    for att in conAttrList:
                        if self.main.abc not in att.inputs(p=True):
                            self.main.abc.connect(att, f=True)

                self.setMesh('pgYetiMaya')

                if conAttrList:
                    self.displayDialog(
                        '总控abc属性已关联yeti的约束节点和cache属性! 蒙皮模型已设置不可渲染, 并隐藏锁定!')
                else:
                    self.displayDialog(
                        '总控abc属性已关联yeti的cache属性! 蒙皮模型已设置不可渲染, 并隐藏锁定! 约束节点没有!')
        else:
            return False
Example #38
0
"Fourth order Runge Kutta method to solve the second order differential equation for mass-spring-damper systems"

__author__ = "Paolo Dominici"
__version__ = "Version: 1.0"
__date__ = "Date: 2008/12/04"

import sys, math
from maya import OpenMaya, OpenMayaAnim, OpenMayaMPx

nodeName = "rungeKutta"
spNodeId = OpenMaya.MTypeId(0x58805)


# node definition
class spNode(OpenMayaMPx.MPxNode):
    currentTime = OpenMaya.MObject()
    targetPosition = OpenMaya.MObject()
    springConstant = OpenMaya.MObject()
    dampingRatio = OpenMaya.MObject()
    frameIterations = OpenMaya.MObject()
    outPosition = OpenMaya.MObject()
    outVelocity = OpenMaya.MObject()

    k = 0.0
    c = 0.0

    lastTime = 0.0
    lastPos = [0.0, 0.0, 0.0]
    lastVel = [0.0, 0.0, 0.0]

    def __init__(self):
Example #39
0
def deltaTool(blendShapeNode, correctiveGroup, correctiveItem, mirrorPlane, mirrorSide,
              mode, pruneValue, factorValue, factorAdd, originalPointIndex, tolerance):    
    #print 'def deltaTool'
    # Funcion that correspond the Delta Option TAP from the UI. The options PRUNE, FACTOR, ZERO

    
    '''
    mirrorPlane:
    1 = 'XY'
    2 = 'YZ'
    3 = 'XZ'
    
    mirrorSide:
    1 = Pos
    2 = Neg
    3 = All
    4 = User    
    '''
    
    if mirrorPlane == 1:
        mirrorPlane = 'XY'
    elif mirrorPlane == 2:
        mirrorPlane = 'YZ'
    elif mirrorPlane == 3:
        mirrorPlane = 'XZ'
        
    if mirrorSide == 1:
        positive = True
        allDeltaIndx = None
        selectionUser = None
    elif mirrorSide == 2:
        positive = False
        allDeltaIndx = None
        selectionUser = None
    elif mirrorSide == 3:
        positive = None
        allDeltaIndx = True
        selectionUser = None
    elif mirrorSide == 4:
        positive = None
        allDeltaIndx = None
        selectionUser = True
    
    
    pointIndex = combinePointIndex(blendShapeNode, correctiveGroup, correctiveItem)
    # Gets all index from the data acquired of the corrective
    deltaIndx = []
    for u in pointIndex:
        deltaIndx.append(int(u[-1]))
        
    #if not pnc:
    #    print 'creating PNC data...'
    #    pnc = posNegCenterIndex(blendShapeNode, mirrorPlane, tolerance)
        
        #print pnc
    #print 'pnc: ', pnc
    
    pnc = posNegCenterIndex(blendShapeNode, mirrorPlane, tolerance)
    posIndx = pnc[0]
    negIndx = pnc[1]
    zeroIndx = pnc[2]     
    
    # Analyzing Selection Format                
    if selectionUser:
        #print 'selectionUser is the priority'
        sideIndx = []
        try:
            userSel = unflattenList(cmds.ls(sl=True))
            for i in userSel:
                if i in deltaIndx:
                    sideIndx.append(i)
        except:
            om.displayInfo('There is no vertices selected by the user')
        
    elif allDeltaIndx:
        # Act in all delta points
        sideIndx = posIndx + negIndx + zeroIndx
    else:
        # Else, check if the posToNeg is to continue the sideIndx as pos or neg index
        if positive:
            sideIndx = posIndx + zeroIndx
        else:
            sideIndx = negIndx + zeroIndx
    
    indexResult = []
    if mode == 'prune':
        pointIndexList = []
        for pi in xrange(len(pointIndex)):
            if pointIndex[pi][3] in sideIndx:
                if not isPruned(pointIndex[pi], pruneValue):
                    pointIndexList.append(pointIndex[pi])
                    indexResult.append(pointIndex[pi][3])
            else:
                pointIndexList.append(pointIndex[pi])
                indexResult.append(pointIndex[pi][3])        

    elif mode == 'factor':
        pointIndexList = []
        for pi in xrange(len(pointIndex)):
            if pointIndex[pi][3] in sideIndx:
                pointIndexList.append(factorPoint(pointIndex[pi], 
                                                  originalPointIndex[pi], 
                                                  factorAdd, factorValue))
                indexResult.append(pointIndex[pi][3])
            else:
                pointIndexList.append(pointIndex[pi])
                indexResult.append(pointIndex[pi][3])
    
    elif mode == 'zero':
        pointIndexList = []
        for pi in xrange(len(pointIndex)):
            if pointIndex[pi][3] in sideIndx:
                pZero = (0.0, 0.0, 0.0, pointIndex[pi][3])
                pointIndexList.append(pZero)
                indexResult.append(pointIndex[pi][3])
            else:
                pointIndexList.append(pointIndex[pi])
                indexResult.append(pointIndex[pi][3])
                
    elif mode == 'reset':
        pointIndexList = []
        for pi in xrange(len(pointIndex)):
            if pointIndex[pi][3] in sideIndx:
                pReset = (originalPointIndex[pi][0],originalPointIndex[pi][1],
                          originalPointIndex[pi][2], pointIndex[pi][3])
                pointIndexList.append(pReset)
                indexResult.append(pointIndex[pi][3])
            else:
                pointIndexList.append(pointIndex[pi])
                indexResult.append(pointIndex[pi][3])
    '''
    elif mode == 'check':
        selectVtxFromIndices(blendShapeNode, deltaIndx)
    '''
    deltaData = indexPointToDeltaData(pointIndexList)
    # Apply data to the array values
    getApplyPI(blendShapeNode, correctiveGroup, correctiveItem, mode='applyPoint', 
               pointData=deltaData[0])
    getApplyPI(blendShapeNode, correctiveGroup, correctiveItem, mode='applyIndex', 
               componentData=deltaData[1])                   
    
    cmds.refresh()
    if mirrorSide != 4:
        try:
            selectVtxFromIndices(blendShapeNode, indexResult)
        except:
            'There is no Delta to be showed'
            pass
    
    #selectVtxFromIndices(blendShapeNode, listIndice=negIndx)
    #print 'List before Pruning: ', pointIndex
    #print 'List After Pruning: ', pointIndexList
    return pointIndex
Example #40
0
class RandomizeDeformer(OpenMayaMPx.MPxDeformerNode):
    """a node to randomize uvs (for now)
    """

    aMaxOffset = OpenMaya.MObject()

    def __init__(self):
        OpenMayaMPx.MPxDeformerNode.__init__(self)

    def get_deformer_input_geometry(self, data_block, geometry_index):
        """Obtain a reference to the input mesh. This mesh will be used to
        compute our bounding box, and we will also require its normals.

        We use MDataBlock.outputArrayValue() to avoid having to recompute the
        mesh and propagate this recomputation throughout theDependency Graph.

        OpenMayaMPx.cvar.MPxDeformerNode_input and
        OpenMayaMPx.cvar.MPxDeformerNode_inputGeom are SWIG-generated
        variables which respectively contain references to the deformer's
        'input' attribute and 'inputGeom' attribute.
        """
        input_attribute = OpenMayaMPx.cvar.MPxDeformerNode_input
        input_geometry_attribute = OpenMayaMPx.cvar.MPxDeformerNode_inputGeom

        input_handle = data_block.outputArrayValue(input_attribute)
        input_handle.jumpToElement(geometry_index)
        input_geometry_object =\
            input_handle.outputValue().child(input_geometry_attribute).asMesh()

        return input_geometry_object

    def deform(self, data_block, geometry_iterator, local_to_world_matrix,
               geometry_index):
        """do deformation
        """
        envelope_attribute = OpenMayaMPx.cvar.MPxDeformerNode_envelope
        envelope_value = data_block.inputValue(envelope_attribute).asFloat()

        input_geometry_object = \
            self.get_deformer_input_geometry(data_block, geometry_index)

        # Obtain the list of normals for each vertex in the mesh.
        mesh_fn = OpenMaya.MFnMesh(input_geometry_object)

        uv_shell_array = OpenMaya.MIntArray()
        u_array = OpenMaya.MFloatArray()
        v_array = OpenMaya.MFloatArray()
        script_util = OpenMaya.MScriptUtil(0)
        shells_ptr = script_util.asUintPtr()

        mesh_fn.getUvShellsIds(uv_shell_array, shells_ptr)
        mesh_fn.getUVs(u_array, v_array)

        max_offset_attr_handle = \
            data_block.inputValue(RandomizeDeformer.aMaxOffset)
        max_offset = max_offset_attr_handle.asInt()

        # compute and write the new uvs
        for uv_id in xrange(len(u_array)):
            shell_id = uv_shell_array[uv_id]
            offset_u = shell_id % max_offset
            u_array[uv_id] += offset_u

        mesh_fn.setUVs(u_array, v_array)

        uv_shell_array.clear()
        u_array.clear()
        v_array.clear()
def create_orient_group(*args):
    plane01_normal = None
    plane02_normal = None
    if (plane01 and my_control and not plane02):
        print("no plane02")
        #create helper plane. Find normals
        plane01_normal = plane01.get_normal()
        # if only one plane is provided, find which one of the world axes is orthogonal to the normal
        if (plane01_normal * om.MVector(1, 0, 0) == 0):
            plane02_normal = om.MVector(1, 0, 0)
        elif (plane01_normal * om.MVector(0, 1, 0) == 0):
            plane02_normal = om.MVector(0, 1, 0)
        elif (plane01_normal * om.MVector(0, 0, 1) == 0):
            plane02_normal = om.MVector(0, 0, 1)
        else:
            #if none of the axes are aligned with a world axis, ask for more verts to define a 2nd plane
            warning_msg(
                "No axes are aligned with a world axis. You'll need to select 6 vertices and then ctrl."
            )
            return
    elif (plane01 and my_control and plane02):
        #create helper plane/s. Find normals
        plane01_normal = plane01.get_normal()
        plane02_normal = plane02.get_normal()
        dot_prd = plane01_normal * plane02_normal
        #if both planes are the same warn and exit
        if almost_equal(abs(dot_prd), 1.0, decimal=4):
            print("dot product: ", dot_prd)
            warning_msg(
                "1st plane and 2nd plane are the same.Please select 2 different planes."
            )
            return
        #if planes are not orthogonal warn and aproximate
        if not almost_equal(abs(dot_prd), 0.0, decimal=4):
            print("dot product: ", dot_prd)
            warning_msg(
                "1st plane and 2nd plane are not orthogonal. Aproximating.")
            #return

    else:
        warning_msg("Please assign at least 1 plane and a control.")
        return

    #find 3rd vector
    plane03_normal = plane01_normal ^ plane02_normal
    #recross in case plane01 and plane02 were not originally orthogonal
    plane02_normal = plane03_normal ^ plane01_normal

    #create orient grp with same pivot as ctrl then parent ctrl
    orientGrp = mc.group(n=str(my_control).replace('_Ctrl', '_') + 'orientGrp',
                         em=1)
    constraint = mc.parentConstraint(my_control, orientGrp)
    mc.delete(constraint)
    mc.parent(my_control, orientGrp)

    #make rotation matrix from vectors
    #query matrix to use position row
    orientGrp_matrix = mc.xform(orientGrp, q=1, m=1)
    #query axes selection
    plane01_axis = mc.radioCollection(xyz_collection01, q=1, sl=1)
    plane02_axis = mc.radioCollection(xyz_collection02, q=1, sl=1)
    #assign vector order
    vectorX = None
    vectorY = None
    vectorZ = None
    if plane01_axis == xrb01.split("|")[-1]:
        vectorX = plane01_normal
        if plane02_axis == yrb02.split("|")[-1]:
            vectorY = plane02_normal
            vectorZ = plane03_normal
        if plane02_axis == zrb02.split("|")[-1]:
            vectorZ = plane02_normal
            vectorY = plane03_normal
    if plane01_axis == yrb01.split("|")[-1]:
        vectorY = plane01_normal
        if plane02_axis == xrb02.split("|")[-1]:
            vectorX = plane02_normal
            vectorZ = plane03_normal
        if plane02_axis == zrb02.split("|")[-1]:
            vectorZ = plane02_normal
            vectorX = plane03_normal
    if plane01_axis == zrb01.split("|")[-1]:
        vectorZ = plane01_normal
        if plane02_axis == xrb02.split("|")[-1]:
            vectorX = plane02_normal
            vectorY = plane03_normal
        if plane02_axis == yrb02.split("|")[-1]:
            vectorY = plane02_normal
            vectorX = plane03_normal

    #assign rotation matrix to orientGrp
    mc.xform(orientGrp,
             m=(vectorX.x, vectorX.y, vectorX.z, 0, vectorY.x, vectorY.y,
                vectorY.z, 0, vectorZ.x, vectorZ.y, vectorZ.z, 0,
                orientGrp_matrix[12], orientGrp_matrix[13],
                orientGrp_matrix[14], orientGrp_matrix[15]))
    #freeze transforms
    mc.makeIdentity(orientGrp, apply=1, t=1, n=0)
Example #42
0
def isShape(fullPathName):
    selectionList = om.MSelectionList()
    mObject = om.MObject()
    selectionList.add(fullPathName)
    selectionList.getDependNode(0, mObject)
    return bool(mObject.hasFn(om.MFn.kShape))
Example #43
0
 def getSkinClusterBlendWeight(self):
     mDagPath, component = self.getSkinClusterData(self.mfnSkinCluster)
     blendWeights = OpenMaya.MDoubleArray()
     self.mfnSkinCluster.getBlendWeights(mDagPath, component, blendWeights)
     return blendWeights
Example #44
0
def nodeInitializer():
    tAttr = OpenMaya.MFnTypedAttribute()
    nAttr = OpenMaya.MFnNumericAttribute()
    uAttr = OpenMaya.MFnUnitAttribute()
    mAttr = OpenMaya.MFnMatrixAttribute()

    # input surface
    ehm_surfaceOrient.inputSurface = tAttr.create(
        'inputSurface', 'is', OpenMaya.MFnNurbsSurfaceData.kNurbsSurface)
    tAttr.setStorable(1)
    tAttr.setWritable(1)
    ehm_surfaceOrient.addAttribute(ehm_surfaceOrient.inputSurface)

    # input Translate
    ehm_surfaceOrient.translateX = nAttr.create(
        "translateX", "tx", OpenMaya.MFnNumericData.kDouble, 0.0)
    nAttr.setStorable(0)

    ehm_surfaceOrient.translateY = nAttr.create(
        "translateY", "ty", OpenMaya.MFnNumericData.kDouble, 0.0)
    nAttr.setStorable(0)

    ehm_surfaceOrient.translateZ = nAttr.create(
        "translateZ", "tz", OpenMaya.MFnNumericData.kDouble, 0.0)
    nAttr.setStorable(0)

    ehm_surfaceOrient.translate = nAttr.create('translate', 't',
                                               ehm_surfaceOrient.translateX,
                                               ehm_surfaceOrient.translateY,
                                               ehm_surfaceOrient.translateZ)
    nAttr.setStorable(1)
    nAttr.setWritable(1)
    ehm_surfaceOrient.addAttribute(ehm_surfaceOrient.translate)

    # out rotation
    ehm_surfaceOrient.rotateX = uAttr.create("rotateX", "rx",
                                             OpenMaya.MFnUnitAttribute.kAngle,
                                             0.0)
    uAttr.setStorable(0)

    ehm_surfaceOrient.rotateY = uAttr.create("rotateY", "ry",
                                             OpenMaya.MFnUnitAttribute.kAngle,
                                             0.0)
    uAttr.setStorable(0)

    ehm_surfaceOrient.rotateZ = uAttr.create("rotateZ", "rz",
                                             OpenMaya.MFnUnitAttribute.kAngle,
                                             0.0)
    uAttr.setStorable(0)

    ehm_surfaceOrient.rotation = nAttr.create("rotate", "r",
                                              ehm_surfaceOrient.rotateX,
                                              ehm_surfaceOrient.rotateY,
                                              ehm_surfaceOrient.rotateZ)
    nAttr.setStorable(0)
    nAttr.setWritable(0)

    ehm_surfaceOrient.addAttribute(ehm_surfaceOrient.rotation)
    ehm_surfaceOrient.attributeAffects(ehm_surfaceOrient.inputSurface,
                                       ehm_surfaceOrient.rotation)
    ehm_surfaceOrient.attributeAffects(ehm_surfaceOrient.translate,
                                       ehm_surfaceOrient.rotation)
Example #45
0
b1xgCc.attachToAniModel('charA_head')
b1xgCc.exportCaches()



import maya.OpenMaya as OpenMaya
import maya.OpenMayaAnim as OpenMayaAnim
import maya.cmds as cmds
import maya.mel as mel

# poly mesh and skinCluster name
shapeName = 'pSphere1'
clusterName = 'skinCluster1'

# get the MFnSkinCluster for clusterName
selList = OpenMaya.MSelectionList()
selList.add(clusterName)
clusterNode = OpenMaya.MObject()
selList.getDependNode(0, clusterNode)
skinFn = OpenMayaAnim.MFnSkinCluster(clusterNode)

# get the MDagPath for all influence
infDags = OpenMaya.MDagPathArray()
skinFn.influenceObjects(infDags)

# create a dictionary whose key is the MPlug indice id and
# whose value is the influence list id
infIds = {}
infs = []
for x in xrange(infDags.length()):
	infPath = infDags[x].fullPathName()
Example #46
0
def findMeshIntersection(mesh, raySource, rayDir, maxDistance = 1000, tolerance = .1):
    """
    Return the closest point on a surface from a raySource and rayDir. Can't process uv point for surfaces yet
    Thanks to Deane @ https://groups.google.com/forum/?fromgroups#!topic/python_inside_maya/n6aJq27fg0o%5B1-25%5D
    Thanks to Samaneh Momtazmand for doing the r&d to get this working with surfaces
    
    :parameters:
        mesh(string) | Surface to cast at
        raySource(double3) | point from which to cast in world space
        rayDir(vector) | world space vector
	maxDistance(float) | Maximum cast distance 
	tolerance(float) | Tolerance for cast (surface cast mode only) 

    :returns:
        Dict ------------------------------------------------------------------
	'source'(double3) |  point from which we cast
	'hit'(double3) | world space points | active during single return
	'hits'(list) | world space points | active during multi return
	'uv'(double2) | uv on surface of hit | only works for mesh surfaces
	
    :raises:
	Exception | if reached
	
    """      
    try:
        _str_funcName = 'findMeshIntersection'

        try:
	    if cgmValid.isListArg(mesh):
		log.debug("{0}>>> list provided. Using first : {1}".format(_str_funcName,mesh))
		mesh = mesh[0]
            if len(mc.ls(mesh))>1:
                raise StandardError,"{0}>>> More than one mesh named: {1}".format(_str_funcName,mesh)
            _str_objType = search.returnObjectType(mesh)
            if _str_objType not in ['mesh','nurbsSurface']:
                raise ValueError,"Object type not supported | type: {0}".format(_str_objType)
	    
	    #Create an empty selection list.
	    selectionList = om.MSelectionList()

	    #Convert the 'raySource' parameter into an MFloatPoint.
	    #raySource = om.MFloatPoint(raySource[0], raySource[1], raySource[2])
	    mPoint_raySource = om.MFloatPoint(raySource[0], raySource[1], raySource[2])
	
	    #Convert the 'rayDir' parameter into an MVector.`
	    mVec_rayDirection = om.MFloatVector(rayDir[0], rayDir[1], rayDir[2])
	
	    #Create an empty MFloatPoint to receive the hit point from the call.
	    mPoint_hit = om.MFloatPoint()
	    
	    #centerPointVector = om.MFloatVector(centerPoint[0],centerPoint[1],centerPoint[2]) 
	    #rayDir = om.MFloatPoint(centerPointVector - raySourceVector)
	    maxDist = maxDistance
	    spc = om.MSpace.kWorld	
	    
        except Exception,error:
            raise ValueError,"Validation fail |{0}".format(error)    
        
        try:
	    if _str_objType == 'nurbsSurface': 
		log.debug("{0} | Surface cast mode".format(_str_funcName))
		
		surfaceShape = mc.listRelatives(mesh, s=1)[0]

		mPoint_raySource = om.MPoint(raySource[0], raySource[1], raySource[2])
		mVec_rayDirection = om.MVector(rayDir[0], rayDir[1], rayDir[2])
		mPoint_hit = om.MPoint()    
		selectionList = om.MSelectionList()
		selectionList.add(surfaceShape)
		surfacePath = om.MDagPath()
		selectionList.getDagPath(0, surfacePath)
		surfaceFn = om.MFnNurbsSurface(surfacePath)		
	
		#other variables 
		#uSU = om.MScriptUtil()
		#vSU = om.MScriptUtil()
		#uPtr = uSU.asDoublePtr()
		#vPtr = vSU.asDoublePtr()		
		mPoint_u = om.doublePtr()
		mPoint_v = om.doublePtr()
		
		#Get the closest intersection.
		gotHit = surfaceFn.intersect(mPoint_raySource,
		                             mVec_rayDirection,
		                             mPoint_u, mPoint_v,mPoint_hit, tolerance, spc, False, None, False, None)

	    elif _str_objType == 'mesh':
		log.debug("{0} | Mesh cast mode".format(_str_funcName))
		
		#Put the mesh's name on the selection list.
		selectionList.add(mesh)
	    
		#Create an empty MDagPath object.
		meshPath = om.MDagPath()
	    
		#Get the first item on the selection list (which will be our mesh)
		#as an MDagPath.
		selectionList.getDagPath(0, meshPath)
	    
		#Create an MFnMesh functionset to operate on the node pointed to by
		#the dag path.
		meshFn = om.MFnMesh(meshPath)
	    
		#Set up a variable for each remaining parameter in the
		#MFnMesh::closestIntersection call. We could have supplied these as
		#literal values in the call, but this makes the example more readable.
		sortIds = False
		#maxDist = maxDistance#om.MDistance.internalToUI(1000000)# This needs work    
		#maxDist = om.MDistance.internalToUI(maxDistance) # This needs work
		bothDirections = False
		noFaceIds = None
		noTriangleIds = None
		noAccelerator = None
		noHitParam = None
		noHitFace = None
		noHitTriangle = None
		noHitBary1 = None
		noHitBary2 = None
		
		#Get the closest intersection.
		gotHit = meshFn.closestIntersection(
		    mPoint_raySource, mVec_rayDirection,
		    noFaceIds, noTriangleIds,
		    sortIds, om.MSpace.kWorld, maxDist, bothDirections,
		    noAccelerator,
		    mPoint_hit,
		    noHitParam, noHitFace, noHitTriangle, noHitBary1, noHitBary2)
	    
		#Get the closest intersection.
		#gotHit=meshFn.closestIntersection(raySource,rayDirection,None,None,False,spc,maxDist,False,None,hitPoint,None,None,None,None,None)
	    else : raise ValueError,"Wrong surface type!"
        except Exception,error:
            raise Exception,"Cast fail |{0}".format(error)