From c051bc843fc1ab60efb4507efb741c754568e208 Mon Sep 17 00:00:00 2001 From: Kristian <57712777+NMC-TBone@users.noreply.github.com> Date: Mon, 9 Dec 2024 23:58:37 +0100 Subject: [PATCH] feat(material tools): rename operator and enhance functionality to remove unused material slots --- .../tools/material_tools.py | 31 +++++++++++-------- i3d_exporter_additionals/ui.py | 2 +- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/i3d_exporter_additionals/tools/material_tools.py b/i3d_exporter_additionals/tools/material_tools.py index 73ab9cb..28097a6 100644 --- a/i3d_exporter_additionals/tools/material_tools.py +++ b/i3d_exporter_additionals/tools/material_tools.py @@ -102,22 +102,27 @@ def execute(self, context: bpy.types.Context): return {'FINISHED'} -class I3DEA_OT_remove_duplicate_material(bpy.types.Operator): - bl_idname = "i3dea.remove_duplicate_material" - bl_label = "Remove Duplicate Materials" - bl_description = "Removes all duplicated/not assigned materials" +class I3DEA_OT_remove_unused_material_slots(bpy.types.Operator): + bl_idname = "i3dea.remove_unused_material_slots" + bl_label = "Remove Unused Material Slots" + bl_description = "Removes duplicate materials and unused material slots" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): - bpy.ops.object.mode_set(mode='OBJECT') - for ob in bpy.context.scene.objects: - if not ob.material_slots: + for obj in context.scene.objects: + if obj.type != 'MESH' and not obj.material_slots: continue - bpy.ops.object.material_slot_remove_unused() - for mat in bpy.data.materials: - if not mat.users: - bpy.data.materials.remove(mat) - bpy.ops.outliner.orphans_purge() + + mesh: bpy.types.Mesh = obj.data + + used_material_indices = set(poly.material_index for poly in mesh.polygons) + used_materials = [mesh.materials[i] for i in used_material_indices if mesh.materials[i] is not None] + + mesh.materials.clear() + + for mat in used_materials: + mesh.materials.append(mat) + self.report({'INFO'}, "Unused material slots & Orphan Data removed") return {'FINISHED'} @@ -257,7 +262,7 @@ def execute(self, context): classes = ( I3DEA_OT_mirror_material, - I3DEA_OT_remove_duplicate_material, + I3DEA_OT_remove_unused_material_slots, I3DEA_OT_setup_material, I3DEA_OT_i3dio_material, ) diff --git a/i3d_exporter_additionals/ui.py b/i3d_exporter_additionals/ui.py index 3a1bab2..26eff94 100644 --- a/i3d_exporter_additionals/ui.py +++ b/i3d_exporter_additionals/ui.py @@ -186,7 +186,7 @@ def draw(self, context): box_col.label(text="Material operators") box_row = box_col.row(align=True) box_row.operator("i3dea.mirror_material", text="Add Mirror Material") - box_row.operator("i3dea.remove_duplicate_material", text="Remove Duplicate Materials") + box_row.operator("i3dea.remove_unused_material_slots") box = layout.box() box_col = box.column(align=True)