Beispiel #1
0
def main():

    mesh_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh")
    if not mesh_list:
        return

    csv_path = r"C:\Users\timmyliang\Desktop\file_test\2020-12-1\head.csv"
    pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0)

    with open(csv_path, "r") as f:
        reader = csv.DictReader(f)
        data_list = {
            int(row[" IDX"]): (
                float(row[" COLOR.x"]),
                float(row[" COLOR.y"]),
                float(row[" COLOR.z"]),
                float(row[" COLOR.w"]),
            )
            for row in reader
        }

    mesh = mesh_list[0]
    mfn = mesh.__apimfn__()
    itr = OpenMaya.MItMeshFaceVertex(mesh.__apimobject__())

    face_list = OpenMaya.MIntArray()
    vertex_list = OpenMaya.MIntArray()
    colors = OpenMaya.MColorArray()

    index = -1
    total = len(mesh.vtxFace)
    pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0)
    while not itr.isDone():
        index += 1
        pm.progressWindow(e=1, progress=index / total * 100)
        vert_id = itr.vertId()
        face_id = itr.faceId()
        vertex_list.append(vert_id)
        face_list.append(face_id)

        color = data_list.get(vert_id)
        if not color:
            colors.append(OpenMaya.MColor(0, 0, 0))
            itr.next()
            continue
        r, g, b,a = color
        
        colors.append(OpenMaya.MColor(r, g, b))

        itr.next()

    mfn.setFaceVertexColors(colors, face_list, vertex_list)
    pm.progressWindow(ep=1)
Beispiel #2
0
def WriteMeshVertexColor(fileRec, meshPath, prof):
    print('write mesh vertex color %s' % meshPath.fullPathName())

    itvert = om.MItMeshVertex(meshPath)
    print('vertex count: %i' % itvert.count())

    nf = itvert.count() * 3

    fileRec.write('static const float s%s_%sVertexColors[%i] = {' %
                  (prof.prefixName, meshPath.partialPathName(), nf))

    count = 0
    while not itvert.isDone():
        col = om.MColor()
        itvert.getColor(col, prof.colorName)

        fileRec.write("%ff, %ff, %ff, " % (col.r, col.g, col.b))

        count += 1
        if (count % 32 == 0) or (count == itvert.count() - 1):
            fileRec.write("\n")

        itvert.next()

    fileRec.write('};\n')
def NormaltoColor(VecOriginlist, vTarNorArray, Intensity):
    oMeshArray = VecOriginlist[0]
    iVertArray = VecOriginlist[1]
    iFaceArray = VecOriginlist[2]
    vOriNorArray = VecOriginlist[3]
    oMeshlist = VecOriginlist[5]
    for y in range(oMeshlist.length()):
        mMesh = om.MFnMesh(oMeshlist[y])
        IntenVec = om.MVector(Intensity, Intensity, Intensity)
        cVtxColorArray = om.MColorArray()
        CiVertArray = om.MIntArray()
        CiFaceArray = om.MIntArray()
        samemeshposit = [
            i for i in range(oMeshArray.length())
            if oMeshArray[i] == oMeshlist[y]
        ]
        for x in range(len(samemeshposit)):
            posit = samemeshposit[x]
            CiFaceArray.append(iFaceArray[posit])
            CiVertArray.append(iVertArray[posit])
            OriNor = vOriNorArray[posit]
            TarNor = vTarNorArray[posit]
            ResultNor = lerpVector(OriNor, TarNor, IntenVec)
            cVtxColor = om.MColor((ResultNor.x + 1) / 2, (ResultNor.y + 1) / 2,
                                  (ResultNor.z + 1) / 2, 1.0)
            cVtxColorArray.append(cVtxColor)
        mMesh.setFaceVertexColors(cVtxColorArray, CiFaceArray, CiVertArray)
Beispiel #4
0
    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()

            next(itMeshFV)

            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)
    def deform(self, dataBlock, geoIter, mtx, multiIndex):
        """This method performs the deformation algorithm.
        The geometry iterator passed to this method is in local space and not world space. To convert
        points to world space use the matrix that is suppied.
            * dataBlock [MDataBlock] is the node's datablock.
            * geoIter [MItGeometry] is an iterator for the current geometry being deformed.
            * mtx [MMatrix] is the geometry's world space transformation matrix.
            * multiIndex [int] is the index corresponding to the requested output geometry.
        """
        # pylint: disable=unused-argument
        envelope = dataBlock.inputValue(
            ompx.cvar.MPxGeometryFilter_envelope).asFloat()
        amplitude = dataBlock.inputValue(TestDeformer.inAmplitude).asFloat()
        displace = dataBlock.inputValue(TestDeformer.inDisplace).asFloat()
        inputArrayHandle = dataBlock.outputArrayValue(
            ompx.cvar.MPxGeometryFilter_input)
        inputArrayHandle.jumpToElement(multiIndex)
        inputElement = inputArrayHandle.outputValue()
        inMesh = inputElement.child(
            ompx.cvar.MPxGeometryFilter_inputGeom).asMesh()
        outMeshArrayHandle = dataBlock.outputArrayValue(
            ompx.cvar.MPxGeometryFilter_outputGeom)
        outMesh = outMeshArrayHandle.inputValue().asMesh()
        mMatrix = dataBlock.inputValue(TestDeformer.inMatrix).asMatrix()

        vTrans = om1.MVector(mMatrix(3, 0), mMatrix(3, 1), mMatrix(3, 2))

        meshFn = om1.MFnMesh(inMesh)
        normalsArray = om1.MFloatVectorArray()
        meshFn.getVertexNormals(False, normalsArray, om1.MSpace.kObject)
        posArray = om1.MPointArray()
        colorsArray = om1.MColorArray()
        vertexArray = om1.MIntArray()

        while not geoIter.isDone():
            index = geoIter.index()
            vertexArray.append(index)
            pntPos = geoIter.position()
            weight = self.weightValue(dataBlock, multiIndex, index)
            colorsArray.append(om1.MColor(1, 0, 0, 1))
            if weight != 0:
                pntPos.x = pntPos.x + math.sin(
                    index + displace - vTrans[0]
                ) * amplitude * normalsArray[index].x * weight * envelope
                pntPos.y = pntPos.y + math.sin(
                    index + displace - vTrans[0]
                ) * amplitude * normalsArray[index].y * weight * envelope
                pntPos.z = pntPos.z + math.sin(
                    index + displace - vTrans[0]
                ) * amplitude * normalsArray[index].z * weight * envelope
            posArray.append(pntPos)
            geoIter.next()
        meshFn.setObject(outMesh)
        meshFn.setVertexColors(colorsArray, vertexArray)
        geoIter.setAllPositions(posArray)
def tagMesh(meshDagPath):
	"""Tag the points on the supplied mesh with vertex colors to store Maya's point order"""
	# clear any extant vertex colors
	try: cmds.polyColorSet(meshDagPath.partialPathName(), e=True, delete=True, acs=True)
	except: pass
	
	# encode each point index in the red and green channels of each point's color value
	meshFn = om.MFnMesh(meshDagPath)
	vertexCount = om.MIntArray()
	vertexList = om.MIntArray()
	meshFn.getVertices(vertexCount, vertexList)
	vertexColors = om.MColorArray(meshFn.numVertices(), om.MColor(0.0,0.0,1.0,1.0))	
	
	for i in xrange(meshFn.numVertices()):
		col = om.MColor(tagIndexToColor(i))
		vertexColors[i].r = col.r
		vertexColors[i].g = col.g
	meshFn.createColorSetWithName('blendShapeIndexMap')
	meshFn.setColors(vertexColors, 'blendShapeIndexMap')
	meshFn.assignColors(vertexList)
def tagIndexToColor(i):
	"""Encode an integer as an MColor value."""
	# get 4 complete hex digits to represent i
	asHex = hex(i)
	digits = asHex[asHex.find('x')+1::][::-1]
	while len(digits) < 4: digits += '0'
	digits = digits[::-1]
	# pack hex digits into the red and green color values
	return om.MColor(
		int('0x%s'%digits[2:4], 16)*__oneOverTwoFiftyFive,
		int('0x%s'%digits[0:2], 16)*__oneOverTwoFiftyFive,
		1.0,
		1.0)
    def create_object_openmaya():
        global imported_object

        cmds.select(all=True, hierarchy=True)
        current_objs = cmds.ls(selection=True)

        new_mesh = om.MFnMesh()

        merge_vertices = True
        point_tolerance = 0.0001

        # create polys
        for p in range(0, len(imported_object.polys), 1):
            poly_list = []
            v_count = len(imported_object.polys[p])
            poly_list = om.MPointArray()
            poly_list.setLength(v_count)
            for i in range(v_count):
                poly_list.set(
                    imported_object.omVertices[int(
                        imported_object.polys[p][i])], i)
            new_mesh.addPolygon(poly_list, merge_vertices, point_tolerance)

        # create weightmaps
        if len(imported_object.weightMap) > 0:
            for v in range(0, imported_object.vertexCount, 1):
                c = imported_object.weightMap[v]
                vColor = om.MColor(c, c, c, c)
                new_mesh.setVertexColor(vColor, v)

        # Set mesh edits
        new_mesh.updateSurface()

        cmds.select(all=True, hierarchy=True)
        cmds.select(current_objs, deselect=True)
        mesh = pm.selected()[0]
        # create vertex normal map
        if len(imported_object.vertexNormals) > 0:
            for v in range(0, imported_object.vertexNormalsCount, 1):
                values = imported_object.vertexNormals[v]
                vertex_normal_vector = values[0]
                polygon_id = int(values[1])
                vert_id = int(values[2])
                try:
                    pm.select(mesh.vtxFace[vert_id][polygon_id])
                    pm.polyNormalPerVertex(xyz=vertex_normal_vector)
                except IndexError, e:
                    print e
