Esempio n. 1
0
    def group_all_proxies(self):
        self.proxy_group_name = 'proxies_grp'
        try:
            om.MGlobal.getSelectionListByName(self.proxy_group_name)

            dg_mod = om.MDagModifier()
            dg_mod.commandToExecute('parent ' + self.proxy_groups + ' ' + self.proxy_group_name)
            dg_mod.doIt()
        except:
            dg_mod = om.MDagModifier()
            dg_mod.commandToExecute('group -w -n ' + self.proxy_group_name + ' ' + self.proxy_groups)
            dg_mod.doIt()
Esempio n. 2
0
 def undoIt(self):
     if self._testNode is None:
         raise ValueError("failed to undo")
     mod = om2.MDagModifier()
     mod.deleteNode(self._testNode.object())
     mod.doIt()
     self._testNode = None
Esempio n. 3
0
def setParent(child, newParent, maintainOffset=False):
    """Sets the parent for the given child

    :param child: the child node which will have its parent changed
    :type child: om2.MObject
    :param newParent: The new parent for the child
    :type newParent: om2.MObject
    :param maintainOffset: if True then the current transformation is maintained relative to the new parent
    :type maintainOffset: bool
    :rtype bool
    """

    newParent = newParent or om2.MObject.kNullObj
    if child == newParent:
        return False
    dag = om2.MDagModifier()
    if maintainOffset:
        if newParent == om2.MObject.kNullObj:
            offset = getWorldMatrix(child)
        else:
            start = getWorldMatrix(newParent)
            end = getWorldMatrix(child)
            offset = end * start.inverse()
    dag.reparentNode(child, newParent)
    dag.doIt()
    if maintainOffset:
        setMatrix(child, offset)
    return True
Esempio n. 4
0
    def create(self):
        self._segments = []

        if self._modifier is None:
            self._modifier = om.MDagModifier()

        if self._qtm_settings is None and self._qtm.connected:
            self._qtm_settings = self._qtm.get_settings("skeleton")

        if (self._qtm_settings is not None
                and self._qtm_settings.get("Skeletons", None) is not None):
            self._skeletons = self._qtm_settings["Skeletons"].get(
                "Skeleton", [])

            if type(self._skeletons) != type([]):
                self._skeletons = [self._skeletons]

            for skeleton_index, skeleton in enumerate(self._skeletons):
                if not cmds.namespace(exists=skeleton["@Name"]):
                    cmds.namespace(add=skeleton["@Name"])
                self._segments.append({})

                self.add_segment(skeleton_index,
                                 skeleton["Segments"]["Segment"], None)

            self._modifier.doIt()
    def create(self):
        modifier = om.MDagModifier()

        if self._marker_groups is not None:
            for group_name, marker_group in self._marker_groups.items():
                parent = MayaUtil.get_node_by_name(group_name)

                if parent is None:
                    parent = modifier.createNode("transform")

                    modifier.renameNode(parent, group_name)
                    modifier.doIt()

                for i, marker in enumerate(marker_group):
                    locator = MayaUtil.get_node_by_name(marker["Name"])

                    if locator is None:
                        locator = modifier.createNode("locator")

                        modifier.renameNode(locator, marker["Name"])

                    modifier.reparentNode(locator, parent)
                    modifier.doIt()

                    transformFn = om.MFnTransform(locator)
                    self._markers[marker["Index"]]["locator"] = locator
                    self._markers[marker["Index"]]["transformFn"] = transformFn
Esempio n. 6
0
 def undoIt(self):
     dg_mod = om.MDagModifier()
     if self.proxy_group_name != '':
         dg_mod.commandToExecute('delete ' + self.proxy_group_name)
         dg_mod.doIt()
     om.MGlobal.setActiveSelectionList(self.selection_prev,
                                       om.MGlobal.kReplaceList)
