align columns (for multi-drag)
[blender-addons.git] / space_view3d_copy_attributes.py
blob289e356aa5bcc6a522f70e0dcc9f27a18a02ef07
1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
19 # <pep8 compliant>
21 bl_info = {
22 "name": "Copy Attributes Menu",
23 "author": "Bassam Kurdali, Fabian Fricke, Adam Wiseman",
24 "version": (0, 4, 7),
25 "blender": (2, 63, 0),
26 "location": "View3D > Ctrl-C",
27 "description": "Copy Attributes Menu from Blender 2.4",
28 "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"
29 "Scripts/3D_interaction/Copy_Attributes_Menu",
30 "category": "3D View",
33 import bpy
34 from mathutils import Matrix
37 def build_exec(loopfunc, func):
38 """Generator function that returns exec functions for operators """
40 def exec_func(self, context):
41 loopfunc(self, context, func)
42 return {'FINISHED'}
43 return exec_func
46 def build_invoke(loopfunc, func):
47 """Generator function that returns invoke functions for operators"""
49 def invoke_func(self, context, event):
50 loopfunc(self, context, func)
51 return {'FINISHED'}
52 return invoke_func
55 def build_op(idname, label, description, fpoll, fexec, finvoke):
56 """Generator function that returns the basic operator"""
58 class myopic(bpy.types.Operator):
59 bl_idname = idname
60 bl_label = label
61 bl_description = description
62 execute = fexec
63 poll = fpoll
64 invoke = finvoke
65 return myopic
68 def genops(copylist, oplist, prefix, poll_func, loopfunc):
69 """Generate ops from the copy list and its associated functions """
70 for op in copylist:
71 exec_func = build_exec(loopfunc, op[3])
72 invoke_func = build_invoke(loopfunc, op[3])
73 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
74 poll_func, exec_func, invoke_func)
75 oplist.append(opclass)
78 def generic_copy(source, target, string=""):
79 """ copy attributes from source to target that have string in them """
80 for attr in dir(source):
81 if attr.find(string) > -1:
82 try:
83 setattr(target, attr, getattr(source, attr))
84 except:
85 pass
86 return
89 def getmat(bone, active, context, ignoreparent):
90 """Helper function for visual transform copy,
91 gets the active transform in bone space
92 """
93 obj_act = context.active_object
94 data_bone = obj_act.data.bones[bone.name]
95 #all matrices are in armature space unless commented otherwise
96 otherloc = active.matrix # final 4x4 mat of target, location.
97 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
98 if data_bone.parent:
99 parentposemat = obj_act.pose.bones[data_bone.parent.name].matrix.copy()
100 parentbonemat = data_bone.parent.matrix_local.copy()
101 else:
102 parentposemat = parentbonemat = Matrix()
103 if parentbonemat == parentposemat or ignoreparent:
104 newmat = bonemat_local.inverted() * otherloc
105 else:
106 bonemat = parentbonemat.inverted() * bonemat_local
108 newmat = bonemat.inverted() * parentposemat.inverted() * otherloc
109 return newmat
112 def rotcopy(item, mat):
113 """copy rotation to item from matrix mat depending on item.rotation_mode"""
114 if item.rotation_mode == 'QUATERNION':
115 item.rotation_quaternion = mat.to_3x3().to_quaternion()
116 elif item.rotation_mode == 'AXIS_ANGLE':
117 quat = mat.to_3x3().to_quaternion()
118 item.rotation_axis_angle = quat.axis[:] + (quat.angle, )
119 else:
120 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
123 def pLoopExec(self, context, funk):
124 """Loop over selected bones and execute funk on them"""
125 active = context.active_pose_bone
126 selected = context.selected_pose_bones
127 selected.remove(active)
128 for bone in selected:
129 funk(bone, active, context)
131 #The following functions are used o copy attributes frome active to bone
134 def pLocLocExec(bone, active, context):
135 bone.location = active.location
138 def pLocRotExec(bone, active, context):
139 rotcopy(bone, active.matrix_basis.to_3x3())
142 def pLocScaExec(bone, active, context):
143 bone.scale = active.scale
146 def pVisLocExec(bone, active, context):
147 bone.location = getmat(bone, active, context, False).to_translation()
150 def pVisRotExec(bone, active, context):
151 rotcopy(bone, getmat(bone, active,
152 context, not context.active_object.data.bones[bone.name].use_inherit_rotation))
155 def pVisScaExec(bone, active, context):
156 bone.scale = getmat(bone, active, context,
157 not context.active_object.data.bones[bone.name].use_inherit_scale)\
158 .to_scale()
161 def pDrwExec(bone, active, context):
162 bone.custom_shape = active.custom_shape
165 def pLokExec(bone, active, context):
166 for index, state in enumerate(active.lock_location):
167 bone.lock_location[index] = state
168 for index, state in enumerate(active.lock_rotation):
169 bone.lock_rotation[index] = state
170 bone.lock_rotations_4d = active.lock_rotations_4d
171 bone.lock_rotation_w = active.lock_rotation_w
172 for index, state in enumerate(active.lock_scale):
173 bone.lock_scale[index] = state
176 def pConExec(bone, active, context):
177 for old_constraint in active.constraints.values():
178 new_constraint = bone.constraints.new(old_constraint.type)
179 generic_copy(old_constraint, new_constraint)
182 def pIKsExec(bone, active, context):
183 generic_copy(active, bone, "ik_")
186 def pBBonesExec(bone, active, context):
187 object = active.id_data
188 generic_copy(
189 object.data.bones[active.name],
190 object.data.bones[bone.name],
191 "bbone_")
193 pose_copies = (('pose_loc_loc', "Local Location",
194 "Copy Location from Active to Selected", pLocLocExec),
195 ('pose_loc_rot', "Local Rotation",
196 "Copy Rotation from Active to Selected", pLocRotExec),
197 ('pose_loc_sca', "Local Scale",
198 "Copy Scale from Active to Selected", pLocScaExec),
199 ('pose_vis_loc', "Visual Location",
200 "Copy Location from Active to Selected", pVisLocExec),
201 ('pose_vis_rot', "Visual Rotation",
202 "Copy Rotation from Active to Selected", pVisRotExec),
203 ('pose_vis_sca', "Visual Scale",
204 "Copy Scale from Active to Selected", pVisScaExec),
205 ('pose_drw', "Bone Shape",
206 "Copy Bone Shape from Active to Selected", pDrwExec),
207 ('pose_lok', "Protected Transform",
208 "Copy Protected Tranforms from Active to Selected", pLokExec),
209 ('pose_con', "Bone Constraints",
210 "Copy Object Constraints from Active to Selected", pConExec),
211 ('pose_iks', "IK Limits",
212 "Copy IK Limits from Active to Selected", pIKsExec),
213 ('bbone_settings', "BBone Settings",
214 "Copy BBone Settings from Active to Selected", pBBonesExec),)
217 @classmethod
218 def pose_poll_func(cls, context):
219 return(context.mode == 'POSE')
222 def pose_invoke_func(self, context, event):
223 wm = context.window_manager
224 wm.invoke_props_dialog(self)
225 return {'RUNNING_MODAL'}
228 class CopySelectedPoseConstraints(bpy.types.Operator):
229 """Copy Chosen constraints from active to selected"""
230 bl_idname = "pose.copy_selected_constraints"
231 bl_label = "Copy Selected Constraints"
232 selection = bpy.props.BoolVectorProperty(size=32)
234 poll = pose_poll_func
235 invoke = pose_invoke_func
237 def draw(self, context):
238 layout = self.layout
239 for idx, const in enumerate(context.active_pose_bone.constraints):
240 layout.prop(self, "selection", index=idx, text=const.name,
241 toggle=True)
243 def execute(self, context):
244 active = context.active_pose_bone
245 selected = context.selected_pose_bones[:]
246 selected.remove(active)
247 for bone in selected:
248 for index, flag in enumerate(self.selection):
249 if flag:
250 old_constraint = active.constraints[index]
251 new_constraint = bone.constraints.new(\
252 active.constraints[index].type)
253 generic_copy(old_constraint, new_constraint)
254 return {'FINISHED'}
256 pose_ops = [] # list of pose mode copy operators
258 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
261 class VIEW3D_MT_posecopypopup(bpy.types.Menu):
262 bl_label = "Copy Attributes"
264 def draw(self, context):
265 layout = self.layout
266 layout.operator_context = 'INVOKE_REGION_WIN'
267 for op in pose_copies:
268 layout.operator("pose.copy_" + op[0])
269 layout.operator("pose.copy_selected_constraints")
270 layout.operator("pose.copy", text="copy pose")
273 def obLoopExec(self, context, funk):
274 """Loop over selected objects and execute funk on them"""
275 active = context.active_object
276 selected = context.selected_objects[:]
277 selected.remove(active)
278 for obj in selected:
279 msg = funk(obj, active, context)
280 if msg:
281 self.report({msg[0]}, msg[1])
284 def world_to_basis(active, ob, context):
285 """put world coords of active as basis coords of ob"""
286 local = ob.parent.matrix_world.inverted() * active.matrix_world
287 P = ob.matrix_basis * ob.matrix_local.inverted()
288 mat = P * local
289 return(mat)
291 #The following functions are used o copy attributes from
292 #active to selected object
295 def obLoc(ob, active, context):
296 ob.location = active.location
299 def obRot(ob, active, context):
300 rotcopy(ob, active.matrix_local.to_3x3())
303 def obSca(ob, active, context):
304 ob.scale = active.scale
307 def obVisLoc(ob, active, context):
308 if ob.parent:
309 mat = world_to_basis(active, ob, context)
310 ob.location = mat.to_translation()
311 else:
312 ob.location = active.matrix_world.to_translation()
315 def obVisRot(ob, active, context):
316 if ob.parent:
317 mat = world_to_basis(active, ob, context)
318 rotcopy(ob, mat.to_3x3())
319 else:
320 rotcopy(ob, active.matrix_world.to_3x3())
323 def obVisSca(ob, active, context):
324 if ob.parent:
325 mat = world_to_basis(active, ob, context)
326 ob.scale = mat.to_scale()
327 else:
328 ob.scale = active.matrix_world.to_scale()
331 def obDrw(ob, active, context):
332 ob.draw_type = active.draw_type
333 ob.show_axis = active.show_axis
334 ob.show_bounds = active.show_bounds
335 ob.draw_bounds_type = active.draw_bounds_type
336 ob.show_name = active.show_name
337 ob.show_texture_space = active.show_texture_space
338 ob.show_transparent = active.show_transparent
339 ob.show_wire = active.show_wire
340 ob.show_x_ray = active.show_x_ray
341 ob.empty_draw_type = active.empty_draw_type
342 ob.empty_draw_size = active.empty_draw_size
345 def obOfs(ob, active, context):
346 ob.time_offset = active.time_offset
347 return('INFO', "time offset copied")
350 def obDup(ob, active, context):
351 generic_copy(active, ob, "dupli")
352 return('INFO', "duplication method copied")
355 def obCol(ob, active, context):
356 ob.color = active.color
359 def obMas(ob, active, context):
360 ob.game.mass = active.game.mass
361 return('INFO', "mass copied")
364 def obLok(ob, active, context):
365 for index, state in enumerate(active.lock_location):
366 ob.lock_location[index] = state
367 for index, state in enumerate(active.lock_rotation):
368 ob.lock_rotation[index] = state
369 ob.lock_rotations_4d = active.lock_rotations_4d
370 ob.lock_rotation_w = active.lock_rotation_w
371 for index, state in enumerate(active.lock_scale):
372 ob.lock_scale[index] = state
373 return('INFO', "transform locks copied")
376 def obCon(ob, active, context):
377 #for consistency with 2.49, delete old constraints first
378 for removeconst in ob.constraints:
379 ob.constraints.remove(removeconst)
380 for old_constraint in active.constraints.values():
381 new_constraint = ob.constraints.new(old_constraint.type)
382 generic_copy(old_constraint, new_constraint)
383 return('INFO', "constraints copied")
386 def obTex(ob, active, context):
387 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
388 active.data):
389 ob.data.texspace_location[:] = active.data.texspace_location[:]
390 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
391 ob.data.texspace_size[:] = active.data.texspace_size[:]
392 return('INFO', "texture space copied")
395 def obIdx(ob, active, context):
396 ob.pass_index = active.pass_index
397 return('INFO', "pass index copied")
400 def obMod(ob, active, context):
401 for modifier in ob.modifiers:
402 #remove existing before adding new:
403 ob.modifiers.remove(modifier)
404 for old_modifier in active.modifiers.values():
405 new_modifier = ob.modifiers.new(name=old_modifier.name,
406 type=old_modifier.type)
407 generic_copy(old_modifier, new_modifier)
408 return('INFO', "modifiers copied")
411 def obGrp(ob, active, context):
412 for grp in bpy.data.groups:
413 if active.name in grp.objects and ob.name not in grp.objects:
414 grp.objects.link(ob)
415 return('INFO', "groups copied")
418 def obWei(ob, active, context):
419 me_source = active.data
420 me_target = ob.data
421 # sanity check: do source and target have the same amount of verts?
422 if len(me_source.vertices) != len(me_target.vertices):
423 return('ERROR', "objects have different vertex counts, doing nothing")
424 vgroups_IndexName = {}
425 for i in range(0, len(active.vertex_groups)):
426 groups = active.vertex_groups[i]
427 vgroups_IndexName[groups.index] = groups.name
428 data = {} # vert_indices, [(vgroup_index, weights)]
429 for v in me_source.vertices:
430 vg = v.groups
431 vi = v.index
432 if len(vg) > 0:
433 vgroup_collect = []
434 for i in range(0, len(vg)):
435 vgroup_collect.append((vg[i].group, vg[i].weight))
436 data[vi] = vgroup_collect
437 # write data to target
438 if ob != active:
439 # add missing vertex groups
440 for vgroup_name in vgroups_IndexName.values():
441 #check if group already exists...
442 already_present = 0
443 for i in range(0, len(ob.vertex_groups)):
444 if ob.vertex_groups[i].name == vgroup_name:
445 already_present = 1
446 # ... if not, then add
447 if already_present == 0:
448 ob.vertex_groups.new(name=vgroup_name)
449 # write weights
450 for v in me_target.vertices:
451 for vi_source, vgroupIndex_weight in data.items():
452 if v.index == vi_source:
454 for i in range(0, len(vgroupIndex_weight)):
455 groupName = vgroups_IndexName[vgroupIndex_weight[i][0]]
456 groups = ob.vertex_groups
457 for vgs in range(0, len(groups)):
458 if groups[vgs].name == groupName:
459 groups[vgs].add((v.index,),
460 vgroupIndex_weight[i][1], "REPLACE")
461 return('INFO', "weights copied")
463 object_copies = (
464 #('obj_loc', "Location",
465 #"Copy Location from Active to Selected", obLoc),
466 #('obj_rot', "Rotation",
467 #"Copy Rotation from Active to Selected", obRot),
468 #('obj_sca', "Scale",
469 #"Copy Scale from Active to Selected", obSca),
470 ('obj_vis_loc', "Location",
471 "Copy Location from Active to Selected", obVisLoc),
472 ('obj_vis_rot', "Rotation",
473 "Copy Rotation from Active to Selected", obVisRot),
474 ('obj_vis_sca', "Scale",
475 "Copy Scale from Active to Selected", obVisSca),
476 ('obj_drw', "Draw Options",
477 "Copy Draw Options from Active to Selected", obDrw),
478 ('obj_ofs', "Time Offset",
479 "Copy Time Offset from Active to Selected", obOfs),
480 ('obj_dup', "Dupli",
481 "Copy Dupli from Active to Selected", obDup),
482 ('obj_col', "Object Color",
483 "Copy Object Color from Active to Selected", obCol),
484 ('obj_mas', "Mass",
485 "Copy Mass from Active to Selected", obMas),
486 #('obj_dmp', "Damping",
487 #"Copy Damping from Active to Selected"),
488 #('obj_all', "All Physical Attributes",
489 #"Copy Physical Atributes from Active to Selected"),
490 #('obj_prp', "Properties",
491 #"Copy Properties from Active to Selected"),
492 #('obj_log', "Logic Bricks",
493 #"Copy Logic Bricks from Active to Selected"),
494 ('obj_lok', "Protected Transform",
495 "Copy Protected Tranforms from Active to Selected", obLok),
496 ('obj_con', "Object Constraints",
497 "Copy Object Constraints from Active to Selected", obCon),
498 #('obj_nla', "NLA Strips",
499 #"Copy NLA Strips from Active to Selected"),
500 #('obj_tex', "Texture Space",
501 #"Copy Texture Space from Active to Selected", obTex),
502 #('obj_sub', "Subsurf Settings",
503 #"Copy Subsurf Setings from Active to Selected"),
504 #('obj_smo', "AutoSmooth",
505 #"Copy AutoSmooth from Active to Selected"),
506 ('obj_idx', "Pass Index",
507 "Copy Pass Index from Active to Selected", obIdx),
508 ('obj_mod', "Modifiers",
509 "Copy Modifiers from Active to Selected", obMod),
510 ('obj_wei', "Vertex Weights",
511 "Copy vertex weights based on indices", obWei),
512 ('obj_grp', "Group Links",
513 "Copy selected into active object's groups", obGrp))
516 @classmethod
517 def object_poll_func(cls, context):
518 return(len(context.selected_objects) > 1)
521 def object_invoke_func(self, context, event):
522 wm = context.window_manager
523 wm.invoke_props_dialog(self)
524 return {'RUNNING_MODAL'}
527 class CopySelectedObjectConstraints(bpy.types.Operator):
528 """Copy Chosen constraints from active to selected"""
529 bl_idname = "object.copy_selected_constraints"
530 bl_label = "Copy Selected Constraints"
531 selection = bpy.props.BoolVectorProperty(size=32)
533 poll = object_poll_func
535 invoke = object_invoke_func
537 def draw(self, context):
538 layout = self.layout
539 for idx, const in enumerate(context.active_object.constraints):
540 layout.prop(self, "selection", index=idx, text=const.name,
541 toggle=True)
543 def execute(self, context):
544 active = context.active_object
545 selected = context.selected_objects[:]
546 selected.remove(active)
547 for obj in selected:
548 for index, flag in enumerate(self.selection):
549 if flag:
550 old_constraint = active.constraints[index]
551 new_constraint = obj.constraints.new(\
552 active.constraints[index].type)
553 generic_copy(old_constraint, new_constraint)
554 return{'FINISHED'}
557 class CopySelectedObjectModifiers(bpy.types.Operator):
558 """Copy Chosen modifiers from active to selected"""
559 bl_idname = "object.copy_selected_modifiers"
560 bl_label = "Copy Selected Modifiers"
561 selection = bpy.props.BoolVectorProperty(size=32)
563 poll = object_poll_func
565 invoke = object_invoke_func
567 def draw(self, context):
568 layout = self.layout
569 for idx, const in enumerate(context.active_object.modifiers):
570 layout.prop(self, 'selection', index=idx, text=const.name,
571 toggle=True)
573 def execute(self, context):
574 active = context.active_object
575 selected = context.selected_objects[:]
576 selected.remove(active)
577 for obj in selected:
578 for index, flag in enumerate(self.selection):
579 if flag:
580 old_modifier = active.modifiers[index]
581 new_modifier = obj.modifiers.new(\
582 type=active.modifiers[index].type,
583 name=active.modifiers[index].name)
584 generic_copy(old_modifier, new_modifier)
585 return{'FINISHED'}
587 object_ops = []
588 genops(object_copies, object_ops, "object.copy_", object_poll_func, obLoopExec)
591 class VIEW3D_MT_copypopup(bpy.types.Menu):
592 bl_label = "Copy Attributes"
594 def draw(self, context):
595 layout = self.layout
596 layout.operator_context = 'INVOKE_REGION_WIN'
597 for op in object_copies:
598 layout.operator("object.copy_" + op[0])
599 layout.operator("object.copy_selected_constraints")
600 layout.operator("object.copy_selected_modifiers")
602 #Begin Mesh copy settings:
605 class MESH_MT_CopyFaceSettings(bpy.types.Menu):
606 bl_label = "Copy Face Settings"
608 @classmethod
609 def poll(cls, context):
610 return context.mode == 'EDIT_MESH'
612 def draw(self, context):
613 mesh = context.object.data
614 uv = len(mesh.uv_textures) > 1
615 vc = len(mesh.vertex_colors) > 1
616 layout = self.layout
618 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
619 text="Copy Material")
620 op['layer'] = ''
621 op['mode'] = 'MAT'
622 if mesh.uv_textures.active:
623 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
624 text="Copy Image")
625 op['layer'] = ''
626 op['mode'] = 'IMAGE'
627 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
628 text="Copy UV Coords")
629 op['layer'] = ''
630 op['mode'] = 'UV'
631 if mesh.vertex_colors.active:
632 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
633 text="Copy Vertex Colors")
634 op['layer'] = ''
635 op['mode'] = 'VCOL'
636 if uv or vc:
637 layout.separator()
638 if uv:
639 layout.menu("MESH_MT_CopyImagesFromLayer")
640 layout.menu("MESH_MT_CopyUVCoordsFromLayer")
641 if vc:
642 layout.menu("MESH_MT_CopyVertexColorsFromLayer")
645 def _buildmenu(self, mesh, mode):
646 layout = self.layout
647 if mode == 'VCOL':
648 layers = mesh.vertex_colors
649 else:
650 layers = mesh.uv_textures
651 for layer in layers:
652 if not layer.active:
653 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
654 text=layer.name)
655 op['layer'] = layer.name
656 op['mode'] = mode
659 @classmethod
660 def _poll_layer_uvs(cls, context):
661 return context.mode == "EDIT_MESH" and len(
662 context.object.data.uv_layers) > 1
665 @classmethod
666 def _poll_layer_vcols(cls, context):
667 return context.mode == "EDIT_MESH" and len(
668 context.object.data.vertex_colors) > 1
671 def _build_draw(mode):
672 return (lambda self, context: _buildmenu(self, context.object.data, mode))
674 _layer_menu_data = (("UV Coords", _build_draw("UV"), _poll_layer_uvs),
675 ("Images", _build_draw("IMAGE"), _poll_layer_uvs),
676 ("Vertex Colors", _build_draw("VCOL"), _poll_layer_vcols))
677 _layer_menus = []
678 for name, draw_func, poll_func in _layer_menu_data:
679 classname = "MESH_MT_Copy" + "".join(name.split()) + "FromLayer"
680 menuclass = type(classname, (bpy.types.Menu,),
681 dict(bl_label="Copy " + name + " from layer",
682 bl_idname=classname,
683 draw=draw_func,
684 poll=poll_func))
685 _layer_menus.append(menuclass)
688 class MESH_OT_CopyFaceSettings(bpy.types.Operator):
689 """Copy settings from active face to all selected faces"""
690 bl_idname = 'mesh.copy_face_settings'
691 bl_label = "Copy Face Settings"
692 bl_options = {'REGISTER', 'UNDO'}
694 mode = bpy.props.StringProperty(name="mode")
695 layer = bpy.props.StringProperty(name="layer")
697 @classmethod
698 def poll(cls, context):
699 return context.mode == 'EDIT_MESH'
701 def execute(self, context):
702 mode = getattr(self, 'mode', '')
703 if not mode in {'MAT', 'VCOL', 'IMAGE', 'UV'}:
704 self.report({'ERROR'}, "No mode specified or invalid mode.")
705 return self._end(context, {'CANCELLED'})
706 layername = getattr(self, 'layer', '')
707 mesh = context.object.data
709 # Switching out of edit mode updates the selected state of faces and
710 # makes the data from the uv texture and vertex color layers available.
711 bpy.ops.object.editmode_toggle()
713 polys = mesh.polygons
714 if mode == 'MAT':
715 to_data = from_data = polys
716 else:
717 if mode == 'VCOL':
718 layers = mesh.vertex_colors
719 act_layer = mesh.vertex_colors.active
720 elif mode == 'IMAGE':
721 layers = mesh.uv_textures
722 act_layer = mesh.uv_textures.active
723 elif mode == 'UV':
724 layers = mesh.uv_layers
725 act_layer = mesh.uv_layers.active
726 if not layers or (layername and not layername in layers):
727 self.report({'ERROR'}, "Invalid UV or color layer.")
728 return self._end(context, {'CANCELLED'})
729 from_data = layers[layername or act_layer.name].data
730 to_data = act_layer.data
731 from_index = polys.active
733 for f in polys:
734 if f.select:
735 if to_data != from_data:
736 # Copying from another layer.
737 # from_face is to_face's counterpart from other layer.
738 from_index = f.index
739 elif f.index == from_index:
740 # Otherwise skip copying a face to itself.
741 continue
742 if mode == 'MAT':
743 f.material_index = polys[from_index].material_index
744 continue
745 elif mode == 'IMAGE':
746 to_data[f.index].image = from_data[from_index].image
747 continue
748 if len(f.loop_indices) != len(polys[from_index].loop_indices):
749 self.report({'WARNING'}, "Different number of vertices.")
750 for i in range(len(f.loop_indices)):
751 to_vertex = f.loop_indices[i]
752 from_vertex = polys[from_index].loop_indices[i]
753 if mode == 'VCOL':
754 to_data[to_vertex].color = from_data[from_vertex].color
755 elif mode == 'UV':
756 to_data[to_vertex].uv = from_data[from_vertex].uv
758 return self._end(context, {'FINISHED'})
760 def _end(self, context, retval):
761 if context.mode != 'EDIT_MESH':
762 # Clean up by returning to edit mode like it was before.
763 bpy.ops.object.editmode_toggle()
764 return(retval)
767 def register():
768 bpy.utils.register_module(__name__)
770 ''' mostly to get the keymap working '''
771 kc = bpy.context.window_manager.keyconfigs.addon
772 if kc:
773 km = kc.keymaps.new(name="Object Mode")
774 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
775 kmi.properties.name = 'VIEW3D_MT_copypopup'
777 km = kc.keymaps.new(name="Pose")
778 kmi = km.keymap_items.get("pose.copy")
779 if kmi is not None:
780 kmi.idname = 'wm.call_menu'
781 else:
782 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
783 kmi.properties.name = 'VIEW3D_MT_posecopypopup'
784 for menu in _layer_menus:
785 bpy.utils.register_class(menu)
787 km = kc.keymaps.new(name="Mesh")
788 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS')
789 kmi.ctrl = True
790 kmi.properties.name = 'MESH_MT_CopyFaceSettings'
793 def unregister():
794 bpy.utils.unregister_module(__name__)
796 ''' mostly to remove the keymap '''
797 kc = bpy.context.window_manager.keyconfigs.addon
798 if kc:
799 kms = kc.keymaps['Pose']
800 for item in kms.keymap_items:
801 if item.name == 'Call Menu' and item.idname == 'wm.call_menu' and \
802 item.properties.name == 'VIEW3D_MT_posecopypopup':
803 item.idname = 'pose.copy'
804 break
805 for menu in _layer_menus:
806 bpy.utils.unregister_class(menu)
807 km = kc.keymaps['Mesh']
808 for kmi in km.keymap_items:
809 if kmi.idname == 'wm.call_menu':
810 if kmi.properties.name == 'MESH_MT_CopyFaceSettings':
811 km.keymap_items.remove(kmi)
813 km = kc.keymaps['Object Mode']
814 for kmi in km.keymap_items:
815 if kmi.idname == 'wm.call_menu':
816 if kmi.properties.name == 'VIEW3D_MT_copypopup':
817 km.keymap_items.remove(kmi)
819 if __name__ == "__main__":
820 register()