Beispiel #9
0
    def draw(self, view, path, style, status):
        OpenMayaMPx.MPxManipContainer.draw(self, view, path, style, status)

        if not self.isMouseDown:
            return

        u = OpenMaya.MPoint()
        v = OpenMaya.MPoint()
        drawText = ""
        am = self.activeManip()
        m = self.getTransformMtxFromNode(
                                self.helices[self.firstHelix].helixTransform)
        if am is self.fDistanceFrontManip:
            drawText = str(self.deltaFront)
            if self.deltaFront > 0:
                drawText = "+" + drawText
            c = self.canMove(self.deltaFront)
            if c[0]:
                drawText = "<  " + drawText
            if c[1]:
                drawText = drawText + "  >"
            u = self.sp * m
            v = u + self.frontDir * self.frontDistance
        elif am is self.fDistanceBackManip:
            drawText = str(self.deltaBack)
            if self.deltaBack > 0:
                drawText = "+" + drawText
            c = self.canMove(self.deltaBack)
            if c[0]:
                drawText = "<  " + drawText
            if c[1]:
                drawText = drawText + "  >"
            u = self.ep * m
            v = u + self.backDir * self.backDistance

        w = OpenMaya.MPoint((u.x + v.x) / 2, (u.y + v.y) / 2, (u.z + v.z) / 2)

        view.beginGL()
        view.setDrawColor(OpenMaya.MColor(0.9, 0, 0))
        view.drawText(drawText, w, OpenMayaUI.M3dView.kCenter)
        view.endGL()
Beispiel #10
0
def apply_vert_colors(obj, colors, vert_indexes):
    """
    Sets vert colors on the supplied mesh.
    
    Args:
        obj(string): Object to edit vert colors.
        colors(float[]): A list of rgb values.
        vert_indexes(int[]): A list of vertex indexes.
                             This should match the length of colors.
    """
    obj_shapes = cmds.listRelatives(obj, f=True, shapes=True) or []

    old_pcolor = set(
        cmds.ls(cmds.listHistory(obj_shapes), type="polyColorPerVertex"))

    color_array = OpenMaya.MColorArray()
    int_array = OpenMaya.MIntArray()

    for rgb, vert_index in zip(colors, vert_indexes):
        color_array.append(OpenMaya.MColor(rgb[0], rgb[1], rgb[2]))
        int_array.append(vert_index)

    selection_list = OpenMaya.MSelectionList()
    dag_path = OpenMaya.MDagPath()
    selection_list.add(obj)
    selection_list.getDagPath(0, dag_path)

    mfn_mesh = OpenMaya.MFnMesh(dag_path)
    mfn_mesh.setVertexColors(color_array,
                             int_array)  # This creates polyColorPerVertex

    new_pcolor = set(
        cmds.ls(cmds.listHistory(obj_shapes), type="polyColorPerVertex"))

    dif_pcolor = list(new_pcolor.difference(old_pcolor))
    if dif_pcolor:
        cmds.addAttr(dif_pcolor[0],
                     ln=constants.POLY_COLOR_PER_VERT,
                     dt="string")
        cmds.rename(dif_pcolor[0], constants.POLY_COLOR_PER_VERT)
Beispiel #11
0
    def draw(self, view, path, style, status):

        view.beginGL()
        # Push the current state
        glFuncTable.glPushAttrib(openmayarender.MGL_CURRENT_BIT)
        # Enable Blend mode(to enable transparency)
        glFuncTable.glEnable(openmayarender.MGL_BLEND)
        # Defined Blend function
        glFuncTable.glBlendFunc(openmayarender.MGL_SRC_ALPHA,
                                openmayarender.MGL_ONE_MINUS_SRC_ALPHA)

        if status == view.kActive:
            glFuncTable.glColor4f(0.2, 0.5, 0.1, 0.3)
        elif status == view.kLead:
            glFuncTable.glColor4f(0.5, 0.2, 0.1, 0.3)
        elif status == view.kDormant:
            glFuncTable.glColor4f(0.1, 0.1, 0.1, 0.3)

        # Draw Polygon shape
        glFuncTable.glBegin(openmayarender.MGL_POLYGON)
        glFuncTable.glVertex3f(-0.031, 0, -2.875)
        glFuncTable.glVertex3f(-0.939, 0.1, -2.370)
        glFuncTable.glVertex3f(-1.175, 0.2, -1.731)
        glFuncTable.glVertex3f(-0.603, 0.3, 1.060)
        glFuncTable.glVertex3f(0.473, 0.3, 1.026)
        glFuncTable.glVertex3f(0.977, 0.2, -1.731)
        glFuncTable.glVertex3f(0.809, 0.1, -2.337)
        glFuncTable.glVertex3f(0.035, 0, -2.807)

        glFuncTable.glEnd()
        # Disable blend shape
        glFuncTable.glDisable(openmayarender.MGL_BLEND)
        # Restore the state
        glFuncTable.glPopAttrib()

        view.endGL()

        view.setDrawColor(openmaya.MColor(0.1, 0.8, 0.7, 1.0))
        view.drawText("Left Foot", openmaya.MPoint(0, 0, 0), view.kLeft)
def fn_createObject_openMaya():
    global importedObj

    cmds.select(all=True, hierarchy=True)
    currentObjs = cmds.ls(selection=True)

    newMesh = om.MFnMesh()

    mergeVertices = True
    pointTolerance = 0.0001

    for p in range(0, len(importedObj.polys), 1):
        polylist = []
        vCount = len(importedObj.polys[p])
        polylist = om.MPointArray()
        polylist.setLength(vCount)
        for i in range(vCount):
            polylist.set(importedObj.omVertices[int(importedObj.polys[p][i])],
                         i)

        newMesh.addPolygon(polylist, mergeVertices, pointTolerance)

    if len(importedObj.weightMap) > 0:
        for v in range(0, importedObj.vertexCount, 1):
            c = importedObj.weightMap[v]
            vColor = om.MColor(c, c, c, c)
            newMesh.setVertexColor(vColor, v)

    newMesh.updateSurface()

    cmds.select(all=True, hierarchy=True)
    cmds.select(currentObjs, deselect=True)
    newObjs = cmds.ls(selection=True, transforms=True)
    cmds.select(newObjs, replace=True)
    cmds.sets(newObjs, e=True, forceElement='initialShadingGroup')
    cmds.rename(newObjs, importObjectName)