Esempio n. 7
0
def parentAPI(source, target, absolute=True):
    # TODO: implement undo
    mSource = nodeToMObject(source)

    if absolute:
        srcFnDependencyNode = om.MFnDependencyNode(mSource)
        worldMatrixPlug = srcFnDependencyNode.findPlug('worldMatrix', False).elementByLogicalIndex(0)
        matrixMObj = worldMatrixPlug.asMObject()
        fnMatrixData = om.MFnMatrixData(matrixMObj)

        srcWMtx = fnMatrixData.transformation()

    mDagMod = om.MDagModifier()
    if target:
        mTarget = nodeToMObject(target)
        mDagMod.reparentNode(mSource, mTarget)
    else:
        mDagMod.reparentNode(mSource)
    mDagMod.doIt()

    fnDagNode = om.MFnDagNode(mSource)

    if absolute:
        srcFnTransform = om.MFnTransform(fnDagNode.getPath())
        # srcFnTransform = om.MFnTransform(mSource)
        # noinspection PyUnboundLocalVariable
        srcFnTransform.setTranslation(srcWMtx.translation(om.MSpace.kWorld), om.MSpace.kWorld)
        srcFnTransform.setRotation(srcWMtx.rotation(asQuaternion=True), om.MSpace.kWorld)
        srcFnTransform.setScale(srcWMtx.scale(om.MSpace.kWorld))
        srcFnTransform.setShear(srcWMtx.shear(om.MSpace.kWorld))

    return fnDagNode.fullPathName()
Esempio n. 8
0
 def groupProxies(self,node):
     dgMod = om.MDagModifier()
     proxiesString = ''
     for proxy in self.proxyInfluencePairs.keys():
         proxiesString = proxiesString + proxy.partialPathName() + ' '
     dgMod.commandToExecute('group -w -n ' + node.partialPathName() + '_proxies_grp ' + proxiesString) 
     dgMod.doIt()
     self.proxyGroups = self.proxyGroups + node.partialPathName() + '_proxies_grp '
Esempio n. 9
0
	def create(dagtype = "transform", name = "default"):
		mdagmod = om.MDagModifier()
		mobj = mdagmod.createNode(dagtype)
		mdagmod.doIt()

		dagnode = DagNode(mobj)
		dagnode.setName(name)
		return dagnode
Esempio n. 10
0
 def create_proxy_group(self, node):
     dg_mod = om.MDagModifier()
     # build a string containing all the proxy names to be used for grouping
     proxies_str = ''
     for proxy in self.proxy_influence_pairs.keys():
         proxies_str = proxies_str + proxy + ' '
     dg_mod.commandToExecute('group -w -n ' + node.partialPathName() + '_proxies_grp ' + proxies_str) 
     dg_mod.doIt()
     self.proxy_groups = self.proxy_groups + node.partialPathName() + '_proxies_grp '
Esempio n. 11
0
 def __init__(self):
     om2.MPxCommand.__init__(self)
     self.dagModifier = om2.MDagModifier()
     self.dgModifier = om2.MDGModifier()
     self.selList = om2.MSelectionList()
     self.matchScale = True
     self.matchRotation = True
     self.matchTranslation = True
     self.origTransforms = []
	def undoIt(self):
		dgModifier = om.MDGModifier()
		dagModifier = om.MDagModifier()
		dgModifier.deleteNode(self.caveNode)
		dgModifier.deleteNode(self.loftNode)
		dgModifier.deleteNode(self.loftTessellateNode)
		dgModifier.deleteNode(self.planarNode)
		dgModifier.deleteNode(self.planarTesselateNode)
		dagModifier.deleteNode(self.loftMeshTransformNode)
		dgModifier.doIt()
		dagModifier.doIt()
Esempio n. 13
0
def createDAGNode(dagNodeType, nodeName="newDAGNode"):
    """
    Create a new new DAG node of type with name
    :param createNodeType: str - node type
    :param nodeName: str
    :return: MObject - new node MObject
    """
    dagMod = om2.MDagModifier()
    newDAGNode = dagMod.createNode(dagNodeType)
    dagMod.renameNode(newDAGNode, nodeName + "_" + dagNodeType)
    dagMod.doIt()
    return newDAGNode
