forked from Taremin/ApplyModifier
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
356 lines (284 loc) · 12.3 KB
/
__init__.py
File metadata and controls
356 lines (284 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# Copyright (c) 2014 mato.sus304(mato.sus304@gmail.com)
#
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
from time import perf_counter as pc
bl_info = {
"name": "Apply Modifier With Shape Keys",
"author": "mate.sus304, Taremin, SAM-tak",
"version": (1, 2, 2),
"blender": (2, 80, 0),
"location": "View3D > Object > Apply",
"description": "Apply all modifiers to mesh object respecting shape keys.",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"website":"https://sites.google.com/site/matosus304blendernotes/home",
"category": "Object"
}
######################################################
def clear_shape_keys(obj, last_remain_shape_key_name):
if obj.data.shape_keys is None:
return True
for shape_key in obj.data.shape_keys.key_blocks:
if shape_key.name != last_remain_shape_key_name:
obj.shape_key_remove(shape_key)
if obj.data.shape_keys and len(obj.data.shape_keys.key_blocks) > 0:
obj.shape_key_remove(obj.data.shape_keys.key_blocks[0])
def clone_object(obj):
tmp_obj = obj.copy()
tmp_obj.name = f"applymodifier_tmp_{obj.name}"
tmp_obj.data = tmp_obj.data.copy()
tmp_obj.data.name = f"applymodifier_tmp_{obj.data.name}"
bpy.context.scene.collection.objects.link(tmp_obj)
return tmp_obj
def delete_object(obj):
if obj.data.users == 1:
obj.data.user_clear()
for scn in bpy.data.scenes:
try:
scn.collection.objects.unlink(obj)
except:
pass
def copy_attributes(a, b):
keys = dir(a)
for key in keys:
if not key.startswith("_") \
and not key.startswith("error_") \
and key != "group" \
and key != "strips" \
and key != "is_valid" \
and key != "rna_type" \
and key != "bl_rna":
try:
setattr(b, key, getattr(a, key))
except AttributeError:
pass
######################################################
def apply_modifier(target_object=None, target_modifiers=None):
if target_object is None:
obj_src = bpy.context.window.view_layer.objects.active
else:
obj_src = target_object
if target_modifiers is None:
target_modifiers = []
for x in obj_src.modifiers:
if x.show_viewport:
target_modifiers.append(x.name)
if len(target_modifiers) == 0:
# if object has no modifier then skip
return True
# make single user
if obj_src.data.users != 1:
obj_src.data = obj_src.data.copy()
if obj_src.data.shape_keys is None or len(obj_src.data.shape_keys.key_blocks) == 0:
# if object has no shapekeys, just apply modifier
bpy.context.window.view_layer.objects.active = obj_src
for x in target_modifiers:
try:
bpy.ops.object.modifier_apply(modifier=x)
except RuntimeError:
pass
return True
obj_fin = clone_object(obj_src)
bpy.context.window.view_layer.objects.active = obj_fin
clear_shape_keys(obj_fin, obj_src.data.shape_keys.key_blocks[0].name)
for x in target_modifiers:
try:
bpy.ops.object.modifier_apply(modifier=x)
except RuntimeError:
pass
flag_on_error = False
list_skipped = []
for i in range(1, len(obj_src.data.shape_keys.key_blocks)):
st = pc()
shape_key = obj_src.data.shape_keys.key_blocks[i]
tmp_name = shape_key.name
obj_tmp = clone_object(obj_src)
bpy.context.window.view_layer.objects.active = obj_tmp
clear_shape_keys(obj_tmp, tmp_name)
for x in target_modifiers:
try:
bpy.ops.object.modifier_apply(modifier=x)
except RuntimeError:
pass
obj_tmp.modifiers.clear()
obj_tmp.select_set(True)
bpy.context.window.view_layer.objects.active = obj_fin
try:
bpy.ops.object.join_shapes()
obj_fin.data.shape_keys.key_blocks[-1].name = tmp_name
except:
flag_on_error = True
list_skipped.append(tmp_name)
delete_object(obj_tmp)
print(f"{i} / {len(obj_src.data.shape_keys.key_blocks) - 1} done {tmp_name} : {pc()-st}")
# Copy shape key drivers
if obj_src.data.shape_keys.animation_data and obj_fin.data.shape_keys:
for d1 in obj_src.data.shape_keys.animation_data.drivers:
try:
d2 = obj_fin.data.shape_keys.driver_add(d1.data_path)
copy_attributes(d1, d2)
copy_attributes(d1.driver, d2.driver)
# Remove default modifiers, variables, etc.
for m in d2.modifiers:
d2.modifiers.remove(m)
for v in d2.driver.variables:
d2.driver.variables.remove(v)
# Copy modifiers
for m1 in d1.modifiers:
m2 = d2.modifiers.new(type=m1.type)
copy_attributes(m1, m2)
# Copy variables
for v1 in d1.driver.variables:
v2 = d2.driver.variables.new()
copy_attributes(v1, v2)
for i in range(len(v1.targets)):
copy_attributes(v1.targets[i], v2.targets[i])
except TypeError:
pass
tmp_name = obj_src.name
tmp_data_name = obj_src.data.name
obj_fin.name = tmp_name + '.tmp'
obj_src.data = obj_fin.data
obj_src.data.name = tmp_data_name
for x in target_modifiers:
obj_src.modifiers.remove(obj_src.modifiers[x])
delete_object(obj_fin)
bpy.context.window.view_layer.objects.active = obj_src
if flag_on_error:
def draw(self, context):
self.layout.label(text="Vertex Count Disagreement! Some shapekeys skipped.")
for s in list_skipped:
self.layout.label(text=s)
bpy.context.window_manager.popup_menu(draw, title="Error", icon='INFO')
return False
class AMWSK_OT_apply_all_modifiers(bpy.types.Operator):
"""Apply All Modifier to Selected Mesh Object"""
bl_idname = "amwsk.apply_all_modifiers"
bl_label = "Apply All Modifiers With Shape Keys"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return any([len(i.modifiers) > 0 for i in bpy.context.selected_objects])
def execute(self, context):
prev_active = bpy.context.window.view_layer.objects.active
targets = []
for x in bpy.context.selected_objects:
targets.append(x.name)
bpy.ops.object.select_all(action='DESELECT')
for x in targets:
apply_modifier(target_object=bpy.data.objects[x])
for x in targets:
bpy.data.objects[x].select_set(True)
bpy.context.window.view_layer.objects.active = prev_active
return {'FINISHED'}
class AMWSK_OT_apply_selected_modifier(bpy.types.Operator):
"""Apply Selected Modifier to Active Mesh Object"""
bl_idname = "amwsk.apply_selected_modifier"
bl_label = "Apply Selected Modifier With Shape Keys"
bl_options = {'REGISTER', 'UNDO'}
flags : bpy.props.BoolVectorProperty(name="Targets", description="Flags for applyee modifiers", size=32)
modifier_names = None
@classmethod
def poll(cls, context):
obj = context.object
return obj and obj.type == 'MESH'
def execute(self, context):
obj = context.window.view_layer.objects.active
if self.modifier_names and len(self.modifier_names) > 0:
bpy.ops.object.select_all(action='DESELECT')
str_targets = []
for i in range(len(self.modifier_names)):
if self.flags[i] and obj.modifiers[self.modifier_names[i]]:
str_targets.append(self.modifier_names[i])
apply_modifier(target_object=obj, target_modifiers=str_targets)
obj.select_set(True)
else:
self.modifier_names = tuple(i.name for i in obj.modifiers)
self.flags = tuple(False for i in range(32))
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def draw(self, context):
obj = context.object
layout = self.layout
col = layout.column()
for i in range(len(self.modifier_names)):
col.prop(self, "flags", text=self.modifier_names[i], index=i)
class AMWSK_OT_apply_pose_as_rest_pose(bpy.types.Operator):
"""Apply Armature Modifier to Selected Mesh Object and Apply Pose As Rest Pose to Armature"""
bl_idname = "amwsk.apply_pose_as_rest_pose"
bl_label = "Apply Armature Modifier With Shape Keys And Apply Current Pose As Rest Pose"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return any([i.type == 'ARMATURE' for i in context.selected_objects])
def execute(self, context):
targets = [i for i in context.selected_objects if i.type == 'ARMATURE']
prev_active = context.window.view_layer.objects.active
bpy.ops.object.select_all(action='DESELECT')
for obj_src in [i for i in context.window.view_layer.objects if i.type == 'MESH']:
target_modifiers = [x.name for x in obj_src.modifiers if x.type == 'ARMATURE' and x.object in targets]
if len(target_modifiers) > 0:
context.window.view_layer.objects.active = obj_src
for x in target_modifiers:
bpy.ops.object.modifier_copy(modifier=x)
duped_modifiers = []
for i in range(len(obj_src.modifiers)):
x = obj_src.modifiers[i]
if x.name in target_modifiers:
duped_modifiers.append(obj_src.modifiers[i+1].name)
apply_modifier(target_object=obj_src, target_modifiers=target_modifiers)
for x in obj_src.modifiers:
if x.name in duped_modifiers:
x.name = target_modifiers[duped_modifiers.index(x.name)]
for x in targets:
context.window.view_layer.objects.active = x
bpy.ops.object.mode_set(mode='POSE')
bpy.ops.pose.armature_apply(selected=False)
bpy.ops.object.mode_set(mode='OBJECT')
x.select_set(True)
context.window.view_layer.objects.active = prev_active
return {'FINISHED'}
# Registration
def apply_modifier_buttons(self, context):
self.layout.separator()
self.layout.operator(
AMWSK_OT_apply_all_modifiers.bl_idname,
text="Apply All Modifiers With Shape Keys")
self.layout.operator(
AMWSK_OT_apply_selected_modifier.bl_idname,
text="Apply Selected Modifier With Shape Keys")
self.layout.operator(
AMWSK_OT_apply_pose_as_rest_pose.bl_idname,
text="Apply Pose As Rest Pose With Shape Keys")
def register():
bpy.utils.register_class(AMWSK_OT_apply_all_modifiers)
bpy.utils.register_class(AMWSK_OT_apply_selected_modifier)
bpy.utils.register_class(AMWSK_OT_apply_pose_as_rest_pose)
bpy.types.VIEW3D_MT_object_apply.append(apply_modifier_buttons)
def unregister():
bpy.utils.unregister_class(AMWSK_OT_apply_all_modifiers)
bpy.utils.unregister_class(AMWSK_OT_apply_selected_modifier)
bpy.utils.unregister_class(AMWSK_OT_apply_pose_as_rest_pose)
bpy.types.VIEW3D_MT_object_apply.remove(apply_modifier_buttons)
if __name__ == "__main__":
register()