def BuildVecOrigin():
    dagPathMeshArray, oCompsArray, oMeshList = _getSelectedComponents()
    if not oCompsArray[0].isNull():
        oMeshArray = om.MObjectArray()
        iVertArray = om.MIntArray()
        iFaceArray = om.MIntArray()
        vPosArray = om.MVectorArray()
        vNormalArray = om.MVectorArray()
        cVtxColorArray = om.MColorArray()
        for x in range(dagPathMeshArray.length()):
            dagPathMesh = dagPathMeshArray[x]
            oMesh = dagPathMesh.node()
            oComps = oCompsArray[x]
            itComponent = om.MItMeshFaceVertex(
                dagPathMesh, oComps)  # iterate only on selected components
            while not itComponent.isDone():
                iVertArray.append(itComponent.vertId())
                iFaceArray.append(itComponent.faceId())
                oMeshArray.append(oMesh)
                cVtxColor = om.MColor()
                itComponent.getColor(cVtxColor, om.MSpace.kObject)
                cVtxColorArray.append(cVtxColor)
                #get normals in each vertex
                pPos = itComponent.position(om.MSpace.kWorld)
                vPosArray.append(om.MVector(pPos.x, pPos.y, pPos.z))
                oNormal = om.MVector()
                itComponent.getNormal(oNormal, om.MSpace.kObject)
                vNormalArray.append(oNormal)
                itComponent.next()
        return [
            oMeshArray, iVertArray, iFaceArray, vNormalArray, vPosArray,
            oMeshList, cVtxColorArray
        ]
    else:
        print "nothing test"
        return [0, 0, 0, 0, 0]
    else:
        xform = OpenMaya.MMatrix()
        xform.setToIdentity()

    dagPath.extendToShape()
    if (dagPath.apiType() == OpenMaya.MFn.kMesh):
        mesh = dagPath.node()
        meshFn = OpenMaya.MFnMesh(mesh)

        vertIter = OpenMaya.MItMeshVertex(dagPath, component)
        print "// ", vertIter.count(), " verts in ", dagPath.partialPathName()
        print "ErrorRenderLoop::Vertex_t g_verts_%s[%d] = {" % (
            dagPath.partialPathName(), vertIter.count())
        while not vertIter.isDone():
            vertPos = OpenMaya.MVector(vertIter.position()).rotateBy(rot)
            vertColor = OpenMaya.MColor(1, 1, 1, 1)
            vertNormal = OpenMaya.MVector()
            vertIter.getNormal(vertNormal)
            if (vertIter.hasColor()):
                vertIter.getColor(vertColor)
            vertNormal = vertNormal.rotateBy(rot)
            print "{%.3f,%.3f,%.3f,  %.3f,%.3f,%.3f, 0x%02X%02X%02X%02X }," % (
                vertPos.x, vertPos.y, vertPos.z, vertNormal.x, vertNormal.y,
                vertNormal.z, vertColor.r * 255, vertColor.g * 255,
                vertColor.b * 255, vertColor.a * 255)
            vertIter.next()
        print "};"

        faceIter = OpenMaya.MItMeshPolygon(dagPath, component)
        print "// ", faceIter.count(), " triangles"
        print "uint16_t g_tris_%s[%d][3] = {" % (dagPath.partialPathName(),
Beispiel #15
0
    def exportMesh(self,
                   mObject,
                   dagPath,
                   meshNode,
                   points,
                   us,
                   vs,
                   normals,
                   faceVertexColors,
                   exportOptions,
                   verbose=False):

        if verbose:
            print("\texportMesh")

        itMeshPoly = OpenMaya.MItMeshPolygon(mObject)
        numPerFaceVertices = 0
        while not itMeshPoly.isDone():
            currentFace = itMeshPoly.currentItem()

            numFaceVertices = itMeshPoly.polygonVertexCount()
            numPerFaceVertices = numPerFaceVertices + numFaceVertices

            itMeshPoly.next()

        if verbose:
            print("\tPer Faces Vertices  : %d" % numPerFaceVertices)

        numPoints = points.length()
        numNormals = normals.length()
        numFaces = meshNode.numPolygons()
        numUVs = us.length()

        hasColors = faceVertexColors and faceVertexColors.length() > 0

        if (numPerFaceVertices == numNormals):
            perFacePerVertexNormals = True
            mergeNormalsWithFaces = False
            mergeNormalsWithVertices = False
        elif (numFaces == numNormals):
            perFacePerVertexNormals = False
            mergeNormalsWithFaces = True
            mergeNormalsWithVertices = False
        elif (numNormals == numPoints):
            perFacePerVertexNormals = False
            mergeNormalsWithFaces = False
            mergeNormalsWithVertices = True

        mergeUVsWithVertices = (numUVs == numPoints)

        # PLY Vertex type
        vertexDType = [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]
        if mergeUVsWithVertices:
            if verbose:
                print("\tVertices have UVs")
            vertexDType.extend([('u', 'f4'), ('v', 'f4')])
        if mergeNormalsWithVertices:
            if verbose:
                print("\tVertices have Normals")
            vertexDType.extend([('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4')])

        vertices = np.zeros(numPoints, dtype=vertexDType)

        # Copy data to PLY vertex list
        for i in range(numPoints):
            vertex = (points[i].x, points[i].y, points[i].z)
            if mergeUVsWithVertices:
                vertex = vertex + (us[i], vs[i])
            if mergeNormalsWithVertices:
                vertex = vertex + (normals[i].x, normals[i].y, normals[i].z)
            vertices[i] = vertex

        # Copy data to PLY UV list, if necessary
        if not mergeUVsWithVertices:
            if verbose:
                print("\tUVs listed independently")
            uvs = np.zeros(numUVs, dtype=[('u', 'f4'), ('v', 'f4')])
            for i in range(us.length()):
                #print( "UV %d : %s, %s" % (i, us[i], vs[i]))
                uvs[i] = (us[i], vs[i])

        # Copy data to PLY Normals list, if necessary
        if perFacePerVertexNormals:
            if verbose:
                print("\tNormals listed independently")
            normalsNP = np.zeros(numNormals,
                                 dtype=[('nx', 'f4'), ('ny', 'f4'),
                                        ('nz', 'f4')])
            for i in range(normals.length()):
                #print( "Normals %d : %s %s %s" % (i,
                #    normals[i].x, normals[i].y, normals[i].z))
                normalsNP[i] = (normals[i].x, normals[i].y, normals[i].z)

        if hasColors:
            if verbose:
                print("\tColors listed independently")
            colorsNP = np.zeros(faceVertexColors.length(),
                                dtype=[('r', 'f4'), ('g', 'f4'), ('b', 'f4')])

            # Use this later
            faceColorDict = {}
            faceColorCount = 0

            for i in range(faceVertexColors.length()):
                #if verbose:
                #    print( "Colors %d : %s %s %s" % (i,
                #        faceVertexColors[i].r, faceVertexColors[i].g, faceVertexColors[i].b))
                color = (faceVertexColors[i].r, faceVertexColors[i].g,
                         faceVertexColors[i].b)
                colorsNP[i] = color
                faceColorDict[color] = i

        # Create face data
        rawFaces = []
        rawFaceUVs = []
        rawFaceNormals = []
        rawFaceNormalValues = []
        rawFaceColors = []

        colorIdxPx = OpenMaya.MScriptUtil()
        colorIdxPx.createFromInt(0)
        colorIdxPtr = colorIdxPx.asIntPtr()

        # object-relative vert indices in a face
        polygonVertices = OpenMaya.MIntArray()

        itMeshPoly = OpenMaya.MItMeshPolygon(mObject)
        while not itMeshPoly.isDone():
            currentFace = itMeshPoly.currentItem()
            numFaceVertices = itMeshPoly.polygonVertexCount()

            faceVertices = []
            faceVertexUVIndices = []
            faceVertexNormalIndices = []
            faceNormal = ()
            faceVertexColorIndices = []

            # Step through 'local' vertex indices
            # vertexIndex, getUVIndex, normalIndex and getColorIndex expect
            # local vertex indices
            for v in range(numFaceVertices):
                vertIndex = itMeshPoly.vertexIndex(v)
                faceVertices.append(vertIndex)

                if not mergeUVsWithVertices and us.length() > 0:
                    util = OpenMaya.MScriptUtil()
                    util.createFromInt(0)
                    uv_pInt = util.asIntPtr()
                    uv_index = OpenMaya.MScriptUtil()
                    uv_index.createFromInt(0)
                    itMeshPoly.getUVIndex(v, uv_pInt)
                    vertexUVIndex = uv_index.getInt(uv_pInt)
                    faceVertexUVIndices.append(vertexUVIndex)

                if not mergeNormalsWithVertices and normals.length() > 0:
                    vertexNormalIndex = itMeshPoly.normalIndex(v)
                    if perFacePerVertexNormals:
                        faceVertexNormalIndices.append(vertexNormalIndex)
                    else:
                        faceNormal = (normals[vertexNormalIndex].x,
                                      normals[vertexNormalIndex].y,
                                      normals[vertexNormalIndex].z)

                if hasColors:
                    itMeshPoly.getColorIndex(v, colorIdxPtr)

                    # Going to override this as the values seem to be off
                    vertColorIndex = OpenMaya.MScriptUtil(colorIdxPtr).asInt()

                    vertColorIndex0 = vertColorIndex

                    color = OpenMaya.MColor()
                    itMeshPoly.getColor(color, v)
                    colorTuple = (color.r, color.g, color.b)
                    if colorTuple in faceColorDict:
                        vertColorIndex = faceColorDict[colorTuple]

                    faceVertexColorIndices.append(vertColorIndex)

            rawFaces.append(faceVertices)
            rawFaceUVs.append(faceVertexUVIndices)
            rawFaceNormals.append(faceVertexNormalIndices)
            rawFaceColors.append(faceVertexColorIndices)
            rawFaceNormalValues.append(faceNormal)

            #if verbose:
            #    print( "Face %d Vertices : %s" % (i, faceVertices) )
            #    print( "Face %d UVs      : %s" % (i, faceVertexUVIndices) )
            #    print( "Face %d Normals  : %s" % (i, faceVertexNormalIndices) )
            #    print( "Face %d Normal   : %s" % (i, faceNormal) )
            #    print( "Face %d Colors   : %s" % (i, faceVertexColorIndices) )
            itMeshPoly.next()

        # Using 'object' instead of something like
        # ('vertex_indices', 'i4', (maxVertices,))
        # allows for faces with varying numbers of vertices
        dtype = []
        dtype.append(('vertex_indices', object))
        if not mergeUVsWithVertices:
            if verbose:
                print("\tFaces have Per-Vertex UVs")
            dtype.append(('uv_indices', object))
        if mergeNormalsWithFaces:
            if verbose:
                print("\tFaces have single Normals")
            dtype.extend([('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4')])
        elif perFacePerVertexNormals:
            if verbose:
                print("\tFaces have Per-Vertex Normals")
            dtype.append(('normals_indices', object))
        if hasColors:
            if verbose:
                print("\tFaces have Per-Vertex Colors")
            dtype.append(('colors_indices', object))

        #print( "Face D Type : %s" % str(dtype) )

        faces = np.zeros(numFaces, dtype=dtype)
        for i in range(numFaces):
            #print( "Face %d" % i )
            faceEntryIndex = 0
            faces[i][faceEntryIndex] = rawFaces[i]
            faceEntryIndex = faceEntryIndex + 1

            if not mergeUVsWithVertices:
                faces[i][faceEntryIndex] = rawFaceUVs[i]
                faceEntryIndex = faceEntryIndex + 1

            if mergeNormalsWithFaces:
                #print( "Normal : %3.3f, %3.3f, %3.3f" % (rawFaceNormalValues[i][0],
                #    rawFaceNormalValues[i][1], rawFaceNormalValues[i][2]) )
                faces[i][faceEntryIndex + 0] = float(rawFaceNormalValues[i][0])
                faces[i][faceEntryIndex + 1] = float(rawFaceNormalValues[i][1])
                faces[i][faceEntryIndex + 2] = float(rawFaceNormalValues[i][2])
                faceEntryIndex = faceEntryIndex + 3
            elif perFacePerVertexNormals:
                faces[i][2] = rawFaceNormals[i]
                faceEntryIndex = faceEntryIndex + 1

            if hasColors:
                faces[i][faceEntryIndex] = rawFaceColors[i]
                faceEntryIndex = faceEntryIndex + 1

        # Build PLY data structures
        text = False
        byte_order = '='
        if exportOptions:
            if 'format' in exportOptions and exportOptions['format'] == 'text':
                text = True

        plyElements = [
            ply.PlyElement.describe(vertices, 'vertex'),
            ply.PlyElement.describe(faces, 'face')
        ]
        if not mergeUVsWithVertices:
            plyElements.insert(-1, ply.PlyElement.describe(uvs, 'uvs'))
        if perFacePerVertexNormals:
            plyElements.insert(-1,
                               ply.PlyElement.describe(normalsNP, 'normals'))

        if hasColors:
            plyElements.insert(-1, ply.PlyElement.describe(colorsNP, 'colors'))

        plyData = ply.PlyData(plyElements,
                              text=text,
                              byte_order=byte_order,
                              comments=[dagPath])

        return plyData
Beispiel #16
0
    def importPly(self, plyPath, importOptions):
        verbose = False
        if importOptions:
            if 'verbose' in importOptions and importOptions[
                    'verbose'] == 'true':
                verbose = True

        plydata = ply.PlyData.read(str(plyPath))
        #if verbose:
        #    print( plydata )

        #
        # Process vertices
        #
        vertexElement = plydata['vertex']
        numVertices = vertexElement.count
        vertexAttributes = map(lambda x: x[0], vertexElement.dtype())

        if verbose:
            print("Vertices : %d" % numVertices)
            print("Vertex Attributes : %s" % vertexAttributes)

        vertexProperties = vertexElement.properties
        (x, y, z) = (vertexElement[t] for t in ('x', 'y', 'z'))

        vertices = OpenMaya.MFloatPointArray(numVertices)
        for i in range(numVertices):
            vertices.set(i, float(x[i]), float(y[i]), float(z[i]))

        vertexNormalsPresent = ('nx' in vertexAttributes
                                and 'ny' in vertexAttributes
                                and 'nz' in vertexAttributes)

        if vertexNormalsPresent:
            if verbose:
                print("Vertex Normals present")
            (nx, ny, nz) = (vertexElement[t] for t in ('nx', 'ny', 'nz'))
            vertexNormals = OpenMaya.MVectorArray()
            vertexNormalsIndices = OpenMaya.MIntArray()
            vertexNormalsIndices.setLength(numVertices)
            for i in range(numVertices):
                vertexNormals.append(
                    OpenMaya.MVector(float(nx[i]), float(ny[i]), float(nz[i])))
                vertexNormalsIndices.set(i, i)

        vertexUVsPresent = ('u' in vertexAttributes
                            and 'v' in vertexAttributes)
        if vertexUVsPresent:
            if verbose:
                print("Vertex UVs present")
            (u, v) = (vertexElement[t] for t in ('u', 'v'))
            uArray = OpenMaya.MFloatArray()
            uArray.setLength(numVertices)

            vArray = OpenMaya.MFloatArray()
            vArray.setLength(numVertices)

            for i in range(numVertices):
                uArray.set(float(u[i]), i)
                vArray.set(float(v[i]), i)

        vertexColorsPresent = ('r' in vertexAttributes
                               and 'g' in vertexAttributes
                               and 'b' in vertexAttributes)
        if vertexColorsPresent:
            if verbose:
                print("Vertex Colors present")
            (r, g, b) = (vertexElement[t] for t in ('r', 'g', 'b'))
            vertexColors = OpenMaya.MColorArray()
            vertexColorsIndices = OpenMaya.MIntArray()
            vertexColorsIndices.setLength(numVertices)
            for i in range(numVertices):
                vertexColors.append(
                    OpenMaya.MColor(float(r[i]), float(g[i]), float(b[i])))
                vertexColorsIndices.set(i, i)

        #
        # Process faces
        #
        faceElement = plydata['face']
        numFaces = faceElement.count
        faceAttributes = map(lambda x: x[0], faceElement.dtype())

        if verbose:
            print("Faces : %d" % numFaces)
            print("Face Attributes : %s" % faceAttributes)

        vertex_indices = faceElement['vertex_indices']

        faceCounts = OpenMaya.MIntArray()
        faceCounts.setLength(numFaces)
        faceIndicesCount = 0
        for i in range(numFaces):
            indices = vertex_indices[i]
            faceCounts.set(int(len(indices)), i)
            faceIndicesCount += int(len(indices))

        faceIndicesArray = OpenMaya.MIntArray()
        faceIndicesArray.setLength(faceIndicesCount)
        n = 0
        for i in range(numFaces):
            indices = vertex_indices[i]
            for j in range(len(indices)):
                faceIndicesArray.set(int(indices[j]), int(n))
                n = n + 1

        faceNormalsPresent = ('nx' in faceAttributes and 'ny' in faceAttributes
                              and 'nz' in faceAttributes)

        if faceNormalsPresent:
            if verbose:
                print("Per Face Normals present")
            (nx, ny, nz) = (faceElement[t] for t in ('nx', 'ny', 'nz'))
            faceNormals = OpenMaya.MVectorArray()
            faceNormalsIndices = OpenMaya.MIntArray()
            faceNormalsVertexIndices = OpenMaya.MIntArray()

            faceNormalsIndices.setLength(faceIndicesCount)
            faceNormalsVertexIndices.setLength(faceIndicesCount)
            n = 0
            for i in range(numFaces):
                indices = vertex_indices[i]
                for j in range(len(indices)):
                    faceNormals.append(
                        OpenMaya.MVector(float(nx[i]), float(ny[i]),
                                         float(nz[i])))
                    faceNormalsIndices.set(i, n)
                    faceNormalsVertexIndices.set(int(indices[j]), int(n))
                    n = n + 1

        normalsElement = None
        if 'normals' in plydata:
            normalsElement = plydata['normals']
        facePerVertexNormalsPresent = ('normals_indices'
                                       in faceAttributes) and normalsElement

        if facePerVertexNormalsPresent:
            if verbose:
                print("Per Face Per Vertex Normals present")

            (nx, ny, nz) = (normalsElement[t] for t in ('nx', 'ny', 'nz'))
            normals_indices = faceElement['normals_indices']

            faceNormals = OpenMaya.MVectorArray()
            faceNormalsIndices = OpenMaya.MIntArray()
            faceNormalsVertexIndices = OpenMaya.MIntArray()

            faceNormalsIndices.setLength(faceIndicesCount)
            faceNormalsVertexIndices.setLength(faceIndicesCount)
            n = 0
            for i in range(numFaces):
                indices = normals_indices[i]
                for j in range(len(indices)):
                    normalIndex = indices[j]
                    faceNormals.append(
                        OpenMaya.MVector(float(nx[normalIndex]),
                                         float(ny[normalIndex]),
                                         float(nz[normalIndex])))
                    faceNormalsIndices.set(i, n)
                    faceNormalsVertexIndices.set(int(normalIndex), int(n))
                    n = n + 1

                    #if verbose:
                    #    print( "Face %d : Vertex %d : Normal %3.3f, %3.3f, %3.3f" % (
                    #        i, j, float(nx[normalIndex]), float(ny[normalIndex]), float(nz[normalIndex])))

        uvElement = None
        if 'uvs' in plydata:
            uvElement = plydata['uvs']
        faceUVsPresent = ('uv_indices' in faceAttributes) and uvElement

        if faceUVsPresent:
            if verbose:
                print("Per Face Per Vertex UVs present")
            (u, v) = (uvElement[t] for t in ('u', 'v'))
            uv_indices = faceElement['uv_indices']

            uArray = OpenMaya.MFloatArray()
            uArray.setLength(len(u))

            vArray = OpenMaya.MFloatArray()
            vArray.setLength(len(v))

            for i in range(len(u)):
                uArray.set(float(u[i]), i)
                vArray.set(float(v[i]), i)

        colorsElement = None
        if 'colors' in plydata:
            colorsElement = plydata['colors']
        facePerVertexColorsPresent = ('colors_indices'
                                      in faceAttributes) and colorsElement

        if facePerVertexColorsPresent:
            if verbose:
                print("Per Face Per Vertex Colors present")

            (r, g, b) = (colorsElement[t] for t in ('r', 'g', 'b'))
            colors_indices = faceElement['colors_indices']

            faceColors = OpenMaya.MColorArray()
            faceColorsIndices = OpenMaya.MIntArray()
            faceColorsVertexIndices = OpenMaya.MIntArray()

            faceColorsIndices.setLength(faceIndicesCount)
            faceColorsVertexIndices.setLength(faceIndicesCount)
            n = 0
            for i in range(numFaces):
                indices = colors_indices[i]
                for j in range(len(indices)):
                    colorIndex = indices[j]
                    faceColors.append(
                        OpenMaya.MColor(float(r[colorIndex]),
                                        float(g[colorIndex]),
                                        float(b[colorIndex])))
                    faceColorsIndices.set(i, n)
                    faceColorsVertexIndices.set(int(colorIndex), int(n))
                    n = n + 1

        #
        # Build Maya mesh
        #
        outputMesh = OpenMaya.MObject()
        meshFS = OpenMaya.MFnMesh()
        newMesh = meshFS.create(numVertices, numFaces, vertices, faceCounts,
                                faceIndicesArray, outputMesh)

        if vertexNormalsPresent:
            meshFS.setVertexNormals(vertexNormals, vertexNormalsIndices)

        if vertexColorsPresent:
            meshFS.setVertexColors(vertexColors, vertexColorsIndices)

        if facePerVertexNormalsPresent:
            status = meshFS.setFaceVertexNormals(faceNormals,
                                                 faceNormalsIndices,
                                                 faceIndicesArray)

        if faceNormalsPresent:
            status = meshFS.setFaceVertexNormals(faceNormals,
                                                 faceNormalsIndices,
                                                 faceIndicesArray)

        if facePerVertexColorsPresent:
            meshFS.setFaceVertexColors(faceColors, faceColorsIndices,
                                       faceIndicesArray)

        if vertexUVsPresent:
            if verbose:
                print("Vertex UVs present")
            meshFS.setUVs(uArray, vArray)

            uvCounts = OpenMaya.MIntArray()
            uvCounts.setLength(numFaces)
            uvIds = OpenMaya.MIntArray()
            uvIds.setLength(faceIndicesCount)

            uvCountsIndex = 0
            uvIndex = 0
            for i in range(numFaces):
                numPolygonVertices = meshFS.polygonVertexCount(i)
                uvCounts.set(numPolygonVertices, int(uvCountsIndex))
                uvCountsIndex = uvCountsIndex + 1

                if numPolygonVertices == 0:
                    continue

                indices = vertex_indices[i]
                for vertexIndex in range(numPolygonVertices):
                    uvIds.set(int(indices[vertexIndex]), int(uvIndex))
                    uvIndex = uvIndex + 1

            meshFS.assignUVs(uvCounts, uvIds)

        if faceUVsPresent:
            if verbose:
                print("Face UVs present")
            meshFS.setUVs(uArray, vArray)

            uvCounts = OpenMaya.MIntArray()
            uvCounts.setLength(numFaces)
            uvIds = OpenMaya.MIntArray()
            uvIds.setLength(faceIndicesCount)

            uvCountsIndex = 0
            uvIndex = 0
            for i in range(numFaces):
                numPolygonVertices = meshFS.polygonVertexCount(i)
                uvCounts.set(numPolygonVertices, int(uvCountsIndex))
                uvCountsIndex = uvCountsIndex + 1

                if numPolygonVertices == 0:
                    continue

                indices = uv_indices[i]
                for vertexIndex in range(numPolygonVertices):
                    uvIds.set(int(indices[vertexIndex]), int(uvIndex))
                    uvIndex = uvIndex + 1

            meshFS.assignUVs(uvCounts, uvIds)

        meshFS.updateSurface()

        # Assign initial shading group
        initialSG = OpenMaya.MObject()
        slist = OpenMaya.MSelectionList()
        OpenMaya.MGlobal.getSelectionListByName("initialShadingGroup", slist)
        slist.getDependNode(0, initialSG)

        fnSG = OpenMaya.MFnSet(initialSG)
        if fnSG.restriction() == OpenMaya.MFnSet.kRenderableOnly:
            fnSG.addMember(newMesh)
Beispiel #17
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)
Beispiel #18
0
    def compute(self, plug, dataBlock):
        # Always update the whole array at once - we shouldn't be connecting to
        # only a single element in the output arrays anyway (ie, what happens
        # if the number of verts changes, and we're connected to an output
        # index whose vert no longer exists?)

        #print plug
        #print self.multiAttrs.values()

        if plug in self.multiAttrs.values():
            meshDataHandle = dataBlock.inputValue(self.meshAttr)
            meshObj = meshDataHandle.asMesh()

            handles = {}
            for comp, attr in self.multiAttrs.iteritems():
                handles[comp] = dataBlock.outputArrayValue(attr)

            builders = {}
            for comp, handle in handles.iteritems():
                builders[comp] = handle.builder()

            vertIter = om.MItMeshVertex(meshObj)
            while not vertIter.isDone():
                index = vertIter.index()

                # Retrieve the component color info
                color = om.MColor()
                if vertIter.hasColor():
                    vertIter.getColor(color)
                r = color.r
                g = color.g
                b = color.b
                a = color.a

                hUtil = om.MScriptUtil()
                hUtil.createFromDouble(0.0)
                hPtr = hUtil.asFloatPtr()

                sUtil = om.MScriptUtil()
                sUtil.createFromDouble(0.0)
                sPtr = hUtil.asFloatPtr()

                vUtil = om.MScriptUtil()
                vUtil.createFromDouble(0.0)
                vPtr = hUtil.asFloatPtr()

                color.get(color.kHSV, hPtr, sPtr, vPtr)

                h = hUtil.getFloat(hPtr)
                s = sUtil.getFloat(sPtr)
                v = vUtil.getFloat(vPtr)

                #print "rgba %3d: %s, %s, %s, %s" % (index, r, g, b, a)
                #print "hsv  %3d:  %s, %s, %s" % (index, h, s, v)

                # Add the elements to the array, and set them
                indexHandles = {}
                for comp, builder in builders.iteritems():
                    indexHandles[comp] = builder.addElement(index)

                indexHandles['red'].setFloat(r)
                indexHandles['green'].setFloat(g)
                indexHandles['blue'].setFloat(b)
                indexHandles['alpha'].setFloat(a)
                indexHandles['hue'].setFloat(h)
                indexHandles['saturation'].setFloat(s)
                indexHandles['value'].setFloat(v)

                # done!
                vertIter.next()

            # Set the array plugs to the builders
            for comp, handle in handles.iteritems():
                handle.set(builders[comp])

            # mark all array plugs clean
            for handle in handles.itervalues():
                handle.setAllClean()

            dataBlock.setClean(plug)
        return om.kUnknownParameter
