├── ApplyModifierForObjectWithShapeKeys.py ├── CHANGELOG.md ├── LICENSE ├── README.md └── screen.png /ApplyModifierForObjectWithShapeKeys.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------ 2 | # The MIT License (MIT) 3 | # 4 | # Copyright (c) 2015 Przemysław Bągard 5 | # 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be included in 14 | # all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | # THE SOFTWARE. 23 | # ------------------------------------------------------------------------------ 24 | 25 | # Date: 01 February 2015 26 | # Blender script 27 | # Description: Apply modifier and remove from the stack for object with shape keys 28 | # (Pushing 'Apply' button in 'Object modifiers' tab result in an error 'Modifier cannot be applied to a mesh with shape keys'). 29 | 30 | bl_info = { 31 | "name": "Apply modifier for object with shape keys", 32 | "author": "Przemysław Bągard, additonal contributions by Iszotic, updated to 2.93 by Fro Zen", 33 | "blender": (2,93,0), 34 | "version": (0,2,1), 35 | "location": "Context menu", 36 | "description": "Apply modifier and remove from the stack for object with shape keys (Pushing 'Apply' button in 'Object modifiers' tab result in an error 'Modifier cannot be applied to a mesh with shape keys').", 37 | "category": "Object Tools > Multi Shape Keys" 38 | } 39 | 40 | import bpy, math 41 | import time 42 | from bpy.utils import register_class 43 | from bpy.props import * 44 | 45 | # Algorithm (old): 46 | # - Duplicate active object as many times as the number of shape keys 47 | # - For each copy remove all shape keys except one 48 | # - Removing last shape does not change geometry data of object 49 | # - Apply modifier for each copy 50 | # - Join objects as shapes and restore shape keys names 51 | # - Delete all duplicated object except one 52 | # - Delete old object 53 | # Original object should be preserved (to keep object name and other data associated with object/mesh). 54 | 55 | # Algorithm (new): 56 | # Don't make list of copies, handle it one shape at time. 57 | # In this algorithm there shouldn't be more than 3 copy of object at time, so it should be more memory-friendly. 58 | # 59 | # - Copy object which will hold shape keys 60 | # - For original object (which will be also result object), remove all shape keys, then apply modifiers. Add "base" shape key 61 | # - For each shape key except base copy temporary object from copy. Then for temporaryObject: 62 | # - remove all shape keys except one (done by removing all shape keys, then transfering the right one from copyObject) 63 | # - apply modifiers 64 | # - merge with originalObject 65 | # - delete temporaryObject 66 | # - Delete copyObject. 67 | 68 | def applyModifierForObjectWithShapeKeys(context, selectedModifiers, disable_armatures): 69 | 70 | list_properties = [] 71 | properties = ["interpolation", "mute", "name", "relative_key", "slider_max", "slider_min", "value", "vertex_group"] 72 | shapesCount = 0 73 | vertCount = -1 74 | startTime = time.time() 75 | 76 | # Inspect modifiers for hints used in error message if needed. 77 | contains_mirror_with_merge = False 78 | for modifier in context.object.modifiers: 79 | if modifier.name in selectedModifiers: 80 | if modifier.type == 'MIRROR' and modifier.use_mirror_merge == True: 81 | contains_mirror_with_merge = True 82 | 83 | # Disable armature modifiers. 84 | disabled_armature_modifiers = [] 85 | if disable_armatures: 86 | for modifier in context.object.modifiers: 87 | if modifier.name not in selectedModifiers and modifier.type == 'ARMATURE' and modifier.show_viewport == True: 88 | disabled_armature_modifiers.append(modifier) 89 | modifier.show_viewport = False 90 | 91 | # Calculate shape keys count. 92 | if context.object.data.shape_keys: 93 | shapesCount = len(context.object.data.shape_keys.key_blocks) 94 | 95 | # If there are no shape keys, just apply modifiers. 96 | if(shapesCount == 0): 97 | for modifierName in selectedModifiers: 98 | bpy.ops.object.modifier_apply(modifier=modifierName) 99 | return (True, None) 100 | 101 | # We want to preserve original object, so all shapes will be joined to it. 102 | originalObject = context.view_layer.objects.active 103 | bpy.ops.object.select_all(action='DESELECT') 104 | originalObject.select_set(True) 105 | 106 | # Copy object which will holds all shape keys. 107 | bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(0, 0, 0), "orient_type":'GLOBAL', "orient_matrix":((1, 0, 0), (0, 1, 0), (0, 0, 1)), "orient_matrix_type":'GLOBAL', "constraint_axis":(False, False, False), "mirror":True, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "cursor_transform":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False}) 108 | copyObject = context.view_layer.objects.active 109 | copyObject.select_set(False) 110 | 111 | # Return selection to originalObject. 112 | context.view_layer.objects.active = originalObject 113 | originalObject.select_set(True) 114 | 115 | # Save key shape properties 116 | for i in range(0, shapesCount): 117 | key_b = originalObject.data.shape_keys.key_blocks[i] 118 | print (originalObject.data.shape_keys.key_blocks[i].name, key_b.name) 119 | properties_object = {p:None for p in properties} 120 | properties_object["name"] = key_b.name 121 | properties_object["mute"] = key_b.mute 122 | properties_object["interpolation"] = key_b.interpolation 123 | properties_object["relative_key"] = key_b.relative_key.name 124 | properties_object["slider_max"] = key_b.slider_max 125 | properties_object["slider_min"] = key_b.slider_min 126 | properties_object["value"] = key_b.value 127 | properties_object["vertex_group"] = key_b.vertex_group 128 | list_properties.append(properties_object) 129 | 130 | # Handle base shape in "originalObject" 131 | print("applyModifierForObjectWithShapeKeys: Applying base shape key") 132 | bpy.ops.object.shape_key_remove(all=True) 133 | for modifierName in selectedModifiers: 134 | bpy.ops.object.modifier_apply(modifier=modifierName) 135 | vertCount = len(originalObject.data.vertices) 136 | bpy.ops.object.shape_key_add(from_mix=False) 137 | originalObject.select_set(False) 138 | 139 | # Handle other shape-keys: copy object, get right shape-key, apply modifiers and merge with originalObject. 140 | # We handle one object at time here. 141 | for i in range(1, shapesCount): 142 | currTime = time.time() 143 | elapsedTime = currTime - startTime 144 | 145 | print("applyModifierForObjectWithShapeKeys: Applying shape key %d/%d ('%s', %0.2f seconds since start)" % (i+1, shapesCount, list_properties[i]["name"], elapsedTime)) 146 | context.view_layer.objects.active = copyObject 147 | copyObject.select_set(True) 148 | 149 | # Copy temp object. 150 | bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(0, 0, 0), "orient_type":'GLOBAL', "orient_matrix":((1, 0, 0), (0, 1, 0), (0, 0, 1)), "orient_matrix_type":'GLOBAL', "constraint_axis":(False, False, False), "mirror":True, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "cursor_transform":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False}) 151 | tmpObject = context.view_layer.objects.active 152 | bpy.ops.object.shape_key_remove(all=True) 153 | copyObject.select_set(True) 154 | copyObject.active_shape_key_index = i 155 | 156 | # Get right shape-key. 157 | bpy.ops.object.shape_key_transfer() 158 | context.object.active_shape_key_index = 0 159 | bpy.ops.object.shape_key_remove() 160 | bpy.ops.object.shape_key_remove(all=True) 161 | 162 | # Time to apply modifiers. 163 | for modifierName in selectedModifiers: 164 | bpy.ops.object.modifier_apply(modifier=modifierName) 165 | 166 | # Verify number of vertices. 167 | if vertCount != len(tmpObject.data.vertices): 168 | 169 | errorInfoHint = "" 170 | if contains_mirror_with_merge == True: 171 | errorInfoHint = "There is mirror modifier with 'Merge' property enabled. This may cause a problem." 172 | if errorInfoHint: 173 | errorInfoHint = "\n\nHint: " + errorInfoHint 174 | errorInfo = ("Shape keys ended up with different number of vertices!\n" 175 | "All shape keys needs to have the same number of vertices after modifier is applied.\n" 176 | "Otherwise joining such shape keys will fail!%s" % errorInfoHint) 177 | return (False, errorInfo) 178 | 179 | # Join with originalObject 180 | copyObject.select_set(False) 181 | context.view_layer.objects.active = originalObject 182 | originalObject.select_set(True) 183 | bpy.ops.object.join_shapes() 184 | originalObject.select_set(False) 185 | context.view_layer.objects.active = tmpObject 186 | 187 | # Remove tmpObject 188 | tmpMesh = tmpObject.data 189 | bpy.ops.object.delete(use_global=False) 190 | bpy.data.meshes.remove(tmpMesh) 191 | 192 | # Restore shape key properties like name, mute etc. 193 | context.view_layer.objects.active = originalObject 194 | for i in range(0, shapesCount): 195 | key_b = context.view_layer.objects.active.data.shape_keys.key_blocks[i] 196 | # name needs to be restored before relative_key 197 | key_b.name = list_properties[i]["name"] 198 | 199 | for i in range(0, shapesCount): 200 | key_b = context.view_layer.objects.active.data.shape_keys.key_blocks[i] 201 | key_b.interpolation = list_properties[i]["interpolation"] 202 | key_b.mute = list_properties[i]["mute"] 203 | key_b.slider_max = list_properties[i]["slider_max"] 204 | key_b.slider_min = list_properties[i]["slider_min"] 205 | key_b.value = list_properties[i]["value"] 206 | key_b.vertex_group = list_properties[i]["vertex_group"] 207 | rel_key = list_properties[i]["relative_key"] 208 | 209 | for j in range(0, shapesCount): 210 | key_brel = context.view_layer.objects.active.data.shape_keys.key_blocks[j] 211 | if rel_key == key_brel.name: 212 | key_b.relative_key = key_brel 213 | break 214 | 215 | # Remove copyObject. 216 | originalObject.select_set(False) 217 | context.view_layer.objects.active = copyObject 218 | copyObject.select_set(True) 219 | tmpMesh = copyObject.data 220 | bpy.ops.object.delete(use_global=False) 221 | bpy.data.meshes.remove(tmpMesh) 222 | 223 | # Select originalObject. 224 | context.view_layer.objects.active = originalObject 225 | context.view_layer.objects.active.select_set(True) 226 | 227 | if disable_armatures: 228 | for modifier in disabled_armature_modifiers: 229 | modifier.show_viewport = True 230 | 231 | return (True, None) 232 | 233 | class PropertyCollectionModifierItem(bpy.types.PropertyGroup): 234 | checked: BoolProperty(name="", default=False) 235 | bpy.utils.register_class(PropertyCollectionModifierItem) 236 | 237 | class ApplyModifierForObjectWithShapeKeysOperator(bpy.types.Operator): 238 | bl_idname = "object.apply_modifier_for_object_with_shape_keys" 239 | bl_label = "Apply modifier for object with shape keys" 240 | 241 | def item_list(self, context): 242 | return [(modifier.name, modifier.name, modifier.name) for modifier in bpy.context.object.modifiers] 243 | 244 | ##my_enum = EnumProperty(name="Modifier name", items = item_list) 245 | #my_enum: EnumProperty( 246 | #name="Modifier name", 247 | #items=item_list, 248 | #) 249 | 250 | #my_enum: BoolVectorProperty( 251 | #name="Modifier name", 252 | #size=len( 253 | #items=item_list, 254 | #) 255 | 256 | my_collection: CollectionProperty(type=PropertyCollectionModifierItem) 257 | 258 | #disable_armatures = BoolProperty(name="Don't include armature deformations", default = True) 259 | disable_armatures: BoolProperty( 260 | name="Don't include armature deformations", 261 | default=True, 262 | ) 263 | 264 | def execute(self, context): 265 | ob = bpy.context.object 266 | bpy.ops.object.select_all(action='DESELECT') 267 | context.view_layer.objects.active = ob 268 | ob.select_set(True) 269 | 270 | selectedModifiers = [o.name for o in self.my_collection if o.checked] 271 | 272 | if not selectedModifiers: 273 | self.report({'ERROR'}, 'No modifier selected!') 274 | return {'FINISHED'} 275 | 276 | success, errorInfo = applyModifierForObjectWithShapeKeys(context, selectedModifiers, self.disable_armatures) 277 | 278 | if not success: 279 | self.report({'ERROR'}, errorInfo) 280 | 281 | return {'FINISHED'} 282 | 283 | def draw(self, context): 284 | if context.object.data.shape_keys and context.object.data.shape_keys.animation_data: 285 | self.layout.separator() 286 | self.layout.label(text="Warning:") 287 | self.layout.label(text=" Object contains animation data") 288 | self.layout.label(text=" (like drivers, keyframes etc.)") 289 | self.layout.label(text=" assigned to shape keys.") 290 | self.layout.label(text=" Those data will be lost!") 291 | self.layout.separator() 292 | #self.layout.prop(self, "my_enum") 293 | box = self.layout.box() 294 | for prop in self.my_collection: 295 | box.prop(prop, "checked", text=prop["name"]) 296 | #box.prop(self, "my_collection") 297 | self.layout.prop(self, "disable_armatures") 298 | 299 | def invoke(self, context, event): 300 | self.my_collection.clear() 301 | for i in range(len(bpy.context.object.modifiers)): 302 | item = self.my_collection.add() 303 | item.name = bpy.context.object.modifiers[i].name 304 | item.checked = False 305 | return context.window_manager.invoke_props_dialog(self) 306 | 307 | class DialogPanel(bpy.types.Panel): 308 | bl_idname = "OBJECT_PT_apply_modifier_for_object_with_shape_keys" 309 | bl_label = "Multi Shape Keys" 310 | bl_space_type = "VIEW_3D" 311 | bl_region_type = "TOOLS" 312 | 313 | def draw(self, context): 314 | self.layout.operator("object.apply_modifier_for_object_with_shape_keys") 315 | 316 | classes = [ 317 | DialogPanel, 318 | ApplyModifierForObjectWithShapeKeysOperator 319 | ] 320 | 321 | def menu_func(self, context): 322 | self.layout.operator(ApplyModifierForObjectWithShapeKeysOperator.bl_idname) 323 | 324 | def register(): 325 | for cls in classes: 326 | bpy.utils.register_class(cls) 327 | bpy.types.VIEW3D_MT_object.append(menu_func) 328 | 329 | def unregister(): 330 | for cls in classes: 331 | bpy.utils.unregister_class(cls) 332 | 333 | if __name__ == "__main__": 334 | register() 335 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2021-11-07 2 | 1) Algorithm changed! Now instead of copying all objects to list, they are handled one by one. There will be maximum 3 copies of objects (including original object) at time. 3 | 4 | 2021-10-31 5 | 1) Algorithm changed! Now instead of copying objects with all shape keys then removing those shape keys, objects are copied without shape keys (except first one), then shape keys are transferred from original object to corresponding copies. It should be faster and less memory consuming for heavier models with many shape keys that way. 6 | 2) Changed combo to list with checkboxes for modifiers. It is possible now to apply multiple modifiers at once. 7 | 8 | 2021-03-23 9 | 1) Merged pull request. Thanks to Iszotic, addon now preserve some shape key's properties like value, range, mute, vertex group, relative to. 10 | 2) Added checkbox 'Don't include armature deformations', enabled by default. This solve the problem with applying bone scale to shape key during process. 11 | 3) Addon support Blender 2.9.2 12 | 13 | 2021-02-11 14 | Error message if number of vertices for shape keys is different. Number of vertices is checked after splitting mesh into many meshes but before merging any of them. 15 | 16 | 2021-02-05 17 | Added warning in dialog panel when user use operator on object with animation data (like drivers, keyframes) assigned to shape keys. Those data will be lost. 18 | 19 | 2020-09-15 20 | Addon support Blender 2.9. 21 | 22 | 2019-03-15 23 | Fixed problem with deleted shapekey's content. 24 | 25 | 2015-02-06 26 | Instead of duplicate for base shape, original object is used. 27 | 28 | 2015-02-04 29 | First commit. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Przemysław Bągard 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ApplyModifierForObjectWithShapeKeys 2 | *Blender script* 3 | 4 | Apply modifiers and remove them from the stack for objects with shape keys. 5 | (Pushing 'Apply' in the 'Object modifiers' tab results in the error 'Modifier cannot be applied to a mesh with shape keys'). 6 | 7 | ## Usage 8 | 9 | Press 'F3' and choose 'Apply modifier for object with shape keys'. 10 | 11 | ![screen](screen.png 'Addon location') 12 | 13 | ## Usage in script 14 | 15 | In case you want to use addon's method in script/exporter here is sample usage: 16 | 17 | ``` 18 | import bpy 19 | import time 20 | 21 | import ApplyModifierForObjectWithShapeKeys 22 | 23 | modifiers = ['Subdivision'] 24 | 25 | ApplyModifierForObjectWithShapeKeys.applyModifierForObjectWithShapeKeys(bpy.context, modifiers, True) 26 | ``` 27 | Modifiers are identified by name. 28 | 29 | Last parameter is 'Don't include armature deformation' and by default is set to true. 30 | 31 | Note that method assumes object is selected. 32 | 33 | ## Installation 34 | 35 | Select "File -> User Preferences" and choose "Addon" tab. Click "Install from file..." and choose the downloaded file (only "ApplyModifierForObjectWithShapeKeys.py", not the folder). 36 | 37 | ## How the script works 38 | 39 | The object is duplicated to match the number of shapekeys. For each object, all but one shape key is removed, with each object having a different shape key. Then, each object applies the selected modifier. After that, all objects are merged into one as shape keys. 40 | Note that this solution may not work for modifiers which change the amount of vertices for different shapes (for example, 'Boolean' modifier, or 'Mirror' with merge option). 41 | 42 | Algorithm changed! 43 | Now instead of copying all objects to list, they are handled one by one. There will be maximum 3 copies of objects (including original object) at time. 44 | It should be less memory consuming for heavier models with many shape keys that way. 45 | 46 | 47 | -------------------------------------------------------------------------------- /screen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/przemir/ApplyModifierForObjectWithShapeKeys/254904c8863100f458f9979294bddc225120d1fb/screen.png --------------------------------------------------------------------------------