To quickly toggle geometry shading from flat mode to smooth and back, we need to change the value of the “smooth” property for each polygon of the mesh.
Just to enable smooth shading for the active object, we can execute the following code:
1 2 |
obj = bpy.context.object obj.data.polygons.foreach_set('use_smooth', [True] * len(obj.data.polygons)) |
Specifying False instead of True, we will enable the flat shading mode.
To make toggling – switching shading between these two modes and back, we can use the “not” operator for the “smooth” property:
1 2 3 |
obj = bpy.context.object for i in range(len(obj.data.polygons)): setattr(obj.data.polygons[i], 'use_smooth', not obj.data.polygons[i].use_smooth) |
Every time this code is executed, the shading will switch from the current mode to the opposite.
Let’s define an operator, and place this code for toggling shading modes in its execute function:
1 2 3 4 5 6 7 8 9 10 11 |
class Shade_OP_Toggle(bpy.types.Operator): bl_idname = 'shade.toggle' bl_label = 'SHADE' def execute(self, context): # toggle shade flat-smooth for obj in context.selected_objects: for p in obj.data.polygons: setattr(p, 'use_smooth', not p.use_smooth) context.object.data.update() return {'FINISHED'} |
For each of the selected objects, we loop through its polygons and reverse shading.
To see the changes in the 3D viewport immediately, we execute the update command for the object data:
1 |
context.object.data.update() |
Define a custom panel in the 3D viewport area with the “SHADE” tab label:
1 2 3 4 5 6 7 8 9 |
class SHADE_PT_Panel(bpy.types.Panel): bl_idname = 'SHADE_PT_panel' bl_label = 'SHADE' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'SHADE' def draw(self, context): self.layout.operator('shade.toggle', text = 'Toggle Shade') |
In its draw function, we define a “Toggle Shade” button that invokes the toggle shading operator we defined earlier.
Don’t forget to register the operator and panel classes in the Blender Python API:
1 2 |
register_class(Shade_OP_Toggle) register_class(SHADE_PT_Panel) |
Now, each time we press the button on our panel, the shading of all selected objects will toggle to the opposite one.