## Description
The “Shape Key Cleaner” script helps clean up shape keys in selected mesh objects in a Blender scene. It performs two main actions:
1. It removes any shape keys that have the same vertex coordinates as the first shape key (basis shape key).
2. If the first shape key is the only one left after the process, it removes the first shape key as well.
## How to Use
1. Open Blender and load the scene containing the mesh objects you want to process.
2. In the 3D Viewport, select the mesh objects with shape keys that you want to clean up.
3. Open the Scripting workspace or Text Editor in Blender and create a new text file.
4. Copy and paste the “Shape Key Cleaner” script into the text file.
5. Click the “Run Script” button to execute the script.
6. The script will process the selected mesh objects and clean up the shape keys as described.
## Source
```python
import bpy
import math
# Define a tolerance for comparing vertex positions
tolerance = 1e-5
def are_vertices_equal(verts_a, verts_b):
for i in range(len(verts_a)):
if math.sqrt((verts_a[i].co - verts_b[i].co).length_squared) > tolerance:
return False
return True
# Iterate over all selected objects
for obj in bpy.context.selected_objects:
# Check if the object is a mesh and has shape keys
if obj.type == 'MESH' and obj.data.shape_keys:
# Get the vertex coordinates of the first shape key (basis shape key)
basis_shape_key = obj.data.shape_keys.key_blocks[0]
basis_verts = basis_shape_key.data
# Iterate over the rest of the shape keys (ignoring the first one)
i = 1
while i < len(obj.data.shape_keys.key_blocks):
shape_key = obj.data.shape_keys.key_blocks[i]
# Compare the vertex coordinates to the basis shape key's coordinates
if are_vertices_equal(basis_verts, shape_key.data):
# If the vertex coordinates match, delete the shape key
bpy.context.object.active_shape_key_index = i
bpy.ops.object.shape_key_remove(all=False)
else:
i += 1
# Delete the first shape key if it's the only one left
if len(obj.data.shape_keys.key_blocks) == 1:
bpy.context.object.active_shape_key_index = 0
bpy.ops.object.shape_key_remove(all=False)
```