Esempio n. 14
0
def delete(node):
    """Delete the given nodes

    :param node:
    """
    if not isValidMObject(node):
        return
    lockNode(node, False)
    unlockedAndDisconnectConnectedAttributes(node)

    mod = om2.MDagModifier()
    mod.deleteNode(node)
    mod.doIt()
    def create(self):
        if self._bodies == None:
            return

        modifier = om.MDagModifier()

        for body in self._bodies:
            parent = MayaUtil.get_node_by_name(body["Name"])

            if parent is None:
                parent = modifier.createNode("transform")

                modifier.renameNode(parent, body["Name"])
                modifier.doIt()

            transformFn = om.MFnTransform(parent)

            for i, point in enumerate(body["Point"]):
                point_name = body["Name"] + "_" + str(i)
                locator = MayaUtil.get_node_by_name(point_name)

                if locator is None:
                    locator = modifier.createNode("locator")

                    modifier.renameNode(locator, point_name)

                modifier.reparentNode(locator, parent)
                modifier.doIt()

                pointTransformFn = om.MFnTransform(locator)
                translation = None

                if self._up_axis == "y":
                    translation = om.MVector(
                        -float(point["X"]) * self._unit_conversion,
                        float(point["Z"]) * self._unit_conversion,
                        float(point["Y"]) * self._unit_conversion,
                    )
                else:
                    translation = om.MVector(
                        float(point["X"]) * self._unit_conversion,
                        float(point["Y"]) * self._unit_conversion,
                        float(point["Z"]) * self._unit_conversion,
                    )

                pointTransformFn.setTranslation(translation,
                                                om.MSpace.kTransform)
            self._bodies[body["Index"]].update({
                "transform": parent,
                "transformFn": transformFn
            })
Esempio n. 16
0
    def groupAllProxies(self):
        rigNode = self.getDagPath('*RIG')
        proxyGroupName = ''

        if rigNode:
            proxyGroupName = rigNode.partialPathName()
        if proxyGroupName != '':
            proxyGroupName += '_proxies_grp'
        else:
            proxyGroupName = 'proxies_grp'
            
        dgMod = om.MDagModifier()
        dgMod.commandToExecute('group -w -n ' + proxyGroupName +' ' + self.proxyGroups) 
        dgMod.doIt()
Esempio n. 17
0
    def _initialize(self):
        char_instance = om2.MFnTransform().create(om2.MObject.kNullObj)
        deform_instance = om2.MFnTransform().create(om2.MObject.kNullObj)
        globalTransform_instance = om2.MFnTransform().create(
            om2.MObject.kNullObj)
        geometry_instance = om2.MFnTransform().create(om2.MObject.kNullObj)

        dagMod = om2.MDagModifier()
        dagMod.renameNode(char_instance, "%s_char" % self._createName)
        dagMod.renameNode(deform_instance, "deform_hrc")
        dagMod.renameNode(globalTransform_instance, "globalTransform_hrc")
        dagMod.renameNode(geometry_instance, "geometry_hrc")
        dagMod.reparentNode(deform_instance, char_instance)
        dagMod.reparentNode(globalTransform_instance, char_instance)
        dagMod.reparentNode(geometry_instance, char_instance)
        dagMod.doIt()

        cmds.setAttr(
            '%s.useOutlinerColor' %
            om2.MDagPath.getAPathTo(char_instance).fullPathName(), True)
        cmds.setAttr(
            '%s.outlinerColor' %
            om2.MDagPath.getAPathTo(char_instance).fullPathName(), 0.0, 1.0,
            0.0)

        self._data["CharName"] = self._createName
        self._data["Instance"] = char_instance
        self._data["Content"] = collections.OrderedDict()
        self._data["Content"]["Deform"] = collections.OrderedDict()
        self._data["Content"]["Deform"]["Instance"] = deform_instance
        self._data["Content"]["Deform"][
            "DeformationLayers"] = collections.OrderedDict()
        self._data["Content"]["GlobalTransform"] = collections.OrderedDict()
        self._data["Content"]["GlobalTransform"][
            "Instance"] = globalTransform_instance
        self._data["Content"]["Geometry"] = collections.OrderedDict()
        self._data["Content"]["Geometry"]["Instance"] = geometry_instance
        self._data["Info"] = collections.OrderedDict()
        self._data["Info"]["Created"] = datetime.datetime.now().strftime(
            "%b %d, %Y - %I:%M:%S %p")
        self._data["Info"]["LastModified"] = datetime.datetime.now().strftime(
            "%b %d, %Y - %I:%M:%S %p")
        # self._data["Info"]["UseCustomTech"] = self.useCustomTech

        self._deformData = self._data["Content"]["Deform"]
        self._globalTransformData = self._data["Content"]["GlobalTransform"]
        self._geometryData = self._data["Content"]["Geometry"]

        return True
	def redoIt(self):
		# Create a dg and dag modifier
		dgModifier = om.MDGModifier()
		dagModifier = om.MDagModifier()
		# Create the boolean node
		self.booleanNode = dgModifier.createNode("polyCBoolOp")
		dgModifier.renameNode(self.booleanNode, self.name)
		# Get the name of the node
		dgModifier.doIt()
		nodeName = om.MFnDependencyNode(self.booleanNode).name()
		# Connect the attributes
		numShapes = len(self.shapeNames)
		for i in range(numShapes):
			mc.connectAttr(self.shapeNames[i] + ".outMesh", nodeName + ".inputPoly[" + str(i) + "]", f=True)
			mc.connectAttr(self.shapeNames[i] + ".worldMatrix[0]", nodeName + ".inputMat[" + str(i) + "]", f=True)
