Optimzation Panel Re-Added

- Major Improvements all round, Join Meshes improved, Combined Materials, Remove Doubles Improvements.
This commit is contained in:
Yusarina
2024-12-05 01:13:10 +00:00
parent 9961223548
commit 9cc5a41a98
15 changed files with 755 additions and 9 deletions
View File
View File
+175
View File
@@ -0,0 +1,175 @@
import bpy
import re
from typing import Set, Dict, List, Optional, Tuple
from bpy.types import (
Operator,
Context,
Object,
Material,
NodeTree,
ShaderNodeTexImage
)
from ...core.logging_setup import logger
from ...core.translations import t
from ...core.common import (
get_active_armature,
get_all_meshes,
validate_armature,
clear_unused_data_blocks,
ProgressTracker
)
def textures_match(tex1: ShaderNodeTexImage, tex2: ShaderNodeTexImage) -> bool:
"""Compare two texture nodes for matching properties and image data"""
return tex1.image == tex2.image and tex1.extension == tex2.extension
def consolidate_nodes(node1: ShaderNodeTexImage, node2: ShaderNodeTexImage) -> None:
"""Transfer properties from one texture node to another to ensure consistency"""
node2.color_space = node1.color_space
node2.coordinates = node1.coordinates
def consolidate_textures(node_tree1: NodeTree, node_tree2: NodeTree) -> None:
"""Synchronize texture nodes between two material node trees"""
for node1 in node_tree1.nodes:
if node1.type == 'TEX_IMAGE':
for node2 in node_tree2.nodes:
if (node2.type == 'TEX_IMAGE' and node1.image == node2.image):
consolidate_nodes(node1, node2)
node2.image = node1.image
elif node1.type == 'GROUP':
if node1.node_tree and node2.node_tree:
consolidate_textures(node1.node_tree, node2.node_tree)
def color_match(col1: Tuple[float, ...], col2: Tuple[float, ...], tolerance: float = 0.01) -> bool:
"""Compare two color values within a specified tolerance"""
return all(abs(c1 - c2) < tolerance for c1, c2 in zip(col1, col2))
def materials_match(mat1: Material, mat2: Material, tolerance: float = 0.01) -> bool:
"""Compare two materials for matching properties within tolerance"""
if not color_match(mat1.diffuse_color, mat2.diffuse_color, tolerance):
return False
if abs(mat1.roughness - mat2.roughness) > tolerance:
return False
if abs(mat1.metallic - mat2.metallic) > tolerance:
return False
if abs(mat1.alpha_threshold - mat2.alpha_threshold) > tolerance:
return False
if not color_match(mat1.emission_color, mat2.emission_color, tolerance):
return False
if mat1.node_tree and mat2.node_tree:
consolidate_textures(mat1.node_tree, mat2.node_tree)
return True
def get_base_name(name: str) -> str:
"""Extract the base material name by removing numeric suffixes"""
mat_match = re.match(r"^(.*)\.\d{3}$", name)
return mat_match.group(1) if mat_match else name
class AvatarToolkit_OT_CombineMaterials(Operator):
"""Operator for combining similar materials to reduce duplicate materials"""
bl_idname: str = "avatar_toolkit.combine_materials"
bl_label: str = t("Optimization.combine_materials")
bl_description: str = t("Optimization.combine_materials_desc")
bl_options: Set[str] = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context: Context) -> bool:
"""Check if the operator can be executed"""
armature = get_active_armature(context)
if not armature:
return False
valid, _ = validate_armature(armature)
return valid
def execute(self, context: Context) -> Set[str]:
"""Execute the material combination operation"""
try:
armature = get_active_armature(context)
meshes = get_all_meshes(context)
if not meshes:
self.report({'WARNING'}, t("Optimization.no_meshes"))
return {'CANCELLED'}
if not any(mesh.material_slots for mesh in meshes):
self.report({'WARNING'}, t("Optimization.no_materials"))
return {'CANCELLED'}
with ProgressTracker(context, 4, "Combining Materials") as progress:
try:
num_combined = self.consolidate_materials(meshes)
except Exception as e:
logger.error(f"Material consolidation failed: {str(e)}")
self.report({'ERROR'}, t("Optimization.error.consolidation"))
return {'CANCELLED'}
progress.step("Consolidated materials")
try:
num_cleaned = self.clean_material_slots(meshes)
except Exception as e:
logger.error(f"Material slot cleanup failed: {str(e)}")
self.report({'ERROR'}, t("Optimization.error.slot_cleanup"))
return {'CANCELLED'}
progress.step("Cleaned material slots")
try:
num_removed = clear_unused_data_blocks(self)
except Exception as e:
logger.error(f"Data block cleanup failed: {str(e)}")
self.report({'ERROR'}, t("Optimization.error.data_cleanup"))
return {'CANCELLED'}
progress.step("Removed unused data blocks")
self.report({'INFO'}, t("Optimization.materials_combined",
combined=num_combined,
cleaned=num_cleaned,
removed=num_removed))
return {'FINISHED'}
except Exception as e:
logger.error(f"Failed to combine materials: {str(e)}")
self.report({'ERROR'}, t("Optimization.error.combine_materials", error=str(e)))
return {'CANCELLED'}
def consolidate_materials(self, meshes: List[Object]) -> int:
"""Consolidate similar materials across all meshes"""
mat_mapping: Dict[str, Material] = {}
num_combined: int = 0
for mesh in meshes:
for slot in mesh.material_slots:
mat: Optional[Material] = slot.material
if mat:
base_name: str = get_base_name(mat.name)
if base_name in mat_mapping:
base_mat: Material = mat_mapping[base_name]
try:
if materials_match(base_mat, mat):
consolidate_textures(base_mat.node_tree, mat.node_tree)
num_combined += 1
slot.material = base_mat
except AttributeError:
logger.warning(f"Material attribute mismatch: {mat.name}")
continue
else:
mat_mapping[base_name] = mat
return num_combined
def clean_material_slots(self, meshes: List[Object]) -> int:
"""Remove unused material slots from meshes"""
cleaned_slots = 0
for obj in meshes:
initial_slots = len(obj.material_slots)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.material_slot_remove_unused()
cleaned_slots += initial_slots - len(obj.material_slots)
return cleaned_slots
+103
View File
@@ -0,0 +1,103 @@
import bpy
from typing import Set, List, Tuple, ClassVar
from bpy.types import Operator, Context, Object
from ...core.logging_setup import logger
from ...core.translations import t
from ...core.common import (
get_active_armature,
get_all_meshes,
validate_armature,
validate_meshes,
join_mesh_objects,
ProgressTracker
)
class AvatarToolkit_OT_JoinAllMeshes(Operator):
"""Operator to join all meshes in the scene"""
bl_idname: ClassVar[str] = "avatar_toolkit.join_all_meshes"
bl_label: ClassVar[str] = t("Optimization.join_all_meshes")
bl_description: ClassVar[str] = t("Optimization.join_all_meshes_desc")
bl_options: ClassVar[Set[str]] = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context: Context) -> bool:
armature: Object | None = get_active_armature(context)
if not armature:
return False
valid: bool
valid, _ = validate_armature(armature)
return valid
def execute(self, context: Context) -> Set[str]:
try:
armature: Object = get_active_armature(context)
meshes: List[Object] = get_all_meshes(context)
valid: bool
message: str
valid, message = validate_meshes(meshes)
if not valid:
self.report({'WARNING'}, message)
return {'CANCELLED'}
with ProgressTracker(context, 5, "Joining All Meshes") as progress:
success: bool
success, message = join_mesh_objects(context, meshes, progress)
if success:
context.view_layer.objects.active = armature
self.report({'INFO'}, message)
return {'FINISHED'}
else:
self.report({'ERROR'}, message)
return {'CANCELLED'}
except Exception as e:
logger.error(f"Failed to join meshes: {str(e)}")
self.report({'ERROR'}, t("Optimization.error.join_meshes", error=str(e)))
return {'CANCELLED'}
class AvatarToolkit_OT_JoinSelectedMeshes(Operator):
"""Operator to join selected meshes"""
bl_idname: ClassVar[str] = "avatar_toolkit.join_selected_meshes"
bl_label: ClassVar[str] = t("Optimization.join_selected_meshes")
bl_description: ClassVar[str] = t("Optimization.join_selected_meshes_desc")
bl_options: ClassVar[Set[str]] = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context: Context) -> bool:
armature: Object | None = get_active_armature(context)
if not armature:
return False
valid: bool
valid, _ = validate_armature(armature)
return (valid and
context.mode == 'OBJECT' and
len([obj for obj in context.selected_objects if obj.type == 'MESH']) > 1)
def execute(self, context: Context) -> Set[str]:
try:
selected_meshes: List[Object] = [obj for obj in context.selected_objects if obj.type == 'MESH']
valid: bool
message: str
valid, message = validate_meshes(selected_meshes)
if not valid:
self.report({'WARNING'}, message)
return {'CANCELLED'}
with ProgressTracker(context, 5, "Joining Selected Meshes") as progress:
success: bool
success, message = join_mesh_objects(context, selected_meshes, progress)
if success:
self.report({'INFO'}, message)
return {'FINISHED'}
else:
self.report({'ERROR'}, message)
return {'CANCELLED'}
except Exception as e:
logger.error(f"Failed to join selected meshes: {str(e)}")
self.report({'ERROR'}, t("Optimization.error.join_selected", error=str(e)))
return {'CANCELLED'}
+281
View File
@@ -0,0 +1,281 @@
import bpy
import numpy as np
from typing import List, TypedDict, Any, Literal, TypeAlias, cast
from bpy.types import Operator, Context, Object, Event
from ...core.logging_setup import logger
from ...core.translations import t
from ...core.common import (
get_active_armature,
get_all_meshes,
validate_armature
)
# Constants
MERGE_ITERATION_COUNT = 20
MERGE_DISTANCE_DEFAULT = 0.0001
# Type definitions
ModalReturnType: TypeAlias = Literal['RUNNING_MODAL', 'FINISHED', 'CANCELLED']
class MeshEntry(TypedDict):
mesh: Object
shapekeys: list[str]
vertices: int
cur_vertex_pass: int
def create_duplicate_for_merge(context: Context, mesh: Object, shapekey_name: str) -> Object:
"""Creates a duplicate mesh object for merge testing"""
context.view_layer.objects.active = mesh
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
mesh.select_set(True)
bpy.ops.object.duplicate()
bpy.ops.object.shape_key_move(type='TOP')
duplicate = context.view_layer.objects.active
duplicate.name = f"{shapekey_name}_object_is_{mesh.name}"
return duplicate
def process_vertex_merging(mesh_data: bpy.types.Mesh, vertices_original: dict[int, Any], current_vertex: int) -> list[int]:
"""Process vertex merging and return merged vertex indices"""
merged_vertices = []
i, j = 0, 0
while i < len(vertices_original):
if j + 1 > len(mesh_data.vertices):
merged_vertices.append(i)
j = j - 1
elif mesh_data.vertices[j].co.xyz != vertices_original[i]:
merged_vertices.append(i)
j = j - 1
elif vertices_original[i] == vertices_original[current_vertex]:
merged_vertices.append(i)
i, j = i + 1, j + 1
return merged_vertices
class AvatarToolkit_OT_RemoveDoublesAdvanced(Operator):
bl_idname = "avatar_toolkit.remove_doubles_advanced"
bl_label = t("Optimization.remove_doubles_advanced")
bl_description = t("Optimization.remove_doubles_advanced_desc")
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context: Context) -> bool:
"""Check if the operator can be executed"""
armature = get_active_armature(context)
if not armature:
return False
valid, _ = validate_armature(armature)
return valid
def execute(self, context: Context) -> set[str]:
"""Execute the advanced remove doubles operator"""
context.scene.avatar_toolkit.remove_doubles_advanced = True
bpy.ops.avatar_toolkit.remove_doubles('INVOKE_DEFAULT')
return {'RUNNING_MODAL'}
class AvatarToolkit_OT_RemoveDoubles(Operator):
bl_idname = "avatar_toolkit.remove_doubles"
bl_label = t("Optimization.remove_doubles")
bl_description = t("Optimization.remove_doubles_desc")
bl_options = {'REGISTER', 'UNDO'}
objects_to_do: list[MeshEntry] = []
@classmethod
def poll(cls, context: Context) -> bool:
"""Check if the operator can be executed"""
armature = get_active_armature(context)
if not armature:
return False
valid, _ = validate_armature(armature)
return valid
def draw(self, context: Context) -> None:
"""Draw the operator's UI"""
layout = self.layout
layout.prop(context.scene.avatar_toolkit, "remove_doubles_merge_distance")
layout.label(text=t("Optimization.remove_doubles_warning"))
layout.label(text=t("Optimization.remove_doubles_wait"))
def invoke(self, context: Context, event: Event) -> set[str]:
"""Initialize the operator"""
logger.info("Starting modal execution of merge doubles safely")
return context.window_manager.invoke_props_dialog(self)
def setup_mesh_entry(self, mesh: Object) -> MeshEntry:
"""Set up mesh entry data structure"""
mesh_entry: MeshEntry = {
"mesh": mesh,
"shapekeys": [],
"vertices": len(mesh.data.vertices),
"cur_vertex_pass": 0
}
if mesh.data.shape_keys:
mesh_entry["shapekeys"] = [shape.name for shape in mesh.data.shape_keys.key_blocks]
return mesh_entry
def execute(self, context: Context) -> set[str]:
"""Execute the remove doubles operator"""
try:
armature = get_active_armature(context)
if not armature:
self.report({'WARNING'}, t("Optimization.no_armature"))
return {'CANCELLED'}
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
objects = get_all_meshes(context)
self.objects_to_do = []
for mesh in objects:
if mesh.data.name not in [obj["mesh"].data.name for obj in self.objects_to_do]:
logger.debug(f"Setting up data for object {mesh.name}")
mesh_entry = self.setup_mesh_entry(mesh)
self.objects_to_do.append(mesh_entry)
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
except Exception as e:
logger.error(f"Error in execute: {str(e)}")
return {'CANCELLED'}
def modify_mesh(self, context: Context, mesh: MeshEntry) -> None:
"""Basic mesh modification for simple cases"""
try:
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
mesh_data = mesh["mesh"].data
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
# Select vertices with different positions in shape keys
for index, point in enumerate(mesh["mesh"].active_shape_key.points):
if point.co.xyz != mesh_data.shape_keys.key_blocks[0].points[index].co.xyz:
mesh_data.vertices[index].select = True
logger.debug(f"Shapekey has moved vertex at index {index}")
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
except Exception as e:
logger.error(f"Error in modify_mesh: {str(e)}")
def modify_mesh_advanced(self, context: Context, mesh_entry: MeshEntry) -> bool:
"""Advanced mesh modification with shape key handling"""
try:
final_merged_vertex_group = []
initialized_final = False
merge_distance = context.scene.avatar_toolkit.remove_doubles_merge_distance
for shapekey_name in mesh_entry["shapekeys"]:
duplicate = create_duplicate_for_merge(context, mesh_entry["mesh"], shapekey_name)
vertices_original = {i: v.co.xyz for i, v in enumerate(duplicate.data.vertices)}
# Process merging
merged_vertices = process_vertex_merging(duplicate.data, vertices_original, mesh_entry["cur_vertex_pass"])
if not initialized_final:
final_merged_vertex_group = merged_vertices.copy()
initialized_final = True
else:
final_merged_vertex_group = [v for v in final_merged_vertex_group if v in merged_vertices]
bpy.ops.object.delete()
# Apply final merging
if final_merged_vertex_group:
self.apply_final_merging(context, mesh_entry, final_merged_vertex_group, merge_distance)
return not (len(final_merged_vertex_group) > 1)
except Exception as e:
logger.error(f"Error in modify_mesh_advanced: {str(e)}")
return True
def apply_final_merging(self, context: Context, mesh_entry: MeshEntry, vertex_group: list[int], merge_distance: float) -> None:
"""Apply final vertex merging operations"""
mesh = mesh_entry["mesh"]
context.view_layer.objects.active = mesh
mesh.select_set(True)
bpy.ops.object.mode_set(mode='OBJECT')
select_target_group = [False] * len(mesh.data.vertices)
for vertex_index in vertex_group:
select_target_group[vertex_index] = True
mesh.data.vertices.foreach_set("select", select_target_group)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.remove_doubles(threshold=merge_distance, use_unselected=False)
bpy.ops.object.mode_set(mode='OBJECT')
def process_simple_mesh(self, context: Context, mesh: MeshEntry, merge_distance: float) -> None:
"""Process mesh without shapekeys using simple merge operation"""
logger.debug(f"Processing mesh without shapekeys: {mesh['mesh'].name}")
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
bpy.ops.object.mode_set(mode='EDIT')
mesh["mesh"].data.vertices.foreach_set("select", [False] * len(mesh["mesh"].data.vertices))
bpy.ops.mesh.select_all(action="INVERT")
bpy.ops.mesh.remove_doubles(threshold=merge_distance, use_unselected=False)
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
def finish_mesh_processing(self, context: Context, mesh: MeshEntry, advanced: bool, merge_distance: float) -> None:
"""Complete the mesh processing by performing final merge operations"""
logger.debug("Finishing mesh processing")
if not advanced:
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action="INVERT")
bpy.ops.mesh.remove_doubles(threshold=merge_distance, use_unselected=False)
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
def modal(self, context: Context, event: Event) -> set[ModalReturnType]:
"""Modal operator execution"""
try:
if not self.objects_to_do:
self.report({'INFO'}, t("Optimization.remove_doubles_completed"))
logger.info("Finishing modal execution of merge doubles safely")
return {'FINISHED'}
mesh = self.objects_to_do[0]
mesh_data = mesh["mesh"].data
advanced = context.scene.avatar_toolkit.remove_doubles_advanced
merge_distance = context.scene.avatar_toolkit.remove_doubles_merge_distance
if len(mesh['shapekeys']) > 0 and not advanced:
shapekeyname = mesh['shapekeys'].pop(0)
mesh["mesh"].active_shape_key_index = mesh_data.shape_keys.key_blocks.find(shapekeyname)
logger.debug(f"Processing shapekey {shapekeyname}")
self.modify_mesh(context, mesh)
elif not mesh_data.shape_keys:
self.process_simple_mesh(context, mesh, merge_distance)
self.objects_to_do.pop(0)
elif not (mesh["cur_vertex_pass"] > mesh["vertices"]) and advanced:
if self.modify_mesh_advanced(context, mesh):
mesh["cur_vertex_pass"] += 1
else:
self.finish_mesh_processing(context, mesh, advanced, merge_distance)
self.objects_to_do.pop(0)
return {'RUNNING_MODAL'}
except Exception as e:
logger.error(f"Error in modal: {str(e)}")
return {'CANCELLED'}