Source code for linkforge.blender.operators.link_ops

"""Operators for managing robot links."""

from __future__ import annotations

import contextlib
import time
import typing

import bpy
from bpy.types import Context, Operator

from ..adapters.geometry_extractor import (
    detect_primitive_type,
    extract_mesh_triangles,
)
from ..constants import (
    DEFAULT_LINK_GIZMO_SIZE,
    GEOM_AUTO,
    PROP_GEOM,
    PROP_LINK,
    SUFFIX_COLLISION,
    SUFFIX_VISUAL,
)
from ..core import InertiaTensor, Vector3, get_logger
from ..core.constants import (
    GEOM_BOX,
    GEOM_CYLINDER,
    GEOM_MESH,
    GEOM_SPHERE,
)
from ..logic.collision_builder import (
    create_collision_for_link,
    regenerate_collision_mesh,
)
from ..preferences import get_addon_prefs
from ..properties.link_props import (
    LinkPropertyGroup,
    sanitize_name,
    update_active_collision,
    update_active_visual,
)
from ..utils.decorators import OperatorReturn, safe_execute
from ..utils.mode_guard import context_and_mode_guard
from ..utils.scene_utils import clear_stats_cache, compute_anchor_size

logger = get_logger(__name__)

# Debounce state for real-time collision preview updates
_preview_pending_object: bpy.types.Object | None = None
_preview_last_request_time: float = 0.0
COLLISION_PREVIEW_DEBOUNCE_DELAY: float = 0.3