Esempio n. 19
0
    def create(self):
        modifier = om.MDagModifier()
        self._segments = {}

        if self._qtm_settings is None and self._qtm.connected:
            self._qtm_settings = self._qtm.get_settings("skeleton")

        if (
            self._qtm_settings is not None
            and self._qtm_settings.get("Skeletons", None) is not None
        ):
            self._skeletons = self._qtm_settings["Skeletons"].get("Skeleton", [])

            if type(self._skeletons) != type([]):
                self._skeletons = [self._skeletons]

            for skeleton in self._skeletons:
                create = True

                for segment in skeleton["Segment"]:
                    segment_name = skeleton["@Name"] + "_" + segment["@Name"]
                    j = MayaUtil.get_node_by_name(segment_name)

                    if j is None:
                        j = modifier.createNode("joint")

                        modifier.renameNode(j, segment_name)
                    else:
                        create = False

                    transformFn = om.MFnTransform(j)

                    self._segments[int(segment["@ID"])] = {
                        "MObject": j,
                        "transformFn": transformFn,
                    }

                    if "@Parent_ID" in segment:
                        modifier.reparentNode(
                            j, self._segments[int(segment["@Parent_ID"])]["MObject"]
                        )

                    if create:
                        self._assume_t_pose(segment)

            modifier.doIt()
Esempio n. 20
0
def rename_mobj(mobj, name):
    """Rename the given MObject.

    Note:
        This is currently NOT undoable!!! Therefore be careful!

    Args:
        mobj (MObject): Node to be renamed.
        name (str): New name for the node.

    Returns:
        str: New name of renamed mobj
    """
    dag_modifier = OpenMaya.MDagModifier()
    dag_modifier.renameNode(mobj, name)
    dag_modifier.doIt()

    return get_name_of_mobj(mobj)
Esempio n. 21
0
    def renameChar(self, name):
        """
        Signature: <Character>.renameChar(name)
        Parameters: name - string
        Returns:
        Description: Change the name of a Character class instance.
        """
        if _checkObjectExists(self._data["Instance"]):
            dagMod = om2.MDagModifier()
            dagMod.renameNode(self._data["Instance"], "%s_char" % name)
            dagMod.doIt()

            self._data["CharName"] = name

            return True
        else:
            om2.MGlobal.displayError("Cannot find character node.")
            return
