Selecting vertices by vertex color

Mesh vertices don’t have a “color” property. Vertex colors specified by coloring in Vertex Paint mode or any other way are stored in an attribute – a separate list of values. To select a vertex by the color assigned to it in an attribute, we need to associate the attribute’s index with the vertex index.

There is no direct link between the vertex index and the color index in the attribute, either. This is because one vertex can have more than one color.

For example, let’s take two adjacent polygons and color them purple and blue. What color in this case should be assigned to vertices with indices 0 and 3 – blue or purple? Assigning only one color to a vertex will distort the color of the polygon.

To avoid such ambiguity on adjacent polygons, colors are assigned to vertices not by their indices, but by the indices of the polygon’s “loops”.

A mesh consisting of two adjacent polygons has 6 vertices with indices from 0 to 5, and at the same time, each of its polygons has 4 loops with indices from 0 to 7.

In our case, for the vertex with index 0, blue is assigned to the loop with index 0, and purple is assigned to the loop with index 5. For the vertex with index 3, blue is assigned to the loop with index 3, and purple is assigned to the loop with index 6.

So, each vertex can have several colors, more precisely, as many as how many polygons this vertex belongs to.

A mesh can have multiple independent coloring distributed on layers. The list of layers, each with its own coloring, is stored in the “vertex_colors” parameter.

The currently active layer can be obtained through the “active” pointer:

And the list of colors themselves we can get from the “data” pointer:

Having a list of colors for all points, we can go through all polygon loops, get the necessary indices, and use these indices to get the colors corresponding to the mesh vertices.

First, loop through all the polygons:

and for each polygon, loop by its loop indices:

By the index of the loop, we can get the color data for the active color layer:

and, for example, select those vertices that are colored red for at least one polygon:

To compare color components, we can use full equality (the == sign), but the comparison conditions > and < are better to get rid of inaccuracies for floating point numbers.

The complete code to select all red vertices of the currently active mesh:

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments