Import images: add file handler
[blender-addons.git] / space_view3d_copy_attributes.py
blobadb5483e96668f0cd641bc10b497151f8594ad91
1 # SPDX-FileCopyrightText: 2010-2023 Blender Foundation
3 # SPDX-License-Identifier: GPL-2.0-or-later
5 bl_info = {
6 "name": "Copy Attributes Menu",
7 "author": "Bassam Kurdali, Fabian Fricke, Adam Wiseman, Demeter Dzadik",
8 "version": (0, 6, 0),
9 "blender": (3, 4, 0),
10 "location": "View3D > Ctrl-C",
11 "description": "Copy Attributes Menu",
12 "doc_url": "{BLENDER_MANUAL_URL}/addons/interface/copy_attributes.html",
13 "category": "Interface",
16 import bpy
17 from mathutils import Matrix
18 from bpy.types import (
19 Operator,
20 Menu,
22 from bpy.props import (
23 BoolVectorProperty,
24 StringProperty,
27 # First part of the operator Info message
28 INFO_MESSAGE = "Copy Attributes: "
31 def build_exec(loopfunc, func):
32 """Generator function that returns exec functions for operators """
34 def exec_func(self, context):
35 loopfunc(self, context, func)
36 return {'FINISHED'}
37 return exec_func
40 def build_invoke(loopfunc, func):
41 """Generator function that returns invoke functions for operators"""
43 def invoke_func(self, context, event):
44 loopfunc(self, context, func)
45 return {'FINISHED'}
46 return invoke_func
49 def build_op(idname, label, description, fpoll, fexec, finvoke):
50 """Generator function that returns the basic operator"""
52 class myopic(Operator):
53 bl_idname = idname
54 bl_label = label
55 bl_description = description
56 execute = fexec
57 poll = fpoll
58 invoke = finvoke
59 return myopic
62 def genops(copylist, oplist, prefix, poll_func, loopfunc):
63 """Generate ops from the copy list and its associated functions"""
64 for op in copylist:
65 exec_func = build_exec(loopfunc, op[3])
66 invoke_func = build_invoke(loopfunc, op[3])
67 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
68 poll_func, exec_func, invoke_func)
69 oplist.append(opclass)
72 def generic_copy(source, target, string=""):
73 """Copy attributes from source to target that have string in them"""
74 for attr in dir(source):
75 if attr.find(string) > -1:
76 try:
77 setattr(target, attr, getattr(source, attr))
78 except:
79 pass
80 return
83 def getmat(bone, active, context, ignoreparent):
84 """Helper function for visual transform copy,
85 gets the active transform in bone space
86 """
87 obj_bone = bone.id_data
88 obj_active = active.id_data
89 data_bone = obj_bone.data.bones[bone.name]
90 # all matrices are in armature space unless commented otherwise
91 active_to_selected = obj_bone.matrix_world.inverted() @ obj_active.matrix_world
92 active_matrix = active_to_selected @ active.matrix
93 otherloc = active_matrix # final 4x4 mat of target, location.
94 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
95 if data_bone.parent:
96 parentposemat = obj_bone.pose.bones[data_bone.parent.name].matrix.copy()
97 parentbonemat = data_bone.parent.matrix_local.copy()
98 else:
99 parentposemat = parentbonemat = Matrix()
100 if parentbonemat == parentposemat or ignoreparent:
101 newmat = bonemat_local.inverted() @ otherloc
102 else:
103 bonemat = parentbonemat.inverted() @ bonemat_local
105 newmat = bonemat.inverted() @ parentposemat.inverted() @ otherloc
106 return newmat
109 def rotcopy(item, mat):
110 """Copy rotation to item from matrix mat depending on item.rotation_mode"""
111 if item.rotation_mode == 'QUATERNION':
112 item.rotation_quaternion = mat.to_3x3().to_quaternion()
113 elif item.rotation_mode == 'AXIS_ANGLE':
114 rot = mat.to_3x3().to_quaternion().to_axis_angle() # returns (Vector((x, y, z)), w)
115 axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2] # convert to w, x, y, z
116 item.rotation_axis_angle = axis_angle
117 else:
118 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
121 def pLoopExec(self, context, funk):
122 """Loop over selected bones and execute funk on them"""
123 active = context.active_pose_bone
124 selected = context.selected_pose_bones
125 selected.remove(active)
126 for bone in selected:
127 funk(bone, active, context)
130 # The following functions are used to copy attributes from active to bone
132 def pLocLocExec(bone, active, context):
133 bone.location = active.location
136 def pLocRotExec(bone, active, context):
137 rotcopy(bone, active.matrix_basis.to_3x3())
140 def pLocScaExec(bone, active, context):
141 bone.scale = active.scale
144 def pVisLocExec(bone, active, context):
145 bone.location = getmat(bone, active, context, False).to_translation()
148 def pVisRotExec(bone, active, context):
149 obj_bone = bone.id_data
150 rotcopy(bone, getmat(bone, active,
151 context, not obj_bone.data.bones[bone.name].use_inherit_rotation))
154 def pVisScaExec(bone, active, context):
155 obj_bone = bone.id_data
156 bone.scale = getmat(
157 bone, active, context,
158 obj_bone.data.bones[bone.name].inherit_scale not in {'NONE', 'NONE_LEGACY'}
159 ).to_scale()
162 def pDrwExec(bone, active, context):
163 bone.custom_shape = active.custom_shape
164 bone.use_custom_shape_bone_size = active.use_custom_shape_bone_size
165 bone.custom_shape_translation = active.custom_shape_translation
166 bone.custom_shape_rotation_euler = active.custom_shape_rotation_euler
167 bone.custom_shape_scale_xyz = active.custom_shape_scale_xyz
168 bone.bone.show_wire = active.bone.show_wire
171 def pLokExec(bone, active, context):
172 for index, state in enumerate(active.lock_location):
173 bone.lock_location[index] = state
174 for index, state in enumerate(active.lock_rotation):
175 bone.lock_rotation[index] = state
176 bone.lock_rotations_4d = active.lock_rotations_4d
177 bone.lock_rotation_w = active.lock_rotation_w
178 for index, state in enumerate(active.lock_scale):
179 bone.lock_scale[index] = state
182 def pConExec(bone, active, context):
183 for old_constraint in active.constraints.values():
184 new_constraint = bone.constraints.new(old_constraint.type)
185 generic_copy(old_constraint, new_constraint)
188 def pIKsExec(bone, active, context):
189 generic_copy(active, bone, "ik_")
192 def pBBonesExec(bone, active, context):
193 object = active.id_data
194 generic_copy(
195 object.data.bones[active.name],
196 object.data.bones[bone.name],
197 "bbone_")
200 pose_copies = (
201 ('pose_loc_loc', "Local Location",
202 "Copy Location from Active to Selected", pLocLocExec),
203 ('pose_loc_rot', "Local Rotation",
204 "Copy Rotation from Active to Selected", pLocRotExec),
205 ('pose_loc_sca', "Local Scale",
206 "Copy Scale from Active to Selected", pLocScaExec),
207 ('pose_vis_loc', "Visual Location",
208 "Copy Location from Active to Selected", pVisLocExec),
209 ('pose_vis_rot', "Visual Rotation",
210 "Copy Rotation from Active to Selected", pVisRotExec),
211 ('pose_vis_sca', "Visual Scale",
212 "Copy Scale from Active to Selected", pVisScaExec),
213 ('pose_drw', "Bone Shape",
214 "Copy Bone Shape from Active to Selected", pDrwExec),
215 ('pose_lok', "Protected Transform",
216 "Copy Protected Transforms from Active to Selected", pLokExec),
217 ('pose_con', "Bone Constraints",
218 "Copy Object Constraints from Active to Selected", pConExec),
219 ('pose_iks', "IK Limits",
220 "Copy IK Limits from Active to Selected", pIKsExec),
221 ('bbone_settings', "BBone Settings",
222 "Copy BBone Settings from Active to Selected", pBBonesExec),
225 @classmethod
226 def pose_poll_func(cls, context):
227 return(context.mode == 'POSE')
230 def pose_invoke_func(self, context, event):
231 wm = context.window_manager
232 wm.invoke_props_dialog(self)
233 return {'RUNNING_MODAL'}
236 CustomPropSelectionBoolsProperty = BoolVectorProperty(
237 size=32,
238 options={'SKIP_SAVE'}
241 class CopySelection:
242 """Base class for copying properties from active to selected based on a selection."""
244 selection: CustomPropSelectionBoolsProperty
246 def draw_bools(self, button_names):
247 """Draws the boolean toggle list with a list of strings for the button texts."""
248 layout = self.layout
249 for idx, name in enumerate(button_names):
250 layout.prop(self, "selection", index=idx, text=name,
251 toggle=True)
253 def copy_custom_property(source, destination, prop_name):
254 """Copy a custom property called prop_name, from source to destination.
255 source and destination must be a Blender data type that can hold custom properties.
256 For a list of such data types, see:
257 https://docs.blender.org/manual/en/latest/files/data_blocks.html#files-data-blocks-custom-properties
260 # Create the property.
261 destination[prop_name] = source[prop_name]
262 # Copy the settings of the property.
263 try:
264 dst_prop_manager = destination.id_properties_ui(prop_name)
265 except TypeError:
266 # Python values like lists or dictionaries don't have any settings to copy.
267 # They just consist of a value and nothing else.
268 return
270 src_prop_manager = source.id_properties_ui(prop_name)
271 assert src_prop_manager, f'Property "{prop_name}" not found in {source}'
273 dst_prop_manager.update_from(src_prop_manager)
275 # Copy the Library Overridable flag, which is stored elsewhere.
276 prop_rna_path = f'["{prop_name}"]'
277 is_lib_overridable = source.is_property_overridable_library(prop_rna_path)
278 destination.property_overridable_library_set(prop_rna_path, is_lib_overridable)
280 class CopyCustomProperties(CopySelection):
281 """Base class for copying a selection of custom properties."""
283 def copy_selected_custom_props(self, active, selected):
284 keys = list(active.keys())
285 for item in selected:
286 if item == active:
287 continue
288 for index, is_selected in enumerate(self.selection):
289 if is_selected:
290 copy_custom_property(active, item, keys[index])
292 class CopySelectedBoneCustomProperties(CopyCustomProperties, Operator):
293 """Copy Chosen custom properties from active to selected"""
294 bl_idname = "pose.copy_selected_custom_props"
295 bl_label = "Copy Selected Custom Properties"
296 bl_options = {'REGISTER', 'UNDO'}
298 poll = pose_poll_func
299 invoke = pose_invoke_func
301 def draw(self, context):
302 self.draw_bools(context.active_pose_bone.keys())
304 def execute(self, context):
305 self.copy_selected_custom_props(context.active_pose_bone, context.selected_pose_bones)
306 return {'FINISHED'}
309 class CopySelectedPoseConstraints(Operator):
310 """Copy Chosen constraints from active to selected"""
311 bl_idname = "pose.copy_selected_constraints"
312 bl_label = "Copy Selected Constraints"
314 selection: BoolVectorProperty(
315 size=32,
316 options={'SKIP_SAVE'}
319 poll = pose_poll_func
320 invoke = pose_invoke_func
322 def draw(self, context):
323 layout = self.layout
324 for idx, const in enumerate(context.active_pose_bone.constraints):
325 layout.prop(self, "selection", index=idx, text=const.name,
326 toggle=True)
328 def execute(self, context):
329 active = context.active_pose_bone
330 selected = context.selected_pose_bones[:]
331 selected.remove(active)
332 for bone in selected:
333 for index, flag in enumerate(self.selection):
334 if flag:
335 bone.constraints.copy(active.constraints[index])
336 return {'FINISHED'}
339 pose_ops = [] # list of pose mode copy operators
340 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
343 class VIEW3D_MT_posecopypopup(Menu):
344 bl_label = "Copy Attributes"
346 def draw(self, context):
347 layout = self.layout
348 layout.operator_context = 'INVOKE_REGION_WIN'
349 for op in pose_copies:
350 layout.operator("pose.copy_" + op[0])
351 layout.operator("pose.copy_selected_constraints")
352 layout.operator("pose.copy_selected_custom_props")
353 layout.operator("pose.copy", text="copy pose")
356 def obLoopExec(self, context, funk):
357 """Loop over selected objects and execute funk on them"""
358 active = context.active_object
359 selected = context.selected_objects[:]
360 selected.remove(active)
361 for obj in selected:
362 msg = funk(obj, active, context)
363 if msg:
364 self.report({msg[0]}, INFO_MESSAGE + msg[1])
367 def world_to_basis(active, ob, context):
368 """put world coords of active as basis coords of ob"""
369 local = ob.parent.matrix_world.inverted() @ active.matrix_world
370 P = ob.matrix_basis @ ob.matrix_local.inverted()
371 mat = P @ local
372 return(mat)
375 # The following functions are used to copy attributes from
376 # active to selected object
378 def obLoc(ob, active, context):
379 ob.location = active.location
382 def obRot(ob, active, context):
383 rotcopy(ob, active.matrix_local.to_3x3())
386 def obSca(ob, active, context):
387 ob.scale = active.scale
390 def obVisLoc(ob, active, context):
391 if ob.parent:
392 mat = world_to_basis(active, ob, context)
393 ob.location = mat.to_translation()
394 else:
395 ob.location = active.matrix_world.to_translation()
396 return('INFO', "Object location copied")
399 def obVisRot(ob, active, context):
400 if ob.parent:
401 mat = world_to_basis(active, ob, context)
402 rotcopy(ob, mat.to_3x3())
403 else:
404 rotcopy(ob, active.matrix_world.to_3x3())
405 return('INFO', "Object rotation copied")
408 def obVisSca(ob, active, context):
409 if ob.parent:
410 mat = world_to_basis(active, ob, context)
411 ob.scale = mat.to_scale()
412 else:
413 ob.scale = active.matrix_world.to_scale()
414 return('INFO', "Object scale copied")
417 def obDrw(ob, active, context):
418 ob.display_type = active.display_type
419 ob.show_axis = active.show_axis
420 ob.show_bounds = active.show_bounds
421 ob.display_bounds_type = active.display_bounds_type
422 ob.show_name = active.show_name
423 ob.show_texture_space = active.show_texture_space
424 ob.show_transparent = active.show_transparent
425 ob.show_wire = active.show_wire
426 ob.show_in_front = active.show_in_front
427 ob.empty_display_type = active.empty_display_type
428 ob.empty_display_size = active.empty_display_size
431 def obDup(ob, active, context):
432 generic_copy(active, ob, "instance_type")
433 return('INFO', "Duplication method copied")
436 def obCol(ob, active, context):
437 ob.color = active.color
440 def obLok(ob, active, context):
441 for index, state in enumerate(active.lock_location):
442 ob.lock_location[index] = state
443 for index, state in enumerate(active.lock_rotation):
444 ob.lock_rotation[index] = state
445 ob.lock_rotations_4d = active.lock_rotations_4d
446 ob.lock_rotation_w = active.lock_rotation_w
447 for index, state in enumerate(active.lock_scale):
448 ob.lock_scale[index] = state
449 return('INFO', "Transform locks copied")
452 def obCon(ob, active, context):
453 # for consistency with 2.49, delete old constraints first
454 for removeconst in ob.constraints:
455 ob.constraints.remove(removeconst)
456 for old_constraint in active.constraints.values():
457 new_constraint = ob.constraints.new(old_constraint.type)
458 generic_copy(old_constraint, new_constraint)
459 return('INFO', "Constraints copied")
462 def obTex(ob, active, context):
463 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
464 active.data):
465 ob.data.texspace_location[:] = active.data.texspace_location[:]
466 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
467 ob.data.texspace_size[:] = active.data.texspace_size[:]
468 return('INFO', "Texture space copied")
471 def obIdx(ob, active, context):
472 ob.pass_index = active.pass_index
473 return('INFO', "Pass index copied")
476 def obMod(ob, active, context):
477 for modifier in ob.modifiers:
478 # remove existing before adding new:
479 ob.modifiers.remove(modifier)
480 for old_modifier in active.modifiers.values():
481 new_modifier = ob.modifiers.new(name=old_modifier.name,
482 type=old_modifier.type)
483 generic_copy(old_modifier, new_modifier)
484 return('INFO', "Modifiers copied")
487 def obCollections(ob, active, context):
488 for collection in bpy.data.collections:
489 if active.name in collection.objects and ob.name not in collection.objects:
490 collection.objects.link(ob)
491 return('INFO', "Collections copied")
494 def obWei(ob, active, context):
495 # sanity check: are source and target both mesh objects?
496 if ob.type != 'MESH' or active.type != 'MESH':
497 return('ERROR', "objects have to be of mesh type, doing nothing")
498 me_source = active.data
499 me_target = ob.data
500 # sanity check: do source and target have the same amount of verts?
501 if len(me_source.vertices) != len(me_target.vertices):
502 return('ERROR', "objects have different vertex counts, doing nothing")
503 vgroups_IndexName = {}
504 for i in range(0, len(active.vertex_groups)):
505 groups = active.vertex_groups[i]
506 vgroups_IndexName[groups.index] = groups.name
507 data = {} # vert_indices, [(vgroup_index, weights)]
508 for v in me_source.vertices:
509 vg = v.groups
510 vi = v.index
511 if len(vg) > 0:
512 vgroup_collect = []
513 for i in range(0, len(vg)):
514 vgroup_collect.append((vg[i].group, vg[i].weight))
515 data[vi] = vgroup_collect
516 # write data to target
517 if ob != active:
518 # add missing vertex groups
519 for vgroup_name in vgroups_IndexName.values():
520 # check if group already exists...
521 already_present = 0
522 for i in range(0, len(ob.vertex_groups)):
523 if ob.vertex_groups[i].name == vgroup_name:
524 already_present = 1
525 # ... if not, then add
526 if already_present == 0:
527 ob.vertex_groups.new(name=vgroup_name)
528 # write weights
529 for v in me_target.vertices:
530 for vi_source, vgroupIndex_weight in data.items():
531 if v.index == vi_source:
533 for i in range(0, len(vgroupIndex_weight)):
534 groupName = vgroups_IndexName[vgroupIndex_weight[i][0]]
535 groups = ob.vertex_groups
536 for vgs in range(0, len(groups)):
537 if groups[vgs].name == groupName:
538 groups[vgs].add((v.index,),
539 vgroupIndex_weight[i][1], "REPLACE")
540 return('INFO', "Weights copied")
543 object_copies = (
544 # ('obj_loc', "Location",
545 # "Copy Location from Active to Selected", obLoc),
546 # ('obj_rot', "Rotation",
547 # "Copy Rotation from Active to Selected", obRot),
548 # ('obj_sca', "Scale",
549 # "Copy Scale from Active to Selected", obSca),
550 ('obj_vis_loc', "Location",
551 "Copy Location from Active to Selected", obVisLoc),
552 ('obj_vis_rot', "Rotation",
553 "Copy Rotation from Active to Selected", obVisRot),
554 ('obj_vis_sca', "Scale",
555 "Copy Scale from Active to Selected", obVisSca),
556 ('obj_drw', "Draw Options",
557 "Copy Draw Options from Active to Selected", obDrw),
558 ('obj_dup', "Instancing",
559 "Copy instancing properties from Active to Selected", obDup),
560 ('obj_col', "Object Color",
561 "Copy Object Color from Active to Selected", obCol),
562 # ('obj_dmp', "Damping",
563 # "Copy Damping from Active to Selected"),
564 # ('obj_all', "All Physical Attributes",
565 # "Copy Physical Attributes from Active to Selected"),
566 # ('obj_prp', "Properties",
567 # "Copy Properties from Active to Selected"),
568 ('obj_lok', "Protected Transform",
569 "Copy Protected Transforms from Active to Selected", obLok),
570 ('obj_con', "Object Constraints",
571 "Copy Object Constraints from Active to Selected", obCon),
572 # ('obj_nla', "NLA Strips",
573 # "Copy NLA Strips from Active to Selected"),
574 # ('obj_tex', "Texture Space",
575 # "Copy Texture Space from Active to Selected", obTex),
576 # ('obj_sub', "Subdivision Surface Settings",
577 # "Copy Subdivision Surface Settings from Active to Selected"),
578 # ('obj_smo', "AutoSmooth",
579 # "Copy AutoSmooth from Active to Selected"),
580 ('obj_idx', "Pass Index",
581 "Copy Pass Index from Active to Selected", obIdx),
582 ('obj_mod', "Modifiers",
583 "Copy Modifiers from Active to Selected", obMod),
584 ('obj_wei', "Vertex Weights",
585 "Copy vertex weights based on indices", obWei),
586 ('obj_grp', "Collection Links",
587 "Copy selected into active object's collection", obCollections)
591 @classmethod
592 def object_poll_func(cls, context):
593 return (len(context.selected_objects) > 1)
596 def object_invoke_func(self, context, event):
597 wm = context.window_manager
598 wm.invoke_props_dialog(self)
599 return {'RUNNING_MODAL'}
602 class CopySelectedObjectConstraints(Operator):
603 """Copy Chosen constraints from active to selected"""
604 bl_idname = "object.copy_selected_constraints"
605 bl_label = "Copy Selected Constraints"
607 selection: BoolVectorProperty(
608 size=32,
609 options={'SKIP_SAVE'}
612 poll = object_poll_func
613 invoke = object_invoke_func
615 def draw(self, context):
616 layout = self.layout
617 for idx, const in enumerate(context.active_object.constraints):
618 layout.prop(self, "selection", index=idx, text=const.name,
619 toggle=True)
621 def execute(self, context):
622 active = context.active_object
623 selected = context.selected_objects[:]
624 selected.remove(active)
625 for obj in selected:
626 for index, flag in enumerate(self.selection):
627 if flag:
628 obj.constraints.copy(active.constraints[index])
629 return{'FINISHED'}
632 class CopySelectedObjectModifiers(Operator):
633 """Copy Chosen modifiers from active to selected"""
634 bl_idname = "object.copy_selected_modifiers"
635 bl_label = "Copy Selected Modifiers"
637 selection: BoolVectorProperty(
638 size=32,
639 options={'SKIP_SAVE'}
642 poll = object_poll_func
643 invoke = object_invoke_func
645 def draw(self, context):
646 layout = self.layout
647 for idx, const in enumerate(context.active_object.modifiers):
648 layout.prop(self, 'selection', index=idx, text=const.name,
649 toggle=True)
651 def execute(self, context):
652 active = context.active_object
653 selected = context.selected_objects[:]
654 selected.remove(active)
655 for obj in selected:
656 for index, flag in enumerate(self.selection):
657 if flag:
658 old_modifier = active.modifiers[index]
659 new_modifier = obj.modifiers.new(
660 type=active.modifiers[index].type,
661 name=active.modifiers[index].name
663 generic_copy(old_modifier, new_modifier)
664 return{'FINISHED'}
667 class CopySelectedObjectCustomProperties(CopyCustomProperties, Operator):
668 """Copy Chosen custom properties from active to selected objects"""
669 bl_idname = "object.copy_selected_custom_props"
670 bl_label = "Copy Selected Custom Properties"
671 bl_options = {'REGISTER', 'UNDO'}
673 poll = object_poll_func
674 invoke = object_invoke_func
676 def draw(self, context):
677 self.draw_bools(context.object.keys())
679 def execute(self, context):
680 self.copy_selected_custom_props(context.object, context.selected_objects)
681 return {'FINISHED'}
683 object_ops = []
684 genops(object_copies, object_ops, "object.copy_", object_poll_func, obLoopExec)
687 class VIEW3D_MT_copypopup(Menu):
688 bl_label = "Copy Attributes"
690 def draw(self, context):
691 layout = self.layout
693 layout.operator_context = 'INVOKE_REGION_WIN'
694 layout.operator("view3d.copybuffer", icon="COPY_ID")
696 if (len(context.selected_objects) <= 1):
697 layout.separator()
698 layout.label(text="Please select at least two objects", icon="INFO")
699 layout.separator()
701 for entry, op in enumerate(object_copies):
702 if entry and entry % 4 == 0:
703 layout.separator()
704 layout.operator("object.copy_" + op[0])
705 layout.operator("object.copy_selected_constraints")
706 layout.operator("object.copy_selected_modifiers")
707 layout.operator("object.copy_selected_custom_props")
710 # Begin Mesh copy settings:
712 class MESH_MT_CopyFaceSettings(Menu):
713 bl_label = "Copy Face Settings"
715 @classmethod
716 def poll(cls, context):
717 return context.mode == 'EDIT_MESH'
719 def draw(self, context):
720 mesh = context.object.data
721 uv = len(mesh.uv_layers) > 1
722 vc = len(mesh.vertex_colors) > 1
724 layout = self.layout
726 op = layout.operator("mesh.copy_face_settings", text="Copy Material")
727 op['layer'] = ''
728 op['mode'] = 'MAT'
730 if mesh.uv_layers.active:
731 op = layout.operator("mesh.copy_face_settings", text="Copy Active UV Coords")
732 op['layer'] = ''
733 op['mode'] = 'UV'
735 if mesh.vertex_colors.active:
736 op = layout.operator("mesh.copy_face_settings", text="Copy Active Vertex Colors")
737 op['layer'] = ''
738 op['mode'] = 'VCOL'
740 if uv or vc:
741 layout.separator()
742 if uv:
743 layout.menu("MESH_MT_CopyUVCoordsFromLayer")
744 if vc:
745 layout.menu("MESH_MT_CopyVertexColorsFromLayer")
748 # Data (UV map, Image and Vertex color) menus calling MESH_OT_CopyFaceSettings
749 # Explicitly defined as using the generator code was broken in case of Menus
750 # causing issues with access and registration
753 class MESH_MT_CopyUVCoordsFromLayer(Menu):
754 bl_label = "Copy UV Coordinates from Layer"
756 @classmethod
757 def poll(cls, context):
758 obj = context.active_object
759 return obj and obj.mode == "EDIT_MESH" and len(
760 obj.data.uv_layers) > 1
762 def draw(self, context):
763 mesh = context.active_object.data
764 _buildmenu(self, mesh, 'UV', "GROUP_UVS")
767 class MESH_MT_CopyVertexColorsFromLayer(Menu):
768 bl_label = "Copy Vertex Colors from Layer"
770 @classmethod
771 def poll(cls, context):
772 obj = context.active_object
773 return obj and obj.mode == "EDIT_MESH" and len(
774 obj.data.vertex_colors) > 1
776 def draw(self, context):
777 mesh = context.active_object.data
778 _buildmenu(self, mesh, 'VCOL', "GROUP_VCOL")
781 def _buildmenu(self, mesh, mode, icon):
782 layout = self.layout
783 if mode == 'VCOL':
784 layers = mesh.vertex_colors
785 else:
786 layers = mesh.uv_layers
787 for layer in layers:
788 if not layer.active:
789 op = layout.operator("mesh.copy_face_settings",
790 text=layer.name, icon=icon)
791 op['layer'] = layer.name
792 op['mode'] = mode
795 class MESH_OT_CopyFaceSettings(Operator):
796 """Copy settings from active face to all selected faces"""
797 bl_idname = 'mesh.copy_face_settings'
798 bl_label = "Copy Face Settings"
799 bl_options = {'REGISTER', 'UNDO'}
801 mode: StringProperty(
802 name="Mode",
803 options={"HIDDEN"},
805 layer: StringProperty(
806 name="Layer",
807 options={"HIDDEN"},
810 @classmethod
811 def poll(cls, context):
812 return context.mode == 'EDIT_MESH'
814 def execute(self, context):
815 mode = getattr(self, 'mode', '')
816 if mode not in {'MAT', 'VCOL', 'UV'}:
817 self.report({'ERROR'}, "No mode specified or invalid mode")
818 return self._end(context, {'CANCELLED'})
819 layername = getattr(self, 'layer', '')
820 mesh = context.object.data
822 # Switching out of edit mode updates the selected state of faces and
823 # makes the data from the uv texture and vertex color layers available.
824 bpy.ops.object.editmode_toggle()
826 polys = mesh.polygons
827 if mode == 'MAT':
828 to_data = from_data = polys
829 else:
830 if mode == 'VCOL':
831 layers = mesh.vertex_colors
832 act_layer = mesh.vertex_colors.active
833 elif mode == 'UV':
834 layers = mesh.uv_layers
835 act_layer = mesh.uv_layers.active
836 if not layers or (layername and layername not in layers):
837 self.report({'ERROR'}, "Invalid UV or color layer. Operation Cancelled")
838 return self._end(context, {'CANCELLED'})
839 from_data = layers[layername or act_layer.name].data
840 to_data = act_layer.data
841 from_index = polys.active
843 for f in polys:
844 if f.select:
845 if to_data != from_data:
846 # Copying from another layer.
847 # from_face is to_face's counterpart from other layer.
848 from_index = f.index
849 elif f.index == from_index:
850 # Otherwise skip copying a face to itself.
851 continue
852 if mode == 'MAT':
853 f.material_index = polys[from_index].material_index
854 continue
855 if len(f.loop_indices) != len(polys[from_index].loop_indices):
856 self.report({'WARNING'}, "Different number of vertices.")
857 for i in range(len(f.loop_indices)):
858 to_vertex = f.loop_indices[i]
859 from_vertex = polys[from_index].loop_indices[i]
860 if mode == 'VCOL':
861 to_data[to_vertex].color = from_data[from_vertex].color
862 elif mode == 'UV':
863 to_data[to_vertex].uv = from_data[from_vertex].uv
865 return self._end(context, {'FINISHED'})
867 def _end(self, context, retval):
868 if context.mode != 'EDIT_MESH':
869 # Clean up by returning to edit mode like it was before.
870 bpy.ops.object.editmode_toggle()
871 return(retval)
874 classes = (
875 CopySelectedPoseConstraints,
876 CopySelectedBoneCustomProperties,
877 VIEW3D_MT_posecopypopup,
878 CopySelectedObjectConstraints,
879 CopySelectedObjectModifiers,
880 CopySelectedObjectCustomProperties,
881 VIEW3D_MT_copypopup,
882 MESH_MT_CopyFaceSettings,
883 MESH_MT_CopyUVCoordsFromLayer,
884 MESH_MT_CopyVertexColorsFromLayer,
885 MESH_OT_CopyFaceSettings,
886 *pose_ops,
887 *object_ops,
890 def register():
891 from bpy.utils import register_class
892 for cls in classes:
893 register_class(cls)
895 # mostly to get the keymap working
896 kc = bpy.context.window_manager.keyconfigs.addon
897 if kc:
898 km = kc.keymaps.new(name="Object Mode")
899 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
900 kmi.properties.name = 'VIEW3D_MT_copypopup'
902 km = kc.keymaps.new(name="Pose")
903 kmi = km.keymap_items.get("pose.copy")
904 if kmi is not None:
905 kmi.idname = 'wm.call_menu'
906 else:
907 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
908 kmi.properties.name = 'VIEW3D_MT_posecopypopup'
910 km = kc.keymaps.new(name="Mesh")
911 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS')
912 kmi.ctrl = True
913 kmi.properties.name = 'MESH_MT_CopyFaceSettings'
916 def unregister():
917 # mostly to remove the keymap
918 kc = bpy.context.window_manager.keyconfigs.addon
919 if kc:
920 kms = kc.keymaps.get('Pose')
921 if kms is not None:
922 for item in kms.keymap_items:
923 if item.name == 'Call Menu' and item.idname == 'wm.call_menu' and \
924 item.properties.name == 'VIEW3D_MT_posecopypopup':
925 item.idname = 'pose.copy'
926 break
928 km = kc.keymaps.get('Mesh')
929 if km is not None:
930 for kmi in km.keymap_items:
931 if kmi.idname == 'wm.call_menu':
932 if kmi.properties.name == 'MESH_MT_CopyFaceSettings':
933 km.keymap_items.remove(kmi)
935 km = kc.keymaps.get('Object Mode')
936 if km is not None:
937 for kmi in km.keymap_items:
938 if kmi.idname == 'wm.call_menu':
939 if kmi.properties.name == 'VIEW3D_MT_copypopup':
940 km.keymap_items.remove(kmi)
942 from bpy.utils import unregister_class
943 for cls in classes:
944 unregister_class(cls)
947 if __name__ == "__main__":
948 register()