Beispiel #19
0
    def draw(self, view, mdag_path, display_style, display_status):
        use_box = OpenMaya.MPlug(self.thisMObject(), Point.input_box).asInt()
        use_cross = OpenMaya.MPlug(self.thisMObject(),
                                   Point.input_cross).asInt()
        use_tick = OpenMaya.MPlug(self.thisMObject(), Point.input_tick).asInt()
        use_axis = OpenMaya.MPlug(self.thisMObject(), Point.input_axis).asInt()
        color_index = OpenMaya.MPlug(self.thisMObject(),
                                     Point.input_color).asInt()

        local_position = OpenMaya.MFnDependencyNode(
            self.thisMObject()).findPlug("localPosition")
        tx = local_position.child(0).asFloat()
        ty = local_position.child(1).asFloat()
        tz = local_position.child(2).asFloat()

        local_scale = OpenMaya.MFnDependencyNode(
            self.thisMObject()).findPlug("localScale")
        sx = local_scale.child(0).asFloat()
        sy = local_scale.child(1).asFloat()
        sz = local_scale.child(2).asFloat()

        if display_status == OpenMayaUI.M3dView.kActive:
            color = OpenMaya.MColor(1.0, 1.0, 1.0)
        elif display_status == OpenMayaUI.M3dView.kLead:
            color = OpenMaya.MColor(0.26, 1.0, 0.64)
        elif display_status == OpenMayaUI.M3dView.kActiveAffected:
            color = OpenMaya.MColor(0.783999979496, 0, 0.783999979496)
        elif display_status == OpenMayaUI.M3dView.kTemplate:
            color = OpenMaya.MColor(0.469999998808, 0.469999998808,
                                    0.469999998808)
        elif display_status == OpenMayaUI.M3dView.kActiveTemplate:
            color = OpenMaya.MColor(1.0, 0.689999997616, 0.689999997616)
        else:
            color = OpenMaya.MColor(self._colors[color_index][0],
                                    self._colors[color_index][1],
                                    self._colors[color_index][2])

        view.beginGL()

        if use_axis == 1:
            view.setDrawColor(OpenMaya.MColor(1.0, 0, 0))
            view.drawText("x", OpenMaya.MPoint(sx + tx, ty, tz),
                          OpenMayaUI.M3dView.kCenter)

            view.setDrawColor(OpenMaya.MColor(0, 1.0, 0))
            view.drawText("y", OpenMaya.MPoint(tx, sy + ty, tz),
                          OpenMayaUI.M3dView.kCenter)

            view.setDrawColor(OpenMaya.MColor(0, 0, 1.0))
            view.drawText("z", OpenMaya.MPoint(tx, ty, sz + tz),
                          OpenMayaUI.M3dView.kCenter)

        gl_FT.glPushAttrib(OpenMayaRender.MGL_CURRENT_BIT)
        gl_FT.glPushAttrib(OpenMayaRender.MGL_ALL_ATTRIB_BITS)
        gl_FT.glEnable(OpenMayaRender.MGL_BLEND)

        gl_FT.glBegin(OpenMayaRender.MGL_LINES)

        if use_box == 1:
            gl_FT.glColor3f(color.r, color.g, color.b)

            # Top
            gl_FT.glVertex3f(-sx + tx, sy + ty, -sz + tz)
            gl_FT.glVertex3f(sx + tx, sy + ty, -sz + tz)

            gl_FT.glVertex3f(sx + tx, sy + ty, -sz + tz)
            gl_FT.glVertex3f(sx + tx, sy + ty, sz + tz)

            gl_FT.glVertex3f(sx + tx, sy + ty, sz + tz)
            gl_FT.glVertex3f(-sx + tx, sy + ty, sz + tz)

            gl_FT.glVertex3f(-sx + tx, sy + ty, sz + tz)
            gl_FT.glVertex3f(-sx + tx, sy + ty, -sz + tz)

            # Bottom
            gl_FT.glVertex3f(-sx + tx, -sy + ty, -sz + tz)
            gl_FT.glVertex3f(sx + tx, -sy + ty, -sz + tz)

            gl_FT.glVertex3f(sx + tx, -sy + ty, -sz + tz)
            gl_FT.glVertex3f(sx + tx, -sy + ty, sz + tz)

            gl_FT.glVertex3f(sx + tx, -sy + ty, sz + tz)
            gl_FT.glVertex3f(-sx + tx, -sy + ty, sz + tz)

            gl_FT.glVertex3f(-sx + tx, -sy + ty, sz + tz)
            gl_FT.glVertex3f(-sx + tx, -sy + ty, -sz + tz)

            # Left
            gl_FT.glVertex3f(-sx + tx, -sy + ty, -sz + tz)
            gl_FT.glVertex3f(-sx + tx, sy + ty, -sz + tz)

            gl_FT.glVertex3f(-sx + tx, sy + ty, -sz + tz)
            gl_FT.glVertex3f(-sx + tx, sy + ty, sz + tz)

            gl_FT.glVertex3f(-sx + tx, sy + ty, sz + tz)
            gl_FT.glVertex3f(-sx + tx, -sy + ty, sz + tz)

            gl_FT.glVertex3f(-sx + tx, -sy + ty, sz + tz)
            gl_FT.glVertex3f(-sx + tx, -sy + ty, -sz + tz)

            # Right
            gl_FT.glVertex3f(sx + tx, -sy + ty, -sz + tz)
            gl_FT.glVertex3f(sx + tx, sy + ty, -sz + tz)

            gl_FT.glVertex3f(sx + tx, sy + ty, -sz + tz)
            gl_FT.glVertex3f(sx + tx, sy + ty, sz + tz)

            gl_FT.glVertex3f(sx + tx, sy + ty, sz + tz)
            gl_FT.glVertex3f(sx + tx, -sy + ty, sz + tz)

            gl_FT.glVertex3f(sx + tx, -sy + ty, sz + tz)
            gl_FT.glVertex3f(sx + tx, -sy + ty, -sz + tz)

        if use_cross == 1:
            gl_FT.glColor3f(color.r, color.g, color.b)

            gl_FT.glVertex3f(tx, -sy + ty, tz)
            gl_FT.glVertex3f(tx, sy + ty, tz)

            gl_FT.glVertex3f(-sx + tx, ty, tz)
            gl_FT.glVertex3f(sx + tx, ty, tz)

            gl_FT.glVertex3f(tx, ty, -sz + tz)
            gl_FT.glVertex3f(tx, ty, sz + tz)

        if use_tick == 1:
            gl_FT.glColor3f(color.r, color.g, color.b)

            gl_FT.glVertex3f((-sx * 0.05) + tx, (sy * 0.05) + ty, tz)
            gl_FT.glVertex3f((sx * 0.05) + tx, (-sy * 0.05) + ty, tz)

            gl_FT.glVertex3f((sx * 0.05) + tx, (sy * 0.05) + ty, tz)
            gl_FT.glVertex3f((-sx * 0.05) + tx, (-sy * 0.05) + ty, tz)

            gl_FT.glVertex3f(tx, (sy * 0.05) + ty, (-sz * 0.05) + tz)
            gl_FT.glVertex3f(tx, (-sy * 0.05) + ty, (sz * 0.05) + tz)

            gl_FT.glVertex3f(tx, (sy * 0.05) + ty, (sz * 0.05) + tz)
            gl_FT.glVertex3f(tx, (-sy * 0.05) + ty, (-sz * 0.05) + tz)

            gl_FT.glVertex3f((sx * 0.05) + tx, ty, (-sz * 0.05) + tz)
            gl_FT.glVertex3f((-sx * 0.05) + tx, ty, (sz * 0.05) + tz)

            gl_FT.glVertex3f((sx * 0.05) + tx, ty, (sz * 0.05) + tz)
            gl_FT.glVertex3f((-sx * 0.05) + tx, ty, (-sz * 0.05) + tz)

        if use_axis == 1:
            gl_FT.glColor3f(color.r, color.g, color.b)

            if display_status == OpenMayaUI.M3dView.kDormant:
                gl_FT.glColor3f(1.0, 0, 0)
            gl_FT.glVertex3f(tx, ty, tz)
            gl_FT.glVertex3f(sx + tx, ty, tz)

            if display_status == OpenMayaUI.M3dView.kDormant:
                gl_FT.glColor3f(0, 1.0, 0)
            gl_FT.glVertex3f(tx, ty, tz)
            gl_FT.glVertex3f(tx, sy + ty, tz)

            if display_status == OpenMayaUI.M3dView.kDormant:
                gl_FT.glColor3f(0, 0, 1.0)
            gl_FT.glVertex3f(tx, ty, tz)
            gl_FT.glVertex3f(tx, ty, sz + tz)

        gl_FT.glEnd()

        gl_FT.glDisable(OpenMayaRender.MGL_BLEND)
        gl_FT.glPopAttrib()
        gl_FT.glPopAttrib()

        view.endGL()
Beispiel #20
0
    def exportGeometry(self, msh, shp):

        # api calls
        dag = shp.__apiobject__()
        mshfn = om.MFnMesh(dag)

        # export materials
        pm.progressWindow( edit=True, status='mesh %s/%s (%s): writing materials...'%(self._prg_count,self._prg_msh,msh) )

        sgs = []
        sgf = []

        def faces(x):
          f = []
          for fs in x:
            if fs.startswith('f'):
              fs = fs.split('[')[1].split(']')[0]
              if ':' in fs:
                a, b = fs.split(':')
                a, b = int(a), int(b)
                f.extend(range(a, b + 1))
              else:
                f.append(int(fs))
          return f

        _o = shp.instObjGroups[0].objectGroups.outputs(type='shadingEngine')
        if _o:
            # multi mat
            for _id in shp.instObjGroups[0].objectGroups.getArrayIndices():
                og = shp.instObjGroups[0].objectGroups[_id]
                f = faces( og.objectGrpCompList.get() )

                _sg = og.outputs()
                if _sg and f:
                    sgs.append(_sg[0])
                    sgf.append(f)

        else:
            # single mat
            _o = shp.instObjGroups[0].outputs(type='shadingEngine')
            sgs += _o

        doColors = shp.displayColors.get()


        sgi = []

        for sg in sgs:
            mat = sg.surfaceShader.inputs()[0]
            if str(mat) in self.materials:
                if doColors:
                    for m in self.db['materials']:
                        if m['name'] == str(mat):
                            m['vertexColors'] = True
                            break
            else:
                i = len(self.materials)
                self.materials.append(str(mat))

                m = {
                    'id' : i,
                    'name' : str(mat),

                    'DbgColor' : 0xFFFFFF,
                    'DbgIndex' : i,
                    'DbgName'  : str(mat),
                }

                self.db['materials'].append(m)


                _nt = pm.nodeType(mat)
                if _nt in ('lambert', 'phong', 'blinn', 'anisotropic'):
                    m['shading'] = 'Phong'
                    m['colorDiffuse'] = roundList( mat.color.get(), DECIMALS_COLOR )
                    _c = pm.dt.Vector(mat.ambientColor.get()) + mat.incandescence.get()
                    m['colorAmbient'] = roundList( _c, DECIMALS_COLOR )
                    #m['colorEmissive'] = mat.incandescence.get()
                    m['colorSpecular'] = [0,0,0]

                    self.setTextureInfo(i, 'mapDiffuse', mat.color )
                    self.setTextureInfo(i, 'mapLight', mat.ambientColor )
                    self.setTextureInfo(i, 'mapBump', mat.normalCamera )

                    _t = mat.transparency.get()
                    _t = 1 - (_t[0]+_t[1]+_t[2]) / 3
                    if _t < 1:
                        m['transparency'] = _t
                        m['transparent'] = True

                if _nt in ('phong', 'blinn', 'anisotropic'):
                    m['colorSpecular'] = roundList( mat.specularColor.get(), DECIMALS_COLOR )
                    m['specularCoef'] = 10
                    if _nt == 'blinn':
                        m['specularCoef'] = 4 / mat.eccentricity.get()
                    elif _nt == 'phong':
                        m['specularCoef'] = mat.cosinePower.get() * 2
                    if _nt == 'anisotropic':
                        m['specularCoef'] = 4 / mat.roughness.get()


                    self.setTextureInfo(i, 'mapSpecular', mat.specularColor )

                if _nt == 'surfaceShader':
                    m['shading'] = 'Basic'
                    m['colorDiffuse'] = roundList( mat.outColor.get(), DECIMALS_COLOR )


                if shp.doubleSided.get():
                    m['doubleSided'] = True
                elif shp.opposite.get():
                    m['flipSided'] = True

                if doColors:
                    m['vertexColors'] = True

            sgi.append( self.materials.index(str(mat)) )



        # export vertices
        _v = mshfn.numVertices()
        _voffset = self.db['metadata']['vertices']
        self.db['metadata']['vertices'] += _v
        self.vertices.append(_v)

        pm.progressWindow( edit=True, status='mesh %s/%s (%s): writing vertices...'%(self._prg_count,self._prg_msh,msh) )


        _pts = om.MPointArray()
        mshfn.getPoints(_pts, om.MSpace.kWorld)

        for i in xrange(_v):
            _p = [ _pts[i][0], _pts[i][1], _pts[i][2] ]
            self.db['vertices'] += roundList( _p, DECIMALS_VERTICES )


        # export faces
        _f = mshfn.numPolygons()
        self.db['metadata']['faces'] += _f
        self.faces.append(_f)

        pm.progressWindow( edit=True, status='mesh %s/%s (%s): writing faces...'%(self._prg_count,self._prg_msh,msh) )


        uvs = {}

        _noffset = len(self.db['normals'])/3
        _normals = om.MFloatVectorArray()
        mshfn.getNormals(_normals,om.MSpace.kWorld)
        for i in xrange(_normals.length()):
            _n = [ _normals[i][0], _normals[i][1], _normals[i][2] ]
            self.db['normals'] += roundList( _n, DECIMALS_NORMALS )
        _npf = om.MIntArray()
        _nid = om.MIntArray()
        mshfn.getNormalIds(_npf, _nid)

        _coffset = len(self.db['colors'])


        _vfoffset = 0

        it = om.MItMeshPolygon(dag)
        while not it.isDone():
            f = it.index()

            # vertices
            _vtx = om.MIntArray()
            it.getVertices( _vtx )
            vtx = [x+_voffset for x in _vtx]

            if len(vtx)>4:
                self.db['metadata']['faces'] -= 1
                self.faces[-1] -= 1
                it.next()
                _vfoffset += len(vtx)
                continue
            else:
                dbf = [0]
                dbf += vtx
                if len(vtx)==4:
                    dbf[0] += FACE_QUAD

            # material
            dbf[0] += FACE_MATERIAL

            if len(sgs)==1:
                dbf.append(sgi[0])
            else:
                for i,fset in enumerate(sgf):
                    if f in fset:
                        dbf.append(sgi[i])
                        break

            # uvs
            _u = om.MFloatArray()
            _v = om.MFloatArray()
            try:
                it.getUVs( _u, _v )
                dbf[0] += FACE_VERTEX_UV

                for v,uv in zip( vtx, zip(_u,_v) ):
                    uv = roundList(uv, DECIMALS_UVS)

                    if not uvs.get(v):
                        uvs[v] = []

                    exported = False
                    for _i,_uv in uvs[v]:
                        if _uv == uv:
                            dbf.append(_i)
                            exported = True
                            break

                    if not exported:
                        i = len(self.db['uvs'][0])/2
                        self.db['uvs'][0] += uv
                        uvs[v].append((i,uv))
                        dbf.append(i)
            except:
                pass
                #print '# warning: %s.f[%s] has no uv' % (shp, f)

            # normals
            dbf[0] += FACE_VERTEX_NORMAL

            for i in xrange( len(vtx) ):
                _n = _nid[i+_vfoffset]
                dbf.append(_n+_noffset)

            # colors
            if doColors:
                dbf[0] += FACE_VERTEX_COLOR

                for i in xrange( len(vtx) ):
                    if it.hasColor( i ):
                        color = om.MColor()
                        it.getColor( color, i )
                        c = (int(color[0]*255)<<16) + (int(color[1]*255)<<8) + int(color[2]*255)
                        self.db['colors'].append(c)
                        dbf.append(i+_vfoffset+_coffset)
                    else:
                        # white for colorless vertex
                        dbf.append(0)
                        _coffset -= 1


            _vfoffset += len(vtx)

            # add face
            self.db['faces'] += dbf
            it.next()


        self._prg_count += 1
        pm.progressWindow( edit=True, step=1 )