[docs] def schedule_collision_preview_update(obj: bpy.types.Object) -> None: """Debounce timer callback to update collision preview. Registers `execute_collision_preview_update` as a timer if not already registered. """ global _preview_pending_object, _preview_last_request_time _preview_pending_object = obj _preview_last_request_time = time.time() if not bpy.app.timers.is_registered(execute_collision_preview_update): bpy.app.timers.register( execute_collision_preview_update, first_interval=COLLISION_PREVIEW_DEBOUNCE_DELAY, )
[docs] def execute_collision_preview_update() -> float | None: """Timer callback for collision preview debounce. Returns: Remaining delay to wait, or None to unregister the timer. """ global _preview_pending_object, _preview_last_request_time if _preview_pending_object is None: return None elapsed = time.time() - _preview_last_request_time if elapsed < COLLISION_PREVIEW_DEBOUNCE_DELAY: return max(COLLISION_PREVIEW_DEBOUNCE_DELAY - elapsed, 0.01) obj = _preview_pending_object _preview_pending_object = None if not obj or not hasattr(obj, PROP_LINK): return None try: collision_type = detect_primitive_type(obj) regenerate_collision_mesh(obj, str(collision_type), bpy.context) except Exception as e: logger.error(f"Error during debounce collision preview update: {e}") return None
[docs] class LINKFORGE_OT_generate_collision(Operator): """Generate collision geometry from visual geometry for the active link. This operator analyzes the visual mesh(es) of the selected link and automatically generates simplified collision geometry (primitive or mesh) based on the specified collision type. """ bl_idname = "linkforge.generate_collision" bl_label = "Generate Collision" bl_description = ( "Auto-generate collision geometry from visual mesh. " "Requires at least one child mesh with " + SUFFIX_VISUAL + " suffix." ) bl_options = {"REGISTER", "UNDO"} collision_type: bpy.props.EnumProperty( # type: ignore name="Collision Type", description="Type of collision geometry to generate", items=[ ( GEOM_AUTO, "Auto-Detect", "Automatically detect primitive shape or use mesh simplification", ), (GEOM_BOX, "Bounding Box", "Use axis-aligned bounding box"), (GEOM_SPHERE, "Bounding Sphere", "Use bounding sphere"), (GEOM_CYLINDER, "Bounding Cylinder", "Cylindrical bounding volume around the mesh"), ( GEOM_MESH, "Mesh (Simplified)", "Generate simplified mesh from visual geometry", ), ], default=GEOM_AUTO, )
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" obj = context.active_object if obj is None: return False if not obj.select_get(): return False # Allow if object is a link if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): return True # Allow if object is visual/collision child return bool( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link and (SUFFIX_VISUAL in obj.name.lower() or SUFFIX_COLLISION in obj.name.lower()) )
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" # Find all robot links links = [ o for o in bpy.data.objects if hasattr(o, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(o, PROP_LINK)).is_robot_link ] if not links: self.report({"WARNING"}, "No robot links found") return {"CANCELLED"} obj = context.active_object if not obj: return {"CANCELLED"} # If selected object is visual or collision child, use parent link link_obj = obj if ( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link and (SUFFIX_VISUAL in obj.name.lower() or SUFFIX_COLLISION in obj.name.lower()) ): link_obj = obj.parent if not link_obj: return {"CANCELLED"} # Determine collision type # Priority: Operator property (if changed in redo) > Link property > Default GEOM_AUTO collision_type = self.collision_type # Create collision collision_obj = create_collision_for_link(link_obj, collision_type, context) if collision_obj is None: # Check if it failed because of missing visuals visual_children = [ c for c in link_obj.children if SUFFIX_VISUAL in c.name.lower() and c.type == "MESH" ] if not visual_children: self.report({"ERROR"}, "No visual meshes found. Cannot generate collision.") else: self.report({"ERROR"}, "Failed to generate collision geometry") return {"CANCELLED"} # Restore selection (fall back to link if original object was deleted) vl = context.view_layer try: obj.select_set(True) if vl: vl.objects.active = obj except ReferenceError: if link_obj: link_obj.select_set(True) if vl: vl.objects.active = link_obj lp = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) self.report({"INFO"}, f"Generated '{collision_type}' collision for '{lp.link_name}'") clear_stats_cache() return {"FINISHED"}
[docs] class LINKFORGE_OT_generate_collision_all(Operator): """Generate collision geometry for all robot links in the scene. This operator performs a batch collision generation for every object marked as a LinkForge Robot Link, using each link's stored collision type preferences. """ bl_idname = "linkforge.generate_collision_all" bl_label = "Generate All Collisions" bl_description = "Generate collision geometry for all robot links in the scene" bl_options = {"REGISTER", "UNDO"}
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" scene = context.scene if not scene: return {"FINISHED"} count = 0 failed = 0 # Iterate over all objects in scene for obj in scene.objects: # Check if it's a robot link if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): # Resolve primary mesh to use for detection visual_children = [c for c in obj.children if SUFFIX_VISUAL in c.name.lower()] if visual_children: collision_type = GEOM_AUTO if create_collision_for_link(obj, collision_type, context): count += 1 else: failed += 1 if failed > 0: self.report({"WARNING"}, f"Failed to generate collision for {failed} links") clear_stats_cache() return {"FINISHED"}
[docs] class LINKFORGE_OT_toggle_collision_visibility(Operator): """Toggle collision geometry visibility in the 3D viewport. This operator recursively toggles the visibility state of all collision mesh children for the selected robot link(s). """ bl_idname = "linkforge.toggle_collision_visibility" bl_label = "Toggle Collision Visibility" bl_description = "Show/hide collision geometry in the viewport" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" obj = context.active_object if obj is None: return False if not obj.select_get(): return False # Allow if object is a link with collision children if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): collision_children = [c for c in obj.children if SUFFIX_COLLISION in c.name.lower()] return len(collision_children) > 0 # Allow if object is visual/collision child if ( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link ): collision_children = [ c for c in obj.parent.children if SUFFIX_COLLISION in c.name.lower() ] return len(collision_children) > 0 return False
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" obj = context.active_object if obj is None: return {"CANCELLED"} # Toggle visibility if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): # It's a link - toggle all its collision children for child in obj.children: if SUFFIX_COLLISION in child.name.lower(): child.hide_viewport = not child.hide_viewport child.hide_render = child.hide_viewport # Keep render state consistent else: # It's a visual/collision child - toggle its parent's collisions if obj.parent and hasattr(obj.parent, PROP_LINK): for child in obj.parent.children: if SUFFIX_COLLISION in child.name.lower(): child.hide_viewport = not child.hide_viewport child.hide_render = child.hide_viewport # Keep render state consistent return {"FINISHED"}
[docs] class LINKFORGE_OT_calculate_inertia(Operator): """Calculate the inertia tensor from link geometry and mass. This operator utilizes the Core inertia calculator to derive the moment of inertia and center of mass for the selected link based on its visual and collision volumes. """ bl_idname = "linkforge.calculate_inertia" bl_label = "Calculate Inertia" bl_description = "Auto-calculate inertia tensor from object geometry and mass" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" obj = context.active_object if obj is None: return False if not obj.select_get(): return False # If selected object is a visual/collision child, check parent if ( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link ): return True return bool( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link )
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" obj = context.active_object if not obj: return {"CANCELLED"} # Resolve target link link_obj = obj if ( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link ): link_obj = obj.parent if not link_obj: return {"CANCELLED"} success = calculate_inertia_for_link(link_obj) if success: link_name = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)).link_name self.report({"INFO"}, f"Calculated inertia for '{link_name}'") return {"FINISHED"} else: self.report({"WARNING"}, "Failed to calculate inertia (check geometry/mass)") return {"CANCELLED"}
[docs] class LINKFORGE_OT_calculate_inertia_all(Operator): """Calculate the inertia tensor for all robot links in the scene. This operator performs a batch inertia calculation for every LinkForge Robot Link, updating their mass and inertial properties based on their active geometry. """ bl_idname = "linkforge.calculate_inertia_all" bl_label = "Calculate All Inertias" bl_description = "Auto-calculate inertia tensor for all robot links in the scene" bl_options = {"REGISTER", "UNDO"}
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" scene = context.scene if not scene: return {"FINISHED"} count = 0 failed = 0 # Iterate over all objects in scene for obj in scene.objects: # Check if it's a robot link if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): if calculate_inertia_for_link(obj): count += 1 else: # Only count as failed if it had visual/collision mesh but failed has_mesh = any( c.type == "MESH" and (SUFFIX_VISUAL in c.name.lower() or SUFFIX_COLLISION in c.name.lower()) for c in obj.children ) if has_mesh: failed += 1 if count > 0: self.report({"INFO"}, f"Calculated inertia for {count} links") elif failed > 0: self.report({"WARNING"}, f"Failed to calculate inertia for {failed} links") else: self.report({"INFO"}, "No links found needing inertia calculation") return {"FINISHED"}
def _resolve_active_link(context: Context) -> bpy.types.Object | None: """Resolve the active link object from selection.""" obj = context.active_object if not obj: return None if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): return obj if ( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link ): return obj.parent # If active object is not a link (e.g. it's a loose mesh), check selected objects for sel_obj in context.selected_objects: if ( hasattr(sel_obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(sel_obj, PROP_LINK)).is_robot_link ): return sel_obj if ( sel_obj.parent and hasattr(sel_obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(sel_obj.parent, PROP_LINK)).is_robot_link ): return sel_obj.parent return None
[docs] class LINKFORGE_OT_assign_as_visual(Operator): """Parent selected mesh(es) to the active link as visual geometry.""" bl_idname = "linkforge.assign_as_visual" bl_label = "Assign Selected as Visual" bl_description = "Parent selected mesh(es) to the active link as visual geometry" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" link_obj = _resolve_active_link(context) return link_obj is not None and any( o.type == "MESH" and o != link_obj and o.parent != link_obj for o in context.selected_objects )
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" link_obj = _resolve_active_link(context) if not link_obj: return {"CANCELLED"} meshes = [ o for o in context.selected_objects if o.type == "MESH" and o != link_obj and o.parent != link_obj ] if not meshes: self.report({"WARNING"}, "Select at least one loose mesh to assign") return {"CANCELLED"} lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) link_name = lf.link_name or link_obj.name for mesh in meshes: detected = detect_primitive_type(mesh) or GEOM_MESH idx = sum(1 for c in link_obj.children if SUFFIX_VISUAL in c.name.lower()) suffix = f"_{idx}" if idx > 0 else "" mesh.name = f"{link_name}{SUFFIX_VISUAL}{suffix}" mesh.parent = link_obj mesh.matrix_parent_inverse = link_obj.matrix_world.inverted() mesh.rotation_mode = "XYZ" geom_props = getattr(mesh, PROP_GEOM, None) if geom_props: geom_props.geometry_type = detected geom_props.geom_role = "VISUAL" self.report({"INFO"}, f"Assigned {len(meshes)} visual(s) to '{link_name}'") clear_stats_cache() return {"FINISHED"}
[docs] class LINKFORGE_OT_assign_as_collision(Operator): """Parent selected mesh(es) to the active link as collision geometry.""" bl_idname = "linkforge.assign_as_collision" bl_label = "Assign Selected as Collision" bl_description = "Parent selected mesh(es) to the active link as collision geometry" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" link_obj = _resolve_active_link(context) return link_obj is not None and any( o.type == "MESH" and o != link_obj and o.parent != link_obj for o in context.selected_objects )
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" link_obj = _resolve_active_link(context) if not link_obj: return {"CANCELLED"} meshes = [ o for o in context.selected_objects if o.type == "MESH" and o != link_obj and o.parent != link_obj ] if not meshes: self.report({"WARNING"}, "Select at least one loose mesh to assign") return {"CANCELLED"} lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) link_name = lf.link_name or link_obj.name for mesh in meshes: detected = detect_primitive_type(mesh) or GEOM_MESH idx = sum(1 for c in link_obj.children if SUFFIX_COLLISION in c.name.lower()) suffix = f"_{idx}" if idx > 0 else "" mesh.name = f"{link_name}{SUFFIX_COLLISION}{suffix}" mesh.parent = link_obj mesh.matrix_parent_inverse = link_obj.matrix_world.inverted() mesh.rotation_mode = "XYZ" mesh.display_type = "WIRE" mesh.show_in_front = True mesh.hide_render = True geom_props = getattr(mesh, PROP_GEOM, None) if geom_props: geom_props.geometry_type = detected geom_props.geom_role = "COLLISION" geom_props.collision_quality = 100.0 self.report({"INFO"}, f"Assigned {len(meshes)} collision(s) to '{link_name}'") clear_stats_cache() return {"FINISHED"}
[docs] class LINKFORGE_OT_set_active_geometry(Operator): """Set the active geometry index and select it.""" bl_idname = "linkforge.set_active_geometry" bl_label = "Set Active Geometry" bl_description = "Set this geometry as active and select it in the viewport" bl_options = {"REGISTER", "UNDO"} geometry_type: bpy.props.EnumProperty( # type: ignore items=[ ("VISUAL", "Visual", ""), ("COLLISION", "Collision", ""), ], name="Geometry Type", ) index: bpy.props.IntProperty(name="Index", default=0) # type: ignore
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" return _resolve_active_link(context) is not None
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" link_obj = _resolve_active_link(context) if not link_obj: return {"CANCELLED"} lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) if self.geometry_type == "VISUAL": lf.active_visual_index = self.index update_active_visual(lf, context) elif self.geometry_type == "COLLISION": lf.active_collision_index = self.index update_active_collision(lf, context) return {"FINISHED"}
[docs] class LINKFORGE_OT_remove_visual(Operator): """Remove the active visual mesh from the link.""" bl_idname = "linkforge.remove_visual" bl_label = "Remove Visual" bl_description = "Remove the active visual mesh from the link" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" link_obj = _resolve_active_link(context) if not link_obj: return False lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) return hasattr(lf, "active_visual_index") and lf.active_visual_index >= 0
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" link_obj = _resolve_active_link(context) if not link_obj: return {"CANCELLED"} lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) visuals = [c for c in link_obj.children if SUFFIX_VISUAL in c.name.lower()] idx = getattr(lf, "active_visual_index", 0) if 0 <= idx < len(visuals): obj_to_remove = visuals[idx] # Keep world transforms when unparenting original_world_matrix = obj_to_remove.matrix_world.copy() obj_to_remove.parent = None obj_to_remove.matrix_world = original_world_matrix # Clean up name link_name = lf.link_name or link_obj.name if obj_to_remove.name.startswith(f"{link_name}{SUFFIX_VISUAL}"): obj_to_remove.name = obj_to_remove.name.replace(SUFFIX_VISUAL, "") # Adjust index if necessary if idx >= len(visuals) - 1 and idx > 0: lf.active_visual_index = idx - 1 self.report({"INFO"}, f"Removed visual '{obj_to_remove.name}'") clear_stats_cache() return {"FINISHED"}
[docs] class LINKFORGE_OT_remove_collision(Operator): """Remove the active collision mesh from the link.""" bl_idname = "linkforge.remove_collision" bl_label = "Remove Collision" bl_description = "Remove the active collision mesh from the link" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" link_obj = _resolve_active_link(context) if not link_obj: return False lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) return hasattr(lf, "active_collision_index") and lf.active_collision_index >= 0
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" link_obj = _resolve_active_link(context) if not link_obj: return {"CANCELLED"} lf = typing.cast("LinkPropertyGroup", getattr(link_obj, PROP_LINK)) collisions = [c for c in link_obj.children if SUFFIX_COLLISION in c.name.lower()] idx = getattr(lf, "active_collision_index", 0) if 0 <= idx < len(collisions): obj_to_remove = collisions[idx] bpy.data.objects.remove(obj_to_remove, do_unlink=True) # Adjust index if necessary if idx >= len(collisions) - 1 and idx > 0: lf.active_collision_index = idx - 1 self.report({"INFO"}, "Removed collision geometry") clear_stats_cache() return {"FINISHED"}
[docs] class LINKFORGE_OT_add_material_slot(Operator): """Add a material slot to the visual mesh of a link""" bl_idname = "linkforge.add_material_slot" bl_label = "Add Material Slot" bl_description = "Add a material slot to the visual mesh so a material can be assigned" bl_options = {"REGISTER", "UNDO"}
[docs] @classmethod def poll(cls, context: Context) -> bool: """Check if operator can run.""" obj = context.active_object if obj is None: return False # Allow if object is a link if ( hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): return True # Allow if object is a visual child return bool( obj.parent and hasattr(obj.parent, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj.parent, PROP_LINK)).is_robot_link and SUFFIX_VISUAL in obj.name.lower() )
[docs] @safe_execute def execute(self, context: Context) -> OperatorReturn: """Execute the operator.""" obj = context.active_object # If selected object is link, find visual child if ( obj and hasattr(obj, PROP_LINK) and typing.cast("LinkPropertyGroup", getattr(obj, PROP_LINK)).is_robot_link ): visual_children = [ c for c in obj.children if SUFFIX_VISUAL in c.name.lower() and c.type == "MESH" ] if not visual_children: self.report({"ERROR"}, "No visual mesh found for this link") return {"CANCELLED"} visual_obj = visual_children[0] link_name = typing.cast(typing.Any, obj).linkforge.link_name else: # Selected object is the visual mesh if not obj or not obj.parent: return {"CANCELLED"} visual_obj = obj link_name = typing.cast(typing.Any, obj.parent).linkforge.link_name # Append new material slot if visual_obj.data and hasattr(visual_obj.data, "materials"): visual_obj.data.materials.append(None) # Create and assign a default material immediately for better UX mat_name = f"{link_name}_material" mat = bpy.data.materials.get(mat_name) if not mat: mat = bpy.data.materials.new(name=mat_name) mat.use_nodes = True visual_obj.data.materials[0] = mat self.report({"INFO"}, "Created new material slot with default material") return {"FINISHED"}
[docs] def update_collision_quality_realtime( obj: bpy.types.Object, collision_obj: bpy.types.Object ) -> None: """Update collision quality ratio in realtime via Decimate modifier. Args: obj: The main link object. collision_obj: The generated collision object. """ if not collision_obj or not obj: return # FAST PATH: If we have a Decimate modifier, just update the ratio # This provides instant feedback without expensive mesh regeneration geom_props = getattr(collision_obj, PROP_GEOM, None) if not geom_props: return # PRIMITIVE INVARIANCE GUARANTEE: # Do not decimate primitive shapes (Box, Sphere, Cylinder). Decimation corrupts their bounding geometry # and distorts their representation in the 3D viewport. If any Decimate modifier exists, cleanly remove it. if geom_props.geometry_type != GEOM_MESH: decimate_mods = [m for m in collision_obj.modifiers if m.type == "DECIMATE"] for mod in decimate_mods: collision_obj.modifiers.remove(mod) return quality_ratio = geom_props.collision_quality / 100.0 decimate_mod = next((m for m in collision_obj.modifiers if m.type == "DECIMATE"), None) if decimate_mod and ( isinstance(decimate_mod, bpy.types.DecimateModifier) or hasattr(decimate_mod, "ratio") ): decimate_mod.ratio = quality_ratio elif collision_obj.type == "MESH": # FALLBACK IMPROVEMENT: If modifier is missing but object exists, try adding it first # This is much faster than full _regenerate_ and avoids one potential "jump". decimate_mod = typing.cast( typing.Any, collision_obj.modifiers.new(name="Decimate", type="DECIMATE"), ) decimate_mod.ratio = quality_ratio decimate_mod.decimate_type = "COLLAPSE" else: # ABSOLUTE FALLBACK: schedule a full regeneration for primitives or missing objects. schedule_collision_preview_update(obj)
# Registration classes = [ LINKFORGE_OT_add_empty_link, LINKFORGE_OT_create_link_from_mesh, LINKFORGE_OT_assign_as_visual, LINKFORGE_OT_assign_as_collision, LINKFORGE_OT_set_active_geometry, LINKFORGE_OT_remove_visual, LINKFORGE_OT_remove_collision, LINKFORGE_OT_generate_collision, LINKFORGE_OT_generate_collision_all, LINKFORGE_OT_toggle_collision_visibility, LINKFORGE_OT_calculate_inertia, LINKFORGE_OT_calculate_inertia_all, LINKFORGE_OT_remove_link, LINKFORGE_OT_add_material_slot, ]
[docs] def register() -> None: """Register operators.""" logger.debug(f"link_ops.register called with {len(classes)} classes") for cls in classes: with contextlib.suppress(ValueError): bpy.utils.register_class(cls)
[docs] def unregister() -> None: """Unregister operators.""" for cls in reversed(classes): with contextlib.suppress(RuntimeError): bpy.utils.unregister_class(cls)
if __name__ == "__main__": register()