setting vertex colors
first, run this code only on primitive objects until you understand what it does. this is for setting vertex colors of a vertex color map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bpy | |
import random | |
# start in object mode | |
my_object = bpy.data.objects['Cube'].data | |
color_map_collection = my_object.vertex_colors | |
if len(color_map_collection) == 0: | |
color_map_collection.new() | |
""" | |
let us assume for sake of brevity that there is now | |
a vertex color map called 'Col' | |
""" | |
color_map = color_map_collection['Col'] | |
# or you could avoid using the vertex color map name | |
# color_map = color_map_collection.active | |
i = 0 | |
for poly in my_object.polygons: | |
for idx in poly.loop_indices: | |
rgb = [random.random() for i in range(3)] | |
color_map.data[i].color = rgb | |
i += 1 | |
# set to vertex paint mode to see the result | |
bpy.ops.object.mode_set(mode='VERTEX_PAINT') |
getting vertex colors
getting vertex colors is similar but in reverse, remember that 1 vertex can be shared by several polygons and each polygon can set a different color for that vertex/index. Notice how the plane divided into 4 below has one central vertex which is shared by 4 surrounding polygons, each polygon has a different color for that vertex.Material from vertex color map
this requires setting viewport shading from solid to texture.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bpy | |
import random | |
# start in object mode | |
my_object = bpy.data.objects['Cube'].data | |
color_map_collection = my_object.vertex_colors | |
if len(color_map_collection) == 0: | |
color_map_collection.new() | |
""" | |
let us assume for sake of brevity that there is now | |
a vertex color map called 'Col' | |
""" | |
color_map = color_map_collection['Col'] | |
# or you could avoid using the vertex color map name | |
# color_map = color_map_collection.active | |
i = 0 | |
for poly in my_object.polygons: | |
for idx in poly.loop_indices: | |
rgb = [random.random() for i in range(3)] | |
color_map.data[i].color = rgb | |
i += 1 | |
mat = bpy.data.materials.new('vertex_material') | |
mat.use_vertex_color_paint = True | |
mat.use_vertex_color_light = True # material affected by lights | |
my_object.materials.append(mat) | |
# set viewport shading to texture to view this. |