Beispiel #21
0
    def deform(self, block, iter, mat, multiIndex):
        # ###################################
        # get attributes
        # ###################################
        # envelope
        envelope = block.inputValue(
            OpenMayaMPx.cvar.MPxDeformerNode_envelope).asFloat()
        if (envelope == 0.0):
            return

        # ==================================
        # aOrigMesh
        oOrig = block.inputValue(self.aOrigMesh).asMesh()
        if oOrig.isNull():
            return
        fnOrig = om.MFnMesh(oOrig)

        # ==================================
        # input[multiIndex].inputGeometry
        hInput = block.outputArrayValue(self.input)
        hInput.jumpToElement(multiIndex)
        hInputGeom = hInput.outputValue().child(self.inputGeom)
        oInputGeom = hInputGeom.asMesh()
        fnCurrent = om.MFnMesh(oInputGeom)

        # ==================================
        # aDisplayColors
        displayColors = block.inputValue(self.aDisplayColors).asBool()
        if (displayColors):
            colorBase = block.inputValue(self.aColorBase).asFloatVector()
            colorStretch = block.inputValue(self.aColorStretch).asFloatVector()
            colorSquash = block.inputValue(self.aColorSquash).asFloatVector()

        # ==================================
        # aMeasureTypeHeat
        measureTypeHeat = block.inputValue(self.aMeasureTypeHeat).asShort()

        # aMultiplyHeat aSquashMultiplyHeat aStretchMultiplyHeat
        multHeat = block.inputValue(self.aMultiplyHeat).asFloat()
        squashMultHeat = block.inputValue(self.aSquashMultiplyHeat).asFloat()
        stretchMultHeat = block.inputValue(self.aStretchMultiplyHeat).asFloat()
        if (multHeat == 0.0
                or squashMultHeat == 0.0 and stretchMultHeat == 0.0):
            return

        # aMaxHeat aSquashMaxHeat aStretchMaxHeat
        maxHeat = block.inputValue(self.aMaxHeat).asBool()
        squashMaxHeat = block.inputValue(self.aSquashMaxHeat).asFloat() * -1
        stretchMaxHeat = block.inputValue(self.aStretchMaxHeat).asFloat()
        if (squashMaxHeat == 0.0 and stretchMaxHeat == 0.0):
            return

        # aGrowHeat aSquashGrowHeat aStretchGrowHeat
        growHeat = block.inputValue(self.aGrowHeat).asInt()
        squashGrowHeat = block.inputValue(self.aSquashGrowHeat).asInt()
        stretchGrowHeat = block.inputValue(self.aStretchGrowHeat).asInt()

        # aIterationsSmoothHeat
        iterationsSmoothHeat = block.inputValue(
            self.aIterationsSmoothHeat).asInt()

        # aStrengthSmoothHeat
        strengthSmoothHeat = block.inputValue(
            self.aStrengthSmoothHeat).asFloat()

        # ==================================
        # aDeformationType
        deformationType = block.inputValue(self.aDeformationType).asShort()
        if (deformationType == 0):
            return

        # aIterationsSmoothDeformation
        iterationsSmoothDeformation = block.inputValue(
            self.aIterationsSmoothDeformation).asInt()

        # aStrengthSmoothDeformation
        strengthSmoothDeformation = block.inputValue(
            self.aStrengthSmoothDeformation).asFloat()

        # aTangentSpace
        tangentSpace = False
        if (deformationType == 2):
            tangentSpace = block.inputValue(self.aTangentSpace).asShort()

        # ==================================
        # aStretchMesh aSquashMesh
        if (deformationType == 2):
            # aStretchMesh
            oStretch = block.inputValue(self.aStretchMesh).asMesh()
            if oStretch.isNull():
                return
            fnStretch = om.MFnMesh(oStretch)
            stretchPoints = om.MPointArray()
            fnStretch.getPoints(stretchPoints)
            # aSquashMesh
            oSquash = block.inputValue(self.aSquashMesh).asMesh()
            if oSquash.isNull():
                return
            fnSquash = om.MFnMesh(oSquash)
            squashPoints = om.MPointArray()
            fnSquash.getPoints(squashPoints)
            # orig points
            origPoints = om.MPointArray()
            fnOrig.getPoints(origPoints)

        # ###################################
        # Gather information TODO: STORE in node (refresh button)
        # ###################################
        d_util = om.MScriptUtil()
        doublePtr = d_util.asDoublePtr()
        # orig edge lengths
        itEdgeOrig = om.MItMeshEdge(oOrig)
        edgeLengthsOrig = []
        lengthSum = 0.0
        while not itEdgeOrig.isDone():
            itEdgeOrig.getLength(doublePtr)
            eachLength = d_util.getDouble(doublePtr)
            lengthSum += eachLength
            edgeLengthsOrig.append(eachLength)
            itEdgeOrig.next()
        edgeLengthAvrg = lengthSum / itEdgeOrig.count()
        # orig face area
        itPolyOrig = om.MItMeshPolygon(oOrig)
        polyAreasOrig = []
        while not itPolyOrig.isDone():
            itPolyOrig.getArea(doublePtr)
            eachArea = d_util.getDouble(doublePtr)
            polyAreasOrig.append(eachArea)
            itPolyOrig.next()
        # connected edges and vertices (and faces)
        connectedEdges = []
        connectedPoints = []
        connectedFaces = []
        itPointCurrent = om.MItMeshVertex(oOrig)
        iaConnectedObjects = om.MIntArray()
        while not itPointCurrent.isDone():
            # edges
            itPointCurrent.getConnectedEdges(iaConnectedObjects)
            connectedEdges.append(list(iaConnectedObjects))
            # vertices
            itPointCurrent.getConnectedVertices(iaConnectedObjects)
            connectedPoints.append(list(iaConnectedObjects))
            # faces
            itPointCurrent.getConnectedFaces(iaConnectedObjects)
            connectedFaces.append(list(iaConnectedObjects))
            # finish
            itPointCurrent.next()

        # ###################################
        # Gather information per call
        # ###################################
        d_util = om.MScriptUtil()
        doublePtr = d_util.asDoublePtr()
        # current polygon area
        if (measureTypeHeat == 0):
            itPolyCurrent = om.MItMeshPolygon(oInputGeom)
            polyAreasCurrent = []
            while not itPolyCurrent.isDone():
                itPolyCurrent.getArea(doublePtr)
                eachArea = d_util.getDouble(doublePtr)
                polyAreasCurrent.append(eachArea)
                itPolyCurrent.next()
        # current edge length
        elif (measureTypeHeat == 1):
            edgeLengthsCurrent = []
            itEdgeCurrent = om.MItMeshEdge(oInputGeom)
            while not itEdgeCurrent.isDone():
                itEdgeCurrent.getLength(doublePtr)
                edgeLengthsCurrent.append(d_util.getDouble(doublePtr))
                itEdgeCurrent.next()
        # current normals
        if (deformationType == 1):
            currentNormals = om.MFloatVectorArray()
            fnCurrent.getVertexNormals(False, currentNormals,
                                       om.MSpace.kObject)
        # find relevant points
        paPoints = om.MPointArray()
        ptIndices = []
        ptWeights = []
        while not iter.isDone():
            iterIndex = iter.index()
            pt = iter.position()
            # get painted weight
            wPt = self.weightValue(block, multiIndex, iterIndex)
            if (wPt == 0.0):
                iter.next()
                continue
            # only store points with weights
            paPoints.append(pt)
            ptIndices.append(iterIndex)
            ptWeights.append(wPt)
            iter.next()
        iter.reset()

        # ###################################
        # Heat Calculation
        # ###################################
        # input: relevant points, default lengths, current lengths, edgeLengthAvrg
        # output: arHeat
        #
        # eachHeat =-1.0 // origLength*0 // squashed
        # eachHeat = 0.0 // origLength*1 // default
        # eachHeat = 1.0 // origLength*2 // stretched
        arHeat = []
        for x, eachId in enumerate(ptIndices):
            # measure difference between orig and current
            currentMeasure = 0.0
            origMeasure = 0.0
            # faces
            if (measureTypeHeat == 0):
                for eachFace in connectedFaces[eachId]:
                    currentMeasure += polyAreasCurrent[eachFace]
                    origMeasure += polyAreasOrig[eachFace]
                eachHeat = ((currentMeasure - origMeasure) / origMeasure)
            # edges
            elif (measureTypeHeat == 1):
                for eachEdge in connectedEdges[eachId]:
                    currentMeasure += edgeLengthsCurrent[eachEdge]
                    origMeasure += edgeLengthsOrig[eachEdge]
                # to have similar behavior as face area multiply
                eachHeat = ((currentMeasure - origMeasure) / origMeasure) * 2
            #

            # stretch and squash specific modification
            if (eachHeat < 0.0):
                eachHeat *= squashMultHeat * multHeat
                if (eachHeat < squashMaxHeat and maxHeat):
                    eachHeat = squashMaxHeat
            elif (eachHeat > 0.0):
                eachHeat *= stretchMultHeat * multHeat
                if (eachHeat > stretchMaxHeat and maxHeat):
                    eachHeat = stretchMaxHeat
            # store
            arHeat.append(eachHeat)

        # ###################################
        # Heat Grow
        # ###################################
        squashGrowHeat += growHeat
        stretchGrowHeat += growHeat
        if (squashGrowHeat or stretchGrowHeat):
            # find iteration count
            growIterations = squashGrowHeat
            if (stretchGrowHeat > growIterations):
                growIterations = stretchGrowHeat

            for y in range(growIterations):
                arHeatNew = list(arHeat)
                # loop through effected points
                for x, eachId in enumerate(ptIndices):
                    strongestSquash = arHeatNew[x]
                    strongestStretch = arHeatNew[x]
                    # loop over neighbors
                    for eachNeighborId in connectedPoints[eachId]:
                        if (eachNeighborId in ptIndices):
                            eachNeighborHeat = arHeat[ptIndices.index(
                                eachNeighborId)]
                            if (eachNeighborHeat < strongestSquash):
                                strongestSquash = eachNeighborHeat
                            if (eachNeighborHeat > strongestStretch):
                                strongestStretch = eachNeighborHeat
                    # set proper value
                    if (squashGrowHeat > y and stretchGrowHeat > y):
                        newValue = 0.0
                        if (strongestSquash < 0.0):
                            newValue = strongestSquash
                        if (strongestStretch > 0.0):
                            newValue += strongestStretch
                        if (newValue):
                            arHeatNew[x] = newValue
                    elif (squashGrowHeat > y and strongestSquash < 0.0):
                        if (arHeatNew[x] > 0.0):
                            arHeatNew[x] += strongestSquash
                        else:
                            arHeatNew[x] = strongestSquash
                    elif (stretchGrowHeat > y and strongestStretch > 0.0):
                        if (arHeatNew[x] < 0.0):
                            arHeatNew[x] += strongestStretch
                        else:
                            arHeatNew[x] = strongestStretch
                arHeat = arHeatNew
            #

        # ###################################
        # Heat Smooth
        # ###################################
        # input: arHeat
        # output: arHeat
        for y in range(iterationsSmoothHeat):
            arHeatNew = list(arHeat)
            for x, eachId in enumerate(ptIndices):
                neighborIds = connectedPoints[eachId]
                neighborAvrg = 0.0
                validNeighbor = False
                for eachNeighborId in neighborIds:
                    if (eachNeighborId in ptIndices):
                        validNeighbor = True
                        neighborAvrg += arHeat[ptIndices.index(eachNeighborId)]
                if (validNeighbor):
                    neighborAvrg /= len(neighborIds)
                    arHeatNew[x] = arHeatNew[x] * (
                        1.0 -
                        strengthSmoothHeat) + neighborAvrg * strengthSmoothHeat
            arHeat = arHeatNew

        # ###################################
        # Heat Display
        # ###################################
        # input: arHeat
        # result: vertexColors
        if (displayColors):
            colorList = om.MColorArray()
            indexList = om.MIntArray()
            for x, eachId in enumerate(ptIndices):
                # colorBase colorStretch colorSquash
                eachColor = om.MFloatVector(colorBase)
                if (arHeat[x] > 0.0):
                    eachColor += (colorStretch - eachColor) * (arHeat[x])
                elif (arHeat[x] < 0.0):
                    eachColor += (colorSquash - eachColor) * (arHeat[x] * -1)
                colorList.append(
                    om.MColor(eachColor.x, eachColor.y, eachColor.z, 1.0))
                indexList.append(eachId)
                #fnCurrent.setVertexColor( om.MColor(eachColor.x, eachColor.y, eachColor.z), eachId )# (setting all at once is faster)
            fnCurrent.setVertexColors(colorList, indexList)

        # ###################################
        # Deformation Calculation
        # ###################################
        # input: heatArray
        # output: motionVectorArray
        arVectors = []
        for x, eachId in enumerate(ptIndices):
            eachHeat = arHeat[x]
            vecMove = om.MVector()

            # skip calculation for 0.0 heat
            if (eachHeat == 0.0):
                arVectors.append(vecMove)
                continue

            # ###################################
            # Normal
            # ###################################
            if (deformationType == 1):
                # normal deformation
                vecMove += om.MVector(
                    currentNormals[eachId]) * (eachHeat * -1) * edgeLengthAvrg

            # ###################################
            # BlendShape
            # ###################################
            if (deformationType == 2):
                if (eachHeat < 0.0):
                    targetPt = squashPoints[eachId]
                    vecMove += (targetPt - origPoints[eachId]) * (eachHeat *
                                                                  -1)
                elif (eachHeat > 0.0):
                    targetPt = stretchPoints[eachId]
                    vecMove += (targetPt - origPoints[eachId]) * (eachHeat)
                # tangent spaces
                if (tangentSpace):
                    matTangentOrig = getTangentSpace(tangentSpace, fnOrig,
                                                     eachId,
                                                     connectedFaces[eachId])
                    matTangentCurrent = getTangentSpace(
                        tangentSpace, fnCurrent, eachId,
                        connectedFaces[eachId])
                    vecMove *= matTangentOrig.inverse() * matTangentCurrent
                #
            # save vector
            arVectors.append(vecMove)

        # ###################################
        # Deformation Smooth
        # ###################################
        # input: motionVectorArray
        # result: motionVectorArray
        for x in range(iterationsSmoothDeformation):
            arVectorsNew = list(arVectors)
            for x, eachId in enumerate(ptIndices):
                neighborIds = connectedPoints[eachId]
                neighborAvrg = om.MVector()
                validNeighbor = False
                for eachNeighborId in neighborIds:
                    if (eachNeighborId in ptIndices):
                        validNeighbor = True
                        neighborAvrg += arVectors[ptIndices.index(
                            eachNeighborId)]
                if (validNeighbor):
                    neighborAvrg /= len(neighborIds)
                    arVectorsNew[x] = arVectorsNew[x] * (
                        1.0 - strengthSmoothDeformation
                    ) + neighborAvrg * strengthSmoothDeformation
            arVectors = arVectorsNew

        # ###################################
        # Deformation
        # ###################################
        # input: motionVectorArray, weights
        # result: deformed mesh
        counter = 0
        while not iter.isDone():
            if (iter.index() in ptIndices):
                iter.setPosition(paPoints[counter] + arVectors[counter] *
                                 ptWeights[counter] * envelope)
                counter += 1
            iter.next()