Esempio n. 22
0
def createLocAtSelection():
    selList = om2.MGlobal.getActiveSelectionList()
    mObjs = [selList.getDependNode(idx) for idx in range(selList.length())]
    mDagMod = om2.MDagModifier()

    for mObj in mObjs:
        mObjHandle = om2.MObjectHandle(mObj)
        mFn = om2.MFnDependencyNode(mObj)
        locMObj = createNode("locator", "{}_LOC".format(mFn.name()), mDagMod)
        locMObjHandle = om2.MObjectHandle(locMObj)

        mPlug = findPlug(mObjHandle, "worldMatrix")
        if mPlug.isArray:
            mtxIdxZero = mPlug.elementByLogicalIndex(0)

            plugMObj = mtxIdxZero.asMObject()
            mFnMtxData = om2.MFnMatrixData(plugMObj)
            mMtx = mFnMtxData.matrix()

            setAtters(locMObjHandle, mMtx)
 def redoIt(self):
     # Create a dg and dag modifier
     dgModifier = om.MDGModifier()
     dagModifier = om.MDagModifier()
     # Create the sculpt layer node
     self.sculptLayerNode = dgModifier.createNode("SculptLayerNode")
     dgModifier.renameNode(self.sculptLayerNode, self.name)
     # Get the name of the node
     dgModifier.doIt()
     nodeName = om.MFnDependencyNode(self.sculptLayerNode).name()
     # Set the parameters
     mc.setAttr(nodeName + ".sculptStrength", self.sculptStrength)
     mc.setAttr(nodeName + ".curveOffset", self.curveOffset)
     mc.setAttr(nodeName + ".maxProjectionDistance", self.maxProjection)
     # Connect the attributes
     mc.connectAttr(self.curveMask + ".worldSpace[0]",
                    nodeName + ".curveMask")
     mc.connectAttr(self.sculptedMesh + ".worldMesh[0]",
                    nodeName + ".sculptedMesh")
     mc.connectAttr(self.terrain + ".worldMesh[0]", nodeName + ".terrain")
Esempio n. 24
0
def run(child, parent=None, *args, **kwargs):
    """Parent an object to another

    :param child: MObject of the child node.
    :type child: MObject or str
    :param parent: MObject of the parent node.
    :type parent: MObject or str or None
    """
    dag_mod = om.MDagModifier()

    if parent is None:
        parent = om.MObject.kNullObj
    elif isinstance(parent, str):
        parent = get_mobject.run(parent)

    if isinstance(child, str):
        child = get_mobject.run(child)

    dag_mod.reparentNode(child, newParent=parent)
    dag_mod.doIt()
Esempio n. 25
0
def createDagNode(name, nodeType, parent=None):
    """Create's a new dag node and if theres a parent specified then parent the new node

    :param name: The new name of the created node
    :type name: str
    :param nodeType: The node type to create
    :type nodeType: str
    :param parent: The node the parent the new node to, if the parent is none or MObject.kNullObj then it will parent
    to the world, defaults to world
    :type parent: MObject or MObject.kNullObj
    :return:The newly create nodes mobject
    :rtype: MObject
    """
    if parent is None or parent.isNull() or parent.apiType() in (om2.MFn.kInvalid, om2.MFn.kWorld):
        parent = om2.MObject.kNullObj

    command = om2.MDagModifier()
    node = command.createNode(nodeType)
    command.renameNode(node, name)
    command.reparentNode(node, parent)
    command.doIt()
    return node
Esempio n. 26
0
    def createDeformationLayer(self, name):
        """
        Signature: <Character>.createDeformationLayer(name)
        Parameters: name - string
        Returns:
        Description: Create a deformation layer node in the character hierarchy.
        """
        if _checkObjectExists(self._deformData["Instance"]):
            defLyr = om2.MFnTransform().create(om2.MObject.kNullObj)
            dagMod = om2.MDagModifier()
            dagMod.renameNode(defLyr, "%s_defLyr" % name)
            dagMod.reparentNode(defLyr, self._deformData["Instance"])
            dagMod.doIt()

            self._deformData["DeformationLayers"][
                name] = collections.OrderedDict()
            self._deformData["DeformationLayers"][name]["Instance"] = defLyr
            self._deformData["DeformationLayers"][name][
                "Components"] = collections.OrderedDict()

            return True
        else:
            om2.MGlobal.displayError("Cannot find character deform node.")
            return
