Assigning custom properties to vertexes

Working with mesh geometry, it may be necessary to assign each vertex some custom properties or data that must be written to the blend-file when saved, and which must be accessed later.

However, an attempt to assign the necessary data to the vertexes through the creation of custom properties fails. Instead of the custom vertex property, only a tuple with reference to the type of the property is created.

This happens because we can set custom properties only to the ID-types objects, for example, meshes, bones, shaders. But vertexes do not correspond to this type, therefore it is impossible to give them additional properties in this way.

It seems that the problem cannot be solved … But we have BMesh, which provides more opportunities in terms of working with meshes!

It is also impossible to directly assign additional properties to vertexes through the BMesh structure. When updating mesh data from the BMesh structure, only the main data is saved. However, BMesh allows the user to specify additional data to vertices (as well as edges, polygons, and loops) through the layers system.

The vertex layer in BMesh is an array of a certain data type with a size equal to the number of vertices. Each cell of the array is tied to a specific vertex through its index i.e. the cell of the layer with index 0 is associated with the vertex with index 0, the cell with index 1 – with the vertex with index 1, etc.

Having created such a layer, we get an array of cells, into which we can write the custom data we need, each of which corresponds to its own vertex.

To create a vertex layer we need to execute the following code:

Here we created a vertex layer of type “int”, so we can specify for each vertex additional data of one integer type number.

Having the layer, we can enter the necessary data into it. For example, save the currently selected vertices:

For selected vertices, 1 will be written to the layer, for non-selected vertices – 0.

As we can see, data from the vertex layer is accessed from the vertex itself using the layer name.

A layer itself can be obtained by its name through calling the get() method:

The following code will print our custom data (selection status) from a previously created layer:

 

Nikita

Author: Nikita

Blender add-ons developer and articles writer.