Beispiel #22
0
    def createVoxelMesh(self, voxelCenterPosition, uvArray, texNodeName,
                        cubeWidth, outputMeshData):
        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
        #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()

        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 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], 1.0)
                    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)
            #for j in range (numPolygonConnectsPerVoxel):

        mFnMesh = OpenMaya.MFnMesh()
        #shapeNode
        mMeshShape = mFnMesh.create(totalVertices, totalPolygons, vertexArray,
                                    polygonCounts, polygonConnects,
                                    outputMeshData)
        #mMeshShape --> kMeshGeom
        mCubeMesh = OpenMaya.MFnMesh(mMeshShape)
        '''
		#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.createColorSetDataMesh('vertexColorSet')
            mCubeMesh.setVertexColors(vertexColorArray, vertexIndexArray, None,
                                      OpenMaya.MFnMesh.kRGBA)
        #'''

        return outputMeshData
Beispiel #23
0
    def test_array_creation(self):
        def assert_matches(ar, items):
            assert len(ar) == len(items)
            for i in xrange(len(ar)):
                assert ar[i] == items[i]
            # END assert array entry matches item entry

        # END assert items

        # test all random access types
        def assert_creation(cls, items):
            # from multiple
            ar = cls.mfromMultiple(*items)
            assert_matches(ar, items)

            # from iter
            ar = cls.mfromIter(iter(items))
            assert_matches(ar, items)

            # from list
            ar = cls.mfromList(items)
            assert_matches(ar, items)

            # test iteration
            ne = 0
            for elm in ar:
                ne += 1
            assert len(ar) == ne

        # END assert items

        col1 = api.MColor(1.0, 1.0)
        col2 = api.MColor(1.0, 2.0)
        col3 = api.MColor(1.0, 3.0)

        p1 = api.MPoint(1.0, 1.0)
        p2 = api.MPoint(1.0, 2.0)
        p3 = api.MPoint(1.0, 3.0)

        fp1 = api.MFloatPoint(1.0, 1.0)
        fp2 = api.MFloatPoint(1.0, 2.0)
        fp3 = api.MFloatPoint(1.0, 3.0)

        fv1 = api.MFloatVector(1.0, 1.0)
        fv2 = api.MFloatVector(1.0, 2.0)
        fv3 = api.MFloatVector(1.0, 3.0)

        v1 = api.MVector(1.0, 1.0)
        v2 = api.MVector(1.0, 2.0)
        v3 = api.MVector(1.0, 3.0)

        for cls, items in ((api.MIntArray, (4, 6, 7)), (api.MDoubleArray,
                                                        (4.0, 6.0, 7.0)),
                           (api.MFloatArray, (4.0, 6.0, 7.0)),
                           (api.MColorArray, (col1, col2, col3)),
                           (api.MPointArray, (p1, p2, p3)),
                           (api.MFloatPointArray, (fp1, fp2, fp3)),
                           (api.MFloatVectorArray,
                            (fv1, fv2, fv3)), (api.MVectorArray, (v1, v2,
                                                                  v3))):
            assert_creation(cls, items)