Esempio n. 27
0
                    transX = locMFn.findPlug("translateX", False)
                    transY = locMFn.findPlug("translateY", False)
                    transZ = locMFn.findPlug("translateZ", False)
                    transX.setFloat(trans.x)
                    transY.setFloat(trans.y)
                    transZ.setFloat(trans.z)

                    rotX = locMFn.findPlug("rotateX", False)
                    rotY = locMFn.findPlug("rotateY", False)
                    rotZ = locMFn.findPlug("rotateZ", False)
                    rotX.setFloat(rot.x)
                    rotY.setFloat(rot.y)
                    rotZ.setFloat(rot.z)
                polyIter.next()
        iter.next()

    print("Done! Face locator/s created and placed!")


selList = om2.MGlobal.getActiveSelectionList()
componentIDs, typeID = geIDsAndTypes(selList)
mDagMod = om2.MDagModifier()

if typeID == om2.MFn.kMeshVertComponent:
    for componentID in componentIDs:
        createLocAtVertex(selList, componentID, mDagMod)
elif typeID == om2.MFn.kMeshPolygonComponent:
    createLocAtFace(selList, mDagMod)
else:
    print("Please select an polygon")
Esempio n. 28
0
    def create_proxies(self, node, mesh_fn, skin_fn):
        components = om.MFnSingleIndexedComponent()
        try:
            skin_influences = skin_fn.influenceObjects()
        except:
            sys.stderr.write('Object has no influences')
            return

        self.reset_attr()
        num_faces = mesh_fn.numPolygons

        poly_iter = om.MItMeshPolygon(node)
        # iterates through all the selected mesh faces
        computation = om1.MComputation()
        computation.beginComputation(True, False)
        computation.setProgressRange(0, poly_iter.count())
        computation.setProgress(0)
        progress_amount = 0
        while not poly_iter.isDone():
            # initialize average_weights as a zero list with the length of number of influences
            self.average_weights = [0] * len(skin_influences)
            face_verts = poly_iter.getVertices()
            vert_comp = components.create(om.MFn.kMeshVertComponent)
            components.addElements(face_verts)
            vert_iter = om.MItMeshVertex(node, vert_comp)
            # iterates through all the face vertices, computes the max influence per face
            while not vert_iter.isDone():
                weights, inf_index = skin_fn.getWeights(
                    node, vert_iter.currentItem())
                self.average_face_weights(weights)
                vert_iter.next()
            self.set_face_weights(poly_iter.index(), self.average_weights,
                                  skin_influences)
            computation.setProgress(poly_iter.index())
            poly_iter.next(None)

        # list holding the num faces, will be used to get the faces that need to be deleted
        faces_list = [i for i in range(num_faces)]
        computation.endComputation()

        for inf, faces in self.faces_weights.iteritems():
            mesh_name = node.partialPathName()
            proxy_name = mesh_name.split('|')[-1] + '_' + inf + '_proxy'

            dg_mod = om.MDagModifier()
            dg_mod.commandToExecute('duplicate -n ' + proxy_name + ' ' +
                                    mesh_name)
            dg_mod.commandToExecute('parent -w ' + proxy_name)
            dg_mod.doIt()

            # duplicates the skinned mesh, named as above
            mesh_duplicate_dag = self.get_object_path(proxy_name)
            self.unlock_channels(mesh_duplicate_dag)
            mesh_duplicate_fn = om.MFnMesh(mesh_duplicate_dag)
            # faces is read from the self.faces_weights attribute, holds the indexes of the faces that will be kept
            faces_to_delete = list(set(faces_list) - set(faces))

            if len(faces_to_delete) > 0:
                mesh_duplicate_fn.extractFaces(faces_to_delete)
                mesh_duplicate_fn.collapseFaces(faces_to_delete)
                mesh_duplicate_fn.updateSurface()

            # sets the proxy pivot based on the joint position / rotation
            self.set_proxy_pivot(mesh_duplicate_dag, inf)
            self.proxy_influence_pairs[mesh_duplicate_dag.partialPathName(
            )] = self.get_object_path(inf)
            self.proxies.append(proxy_name)

        self.animate_proxy()
        self.create_proxy_group(node)
Esempio n. 29
0
def read_gmc_data(scale_rate, gmc_path, mesh_name):
    # first read, get object section
    file = open(gmc_path, "r")

    line_num = -1
    line_nums = []

    line = file.readline()
    line_num += 1

    while True:
        line = file.readline()
        line_num += 1

        if not line:
            break

        line = strip_space_line(line)
        if line.find("Object") == 0:
            line_nums.append(line_num)

    print line_nums

    file.close()

    # second read,read section 1
    vertexArray = OpenMaya.MFloatPointArray()
    uArray = OpenMaya.MFloatArray()
    vArray = OpenMaya.MFloatArray()

    polygonCounts = OpenMaya.MIntArray()
    polygonConnects = OpenMaya.MIntArray()

    material_num = 0
    material_sets = []

    file = open(gmc_path, "r")
    line_num = -1

    line = file.readline()
    line_num += 1

    while True:
        line = file.readline()
        line_num += 1

        if not line:
            break

        line = strip_space_line(line)
        if line_num >= line_nums[0] and line_num < line_nums[1]:

            if line.find("Vertices") == 0:
                print line
            elif line.find("v") == 0:
                vertex_line = re.split("v|n|c|t", line)
                vertex_data = []
                vertex_data.append(parse_mesh_element(vertex_line[1]))
                vertex_data.append(parse_mesh_element(vertex_line[4]))

                pos = vertex_data[0]
                pos[0] *= scale_rate
                pos[1] *= scale_rate
                pos[2] *= scale_rate

                v = OpenMaya.MFloatPoint(pos[0], pos[1], pos[2])
                vertexArray.append(v)

                uv = vertex_data[1]
                uArray.append(uv[0])
                vArray.append(uv[1])

            elif line.find("f") == 0:
                face_line = line[1:]
                face_data = []
                face_data = parse_mesh_element(face_line)

                print face_data

                polygonCounts.append(3)

                polygonConnects.append(int(face_data[1]))
                polygonConnects.append(int(face_data[2]))
                polygonConnects.append(int(face_data[3]))

    mFn_Mesh = OpenMaya.MFnMesh()
    m_DagMod = OpenMaya.MDagModifier()
    new_object = m_DagMod.createNode('transform')

    mFn_Mesh.create(vertexArray, polygonCounts, polygonConnects, uArray,
                    vArray, new_object)
    mFn_Mesh.setName(mesh_name)
    m_DagMod.doIt()

    new_mesh = pmc.PyNode(mesh_name)
    new_transform = pmc.listRelatives(new_mesh, type='transform',
                                      parent=True)[0]

    mFn_Mesh.assignUVs(polygonCounts, polygonConnects, 'map1')

    node_name = mesh_name + "_mesh"

    pmc.select(new_transform)
    pmc.rename(new_transform, node_name)

    file.close()
