MFnMesh.numColors() returns the number of colors per-polygon per-vertex. Or so the documentation says.
However I’ve seen this function return all sorts of crazy numbers and I’m not quite sure what’s going on here. The code is below.
What I’m trying to achieve is to apply a function on each vertex face. The function does some magic based on position data. The issue I get is when I try to APPLY these colors. MFnMesh.setColors() will give you a kInvalidParameter error if MFnMesh.numColors() is larger than the length of your MColorArray. And since numColors() goes bananas, it doesn’t matter how I iterate over my geometry. On a simple prism (two triangle end pieces, three quad sides) I get numColors() = 67
import maya.OpenMaya as om
# Get selection
selection = om.MSelectionList()
component = om.MObject()
mDagPath = om.MDagPath()
om.MGlobal.getActiveSelectionList(selection)
selection.getDagPath(0, mDagPath, component)
meshFn = om.MFnMesh(mDagPath)
# This one will lie to us. I've got all kinds of weird numbers from this one...
print("numColors: %s" % meshFn.numColors())
color_array = om.MColorArray()
color_ids = om.MIntArray()
# The iterators are great. They don't lie to us. They will go thru the geo as it is.
mItFaceVtx = om.MItMeshFaceVertex(mDagPath)
while not mItFaceVtx.isDone():
# Bal bla bla - Running some func for determining color based on it's position here...
# ...but for now, use dummy data
color = om.MColor()
color.r = 0.2
color.g = 0.3
color.b = 0.4
color_array.append(color)
# Getting the color index of the current vertex face. Unfortunately getColorIndex requires an Int &
intRef = om.MScriptUtil().asIntPtr()
mItFaceVtx.getColorIndex(intRef, "my_color_set")
# ...okay we got the pointer, now we want it as an Int
id = om.MScriptUtil(intRef).asInt()
print("id: %s" % id)
color_ids.append(id)
print("color_ids are now of len(): %s" % len(color_ids))
mItFaceVtx.next()
meshFn.setColors(color_array, "my_color_set") # ...and since numColors() is crazy, we get kInvalidParameter quite often here
meshFn.assignColors(color_ids, "my_color_set")
meshFn.setCurrentColorSetName("my_color_set")