Beispiel #24
0
    #Get points.
    source_MfnMesh = OpenMaya.MFnMesh(source_mDagPath)
    source_Pnts = OpenMaya.MFloatPointArray()
    source_MfnMesh.getPoints(source_Pnts, OpenMaya.MSpace.kWorld)

    #Defining used variables.
    checkCollision = 0
    maxDeformation = 0.0
    dummyFloatArray = OpenMaya.MFloatArray()
    source_pntNormal = OpenMaya.MVector()

    #Get Vertex color.
    vertexColorList = OpenMaya.MColorArray()
    source_MfnMesh.getVertexColors(vertexColorList)
    collideColor = OpenMaya.MColor(1.0, 0.0, 0.0, 1.0)
    lenVertexList = vertexColorList.length()

    #Get Vert list.
    fnComponent = OpenMaya.MFnSingleIndexedComponent()
    fullComponent = fnComponent.create(OpenMaya.MFn.kMeshVertComponent)
    fnComponent.setCompleteData(lenVertexList)
    vertexIndexList = OpenMaya.MIntArray()
    fnComponent.getElements(vertexIndexList)

    # direct collision deformation:
    for k in xrange(source_Pnts.length()):
        source_MfnMesh.getVertexNormal(k, source_pntNormal,
                                       OpenMaya.MSpace.kWorld)

        # define an intersection ray from the mesh that should be deformed
    def deform(self, dataBlock, geoIterator, matrix, geometryIndex):
        input = OpenMayaMPx.cvar.MPxDeformerNode_input
        # attach a handle to input Array Attribute
        # prevent recomputation
        dataHandleInputArray = dataBlock.outputArrayValue(input)
        #jump to particular element
        dataHandleInputArray.jumpToElement(geometryIndex)
        #attach a handle to specific data block
        dataHandleInputElement = dataHandleInputArray.outputValue()
        #reach to the child
        inputGeom = OpenMayaMPx.cvar.MPxDeformerNode_inputGeom
        dataHandleInputGeom = dataHandleInputElement.child(inputGeom)
        inMesh = dataHandleInputGeom.asMesh()

        #envelope
        envolope = OpenMayaMPx.cvar.MPxDeformerNode_envelope
        dataHandleEnvelope = dataBlock.inputValue(envolope)
        envolopeValue = dataHandleEnvelope.asFloat()
        #amplitude
        dataHandleAmplitude = dataBlock.inputValue(rippleDeformer.amplitude)
        amplitudeValue = dataHandleAmplitude.asFloat()
        #displace
        dataHandleDisplace = dataBlock.inputValue(rippleDeformer.displacement)
        displaceValue = dataHandleDisplace.asFloat()
        #matrix
        dataHandleMatrix = dataBlock.inputValue(rippleDeformer.matrix)
        MatrixValue = dataHandleMatrix.asMatrix()
        #read translation from Matrix
        mTransMatrix = OpenMaya.MTransformationMatrix(MatrixValue)
        translationValue = mTransMatrix.getTranslation(OpenMaya.MSpace.kObject)

        #mEulerRot = OpenMaya.MVector()
        #mEulerRot = mTransMatrix.eulerRotation().asVector()

        mFloatVectorArray_Normal = OpenMaya.MFloatVectorArray()
        inMeshMfn = OpenMaya.MFnMesh(inMesh)
        inMeshMfn.getVertexNormals(False, mFloatVectorArray_Normal,
                                   OpenMaya.MSpace.kObject)
        #create colorSet
        inMeshMfn.createColorSetDataMesh('vertexColorSet')
        inMeshMfn.setIsColorClamped('vertexColorSet', True)
        mPointArray_meshVert = OpenMaya.MPointArray()
        mColorArray_meshVert = OpenMaya.MColorArray()
        mVertexArray_meshVert = OpenMaya.MIntArray()
        while (not geoIterator.isDone()):
            pointPosition = geoIterator.position()
            weight = self.weightValue(dataBlock, geometryIndex,
                                      geoIterator.index())
            #inMeshMfn.setVertexColor(pointColor, geoIterator.index(),None,OpenMaya.MFnMesh.kRGBA)
            pointPosition.x = pointPosition.x + math.sin(
                geoIterator.index() + displaceValue + translationValue[0]
            ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[
                geoIterator.index()].x * weight
            pointPosition.y = pointPosition.y + math.sin(
                geoIterator.index() + displaceValue + translationValue[0]
            ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[
                geoIterator.index()].y * weight
            pointPosition.z = pointPosition.z + math.sin(
                geoIterator.index() + displaceValue + translationValue[0]
            ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[
                geoIterator.index()].z * weight
            mPointArray_meshVert.append(pointPosition)
            #paint vertex color
            Color_R = math.sin(geoIterator.index() +
                               displaceValue) * amplitudeValue
            Color_G = math.cos(geoIterator.index() +
                               displaceValue) * amplitudeValue
            Color_B = math.sin(geoIterator.index() -
                               displaceValue) * amplitudeValue
            pointColor = OpenMaya.MColor(Color_R, Color_G, Color_B, 1.0)
            mColorArray_meshVert.append(pointColor)
            mVertexArray_meshVert.append(geoIterator.index())
            geoIterator.next()

        #optimize performance
        geoIterator.setAllPositions(mPointArray_meshVert)
        inMeshMfn.setVertexColors(mColorArray_meshVert, mVertexArray_meshVert,
                                  None, OpenMaya.MFnMesh.kRGBA)
        #set current colorset
        #inMeshMfn.setCurrentColorSetDataMesh('vertexColorSet')
        if (not cmds.polyColorSet(ccs=True, q=True) == 'vertexColorSet'):
            cmds.polyColorSet(ccs=True, cs='vertexColorSet')