Esempio n. 30
0
def read_skc_file(scale_rate, skc_path, mesh_name):
    file = open(skc_path, "r")

    line = file.readline()

    vertexArray = OpenMaya.MFloatPointArray()
    uArray = OpenMaya.MFloatArray()
    vArray = OpenMaya.MFloatArray()

    polygonCounts = OpenMaya.MIntArray()
    polygonConnects = OpenMaya.MIntArray()

    vertexWeights = []

    material_num = 0
    material_sets = []

    while True:
        line = file.readline()
        if not line:
            break

        line = strip_space_line(line)

        if line.find("Materials") != -1:
            line = strip_space_line(line)
            material_num = int(line.split(":")[1])
            for i in range(0, int(material_num)):
                material_sets.append(0)
        elif line.find("Vertices") != -1:
            print line
        elif line[0] == "v":
            vertex_data = parse_pos_uv_weight(line)
            pos = vertex_data[0]
            pos[0] *= scale_rate
            pos[1] *= scale_rate
            pos[2] *= scale_rate
            v = OpenMaya.MFloatPoint(pos[0], pos[1], pos[2])
            vertexArray.append(v)

            uv = vertex_data[1]
            uArray.append(uv[0])
            vArray.append(uv[1])

            # bone weights
            skin_data = vertex_data[2]
            weight_num = skin_data[0]
            weights = []
            for bi in range(0, int(weight_num)):
                tmp_bone_idx = skin_data[int(1 + 2 * bi)]
                tmp_bone_name = bone_name_list[int(tmp_bone_idx)]
                tmp_bone_weight = skin_data[int(2 + 2 * bi)]
                key_value = (tmp_bone_name, tmp_bone_weight)
                weights.append(key_value)
            vertexWeights.append(weights)

        elif line.find("Triangles") != -1:
            print line
        elif line[0] == "f":
            face_data = parse_face(line)
            polygonCounts.append(3)

            polygonConnects.append(int(face_data[2]))
            polygonConnects.append(int(face_data[3]))
            polygonConnects.append(int(face_data[4]))

            # assign material
            material_sets[int(face_data[1])] += 1

    mFn_Mesh = OpenMaya.MFnMesh()
    m_DagMod = OpenMaya.MDagModifier()
    new_object = m_DagMod.createNode('transform')

    mFn_Mesh.create(vertexArray, polygonCounts, polygonConnects, uArray,
                    vArray, new_object)
    mFn_Mesh.setName(mesh_name)
    m_DagMod.doIt()

    new_mesh = pmc.PyNode(mesh_name)
    new_transform = pmc.listRelatives(new_mesh, type='transform',
                                      parent=True)[0]

    mFn_Mesh.assignUVs(polygonCounts, polygonConnects, 'map1')

    node_name = mesh_name + "_mesh"

    pmc.select(new_transform)
    pmc.rename(new_transform, node_name)

    # skin cluster
    pmc.select(bone_name_list[0], add=True)
    skin_cluster = pmc.skinCluster(bindMethod=0,
                                   skinMethod=1,
                                   normalizeWeights=0,
                                   maximumInfluences=4,
                                   obeyMaxInfluences=True)
    pmc.select(node_name, r=True)
    pmc.skinPercent(skin_cluster, node_name, normalize=False, pruneWeights=100)

    for v in range(0, len(vertexWeights)):
        pmc.skinPercent(skin_cluster,
                        "{0}.vtx[{1}]".format(node_name, v),
                        transformValue=vertexWeights[v],
                        normalize=True)

    #create material
    #pCylinder1.f[14:17] _mesh.f[{0}:{1}].format()

    material_starts = []
    material_ends = []
    mesh_selcte_sets = []

    material_sets = filter(lambda x: x != 0, material_sets)
    print material_sets

    material_starts.append(0)
    material_ends.append(material_sets[0] - 1)
    mesh_selcte_sets.append(
        node_name +
        ".f[{0}:{1}]".format(int(material_starts[0]), int(material_ends[0])))
    for i in range(1, len(material_sets)):
        material_starts.append(material_ends[int(i - 1)] + 1)
        material_ends.append(material_ends[int(i - 1)] + material_sets[i])
        mesh_selcte_sets.append(node_name + ".f[{0}:{1}]".format(
            int(material_starts[i]), int(material_ends[i])))

    print mesh_selcte_sets

    # 没有这一句会出错,必须将以前的选择清理掉
    pmc.select(clear=True)

    for i in range(0, len(mesh_selcte_sets)):
        shader_name = "p_shader{0}".format(int(i))
        new_shader = pmc.shadingNode("lambert",
                                     asShader=True,
                                     name=shader_name)
        new_shadinggroup = pmc.sets(renderable=True,
                                    noSurfaceShader=True,
                                    empty=True,
                                    name='{}_SG'.format(shader_name))
        pmc.connectAttr(new_shader.outColor, new_shadinggroup.surfaceShader)

        pmc.select(mesh_selcte_sets[i])
        pmc.hyperShade(assign=new_shadinggroup)
        pmc.select(clear=True)