Skip to content

Transform your 3D texturing workflow with the power of generative AI, directly within Blender!

expand automatic rigging and trellis workflows

sakalond559daa9a5d54
diff --git a/stablegen/_generator_utils.py b/stablegen/_generator_utils.py
index 099fb9d..7808577 100644
--- a/stablegen/_generator_utils.py
+++ b/stablegen/_generator_utils.py
@@ -5,7 +5,12 @@ import bpy # pylint: disable=import-error
import mathutils # pylint: disable=import-error
import json
import math
+import mimetypes
+import re
+import tempfile
+import time
import traceback
+import uuid
import requests
from .timeout_config import get_timeout
@@ -147,4 +152,273 @@ def upload_image_to_comfyui(server_address, image_path, image_type="input"):
print(f"[StableGen] An unexpected error occurred during image upload of {os.path.basename(image_path)}: {e}")
traceback.print_exc() # Print full traceback for unexpected errors
- return None
\ No newline at end of file
+ return None
+
+
+class _TransferCancelled(Exception):
+ """Internal signal used to stop a transfer without retrying it."""
+
+
+class _MultipartFileStream:
+ """Replayable streaming multipart body for one file.
+
+ ``requests`` normally reads every file in ``files=`` into memory while it
+ constructs the multipart body. This iterable keeps large GLBs on disk and
+ reports progress as their bytes are handed to the HTTP connection.
+ """
+
+ def __init__(
+ self, file_path, mime_type, fields, progress_cb=None,
+ cancel_cb=None, attempt=1, chunk_size=1024 * 1024):
+ self.file_path = file_path
+ self.file_size = os.path.getsize(file_path)
+ self.progress_cb = progress_cb
+ self.cancel_cb = cancel_cb
+ self.attempt = attempt
+ self.chunk_size = chunk_size
+ self.boundary = f"----StableGen{uuid.uuid4().hex}"
+
+ field_parts = []
+ for name, value in fields.items():
+ field_parts.append(
+ f"--{self.boundary}\r\n"
+ f'Content-Disposition: form-data; name="{name}"\r\n\r\n'
+ f"{value}\r\n".encode("utf-8")
+ )
+ safe_filename = os.path.basename(file_path).replace('"', "_")
+ self.prefix = b"".join(field_parts) + (
+ f"--{self.boundary}\r\n"
+ f'Content-Disposition: form-data; name="image"; '
+ f'filename="{safe_filename}"\r\n'
+ f"Content-Type: {mime_type}\r\n\r\n"
+ ).encode("utf-8")
+ self.suffix = f"\r\n--{self.boundary}--\r\n".encode("ascii")
+ self.content_length = len(self.prefix) + self.file_size + len(self.suffix)
+
+ def __len__(self):
+ return self.content_length
+
+ def __iter__(self):
+ if self.cancel_cb and self.cancel_cb():
+ raise _TransferCancelled()
+ yield self.prefix
+ sent = 0
+ if self.progress_cb:
+ self.progress_cb(sent, self.file_size, self.attempt)
+ while sent < self.file_size:
+ if self.cancel_cb and self.cancel_cb():
+ raise _TransferCancelled()
+ # Do not retain an open Windows file handle across ``yield``. If
+ # the socket aborts, requests may keep the suspended iterator alive
+ # in an exception traceback until the next retry has completed.
+ with open(self.file_path, "rb") as handle:
+ handle.seek(sent)
+ chunk = handle.read(self.chunk_size)
+ if not chunk:
+ break
+ yield chunk
+ sent += len(chunk)
+ if self.progress_cb:
+ self.progress_cb(sent, self.file_size, self.attempt)
+ yield self.suffix
+
+
+def upload_file_to_comfyui(
+ server_address, file_path, file_type="input", subfolder="",
+ progress_cb=None, cancel_cb=None, max_retries=3):
+ """Stream an arbitrary file through ComfyUI's upload route.
+
+ ComfyUI's standard upload API has no append/resume operation. Interrupted
+ uploads are therefore retried from byte zero with ``overwrite=true``. The
+ operation is safe and idempotent because every attempt sends the same file
+ to the same destination and ComfyUI only exposes the completed upload.
+ """
+ if not os.path.isfile(file_path):
+ print(f"[StableGen] File upload source does not exist: {file_path}")
+ return None
+
+ upload_url = f"http://{server_address}/upload/image"
+ filename = os.path.basename(file_path)
+ mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
+ if filename.lower().endswith(".glb"):
+ mime_type = "model/gltf-binary"
+ print(
+ f"[StableGen] Uploading {filename} to ComfyUI "
+ f"input/{subfolder or ''} ..."
+ )
+
+ last_error = None
+ for attempt in range(1, max(1, int(max_retries)) + 1):
+ try:
+ body = _MultipartFileStream(
+ file_path,
+ mime_type,
+ {
+ "overwrite": "true",
+ "type": file_type,
+ "subfolder": subfolder,
+ },
+ progress_cb=progress_cb,
+ cancel_cb=cancel_cb,
+ attempt=attempt,
+ )
+ response = requests.post(
+ upload_url,
+ data=body,
+ headers={
+ "Content-Type": f"multipart/form-data; boundary={body.boundary}",
+ "Content-Length": str(len(body)),
+ },
+ timeout=get_timeout("transfer"),
+ )
+ response.raise_for_status()
+ result = response.json()
+ if not result.get("name"):
+ print(
+ "[StableGen] ComfyUI file upload response did not include a "
+ f"filename: {result}"
+ )
+ return None
+ print(f"[StableGen] File upload successful: {result}")
+ return result
+ except _TransferCancelled:
+ print(f"[StableGen] Upload cancelled: {filename}")
+ return None
+ except requests.exceptions.HTTPError as exc:
+ # Authentication, upload-size, and other 4xx errors will not become
+ # healthy by replaying a very large request.
+ last_error = exc
+ status = exc.response.status_code if exc.response is not None else 0
+ print(
+ f"[StableGen] HTTP {status} while uploading {filename}: "
+ f"{exc.response.text if exc.response is not None else exc}"
+ )
+ if 400 <= status < 500:
+ break
+ except (requests.exceptions.RequestException, OSError, ValueError,
+ json.JSONDecodeError) as exc:
+ if cancel_cb and cancel_cb():
+ print(f"[StableGen] Upload cancelled: {filename}")
+ return None
+ last_error = exc
+ print(
+ f"[StableGen] Upload attempt {attempt}/{max_retries} failed "
+ f"for {filename}: {exc}"
+ )
+ if attempt < max_retries:
+ time.sleep(min(2 ** (attempt - 1), 4))
+ if last_error:
+ print(f"[StableGen] Could not upload {filename}: {last_error}")
+ return None
+
+
+def download_file_with_resume(
+ url, progress_cb=None, cancel_cb=None, max_retries=5,
+ chunk_size=1024 * 1024):
+ """Download *url* with validated HTTP Range resumption.
+
+ Partial data is only appended after a matching ``206 Content-Range``. If a
+ server ignores Range, changes the entity, or returns an incompatible range,
+ the temporary file is truncated and that response becomes a clean restart.
+ ``If-Range`` prevents bytes from two different file versions being joined.
+ """
+ downloaded = 0
+ total_size = None
+ validator = None
+ last_error = None
+
+ with tempfile.TemporaryFile() as temp_file:
+ for attempt in range(1, max(1, int(max_retries)) + 1):
+ if cancel_cb and cancel_cb():
+ raise _TransferCancelled()
+
+ headers = {}
+ requested_offset = downloaded
+ if requested_offset:
+ headers["Range"] = f"bytes={requested_offset}-"
+ if validator:
+ headers["If-Range"] = validator
+
+ try:
+ with requests.get(
+ url, headers=headers, stream=True,
+ timeout=get_timeout("transfer")) as response:
+ if response.status_code == 416 and total_size == downloaded:
+ break
+ response.raise_for_status()
+
+ append_response = requested_offset > 0 and response.status_code == 206
+ if append_response:
+ content_range = response.headers.get("Content-Range", "")
+ match = re.match(
+ r"bytes\s+(\d+)-(\d+)/(\d+|\*)", content_range)
+ if not match or int(match.group(1)) != requested_offset:
+ temp_file.seek(0)
+ temp_file.truncate()
+ downloaded = 0
+ total_size = None
+ validator = None
+ raise IOError(
+ "Server returned an incompatible Content-Range: "
+ f"{content_range or '<missing>'}"
+ )
+ if match.group(3) != "*":
+ total_size = int(match.group(3))
+ else:
+ # A 200 response to a Range request means Range is not
+ # supported (or If-Range detected a changed entity).
+ temp_file.seek(0)
+ temp_file.truncate()
+ downloaded = 0
+ requested_offset = 0
+ length = response.headers.get("Content-Length")
+ total_size = int(length) if length and length.isdigit() else None
+
+ validator = (
+ response.headers.get("ETag")
+ or response.headers.get("Last-Modified")
+ or validator
+ )
+ temp_file.seek(downloaded)
+ if progress_cb:
+ progress_cb(downloaded, total_size, attempt)
+ for chunk in response.iter_content(chunk_size=chunk_size):
+ if cancel_cb and cancel_cb():
+ raise _TransferCancelled()
+ if not chunk:
+ continue
+ temp_file.write(chunk)
+ downloaded += len(chunk)
+ if progress_cb:
+ progress_cb(downloaded, total_size, attempt)
+
+ if total_size is not None and downloaded < total_size:
+ raise IOError(
+ f"HTTP body ended at {downloaded} of {total_size} bytes"
+ )
+ break
+ except _TransferCancelled:
+ raise
+ except (requests.exceptions.RequestException, OSError, ValueError) as exc:
+ last_error = exc
+ print(
+ f"[StableGen] Download attempt {attempt}/{max_retries} "
+ f"interrupted at {downloaded} bytes: {exc}"
+ )
+ if attempt < max_retries:
+ time.sleep(min(2 ** (attempt - 1), 4))
+ continue
+ raise
+ else:
+ if last_error:
+ raise last_error
+
+ if not downloaded:
+ return b""
+ temp_file.seek(0)
+ data = temp_file.read()
+ if total_size is not None and len(data) != total_size:
+ raise IOError(
+ f"Downloaded size mismatch: received {len(data)} of {total_size} bytes"
+ )
+ return data
diff --git a/stablegen/animation/retargeting.py b/stablegen/animation/retargeting.py
index 447bfd9..9bbe5c2 100644
--- a/stablegen/animation/retargeting.py
+++ b/stablegen/animation/retargeting.py
@@ -25,9 +25,19 @@ _PROFILE_PROP = "sg_retarget_profile"
_REFERENCE_POSE_PROP = "sg_retarget_reference_pose"
_SOURCE_PREVIEW_PROP = "sg_retarget_source_preview"
_COLLISION_PROXY_PROP = "sg_retarget_collision_proxy"
+_COLLISION_SEGMENT_MODE_PROP = "sg_retarget_collision_segment_mode"
+_UPPER_ARM_COLLISION_PROP = "sg_retarget_upper_arm_collision"
+_ARM_CORRECTION_DRIVER_PROP = "sg_retarget_arm_correction_driver"
+_HAND_MATCH_ENABLED_PROP = "sg_retarget_match_hand_orientation"
+_HAND_MATCH_STRENGTH_PROP = "sg_retarget_hand_match_strength"
+_HAND_ROLL_MODE_PROP = "sg_retarget_hand_roll_mode"
+_HAND_ROLL_LIMIT_PROP = "sg_retarget_hand_roll_limit"
+_TWIST_CHAIN_VERSION_PROP = "sg_retarget_twist_chain_version"
_PROFILE_VERSION = 14
_REFERENCE_POSE_VERSION = 2
-_COLLISION_PROXY_VERSION = 2
+_COLLISION_PROXY_VERSION = 3
+_HAND_MATCH_ALGORITHM_VERSION = 4
+_TWIST_CHAIN_VERSION = 1
_LEGACY_REFERENCE_POSE_VERSION = 1
_CONSTRAINT_PREFIX = "SG_Retarget_"
_BONE_ENUM_ITEMS_CACHE = {}
@@ -53,6 +63,11 @@ _CHAIN_LABELS = {
"right_leg": "R Leg",
}
+_HAND_LABELS = {
+ "left_arm": "L Hand",
+ "right_arm": "R Hand",
+}
+
_BASIS_COLORS = {
"forward": (1.0, 0.25, 0.95, 0.98),
"left": (0.15, 0.55, 1.0, 0.98),
@@ -68,6 +83,7 @@ _COLLISION_PROXY_COLORS = {
"left_arm": (0.2, 0.95, 0.55, 0.82),
"right_arm": (1.0, 0.55, 0.16, 0.82),
"inactive": (0.55, 0.55, 0.6, 0.38),
+ "driver": (0.3, 0.65, 1.0, 0.62),
}
_ARM_CORRECTION_DRIVER_ITEMS = (
@@ -88,6 +104,60 @@ _ARM_CORRECTION_DRIVER_ITEMS = (
),
)
+_COLLISION_SEGMENT_MODE_ITEMS = (
+ (
+ "BONE_TAILS",
+ "Bone Heads to Tails",
+ "Build capsules from each Blender bone head to its raw tail",
+ ),
+ (
+ "JOINT_HEADS",
+ "Joint to Joint",
+ "Build capsules between consecutive mapped joint heads; recommended for disconnected rigs",
+ ),
+)
+
+_UPPER_ARM_COLLISION_ITEMS = (
+ (
+ "DISABLED",
+ "Disabled",
+ "Do not use the upper-arm capsule for collision detection",
+ ),
+ (
+ "DISTAL",
+ "Distal 75% (Recommended)",
+ "Check the upper arm while excluding its proximal shoulder-attachment region",
+ ),
+ (
+ "FULL",
+ "Full Upper Arm",
+ "Check the complete upper-arm capsule and preserve reference-pose intersections",
+ ),
+)
+
+_HAND_ROLL_MODE_ITEMS = (
+ (
+ "FOREARM",
+ "Single Forearm",
+ "Apply palm roll to the mapped forearm and leave only flexion at the wrist",
+ ),
+ (
+ "TWIST_CHAIN",
+ "Generated Twist Chain",
+ "Create deform helpers and distribute palm roll gradually along the forearm",
+ ),
+ (
+ "LIMITED",
+ "Limited Roll",
+ "Limit transferred palm roll to protect meshes that cannot tolerate full torsion",
+ ),
+ (
+ "WRIST",
+ "Wrist Only",
+ "Apply the complete palm correction directly to the hand bone",
+ ),
+)
+
def _norm_name(name):
value = name.lower()
@@ -629,7 +699,9 @@ def _animation_file_identity(filepath):
def _reference_provenance(
filepath, source_profile, target_profile, source_frame,
- source_reference_mode, swap_target_sides=False):
+ source_reference_mode, swap_target_sides=False,
+ match_hand_orientation=False, hand_match_strength=1.0,
+ hand_roll_mode="FOREARM", hand_roll_limit=60.0):
return {
"animation": _animation_file_identity(filepath),
"source_frame": int(source_frame),
@@ -637,6 +709,21 @@ def _reference_provenance(
"source_profile_signature": _profile_signature(source_profile),
"target_profile_signature": _profile_signature(target_profile),
"swap_target_sides": bool(swap_target_sides),
+ "match_hand_orientation": bool(match_hand_orientation),
+ "hand_match_strength": (
+ round(float(hand_match_strength), 6)
+ if match_hand_orientation else None
+ ),
+ "hand_match_algorithm_version": (
+ _HAND_MATCH_ALGORITHM_VERSION
+ if match_hand_orientation else None
+ ),
+ "hand_roll_mode": hand_roll_mode if match_hand_orientation else None,
+ "hand_roll_limit": (
+ round(float(hand_roll_limit), 4)
+ if match_hand_orientation and hand_roll_mode == "LIMITED"
+ else None
+ ),
}
@@ -646,8 +733,12 @@ def _reference_provenance_matches(reference_pose, expected):
return False, "target reference has no source provenance"
for key in (
"source_frame", "source_reference_mode", "source_profile_signature",
- "target_profile_signature", "swap_target_sides"):
- if actual.get(key) != expected.get(key):
+ "target_profile_signature", "swap_target_sides",
+ "match_hand_orientation", "hand_match_strength",
+ "hand_match_algorithm_version", "hand_roll_mode",
+ "hand_roll_limit"):
+ default = False if key == "match_hand_orientation" else None
+ if actual.get(key, default) != expected.get(key):
return False, f"target reference {key} does not match"
actual_file = actual.get("animation", {})
expected_file = expected.get("animation", {})
@@ -771,6 +862,65 @@ def _chain_world_points(armature, chain):
return points
+def _hand_mapping_overlay_data(armature, profile):
+ """Return mapped palm/digit segments without assuming exactly five digits."""
+ result = []
+ world_matrix = armature.matrix_world
+ for role in ("left_arm", "right_arm"):
+ chain = _profile_chains(profile).get(role, [])
+ if not chain:
+ continue
+ hand_name = chain[-1]
+ hand_pose = armature.pose.bones.get(hand_name)
+ if not hand_pose:
+ continue
+
+ segments = [
+ world_matrix @ hand_pose.head,
+ world_matrix @ hand_pose.tail,
+ ]
+ label_points = [world_matrix @ hand_pose.tail]
+ digit_roots = _hand_digit_root_names(armature, hand_name)
+ visited = set()
+ stack = []
+ for root_name in digit_roots:
+ cursor = armature.data.bones.get(root_name)
+ while cursor and cursor.name != hand_name:
+ stack.append(cursor.name)
+ cursor = cursor.parent
+ while stack:
+ bone_name = stack.pop()
+ if bone_name in visited:
+ continue
+ visited.add(bone_name)
+ pose_bone = armature.pose.bones.get(bone_name)
+ data_bone = armature.data.bones.get(bone_name)
+ if not pose_bone or not data_bone:
+ continue
+ head = world_matrix @ pose_bone.head
+ tail = world_matrix @ pose_bone.tail
+ if pose_bone.parent:
+ parent_tail = world_matrix @ pose_bone.parent.tail
+ if (head - parent_tail).length > 1e-6:
+ segments.extend((parent_tail, head))
+ segments.extend((head, tail))
+ label_points.extend((head, tail))
+ stack.extend(child.name for child in data_bone.children)
+
+ center = sum(
+ label_points,
+ mathutils.Vector((0.0, 0.0, 0.0)),
+ ) / len(label_points)
+ result.append({
+ "role": role,
+ "hand": hand_name,
+ "segments": segments,
+ "center": center,
+ "digit_count": len(digit_roots),
+ })
+ return result
+
+
def _profile_world_points(armature, profile):
points = []
chains = _profile_chains(profile) if profile else {}
@@ -887,6 +1037,19 @@ def _draw_rig_mapping_overlay():
batch = batch_for_shader(shader, "LINE_STRIP", {"pos": points})
batch.draw(shader)
+ gpu.state.line_width_set(2.2)
+ for hand_data in _hand_mapping_overlay_data(armature, profile):
+ segments = hand_data["segments"]
+ if len(segments) < 2:
+ continue
+ shader.uniform_float(
+ "color",
+ _CHAIN_COLORS.get(
+ hand_data["role"], (1.0, 1.0, 1.0, 0.9)),
+ )
+ batch = batch_for_shader(shader, "LINES", {"pos": segments})
+ batch.draw(shader)
+
gpu.state.line_width_set(5.0)
for name, vector in _rig_basis_overlay_vectors(armature, profile).items():
segments = _basis_arrow_segments(
@@ -944,6 +1107,21 @@ def _draw_rig_mapping_labels():
blf.position(font_id, co_2d.x + 6, co_2d.y + 6, 0)
blf.draw(font_id, label)
+ for hand_data in _hand_mapping_overlay_data(armature, profile):
+ co_2d = view3d_utils.location_3d_to_region_2d(
+ region, rv3d, hand_data["center"])
+ if co_2d is None:
+ continue
+ label = _HAND_LABELS.get(hand_data["role"], "Hand")
+ color = _CHAIN_COLORS.get(
+ hand_data["role"], (1.0, 1.0, 1.0, 0.9))
+ blf.color(font_id, 0.0, 0.0, 0.0, 0.75)
+ blf.position(font_id, co_2d.x + 8, co_2d.y + 4, 0)
+ blf.draw(font_id, label)
+ blf.color(font_id, color[0], color[1], color[2], 0.98)
+ blf.position(font_id, co_2d.x + 6, co_2d.y + 6, 0)
+ blf.draw(font_id, label)
+
for name, vector in _rig_basis_overlay_vectors(armature, profile).items():
co_2d = view3d_utils.location_3d_to_region_2d(region, rv3d, vector["tip"])
if co_2d is None:
@@ -1072,20 +1250,51 @@ def _capsule_wire_segments(
return segments
-def _collision_proxy_bone_groups(proxy):
+def _collision_proxy_bone_groups(proxy, armature=None, profile=None):
groups = []
seen = set()
for name in proxy.get("body_bones", []):
if name not in seen:
seen.add(name)
- groups.append((name, "body"))
+ groups.append((name, "body", 0.0))
+ upper_arm_collision = (
+ armature.get(_UPPER_ARM_COLLISION_PROP, "DISABLED")
+ if armature else "DISABLED"
+ )
+ arm_correction_driver = (
+ armature.get(_ARM_CORRECTION_DRIVER_PROP, "AUTO")
+ if armature else "AUTO"
+ )
for role in ("left_arm", "right_arm"):
chain = proxy.get("arm_chains", {}).get(role, [])
- active_bones = set(_distal_arm_proxy_bones(chain))
+ active_bone_list, start_fractions = _arm_collision_probe_spec(
+ chain, upper_arm_collision)
+ active_bones = set(active_bone_list)
+ correction_driver_bone = None
+ if armature and profile:
+ correction_chain = _arm_correction_chain(
+ armature,
+ profile,
+ role,
+ chain,
+ driver_mode=arm_correction_driver,
+ )
+ if correction_chain:
+ correction_driver_bone = correction_chain[0]
for name in chain:
if name not in seen:
seen.add(name)
- groups.append((name, role if name in active_bones else "inactive"))
+ if name in active_bones:
+ display_role = role
+ elif name == correction_driver_bone:
+ display_role = "driver"
+ else:
+ display_role = "inactive"
+ groups.append((
+ name,
+ display_role,
+ float(start_fractions.get(name, 0.0)),
+ ))
return groups
@@ -1094,6 +1303,7 @@ def _draw_collision_proxy_overlay():
proxy = _cached_collision_proxy(armature)
if not armature or not proxy:
return
+ profile = _load_profile(armature)
shader = gpu.shader.from_builtin("UNIFORM_COLOR")
gpu.state.blend_set("ALPHA")
@@ -1101,10 +1311,14 @@ def _draw_collision_proxy_overlay():
gpu.state.depth_mask_set(False)
gpu.state.line_width_set(1.6)
try:
- for bone_name, role in _collision_proxy_bone_groups(proxy):
+ for bone_name, role, start_fraction in _collision_proxy_bone_groups(
+ proxy, armature=armature, profile=profile):
capsule = _proxy_pose_capsule(armature, proxy, bone_name)
if not capsule:
continue
+ if start_fraction > 0.0:
+ capsule["start"] = capsule["start"].lerp(
+ capsule["end"], start_fraction)
segments = _capsule_wire_segments(
capsule["start"],
capsule["end"],
@@ -1255,6 +1469,57 @@ def _active_or_selected_armature(context):
return None
+def _initialize_collision_operator_settings(operator, context):
+ armature = _active_or_selected_armature(context)
+ if not armature:
+ return
+ stored_values = (
+ (
+ "collision_segment_mode",
+ _COLLISION_SEGMENT_MODE_PROP,
+ {"BONE_TAILS", "JOINT_HEADS"},
+ ),
+ (
+ "upper_arm_collision",
+ _UPPER_ARM_COLLISION_PROP,
+ {"DISABLED", "DISTAL", "FULL"},
+ ),
+ (
+ "arm_correction_driver",
+ _ARM_CORRECTION_DRIVER_PROP,
+ {"AUTO", "SHOULDER", "UPPER_ARM"},
+ ),
+ )
+ for attribute, property_name, valid_values in stored_values:
+ value = armature.get(property_name)
+ if hasattr(operator, attribute) and value in valid_values:
+ setattr(operator, attribute, value)
+ if (
+ hasattr(operator, "match_hand_orientation")
+ and _HAND_MATCH_ENABLED_PROP in armature):
+ operator.match_hand_orientation = bool(
+ armature[_HAND_MATCH_ENABLED_PROP])
+ if (
+ hasattr(operator, "hand_match_strength")
+ and _HAND_MATCH_STRENGTH_PROP in armature):
+ operator.hand_match_strength = max(
+ 0.0,
+ min(1.0, float(armature[_HAND_MATCH_STRENGTH_PROP])),
+ )
+ if (
+ hasattr(operator, "hand_roll_mode")
+ and armature.get(_HAND_ROLL_MODE_PROP) in {
+ "WRIST", "FOREARM", "TWIST_CHAIN", "LIMITED"}):
+ operator.hand_roll_mode = armature[_HAND_ROLL_MODE_PROP]
+ if (
+ hasattr(operator, "hand_roll_limit")
+ and _HAND_ROLL_LIMIT_PROP in armature):
+ operator.hand_roll_limit = max(
+ 0.0,
+ min(180.0, float(armature[_HAND_ROLL_LIMIT_PROP])),
+ )
+
+
def _common_chain_pairs(
source_profile, target_profile, swap_target_sides=False,
source_armature=None, target_armature=None, trim_feet=False):
@@ -1556,7 +1821,8 @@ def _proxy_radius_limits(bone, role, target_height):
return target_height * 0.010, max(target_height * 0.075, bone_length * 0.42)
-def _build_collision_proxy(armature, target_profile):
+def _build_collision_proxy(
+ armature, target_profile, segment_mode="BONE_TAILS"):
"""Estimate a compact rest-space capsule rig from dominant skin weights."""
chains = _profile_chains(target_profile)
body_bones = []
@@ -1576,6 +1842,10 @@ def _build_collision_proxy(armature, target_profile):
terminal_arm_bones = [
chain[-1] for chain in arm_chains.values() if chain
]
+ segment_end_bones = {}
+ for chain in [body_bones, *arm_chains.values()]:
+ for name, next_name in zip(chain, chain[1:]):
+ segment_end_bones[name] = next_name
proxy_bones = list(body_bones)
for chain in arm_chains.values():
@@ -1620,8 +1890,19 @@ def _build_collision_proxy(armature, target_profile):
if not bone:
continue
point = to_armature @ vertex.co
+ segment_end = bone.tail_local
+ if (
+ segment_mode == "JOINT_HEADS"
+ and dominant_name not in terminal_arm_bones):
+ next_name = segment_end_bones.get(dominant_name)
+ next_bone = (
+ armature.data.bones.get(next_name)
+ if next_name else None
+ )
+ if next_bone:
+ segment_end = next_bone.head_local
distance, parameter = _point_segment_distance(
- point, bone.head_local, bone.tail_local)
+ point, bone.head_local, segment_end)
if parameter < -0.35 or parameter > 1.35:
continue
radial_samples[dominant_name].append(float(distance))
@@ -1654,6 +1935,8 @@ def _build_collision_proxy(armature, target_profile):
"version": _COLLISION_PROXY_VERSION,
"profile_signature": _profile_signature(target_profile),
"mesh_signature": _collision_mesh_signature(armature),
+ "segment_mode": segment_mode,
+ "segment_end_bones": segment_end_bones,
"height": float(target_height),
"body_bones": body_bones,
"arm_chains": arm_chains,
@@ -1669,7 +1952,13 @@ def _build_collision_proxy(armature, target_profile):
return proxy
-def _collision_proxy_for_armature(armature, target_profile, rebuild=False):
+def _collision_proxy_for_armature(
+ armature, target_profile, segment_mode=None, rebuild=False):
+ if segment_mode not in {"BONE_TAILS", "JOINT_HEADS"}:
+ segment_mode = armature.get(
+ _COLLISION_SEGMENT_MODE_PROP, "BONE_TAILS")
+ if segment_mode not in {"BONE_TAILS", "JOINT_HEADS"}:
+ segment_mode = "BONE_TAILS"
expected_profile = _profile_signature(target_profile)
expected_mesh = _collision_mesh_signature(armature)
if not rebuild:
@@ -1680,11 +1969,13 @@ def _collision_proxy_for_armature(armature, target_profile, rebuild=False):
if (
proxy.get("version") == _COLLISION_PROXY_VERSION
and proxy.get("profile_signature") == expected_profile
- and proxy.get("mesh_signature") == expected_mesh):
+ and proxy.get("mesh_signature") == expected_mesh
+ and proxy.get("segment_mode") == segment_mode):
return proxy
except Exception:
pass
- return _build_collision_proxy(armature, target_profile)
+ return _build_collision_proxy(
+ armature, target_profile, segment_mode=segment_mode)
def _profile_point(armature, bone_name, use_tail=False):
@@ -2000,11 +2291,19 @@ def _apply_pose_delta(
def _keyframe_retarget_pose(
target_armature, target_names, frame, copy_root_motion,
- key_locations=False, key_scale=False):
+ key_locations=False, key_scale=False,
+ previous_rotations=None):
for name in target_names:
pose_bone = target_armature.pose.bones.get(name)
if not pose_bone:
continue
+ if previous_rotations is not None:
+ rotation = pose_bone.rotation_quaternion.copy()
+ previous = previous_rotations.get(name)
+ if previous is not None:
+ rotation.make_compatible(previous)
+ pose_bone.rotation_quaternion = rotation
+ previous_rotations[name] = rotation.copy()
pose_bone.keyframe_insert(data_path="rotation_quaternion", frame=frame)
if copy_root_motion or key_locations:
pose_bone.keyframe_insert(data_path="location", frame=frame)
@@ -2209,9 +2508,25 @@ def _bake_rest_space_retarget(
collision_proxy=None, collision_adaptation=True,
collision_strength=0.75, collision_margin=0.008,
collision_iterations=2, collision_max_deviation=0.08,
- arm_correction_driver="AUTO"):
+ arm_correction_driver="AUTO",
+ upper_arm_collision="DISABLED",
+ match_hand_orientation=False, hand_match_strength=1.0,
+ hand_roll_mode="FOREARM", hand_roll_limit=60.0):
"""Bake parent-local motion deltas through corresponding reference frames."""
+ twist_helper_names = []
+ if match_hand_orientation:
+ twist_helper_names = _ensure_hand_roll_setup(
+ context,
+ target_armature,
+ target_profile,
+ hand_roll_mode,
+ )
+ else:
+ _configure_twist_helpers(
+ target_armature, target_profile, use_twist_chain=False)
target_names = _mapped_target_bones(pairs)
+ target_names.extend(
+ name for name in twist_helper_names if name not in target_names)
all_target_names = [pose_bone.name for pose_bone in target_armature.pose.bones]
source_height = _height_from_profile(source_armature, source_profile)
target_height = _height_from_profile(target_armature, target_profile)
@@ -2232,6 +2547,14 @@ def _bake_rest_space_retarget(
_profile_body_basis(source_armature, source_profile),
use_rest=source_reference_mode == "REST",
)
+ source_reference_hand_frames = {}
+ if match_hand_orientation:
+ source_reference_hand_frames = _hand_reference_body_frames(
+ source_armature,
+ source_profile,
+ _profile_rotation_basis(source_armature, source_profile),
+ use_rest=source_reference_mode == "REST",
+ )
if target_reference_pose.get("label") == "rest_pose":
_reset_target_pose(target_armature, all_target_names)
@@ -2245,12 +2568,21 @@ def _bake_rest_space_retarget(
_profile_body_basis(target_armature, target_profile),
use_rest=False,
)
+ target_reference_hand_frames = {}
+ if match_hand_orientation:
+ target_reference_hand_frames = _hand_reference_body_frames(
+ target_armature,
+ target_profile,
+ _profile_rotation_basis(target_armature, target_profile),
+ use_rest=False,
+ )
collision_baseline = {}
if collision_adaptation and collision_proxy:
collision_baseline = _capture_proxy_collision_baseline(
target_armature,
collision_proxy,
margin=collision_margin,
+ upper_arm_collision=upper_arm_collision,
)
target_reference_matrices = _armature_reference_matrices(target_armature)
records = _rest_space_pair_records(
@@ -2282,8 +2614,16 @@ def _bake_rest_space_retarget(
for role, driver in resolved_arm_drivers.items()
)
)
+ if collision_proxy:
+ print(
+ f"[StableGen] Collision proxy mode: "
+ f"segments={collision_proxy.get('segment_mode', 'BONE_TAILS').lower()}, "
+ f"upper_arm={upper_arm_collision.lower()}"
+ )
collision_adjusted_frames = 0
+ hand_matched_frames = 0
+ previous_keyed_rotations = {}
for frame in range(start, end + 1, frame_step):
context.scene.frame_set(frame)
context.view_layer.update()
@@ -2325,9 +2665,34 @@ def _bake_rest_space_retarget(
max_pose_deviation=collision_max_deviation,
accepted_penetrations=collision_baseline,
arm_correction_driver=arm_correction_driver,
+ upper_arm_collision=upper_arm_collision,
)
if adjusted:
collision_adjusted_frames += 1
+ if match_hand_orientation and hand_roll_mode == "TWIST_CHAIN":
+ _sync_twist_helpers_from_reference(
+ target_armature,
+ target_profile,
+ target_reference_matrices,
+ )
+ context.view_layer.update()
+ if match_hand_orientation and hand_match_strength > 0.0:
+ matched_hands = _match_hand_orientations(
+ context,
+ source_armature,
+ target_armature,
+ source_profile,
+ target_profile,
+ strength=hand_match_strength,
+ swap_target_sides=swap_target_sides,
+ use_reference_basis=True,
+ source_reference_body_frames=source_reference_hand_frames,
+ target_reference_body_frames=target_reference_hand_frames,
+ hand_roll_mode=hand_roll_mode,
+ hand_roll_limit=hand_roll_limit,
+ )
+ if matched_hands:
+ hand_matched_frames += 1
_keyframe_retarget_pose(
target_armature,
target_names,
@@ -2335,12 +2700,18 @@ def _bake_rest_space_retarget(
copy_root_motion=copy_root_motion,
key_locations=target_reference_pose.get("label") != "rest_pose",
key_scale=target_reference_pose.get("label") != "rest_pose",
+ previous_rotations=previous_keyed_rotations,
)
if collision_adaptation and collision_proxy:
print(
f"[StableGen] Skeletal proxy collision pass adjusted "
f"{collision_adjusted_frames} baked frame(s)."
)
+ if match_hand_orientation:
+ print(
+ f"[StableGen] Palm-frame matching adjusted "
+ f"{hand_matched_frames} baked frame(s)."
+ )
def _target_chain_key(source_chain_key, swap_target_sides=False):
@@ -2446,6 +2817,558 @@ def _limb_reference_body_directions(
return directions
+def _hand_digit_root_names(armature, hand_name):
+ """Find a palm branch with three to ten digit roots, allowing extra digits."""
+ hand_bone = armature.data.bones.get(hand_name) if hand_name else None
+ if not hand_bone:
+ return []
+ candidates = [(hand_bone, 0)]
+ cursor = 0
+ branching = []
+ while cursor < len(candidates):
+ bone, depth = candidates[cursor]
+ cursor += 1
+ children = list(bone.children)
+ if 3 <= len(children) <= 10:
+ branching.append((depth, -len(children), bone.name, children))
+ if depth < 3:
+ candidates.extend((child, depth + 1) for child in children)
+ if not branching:
+ return []
+ _depth, _count, _name, roots = min(branching)
+ return sorted(root.name for root in roots)
+
+
+def _hand_landmark_point(armature, bone_name, use_rest=False, use_tail=False):
+ if use_rest:
+ return _profile_point(armature, bone_name, use_tail=use_tail)
+ return _pose_point(armature, bone_name, use_tail=use_tail)
+
+
+def _hand_thumb_root_name(armature, hand_name, digit_roots=None):
+ """Identify the thumb by semantics or its rest-pose offset toward the wrist."""
+ digit_roots = list(
+ digit_roots or _hand_digit_root_names(armature, hand_name))
+ if len(digit_roots) < 3:
+ return None
+ for root_name in digit_roots:
+ normalized = _norm_name(root_name)
+ if "thumb" in normalized or "pollex" in normalized:
+ return root_name
+
+ wrist = _profile_point(armature, hand_name, use_tail=False)
+ points = {
+ name: _profile_point(armature, name, use_tail=False)
+ for name in digit_roots
+ }
+ if wrist is None or any(point is None for point in points.values()):
+ return None
+ center = sum(
+ points.values(), mathutils.Vector((0.0, 0.0, 0.0))) / len(points)
+ forward = center - wrist
+ if forward.length < 1e-6:
+ return None
+ forward.normalize()
+ return min(
+ digit_roots,
+ key=lambda name: (points[name] - wrist).dot(forward),
+ )
+
+
+def _hand_frame(armature, hand_name, use_rest=False):
+ digit_roots = _hand_digit_root_names(armature, hand_name)
+ if len(digit_roots) < 3:
+ return None
+ thumb_name = _hand_thumb_root_name(
+ armature, hand_name, digit_roots=digit_roots)
+ if not thumb_name:
+ return None
+ wrist = _hand_landmark_point(armature, hand_name, use_rest=use_rest)
+ root_points = [
+ _hand_landmark_point(armature, name, use_rest=use_rest)
+ for name in digit_roots
+ ]
+ if wrist is None or any(point is None for point in root_points):
+ return None
+
+ def frame_from_points(points):
+ center = sum(
+ points, mathutils.Vector((0.0, 0.0, 0.0))) / len(points)
+ forward = center - wrist
+ if forward.length < 1e-6:
+ return None
+ forward.normalize()
+ thumb_index = digit_roots.index(thumb_name)
+ thumb_point = points[thumb_index]
+ other_points = [
+ point for index, point in enumerate(points)
+ if index != thumb_index
+ ]
+ other_center = sum(
+ other_points,
+ mathutils.Vector((0.0, 0.0, 0.0)),
+ ) / len(other_points)
+ across = thumb_point - other_center
+ across -= forward * across.dot(forward)
+ if across.length < 1e-6:
+ return None
+ across.normalize()
+ normal = across.cross(forward)
+ if normal.length < 1e-6:
+ return None
+ normal.normalize()
+ forward = normal.cross(across).normalized()
+ return mathutils.Matrix((across, forward, normal)).transposed()
+
+ frame = frame_from_points(root_points)
+ if frame is None:
+ root_points = [
+ _hand_landmark_point(
+ armature, name, use_rest=use_rest, use_tail=True)
+ for name in digit_roots
+ ]
+ if any(point is None for point in root_points):
+ return None
+ frame = frame_from_points(root_points)
+ return frame
+
+
+def _hand_reference_body_frames(armature, profile, basis, use_rest=False):
+ frames = {}
+ chains = _profile_chains(profile)
+ for role in ("left_arm", "right_arm"):
+ chain = chains.get(role, [])
+ if not chain:
+ continue
+ frame = _hand_frame(armature, chain[-1], use_rest=use_rest)
+ if frame is not None:
+ frames[role] = basis.inverted_safe() @ frame
+ return frames
+
+
+def _quaternion_twist_about_axis(rotation, axis):
+ """Extract the shortest quaternion component around an armature-space axis."""
+ if axis is None or axis.length < 1e-6:
+ return None
+ axis = axis.normalized()
+ rotation = rotation.normalized()
+ if rotation.w < 0.0:
+ rotation = mathutils.Quaternion(
+ (-rotation.w, -rotation.x, -rotation.y, -rotation.z))
+ vector = mathutils.Vector((rotation.x, rotation.y, rotation.z))
+ projected = axis * vector.dot(axis)
+ twist = mathutils.Quaternion(
+ (rotation.w, projected.x, projected.y, projected.z))
+ if twist.magnitude < 1e-8:
+ return None
+ return twist.normalized()
+
+
+def _twist_helper_specs(role):
+ side = "L" if role == "left_arm" else "R"
+ return (
+ (f"SG_{side}_ForearmTwist_00", 0.0),
+ (f"SG_{side}_ForearmTwist_33", 1.0 / 3.0),
+ (f"SG_{side}_ForearmTwist_67", 2.0 / 3.0),
+ )
+
+
+def _twist_helper_names(armature, profile):
+ names = []
+ chains = _profile_chains(profile)
+ for role in ("left_arm", "right_arm"):
+ if len(chains.get(role, [])) < 2:
+ continue
+ names.extend(
+ name for name, _fraction in _twist_helper_specs(role)
+ if armature.data.bones.get(name)
+ )
+ return names
+
+
+def _twist_follow_constraint(pose_bone):
+ if not pose_bone:
+ return None
+ constraint = pose_bone.constraints.get("SG_Follow_Forearm")
+ if constraint and constraint.type == "COPY_TRANSFORMS":
+ return constraint
+ constraint = pose_bone.constraints.new("COPY_TRANSFORMS")
+ constraint.name = "SG_Follow_Forearm"
+ return constraint
+
+
+def _ensure_twist_helper_bones(context, armature, profile):
+ chains = _profile_chains(profile)
+ required = []
+ for role in ("left_arm", "right_arm"):
+ chain = chains.get(role, [])
+ if len(chain) < 2:
+ continue
+ required.extend(
+ (role, chain[-2], name, fraction)
+ for name, fraction in _twist_helper_specs(role)
+ )
+ if not required:
+ return []
+
+ missing = [
+ item for item in required
+ if not armature.data.bones.get(item[2])
+ ]
+ if missing:
+ original_active = context.view_layer.objects.active
+ original_selection = list(context.selected_objects)
+ try:
+ if bpy.ops.object.mode_set.poll():
+ bpy.ops.object.mode_set(mode="OBJECT")
+ bpy.ops.object.select_all(action="DESELECT")
+ armature.select_set(True)
+ context.view_layer.objects.active = armature
+ bpy.ops.object.mode_set(mode="EDIT")
+ edit_bones = armature.data.edit_bones
+ for _role, forearm_name, helper_name, _fraction in missing:
+ forearm = edit_bones.get(forearm_name)
+ if not forearm or edit_bones.get(helper_name):
+ continue
+ helper = edit_bones.new(helper_name)
+ helper.head = forearm.head
+ helper.tail = forearm.tail
+ helper.roll = forearm.roll
+ helper.parent = None
+ helper.use_connect = False
+ helper.use_deform = True
+ helper.head_radius = forearm.head_radius
+ helper.tail_radius = forearm.tail_radius
+ helper.envelope_distance = forearm.envelope_distance
+ helper.envelope_weight = forearm.envelope_weight
+ bpy.ops.object.mode_set(mode="OBJECT")
+ finally:
+ try:
+ if bpy.ops.object.mode_set.poll():
+ bpy.ops.object.mode_set(mode="OBJECT")
+ except Exception:
+ pass
+ bpy.ops.object.select_all(action="DESELECT")
+ for obj in original_selection:
+ if obj.name in bpy.data.objects:
+ obj.select_set(True)
+ if original_active and original_active.name in bpy.data.objects:
+ context.view_layer.objects.active = original_active
+
+ helper_names = []
+ for role, forearm_name, helper_name, fraction in required:
+ data_bone = armature.data.bones.get(helper_name)
+ pose_bone = armature.pose.bones.get(helper_name)
+ if not data_bone or not pose_bone:
+ continue
+ data_bone["sg_twist_source"] = forearm_name
+ data_bone["sg_twist_fraction"] = float(fraction)
+ data_bone["sg_twist_role"] = role
+ pose_bone.rotation_mode = "QUATERNION"
+ constraint = _twist_follow_constraint(pose_bone)
+ constraint.target = armature
+ constraint.subtarget = forearm_name
+ constraint.target_space = "POSE"
+ constraint.owner_space = "POSE"
+ constraint.influence = 1.0
+ helper_names.append(helper_name)
+ context.view_layer.update()
+ return helper_names
+
+
+def _armature_deformed_meshes(armature):
+ result = []
+ for obj in bpy.data.objects:
+ if obj.type != "MESH":
+ continue
+ if any(
+ modifier.type == "ARMATURE" and modifier.object == armature
+ for modifier in obj.modifiers):
+ result.append(obj)
+ return result
+
+
+def _redistribute_forearm_twist_weights(armature, profile):
+ chains = _profile_chains(profile)
+ total_vertices = 0
+ for mesh_obj in _armature_deformed_meshes(armature):
+ mesh_to_armature = armature.matrix_world.inverted_safe() @ mesh_obj.matrix_world
+ for modifier in mesh_obj.modifiers:
+ if modifier.type == "ARMATURE" and modifier.object == armature:
+ modifier.use_deform_preserve_volume = True
+
+ for role in ("left_arm", "right_arm"):
+ chain = chains.get(role, [])
+ if len(chain) < 2:
+ continue
+ forearm_name = chain[-2]
+ hand_name = chain[-1]
+ marker = f"sg_twist_weights_{armature.name}_{role}"
+ if mesh_obj.get(marker) == _TWIST_CHAIN_VERSION:
+ continue
+ source_group = mesh_obj.vertex_groups.get(forearm_name)
+ forearm = armature.data.bones.get(forearm_name)
+ hand = armature.data.bones.get(hand_name)
+ if not source_group or not forearm or not hand:
+ continue
+ helper_groups = [
+ mesh_obj.vertex_groups.get(name)
+ or mesh_obj.vertex_groups.new(name=name)
+ for name, _fraction in _twist_helper_specs(role)
+ ]
+ elbow = forearm.head_local.copy()
+ wrist = hand.head_local.copy()
+ axis = wrist - elbow
+ length_squared = axis.length_squared
+ if length_squared < 1e-12:
+ continue
+
+ assignments = []
+ source_index = source_group.index
+ for vertex in mesh_obj.data.vertices:
+ source_weight = next(
+ (
+ item.weight for item in vertex.groups
+ if item.group == source_index
+ ),
+ 0.0,
+ )
+ if source_weight <= 1e-8:
+ continue
+ point = mesh_to_armature @ vertex.co
+ parameter = max(
+ 0.0,
+ min(1.0, (point - elbow).dot(axis) / length_squared),
+ )
+ scaled = parameter * 3.0
+ lower = min(2, int(math.floor(scaled)))
+ blend = scaled - lower
+ weights = [0.0, 0.0, 0.0, 0.0]
+ weights[lower] = 1.0 - blend
+ weights[lower + 1] = blend
+ assignments.append((vertex.index, source_weight, weights))
+
+ for vertex_index, source_weight, weights in assignments:
+ for group, weight in zip(helper_groups, weights[:3]):
+ if weight > 1e-8:
+ group.add(
+ [vertex_index], source_weight * weight, "REPLACE")
+ else:
+ try:
+ group.remove([vertex_index])
+ except RuntimeError:
+ pass
+ if weights[3] > 1e-8:
+ source_group.add(
+ [vertex_index], source_weight * weights[3], "REPLACE")
+ else:
+ source_group.remove([vertex_index])
+ mesh_obj[marker] = _TWIST_CHAIN_VERSION
+ total_vertices += len(assignments)
+ if total_vertices:
+ print(
+ f"[StableGen] Distributed {total_vertices} forearm-weighted "
+ "vertices across generated twist chains."
+ )
+ return total_vertices
+
+
+def _configure_twist_helpers(armature, profile, use_twist_chain):
+ chains = _profile_chains(profile)
+ for role in ("left_arm", "right_arm"):
+ chain = chains.get(role, [])
+ if len(chain) < 2:
+ continue
+ forearm_name = chain[-2]
+ forearm_pose = armature.pose.bones.get(forearm_name)
+ for helper_name, _fraction in _twist_helper_specs(role):
+ pose_bone = armature.pose.bones.get(helper_name)
+ if not pose_bone:
+ continue
+ constraint = _twist_follow_constraint(pose_bone)
+ constraint.target = armature
+ constraint.subtarget = forearm_name
+ constraint.target_space = "POSE"
+ constraint.owner_space = "POSE"
+ if use_twist_chain:
+ followed_matrix = (
+ forearm_pose.matrix.copy() if forearm_pose else None)
+ constraint.influence = 0.0
+ if followed_matrix is not None:
+ pose_bone.matrix = followed_matrix
+ else:
+ constraint.influence = 1.0
+
+
+def _ensure_hand_roll_setup(context, armature, profile, hand_roll_mode):
+ use_twist_chain = hand_roll_mode == "TWIST_CHAIN"
+ if use_twist_chain:
+ _ensure_twist_helper_bones(context, armature, profile)
+ _redistribute_forearm_twist_weights(armature, profile)
+ armature[_TWIST_CHAIN_VERSION_PROP] = _TWIST_CHAIN_VERSION
+ _configure_twist_helpers(
+ armature,
+ profile,
+ use_twist_chain=use_twist_chain,
+ )
+ context.view_layer.update()
+ return _twist_helper_names(armature, profile) if use_twist_chain else []
+
+
+def _apply_twist_to_helper_pose(armature, role, twist):
+ for helper_name, fraction in _twist_helper_specs(role):
+ pose_bone = armature.pose.bones.get(helper_name)
+ if not pose_bone:
+ continue
+ partial_twist = mathutils.Quaternion(
+ (1.0, 0.0, 0.0, 0.0)).slerp(twist, fraction)
+ _rotate_pose_bone_in_armature_space(pose_bone, partial_twist)
+
+
+def _sync_twist_helpers_from_reference(
+ armature, profile, reference_matrices):
+ chains = _profile_chains(profile)
+ for role in ("left_arm", "right_arm"):
+ chain = chains.get(role, [])
+ if len(chain) < 2:
+ continue
+ forearm_pose = armature.pose.bones.get(chain[-2])
+ reference_forearm = reference_matrices.get(chain[-2])
+ if not forearm_pose or reference_forearm is None:
+ continue
+ motion_delta = forearm_pose.matrix @ reference_forearm.inverted_safe()
+ for helper_name, _fraction in _twist_helper_specs(role):
+ helper_pose = armature.pose.bones.get(helper_name)
+ reference_helper = reference_matrices.get(helper_name)
+ if helper_pose and reference_helper is not None:
+ helper_pose.matrix = motion_delta @ reference_helper
+
+
+def _sync_twist_helpers_to_forearms(armature, profile):
+ chains = _profile_chains(profile)
+ for role in ("left_arm", "right_arm"):
+ chain = chains.get(role, [])
+ if len(chain) < 2:
+ continue
+ forearm_pose = armature.pose.bones.get(chain[-2])
+ if not forearm_pose:
+ continue
+ for helper_name, _fraction in _twist_helper_specs(role):
+ helper_pose = armature.pose.bones.get(helper_name)
+ if helper_pose:
+ helper_pose.matrix = forearm_pose.matrix.copy()
+
+
+def _match_hand_orientations(
+ context, source_armature, target_armature,
+ source_profile, target_profile, strength=1.0,
+ swap_target_sides=False, use_reference_basis=True,
+ source_reference_body_frames=None,
+ target_reference_body_frames=None,
+ absolute_alignment=False,
+ hand_roll_mode="FOREARM", hand_roll_limit=60.0):
+ if use_reference_basis:
+ source_basis = _profile_rotation_basis(source_armature, source_profile)
+ target_basis = _profile_rotation_basis(target_armature, target_profile)
+ else:
+ source_basis = _pose_rotation_basis(source_armature, source_profile)
+ target_basis = _pose_rotation_basis(target_armature, target_profile)
+ source_chains = _profile_chains(source_profile)
+ target_chains = _profile_chains(target_profile)
+ strength = max(0.0, min(1.0, float(strength)))
+ hand_roll_mode = (
+ hand_roll_mode
+ if hand_roll_mode in {"WRIST", "FOREARM", "TWIST_CHAIN", "LIMITED"}
+ else "FOREARM"
+ )
+ hand_roll_limit = max(0.0, min(180.0, float(hand_roll_limit)))
+ matched = 0
+
+ for source_role in ("left_arm", "right_arm"):
+ target_role = _target_chain_key(
+ source_role, swap_target_sides=swap_target_sides)
+ source_chain = source_chains.get(source_role, [])
+ target_chain = target_chains.get(target_role, [])
+ if not source_chain or not target_chain:
+ continue
+ source_frame = _hand_frame(source_armature, source_chain[-1])
+ target_frame = _hand_frame(target_armature, target_chain[-1])
+ if source_frame is None or target_frame is None:
+ continue
+ source_body_frame = source_basis.inverted_safe() @ source_frame
+ source_reference = (source_reference_body_frames or {}).get(source_role)
+ target_reference = (target_reference_body_frames or {}).get(target_role)
+ if absolute_alignment:
+ desired_target_body_frame = source_body_frame
+ elif use_reference_basis and (
+ source_reference is None or target_reference is None):
+ continue
+ elif source_reference is not None and target_reference is not None:
+ # Transfer the reference-to-current palm rotation in body space.
+ source_delta = source_body_frame @ source_reference.inverted_safe()
+ desired_target_body_frame = source_delta @ target_reference
+ else:
+ desired_target_body_frame = source_body_frame
+ desired_target_frame = target_basis @ desired_target_body_frame
+ try:
+ # The pose-bone helper left-multiplies an armature-space rotation,
+ # so construct that delta explicitly in armature space. Quaternion
+ # rotation_difference() instead returns a local/right-side delta.
+ current_rotation = target_frame.to_quaternion()
+ desired_rotation = desired_target_frame.to_quaternion()
+ delta = desired_rotation @ current_rotation.inverted()
+ except ValueError:
+ continue
+ if strength < 1.0:
+ delta = mathutils.Quaternion((1.0, 0.0, 0.0, 0.0)).slerp(
+ delta, strength)
+ hand_pose = target_armature.pose.bones.get(target_chain[-1])
+ if not hand_pose:
+ continue
+ forearm_pose = (
+ target_armature.pose.bones.get(target_chain[-2])
+ if len(target_chain) >= 2 else None
+ )
+ forearm_axis = (
+ hand_pose.head - forearm_pose.head if forearm_pose else None)
+ twist = _quaternion_twist_about_axis(delta, forearm_axis)
+
+ if hand_roll_mode == "LIMITED" and twist is not None:
+ twist_angle = min(twist.angle, (2.0 * math.pi) - twist.angle)
+ limit_radians = math.radians(hand_roll_limit)
+ if twist_angle > limit_radians and twist_angle > 1e-8:
+ limited_twist = mathutils.Quaternion(
+ (1.0, 0.0, 0.0, 0.0)).slerp(
+ twist, limit_radians / twist_angle)
+ swing = delta @ twist.inverted()
+ delta = swing @ limited_twist
+ twist = limited_twist
+
+ applied_desired_rotation = delta @ current_rotation
+
+ if (
+ hand_roll_mode != "WRIST"
+ and forearm_pose is not None
+ and twist is not None):
+ _rotate_pose_bone_in_armature_space(forearm_pose, twist)
+ context.view_layer.update()
+ if hand_roll_mode == "TWIST_CHAIN" and twist is not None:
+ _apply_twist_to_helper_pose(
+ target_armature, target_role, twist)
+ context.view_layer.update()
+
+ updated_target_frame = _hand_frame(
+ target_armature, target_chain[-1])
+ if updated_target_frame is None:
+ continue
+ updated_rotation = updated_target_frame.to_quaternion()
+ residual = applied_desired_rotation @ updated_rotation.inverted()
+ _rotate_pose_bone_in_armature_space(hand_pose, residual)
+ context.view_layer.update()
+ matched += 1
+ return matched
+
+
def _rotate_pose_bone_in_armature_space(pose_bone, delta_quat):
loc, rot, scale = pose_bone.matrix.decompose()
pose_bone.rotation_mode = "QUATERNION"
@@ -2632,11 +3555,15 @@ def _proxy_pose_capsule(armature, proxy, bone_name, radius_scale=1.0):
if radius <= 1e-6:
return None
start = pose_bone.head.copy()
- end = (
- start.copy()
- if bone_name in set(proxy.get("terminal_arm_bones", []))
- else pose_bone.tail.copy()
- )
+ if bone_name in set(proxy.get("terminal_arm_bones", [])):
+ end = start.copy()
+ elif proxy.get("segment_mode") == "JOINT_HEADS":
+ end_name = proxy.get("segment_end_bones", {}).get(bone_name)
+ end_pose_bone = (
+ armature.pose.bones.get(end_name) if end_name else None)
+ end = end_pose_bone.head.copy() if end_pose_bone else pose_bone.tail.copy()
+ else:
+ end = pose_bone.tail.copy()
return {
"bone": bone_name,
"start": start,
@@ -2645,7 +3572,9 @@ def _proxy_pose_capsule(armature, proxy, bone_name, radius_scale=1.0):
}
-def _proxy_capsules_for_bones(armature, proxy, bone_names, radius_scale=1.0):
+def _proxy_capsules_for_bones(
+ armature, proxy, bone_names, radius_scale=1.0,
+ start_fractions=None):
result = []
seen = set()
for name in bone_names:
@@ -2655,6 +3584,11 @@ def _proxy_capsules_for_bones(armature, proxy, bone_names, radius_scale=1.0):
capsule = _proxy_pose_capsule(
armature, proxy, name, radius_scale=radius_scale)
if capsule:
+ start_fraction = float((start_fractions or {}).get(name, 0.0))
+ if start_fraction > 0.0:
+ start_fraction = max(0.0, min(0.95, start_fraction))
+ capsule["start"] = capsule["start"].lerp(
+ capsule["end"], start_fraction)
result.append(capsule)
return result
@@ -2665,6 +3599,18 @@ def _distal_arm_proxy_bones(chain):
return chain[-2:] if len(chain) >= 2 else chain
+def _arm_collision_probe_spec(chain, upper_arm_collision="DISABLED"):
+ bones = list(_distal_arm_proxy_bones(chain))
+ start_fractions = {}
+ if upper_arm_collision in {"DISTAL", "FULL"} and len(chain) >= 3:
+ upper_arm = chain[-3]
+ if upper_arm not in bones:
+ bones.insert(0, upper_arm)
+ if upper_arm_collision == "DISTAL":
+ start_fractions[upper_arm] = 0.25
+ return bones, start_fractions
+
+
def _capsule_pair_key(moving, obstacle):
return f"{moving['bone']}|{obstacle['bone']}"
@@ -2680,7 +3626,8 @@ def _capsule_pair_penetration(moving, obstacle, margin):
def _capture_proxy_collision_baseline(
- target_armature, collision_proxy, margin=0.0, radius_scale=1.0):
+ target_armature, collision_proxy, margin=0.0, radius_scale=1.0,
+ upper_arm_collision="DISABLED"):
"""Record intersections that already exist in an accepted reference pose."""
if not collision_proxy:
return {}
@@ -2696,18 +3643,24 @@ def _capture_proxy_collision_baseline(
)
baseline = {}
for role in ("left_arm", "right_arm"):
+ moving_bones, moving_start_fractions = _arm_collision_probe_spec(
+ arm_chains.get(role, []), upper_arm_collision)
moving_capsules = _proxy_capsules_for_bones(
target_armature,
collision_proxy,
- _distal_arm_proxy_bones(arm_chains.get(role, [])),
+ moving_bones,
radius_scale=radius_scale,
+ start_fractions=moving_start_fractions,
)
other_role = "right_arm" if role == "left_arm" else "left_arm"
+ other_bones, other_start_fractions = _arm_collision_probe_spec(
+ arm_chains.get(other_role, []), upper_arm_collision)
other_capsules = _proxy_capsules_for_bones(
target_armature,
collision_proxy,
- _distal_arm_proxy_bones(arm_chains.get(other_role, [])),
+ other_bones,
radius_scale=radius_scale,
+ start_fractions=other_start_fractions,
)
for moving in moving_capsules:
for obstacle in body_capsules + other_capsules:
@@ -2752,7 +3705,8 @@ def _resolve_skeletal_proxy_collisions(
context, target_armature, target_profile, collision_proxy,
strength=0.75, margin=0.008, iterations=2,
max_pose_deviation=0.08, radius_scale=1.0,
- accepted_penetrations=None, arm_correction_driver="AUTO"):
+ accepted_penetrations=None, arm_correction_driver="AUTO",
+ upper_arm_collision="DISABLED"):
"""Push distal arm capsules out of body/opposite-arm proxy capsules."""
if not collision_proxy:
return 0
@@ -2800,18 +3754,24 @@ def _resolve_skeletal_proxy_collisions(
original_endpoint = original_endpoints.get(role)
if endpoint is None or original_endpoint is None:
continue
+ moving_bones, moving_start_fractions = _arm_collision_probe_spec(
+ chain, upper_arm_collision)
moving_capsules = _proxy_capsules_for_bones(
target_armature,
collision_proxy,
- _distal_arm_proxy_bones(chain),
+ moving_bones,
radius_scale=radius_scale,
+ start_fractions=moving_start_fractions,
)
other_role = "right_arm" if role == "left_arm" else "left_arm"
+ other_bones, other_start_fractions = _arm_collision_probe_spec(
+ arm_chains.get(other_role, []), upper_arm_collision)
other_capsules = _proxy_capsules_for_bones(
target_armature,
collision_proxy,
- _distal_arm_proxy_bones(arm_chains.get(other_role, [])),
+ other_bones,
radius_scale=radius_scale,
+ start_fractions=other_start_fractions,
)
fallback = left_axis if role == "left_arm" else -left_axis
push = _strongest_capsule_push(
@@ -2847,7 +3807,8 @@ def _resolve_skeletal_proxy_collisions(
def _protect_reference_pose_clearance(
context, target_armature, target_profile, clearance=1.0,
collision_proxy=None, accepted_penetrations=None,
- arm_correction_driver="AUTO"):
+ arm_correction_driver="AUTO",
+ upper_arm_collision="DISABLED"):
"""Keep matched hands outside conservative torso and hand proxy colliders."""
if collision_proxy:
return _resolve_skeletal_proxy_collisions(
@@ -2862,6 +3823,7 @@ def _protect_reference_pose_clearance(
radius_scale=clearance,
accepted_penetrations=accepted_penetrations,
arm_correction_driver=arm_correction_driver,
+ upper_arm_collision=upper_arm_collision,
)
chains = _profile_chains(target_profile)
@@ -2946,7 +3908,20 @@ def _match_source_reference_pose(
context, source_armature, target_armature, pairs,
source_profile, target_profile, strength=1.0,
swap_target_sides=False, protect_mesh=True, clearance=1.0,
- collision_proxy=None, arm_correction_driver="AUTO"):
+ collision_proxy=None, arm_correction_driver="AUTO",
+ upper_arm_collision="DISABLED",
+ match_hand_orientation=False, hand_match_strength=1.0,
+ hand_roll_mode="FOREARM", hand_roll_limit=60.0):
+ if match_hand_orientation:
+ _ensure_hand_roll_setup(
+ context,
+ target_armature,
+ target_profile,
+ hand_roll_mode,
+ )
+ else:
+ _configure_twist_helpers(
+ target_armature, target_profile, use_twist_chain=False)
target_names = _mapped_target_bones(pairs)
all_target_names = [pose_bone.name for pose_bone in target_armature.pose.bones]
source_height = _height_from_profile(source_armature, source_profile)
@@ -2955,6 +3930,21 @@ def _match_source_reference_pose(
_reset_target_pose(target_armature, all_target_names)
context.view_layer.update()
+ source_reference_hand_frames = {}
+ target_reference_hand_frames = {}
+ if match_hand_orientation:
+ source_reference_hand_frames = _hand_reference_body_frames(
+ source_armature,
+ source_profile,
+ _profile_rotation_basis(source_armature, source_profile),
+ use_rest=True,
+ )
+ target_reference_hand_frames = _hand_reference_body_frames(
+ target_armature,
+ target_profile,
+ _profile_rotation_basis(target_armature, target_profile),
+ use_rest=False,
+ )
collision_baseline = {}
if protect_mesh and collision_proxy:
collision_baseline = _capture_proxy_collision_baseline(
@@ -2962,6 +3952,7 @@ def _match_source_reference_pose(
collision_proxy,
margin=0.01,
radius_scale=clearance,
+ upper_arm_collision=upper_arm_collision,
)
source_baseline = _source_rest_pose_baseline(source_armature, pairs)
source_basis = _profile_rotation_basis(source_armature, source_profile)
@@ -2999,12 +3990,37 @@ def _match_source_reference_pose(
collision_proxy=collision_proxy,
accepted_penetrations=collision_baseline,
arm_correction_driver=arm_correction_driver,
+ upper_arm_collision=upper_arm_collision,
)
if adjusted:
print(
f"[StableGen] Reference clearance adjusted {adjusted} arm chain(s) "
"away from skeletal proxy colliders."
)
+ if match_hand_orientation and hand_match_strength > 0.0:
+ if hand_roll_mode == "TWIST_CHAIN":
+ _sync_twist_helpers_to_forearms(
+ target_armature, target_profile)
+ context.view_layer.update()
+ matched_hands = _match_hand_orientations(
+ context,
+ source_armature,
+ target_armature,
+ source_profile,
+ target_profile,
+ strength=hand_match_strength,
+ swap_target_sides=swap_target_sides,
+ use_reference_basis=True,
+ source_reference_body_frames=source_reference_hand_frames,
+ target_reference_body_frames=target_reference_hand_frames,
+ absolute_alignment=True,
+ hand_roll_mode=hand_roll_mode,
+ hand_roll_limit=hand_roll_limit,
+ )
+ print(
+ f"[StableGen] Reference palm-frame matching adjusted "
+ f"{matched_hands} hand(s)."
+ )
return matched_chains
@@ -3382,6 +4398,50 @@ def _chain_point_diagnostics(armature, profile):
return result
+def _hand_mapping_diagnostics(armature, profile):
+ result = {}
+ for role in ("left_arm", "right_arm"):
+ chain = _profile_chains(profile).get(role, [])
+ if not chain:
+ continue
+ hand_name = chain[-1]
+ rest_frame = _hand_frame(armature, hand_name, use_rest=True)
+ pose_frame = _hand_frame(armature, hand_name, use_rest=False)
+ result[role] = {
+ "hand": hand_name,
+ "digit_roots": _hand_digit_root_names(armature, hand_name),
+ "thumb_root": _hand_thumb_root_name(armature, hand_name),
+ "rest_palm_frame": (
+ _matrix3_to_rows(rest_frame) if rest_frame is not None else None
+ ),
+ "pose_palm_frame": (
+ _matrix3_to_rows(pose_frame) if pose_frame is not None else None
+ ),
+ }
+ return result
+
+
+def _retarget_setting_diagnostics(armature):
+ return {
+ "match_hand_orientation": bool(
+ armature.get(_HAND_MATCH_ENABLED_PROP, False)),
+ "hand_match_strength": float(
+ armature.get(_HAND_MATCH_STRENGTH_PROP, 1.0)),
+ "hand_match_algorithm_version": _HAND_MATCH_ALGORITHM_VERSION,
+ "hand_roll_mode": armature.get(_HAND_ROLL_MODE_PROP, "FOREARM"),
+ "hand_roll_limit": float(
+ armature.get(_HAND_ROLL_LIMIT_PROP, 60.0)),
+ "twist_chain_version": int(
+ armature.get(_TWIST_CHAIN_VERSION_PROP, 0)),
+ "collision_segment_mode": armature.get(
+ _COLLISION_SEGMENT_MODE_PROP, "BONE_TAILS"),
+ "upper_arm_collision": armature.get(
+ _UPPER_ARM_COLLISION_PROP, "DISABLED"),
+ "arm_correction_driver": armature.get(
+ _ARM_CORRECTION_DRIVER_PROP, "AUTO"),
+ }
+
+
def _alignment_diagnostics(source_armature, source_profile, target_armature, target_profile, flip_target_forward=False):
source_basis = _profile_rotation_basis(source_armature, source_profile)
target_basis = _profile_rotation_basis(
@@ -3466,6 +4526,7 @@ def _animation_source_diagnostics(context, filepath, target_armature, target_pro
"bones": _bone_diagnostics(source_armature),
"pose_bones_at_start": _pose_bone_diagnostics(source_armature),
"basis": _basis_diagnostics(source_armature, source_profile),
+ "hands": _hand_mapping_diagnostics(source_armature, source_profile),
"mapping_options": _mapping_option_diagnostics(
source_armature,
source_profile,
@@ -3493,7 +4554,7 @@ def _retarget_bundle_diagnostics(context, armature, profile, target_fbx_path, an
)
return {
"schema": "stablegen_retarget_debug_bundle",
- "schema_version": 1,
+ "schema_version": 2,
"created_utc": datetime.utcnow().replace(microsecond=0).isoformat() + "Z",
"blender_version": bpy.app.version_string,
"stablegen_profile_version": _PROFILE_VERSION,
@@ -3515,6 +4576,8 @@ def _retarget_bundle_diagnostics(context, armature, profile, target_fbx_path, an
"bones": _bone_diagnostics(armature),
"pose_bones": _pose_bone_diagnostics(armature),
"chains": _chain_point_diagnostics(armature, profile),
+ "hands": _hand_mapping_diagnostics(armature, profile),
+ "retarget_settings": _retarget_setting_diagnostics(armature),
"stored_reference_pose": stored_reference,
"current_reference_pose": current_reference,
},
@@ -3841,6 +4904,38 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
max=1.0,
) # type: ignore
+ match_hand_orientation: bpy.props.BoolProperty(
+ name="Match Hand Orientation",
+ description=(
+ "Align palm frames when both rigs expose at least three digit branches; "
+ "supports generated hands with additional digits"
+ ),
+ default=False,
+ ) # type: ignore
+
+ hand_match_strength: bpy.props.FloatProperty(
+ name="Hand Match Strength",
+ description="How strongly explicit palm-frame orientation is applied",
+ default=1.0,
+ min=0.0,
+ max=1.0,
+ ) # type: ignore
+
+ hand_roll_mode: bpy.props.EnumProperty(
+ name="Hand Roll Handling",
+ description="Choose where palm roll is applied and how the mesh is protected",
+ items=_HAND_ROLL_MODE_ITEMS,
+ default="FOREARM",
+ ) # type: ignore
+
+ hand_roll_limit: bpy.props.FloatProperty(
+ name="Maximum Hand Roll (Degrees)",
+ description="Maximum axial palm correction transferred in Limited Roll mode",
+ default=60.0,
+ min=0.0,
+ max=180.0,
+ ) # type: ignore
+
arm_correction_driver: bpy.props.EnumProperty(
name="Arm Correction Driver",
description="Choose which joint post-processing may rotate to position each wrist",
@@ -3848,6 +4943,20 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
default="AUTO",
) # type: ignore
+ collision_segment_mode: bpy.props.EnumProperty(
+ name="Proxy Segments",
+ description="Choose how skeletal collision capsule endpoints are constructed",
+ items=_COLLISION_SEGMENT_MODE_ITEMS,
+ default="BONE_TAILS",
+ ) # type: ignore
+
+ upper_arm_collision: bpy.props.EnumProperty(
+ name="Upper Arm Collision",
+ description="Choose how much of the upper-arm capsule participates in collision tests",
+ items=_UPPER_ARM_COLLISION_ITEMS,
+ default="DISABLED",
+ ) # type: ignore
+
store_reference: bpy.props.BoolProperty(
name="Store As Ref Pose",
description="Save the matched target pose as the retarget reference pose immediately",
@@ -3891,6 +5000,7 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
return True
def invoke(self, context, event):
+ _initialize_collision_operator_settings(self, context)
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
@@ -3900,10 +5010,24 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
layout.prop(self, "match_strength")
if self.match_engine == "REFERENCE_AWARE":
layout.prop(self, "arm_correction_driver")
+ layout.prop(self, "match_hand_orientation")
+ if self.match_hand_orientation:
+ layout.prop(self, "hand_match_strength")
+ layout.prop(self, "hand_roll_mode")
+ if self.hand_roll_mode == "LIMITED":
+ layout.prop(self, "hand_roll_limit")
+ elif self.hand_roll_mode == "TWIST_CHAIN":
+ layout.label(
+ text="Creates deform bones and redistributes forearm weights",
+ icon="INFO",
+ )
layout.prop(self, "store_reference")
layout.prop(self, "protect_mesh")
if self.protect_mesh:
layout.prop(self, "clearance")
+ if self.match_engine == "REFERENCE_AWARE":
+ layout.prop(self, "collision_segment_mode")
+ layout.prop(self, "upper_arm_collision")
if self.match_engine == "LEGACY":
layout.prop(self, "swap_target_sides")
layout.prop(self, "keep_source_rig")
@@ -3950,10 +5074,28 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
context.scene.frame_set(start)
context.view_layer.update()
+ effective_hand_match = (
+ self.match_engine == "REFERENCE_AWARE"
+ and self.match_hand_orientation
+ )
+ target_armature[_HAND_MATCH_ENABLED_PROP] = effective_hand_match
+ target_armature[_HAND_MATCH_STRENGTH_PROP] = self.hand_match_strength
+ target_armature[_HAND_ROLL_MODE_PROP] = self.hand_roll_mode
+ target_armature[_HAND_ROLL_LIMIT_PROP] = self.hand_roll_limit
+
collision_proxy = None
if self.protect_mesh and self.match_engine == "REFERENCE_AWARE":
+ target_armature[_COLLISION_SEGMENT_MODE_PROP] = (
+ self.collision_segment_mode)
+ target_armature[_UPPER_ARM_COLLISION_PROP] = (
+ self.upper_arm_collision)
+ target_armature[_ARM_CORRECTION_DRIVER_PROP] = (
+ self.arm_correction_driver)
collision_proxy = _collision_proxy_for_armature(
- target_armature, target_profile)
+ target_armature,
+ target_profile,
+ segment_mode=self.collision_segment_mode,
+ )
print(f"[StableGen] Source reference rig profile for {source_armature.name}: {_profile_summary(source_profile)}")
print(f"[StableGen] Target rig profile for {target_armature.name}: {_profile_summary(target_profile)}")
@@ -3975,6 +5117,11 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
if self.match_engine == "REFERENCE_AWARE"
else "SHOULDER"
),
+ upper_arm_collision=self.upper_arm_collision,
+ match_hand_orientation=effective_hand_match,
+ hand_match_strength=self.hand_match_strength,
+ hand_roll_mode=self.hand_roll_mode,
+ hand_roll_limit=self.hand_roll_limit,
)
if self.store_reference:
@@ -3988,6 +5135,10 @@ class StableGenMatchSourceReferencePose(bpy.types.Operator):
start,
"START_FRAME",
swap_target_sides=effective_swap,
+ match_hand_orientation=effective_hand_match,
+ hand_match_strength=self.hand_match_strength,
+ hand_roll_mode=self.hand_roll_mode,
+ hand_roll_limit=self.hand_roll_limit,
),
)
if not reference_pose or not reference_pose.get("bones"):
@@ -4064,7 +5215,7 @@ class StableGenToggleRigMappingOverlay(bpy.types.Operator):
class StableGenToggleCollisionProxyOverlay(bpy.types.Operator):
- """Show collision capsules; gray proximal arm capsules are visualization-only."""
+ """Show collision capsules; blue is driver-only and gray is inactive."""
bl_idname = "stablegen.toggle_collision_proxy_overlay"
bl_label = "Show Collision Proxy"
@@ -4395,6 +5546,38 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
max=1.0,
) # type: ignore
+ match_hand_orientation: bpy.props.BoolProperty(
+ name="Match Hand Orientation",
+ description=(
+ "Align palm frames when both rigs expose at least three digit branches; "
+ "supports generated hands with additional digits"
+ ),
+ default=False,
+ ) # type: ignore
+
+ hand_match_strength: bpy.props.FloatProperty(
+ name="Hand Match Strength",
+ description="How strongly explicit palm-frame orientation is applied",
+ default=1.0,
+ min=0.0,
+ max=1.0,
+ ) # type: ignore
+
+ hand_roll_mode: bpy.props.EnumProperty(
+ name="Hand Roll Handling",
+ description="Choose where palm roll is applied and how the mesh is protected",
+ items=_HAND_ROLL_MODE_ITEMS,
+ default="FOREARM",
+ ) # type: ignore
+
+ hand_roll_limit: bpy.props.FloatProperty(
+ name="Maximum Hand Roll (Degrees)",
+ description="Maximum axial palm correction transferred in Limited Roll mode",
+ default=60.0,
+ min=0.0,
+ max=180.0,
+ ) # type: ignore
+
arm_correction_driver: bpy.props.EnumProperty(
name="Arm Correction Driver",
description="Choose which joint post-processing may rotate to position each wrist",
@@ -4402,6 +5585,20 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
default="AUTO",
) # type: ignore
+ collision_segment_mode: bpy.props.EnumProperty(
+ name="Proxy Segments",
+ description="Choose how skeletal collision capsule endpoints are constructed",
+ items=_COLLISION_SEGMENT_MODE_ITEMS,
+ default="BONE_TAILS",
+ ) # type: ignore
+
+ upper_arm_collision: bpy.props.EnumProperty(
+ name="Upper Arm Collision",
+ description="Choose how much of the upper-arm capsule participates in collision tests",
+ items=_UPPER_ARM_COLLISION_ITEMS,
+ default="DISABLED",
+ ) # type: ignore
+
collision_adaptation: bpy.props.BoolProperty(
name="Skeletal Proxy Collisions",
description=(
@@ -4494,6 +5691,7 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
return True
def invoke(self, context, event):
+ _initialize_collision_operator_settings(self, context)
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
@@ -4514,7 +5712,20 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
layout.prop(self, "auto_match_clearance")
if self.retarget_engine == "REST_SPACE":
layout.prop(self, "limb_match_strength")
+ layout.prop(self, "match_hand_orientation")
+ if self.match_hand_orientation:
+ layout.prop(self, "hand_match_strength")
+ layout.prop(self, "hand_roll_mode")
+ if self.hand_roll_mode == "LIMITED":
+ layout.prop(self, "hand_roll_limit")
+ elif self.hand_roll_mode == "TWIST_CHAIN":
+ layout.label(
+ text="Creates deform bones and redistributes forearm weights",
+ icon="INFO",
+ )
layout.prop(self, "arm_correction_driver")
+ layout.prop(self, "collision_segment_mode")
+ layout.prop(self, "upper_arm_collision")
layout.prop(self, "collision_adaptation")
if self.collision_adaptation:
collision_box = layout.box()
@@ -4597,7 +5808,22 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
"Not enough source/target bone pairs were found. "
"Try analyzing the rig or using a different source animation."
)
+ target_armature[_HAND_MATCH_ENABLED_PROP] = (
+ self.retarget_engine == "REST_SPACE"
+ and self.match_hand_orientation
+ )
+ target_armature[_HAND_MATCH_STRENGTH_PROP] = (
+ self.hand_match_strength)
+ target_armature[_HAND_ROLL_MODE_PROP] = self.hand_roll_mode
+ target_armature[_HAND_ROLL_LIMIT_PROP] = self.hand_roll_limit
collision_proxy = None
+ if self.retarget_engine == "REST_SPACE":
+ target_armature[_COLLISION_SEGMENT_MODE_PROP] = (
+ self.collision_segment_mode)
+ target_armature[_UPPER_ARM_COLLISION_PROP] = (
+ self.upper_arm_collision)
+ target_armature[_ARM_CORRECTION_DRIVER_PROP] = (
+ self.arm_correction_driver)
needs_reference_proxy = (
self.source_reference_mode == "START_FRAME"
and self.auto_match_reference
@@ -4607,7 +5833,10 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
self.retarget_engine == "REST_SPACE"
and (self.collision_adaptation or needs_reference_proxy)):
collision_proxy = _collision_proxy_for_armature(
- target_armature, target_profile)
+ target_armature,
+ target_profile,
+ segment_mode=self.collision_segment_mode,
+ )
if collision_proxy is None:
print(
"[StableGen] WARNING: Could not build a skeletal collision proxy; "
@@ -4651,6 +5880,10 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
start,
self.source_reference_mode,
swap_target_sides=effective_swap,
+ match_hand_orientation=self.match_hand_orientation,
+ hand_match_strength=self.hand_match_strength,
+ hand_roll_mode=self.hand_roll_mode,
+ hand_roll_limit=self.hand_roll_limit,
)
reference_matches, mismatch_reason = _reference_provenance_matches(
target_reference_pose,
@@ -4670,6 +5903,11 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
clearance=self.auto_match_clearance,
collision_proxy=collision_proxy,
arm_correction_driver=self.arm_correction_driver,
+ upper_arm_collision=self.upper_arm_collision,
+ match_hand_orientation=self.match_hand_orientation,
+ hand_match_strength=self.hand_match_strength,
+ hand_roll_mode=self.hand_roll_mode,
+ hand_roll_limit=self.hand_roll_limit,
)
target_reference_pose = _capture_reference_pose(
target_armature,
@@ -4757,6 +5995,11 @@ class StableGenApplyAnimationToRig(bpy.types.Operator):
collision_iterations=self.collision_iterations,
collision_max_deviation=self.collision_max_deviation,
arm_correction_driver=self.arm_correction_driver,
+ upper_arm_collision=self.upper_arm_collision,
+ match_hand_orientation=self.match_hand_orientation,
+ hand_match_strength=self.hand_match_strength,
+ hand_roll_mode=self.hand_roll_mode,
+ hand_roll_limit=self.hand_roll_limit,
)
context.scene.frame_set(start)
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 0225039..cde13bc 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -1524,6 +1524,32 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
description="Enable SkinTokens voxel skin post-processing before export",
default=False, update=update_parameters
)
+ bpy.types.Scene.trellis2_autorig_cleanup_cross_limb_weights = bpy.props.BoolProperty(
+ name="Clean Limb Weights",
+ description=(
+ "After import, repair spatially implausible hand and foot weights "
+ "such as influences from the opposite limb, spine, pelvis, or legs"
+ ),
+ default=True, update=update_parameters
+ )
+ bpy.types.Scene.trellis2_autorig_garment_mode = bpy.props.EnumProperty(
+ name="Garment Handling",
+ description="Optional post-import weighting for long dresses and skirts",
+ items=[
+ ('NONE', "Original Weights", "Keep the generated garment weights"),
+ (
+ 'STABILIZE',
+ "Stabilized Dress",
+ "Apply a smooth pelvis/thigh blend to detected long garment surfaces",
+ ),
+ (
+ 'LEG_FOLLOW',
+ "Smooth Leg Follow",
+ "Smoothly drive detected long garments from the pelvis, thighs, and lower legs",
+ ),
+ ],
+ default='NONE', update=update_parameters
+ )
bpy.types.Scene.trellis2_autorig_top_k = bpy.props.IntProperty(
name="Top K", description="SkinTokens sampling top-k",
default=5, min=1, max=200, update=update_parameters
@@ -1899,6 +1925,8 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'trellis2_solidify',
'trellis2_autorig_enabled', 'trellis2_autorig_use_transfer',
'trellis2_autorig_use_skeleton', 'trellis2_autorig_use_postprocess',
+ 'trellis2_autorig_cleanup_cross_limb_weights',
+ 'trellis2_autorig_garment_mode',
'trellis2_autorig_top_k', 'trellis2_autorig_top_p',
'trellis2_autorig_temperature', 'trellis2_autorig_repetition_penalty',
'trellis2_autorig_num_beams', 'trellis2_autorig_model_ckpt',
diff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.py
index fd7ff57..48e1556 100644
--- a/stablegen/mesh_gen/trellis2.py
+++ b/stablegen/mesh_gen/trellis2.py
@@ -21,6 +21,1097 @@ from .._generator_utils import setup_studio_lighting, redraw_ui, upload_image_to
from ..texturing.gallery import _PreviewGalleryOverlay
_ADDON_PKG = __package__.rsplit('.', 1)[0]
+_GARMENT_STABILIZED_GROUP = "SG_GarmentStabilized"
+
+
+def _autorig_deforming_armature(mesh_object, imported_armatures):
+ """Return the imported armature that supplies this mesh's skin groups."""
+ for modifier in mesh_object.modifiers:
+ if (
+ modifier.type == 'ARMATURE'
+ and modifier.object in imported_armatures
+ ):
+ return modifier.object
+
+ parent = mesh_object.parent
+ while parent:
+ if parent.type == 'ARMATURE' and parent in imported_armatures:
+ return parent
+ parent = parent.parent
+ return None
+
+
+def _sanitize_autorig_cross_limb_weights(imported_objects):
+ """Repair spatially implausible SkinTokens limb weights.
+
+ SkinTokens can assign both feet to the same distal bone groups when the
+ shoes are close, or weight hand vertices to a leg, pelvis, spine, or the
+ opposite hand. Those errors are often invisible in the bind pose but form
+ long spikes once the limbs move. This pass uses StableGen's semantic rig
+ characterization plus rest-space bone proximity; it does not depend on
+ generated bone names.
+
+ The established cross-foot correction is retained. A second general pass
+ classifies only confident distal hand/foot regions and removes any weighted
+ bone that is materially farther from the vertex than the nearest valid
+ local limb bone. Removed weight is assigned to that nearest bone, keeping
+ the total armature weight unchanged.
+ """
+ from ..animation.retargeting import characterize_armature
+
+ imported_objects = [
+ obj for obj in imported_objects
+ if obj and obj.name in bpy.data.objects
+ ]
+ imported_armatures = {
+ obj for obj in imported_objects if obj.type == 'ARMATURE'
+ }
+ if not imported_armatures:
+ return {"changed_vertices": 0, "moved_weight": 0.0, "meshes": 0}
+
+ total_changed = 0
+ total_moved = 0.0
+ changed_meshes = 0
+
+ for armature in imported_armatures:
+ profile = characterize_armature(armature)
+ chains = dict((profile or {}).get("chains", {}))
+ if (profile or {}).get("orientation_correction") == "ROTATE_180":
+ chains["left_leg"], chains["right_leg"] = (
+ chains.get("right_leg", []),
+ chains.get("left_leg", []),
+ )
+ chains["left_arm"], chains["right_arm"] = (
+ chains.get("right_arm", []),
+ chains.get("left_arm", []),
+ )
+
+ left_chain = [
+ name for name in chains.get("left_leg", [])
+ if armature.data.bones.get(name)
+ ]
+ right_chain = [
+ name for name in chains.get("right_leg", [])
+ if armature.data.bones.get(name)
+ ]
+ if len(left_chain) < 2 or len(right_chain) < 2:
+ print(
+ f"[StableGen] Cross-limb cleanup skipped for {armature.name}: "
+ "paired leg chains were not characterized"
+ )
+ continue
+
+ def bone_point(name, use_tail=False):
+ bone = armature.data.bones[name]
+ return (bone.tail_local if use_tail else bone.head_local).copy()
+
+ left_foot = (
+ bone_point(left_chain[-1]) + bone_point(left_chain[-1], True)
+ ) * 0.5
+ right_foot = (
+ bone_point(right_chain[-1]) + bone_point(right_chain[-1], True)
+ ) * 0.5
+ side_vector = left_foot - right_foot
+ side_separation = side_vector.length
+ if side_separation <= 1e-6:
+ print(
+ f"[StableGen] Cross-limb cleanup skipped for {armature.name}: "
+ "the characterized feet have no usable side separation"
+ )
+ continue
+ side_axis = side_vector / side_separation
+ side_origin = (left_foot + right_foot) * 0.5
+
+ pelvis_bone = armature.data.bones.get((profile or {}).get("pelvis", ""))
+ head_bone = armature.data.bones.get((profile or {}).get("head", ""))
+ if pelvis_bone and head_bone:
+ up_axis = (
+ (head_bone.head_local + head_bone.tail_local) * 0.5
+ - (pelvis_bone.head_local + pelvis_bone.tail_local) * 0.5
+ )
+ else:
+ left_hip = bone_point(left_chain[0])
+ right_hip = bone_point(right_chain[0])
+ up_axis = (left_hip + right_hip) * 0.5 - side_origin
+ if up_axis.length <= 1e-6:
+ continue
+ up_axis.normalize()
+
+ hip_height = sum(
+ bone_point(chain[0]).dot(up_axis)
+ for chain in (left_chain, right_chain)
+ ) * 0.5
+ foot_height = sum(
+ point.dot(up_axis) for point in (left_foot, right_foot)
+ ) * 0.5
+ if hip_height < foot_height:
+ up_axis.negate()
+ hip_height = -hip_height
+ foot_height = -foot_height
+
+ leg_height = hip_height - foot_height
+ if leg_height <= 1e-6:
+ continue
+
+ # Slightly above the anatomical knee on typical 3- or 4-bone chains.
+ # Restricting the pass to this region avoids changing skirt/torso skin.
+ lower_body_cutoff = foot_height + leg_height * 0.58
+ side_margin = side_separation * 0.08
+ armature_inverse = armature.matrix_world.inverted_safe()
+
+ chain_pairs = {}
+ for source_chain, target_chain in (
+ (left_chain, right_chain),
+ (right_chain, left_chain),
+ ):
+ source_last = max(1, len(source_chain) - 1)
+ target_last = max(1, len(target_chain) - 1)
+ for index, source_name in enumerate(source_chain):
+ target_index = round((index / source_last) * target_last)
+ chain_pairs[source_name] = target_chain[target_index]
+
+ def bone_segment_distance(point, bone_name):
+ bone = armature.data.bones[bone_name]
+ start = bone.head_local
+ delta = bone.tail_local - start
+ length_squared = delta.length_squared
+ if length_squared <= 1e-12:
+ return (point - start).length
+ factor = max(
+ 0.0,
+ min(1.0, (point - start).dot(delta) / length_squared),
+ )
+ return (point - (start + delta * factor)).length
+
+ def descendants(root_name):
+ result = set()
+ root_bone = armature.data.bones.get(root_name)
+ stack = list(root_bone.children) if root_bone else []
+ while stack:
+ child = stack.pop()
+ if child.name in result:
+ continue
+ result.add(child.name)
+ stack.extend(child.children)
+ return result
+
+ def make_distal_region(label, chain, region_kind):
+ chain = [
+ name for name in chain if armature.data.bones.get(name)
+ ]
+ if len(chain) < 2:
+ return None
+ terminal_descendants = descendants(chain[-1])
+ if region_kind == "hand":
+ core_names = {chain[-1]} | terminal_descendants
+ allowed_names = core_names | {chain[-2]}
+ else:
+ core_names = set(chain[-2:]) | terminal_descendants
+ allowed_names = set(chain[-3:]) | terminal_descendants
+
+ points = []
+ for name in core_names:
+ bone = armature.data.bones[name]
+ points.extend((bone.head_local.copy(), bone.tail_local.copy()))
+ if not points:
+ return None
+ center = sum(points, mathutils.Vector()) / len(points)
+ extent = max((point - center).length for point in points)
+ proximal_length = armature.data.bones[chain[-2]].length
+ radius = max(extent * 1.35, proximal_length * 0.65)
+ if radius <= 1e-6:
+ return None
+ return {
+ "label": label,
+ "kind": region_kind,
+ "owner_family": label.replace(
+ region_kind,
+ "arm" if region_kind == "hand" else "leg",
+ ),
+ "center": center,
+ "radius": radius,
+ "max_local_distance": radius * 0.55,
+ "distance_margin": max(
+ extent * 0.08,
+ proximal_length * 0.035,
+ radius * 0.02,
+ ),
+ "core": core_names,
+ "allowed": allowed_names,
+ }
+
+ distal_region_pairs = []
+ for region_kind, chain_suffix in (("hand", "arm"), ("foot", "leg")):
+ left_region = make_distal_region(
+ f"left_{region_kind}",
+ chains.get(f"left_{chain_suffix}", []),
+ region_kind,
+ )
+ right_region = make_distal_region(
+ f"right_{region_kind}",
+ chains.get(f"right_{chain_suffix}", []),
+ region_kind,
+ )
+ if left_region and right_region:
+ distal_region_pairs.append((left_region, right_region))
+
+ all_bone_names = {bone.name for bone in armature.data.bones}
+ family_bones = {
+ "spine": set(chains.get("spine", []))
+ | {
+ name for name in (
+ (profile or {}).get("pelvis"),
+ (profile or {}).get("head"),
+ ) if name
+ },
+ "left_arm": set(chains.get("left_arm", []))
+ | descendants((chains.get("left_arm") or [""])[-1]),
+ "right_arm": set(chains.get("right_arm", []))
+ | descendants((chains.get("right_arm") or [""])[-1]),
+ "left_leg": set(chains.get("left_leg", []))
+ | descendants((chains.get("left_leg") or [""])[-1]),
+ "right_leg": set(chains.get("right_leg", []))
+ | descendants((chains.get("right_leg") or [""])[-1]),
+ }
+ bone_family = {
+ name: family
+ for family, names in family_bones.items()
+ for name in names
+ }
+ spatial_region_stats = {
+ region["label"]: {"vertices": 0, "weight": 0.0}
+ for pair in distal_region_pairs
+ for region in pair
+ }
+
+ for mesh_object in imported_objects:
+ if mesh_object.type != 'MESH':
+ continue
+ if _autorig_deforming_armature(mesh_object, imported_armatures) != armature:
+ continue
+
+ group_by_name = {
+ group.name: group for group in mesh_object.vertex_groups
+ }
+ garment_marker = group_by_name.get(_GARMENT_STABILIZED_GROUP)
+ garment_vertex_indices = set()
+ if garment_marker:
+ marker_index = garment_marker.index
+ garment_vertex_indices = {
+ vertex.index
+ for vertex in mesh_object.data.vertices
+ if any(
+ element.group == marker_index and element.weight > 0.5
+ for element in vertex.groups
+ )
+ }
+ relevant_names = set(left_chain) | set(right_chain)
+ for region_pair in distal_region_pairs:
+ for region in region_pair:
+ relevant_names.update(region["allowed"])
+ relevant_names.update(region["core"])
+ if not relevant_names.intersection(group_by_name):
+ continue
+ group_name_by_index = {
+ group.index: group.name for group in mesh_object.vertex_groups
+ }
+
+ # Spatial proximity is ambiguous when hands rest beside a skirt or
+ # coat. Establish a topology-level owner family before changing
+ # any weights. A disconnected hand/finger surface is normally
+ # dominated by its arm family, while nearby garment panels are
+ # dominated by spine/leg families even if a few vertices carry bad
+ # finger weights. This prevents the garment from being reassigned
+ # to the hand merely because the surfaces touch in bind space.
+ component_roots = list(range(len(mesh_object.data.vertices)))
+
+ def component_find(index):
+ while component_roots[index] != index:
+ component_roots[index] = component_roots[
+ component_roots[index]
+ ]
+ index = component_roots[index]
+ return index
+
+ def component_union(first, second):
+ first_root = component_find(first)
+ second_root = component_find(second)
+ if first_root != second_root:
+ component_roots[second_root] = first_root
+
+ for edge in mesh_object.data.edges:
+ component_union(edge.vertices[0], edge.vertices[1])
+ component_roots = [
+ component_find(index) for index in range(len(component_roots))
+ ]
+ component_sizes = {}
+ component_family_weights = {}
+ for vertex, component_root in zip(
+ mesh_object.data.vertices, component_roots
+ ):
+ component_sizes[component_root] = (
+ component_sizes.get(component_root, 0) + 1
+ )
+ weights_by_family = component_family_weights.setdefault(
+ component_root, {})
+ for element in vertex.groups:
+ family = bone_family.get(
+ group_name_by_index.get(element.group)
+ )
+ if family:
+ weights_by_family[family] = (
+ weights_by_family.get(family, 0.0)
+ + float(element.weight)
+ )
+
+ mesh_to_armature = armature_inverse @ mesh_object.matrix_world
+ changed_vertex_indices = set()
+ mesh_moved = 0.0
+ left_set = set(left_chain)
+ right_set = set(right_chain)
+
+ for vertex in mesh_object.data.vertices:
+ if vertex.index in garment_vertex_indices:
+ continue
+ point = mesh_to_armature @ vertex.co
+ if point.dot(up_axis) > lower_body_cutoff:
+ continue
+ side_value = (point - side_origin).dot(side_axis)
+ if abs(side_value) <= side_margin:
+ continue
+
+ correct_set = left_set if side_value > 0.0 else right_set
+ opposite_set = (
+ right_set - left_set
+ if side_value > 0.0
+ else left_set - right_set
+ )
+ weights = {
+ group_name_by_index.get(element.group): float(element.weight)
+ for element in vertex.groups
+ if group_name_by_index.get(element.group) in relevant_names
+ }
+ transfers = {}
+ for opposite_name in opposite_set:
+ weight = weights.get(opposite_name, 0.0)
+ if weight <= 1e-6:
+ continue
+ target_name = chain_pairs.get(opposite_name)
+ if target_name not in correct_set:
+ continue
+ transfers[target_name] = transfers.get(target_name, 0.0) + weight
+ group_by_name[opposite_name].remove([vertex.index])
+ mesh_moved += weight
+
+ if not transfers:
+ continue
+ for target_name, weight in transfers.items():
+ if target_name not in group_by_name:
+ group_by_name[target_name] = mesh_object.vertex_groups.new(
+ name=target_name
+ )
+ current_weight = weights.get(target_name, 0.0)
+ group_by_name[target_name].add(
+ [vertex.index], current_weight + weight, 'REPLACE')
+ changed_vertex_indices.add(vertex.index)
+
+ # General rest-space plausibility pass. It deliberately operates
+ # only inside compact distal regions and requires one side to be a
+ # clearly better geometric match than the other. This catches
+ # hand-to-leg, hand-to-spine, cross-hand, foot-to-pelvis, and
+ # similar remote influences without imposing a global nearest-bone
+ # rule on clothing or the torso.
+ for vertex in mesh_object.data.vertices:
+ if vertex.index in garment_vertex_indices:
+ continue
+ point = mesh_to_armature @ vertex.co
+ candidates = []
+ for region_pair in distal_region_pairs:
+ pair_candidates = []
+ for region in region_pair:
+ if (point - region["center"]).length > region["radius"]:
+ pair_candidates.append(None)
+ continue
+ nearest_core_distance = min(
+ bone_segment_distance(point, name)
+ for name in region["core"]
+ )
+ if nearest_core_distance > region["max_local_distance"]:
+ pair_candidates.append(None)
+ continue
+ pair_candidates.append(
+ (nearest_core_distance / region["radius"], region)
+ )
+
+ valid = [entry for entry in pair_candidates if entry]
+ if not valid:
+ continue
+ valid.sort(key=lambda entry: entry[0])
+ best_score, best_region = valid[0]
+ if len(valid) > 1 and best_score + 0.08 >= valid[1][0]:
+ continue
+ candidates.append((best_score, best_region))
+
+ if not candidates:
+ continue
+ candidates.sort(key=lambda entry: entry[0])
+ best_score, region = candidates[0]
+ if len(candidates) > 1 and best_score + 0.06 >= candidates[1][0]:
+ continue
+
+ component_root = component_roots[vertex.index]
+ component_weights = component_family_weights.get(
+ component_root, {})
+ component_total = sum(component_weights.values())
+ owner_weight = component_weights.get(
+ region["owner_family"], 0.0)
+ owner_share = (
+ owner_weight / component_total
+ if component_total > 1e-8 else 0.0
+ )
+ # Permit mixed hand/finger components when at least a quarter
+ # of their consensus supports this side. A tiny disconnected
+ # digit with wholly corrupt weights may use a very strong
+ # spatial match as fallback; large garment/body components may
+ # not, because proximity is ambiguous there.
+ if owner_share < 0.25 and not (
+ component_sizes.get(component_root, 0) <= 2048
+ and best_score <= 0.12
+ ):
+ continue
+
+ target_name, target_distance = min(
+ (
+ (name, bone_segment_distance(point, name))
+ for name in region["allowed"]
+ ),
+ key=lambda entry: entry[1],
+ )
+ initial_weights = {
+ group_name_by_index.get(element.group): float(element.weight)
+ for element in vertex.groups
+ if group_name_by_index.get(element.group) in all_bone_names
+ }
+ removed_weight = 0.0
+ for source_name, weight in initial_weights.items():
+ if source_name in region["allowed"] or weight <= 1e-6:
+ continue
+ source_distance = bone_segment_distance(point, source_name)
+ plausible_limit = max(
+ target_distance * 1.75,
+ target_distance + region["distance_margin"],
+ )
+ if source_distance <= plausible_limit:
+ continue
+ group_by_name[source_name].remove([vertex.index])
+ removed_weight += weight
+
+ if removed_weight <= 0.0:
+ continue
+ if target_name not in group_by_name:
+ group_by_name[target_name] = mesh_object.vertex_groups.new(
+ name=target_name
+ )
+ target_weight = initial_weights.get(target_name, 0.0)
+ group_by_name[target_name].add(
+ [vertex.index], target_weight + removed_weight, 'REPLACE')
+ changed_vertex_indices.add(vertex.index)
+ mesh_moved += removed_weight
+ spatial_region_stats[region["label"]]["vertices"] += 1
+ spatial_region_stats[region["label"]]["weight"] += removed_weight
+
+ if changed_vertex_indices:
+ mesh_object.data.update()
+ changed_meshes += 1
+ total_changed += len(changed_vertex_indices)
+ total_moved += mesh_moved
+
+ for label, region_stats in spatial_region_stats.items():
+ if region_stats["vertices"]:
+ print(
+ f"[StableGen] Spatial weight cleanup {label}: "
+ f"{region_stats['vertices']} vertices, "
+ f"{region_stats['weight']:.3f} weight remapped"
+ )
+
+ stats = {
+ "changed_vertices": total_changed,
+ "moved_weight": total_moved,
+ "meshes": changed_meshes,
+ }
+ print(
+ "[StableGen] Limb-weight plausibility cleanup: "
+ f"{total_changed} vertices across {changed_meshes} mesh(es), "
+ f"{total_moved:.3f} total weight remapped"
+ )
+ return stats
+
+
+def _stabilize_autorig_garment_weights(imported_objects, mode='STABILIZE'):
+ """Create a conservative skeletal blend for long garment surfaces.
+
+ A humanoid skeleton has no representation for free-hanging cloth. Long
+ dresses therefore inherit discontinuous left/right leg weights and open
+ into a stretched membrane during wide strides. This optional pass detects
+ large connected lower-body surfaces with mixed spine/leg ownership, then
+ replaces their bone weights with a smooth three-bone blend: pelvis plus
+ both upper legs. The waist stays mostly pelvis-anchored while the lower
+ garment follows a softened average of the thighs. ``LEG_FOLLOW`` keeps
+ that waist anchor but gives the lower garment stronger, spatially smooth
+ same-side thigh/shin ownership. It also absorbs small disconnected
+ surface islands close to a confidently detected garment component.
+ """
+ from ..animation.retargeting import characterize_armature
+ from mathutils import kdtree # pylint: disable=import-error
+
+ mode = str(mode or 'STABILIZE').upper()
+ if mode not in {'STABILIZE', 'LEG_FOLLOW'}:
+ raise ValueError(f"Unknown garment weighting mode: {mode}")
+
+ imported_objects = [
+ obj for obj in imported_objects
+ if obj and obj.name in bpy.data.objects
+ ]
+ imported_armatures = {
+ obj for obj in imported_objects if obj.type == 'ARMATURE'
+ }
+ total_changed = 0
+ total_components = 0
+ total_absorbed_components = 0
+
+ for armature in imported_armatures:
+ profile = characterize_armature(armature)
+ chains = dict((profile or {}).get("chains", {}))
+ if (profile or {}).get("orientation_correction") == "ROTATE_180":
+ chains["left_leg"], chains["right_leg"] = (
+ chains.get("right_leg", []),
+ chains.get("left_leg", []),
+ )
+ left_leg = [
+ name for name in chains.get("left_leg", [])
+ if armature.data.bones.get(name)
+ ]
+ right_leg = [
+ name for name in chains.get("right_leg", [])
+ if armature.data.bones.get(name)
+ ]
+ spine = [
+ name for name in chains.get("spine", [])
+ if armature.data.bones.get(name)
+ ]
+ pelvis_name = (profile or {}).get("pelvis")
+ if (
+ len(left_leg) < 2
+ or len(right_leg) < 2
+ or not pelvis_name
+ or not armature.data.bones.get(pelvis_name)
+ ):
+ continue
+
+ left_thigh = left_leg[0]
+ right_thigh = right_leg[0]
+ left_shin = left_leg[1]
+ right_shin = right_leg[1]
+ left_hip = armature.data.bones[left_thigh].head_local.copy()
+ right_hip = armature.data.bones[right_thigh].head_local.copy()
+ side_vector = left_hip - right_hip
+ side_separation = side_vector.length
+ if side_separation <= 1e-6:
+ continue
+ side_axis = side_vector / side_separation
+ side_origin = (left_hip + right_hip) * 0.5
+
+ pelvis_bone = armature.data.bones[pelvis_name]
+ head_bone = armature.data.bones.get((profile or {}).get("head", ""))
+ if head_bone:
+ up_axis = (
+ (head_bone.head_local + head_bone.tail_local) * 0.5
+ - (pelvis_bone.head_local + pelvis_bone.tail_local) * 0.5
+ )
+ else:
+ left_foot = armature.data.bones[left_leg[-1]].tail_local
+ right_foot = armature.data.bones[right_leg[-1]].tail_local
+ up_axis = side_origin - (left_foot + right_foot) * 0.5
+ if up_axis.length <= 1e-6:
+ continue
+ up_axis.normalize()
+
+ hip_height = side_origin.dot(up_axis)
+ foot_height = sum(
+ armature.data.bones[chain[-1]].tail_local.dot(up_axis)
+ for chain in (left_leg, right_leg)
+ ) * 0.5
+ if hip_height < foot_height:
+ up_axis.negate()
+ hip_height = -hip_height
+ foot_height = -foot_height
+ leg_height = hip_height - foot_height
+ if leg_height <= 1e-6:
+ continue
+
+ family_bones = {
+ "spine": set(spine) | {pelvis_name},
+ "left_leg": set(left_leg),
+ "right_leg": set(right_leg),
+ "left_arm": set(chains.get("left_arm", [])),
+ "right_arm": set(chains.get("right_arm", [])),
+ }
+ bone_family = {
+ name: family
+ for family, names in family_bones.items()
+ for name in names
+ }
+ all_bone_names = {bone.name for bone in armature.data.bones}
+ armature_inverse = armature.matrix_world.inverted_safe()
+
+ for mesh_object in imported_objects:
+ if mesh_object.type != 'MESH':
+ continue
+ if _autorig_deforming_armature(
+ mesh_object, imported_armatures
+ ) != armature:
+ continue
+ if not mesh_object.data.edges:
+ continue
+
+ group_by_name = {
+ group.name: group for group in mesh_object.vertex_groups
+ }
+ if not set((pelvis_name, left_thigh, right_thigh)).intersection(
+ group_by_name
+ ):
+ continue
+ group_name_by_index = {
+ group.index: group.name for group in mesh_object.vertex_groups
+ }
+ mesh_to_armature = armature_inverse @ mesh_object.matrix_world
+
+ parents = list(range(len(mesh_object.data.vertices)))
+
+ def find(index):
+ while parents[index] != index:
+ parents[index] = parents[parents[index]]
+ index = parents[index]
+ return index
+
+ def union(first, second):
+ first_root = find(first)
+ second_root = find(second)
+ if first_root != second_root:
+ parents[second_root] = first_root
+
+ for edge in mesh_object.data.edges:
+ union(edge.vertices[0], edge.vertices[1])
+ roots = [find(index) for index in range(len(parents))]
+
+ component_data = {}
+ points = [
+ mesh_to_armature @ vertex.co
+ for vertex in mesh_object.data.vertices
+ ]
+ for vertex, root, point in zip(
+ mesh_object.data.vertices, roots, points
+ ):
+ data = component_data.setdefault(
+ root,
+ {
+ "vertices": [],
+ "families": {},
+ "min_height": float("inf"),
+ "max_height": float("-inf"),
+ },
+ )
+ data["vertices"].append(vertex.index)
+ height = point.dot(up_axis)
+ data["min_height"] = min(data["min_height"], height)
+ data["max_height"] = max(data["max_height"], height)
+ for element in vertex.groups:
+ family = bone_family.get(
+ group_name_by_index.get(element.group)
+ )
+ if family:
+ data["families"][family] = (
+ data["families"].get(family, 0.0)
+ + float(element.weight)
+ )
+
+ minimum_component_size = max(
+ 300,
+ int(len(mesh_object.data.vertices) * 0.0005),
+ )
+ garment_components = []
+ for root, data in component_data.items():
+ vertex_count = len(data["vertices"])
+ if vertex_count < minimum_component_size:
+ continue
+ family_total = sum(data["families"].values())
+ if family_total <= 1e-8:
+ continue
+ share = {
+ family: data["families"].get(family, 0.0) / family_total
+ for family in family_bones
+ }
+ leg_share = share["left_leg"] + share["right_leg"]
+ arm_share = share["left_arm"] + share["right_arm"]
+ vertical_span = data["max_height"] - data["min_height"]
+ reaches_upper_leg = (
+ data["max_height"] >= foot_height + leg_height * 0.55
+ )
+ reaches_below_knee = (
+ data["min_height"] <= foot_height + leg_height * 0.65
+ )
+ mixed_lower_body = (
+ min(share["left_leg"], share["right_leg"]) >= 0.02
+ or share["spine"] >= 0.25
+ )
+ single_leg_surface = (
+ vertex_count < max(
+ 8000,
+ int(len(mesh_object.data.vertices) * 0.01),
+ )
+ and max(share["left_leg"], share["right_leg"]) >= 0.80
+ and share["spine"] < 0.15
+ )
+ if not (
+ share["spine"] >= 0.08
+ and leg_share >= 0.25
+ and arm_share <= 0.08
+ and mixed_lower_body
+ and vertical_span >= leg_height * 0.22
+ and reaches_upper_leg
+ and reaches_below_knee
+ and not single_leg_surface
+ ):
+ continue
+ garment_components.append((root, data, share))
+
+ if not garment_components:
+ continue
+
+ absorbed_components = 0
+ if mode == 'LEG_FOLLOW':
+ # Generated garments commonly contain narrow, disconnected
+ # strips along their boundary. They are too small to pass the
+ # semantic component test above, but leaving their old (or
+ # absent) weights creates the floating triangles visible once
+ # the character leaves its rest pose. Attach only small
+ # lower-body islands that lie very close to a confident core.
+ core_roots = {root for root, _data, _share in garment_components}
+ core_vertices = [
+ vertex_index
+ for _root, data, _share in garment_components
+ for vertex_index in data["vertices"]
+ ]
+ proximity_tree = kdtree.KDTree(len(core_vertices))
+ for tree_index, vertex_index in enumerate(core_vertices):
+ proximity_tree.insert(points[vertex_index], tree_index)
+ proximity_tree.balance()
+
+ island_distance = max(
+ side_separation * 0.16,
+ leg_height * 0.025,
+ )
+ island_size_limit = max(
+ minimum_component_size * 8,
+ int(len(mesh_object.data.vertices) * 0.02),
+ )
+ for root, data in component_data.items():
+ if root in core_roots:
+ continue
+ vertex_count = len(data["vertices"])
+ if vertex_count > island_size_limit:
+ continue
+ if data["max_height"] < foot_height - leg_height * 0.04:
+ continue
+ if data["min_height"] > hip_height + leg_height * 0.08:
+ continue
+
+ family_total = sum(data["families"].values())
+ if family_total > 1e-8:
+ share = {
+ family: data["families"].get(family, 0.0) / family_total
+ for family in family_bones
+ }
+ leg_share = share["left_leg"] + share["right_leg"]
+ arm_share = share["left_arm"] + share["right_arm"]
+ dominant_single_leg = (
+ max(share["left_leg"], share["right_leg"]) >= 0.72
+ and min(share["left_leg"], share["right_leg"]) < 0.08
+ and share["spine"] < 0.18
+ )
+ if (
+ arm_share > 0.35
+ or share["spine"] + leg_share < 0.45
+ or dominant_single_leg
+ ):
+ continue
+ allowed_distance = island_distance
+ else:
+ # An unweighted island must be almost touching the core
+ # before StableGen assumes it belongs to the garment.
+ share = {family: 0.0 for family in family_bones}
+ allowed_distance = island_distance * 0.45
+
+ nearest_distance = min(
+ proximity_tree.find(points[vertex_index])[2]
+ for vertex_index in data["vertices"]
+ )
+ if nearest_distance > allowed_distance:
+ continue
+ garment_components.append((root, data, share))
+ absorbed_components += 1
+
+ total_absorbed_components += absorbed_components
+
+ target_bones = [pelvis_name, left_thigh, right_thigh]
+ if mode == 'LEG_FOLLOW':
+ target_bones.extend((left_shin, right_shin))
+ for target_name in target_bones:
+ if target_name not in group_by_name:
+ group_by_name[target_name] = mesh_object.vertex_groups.new(
+ name=target_name
+ )
+ garment_marker = group_by_name.get(_GARMENT_STABILIZED_GROUP)
+ if not garment_marker:
+ garment_marker = mesh_object.vertex_groups.new(
+ name=_GARMENT_STABILIZED_GROUP
+ )
+
+ changed_indices = set()
+ if mode == 'LEG_FOLLOW':
+ garment_indices = {
+ vertex_index
+ for _root, data, _share in garment_components
+ for vertex_index in data["vertices"]
+ if (
+ points[vertex_index].dot(up_axis)
+ <= hip_height + leg_height * 0.06
+ and points[vertex_index].dot(up_axis)
+ >= foot_height - leg_height * 0.04
+ )
+ }
+ knee_height = sum(
+ armature.data.bones[name].tail_local.dot(up_axis)
+ for name in (left_thigh, right_thigh)
+ ) * 0.5
+ if not foot_height < knee_height < hip_height:
+ knee_height = foot_height + leg_height * 0.52
+
+ target_fractions = {}
+ bone_totals = {}
+ for vertex_index in garment_indices:
+ vertex = mesh_object.data.vertices[vertex_index]
+ point = points[vertex_index]
+ height = point.dot(up_axis)
+ downward = max(
+ 0.0,
+ min(1.0, (hip_height - height) / (leg_height * 0.9)),
+ )
+ smooth_downward = downward * downward * (3.0 - 2.0 * downward)
+ follow_amount = max(
+ 0.0,
+ min(1.0, (smooth_downward - 0.04) / 0.96),
+ )
+ follow_amount = (
+ follow_amount
+ * follow_amount
+ * (3.0 - 2.0 * follow_amount)
+ )
+ pelvis_fraction = 0.90 - 0.68 * follow_amount
+ side_value = (point - side_origin).dot(side_axis)
+ side_normalized = max(
+ -1.0,
+ min(1.0, side_value / max(side_separation * 0.62, 1e-6)),
+ )
+ side_strength = 0.12 + 0.36 * follow_amount
+ left_split = 0.5 + side_strength * side_normalized
+ left_split = max(0.04, min(0.96, left_split))
+
+ below_knee = max(
+ 0.0,
+ min(
+ 1.0,
+ (knee_height - height)
+ / max(knee_height - foot_height, 1e-6),
+ ),
+ )
+ below_knee = below_knee * below_knee * (3.0 - 2.0 * below_knee)
+ shin_share = 0.42 * below_knee * follow_amount
+ thigh_share = 1.0 - shin_share
+ leg_fraction = 1.0 - pelvis_fraction
+ target_fractions[vertex_index] = {
+ pelvis_name: pelvis_fraction,
+ left_thigh: leg_fraction * left_split * thigh_share,
+ right_thigh: leg_fraction * (1.0 - left_split) * thigh_share,
+ left_shin: leg_fraction * left_split * shin_share,
+ right_shin: leg_fraction * (1.0 - left_split) * shin_share,
+ }
+
+ current_bone_weights = {
+ group_name_by_index.get(element.group): float(element.weight)
+ for element in vertex.groups
+ if group_name_by_index.get(element.group) in all_bone_names
+ }
+ bone_total = sum(current_bone_weights.values())
+ if bone_total <= 1e-8:
+ bone_total = 1.0
+ bone_totals[vertex_index] = bone_total
+
+ # Diffuse the analytic field over the garment topology. This
+ # preserves the broad vertical/lateral motion while removing
+ # sharp per-triangle ownership changes from irregular meshes.
+ neighbors = {index: [] for index in target_fractions}
+ for edge in mesh_object.data.edges:
+ first, second = edge.vertices
+ if first in neighbors and second in neighbors:
+ neighbors[first].append(second)
+ neighbors[second].append(first)
+ for _iteration in range(4):
+ smoothed = {}
+ for vertex_index, fractions in target_fractions.items():
+ adjacent = neighbors[vertex_index]
+ if not adjacent:
+ smoothed[vertex_index] = fractions
+ continue
+ adjacent_count = float(len(adjacent))
+ averaged = {
+ name: sum(
+ target_fractions[other][name]
+ for other in adjacent
+ ) / adjacent_count
+ for name in target_bones
+ }
+ blended = {
+ name: fractions[name] * 0.65 + averaged[name] * 0.35
+ for name in target_bones
+ }
+ blend_total = sum(blended.values())
+ smoothed[vertex_index] = {
+ name: weight / blend_total
+ for name, weight in blended.items()
+ }
+ target_fractions = smoothed
+
+ changed_roots = set()
+ for vertex_index, fractions in target_fractions.items():
+ vertex = mesh_object.data.vertices[vertex_index]
+ current_bone_weights = {
+ group_name_by_index.get(element.group): float(element.weight)
+ for element in vertex.groups
+ if group_name_by_index.get(element.group) in all_bone_names
+ }
+ bone_total = bone_totals[vertex_index]
+ target_weights = {
+ name: fraction * bone_total
+ for name, fraction in fractions.items()
+ }
+ for name in current_bone_weights:
+ group_by_name[name].remove([vertex_index])
+ for name, weight in target_weights.items():
+ if weight > 1e-8:
+ group_by_name[name].add(
+ [vertex_index], weight, 'REPLACE')
+ changed_indices.add(vertex_index)
+ changed_roots.add(roots[vertex_index])
+ garment_marker.add([vertex_index], 1.0, 'REPLACE')
+
+ if changed_indices:
+ total_components += len(changed_roots)
+ print(
+ "[StableGen] Smooth garment leg follow: "
+ f"{len(changed_indices)} vertices across "
+ f"{len(changed_roots)} component(s), "
+ f"{absorbed_components} nearby island(s) absorbed"
+ )
+ else:
+ for root, data, share in garment_components:
+ component_changed = 0
+ for vertex_index in data["vertices"]:
+ vertex = mesh_object.data.vertices[vertex_index]
+ point = points[vertex_index]
+ height = point.dot(up_axis)
+ if height > hip_height + leg_height * 0.06:
+ continue
+ if height < foot_height - leg_height * 0.04:
+ continue
+
+ downward = max(
+ 0.0,
+ min(1.0, (hip_height - height) / (leg_height * 0.9)),
+ )
+ smooth_downward = downward * downward * (3.0 - 2.0 * downward)
+ pelvis_fraction = 0.88 - 0.38 * smooth_downward
+ side_value = (point - side_origin).dot(side_axis)
+ side_normalized = max(
+ -1.0,
+ min(1.0, side_value / max(side_separation * 0.7, 1e-6)),
+ )
+ side_strength = 0.18 + 0.08 * smooth_downward
+ left_split = 0.5 + side_strength * side_normalized
+ left_split = max(0.2, min(0.8, left_split))
+
+ current_bone_weights = {
+ group_name_by_index.get(element.group): float(element.weight)
+ for element in vertex.groups
+ if group_name_by_index.get(element.group) in all_bone_names
+ }
+ bone_total = sum(current_bone_weights.values())
+ if bone_total <= 1e-8:
+ continue
+
+ leg_fraction = 1.0 - pelvis_fraction
+ target_weights = {
+ pelvis_name: pelvis_fraction * bone_total,
+ left_thigh: leg_fraction * left_split * bone_total,
+ right_thigh: leg_fraction * (1.0 - left_split) * bone_total,
+ }
+ target_names = set(target_weights)
+ already_stabilized = all(
+ (
+ name in target_names
+ or weight <= 1e-6
+ )
+ for name, weight in current_bone_weights.items()
+ ) and all(
+ abs(current_bone_weights.get(name, 0.0) - weight) <= 1e-5
+ for name, weight in target_weights.items()
+ )
+ if already_stabilized:
+ garment_marker.add([vertex_index], 1.0, 'REPLACE')
+ continue
+ for name in current_bone_weights:
+ group_by_name[name].remove([vertex_index])
+ for name, weight in target_weights.items():
+ if weight > 1e-8:
+ group_by_name[name].add(
+ [vertex_index], weight, 'REPLACE')
+ changed_indices.add(vertex_index)
+ garment_marker.add([vertex_index], 1.0, 'REPLACE')
+ component_changed += 1
+
+ if component_changed:
+ total_components += 1
+ print(
+ "[StableGen] Garment stabilization: "
+ f"component {root}, {component_changed} vertices, "
+ f"spine {share['spine']:.0%}, "
+ f"legs {(share['left_leg'] + share['right_leg']):.0%}"
+ )
+ if changed_indices:
+ mesh_object.data.update()
+ total_changed += len(changed_indices)
+
+ print(
+ "[StableGen] Garment weighting complete: "
+ f"mode {mode}, {total_changed} vertices across "
+ f"{total_components} component(s), "
+ f"{total_absorbed_components} nearby island(s) absorbed"
+ )
+ return {
+ "changed_vertices": total_changed,
+ "components": total_components,
+ "absorbed_components": total_absorbed_components,
+ }
class Trellis2Generate(bpy.types.Operator):
"""Generate a 3D mesh from a reference image using TRELLIS.2 via ComfyUI.
@@ -546,6 +1637,41 @@ class Trellis2Generate(bpy.types.Operator):
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
print(f"[TRELLIS2] Scaled mesh to {target_bu} BU (factor {scale_factor:.4f})")
+ if (
+ autorig_enabled
+ and getattr(
+ context.scene,
+ 'trellis2_autorig_cleanup_cross_limb_weights',
+ True,
+ )
+ ):
+ try:
+ _sanitize_autorig_cross_limb_weights(imported_objects)
+ except Exception as exc:
+ print(
+ "[StableGen] Cross-limb weight cleanup failed; "
+ f"keeping the imported SkinTokens weights: {exc}"
+ )
+ traceback.print_exc()
+
+ garment_mode = getattr(
+ context.scene,
+ 'trellis2_autorig_garment_mode',
+ 'NONE',
+ )
+ if autorig_enabled and garment_mode in {'STABILIZE', 'LEG_FOLLOW'}:
+ try:
+ _stabilize_autorig_garment_weights(
+ imported_objects,
+ mode=garment_mode,
+ )
+ except Exception as exc:
+ print(
+ "[StableGen] Garment weighting failed; "
+ f"keeping the current skin weights: {exc}"
+ )
+ traceback.print_exc()
+
# --- Solidification ---
solidify_mesh = getattr(context.scene, 'trellis2_solidify', False)
if autorig_enabled and solidify_mesh:
@@ -1065,18 +2191,136 @@ class Trellis2Generate(bpy.types.Operator):
class StableGenAutoRigSelectedMesh(bpy.types.Operator):
- """Run SkinTokens auto-rigging on the currently selected mesh objects."""
+ """Run SkinTokens auto-rigging on the selected character mesh objects."""
bl_idname = "object.stablegen_autorig_selected_mesh"
- bl_label = "Auto-Rig Selected Mesh"
- bl_description = "Export the selected mesh to GLB, run SkinTokens in ComfyUI, and import the rigged GLB"
+ bl_label = "Auto-Rig Selected Character"
+ bl_description = (
+ "Join copies of the selected character's mesh parts when needed, export them to GLB, "
+ "run SkinTokens in ComfyUI, and import the rigged GLB"
+ )
bl_options = {'REGISTER', 'UNDO'}
hide_source: bpy.props.BoolProperty(
- name="Hide Source Mesh",
- description="Hide the original selected mesh objects after the rigged duplicate is imported",
+ name="Preserve Original Source",
+ description=(
+ "Keep the original mesh objects and hide them with Blender's eye-style "
+ "viewport toggle after the rigged result imports; when disabled, the "
+ "original objects are deleted after a successful import"
+ ),
default=True,
) # type: ignore
+ use_transfer: bpy.props.BoolProperty(
+ name="Transfer Original",
+ description="Transfer the generated rig back to the joined source mesh to preserve materials and scale",
+ default=True,
+ ) # type: ignore
+ use_skeleton: bpy.props.BoolProperty(
+ name="Use Existing Skeleton",
+ description=(
+ "Preserve an existing skeleton and generate only skin weights; "
+ "when disabled, any existing armature and skin binding are ignored"
+ ),
+ default=False,
+ ) # type: ignore
+ use_postprocess: bpy.props.BoolProperty(
+ name="Skin Postprocess",
+ description="Enable SkinTokens voxel skin post-processing before export",
+ default=False,
+ ) # type: ignore
+ cleanup_cross_limb_weights: bpy.props.BoolProperty(
+ name="Clean Limb Weights",
+ description=(
+ "After import, repair spatially implausible hand and foot weights "
+ "such as influences from the opposite limb, spine, pelvis, or legs"
+ ),
+ default=True,
+ ) # type: ignore
+ garment_mode: bpy.props.EnumProperty(
+ name="Garment Handling",
+ description="Optional post-import handling for long dresses and skirts",
+ items=(
+ ('NONE', "Original Weights", "Keep the generated garment weights"),
+ (
+ 'STABILIZE',
+ "Stabilized Dress",
+ "Detect long garment surfaces and apply a smooth pelvis/thigh blend",
+ ),
+ (
+ 'LEG_FOLLOW',
+ "Smooth Leg Follow",
+ "Smoothly drive detected long garments from the pelvis, thighs, and lower legs",
+ ),
+ ),
+ default='NONE',
+ ) # type: ignore
+ top_k: bpy.props.IntProperty(
+ name="Top K",
+ description="SkinTokens sampling top-k",
+ default=5,
+ min=1,
+ max=200,
+ ) # type: ignore
+ top_p: bpy.props.FloatProperty(
+ name="Top P",
+ description="SkinTokens nucleus sampling top-p",
+ default=0.95,
+ min=0.1,
+ max=1.0,
+ step=0.01,
+ ) # type: ignore
+ temperature: bpy.props.FloatProperty(
+ name="Temperature",
+ description="SkinTokens sampling temperature",
+ default=1.0,
+ min=0.1,
+ max=2.0,
+ step=0.1,
+ ) # type: ignore
+ repetition_penalty: bpy.props.FloatProperty(
+ name="Repetition Penalty",
+ description="SkinTokens repetition penalty",
+ default=2.0,
+ min=0.5,
+ max=3.0,
+ step=0.1,
+ ) # type: ignore
+ num_beams: bpy.props.IntProperty(
+ name="Beams",
+ description="Number of candidate rig-token sequences retained during SkinTokens generation",
+ default=10,
+ min=1,
+ max=20,
+ ) # type: ignore
+ model_ckpt: bpy.props.StringProperty(
+ name="Model Checkpoint",
+ description="Optional SkinTokens checkpoint path relative to SKINTOKENS_ROOT",
+ default="",
+ ) # type: ignore
+ hf_path: bpy.props.StringProperty(
+ name="HF Path",
+ description="Optional Hugging Face path passed to SkinTokens",
+ default="",
+ ) # type: ignore
+
+ _SETTING_BINDINGS = (
+ ("use_transfer", "trellis2_autorig_use_transfer", True),
+ ("use_skeleton", "trellis2_autorig_use_skeleton", False),
+ ("use_postprocess", "trellis2_autorig_use_postprocess", False),
+ (
+ "cleanup_cross_limb_weights",
+ "trellis2_autorig_cleanup_cross_limb_weights",
+ True,
+ ),
+ ("garment_mode", "trellis2_autorig_garment_mode", "NONE"),
+ ("top_k", "trellis2_autorig_top_k", 5),
+ ("top_p", "trellis2_autorig_top_p", 0.95),
+ ("temperature", "trellis2_autorig_temperature", 1.0),
+ ("repetition_penalty", "trellis2_autorig_repetition_penalty", 2.0),
+ ("num_beams", "trellis2_autorig_num_beams", 10),
+ ("model_ckpt", "trellis2_autorig_model_ckpt", ""),
+ ("hf_path", "trellis2_autorig_hf_path", ""),
+ )
_timer = None
_thread = None
@@ -1087,8 +2331,326 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
_active_ws = None
_progress = 0.0
_stage = "Initializing"
+ _overall_progress = 0.0
+ _overall_stage = "Initializing"
+ _phase_progress = 0.0
+ _phase_stage = ""
+ _current_phase = 0
+ _total_phases = 4
workflow_manager: object = None
+ _PHASE_WEIGHTS = (12.0, 75.0, 11.0, 2.0)
+
+ def _set_pipeline_phase(self, phase, label, percent, detail=None):
+ """Update standalone auto-rig overall and current-phase progress."""
+ phase = max(1, min(int(phase), self._total_phases))
+ percent = max(0.0, min(float(percent), 100.0))
+ start = sum(self._PHASE_WEIGHTS[:phase - 1])
+ overall = start + self._PHASE_WEIGHTS[phase - 1] * percent / 100.0
+
+ self._current_phase = phase
+ self._overall_progress = max(self._overall_progress, overall)
+ self._overall_stage = f"Phase {phase}/{self._total_phases}: {label}"
+ self._phase_progress = percent
+ self._phase_stage = detail or label
+
+ # Keep the original fields synchronized for integrations which still
+ # inspect the standalone operator's legacy single-bar state.
+ self._progress = self._overall_progress
+ self._stage = self._phase_stage
+
+ def _load_settings_from_scene(self, scene):
+ for operator_name, scene_name, fallback in self._SETTING_BINDINGS:
+ setattr(self, operator_name, getattr(scene, scene_name, fallback))
+
+ def _store_settings_in_scene(self, scene):
+ for operator_name, scene_name, _fallback in self._SETTING_BINDINGS:
+ setattr(scene, scene_name, getattr(self, operator_name))
+
+ def invoke(self, context, _event):
+ # The same button doubles as Cancel while a job is running. Do not put
+ # a confirmation dialog in front of that time-sensitive action.
+ if StableGenAutoRigSelectedMesh._is_running:
+ return self.execute(context)
+ self._load_settings_from_scene(context.scene)
+ return context.window_manager.invoke_props_dialog(self, width=520)
+
+ def draw(self, context):
+ layout = self.layout
+ layout.use_property_split = True
+ layout.use_property_decorate = False
+
+ mesh_count = len(self._collect_character_meshes(context.selected_objects))
+ if mesh_count > 1:
+ layout.label(
+ text=f"{mesh_count} mesh parts will be joined temporarily for SkinTokens",
+ icon='MESH_DATA',
+ )
+
+ behavior_box = layout.box()
+ behavior_box.label(text="Rigging Behavior", icon='ARMATURE_DATA')
+ behavior_box.prop(self, "use_transfer")
+ behavior_box.prop(self, "use_skeleton")
+ behavior_box.prop(self, "use_postprocess")
+ behavior_box.prop(self, "cleanup_cross_limb_weights")
+ behavior_box.prop(self, "garment_mode")
+ behavior_box.prop(self, "hide_source")
+ if self.hide_source:
+ behavior_box.label(
+ text="Original: preserved and hidden with the Outliner eye toggle",
+ icon='HIDE_ON',
+ )
+ else:
+ warning = behavior_box.row()
+ warning.alert = True
+ warning.label(
+ text="Replace mode: original mesh objects are deleted after success",
+ icon='ERROR',
+ )
+
+ sampling_box = layout.box()
+ sampling_box.label(text="Sampling", icon='SETTINGS')
+ grid = sampling_box.grid_flow(
+ row_major=True,
+ columns=2,
+ even_columns=True,
+ even_rows=False,
+ align=True,
+ )
+ grid.prop(self, "top_k")
+ grid.prop(self, "top_p")
+ grid.prop(self, "temperature")
+ grid.prop(self, "repetition_penalty")
+ sampling_box.prop(self, "num_beams")
+
+ model_box = layout.box()
+ model_box.label(text="Optional Model Overrides", icon='FILE_BLEND')
+ model_box.prop(self, "model_ckpt")
+ model_box.prop(self, "hf_path")
+
+ @staticmethod
+ def _collect_character_meshes(selected_objects):
+ """Return selected meshes plus meshes below selected hierarchy roots.
+
+ Imported FBX/GLTF characters commonly expose an Empty or Armature as the
+ convenient selectable root. Walking its descendants lets the standalone
+ operator handle those characters without requiring every part to be
+ selected manually. Object identity is used for de-duplication because a
+ mesh can be both explicitly selected and below a selected root.
+ """
+ meshes = []
+ seen = set()
+ explicitly_selected = {
+ obj.as_pointer() if hasattr(obj, "as_pointer") else id(obj)
+ for obj in selected_objects
+ }
+
+ def visit(obj):
+ object_key = obj.as_pointer() if hasattr(obj, "as_pointer") else id(obj)
+ if object_key in seen:
+ return
+ seen.add(object_key)
+ if obj.type == 'MESH':
+ is_explicit = object_key in explicitly_selected
+ preserved_source = bool(
+ obj.get("sg_autorig_preserved_source", False))
+ disabled = bool(obj.hide_viewport or obj.hide_get())
+ # A selected hierarchy root commonly contains both the visible
+ # rigged result and the source copy hidden by a previous run.
+ # Do not silently join that preserved copy back into the next
+ # SkinTokens input. Explicitly selecting the mesh itself still
+ # allows the user to rerig the original on purpose.
+ if is_explicit or not (preserved_source or disabled):
+ meshes.append(obj)
+ for child in obj.children:
+ visit(child)
+
+ for selected in selected_objects:
+ visit(selected)
+ return meshes
+
+ @staticmethod
+ def _related_armatures(selected_objects, meshes):
+ """Find armatures explicitly selected or used by the source meshes."""
+ armatures = []
+ seen = set()
+
+ def add(obj):
+ if not obj or obj.type != 'ARMATURE':
+ return
+ object_key = obj.as_pointer() if hasattr(obj, "as_pointer") else id(obj)
+ if object_key not in seen:
+ seen.add(object_key)
+ armatures.append(obj)
+
+ for obj in selected_objects:
+ add(obj)
+ for mesh in meshes:
+ ancestor = mesh.parent
+ while ancestor is not None:
+ add(ancestor)
+ ancestor = ancestor.parent
+ for modifier in mesh.modifiers:
+ if modifier.type == 'ARMATURE':
+ add(getattr(modifier, 'object', None))
+ return armatures
+
+ @staticmethod
+ def _make_joined_export_copy(
+ context, source_meshes, strip_existing_rig=False):
+ """Create one temporary mesh from copies of the source mesh objects.
+
+ Blender's join operation keeps the active copy's transform/modifiers and
+ merges material slots and same-named vertex groups from the other copies.
+ This gives SkinTokens the single mesh node it expects while leaving every
+ source object and datablock untouched. When ``strip_existing_rig`` is
+ true, Armature modifiers and armature ancestry are removed from the
+ copies so a previously rigged character is exported as plain rest mesh.
+
+ Returns ``(joined_object, copied_mesh_datablocks)``. The caller owns and
+ must remove both after export.
+ """
+ copies = []
+ copied_meshes = []
+ try:
+ for index, source in enumerate(source_meshes):
+ duplicate = source.copy()
+ duplicate.data = source.data.copy()
+ duplicate.name = f"SG_AutoRigPart_{index:03d}"
+ duplicate.data.name = f"SG_AutoRigPartMesh_{index:03d}"
+ context.collection.objects.link(duplicate)
+ duplicate.hide_select = False
+ duplicate.hide_viewport = False
+ duplicate.hide_render = False
+ duplicate.hide_set(False)
+ if strip_existing_rig:
+ world_matrix = duplicate.matrix_world.copy()
+ ancestor = duplicate.parent
+ has_armature_ancestor = False
+ while ancestor is not None:
+ if ancestor.type == 'ARMATURE':
+ has_armature_ancestor = True
+ break
+ ancestor = ancestor.parent
+ if has_armature_ancestor:
+ duplicate.parent = None
+ duplicate.matrix_world = world_matrix
+ for modifier in list(duplicate.modifiers):
+ if modifier.type == 'ARMATURE':
+ duplicate.modifiers.remove(modifier)
+ copies.append(duplicate)
+ copied_meshes.append(duplicate.data)
+
+ bpy.ops.object.select_all(action='DESELECT')
+ for duplicate in copies:
+ duplicate.select_set(True)
+
+ # Prefer a mesh already driven by an armature as active so its
+ # Armature modifier survives the join when use_skeleton is enabled.
+ active_copy = next(
+ (
+ duplicate for duplicate in copies
+ if any(modifier.type == 'ARMATURE' for modifier in duplicate.modifiers)
+ ),
+ copies[0],
+ )
+ context.view_layer.objects.active = active_copy
+ if len(copies) > 1:
+ bpy.ops.object.join()
+ joined = context.view_layer.objects.active
+ joined.name = "SG_AutoRigJoinedInput"
+ joined.data.name = "SG_AutoRigJoinedInputMesh"
+ joined["sg_autorig_temporary_join"] = True
+ return joined, copied_meshes
+ except Exception:
+ for duplicate in copies:
+ try:
+ if duplicate and duplicate.name in bpy.data.objects:
+ bpy.data.objects.remove(duplicate, do_unlink=True)
+ except ReferenceError:
+ pass
+ for mesh_data in copied_meshes:
+ try:
+ if mesh_data and mesh_data.name in bpy.data.meshes and mesh_data.users == 0:
+ bpy.data.meshes.remove(mesh_data)
+ except ReferenceError:
+ pass
+ raise
+
+ @staticmethod
+ def _remove_joined_export_copy(joined, copied_meshes):
+ try:
+ if joined and joined.name in bpy.data.objects:
+ bpy.data.objects.remove(joined, do_unlink=True)
+ except ReferenceError:
+ pass
+ for mesh_data in copied_meshes:
+ try:
+ if mesh_data and mesh_data.name in bpy.data.meshes and mesh_data.users == 0:
+ bpy.data.meshes.remove(mesh_data)
+ except ReferenceError:
+ pass
+
+ @staticmethod
+ def _preserve_autorig_sources(source_names):
+ """Keep source meshes with ordinary Outliner eye-style hiding."""
+ preserved = 0
+ for name in source_names:
+ obj = bpy.data.objects.get(name)
+ if not obj or obj.type != 'MESH':
+ continue
+ obj["sg_autorig_preserved_source"] = True
+ # Older StableGen versions used hide_viewport, whose monitor toggle
+ # is independent of the familiar Outliner eye. Clear it before
+ # applying the reversible eye-style hide.
+ obj.hide_viewport = False
+ obj.hide_set(True)
+ obj.hide_render = True
+ preserved += 1
+ return preserved
+
+ @staticmethod
+ def _replace_autorig_sources(source_names, source_armature_names):
+ """Delete superseded source meshes and now-unused source armatures."""
+ removed_meshes = 0
+ for name in source_names:
+ obj = bpy.data.objects.get(name)
+ if not obj or obj.type != 'MESH':
+ continue
+ bpy.data.objects.remove(obj, do_unlink=True)
+ removed_meshes += 1
+
+ removed_armatures = 0
+ for name in source_armature_names:
+ armature = bpy.data.objects.get(name)
+ if not armature or armature.type != 'ARMATURE':
+ continue
+
+ still_used = False
+ for obj in bpy.data.objects:
+ if obj.type != 'MESH':
+ continue
+ if any(
+ modifier.type == 'ARMATURE'
+ and getattr(modifier, 'object', None) == armature
+ for modifier in obj.modifiers):
+ still_used = True
+ break
+ parent = obj.parent
+ while parent is not None:
+ if parent == armature:
+ still_used = True
+ break
+ parent = parent.parent
+ if still_used:
+ break
+
+ if not still_used:
+ bpy.data.objects.remove(armature, do_unlink=True)
+ removed_armatures += 1
+
+ return removed_meshes, removed_armatures
+
@classmethod
def poll(cls, context):
if cls._is_running:
@@ -1106,8 +2668,8 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
if sg_modal_active(context):
cls.poll_message_set("Another operation is in progress")
return False
- if not any(obj.type == 'MESH' for obj in context.selected_objects):
- cls.poll_message_set("Select at least one mesh object to auto-rig")
+ if not cls._collect_character_meshes(context.selected_objects):
+ cls.poll_message_set("Select a mesh object or an imported character root to auto-rig")
return False
return True
@@ -1136,16 +2698,19 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
return {'FINISHED'}
selected_objects = list(context.selected_objects)
- selected_meshes = [obj for obj in selected_objects if obj.type == 'MESH']
+ selected_meshes = self._collect_character_meshes(selected_objects)
if not selected_meshes:
- self.report({'ERROR'}, "Select at least one mesh object to auto-rig")
+ self.report({'ERROR'}, "Select a mesh object or an imported character root to auto-rig")
return {'CANCELLED'}
- server_address = context.preferences.addons[_ADDON_PKG].preferences.server_address
- if not self._server_is_localish(server_address):
- self.report({
- 'WARNING'
- }, "ComfyUI must be able to read the exported GLB path for this operator to work")
+ # Commit dialog values only after the user confirms and the selection is
+ # valid. Cancelling the dialog therefore leaves scene settings intact.
+ self._store_settings_in_scene(context.scene)
+
+ self.report(
+ {'INFO'},
+ "The exported GLB will be uploaded to the ComfyUI input directory",
+ )
try:
gen_dirs = get_generation_dirs(context)
@@ -1154,26 +2719,56 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
export_path = os.path.join(save_dir, f"stablegen_autorig_source_{timestamp}.glb")
- export_objects = []
- for obj in selected_objects:
- if obj.type in {'MESH', 'ARMATURE'} and obj not in export_objects:
- export_objects.append(obj)
- for obj in selected_meshes:
- if obj.parent and obj.parent.type == 'ARMATURE' and obj.parent not in export_objects:
- export_objects.append(obj.parent)
-
previous_active = context.view_layer.objects.active
- bpy.ops.object.select_all(action='DESELECT')
+ joined_export = None
+ copied_mesh_data = []
try:
+ related_armatures = self._related_armatures(
+ selected_objects,
+ selected_meshes,
+ )
+ strip_existing_rig = not self.use_skeleton
+ needs_export_copy = (
+ len(selected_meshes) > 1
+ or (strip_existing_rig and bool(related_armatures))
+ )
+ if needs_export_copy:
+ joined_export, copied_mesh_data = self._make_joined_export_copy(
+ context,
+ selected_meshes,
+ strip_existing_rig=strip_existing_rig,
+ )
+ export_meshes = [joined_export]
+ if len(selected_meshes) > 1:
+ print(
+ f"[StableGen] Auto-rig staging joined {len(selected_meshes)} "
+ "source mesh objects into one temporary SkinTokens input"
+ )
+ if strip_existing_rig and related_armatures:
+ print(
+ "[StableGen] Auto-rig staging removed the existing "
+ "armature and skin binding from the SkinTokens input"
+ )
+ else:
+ export_meshes = selected_meshes
+
+ export_objects = list(export_meshes)
+ if self.use_skeleton:
+ for armature in related_armatures:
+ if armature not in export_objects:
+ export_objects.append(armature)
+
+ bpy.ops.object.select_all(action='DESELECT')
for obj in export_objects:
obj.select_set(True)
- context.view_layer.objects.active = selected_meshes[0]
+ context.view_layer.objects.active = export_meshes[0]
bpy.ops.export_scene.gltf(
filepath=export_path,
export_format='GLB',
use_selection=True,
)
finally:
+ self._remove_joined_export_copy(joined_export, copied_mesh_data)
bpy.ops.object.select_all(action='DESELECT')
for obj in selected_objects:
if context.scene.objects.get(obj.name):
@@ -1195,7 +2790,16 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
self._rigged_data = None
self._progress = 0.0
self._stage = "Queued"
+ self._overall_progress = 0.0
+ self._overall_stage = "Queued"
+ self._phase_progress = 0.0
+ self._phase_stage = "Preparing source"
+ self._current_phase = 0
self._source_names = [obj.name for obj in selected_meshes]
+ self._source_armature_names = [
+ obj.name for obj in related_armatures
+ ]
+ self._source_mesh_count = len(selected_meshes)
self._export_path = export_path
from ..workflows import WorkflowManager
@@ -1209,17 +2813,17 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
context.window_manager.modal_handler_add(self)
self._timer = context.window_manager.event_timer_add(0.5, window=context.window)
- self.report({'INFO'}, "Auto-rigging started")
+ if len(selected_meshes) > 1:
+ self.report(
+ {'INFO'},
+ f"Auto-rigging started with {len(selected_meshes)} joined mesh parts",
+ )
+ else:
+ self.report({'INFO'}, "Auto-rigging started")
return {'RUNNING_MODAL'}
- @staticmethod
- def _server_is_localish(server_address):
- host = (server_address or '').split(':')[0].strip().lower()
- return host in ('', '127.0.0.1', 'localhost', '0.0.0.0', '::1')
-
def _run_autorig(self, context, export_path):
try:
- self._stage = "Auto-Rigging"
result = self.workflow_manager.generate_skintokens_autorig_file(context, export_path)
if self._cancelled:
return
@@ -1260,6 +2864,7 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
return {'CANCELLED'}
try:
+ self._set_pipeline_phase(4, "Blender Import", 0, "Writing rigged GLB")
gen_dirs = get_generation_dirs(context)
save_dir = gen_dirs.get("revision", "") or context.preferences.addons[_ADDON_PKG].preferences.output_dir
os.makedirs(save_dir, exist_ok=True)
@@ -1269,6 +2874,7 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
handle.write(self._rigged_data)
bpy.ops.import_scene.gltf(filepath=output_path)
+ self._set_pipeline_phase(4, "Blender Import", 45, "Preparing imported rig")
imported_objects = list(context.selected_objects)
for obj in imported_objects:
obj["sg_generated"] = True
@@ -1278,6 +2884,38 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
if mesh_objects:
Trellis2Generate._clear_imported_custom_normals(mesh_objects)
+ if self.cleanup_cross_limb_weights:
+ self._set_pipeline_phase(4, "Blender Import", 65, "Cleaning limb weights")
+ try:
+ _sanitize_autorig_cross_limb_weights(imported_objects)
+ except Exception as exc:
+ self.report(
+ {'WARNING'},
+ "Cross-limb weight cleanup failed; imported the original "
+ f"SkinTokens weights: {exc}",
+ )
+ traceback.print_exc()
+
+ if self.garment_mode in {'STABILIZE', 'LEG_FOLLOW'}:
+ garment_stage = (
+ "Smoothing garment leg follow"
+ if self.garment_mode == 'LEG_FOLLOW'
+ else "Stabilizing garment weights"
+ )
+ self._set_pipeline_phase(4, "Blender Import", 82, garment_stage)
+ try:
+ _stabilize_autorig_garment_weights(
+ imported_objects,
+ mode=self.garment_mode,
+ )
+ except Exception as exc:
+ self.report(
+ {'WARNING'},
+ "Garment weighting failed; imported the current "
+ f"skin weights: {exc}",
+ )
+ traceback.print_exc()
+
bpy.ops.object.select_all(action='DESELECT')
for obj in imported_objects:
obj.select_set(True)
@@ -1286,15 +2924,31 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):
elif imported_objects:
context.view_layer.objects.active = imported_objects[0]
+ source_names = list(getattr(self, '_source_names', []))
if self.hide_source:
- imported_names = {obj.name for obj in imported_objects}
- for name in getattr(self, '_source_names', []):
- obj = bpy.data.objects.get(name)
- if obj and obj.name not in imported_names:
- obj.hide_viewport = True
- obj.hide_render = True
-
- self.report({'INFO'}, f"Auto-rigged mesh imported: {os.path.basename(output_path)}")
+ preserved = self._preserve_autorig_sources(source_names)
+ print(
+ f"[StableGen] Preserved {preserved} source mesh object(s) "
+ "with eye-style hiding"
+ )
+ else:
+ removed_meshes, removed_armatures = self._replace_autorig_sources(
+ source_names,
+ list(getattr(self, '_source_armature_names', [])),
+ )
+ print(
+ f"[StableGen] Replace-original mode removed {removed_meshes} "
+ f"source mesh object(s) and {removed_armatures} unused "
+ "source armature object(s)"
+ )
+
+ source_count = int(getattr(self, '_source_mesh_count', 1))
+ part_note = f" from {source_count} joined parts" if source_count > 1 else ""
+ self._set_pipeline_phase(4, "Blender Import", 100, "Import complete")
+ self.report(
+ {'INFO'},
+ f"Auto-rigged mesh imported{part_note}: {os.path.basename(output_path)}",
+ )
return {'FINISHED'}
except Exception as exc:
self.report({'ERROR'}, f"Failed to import rigged GLB: {exc}")
diff --git a/stablegen/mesh_gen/workflows.py b/stablegen/mesh_gen/workflows.py
index 6628866..1bda86d 100644
--- a/stablegen/mesh_gen/workflows.py
+++ b/stablegen/mesh_gen/workflows.py
@@ -1,6 +1,7 @@
import os
import json
import email.utils
+import ntpath
import posixpath
import re
import uuid
@@ -18,6 +19,26 @@ import numpy as np
from PIL import Image
_ADDON_PKG = __package__.rsplit('.', 1)[0]
+_SKINTOKENS_PROGRESS_EVENT = "stablegen_skintokens_progress"
+
+
+def _progress_percent(data):
+ """Return a clamped percentage from a ComfyUI progress payload."""
+ try:
+ value = float(data.get("value", 0.0))
+ maximum = float(data.get("max", 100.0))
+ except (TypeError, ValueError):
+ return None
+ if maximum <= 0:
+ return None
+ return max(0.0, min(100.0, value * 100.0 / maximum))
+
+
+def _message_node_matches(data, expected_node):
+ node = data.get("node")
+ if isinstance(node, (list, tuple)) and node:
+ node = node[0]
+ return str(node or "") == str(expected_node)
class _Trellis2WorkflowMixin:
@@ -125,6 +146,201 @@ class _Trellis2WorkflowMixin:
host = server_address.split(':')[0].strip()
return host in ('127.0.0.1', 'localhost', '0.0.0.0', '::1', '')
+ @staticmethod
+ def _join_remote_path(base_path, *parts):
+ path_module = (
+ ntpath
+ if re.match(r"^[A-Za-z]:[\\/]", base_path or "")
+ or "\\" in (base_path or "")
+ else posixpath
+ )
+ result = base_path
+ for part in parts:
+ for component in re.split(r"[\\/]", part or ""):
+ if component:
+ result = path_module.join(result, component)
+ return path_module.normpath(result)
+
+ @staticmethod
+ def _comfyui_remote_upload_limit(server_address):
+ """Return the host's configured upload limit in bytes when discoverable."""
+ try:
+ stats_url = f"http://{server_address}/system_stats"
+ stats = json.loads(urllib.request.urlopen(
+ stats_url, timeout=get_timeout('api')).read())
+ except Exception:
+ return None
+ system = stats.get("system", {}) if isinstance(stats, dict) else {}
+ argv = system.get("argv", []) if isinstance(system, dict) else []
+ if not isinstance(argv, list):
+ return None
+ argv = [str(value) for value in argv]
+ limit_mb = None
+ for index, value in enumerate(argv):
+ if value == "--max-upload-size" and index + 1 < len(argv):
+ limit_mb = argv[index + 1]
+ break
+ prefix = "--max-upload-size="
+ if value.startswith(prefix):
+ limit_mb = value[len(prefix):]
+ break
+ if limit_mb is None:
+ # This is ComfyUI's command-line default when the option is absent.
+ limit_mb = 100.0
+ try:
+ return max(0, int(float(limit_mb) * 1024 * 1024))
+ except (TypeError, ValueError):
+ return None
+
+ @classmethod
+ def _comfyui_base_from_internal_folder_paths(cls, server_address):
+ """Infer the ComfyUI base directory from its registered model paths.
+
+ Recent ComfyUI builds expose ``/internal/folder_paths`` even when
+ ``/system_stats`` contains only a relative ``main.py`` argv entry and
+ omits the input/output roots. The default model directories live below
+ ``<base>/models``. Extra model paths may point elsewhere, so candidates
+ are scored across categories with each category's first (default) path
+ weighted most heavily.
+ """
+ try:
+ url = f"http://{server_address}/internal/folder_paths"
+ registered = json.loads(urllib.request.urlopen(
+ url, timeout=get_timeout('api')).read())
+ except Exception as exc:
+ print(
+ "[StableGen] Could not query ComfyUI internal folder paths: "
+ f"{exc}"
+ )
+ return None
+ if not isinstance(registered, dict):
+ return None
+
+ scores = {}
+ order = []
+ for values in registered.values():
+ if isinstance(values, str):
+ values = [values]
+ if not isinstance(values, (list, tuple)):
+ continue
+ category_candidates = set()
+ for index, value in enumerate(values):
+ if not isinstance(value, str):
+ continue
+ match = re.match(
+ r"^(.*)[\\/]models(?:[\\/].*)?$",
+ value.strip(),
+ flags=re.IGNORECASE,
+ )
+ if not match or not match.group(1):
+ continue
+ candidate = ntpath.normpath(match.group(1)) if (
+ re.match(r"^[A-Za-z]:[\\/]", value) or "\\" in value
+ ) else posixpath.normpath(match.group(1))
+ key = candidate.lower() if "\\" in candidate else candidate
+ if key in category_candidates:
+ continue
+ category_candidates.add(key)
+ if key not in scores:
+ scores[key] = [0, candidate]
+ order.append(key)
+ scores[key][0] += 3 if index == 0 else 1
+
+ if not scores:
+ return None
+ best_key = max(order, key=lambda key: scores[key][0])
+ base_dir = scores[best_key][1]
+ print(
+ "[StableGen] Inferred ComfyUI base directory from registered "
+ f"model paths: {base_dir}"
+ )
+ return base_dir
+
+ @classmethod
+ def _comfyui_uploaded_file_path(
+ cls, server_address, upload_info):
+ """Resolve an uploaded input reference to an absolute host filesystem path."""
+ for key in ("path", "filepath", "full_path"):
+ value = upload_info.get(key)
+ if value and (ntpath.isabs(value) or posixpath.isabs(value)):
+ return value
+
+ try:
+ stats_url = f"http://{server_address}/system_stats"
+ stats = json.loads(urllib.request.urlopen(
+ stats_url, timeout=get_timeout('api')).read())
+ except Exception as exc:
+ print(f"[StableGen] Could not query ComfyUI input directory: {exc}")
+ return None
+
+ system = stats.get("system", {}) if isinstance(stats, dict) else {}
+ input_dir = None
+ for container in (stats, system):
+ if not isinstance(container, dict):
+ continue
+ for key in ("input_dir", "input_directory"):
+ if container.get(key):
+ input_dir = container[key]
+ break
+ if input_dir:
+ break
+
+ argv = system.get("argv", []) if isinstance(system, dict) else []
+ argv = [str(value) for value in argv] if isinstance(argv, list) else []
+
+ def argument_value(option):
+ for index, value in enumerate(argv):
+ if value == option and index + 1 < len(argv):
+ return argv[index + 1]
+ prefix = option + "="
+ if value.startswith(prefix):
+ return value[len(prefix):]
+ return None
+
+ base_dir = argument_value("--base-directory")
+ if not input_dir:
+ input_dir = argument_value("--input-directory")
+ if input_dir and not (ntpath.isabs(input_dir) or posixpath.isabs(input_dir)):
+ if base_dir:
+ input_dir = cls._join_remote_path(base_dir, input_dir)
+ elif argv and (ntpath.isabs(argv[0]) or posixpath.isabs(argv[0])):
+ script_dir = ntpath.dirname(argv[0]) if "\\" in argv[0] else posixpath.dirname(argv[0])
+ input_dir = cls._join_remote_path(script_dir, input_dir)
+ if not input_dir and base_dir:
+ input_dir = cls._join_remote_path(base_dir, "input")
+ if not input_dir:
+ output_dir = stats.get("output_dir") or system.get("output_dir")
+ if output_dir:
+ path_module = ntpath if "\\" in output_dir else posixpath
+ input_dir = cls._join_remote_path(
+ path_module.dirname(output_dir), "input")
+ if not input_dir:
+ inferred_base = cls._comfyui_base_from_internal_folder_paths(
+ server_address)
+ if inferred_base:
+ input_dir = cls._join_remote_path(inferred_base, "input")
+ if not input_dir and argv and (ntpath.isabs(argv[0]) or posixpath.isabs(argv[0])):
+ path_module = ntpath if "\\" in argv[0] else posixpath
+ input_dir = cls._join_remote_path(
+ path_module.dirname(argv[0]), "input")
+ if not input_dir:
+ # ComfyUI normally starts with its base directory as the process
+ # working directory. A relative reference is preferable to
+ # inventing an absolute host path and remains correct through
+ # localhost tunnels such as zrok/SSH. Custom input-directory users
+ # are handled by the explicit metadata and argv branches above.
+ input_dir = "input"
+ print(
+ "[StableGen] ComfyUI did not expose an absolute input directory; "
+ "using a process-relative input path"
+ )
+
+ return cls._join_remote_path(
+ input_dir,
+ upload_info.get("subfolder", ""),
+ upload_info.get("name", ""),
+ )
+
@staticmethod
def _is_trellis2_mesh_output(value):
"""Return True when *value* looks like a TRELLIS.2 mesh output file."""
@@ -665,6 +881,26 @@ class _Trellis2WorkflowMixin:
server_address = context.preferences.addons[_ADDON_PKG].preferences.server_address
scene = context.scene
+ def _set_phase(phase, label, percent, detail=None):
+ if hasattr(self.operator, '_set_pipeline_phase'):
+ self.operator._set_pipeline_phase(phase, label, percent, detail)
+ else:
+ self.operator._progress = percent
+ self.operator._stage = detail or label
+
+ def _transfer_detail(action, completed, total, attempt):
+ completed_mb = completed / (1024 * 1024)
+ if total:
+ total_mb = total / (1024 * 1024)
+ percent = completed * 100.0 / total
+ detail = f"{action}: {completed_mb:.1f}/{total_mb:.1f} MiB"
+ else:
+ percent = 0.0
+ detail = f"{action}: {completed_mb:.1f} MiB"
+ if attempt > 1:
+ detail += f" (attempt {attempt})"
+ return percent, detail
+
if not getattr(scene, 'skintokens_autorig_available', False):
return {
"error": (
@@ -675,6 +911,69 @@ class _Trellis2WorkflowMixin:
if not self._check_server_alive(server_address):
return {"error": "ComfyUI server is not responding. Please restart it and try again."}
+ # Always upload standalone auto-rig inputs. An address that looks local
+ # can still terminate on another computer through zrok, SSH forwarding,
+ # a reverse proxy, a container, or a VM. In those cases passing the
+ # Blender-side absolute path makes SkinTokens look for a file that only
+ # exists on the client. Uploading is also valid for a genuinely local
+ # ComfyUI instance and gives both cases the same deterministic behavior.
+ from .._generator_utils import (
+ _TransferCancelled,
+ download_file_with_resume,
+ upload_file_to_comfyui,
+ )
+
+ upload_limit = self._comfyui_remote_upload_limit(server_address)
+ source_size = os.path.getsize(input_glb_path)
+ if upload_limit and source_size > upload_limit:
+ source_mb = source_size / (1024 * 1024)
+ limit_mb = upload_limit / (1024 * 1024)
+ required_mb = ((int(source_mb) // 64) + 1) * 64
+ return {
+ "error": (
+ f"The exported GLB is {source_mb:.2f} MB, exceeding the "
+ f"ComfyUI upload limit of {limit_mb:.0f} MB. "
+ "On the ComfyUI host, set --max-upload-size "
+ f"{required_mb} or higher and restart ComfyUI."
+ )
+ }
+ _set_phase(1, "Source Upload", 0, "Starting upload")
+
+ def _upload_progress(completed, total, attempt):
+ percent, detail = _transfer_detail(
+ "Uploading source", completed, total, attempt)
+ _set_phase(1, "Source Upload", percent, detail)
+
+ upload_info = upload_file_to_comfyui(
+ server_address,
+ input_glb_path,
+ file_type="input",
+ subfolder="stablegen_autorig",
+ progress_cb=_upload_progress,
+ cancel_cb=lambda: getattr(self.operator, '_cancelled', False),
+ max_retries=4,
+ )
+ if not upload_info:
+ if getattr(self.operator, '_cancelled', False):
+ return {"error": "cancelled"}
+ return {
+ "error": (
+ "Could not upload the exported GLB to ComfyUI. "
+ "Check the ComfyUI upload-size limit and network connection."
+ )
+ }
+ comfyui_input_path = self._comfyui_uploaded_file_path(
+ server_address, upload_info)
+ if not comfyui_input_path:
+ return {
+ "error": (
+ "The GLB was uploaded to ComfyUI, but StableGen could not "
+ "discover the host input directory from /system_stats."
+ )
+ }
+ print(f"[StableGen] Auto-rig source uploaded to: {comfyui_input_path}")
+ _set_phase(1, "Source Upload", 100, "Upload complete")
+
self._flush_comfyui_vram(server_address, label="Pre-auto-rigging")
unique_prefix = f"stablegen_autorig_{uuid.uuid4().hex[:8]}"
@@ -682,7 +981,7 @@ class _Trellis2WorkflowMixin:
"1": {
"class_type": "StableGenSkinTokensAutoRig",
"inputs": {
- "input_path": input_glb_path,
+ "input_path": comfyui_input_path,
"output_prefix": unique_prefix,
"install_policy": "auto",
"use_transfer": bool(getattr(scene, 'trellis2_autorig_use_transfer', True)),
@@ -716,10 +1015,7 @@ class _Trellis2WorkflowMixin:
try:
prompt_id = self._queue_prompt(prompt, client_id, server_address)
- if hasattr(self.operator, '_stage'):
- self.operator._stage = "Auto-Rigging"
- if hasattr(self.operator, '_progress'):
- self.operator._progress = 5
+ _set_phase(2, "SkinTokens Rigging", 0, "Queued on ComfyUI")
while True:
if _cancelled():
@@ -743,15 +1039,16 @@ class _Trellis2WorkflowMixin:
if data.get('prompt_id') != prompt_id:
continue
if data.get('node') is None:
- if hasattr(self.operator, '_progress'):
- self.operator._progress = 100
+ _set_phase(
+ 2, "SkinTokens Rigging", 100,
+ "Rig generation complete")
break
if data.get('node') == "1":
print("[StableGen] Executing node: Auto-Rigging")
- if hasattr(self.operator, '_stage'):
- self.operator._stage = "Auto-Rigging"
- if hasattr(self.operator, '_progress'):
- self.operator._progress = max(self.operator._progress, 10)
+ _set_phase(
+ 2, "SkinTokens Rigging",
+ max(self.operator._phase_progress, 1),
+ "Starting SkinTokens")
elif message.get('type') == 'executed':
data = message.get('data', {})
@@ -760,6 +1057,36 @@ class _Trellis2WorkflowMixin:
if refs:
output_refs.extend(refs)
+ elif message.get('type') == _SKINTOKENS_PROGRESS_EVENT:
+ data = message.get('data', {})
+ if not _message_node_matches(data, "1"):
+ continue
+ if str(data.get('run_id') or '') != unique_prefix:
+ continue
+ percent = _progress_percent(data)
+ stage = str(data.get('stage') or '').strip()
+ detail = str(data.get('detail') or '').strip()
+ if percent is not None:
+ percent = max(self.operator._phase_progress, percent)
+ _set_phase(
+ 2, "SkinTokens Rigging", percent,
+ detail or stage or "Auto-Rigging")
+ elif stage:
+ _set_phase(
+ 2, "SkinTokens Rigging",
+ self.operator._phase_progress, detail or stage)
+
+ elif message.get('type') == 'progress':
+ data = message.get('data', {})
+ if not _message_node_matches(data, "1"):
+ continue
+ percent = _progress_percent(data)
+ if percent is not None:
+ _set_phase(
+ 2, "SkinTokens Rigging",
+ max(self.operator._phase_progress, percent),
+ "Auto-Rigging")
+
elif message.get('type') == 'execution_error':
error_data = message.get('data', {})
error_msg = error_data.get('exception_message', 'Unknown error')
@@ -786,12 +1113,16 @@ class _Trellis2WorkflowMixin:
print(f"[StableGen] SkinTokens history lookup failed: {hist_err}")
for file_ref in output_refs:
+ if _cancelled():
+ return {"error": "cancelled"}
path = file_ref.get('path') or ''
if path and os.path.isfile(path):
try:
+ _set_phase(3, "Result Download", 0, "Reading local result")
with open(path, 'rb') as handle:
data = handle.read()
if data:
+ _set_phase(3, "Result Download", 100, "Result ready")
return data
except OSError as read_err:
print(f"[StableGen] SkinTokens direct file read failed: {read_err}")
@@ -800,9 +1131,24 @@ class _Trellis2WorkflowMixin:
if not view_url:
continue
try:
- data = urllib.request.urlopen(view_url, timeout=get_timeout('transfer')).read()
+ _set_phase(3, "Result Download", 0, "Starting download")
+
+ def _download_progress(completed, total, attempt):
+ percent, detail = _transfer_detail(
+ "Downloading result", completed, total, attempt)
+ _set_phase(3, "Result Download", percent, detail)
+
+ data = download_file_with_resume(
+ view_url,
+ progress_cb=_download_progress,
+ cancel_cb=_cancelled,
+ max_retries=6,
+ )
if data:
+ _set_phase(3, "Result Download", 100, "Download complete")
return data
+ except _TransferCancelled:
+ return {"error": "cancelled"}
except Exception as view_err:
print(f"[StableGen] SkinTokens HTTP download failed: {view_err}")
@@ -1232,6 +1578,40 @@ class _Trellis2WorkflowMixin:
f"executed event: {self._describe_trellis2_file_ref(refs[0])}"
)
+ elif message['type'] == _SKINTOKENS_PROGRESS_EVENT:
+ if not autorig_enabled:
+ continue
+ p_data = message.get('data', {})
+ autorig_node_id = NODES.get('autorig')
+ if not _message_node_matches(p_data, autorig_node_id):
+ continue
+ expected_run_id = f"{unique_prefix}_skintokens"
+ if str(p_data.get('run_id') or '') != expected_run_id:
+ continue
+
+ autorig_phase = getattr(self.operator, '_autorig_phase', 0)
+ if autorig_phase:
+ if getattr(self.operator, '_current_phase', 0) != autorig_phase:
+ self.operator._current_phase = autorig_phase
+ self.operator._phase_progress = 0
+ total_phases = getattr(
+ self.operator, '_total_phases', autorig_phase)
+ self.operator._overall_stage = (
+ f"Phase {autorig_phase}/{total_phases}: Auto-Rigging"
+ )
+
+ percent = _progress_percent(p_data)
+ if percent is not None:
+ self.operator._phase_progress = max(
+ self.operator._phase_progress, percent)
+ self.operator._detail_progress = percent
+ stage = str(p_data.get('stage') or 'Auto-Rigging').strip()
+ detail = str(p_data.get('detail') or '').strip()
+ self.operator._phase_stage = stage
+ self.operator._detail_stage = detail or stage
+ if hasattr(self.operator, '_update_overall'):
+ self.operator._update_overall()
+
elif message['type'] == 'progress':
# Within-node progress (sampler steps).
# TRELLIS.2 nodes may emit separate runs of progress
@@ -1254,6 +1634,8 @@ class _Trellis2WorkflowMixin:
if autorig_enabled and _current_exec_node == 'autorig':
autorig_phase = getattr(self.operator, '_autorig_phase', 0)
if autorig_phase:
+ if getattr(self.operator, '_current_phase', 0) != autorig_phase:
+ self.operator._phase_progress = 0
self.operator._current_phase = autorig_phase
total_phases = getattr(self.operator, '_total_phases', autorig_phase)
self.operator._overall_stage = (
@@ -1290,6 +1672,16 @@ class _Trellis2WorkflowMixin:
step_progress = (p_value / p_max) * 100 if p_max else 0
+ if _current_exec_node == 'autorig':
+ self.operator._phase_progress = max(
+ self.operator._phase_progress, step_progress)
+ self.operator._detail_progress = step_progress
+ if not self.operator._detail_stage:
+ self.operator._detail_stage = "Auto-Rigging"
+ if hasattr(self.operator, '_update_overall'):
+ self.operator._update_overall()
+ continue
+
# Detect sub-phase transition
if p_value < _prev_p_value:
_sub_phase_idx = min(_sub_phase_idx + 1, _sub_phase_count - 1)
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index d6ace3d..17aa09b 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -279,12 +279,20 @@ class StableGenPanel(bpy.types.Panel):
elif autorig_op:
action_row.operator("object.stablegen_autorig_selected_mesh", text="Cancel Auto-Rigging", icon="CANCEL")
progress_col = layout.column()
- progress = getattr(autorig_op, '_progress', 0)
- stage = getattr(autorig_op, '_stage', 'Auto-Rigging')
+ overall = getattr(autorig_op, '_overall_progress', 0)
+ overall_stage = getattr(
+ autorig_op, '_overall_stage', 'Initializing Auto-Rigging')
progress_col.progress(
- text=f"{stage} ({progress:.0f}%)",
- factor=max(0.0, min(progress / 100.0, 1.0))
+ text=f"{overall_stage} ({overall:.0f}%)",
+ factor=max(0.0, min(overall / 100.0, 1.0))
)
+ phase = getattr(autorig_op, '_phase_progress', 0)
+ phase_stage = getattr(autorig_op, '_phase_stage', '')
+ if phase_stage:
+ progress_col.progress(
+ text=f"{phase_stage} ({phase:.0f}%)",
+ factor=max(0.0, min(phase / 100.0, 1.0))
+ )
elif comfy_tex_op and getattr(scene, 'trellis2_pipeline_active', False):
# ── Phase 3: Texturing via ComfyUIGenerate ──
@@ -1003,6 +1011,18 @@ class StableGenPanel(bpy.types.Panel):
row.prop(scene, "trellis2_autorig_use_postprocess", text="Skin Postprocess", toggle=True)
row = content_box.row()
row.prop(scene, "trellis2_autorig_use_skeleton", text="Use Existing Skeleton", toggle=True)
+ row.prop(
+ scene,
+ "trellis2_autorig_cleanup_cross_limb_weights",
+ text="Clean Limb Weights",
+ toggle=True,
+ )
+ row = content_box.row()
+ row.prop(
+ scene,
+ "trellis2_autorig_garment_mode",
+ text="Garment Handling",
+ )
content_box.separator()
row = content_box.row(align=True)
@@ -2088,7 +2108,8 @@ class StableGenPanel(bpy.types.Panel):
row.operator("object.stablegen_local_postprocess", text="Run Local Post-Processing", icon="MODIFIER")
row = tools_box.row()
- row.operator("object.stablegen_autorig_selected_mesh", text="Auto-Rig Selected Mesh", icon="ARMATURE_DATA")
+ row.operator_context = "INVOKE_DEFAULT"
+ row.operator("object.stablegen_autorig_selected_mesh", text="Auto-Rig Selected Character", icon="ARMATURE_DATA")
# --- Debug Tools ---
prefs = context.preferences.addons.get(_ADDON_PKG)
diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.py
index df5ca47..8cc6112 100644
--- a/stablegen/ui/presets.py
+++ b/stablegen/ui/presets.py
@@ -167,6 +167,8 @@ GEN_PARAMETERS = [
"trellis2_autorig_use_transfer",
"trellis2_autorig_use_skeleton",
"trellis2_autorig_use_postprocess",
+ "trellis2_autorig_cleanup_cross_limb_weights",
+ "trellis2_autorig_garment_mode",
"trellis2_autorig_top_k",
"trellis2_autorig_top_p",
"trellis2_autorig_temperature",