Skip to content

Instantly share code, notes, and snippets.

@obriencole11
Last active June 8, 2022 20:48
Show Gist options
  • Save obriencole11/27cf6037d17c2adb1c26e59943e17402 to your computer and use it in GitHub Desktop.
Save obriencole11/27cf6037d17c2adb1c26e59943e17402 to your computer and use it in GitHub Desktop.
"""
Converts a polygon mesh to a first degree nurbs curve.
"""
from maya import cmds
import maya.api.OpenMaya as om2
def getSelectedMeshes():
"""
Gets the currently selected mesh paths.
Returns:
list(MDagPath): A list of dag paths for the selected meshes.
"""
sel = om2.MGlobal.getActiveSelectionList()
selected = []
for i in range(sel.length()):
mObj, dagPath = sel.getDependNode(i), sel.getDagPath(i)
if mObj.hasFn(om2.MFn.kMesh):
selected.append(dagPath)
for i in range(dagPath.childCount()):
childObj = dagPath.child(i)
if childObj.hasFn(om2.MFn.kMesh):
selected.append(om2.MDagPath.getAPathTo(childObj))
return selected
def getConnectedPoints(meshIt, index, indices=None, points=None):
"""
A recursive function that iteratively returns a line of points connecting all vertices on a mesh.
This function will
Args:
meshIt(MItMeshVertex): A mesh vertex iterator to use.
index(index): The vertex index to find connected points for.
indices(list): A list of connected vertex tuples that have been visited. Used to break recursion.
points(list): An existing list of points to append to.
Returns:
set, list: A set of connected vertex tuples and a list of MPoints.
"""
points = points or []
indices = indices or set()
# Add the current point
meshIt.setIndex(index)
points.append(meshIt.position(om2.MSpace.kWorld))
for connectedIndex in meshIt.getConnectedVertices():
# Skip visited points
if (index, connectedIndex) in indices:
continue
if (connectedIndex, index) in indices:
continue
# Recursively add connected vertices
indices.add((index, connectedIndex))
indices, points = getConnectedPoints(
meshIt, connectedIndex, indices, points
)
# Return the line of points to the current vertex
meshIt.setIndex(index)
points.append(meshIt.position(om2.MSpace.kWorld))
return indices, points
def convertSelectedMesh():
""" Converts the currently selected meshes to nurbs curves. """
for meshDag in getSelectedMeshes():
meshIt = om2.MItMeshVertex(meshDag)
indices, points = getConnectedPoints(meshIt, 0)
points = [om2.MVector(point) for point in points]
cmds.curve(p=points, degree=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment