Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
advance texturing pipeline rework
sakalondfed5acd5375f
diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex 453ee40..bffd241 100644--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -23,6 +23,7 @@ from .texturing.rendering import ()from .texturing.orbit_export import ExportOrbitGIFfrom .texturing.game_export import ExportForGameEngine+from .texturing.solidify import StableGenMakeSolidfrom .animation import (StableGenCharacterizeRig, StableGenApplyRigPosePreset,StableGenSetRetargetReferencePose,@@ -53,7 +54,8 @@ from .texturing.generator import (ComfyUIGenerate, Reproject, Regenerate, MirrorReproject,)from .mesh_gen.trellis2 import (- Trellis2Generate, StableGenAutoRigSelectedMesh, StableGenLocalPostProcess,+ Trellis2Generate, StableGenApplyBoneDisplay,+ StableGenAutoRigSelectedMesh, StableGenLocalPostProcess,)from .mesh_gen.batch import (TRELLIS2_OT_BatchSelectFolder, TRELLIS2_OT_BatchGenerate,@@ -118,6 +120,7 @@ classes = [Regenerate,MirrorReproject,Trellis2Generate,+ StableGenApplyBoneDisplay,StableGenAutoRigSelectedMesh,StableGenLocalPostProcess,TRELLIS2_OT_BatchSelectFolder,@@ -135,6 +138,7 @@ classes = [SwitchMaterial,ExportOrbitGIF,ExportForGameEngine,+ StableGenMakeSolid,StableGenCharacterizeRig,StableGenApplyRigPosePreset,StableGenSetRetargetReferencePose,diff --git a/stablegen/core/load_handlers.py b/stablegen/core/load_handlers.pyindex 8e8bad7..2a26295 100644--- a/stablegen/core/load_handlers.py+++ b/stablegen/core/load_handlers.py@@ -25,6 +25,17 @@ def load_handler(dummy):scene = bpy.context.scene+ # Modal operators and worker sockets cannot survive loading a .blend.+ # Older files may nevertheless contain the serialized transient value+ # "running" or "waiting", which leaves the Generate button permanently+ # stuck after reopening. Runtime status is SKIP_SAVE now, but normalize+ # legacy files as well.+ for loaded_scene in bpy.data.scenes:+ if getattr(loaded_scene, "generation_status", 'idle') != 'idle':+ loaded_scene.generation_status = 'idle'+ if hasattr(loaded_scene, "generation_progress"):+ loaded_scene.generation_progress = 0.0+# Pre-populate multi-color printing palettetry:prepopulate_palette(scene)diff --git a/stablegen/core/properties.py b/stablegen/core/properties.pyindex 7b1b807..6b819c7 100644--- a/stablegen/core/properties.py+++ b/stablegen/core/properties.py@@ -611,7 +611,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,('waiting', 'Waiting for cancel', ''),('error', 'Error', '')],- default='idle', update=update_parameters+ default='idle', update=update_parameters, options={'SKIP_SAVE'})bpy.types.Scene.sg_last_gen_error = bpy.props.BoolProperty(name="Last Generation Error",@@ -620,7 +620,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,)bpy.types.Scene.generation_progress = bpy.props.FloatProperty(name="Generation Progress", description="Current progress of image generation",- default=0.0, min=0.0, max=100.0, update=update_parameters+ default=0.0, min=0.0, max=100.0, update=update_parameters,+ options={'SKIP_SAVE'},)# ── Material / blending ────────────────────────────────────────────@@ -863,6 +864,16 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,description="Use corrected Qwen style-slot routing, TRELLIS initial-only fallback, and refine sampler/model configuration",default=TEXTURING_REWORK_DEFAULTS["sg_rework_qwen_workflow"], update=update_parameters,)+ bpy.types.Scene.qwen_global_style_vlm_only = bpy.props.BoolProperty(+ name="Global Style Reference: VLM Only",+ description="In Qwen Additional Context mode, keep Image 3 available for visual-language style analysis but exclude it from full-resolution ReferenceLatent conditioning so it competes less with the spatial RGB context",+ default=TEXTURING_REWORK_DEFAULTS["qwen_global_style_vlm_only"], update=update_parameters,+ )+ bpy.types.Scene.qwen_latent_locked_context = bpy.props.BoolProperty(+ name="Latent-Locked Context Inpainting",+ description="For later sequential Qwen views, initialize the sampler from the RGB context render and use the exported visibility repair mask as a latent noise mask. White/repair pixels denoise; black/trusted pixels are restored after every sampling step",+ default=TEXTURING_REWORK_DEFAULTS["qwen_latent_locked_context"], update=update_parameters,+ )bpy.types.Scene.sg_rework_final_display = bpy.props.BoolProperty(name="Continuous Final Display Rebuild",description="After sequential generation, rebuild the final material without generation-only binary Qwen write masks so it matches Reproject",@@ -1218,7 +1229,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,)bpy.types.Scene.qwen_use_confidence_context = bpy.props.BoolProperty(name="Confidence-Gated Context",- description="Replace legacy RGB/magenta discovery with an explicit binary trusted-versus-repair context mask",+ description="Build an ownership-independent best-source quality field and replace low-quality context with an explicit binary repair mask. Continuous RGB projection blending is preserved",default=TEXTURING_REWORK_DEFAULTS["qwen_use_confidence_context"], update=update_parameters,)bpy.types.Scene.qwen_regularize_context_mask = bpy.props.BoolProperty(@@ -1752,6 +1763,43 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,],default='NONE', update=update_parameters)+ bpy.types.Scene.trellis2_autorig_bone_display_type = bpy.props.EnumProperty(+ name="Bone Display",+ description="Viewport shape used for newly imported SkinTokens bones",+ items=[+ ('OCTAHEDRAL', "Octahedral (Mixamo-like)", "Classic tapered Blender/Mixamo-style bones"),+ ('STICK', "Stick / Joint Circles", "Thin bone lines with circular joint markers"),+ ('BBONE', "B-Bone", "Box-like bendy-bone display"),+ ('ENVELOPE', "Envelope", "Display bone deformation envelopes"),+ ('WIRE', "Wire", "Wireframe bone display"),+ ('IMPORTED', "Imported", "Keep the display and custom shapes from the imported GLB"),+ ],+ default='OCTAHEDRAL', update=update_parameters,+ )+ bpy.types.Scene.trellis2_autorig_bone_heuristic = bpy.props.EnumProperty(+ name="Bone Direction",+ description=(+ "How Blender constructs bone axes when importing a SkinTokens glTF rig"+ ),+ items=[+ (+ 'FORTUNE',+ "Fortune / Child-Directed",+ "Point one-child bones at their child joints; recommended default",+ ),+ (+ 'BLENDER',+ "Blender / Legacy Round-Trip",+ "Preserve original glTF local joint axes and legacy joint markers",+ ),+ (+ 'TEMPERANCE',+ "Temperance / Nearest Axis",+ "Use the local axis nearest the child direction",+ ),+ ],+ default='FORTUNE', 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@@ -2039,7 +2087,9 @@ def unregister_properties(load_handler, _sg_queue_load_handler):'sg_rework_projection_guard', 'sg_rework_projection_rebuild','sg_rework_projection_geometry','sg_rework_consistent_frame', 'sg_rework_workflow_validation',- 'sg_rework_qwen_workflow', 'sg_rework_final_display',+ 'sg_rework_qwen_workflow', 'qwen_global_style_vlm_only',+ 'qwen_latent_locked_context',+ 'sg_rework_final_display','sg_texel_ownership', 'sg_texel_replacement_margin','sg_allow_trusted_replacement', 'sg_ownership_blend_mode','sg_ownership_seam_width', 'sg_ownership_lowpass_sigma',@@ -2151,7 +2201,8 @@ def unregister_properties(load_handler, _sg_queue_load_handler):'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_garment_mode', 'trellis2_autorig_bone_display_type',+ 'trellis2_autorig_bone_heuristic','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/debug_tools.py b/stablegen/debug_tools.pyindex 32bb052..9cb21b5 100644--- a/stablegen/debug_tools.py+++ b/stablegen/debug_tools.py@@ -14,6 +14,7 @@ import bpyimport osimport colorsysimport numpy as np+import sysfrom contextlib import contextmanagerfrom mathutils import Vector@@ -27,6 +28,11 @@ from .texturing.projection import (from .texturing.rendering import export_visibilityfrom .cameras.geometry import _get_camera_resolutionfrom .utils import get_file_path, get_generation_dirs, ensure_dirs_exist, sg_modal_active+from .mesh_gen.rig_display import (+ convert_armature_bones_to_fortune,+ fortune_conversion_risks,+ selected_armatures_for_display,+)# ─── Shared helpers ──────────────────────────────────────────────────────@@ -59,11 +65,350 @@ def _common_poll(cls, context):return True+class SG_OT_DebugForceGenerationIdle(bpy.types.Operator):+ """Clear stale in-process texturing state after an interrupted operation."""++ bl_idname = "stablegen.debug_force_generation_idle"+ bl_label = "Force Generation Idle"+ bl_description = (+ "Force StableGen's saved generation state back to Idle and close any "+ "stale generation WebSocket; use only when no generation is actually running"+ )+ bl_options = {'REGISTER'}++ @classmethod+ def poll(cls, context):+ # The button itself is debug-gated. Keep the recovery operator callable+ # through Search/Python even when a stale file also lost its UI state.+ return context.scene is not None++ def execute(self, context):+ # Avoid importing generator.py here: debug_tools is imported by the+ # add-on registration graph before the generator operator. If it is+ # already loaded, also clear its process-local sentinels.+ generator_modules = [+ module+ for name, module in tuple(sys.modules.items())+ if name.endswith(".texturing.generator")+ ]+ closed_socket = False+ for module in generator_modules:+ generator = getattr(module, "ComfyUIGenerate", None)+ if generator is None:+ continue+ websocket = getattr(generator, "_active_ws", None)+ if websocket is not None:+ try:+ websocket.close()+ closed_socket = True+ except Exception:+ pass+ generator._active_ws = None+ generator._is_running = False++ context.scene.generation_status = 'idle'+ context.scene.generation_progress = 0.0+ if hasattr(context.scene, "sg_last_gen_error"):+ context.scene.sg_last_gen_error = False++ message = "Forced StableGen generation state to Idle"+ if closed_socket:+ message += " and closed the stale WebSocket"+ self.report({'WARNING'}, message)+ return {'FINISHED'}++def _saturated_colors(n):"""Return *n* maximally-saturated, evenly-spaced RGB tuples."""return [colorsys.hsv_to_rgb(i / max(n, 1), 1.0, 1.0) for i in range(n)]+_SKIN_WEIGHT_COLOR_ATTRIBUTE = "SG_SkinWeights"+_SKIN_WEIGHT_PREVIOUS_ATTRIBUTE = "sg_skin_debug_previous_color_attribute"+++def _mesh_armature_for_skin_debug(obj):+ """Return the armature that owns *obj*'s deform groups, if available."""+ if obj.parent and obj.parent.type == 'ARMATURE':+ return obj.parent+ for modifier in obj.modifiers:+ if (+ modifier.type == 'ARMATURE'+ and modifier.object+ and modifier.object.type == 'ARMATURE'+ ):+ return modifier.object+ return None+++def _get_skinning_target_meshes(context):+ """Resolve meshes for the skin-weight diagnostic without requiring cameras.++ Selected meshes take priority. If an armature is selected, all scene meshes+ driven by it are used. With no useful selection, all rigged scene meshes are+ considered. This matches the common post-auto-rig workflow where the+ imported armature, rather than every individual garment mesh, is selected.+ """+ selected_meshes = [+ obj for obj in context.selected_objects+ if obj.type == 'MESH' and obj.vertex_groups+ ]+ if selected_meshes:+ return selected_meshes++ selected_armatures = {+ obj for obj in context.selected_objects if obj.type == 'ARMATURE'+ }+ if context.active_object and context.active_object.type == 'ARMATURE':+ selected_armatures.add(context.active_object)++ candidates = [+ obj for obj in context.scene.objects+ if obj.type == 'MESH' and obj.vertex_groups+ ]+ if selected_armatures:+ return [+ obj for obj in candidates+ if _mesh_armature_for_skin_debug(obj) in selected_armatures+ ]+ return [obj for obj in candidates if _mesh_armature_for_skin_debug(obj)]+++def _skinning_debug_poll(context):+ prefs = context.preferences.addons.get(__package__)+ if not prefs or not prefs.preferences.enable_debug:+ return False+ if sg_modal_active(context):+ return False+ return bool(_get_skinning_target_meshes(context))+++def _active_skinning_bone_name(context):+ """Resolve the bone/group whose individual influence should be displayed."""+ active_pose_bone = getattr(context, "active_pose_bone", None)+ if active_pose_bone is not None:+ return active_pose_bone.name+ active_edit_bone = getattr(context, "active_bone", None)+ if active_edit_bone is not None:+ return active_edit_bone.name++ active_object = context.active_object+ if active_object and active_object.type == 'ARMATURE':+ active_bone = active_object.data.bones.active+ if active_bone is not None:+ return active_bone.name+ if active_object and active_object.type == 'MESH':+ active_group = active_object.vertex_groups.active+ if active_group is not None:+ return active_group.name++ for obj in context.selected_objects:+ if obj.type == 'ARMATURE' and obj.data.bones.active is not None:+ return obj.data.bones.active.name+ if obj.type == 'MESH' and obj.vertex_groups.active is not None:+ return obj.vertex_groups.active.name+ return None+++def _stable_skinning_palette(names):+ """Return stable, visually separated sRGB colors for bone/group names."""+ golden_ratio = 0.618033988749895+ colors = []+ for index, _name in enumerate(names):+ hue = (0.03 + index * golden_ratio) % 1.0+ saturation = 0.78 + 0.10 * (index % 3)+ value = 1.0+ colors.append(colorsys.hsv_to_rgb(hue, saturation, value))+ return np.asarray(colors, dtype=np.float32)+++def _skinning_palette_for_object(obj):+ """Return (bone names, colors, vertex-group-index -> palette-index)."""+ armature = _mesh_armature_for_skin_debug(obj)+ if armature:+ names = [bone.name for bone in armature.data.bones if bone.use_deform]+ else:+ # Useful for imported/debug meshes whose Armature modifier was removed.+ # StableGen marker groups are not skin influences and are excluded.+ names = sorted(+ group.name for group in obj.vertex_groups+ if not group.name.startswith("SG_")+ )+ palette = _stable_skinning_palette(names)+ group_to_palette = {}+ for palette_index, name in enumerate(names):+ group = obj.vertex_groups.get(name)+ if group is not None:+ group_to_palette[group.index] = palette_index+ return names, palette, group_to_palette+++def _max_weight_heat_color(value):+ """Blue -> cyan -> yellow -> red diagnostic ramp for [0, 1]."""+ value = float(np.clip(value, 0.0, 1.0))+ positions = np.asarray((0.0, 0.33, 0.66, 1.0), dtype=np.float32)+ colors = np.asarray(+ ((0.05, 0.05, 0.45), (0.0, 0.9, 1.0),+ (1.0, 0.95, 0.0), (1.0, 0.0, 0.0)),+ dtype=np.float32,+ )+ return np.asarray([+ np.interp(value, positions, colors[:, channel])+ for channel in range(3)+ ], dtype=np.float32)+++def _influence_heat_color(value):+ """SkinTokens-like pale-blue -> cyan -> green -> yellow -> red ramp."""+ value = float(np.clip(value, 0.0, 1.0))+ positions = np.asarray((0.0, 0.2, 0.45, 0.7, 1.0), dtype=np.float32)+ colors = np.asarray(+ ((0.34, 0.56, 0.78), (0.05, 0.82, 0.95),+ (0.10, 0.82, 0.36), (1.0, 0.88, 0.0), (0.92, 0.05, 0.02)),+ dtype=np.float32,+ )+ return np.asarray([+ np.interp(value, positions, colors[:, channel])+ for channel in range(3)+ ], dtype=np.float32)+++def _skinning_colors_for_object(obj, mode='BLENDED', bone_name=None):+ """Evaluate the current vertex groups into a SkinTokens-style color map.++ ``ACTIVE_BONE`` matches the SkinTokens paper view: a blue-to-red heatmap of+ one selected bone's influence over the complete mesh. ``BLENDED`` displays+ the normalized weighted blend of per-bone colors, ``DOMINANT`` shows hard+ ownership, and ``MAX_WEIGHT`` visualizes assignment certainty.+ """+ names, palette, group_to_palette = _skinning_palette_for_object(obj)+ colors = np.zeros((len(obj.data.vertices), 4), dtype=np.float32)+ colors[:, 3] = 1.0+ unweighted = 0++ if mode == 'ACTIVE_BONE':+ colors[:, :3] = _influence_heat_color(0.0)+ group = obj.vertex_groups.get(bone_name) if bone_name else None+ if group is not None:+ for vertex in obj.data.vertices:+ weight = next(+ (+ float(item.weight) for item in vertex.groups+ if item.group == group.index+ ),+ 0.0,+ )+ colors[vertex.index, :3] = _influence_heat_color(weight)+ return colors, {+ "bone_count": len(names),+ "mapped_group_count": int(group is not None),+ "vertex_count": len(obj.data.vertices),+ "unweighted_count": 0,+ "selected_bone": bone_name,+ }++ for vertex in obj.data.vertices:+ influences = [+ (float(item.weight), group_to_palette[item.group])+ for item in vertex.groups+ if item.group in group_to_palette and item.weight > 1e-8+ ]+ total = sum(weight for weight, _palette_index in influences)+ if total <= 1e-8:+ unweighted += 1+ continue++ if mode == 'DOMINANT':+ _weight, palette_index = max(influences, key=lambda item: item[0])+ colors[vertex.index, :3] = palette[palette_index]+ elif mode == 'MAX_WEIGHT':+ strongest = max(weight for weight, _palette_index in influences)+ colors[vertex.index, :3] = _max_weight_heat_color(strongest / total)+ else:+ blended = np.zeros(3, dtype=np.float32)+ for weight, palette_index in influences:+ blended += palette[palette_index] * weight+ colors[vertex.index, :3] = blended / total++ return colors, {+ "bone_count": len(names),+ "mapped_group_count": len(group_to_palette),+ "vertex_count": len(obj.data.vertices),+ "unweighted_count": unweighted,+ }+++def _apply_skinning_weight_colors(obj, mode='BLENDED', bone_name=None):+ """Write the diagnostic POINT color attribute and return its statistics."""+ mesh = obj.data+ current = mesh.color_attributes.get(_SKIN_WEIGHT_COLOR_ATTRIBUTE)+ if current is None:+ previous = mesh.color_attributes.active_color+ mesh[_SKIN_WEIGHT_PREVIOUS_ATTRIBUTE] = (+ previous.name if previous is not None else ""+ )+ elif current.domain != 'POINT' or current.data_type != 'FLOAT_COLOR':+ mesh.color_attributes.remove(current)+ current = None++ if current is None:+ current = mesh.color_attributes.new(+ name=_SKIN_WEIGHT_COLOR_ATTRIBUTE,+ type='FLOAT_COLOR',+ domain='POINT',+ )++ colors, stats = _skinning_colors_for_object(+ obj, mode=mode, bone_name=bone_name)+ try:+ current.data.foreach_set("color_srgb", colors.ravel())+ except (AttributeError, TypeError):+ # Blender 3.x exposes only the scene-linear color accessor.+ current.data.foreach_set("color", colors.ravel())+ mesh.color_attributes.active_color = current+ mesh.update()+ return stats+++def _clear_skinning_weight_colors(obj):+ """Remove only StableGen's diagnostic attribute and restore color focus."""+ mesh = obj.data+ attribute = mesh.color_attributes.get(_SKIN_WEIGHT_COLOR_ATTRIBUTE)+ if attribute is not None:+ mesh.color_attributes.remove(attribute)+ previous_name = mesh.get(_SKIN_WEIGHT_PREVIOUS_ATTRIBUTE, "")+ previous = mesh.color_attributes.get(previous_name) if previous_name else None+ if previous is not None:+ mesh.color_attributes.active_color = previous+ if _SKIN_WEIGHT_PREVIOUS_ATTRIBUTE in mesh:+ del mesh[_SKIN_WEIGHT_PREVIOUS_ATTRIBUTE]+ mesh.update()+ return attribute is not None+++def _set_skinning_debug_viewport(context, enabled):+ """Select vertex-color solid shading without touching object materials."""+ screen = getattr(context, "screen", None)+ if screen is None:+ return+ for area in screen.areas:+ if area.type != 'VIEW_3D':+ continue+ for space in area.spaces:+ if space.type != 'VIEW_3D':+ continue+ shading = space.shading+ shading.type = 'SOLID'+ if enabled:+ shading.color_type = 'VERTEX'+ try:+ shading.light = 'FLAT'+ except (AttributeError, TypeError):+ pass+ elif shading.color_type == 'VERTEX':+ shading.color_type = 'MATERIAL'++def _save_solid_image(path, width, height, color_rgba):"""Create and save a solid-colour PNG at *path*."""img = bpy.data.images.new("_sg_dbg_tmp", width=width, height=height, alpha=True)@@ -850,7 +1195,271 @@ class SG_OT_DebugUVSeamViz(bpy.types.Operator):# ═════════════════════════════════════════════════════════════════════════-# 8. Restore Original Material+# 8. Skinning Weight Colors+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugConvertFortuneRig(bpy.types.Operator):+ """Reorient an existing generated rig using Fortune joint directions."""++ bl_idname = "stablegen.debug_convert_fortune_rig"+ bl_label = "Convert Existing Rig to Fortune"+ bl_description = (+ "Rebuild an existing SkinTokens rig's rest-pose bone directions so "+ "tails point toward child joints; weights and joint heads are preserved"+ )+ bl_options = {'REGISTER', 'UNDO'}++ force_unsafe: bpy.props.BoolProperty(+ name="Convert Animated/Posed Rig Anyway",+ description=(+ "Rest-axis conversion may change existing animations, constraints, "+ "drivers, or the current pose"+ ),+ default=False,+ ) # type: ignore++ _risks = None++ @classmethod+ def poll(cls, context):+ if sg_modal_active(context):+ cls.poll_message_set("Another StableGen operation is in progress")+ return False+ if not selected_armatures_for_display(context):+ cls.poll_message_set("Select a rigged mesh or armature")+ return False+ return True++ def invoke(self, context, _event):+ armatures = selected_armatures_for_display(context)+ self._risks = {+ armature.name: fortune_conversion_risks(armature)+ for armature in armatures+ if fortune_conversion_risks(armature)+ }+ if self._risks:+ return context.window_manager.invoke_props_dialog(self, width=560)+ return self.execute(context)++ def draw(self, _context):+ layout = self.layout+ layout.label(+ text="This rewrites rest-pose bone axes and is safe by default only for unanimated rigs.",+ icon='ERROR',+ )+ for armature_name, risks in (self._risks or {}).items():+ layout.label(text=f"{armature_name}: {', '.join(risks)}")+ layout.prop(self, "force_unsafe")++ def execute(self, context):+ armatures = selected_armatures_for_display(context)+ blocked = {+ armature.name: fortune_conversion_risks(armature)+ for armature in armatures+ if fortune_conversion_risks(armature)+ }+ if blocked and not self.force_unsafe:+ details = "; ".join(+ f"{name}: {', '.join(risks)}"+ for name, risks in blocked.items()+ )+ self.report(+ {'ERROR'},+ "Conversion cancelled. Enable the confirmation checkbox to "+ f"override: {details}",+ )+ return {'CANCELLED'}++ total = 0+ for armature in armatures:+ stats = convert_armature_bones_to_fortune(armature)+ total += stats["changed"]+ print(+ "[StableGen Debug] Fortune-converted "+ f"{armature.name}: {stats}"+ )+ self.report(+ {'INFO'},+ f"Converted {len(armatures)} rig(s), reoriented {total} bones",+ )+ return {'FINISHED'}++class SG_OT_DebugSkinningWeights(bpy.types.Operator):+ """Color rigged meshes from their actual deform vertex-group weights.++ The default view matches the SkinTokens comparison: the selected bone's+ individual influence is shown from blue (zero) to red (one). Alternative+ modes expose blended per-bone colors, dominant ownership, and assignment+ confidence. Materials and weights are left untouched; only a named mesh+ color attribute and viewport shading mode are changed.+ """+ bl_idname = "stablegen.debug_skinning_weights"+ bl_label = "Skinning Weight Colors"+ bl_description = (+ "Visualize generated skin weights, defaulting to a selected-bone "+ "blue-to-red influence heatmap"+ )+ bl_options = {'REGISTER', 'UNDO'}++ mode: bpy.props.EnumProperty(+ name="Display",+ items=[+ (+ 'ACTIVE_BONE',+ "Selected Bone Heatmap",+ "SkinTokens paper-style view: blue is zero influence and red "+ "is full influence for the active bone or vertex group",+ ),+ (+ 'BLENDED',+ "Blended Bone Colors",+ "SkinTokens-style map: blend stable per-bone colors using "+ "the normalized skin weights",+ ),+ (+ 'DOMINANT',+ "Dominant Bone",+ "Show only the strongest deform bone on every vertex",+ ),+ (+ 'MAX_WEIGHT',+ "Maximum Weight",+ "Heatmap the strongest normalized influence: blue is weak "+ "and red is fully assigned",+ ),+ ],+ default='ACTIVE_BONE',+ ) # type: ignore++ @classmethod+ def poll(cls, context):+ return _skinning_debug_poll(context)++ def execute(self, context):+ meshes = _get_skinning_target_meshes(context)+ bone_name = (+ _active_skinning_bone_name(context)+ if self.mode == 'ACTIVE_BONE' else None+ )+ if self.mode == 'ACTIVE_BONE' and not bone_name:+ self.report(+ {'ERROR'},+ "Select a pose/edit bone or make a deform vertex group active",+ )+ return {'CANCELLED'}+ processed_data = set()+ totals = {+ "meshes": 0,+ "vertices": 0,+ "groups": 0,+ "unweighted": 0,+ }+ skipped = []++ for obj in meshes:+ data_pointer = obj.data.as_pointer()+ if data_pointer in processed_data:+ skipped.append(obj.name)+ continue+ processed_data.add(data_pointer)++ stats = _apply_skinning_weight_colors(+ obj, mode=self.mode, bone_name=bone_name)+ if (+ self.mode != 'ACTIVE_BONE'+ and not stats["mapped_group_count"]+ ):+ _clear_skinning_weight_colors(obj)+ skipped.append(obj.name)+ continue+ totals["meshes"] += 1+ totals["vertices"] += stats["vertex_count"]+ totals["groups"] += stats["mapped_group_count"]+ totals["unweighted"] += stats["unweighted_count"]++ if not totals["meshes"] or (+ self.mode == 'ACTIVE_BONE' and not totals["groups"]+ ):+ for obj in meshes:+ _clear_skinning_weight_colors(obj)+ self.report(+ {'ERROR'},+ (+ f"No vertex group named '{bone_name}' was found on the target meshes"+ if self.mode == 'ACTIVE_BONE'+ else "No deform-bone vertex groups were found on the target meshes"+ ),+ )+ return {'CANCELLED'}++ _set_skinning_debug_viewport(context, True)+ print(+ "[StableGen Debug] Skinning colors: "+ f"{totals['meshes']} mesh(es), {totals['vertices']} vertices, "+ f"{totals['groups']} mapped deform groups, "+ f"{totals['unweighted']} unweighted vertices, mode={self.mode}, "+ f"bone={bone_name or 'all'}."+ )+ if skipped:+ print(+ "[StableGen Debug] Skinning color targets skipped: "+ + ", ".join(skipped)+ )+ self.report(+ {'INFO'},+ (+ f"Skinning heatmap for {bone_name} applied to "+ f"{totals['meshes']} mesh(es)"+ if self.mode == 'ACTIVE_BONE'+ else f"Skinning colors applied to {totals['meshes']} mesh(es); "+ f"{totals['unweighted']} unweighted vertices shown black"+ ),+ )+ return {'FINISHED'}+++class SG_OT_DebugClearSkinningWeights(bpy.types.Operator):+ """Remove StableGen skin-weight colors without changing materials/weights."""+ bl_idname = "stablegen.debug_clear_skinning_weights"+ bl_label = "Clear Skinning Weight Colors"+ bl_description = "Remove the StableGen skin-weight color attribute"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ prefs = context.preferences.addons.get(__package__)+ if not prefs or not prefs.preferences.enable_debug:+ return False+ if sg_modal_active(context):+ return False+ return any(+ obj.type == 'MESH'+ and obj.data.color_attributes.get(_SKIN_WEIGHT_COLOR_ATTRIBUTE)+ for obj in context.scene.objects+ )++ def execute(self, context):+ selected = [obj for obj in context.selected_objects if obj.type == 'MESH']+ meshes = selected or [+ obj for obj in context.scene.objects+ if obj.type == 'MESH'+ and obj.data.color_attributes.get(_SKIN_WEIGHT_COLOR_ATTRIBUTE)+ ]+ processed_data = set()+ removed = 0+ for obj in meshes:+ data_pointer = obj.data.as_pointer()+ if data_pointer in processed_data:+ continue+ processed_data.add(data_pointer)+ removed += int(_clear_skinning_weight_colors(obj))+ _set_skinning_debug_viewport(context, False)+ self.report({'INFO'}, f"Cleared skinning colors from {removed} mesh(es)")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 9. Restore Original Material# ═════════════════════════════════════════════════════════════════════════class SG_OT_DebugRestoreMaterial(bpy.types.Operator):@@ -883,7 +1492,7 @@ class SG_OT_DebugRestoreMaterial(bpy.types.Operator):# ═════════════════════════════════════════════════════════════════════════-# 9. Live Ownership / Confidence Diagnostics+# 10. Live Ownership / Confidence Diagnostics# ═════════════════════════════════════════════════════════════════════════class SG_OT_DebugOwnershipDiagnostic(bpy.types.Operator):@@ -1035,7 +1644,7 @@ class SG_OT_DebugOwnershipDiagnostic(bpy.types.Operator):# ═════════════════════════════════════════════════════════════════════════-# 10. Debug Make Solid+# 11. Debug Make Solid# ═════════════════════════════════════════════════════════════════════════class SG_OT_DebugMakeSolid(bpy.types.Operator):@@ -1285,6 +1894,7 @@ class SG_OT_DebugMakeSolid(bpy.types.Operator):# ─── Registration list ───────────────────────────────────────────────────debug_classes = [+ SG_OT_DebugForceGenerationIdle,SG_OT_DebugSolidColors,SG_OT_DebugGridPattern,SG_OT_DebugVisibilityMaterial,@@ -1292,6 +1902,9 @@ debug_classes = [SG_OT_DebugPerCameraWeight,SG_OT_DebugFeatherPreview,SG_OT_DebugUVSeamViz,+ SG_OT_DebugConvertFortuneRig,+ SG_OT_DebugSkinningWeights,+ SG_OT_DebugClearSkinningWeights,SG_OT_DebugRestoreMaterial,SG_OT_DebugOwnershipDiagnostic,SG_OT_DebugMakeSolid,diff --git a/stablegen/feature_flags.py b/stablegen/feature_flags.pyindex ca2766e..7853c4c 100644--- a/stablegen/feature_flags.py+++ b/stablegen/feature_flags.py@@ -17,6 +17,8 @@ TEXTURING_REWORK_DEFAULTS = {"sg_rework_consistent_frame": False,"sg_rework_workflow_validation": False,"sg_rework_qwen_workflow": False,+ "qwen_global_style_vlm_only": False,+ "qwen_latent_locked_context": False,"sg_rework_final_display": False,"qwen_use_confidence_context": False,"qwen_regularize_context_mask": False,diff --git a/stablegen/mesh_gen/rig_display.py b/stablegen/mesh_gen/rig_display.pynew file mode 100644index 0000000..e8484a8--- /dev/null+++ b/stablegen/mesh_gen/rig_display.py@@ -0,0 +1,336 @@+"""Viewport presentation helpers for imported SkinTokens armatures."""++import json++import bpy # pylint: disable=import-error+from mathutils import Matrix # pylint: disable=import-error+++_AUTORIG_IMPORTED_DISPLAY_PROP = "sg_autorig_imported_bone_display"+_AUTORIG_IMPORTED_SHAPES_PROP = "sg_autorig_imported_custom_shapes"+AUTORIG_GLTF_BONE_HEURISTIC = "FORTUNE"+AUTORIG_GLTF_BONE_HEURISTICS = {"FORTUNE", "BLENDER", "TEMPERANCE"}+++def autorig_gltf_import_kwargs(filepath, bone_heuristic=AUTORIG_GLTF_BONE_HEURISTIC):+ """Return glTF import settings suitable for SkinTokens joint rigs.++ SkinTokens exports glTF joints, which do not contain Blender-style bone+ tails. Blender's default import heuristic points each synthetic tail down+ the joint's local +Y axis. Fortune instead points one-child bones at the+ child joint while compensating the imported transforms so the skin remains+ in place.+ """+ if bone_heuristic not in AUTORIG_GLTF_BONE_HEURISTICS:+ bone_heuristic = AUTORIG_GLTF_BONE_HEURISTIC+ return {+ "filepath": filepath,+ "bone_heuristic": bone_heuristic,+ # Blender creates glTF_not_exported plus an Icosphere whenever bone+ # shapes are enabled, but only its legacy BLENDER heuristic actually+ # assigns that shape to pose bones.+ "disable_bone_shape": bone_heuristic != "BLENDER",+ }+++def configure_gltf_not_exported_visibility(context=None):+ """Hide Blender's glTF helper collection using normal Outliner controls.++ Blender's importer globally disables this collection in viewports via+ ``Collection.hide_viewport``. That is the monitor/restriction setting,+ which is hard to discover and override. Keep the collection globally+ enabled, use each view layer's eye toggle instead, and use only the+ collection render toggle rather than burying duplicate flags on objects.+ """+ context = context or bpy.context+ scene = getattr(context, "scene", None) or bpy.context.scene+ stats = {+ "collections": 0,+ "layer_collections": 0,+ "object_flags_cleared": 0,+ }++ def iter_objects(collection):+ seen = set()++ def visit(current):+ for obj in current.objects:+ if obj.name in seen:+ continue+ seen.add(obj.name)+ yield obj+ for child in current.children:+ yield from visit(child)++ yield from visit(collection)++ def matching_layer_collections(root, target):+ if root.collection == target:+ yield root+ for child in root.children:+ yield from matching_layer_collections(child, target)++ for collection in bpy.data.collections:+ if "not_exported" not in collection.name.lower():+ continue+ stats["collections"] += 1+ collection.hide_viewport = False+ collection.hide_render = True++ for obj in iter_objects(collection):+ if obj.hide_viewport or obj.hide_render:+ stats["object_flags_cleared"] += 1+ obj.hide_viewport = False+ obj.hide_render = False++ for view_layer in scene.view_layers:+ for layer_collection in matching_layer_collections(+ view_layer.layer_collection, collection):+ layer_collection.exclude = False+ layer_collection.hide_viewport = True+ stats["layer_collections"] += 1++ view_layer = getattr(context, "view_layer", None)+ if view_layer:+ view_layer.update()+ return stats+++def record_autorig_bone_heuristic(objects, bone_heuristic):+ """Record the glTF joint-direction heuristic on imported armatures."""+ bone_heuristic = autorig_gltf_import_kwargs(+ "", bone_heuristic)["bone_heuristic"]+ armatures = []+ for obj in objects:+ if obj.type == 'ARMATURE' and obj not in armatures:+ armatures.append(obj)+ if obj.type != 'MESH':+ continue+ if obj.parent and obj.parent.type == 'ARMATURE' and obj.parent not in armatures:+ armatures.append(obj.parent)+ for modifier in obj.modifiers:+ if (+ modifier.type == 'ARMATURE'+ and modifier.object+ and modifier.object not in armatures+ ):+ armatures.append(modifier.object)+ for armature in armatures:+ armature["sg_autorig_bone_heuristic"] = bone_heuristic+ return len(armatures)+++def fortune_conversion_risks(armature):+ """Return reasons why rewriting an existing rig's rest axes is risky."""+ risks = []+ animation_data = armature.animation_data+ if animation_data:+ if animation_data.action is not None:+ risks.append("an active animation action")+ if animation_data.nla_tracks:+ risks.append("NLA animation tracks")+ if animation_data.drivers:+ risks.append("animation drivers")+ if any(pose_bone.constraints for pose_bone in armature.pose.bones):+ risks.append("pose-bone constraints")++ identity = Matrix.Identity(4)+ if any(+ max(+ abs(pose_bone.matrix_basis[row][column] - identity[row][column])+ for row in range(4)+ for column in range(4)+ ) > 1e-6+ for pose_bone in armature.pose.bones+ ):+ risks.append("a non-rest pose")+ return risks+++def convert_armature_bones_to_fortune(armature):+ """Rebuild existing deform-bone axes using Blender's Fortune geometry.++ Joint heads and hierarchy are preserved. Non-leaf tails point toward the+ centroid of their child joints and use the nearest child distance, matching+ Blender's glTF Fortune heuristic. Leaf directions inherit their parent's+ direction correction. The operation is intended for unanimated generated+ rigs; callers should inspect :func:`fortune_conversion_risks` first.+ """+ if not armature or armature.type != 'ARMATURE':+ raise TypeError("Expected an armature object")++ context = bpy.context+ active_object = getattr(context, "object", None)+ if active_object is None:+ active_object = context.view_layer.objects.active+ if active_object and active_object.mode != 'OBJECT':+ 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')++ changed = 0+ one_child = 0+ branches = 0+ leaves = 0+ try:+ edit_bones = armature.data.edit_bones+ snapshots = {+ bone.name: {+ "head": bone.head.copy(),+ "tail": bone.tail.copy(),+ "matrix": bone.matrix.copy(),+ "parent": bone.parent.name if bone.parent else None,+ "children": [child.name for child in bone.children],+ }+ for bone in edit_bones+ }++ def bone_depth(name):+ depth = 0+ parent = snapshots[name]["parent"]+ while parent:+ depth += 1+ parent = snapshots[parent]["parent"]+ return depth++ corrections = {}+ for name in sorted(snapshots, key=bone_depth):+ snapshot = snapshots[name]+ head = snapshot["head"]+ old_vector = snapshot["tail"] - head+ if old_vector.length <= 1e-8:+ continue+ old_direction = old_vector.normalized()+ children = snapshot["children"]++ if children:+ offsets = [+ snapshots[child]["head"] - head+ for child in children+ ]+ offsets = [offset for offset in offsets if offset.length > 1e-8]+ if not offsets:+ continue+ direction_sum = sum(offsets, offsets[0].copy() * 0.0)+ if direction_sum.length <= 1e-8:+ continue+ new_direction = direction_sum.normalized()+ new_length = min(offset.length for offset in offsets)+ if len(offsets) == 1:+ one_child += 1+ else:+ branches += 1+ else:+ parent_name = snapshot["parent"]+ parent_correction = corrections.get(parent_name)+ if parent_correction is None:+ continue+ new_direction = (parent_correction @ old_direction).normalized()+ new_length = old_vector.length+ leaves += 1++ correction = old_direction.rotation_difference(new_direction)+ corrections[name] = correction+ old_z = snapshot["matrix"].to_3x3().col[2].normalized()+ roll_reference = correction @ old_z++ edit_bone = edit_bones[name]+ edit_bone.tail = head + (new_direction * new_length)+ if (+ roll_reference.length > 1e-8+ and abs(roll_reference.normalized().dot(new_direction)) < 0.9999+ ):+ edit_bone.align_roll(roll_reference)+ changed += 1+ finally:+ bpy.ops.object.mode_set(mode='OBJECT')++ apply_autorig_bone_display([armature], 'OCTAHEDRAL')+ armature["sg_autorig_bone_heuristic"] = "FORTUNE_CONVERTED"+ return {+ "changed": changed,+ "one_child": one_child,+ "branches": branches,+ "leaves": leaves,+ }+++def apply_autorig_bone_display(objects, display_type='OCTAHEDRAL'):+ """Apply a selectable Blender bone display to imported SkinTokens rigs.++ The incoming GLB commonly uses Blender's Stick display, whose circular+ joints can look like icospheres. Non-imported modes clear pose-bone custom+ shapes as well, while recording enough information to restore the imported+ presentation later.+ """+ armatures = []+ for obj in objects:+ if obj.type == 'ARMATURE' and obj not in armatures:+ armatures.append(obj)+ if obj.type != 'MESH':+ continue+ if obj.parent and obj.parent.type == 'ARMATURE' and obj.parent not in armatures:+ armatures.append(obj.parent)+ for modifier in obj.modifiers:+ if (+ modifier.type == 'ARMATURE'+ and modifier.object+ and modifier.object not in armatures+ ):+ armatures.append(modifier.object)+ for armature in armatures:+ if _AUTORIG_IMPORTED_DISPLAY_PROP not in armature:+ armature[_AUTORIG_IMPORTED_DISPLAY_PROP] = armature.data.display_type+ if _AUTORIG_IMPORTED_SHAPES_PROP not in armature:+ armature[_AUTORIG_IMPORTED_SHAPES_PROP] = json.dumps({+ bone.name: bone.custom_shape.name+ for bone in armature.pose.bones+ if bone.custom_shape is not None+ }, sort_keys=True)++ if display_type == 'IMPORTED':+ imported_type = armature.get(+ _AUTORIG_IMPORTED_DISPLAY_PROP, armature.data.display_type)+ valid_types = {'OCTAHEDRAL', 'STICK', 'BBONE', 'ENVELOPE', 'WIRE'}+ if imported_type in valid_types:+ armature.data.display_type = imported_type+ try:+ imported_shapes = json.loads(+ armature.get(_AUTORIG_IMPORTED_SHAPES_PROP, "{}"))+ except (TypeError, ValueError):+ imported_shapes = {}+ for bone in armature.pose.bones:+ shape_name = imported_shapes.get(bone.name)+ bone.custom_shape = bpy.data.objects.get(shape_name) if shape_name else None+ else:+ armature.data.display_type = display_type+ for bone in armature.pose.bones:+ bone.custom_shape = None++ # Generated rigs are primarily inspected inside the character mesh.+ armature.show_in_front = True+ armature["sg_autorig_bone_display"] = display_type++ return len(armatures)+++def selected_armatures_for_display(context):+ """Resolve selected armatures, including those driving selected meshes."""+ armatures = []+ for obj in context.selected_objects:+ if obj.type == 'ARMATURE' and obj not in armatures:+ armatures.append(obj)+ if obj.type != 'MESH':+ continue+ if obj.parent and obj.parent.type == 'ARMATURE' and obj.parent not in armatures:+ armatures.append(obj.parent)+ for modifier in obj.modifiers:+ if (+ modifier.type == 'ARMATURE'+ and modifier.object+ and modifier.object not in armatures+ ):+ armatures.append(modifier.object)+ return armaturesdiff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.pyindex 48e1556..29a9a9e 100644--- a/stablegen/mesh_gen/trellis2.py+++ b/stablegen/mesh_gen/trellis2.py@@ -19,6 +19,13 @@ from ..utils import get_generation_dirs, sg_modal_activefrom ..timeout_config import get_timeoutfrom .._generator_utils import setup_studio_lighting, redraw_ui, upload_image_to_comfyuifrom ..texturing.gallery import _PreviewGalleryOverlay+from .rig_display import (+ apply_autorig_bone_display,+ autorig_gltf_import_kwargs,+ configure_gltf_not_exported_visibility,+ record_autorig_bone_heuristic,+ selected_armatures_for_display,+)_ADDON_PKG = __package__.rsplit('.', 1)[0]_GARMENT_STABILIZED_GROUP = "SG_GarmentStabilized"@@ -1231,43 +1238,15 @@ class Trellis2Generate(bpy.types.Operator):print(f"[TRELLIS2] Cleared custom split normals on {cleared} imported mesh object(s)")@staticmethod- def _disable_not_exported_render_helpers():- """Disable glTF control/helper geometry for render and bake."""- disabled_objects = 0- disabled_collections = 0-- def iter_collection_objects(collection):- seen = set()-- def visit(col):- for obj in col.objects:- if obj.name in seen:- continue- seen.add(obj.name)- yield obj- for child in col.children:- yield from visit(child)-- yield from visit(collection)-- for collection in bpy.data.collections:- if "not_exported" not in collection.name.lower():- continue-- if not collection.hide_render:- collection.hide_render = True- disabled_collections += 1-- for obj in iter_collection_objects(collection):- if not obj.hide_render:- obj.hide_render = True- disabled_objects += 1-- if disabled_objects or disabled_collections:+ def _configure_not_exported_helpers():+ """Expose glTF helper visibility through eye/render collection icons."""+ stats = configure_gltf_not_exported_visibility(bpy.context)+ if stats["collections"]:print(- "[TRELLIS2] Disabled render visibility for "- f"{disabled_objects} glTF not_exported helper object(s) "- f"across {disabled_collections} collection(s)."+ "[TRELLIS2] Hid glTF not_exported helpers through "+ f"{stats['layer_collections']} view-layer eye toggle(s) and "+ f"{stats['collections']} collection render toggle(s); cleared "+ f"{stats['object_flags_cleared']} buried object flag(s).")@classmethod@@ -1548,15 +1527,37 @@ class Trellis2Generate(bpy.types.Operator):print(f"[TRELLIS2] Saved GLB to: {glb_path} ({len(self._glb_data)} bytes)")- # Import GLB into Blender- bpy.ops.import_scene.gltf(filepath=glb_path)autorig_enabled = getattr(self, '_autorig_enabled', False)+ autorig_bone_heuristic = getattr(+ context.scene,+ 'trellis2_autorig_bone_heuristic',+ 'FORTUNE',+ )+ # Import rigged SkinTokens joints with child-directed bone tails.+ # Plain TRELLIS GLBs have no armature, so retain Blender's normal+ # import defaults for those files.+ if autorig_enabled:+ bpy.ops.import_scene.gltf(**autorig_gltf_import_kwargs(+ glb_path, autorig_bone_heuristic))+ else:+ bpy.ops.import_scene.gltf(filepath=glb_path)# --- Clean hierarchy, unparent meshes, and remove GLTF/GLB structural empties ---imported_objects = [obj for obj in context.selected_objects]for obj in imported_objects:obj["sg_generated"] = True- self._disable_not_exported_render_helpers()+ if autorig_enabled:+ record_autorig_bone_heuristic(+ imported_objects, autorig_bone_heuristic)+ apply_autorig_bone_display(+ imported_objects,+ getattr(+ context.scene,+ 'trellis2_autorig_bone_display_type',+ 'OCTAHEDRAL',+ ),+ )+ self._configure_not_exported_helpers()mesh_objects = [obj for obj in imported_objects if obj.type == 'MESH']empty_objects = [obj for obj in imported_objects if obj.type == 'EMPTY']@@ -2190,6 +2191,39 @@ class Trellis2Generate(bpy.types.Operator):traceback.print_exc()+class StableGenApplyBoneDisplay(bpy.types.Operator):+ """Apply the configured bone presentation to selected generated rigs."""++ bl_idname = "stablegen.apply_autorig_bone_display"+ bl_label = "Apply Bone Display"+ bl_description = (+ "Apply the selected SkinTokens bone display style to the selected "+ "armature or the armature driving the selected mesh"+ )+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ if sg_modal_active(context):+ return False+ armatures = selected_armatures_for_display(context)+ if not armatures:+ cls.poll_message_set("Select an armature or a rigged mesh")+ return False+ return True++ def execute(self, context):+ armatures = selected_armatures_for_display(context)+ display_type = getattr(+ context.scene, 'trellis2_autorig_bone_display_type', 'OCTAHEDRAL')+ count = apply_autorig_bone_display(armatures, display_type)+ self.report(+ {'INFO'},+ f"Applied {display_type.title()} bone display to {count} armature(s)",+ )+ return {'FINISHED'}++class StableGenAutoRigSelectedMesh(bpy.types.Operator):"""Run SkinTokens auto-rigging on the selected character mesh objects."""@@ -2254,6 +2288,47 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):),default='NONE',) # type: ignore+ bone_display_type: bpy.props.EnumProperty(+ name="Bone Display",+ description="Viewport shape used for the imported SkinTokens bones",+ items=(+ ('OCTAHEDRAL', "Octahedral (Mixamo-like)", "Classic tapered Blender/Mixamo-style bones"),+ ('STICK', "Stick / Joint Circles", "Thin bone lines with circular joint markers"),+ ('BBONE', "B-Bone", "Box-like bendy-bone display"),+ ('ENVELOPE', "Envelope", "Display bone deformation envelopes"),+ ('WIRE', "Wire", "Wireframe bone display"),+ ('IMPORTED', "Imported", "Keep the display and custom shapes from the imported GLB"),+ ),+ default='OCTAHEDRAL',+ ) # type: ignore+ bone_heuristic: bpy.props.EnumProperty(+ name="Bone Direction",+ description=(+ "How Blender constructs display/deform bone axes from SkinTokens "+ "glTF joint transforms"+ ),+ items=(+ (+ 'FORTUNE',+ "Fortune / Child-Directed",+ "Point one-child bones at their child joints; best-looking default, "+ "but non-uniform joint scaling can be less accurate",+ ),+ (+ 'BLENDER',+ "Blender / Legacy Round-Trip",+ "Preserve glTF local joint axes and imported joint-marker shapes; "+ "best for glTF round trips",+ ),+ (+ 'TEMPERANCE',+ "Temperance / Nearest Axis",+ "Point toward the closest local axis; safer for non-uniform scaling "+ "but less anatomically aligned than Fortune",+ ),+ ),+ default='FORTUNE',+ ) # type: ignoretop_k: bpy.props.IntProperty(name="Top K",description="SkinTokens sampling top-k",@@ -2313,6 +2388,16 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):True,),("garment_mode", "trellis2_autorig_garment_mode", "NONE"),+ (+ "bone_display_type",+ "trellis2_autorig_bone_display_type",+ "OCTAHEDRAL",+ ),+ (+ "bone_heuristic",+ "trellis2_autorig_bone_heuristic",+ "FORTUNE",+ ),("top_k", "trellis2_autorig_top_k", 5),("top_p", "trellis2_autorig_top_p", 0.95),("temperature", "trellis2_autorig_temperature", 1.0),@@ -2394,6 +2479,8 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):behavior_box.prop(self, "use_postprocess")behavior_box.prop(self, "cleanup_cross_limb_weights")behavior_box.prop(self, "garment_mode")+ behavior_box.prop(self, "bone_heuristic")+ behavior_box.prop(self, "bone_display_type")behavior_box.prop(self, "hide_source")if self.hide_source:behavior_box.label(@@ -2873,13 +2960,22 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):with open(output_path, 'wb') as handle:handle.write(self._rigged_data)- bpy.ops.import_scene.gltf(filepath=output_path)+ bpy.ops.import_scene.gltf(**autorig_gltf_import_kwargs(+ output_path, getattr(self, 'bone_heuristic', 'FORTUNE')))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+ record_autorig_bone_heuristic(+ imported_objects,+ getattr(self, 'bone_heuristic', 'FORTUNE'),+ )+ apply_autorig_bone_display(+ imported_objects,+ getattr(self, 'bone_display_type', 'OCTAHEDRAL'),+ )- Trellis2Generate._disable_not_exported_render_helpers()+ Trellis2Generate._configure_not_exported_helpers()mesh_objects = [obj for obj in imported_objects if obj.type == 'MESH']if mesh_objects:Trellis2Generate._clear_imported_custom_normals(mesh_objects)diff --git a/stablegen/mesh_gen/workflows.py b/stablegen/mesh_gen/workflows.pyindex 1bda86d..a4db0a5 100644--- a/stablegen/mesh_gen/workflows.py+++ b/stablegen/mesh_gen/workflows.py@@ -1389,7 +1389,7 @@ class _Trellis2WorkflowMixin:# Save prompt for debuggingrevision_dir = get_generation_dirs(context).get("revision", "")if revision_dir:- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(prompt, revision_dir, workflow="trellis2")# --- Two-phase VRAM management for textured path ---# NOTE: Two-phase execution (shape first, flush, then texture) wasdiff --git a/stablegen/prompt_archive.py b/stablegen/prompt_archive.pynew file mode 100644index 0000000..881b136--- /dev/null+++ b/stablegen/prompt_archive.py@@ -0,0 +1,67 @@+"""Blender-independent helpers for preserving submitted ComfyUI workflows."""++from __future__ import annotations++import json+import os+from pathlib import Path+import re+from typing import Mapping+++_UNSAFE_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9._-]+")+++def _safe_filename_component(value: object, fallback: str) -> str:+ text = _UNSAFE_FILENAME_CHARS.sub("_", str(value or "").strip())+ text = text.strip("._-")+ return text or fallback+++def _write_json_atomic(path: Path, prompt: Mapping) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name(f".{path.name}.tmp")+ with temporary.open("w", encoding="utf-8", newline="\n") as handle:+ json.dump(prompt, handle, indent=2, ensure_ascii=False)+ handle.write("\n")+ os.replace(temporary, path)+++def archive_prompt(+ prompt: Mapping,+ output_dir: str | os.PathLike,+ *,+ workflow: str = "workflow",+ view_index: int | None = None,+ camera_name: str | None = None,+) -> tuple[Path, Path]:+ """Save the latest prompt plus a non-overwriting per-submission copy.++ ``prompt.json`` remains a compatibility/convenience alias for the latest+ graph. Every call also creates a JSON file under ``prompts/``. Repeated+ submissions for the same view receive a numeric suffix.+ """+ output_path = Path(output_dir)+ latest_path = output_path / "prompt.json"+ archive_dir = output_path / "prompts"++ workflow_part = _safe_filename_component(workflow, "workflow")+ stem_parts = []+ if view_index is not None:+ stem_parts.append(f"view_{int(view_index):03d}")+ else:+ stem_parts.append("submission")+ if camera_name:+ stem_parts.append(_safe_filename_component(camera_name, "camera"))+ stem_parts.append(workflow_part)+ stem = "_".join(stem_parts)++ archive_path = archive_dir / f"{stem}.json"+ suffix = 2+ while archive_path.exists():+ archive_path = archive_dir / f"{stem}_{suffix:02d}.json"+ suffix += 1++ _write_json_atomic(latest_path, prompt)+ _write_json_atomic(archive_path, prompt)+ return latest_path, archive_pathdiff --git a/stablegen/texturing/confidence.py b/stablegen/texturing/confidence.pyindex 7274923..18f21d7 100644--- a/stablegen/texturing/confidence.py+++ b/stablegen/texturing/confidence.py@@ -65,6 +65,26 @@ def acquisition_quality(return np.clip(result, 0.0, 1.0)+def best_source_quality(qualities, write_masks=None):+ """Return the best legitimately acquired source quality per sample.++ Colour fusion is intentionally absent from this policy. A camera may+ improve confidence only where it was permitted to write; copied/protected+ context therefore cannot inherit the new camera's geometric quality.+ """+ q = np.asarray(qualities, dtype=np.float32)+ if q.ndim < 1 or q.shape[0] == 0:+ raise ValueError("qualities must contain a non-empty camera axis")+ if write_masks is None:+ writes = np.ones_like(q, dtype=bool)+ else:+ writes = np.asarray(write_masks) > 0+ if writes.shape != q.shape:+ raise ValueError("write_masks must match qualities")+ accepted = np.where(writes, np.clip(q, 0.0, 1.0), 0.0)+ return np.max(accepted, axis=0)++def resolve_ownership(qualities,write_masks=None,diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.pyindex e8da1e7..ff3b882 100644--- a/stablegen/texturing/generator.py+++ b/stablegen/texturing/generator.py@@ -48,6 +48,12 @@ from .quality_masks import (build_depth_part_rejection_mask,)from .confidence import camera_direction_from_matrix, overlap_aware_order+from .pose_lock import (+ TexturingPoseLock,+ ensure_texturing_frame,+ restore_active_texturing_frame,+ set_active_texturing_frame,+)from ..feature_flags import TEXTURING_REWORK_DEFAULTSimport websocket@@ -410,9 +416,39 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):self._pbr_cam = 0self._pbr_cam_total = 1self._wait_event = threading.Event()+ self._texturing_pose_lock = None+ self._active_texturing_frame_previous = Nonefrom ..workflows import WorkflowManagerself.workflow_manager = WorkflowManager(self)+ def _begin_texturing_pose_lock(self, context, meshes):+ """Freeze an animated target rig at the pose visible when Generate ran."""+ self._texturing_pose_lock = TexturingPoseLock(context, meshes)+ if not self._texturing_pose_lock.freeze():+ return False+ self._original_texturing_frame = self._texturing_pose_lock.frame+ self._active_texturing_frame_previous = set_active_texturing_frame(+ context.scene, self._original_texturing_frame+ )+ print(+ "[StableGen] Locked animated character pose at frame "+ f"{self._original_texturing_frame} for texturing"+ )+ return True++ def _restore_texturing_pose(self, context):+ """Idempotently restore the target rig and run-scoped frame marker."""+ pose_lock = getattr(self, "_texturing_pose_lock", None)+ if pose_lock is not None:+ pose_lock.restore()+ self._texturing_pose_lock = None+ previous = getattr(self, "_active_texturing_frame_previous", None)+ if previous is not None:+ restore_active_texturing_frame(context.scene, previous)+ self._active_texturing_frame_previous = None+ elif hasattr(self, '_original_texturing_frame'):+ context.scene.frame_set(self._original_texturing_frame)+def _run_on_main_thread(self, func):"""Execute *func* on Blender's main thread via a timer callback andblock until it completes. Sets ``self._error`` on failure."""@@ -851,7 +887,24 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):ordered.append(camera)self._cameras = ordered- if getattr(context.scene, 'sg_rework_consistent_frame', False):+ # An Action is reevaluated by every later frame_set(), including the+ # legacy exporters which select frame 1. Capture and freeze the exact+ # visible pose before any of those calls can move an animated target.+ if context.scene.texture_objects == 'selected':+ pose_lock_targets = [+ obj for obj in bpy.context.selected_objects+ if obj.type == 'MESH'+ ]+ else:+ pose_lock_targets = [+ obj for obj in bpy.context.view_layer.objects+ if obj.type == 'MESH' and not obj.hide_get()+ ]+ pose_locked = self._begin_texturing_pose_lock(+ context, pose_lock_targets+ )+ if (not pose_locked+ and getattr(context.scene, 'sg_rework_consistent_frame', False)):self._original_texturing_frame = context.scene.frame_currentcontext.scene.frame_set(int(getattr(context.scene, 'sg_texturing_frame', 1)))@@ -995,8 +1048,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_percentage = self._original_resolution_percentagerender.resolution_x = self._original_resolution_xrender.resolution_y = self._original_resolution_y- if hasattr(self, '_original_texturing_frame'):- context.scene.frame_set(self._original_texturing_frame)+ self._restore_texturing_pose(context)return {'CANCELLED'}# If there are curves within the scene, warn the user@@ -1021,8 +1073,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_percentage = self._original_resolution_percentagerender.resolution_x = self._original_resolution_xrender.resolution_y = self._original_resolution_y- if hasattr(self, '_original_texturing_frame'):- context.scene.frame_set(self._original_texturing_frame)+ self._restore_texturing_pose(context)return {'CANCELLED'}else: # allself._to_texture = [obj for obj in bpy.context.view_layer.objects if obj.type == 'MESH' and not obj.hide_get()]@@ -1045,8 +1096,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_percentage = self._original_resolution_percentagerender.resolution_x = self._original_resolution_xrender.resolution_y = self._original_resolution_y- if hasattr(self, '_original_texturing_frame'):- context.scene.frame_set(self._original_texturing_frame)+ self._restore_texturing_pose(context)return {'CANCELLED'}if not context.scene.overwrite_material or self._material_id == -1 or (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit')):@@ -1080,6 +1130,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):# Start the prompt collection process with the first objectif not self._object_prompts: # Only if prompts haven't been collectedself.current_object_name = self._to_texture[0].name+ self._restore_texturing_pose(context)return context.window_manager.invoke_props_dialog(self, width=400)# Continue with normal execution if all prompts are collected@@ -1121,6 +1172,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_percentage = self._original_resolution_percentagerender.resolution_x = self._original_resolution_xrender.resolution_y = self._original_resolution_y+ self._restore_texturing_pose(context)return {'CANCELLED'}# Export visibility masks for each object@@ -1232,8 +1284,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):if not self._error:self._error = f"Failed to restore projection state: {reset_error}"finally:- if hasattr(self, '_original_texturing_frame'):- context.scene.frame_set(self._original_texturing_frame)+ self._restore_texturing_pose(context)if self._error:if self._error == "'25'" or self._error == "'111'" or self._error == "'5'":# Probably canceled by user, quietly return@@ -1507,9 +1558,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):context.scene.camera = camerareturn camerareturn None- texturing_frame = int(getattr(context.scene, 'sg_texturing_frame', 1))- if context.scene.frame_current != texturing_frame:- context.scene.frame_set(texturing_frame)+ ensure_texturing_frame(context.scene, force_configured=True)record = self._view_plan[index]camera = record.cameraif record.matrix_world:@@ -2262,7 +2311,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):original_use_compositing = bpy.context.scene.render.use_compositingoriginal_filepath = bpy.context.scene.render.filepath- bpy.context.scene.frame_set(1)+ ensure_texturing_frame(+ bpy.context.scene, honor_consistent=False+ )output_dir = get_dir_path(context, "controlnet")["depth"]output_file = f"depth_map{camera_id}" if camera_id is not None else "depth_map"@@ -2330,8 +2381,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator)::return: None"""print("[StableGen] Exporting depth map")- if not getattr(context.scene, 'sg_rework_consistent_frame', False):- context.scene.frame_set(1)+ ensure_texturing_frame(context.scene)# Save original settings to restore later.original_engine = bpy.context.scene.render.engineoriginal_view_transform = bpy.context.scene.view_settings.view_transform@@ -2584,8 +2634,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):def _export_normal_impl(self, context, camera_id=None):"""Render the evaluated normal pass without mutating production state."""print("[StableGen] Exporting normal map")- if not getattr(context.scene, 'sg_rework_consistent_frame', False):- context.scene.frame_set(1)+ ensure_texturing_frame(context.scene)output_dir = get_dir_path(context, "controlnet")["normal"]output_file = f"normal_map{camera_id}" if camera_id is not None else "normal_map"diff --git a/stablegen/texturing/graph_validation.py b/stablegen/texturing/graph_validation.pyindex 754fc86..d6cd079 100644--- a/stablegen/texturing/graph_validation.py+++ b/stablegen/texturing/graph_validation.py@@ -68,6 +68,122 @@ def qwen_style_semantic_slot(context_mode: str, is_initial_image: bool) -> str:return "image2"+def qwen_reference_latent_slots(+ context_mode: str,+ is_initial_image: bool,+ global_style_vlm_only: bool,+) -> tuple[str, ...]:+ """Return Qwen image slots that should receive spatial reference latents.++ Image 3 remains connected to ``TextEncodeQwenImageEditPlus`` when the+ VLM-only experiment is active; omitting it here removes only its manual+ full-resolution ReferenceLatent conditioning.+ """+ slots = ["image1", "image2", "image3"]+ if (+ global_style_vlm_only+ and context_mode == "ADDITIONAL"+ and not is_initial_image+ ):+ slots.remove("image3")+ return tuple(slots)+++def attach_qwen_latent_lock(+ prompt: dict,+ *,+ sampler_node_id: str,+ vae_node_id: str,+ context_image_name: str,+ repair_mask_name: str,+ start_node_id: int = 650,+) -> dict[str, str]:+ """Attach sampler-level Qwen context inpainting to ``prompt``.++ The context render is VAE-encoded as the sampler's starting latent. The+ exported sequential visibility image uses StableGen's repair convention:+ white pixels may denoise and black pixels remain locked. ComfyUI's generic+ noise-mask sampler restores the protected source latent after every step.++ Dedicated loader/encode nodes are intentional. Qwen's semantic image+ slots are dynamically reordered between Replace Style and Additional+ modes; keeping the latent-lock path separate prevents semantic slot changes+ from silently changing which image is protected.+ """+ sampler_node_id = str(sampler_node_id)+ vae_node_id = str(vae_node_id)+ if sampler_node_id not in prompt:+ raise ValueError(f"Qwen latent lock sampler node {sampler_node_id} is missing")+ if vae_node_id not in prompt:+ raise ValueError(f"Qwen latent lock VAE node {vae_node_id} is missing")+ if not context_image_name:+ raise ValueError("Qwen latent lock requires a context image")+ if not repair_mask_name:+ raise ValueError("Qwen latent lock requires a repair mask")++ next_id = int(start_node_id)++ def allocate() -> str:+ nonlocal next_id+ while str(next_id) in prompt:+ next_id += 1+ node_id = str(next_id)+ next_id += 1+ return node_id++ context_loader = allocate()+ context_encode = allocate()+ mask_loader = allocate()+ image_to_mask = allocate()+ set_noise_mask = allocate()++ prompt[context_loader] = {+ "inputs": {"image": context_image_name},+ "class_type": "LoadImage",+ "_meta": {"title": "Qwen Latent Lock - Context"},+ }+ prompt[context_encode] = {+ "inputs": {+ "pixels": [context_loader, 0],+ "vae": [vae_node_id, 0],+ },+ "class_type": "VAEEncode",+ "_meta": {"title": "Qwen Latent Lock - Encode Context"},+ }+ prompt[mask_loader] = {+ "inputs": {"image": repair_mask_name},+ "class_type": "LoadImage",+ "_meta": {"title": "Qwen Latent Lock - Repair Mask"},+ }+ prompt[image_to_mask] = {+ "inputs": {+ "image": [mask_loader, 0],+ "channel": "red",+ },+ "class_type": "ImageToMask",+ "_meta": {"title": "Qwen Latent Lock - Image to Mask"},+ }+ prompt[set_noise_mask] = {+ "inputs": {+ "samples": [context_encode, 0],+ "mask": [image_to_mask, 0],+ },+ "class_type": "SetLatentNoiseMask",+ "_meta": {"title": "Qwen Latent Lock - Set Noise Mask"},+ }+ prompt[sampler_node_id].setdefault("inputs", {})["latent_image"] = [+ set_noise_mask,+ 0,+ ]+ return {+ "context_loader": context_loader,+ "context_encode": context_encode,+ "mask_loader": mask_loader,+ "image_to_mask": image_to_mask,+ "set_noise_mask": set_noise_mask,+ }++def sdxl_final_mask_reference(blur_mask: bool, nodes: Mapping) -> list:"""Return the one processed mask consumed by all SDXL inpaint nodes."""node_id = nodes['image_to_mask'] if blur_mask else nodes['grow_mask']diff --git a/stablegen/texturing/pose_lock.py b/stablegen/texturing/pose_lock.pynew file mode 100644index 0000000..992351d--- /dev/null+++ b/stablegen/texturing/pose_lock.py@@ -0,0 +1,224 @@+"""Keep an animated character in its visible pose during texturing.++Blender reevaluates Actions whenever ``Scene.frame_set`` is called. Several+texturing render paths intentionally change frames, so a pose edited by the+user (including StableGen's Rest/T/A pose buttons) would otherwise be replaced+by the Action pose. This module snapshots the visible pose, temporarily+disconnects its animation inputs, and restores them after generation.+"""++import bpy # pylint: disable=import-error+++_ACTIVE_TEXTURING_FRAME = "_sg_active_texturing_frame"+++def _has_animation(armature):+ animation_data = armature.animation_data+ if not animation_data:+ return False+ if animation_data.action is not None:+ return True+ if any(track.strips for track in animation_data.nla_tracks):+ return True+ return bool(animation_data.drivers)+++def _target_armatures(meshes):+ armatures = []+ seen = set()+ for mesh in meshes:+ if not mesh or mesh.type != 'MESH':+ continue+ candidates = []+ try:+ found = mesh.find_armature()+ if found is not None:+ candidates.append(found)+ except (AttributeError, RuntimeError):+ pass+ candidates.extend(+ modifier.object+ for modifier in mesh.modifiers+ if modifier.type == 'ARMATURE' and modifier.object is not None+ )+ if mesh.parent and mesh.parent.type == 'ARMATURE':+ candidates.append(mesh.parent)+ for armature in candidates:+ pointer = armature.as_pointer()+ if pointer not in seen and _has_animation(armature):+ seen.add(pointer)+ armatures.append(armature)+ return armatures+++def set_active_texturing_frame(scene, frame):+ """Publish the run frame to render helpers which do not own the operator."""+ previous = (+ _ACTIVE_TEXTURING_FRAME in scene,+ scene.get(_ACTIVE_TEXTURING_FRAME),+ )+ scene[_ACTIVE_TEXTURING_FRAME] = int(frame)+ return previous+++def restore_active_texturing_frame(scene, previous):+ """Restore a pre-existing runtime frame marker, if there was one."""+ existed, value = previous+ if existed:+ scene[_ACTIVE_TEXTURING_FRAME] = value+ elif _ACTIVE_TEXTURING_FRAME in scene:+ del scene[_ACTIVE_TEXTURING_FRAME]+++def ensure_texturing_frame(+ scene, legacy_frame=1, *, honor_consistent=True,+ force_configured=False):+ """Select the run's captured frame, or retain the configured legacy rule."""+ active_frame = scene.get(_ACTIVE_TEXTURING_FRAME)+ if active_frame is not None:+ target = int(active_frame)+ elif (force_configured+ or (honor_consistent+ and getattr(scene, 'sg_rework_consistent_frame', False))):+ target = int(getattr(scene, 'sg_texturing_frame', legacy_frame))+ else:+ target = int(legacy_frame)+ if scene.frame_current != target:+ scene.frame_set(target)+ return target+++class TexturingPoseLock:+ """Freeze animated armatures at the evaluated pose visible at click time."""++ def __init__(self, context, meshes):+ self._context = context+ self._scene = context.scene+ self._frame = int(context.scene.frame_current)+ self._armatures = []+ self._frozen = False+ self._restored = False++ for armature in _target_armatures(meshes):+ animation_data = armature.animation_data+ self._armatures.append({+ "object": armature,+ "matrix_world": armature.matrix_world.copy(),+ "pose_position": armature.data.pose_position,+ "action": animation_data.action,+ "use_nla": getattr(animation_data, "use_nla", None),+ "nla_mutes": [+ (track, bool(track.mute))+ for track in animation_data.nla_tracks+ ],+ "driver_mutes": [+ (driver, bool(driver.mute))+ for driver in animation_data.drivers+ ],+ "object_constraint_mutes": [+ (constraint, bool(constraint.mute))+ for constraint in armature.constraints+ ],+ "bone_constraint_mutes": [+ (constraint, bool(constraint.mute))+ for pose_bone in armature.pose.bones+ for constraint in pose_bone.constraints+ ],+ "bone_matrices": {+ pose_bone.name: pose_bone.matrix.copy()+ for pose_bone in armature.pose.bones+ },+ "bone_bases": {+ pose_bone.name: pose_bone.matrix_basis.copy()+ for pose_bone in armature.pose.bones+ },+ })++ @property+ def active(self):+ return bool(self._armatures)++ @property+ def frame(self):+ return self._frame++ def _apply_captured_pose(self):+ for state in self._armatures:+ armature = state["object"]+ if armature.name not in bpy.data.objects:+ continue+ armature.data.pose_position = 'POSE'+ armature.matrix_world = state["matrix_world"]+ pose_bones = sorted(+ armature.pose.bones,+ key=lambda pose_bone: len(pose_bone.parent_recursive),+ )+ for pose_bone in pose_bones:+ matrix = state["bone_matrices"].get(pose_bone.name)+ if matrix is not None:+ pose_bone.matrix = matrix+ self._context.view_layer.update()++ def freeze(self):+ if not self.active or self._frozen:+ return self.active+ for state in self._armatures:+ armature = state["object"]+ animation_data = armature.animation_data+ animation_data.action = None+ if state["use_nla"] is not None:+ animation_data.use_nla = False+ for track, _mute in state["nla_mutes"]:+ track.mute = True+ for driver, _mute in state["driver_mutes"]:+ driver.mute = True+ for constraint, _mute in (+ state["object_constraint_mutes"]+ + state["bone_constraint_mutes"]):+ constraint.mute = True+ self._apply_captured_pose()+ self._frozen = True+ return True++ def restore(self):+ if self._restored or not self.active:+ return+ # Restore every animation input first. Assigning an Action tags the rig+ # for dependency-graph reevaluation, so applying the manual pose before+ # this point would let the next viewport redraw overwrite it.+ for state in self._armatures:+ armature = state["object"]+ if armature.name not in bpy.data.objects:+ continue+ animation_data = armature.animation_data+ animation_data.action = state["action"]+ if state["use_nla"] is not None:+ animation_data.use_nla = state["use_nla"]+ for track, mute in state["nla_mutes"]:+ track.mute = mute+ for driver, mute in state["driver_mutes"]:+ driver.mute = mute+ for constraint, mute in (+ state["object_constraint_mutes"]+ + state["bone_constraint_mutes"]):+ constraint.mute = mute+ armature.data.pose_position = state["pose_position"]++ # Deliberately evaluate the restored animation at the click-time frame,+ # then reproduce the exact unkeyed/manual state as the final mutation.+ # This is equivalent to the user pressing StableGen's Rest/T/A button+ # after selecting that frame: animation remains attached and resumes on+ # the next explicit timeline change.+ self._scene.frame_set(self._frame)+ self._context.view_layer.update()+ for state in self._armatures:+ armature = state["object"]+ if armature.name not in bpy.data.objects:+ continue+ armature.matrix_world = state["matrix_world"]+ for pose_bone in armature.pose.bones:+ basis = state["bone_bases"].get(pose_bone.name)+ if basis is not None:+ pose_bone.matrix_basis = basis+ self._restored = Truediff --git a/stablegen/texturing/print_export.py b/stablegen/texturing/print_export.pyindex fc89619..ffe9cea 100644--- a/stablegen/texturing/print_export.py+++ b/stablegen/texturing/print_export.py@@ -1971,8 +1971,10 @@ def _collect_face_visibility(mesh):return face_vis-def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None, keep_largest_island=False,- face_visibility=None):+def _make_solid_mesh_object(+ obj, fill_gaps=True, visible_faces=None, keep_largest_island=False,+ face_visibility=None, *, use_evaluated_mesh=True, raycast_count=None,+ weld_distance=0.0001, robust_fill=False, smooth_caps=False):import bmeshfrom mathutils.bvhtree import BVHTreeimport numpy as np@@ -1982,13 +1984,29 @@ def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None, keep_largesimport timet_start = time.perf_counter()- temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms=False)+ if use_evaluated_mesh:+ temp, eval_obj = _get_triangulated_mesh(+ obj, apply_transforms=False+ )+ else:+ # General post-processing must operate on the base/rest mesh. Using+ # evaluated_get().to_mesh() here would bake the current armature pose+ # and leave the Armature modifier attached, causing double deformation.+ temp = obj.data.copy()+ eval_obj = None+ temp.calc_loop_triangles()try:bm = bmesh.new()bm.from_mesh(temp)- # Weld overlapping/duplicate vertices to resolve topological disconnects on boundaries- bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001)+ # The 3D-print export historically welds coincident evaluated geometry.+ # General post-processing must not globally weld detached character+ # shells (clothing/body, armor panels, eyes, etc.), because doing so+ # creates branching boundaries and overlapping caps.+ if weld_distance and weld_distance > 0.0:+ bmesh.ops.remove_doubles(+ bm, verts=bm.verts, dist=float(weld_distance)+ )bm.faces.ensure_lookup_table()bm.edges.ensure_lookup_table()@@ -2041,16 +2059,23 @@ def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None, keep_largesz_bottom = zmin# Precompute cylinder angle offsets (ordered by proximity to 0.0)- raycast_count = 12- if hasattr(bpy, "context") and bpy.context and hasattr(bpy.context, "scene") and bpy.context.scene:- raycast_count = getattr(bpy.context.scene, "stablegen_print_raycast_count", 12)+ effective_raycast_count = raycast_count+ if effective_raycast_count is None:+ effective_raycast_count = 12+ if hasattr(bpy, "context") and bpy.context and hasattr(bpy.context, "scene") and bpy.context.scene:+ effective_raycast_count = getattr(+ bpy.context.scene,+ "stablegen_print_raycast_count",+ 12,+ )+ effective_raycast_count = max(4, int(effective_raycast_count))angle_offsets = [0.0]- step = 2.0 * math.pi / raycast_count+ step = 2.0 * math.pi / effective_raycast_counti = 1- while len(angle_offsets) < raycast_count:+ while len(angle_offsets) < effective_raycast_count:angle_offsets.append(i * step)- if len(angle_offsets) < raycast_count:+ if len(angle_offsets) < effective_raycast_count:angle_offsets.append(-i * step)i += 1@@ -2153,101 +2178,232 @@ def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None, keep_largesif fill_gaps:t0 = time.perf_counter()- visible_centers = {tuple(round(c, 4) for c in f.calc_center_median()) for f in bm.faces}-- # 2. Identify all boundary edges after deletionboundary_edges = [e for e in bm.edges if e.is_boundary]print(f"[StableGen Make Solid] Identified {len(boundary_edges)} boundary edges in {time.perf_counter() - t0:.4f}s")-- # 3. Walk and trace all boundary edge loops to create new cap faces directly (incredibly fast)++ # Mark newly created faces explicitly. Centroid comparison is not+ # reliable on dense meshes because unrelated small triangles can+ # quantize to the same rounded center.+ cap_layer = bm.faces.layers.int.get("_SG_SolidCap")+ if cap_layer is None:+ cap_layer = bm.faces.layers.int.new("_SG_SolidCap")+ source_faces = set(bm.faces)+t0 = time.perf_counter()new_faces = []-- # Map each boundary edge to its desired directed transition (v -> u)- # to ensure that the cap face traverses the edge in the opposite direction- # of the adjacent face (achieving a consistent winding order and correct outward normal).- directed_transitions = []- for e in boundary_edges:- f = e.link_faces[0]- target_loop = None- for l in f.loops:- if l.edge == e:- target_loop = l- break- if target_loop:- u = target_loop.vert- v = target_loop.link_loop_next.vert- directed_transitions.append((v, u, e))-- # Group directed transitions by their start vertex- from collections import defaultdict- vert_to_transitions = defaultdict(list)- for trans in directed_transitions:- v_start, v_end, e = trans- vert_to_transitions[v_start].append(trans)-- directed_edges_set = set(directed_transitions)- while directed_edges_set:- start_trans = directed_edges_set.pop()- v_start, v_next, e = start_trans-- loop_verts = [v_start]- visited_verts_set = {v_start}- v_curr = v_next-- while True:- # Cycle detection: split complex/bowtie networks into separate simple faces- if v_curr in visited_verts_set:- idx = loop_verts.index(v_curr)- cycle = loop_verts[idx:]- if len(cycle) >= 3:- try:- nf = bm.faces.new(cycle)- new_faces.append(nf)- except Exception:- pass- # Remove the completed cycle from the active walk path- loop_verts = loop_verts[:idx]- visited_verts_set = set(loop_verts)-- loop_verts.append(v_curr)- visited_verts_set.add(v_curr)-- next_trans = None- for trans in vert_to_transitions[v_curr]:- if trans in directed_edges_set:- next_trans = trans++ if robust_fill and boundary_edges:+ # Fill each genuine boundary cycle independently. The legacy+ # arbitrary transition walk can cross between touching loops+ # and create overlapping faces. A branching component is+ # rejected rather than silently damaging the source object.+ remaining = set(boundary_edges)+ boundary_set = set(boundary_edges)+ components = []+ while remaining:+ seed = remaining.pop()+ component = {seed}+ stack = [seed]+ while stack:+ edge = stack.pop()+ for vert in edge.verts:+ for linked in vert.link_edges:+ if linked in remaining and linked in boundary_set:+ remaining.remove(linked)+ component.add(linked)+ stack.append(linked)+ components.append(component)++ for component in components:+ component_vertices = {+ vert for edge in component for vert in edge.verts+ }+ branching = [+ vert for vert in component_vertices+ if sum(+ edge in component for edge in vert.link_edges+ ) != 2+ ]+ if branching:+ raise RuntimeError(+ "cannot safely cap a branching boundary "+ f"({len(component)} edges, "+ f"{len(branching)} branching vertices)"+ )+ fill_result = bmesh.ops.triangle_fill(+ bm,+ edges=list(component),+ use_beauty=True,+ use_dissolve=False,+ )+ component_faces = [+ geom for geom in fill_result.get("geom", ())+ if isinstance(geom, bmesh.types.BMFace)+ and geom not in source_faces+ ]+ if not component_faces:+ raise RuntimeError(+ "failed to create a cap for a valid boundary loop"+ )+ new_faces.extend(component_faces)+ else:+ # Preserve the historical 3D-print fill behavior. The general+ # post-processing operator uses the validated triangle-fill+ # path above.+ directed_transitions = []+ for edge in boundary_edges:+ face = edge.link_faces[0]+ target_loop = next(+ (loop for loop in face.loops if loop.edge == edge),+ None,+ )+ if target_loop:+ directed_transitions.append((+ target_loop.link_loop_next.vert,+ target_loop.vert,+ edge,+ ))++ from collections import defaultdict+ vert_to_transitions = defaultdict(list)+ for transition in directed_transitions:+ vert_to_transitions[transition[0]].append(transition)++ directed_edges_set = set(directed_transitions)+ while directed_edges_set:+ start_trans = directed_edges_set.pop()+ loop_verts = [start_trans[0]]+ visited_verts_set = {start_trans[0]}+ vert_current = start_trans[1]++ while True:+ if vert_current in visited_verts_set:+ index = loop_verts.index(vert_current)+ cycle = loop_verts[index:]+ if len(cycle) >= 3:+ try:+ new_faces.append(bm.faces.new(cycle))+ except Exception:+ pass+ loop_verts = loop_verts[:index]+ visited_verts_set = set(loop_verts)++ loop_verts.append(vert_current)+ visited_verts_set.add(vert_current)+ next_trans = next(+ (+ transition+ for transition in vert_to_transitions[+ vert_current+ ]+ if transition in directed_edges_set+ ),+ None,+ )+ if next_trans is None:+ if len(loop_verts) >= 3:+ try:+ new_faces.append(+ bm.faces.new(loop_verts)+ )+ except Exception:+ passbreak- if next_trans is None:- # Close the remaining walk path if valid- if len(loop_verts) >= 3:- try:- nf = bm.faces.new(loop_verts)- new_faces.append(nf)- except Exception:- pass- break-- directed_edges_set.remove(next_trans)- v_curr = next_trans[1]- print(f"[StableGen Make Solid] Traced and created {len(new_faces)} cap faces in {time.perf_counter() - t0:.4f}s")-- # 5. Triangulate the newly created cap faces using beauty settings+ directed_edges_set.remove(next_trans)+ vert_current = next_trans[1]++ print(f"[StableGen Make Solid] Created {len(new_faces)} cap faces in {time.perf_counter() - t0:.4f}s")++ # Use a temporary sentinel so triangulation can be identified+ # without depending on BMesh face identity surviving the operation.+ for face in new_faces:+ face[cap_layer] = 2+t0 = time.perf_counter()- if new_faces:+ if new_faces and not robust_fill:try:- bmesh.ops.triangulate(bm, faces=new_faces, quad_method='BEAUTY', ngon_method='BEAUTY')- except Exception as e:- print(f"[StableGen Make Solid] Warning: BMesh triangulation failed: {e}")- print(f"[StableGen Make Solid] Triangulated new faces in {time.perf_counter() - t0:.4f}s")-- # 6. Find new faces and transfer nearest colors+ bmesh.ops.triangulate(+ bm,+ faces=new_faces,+ quad_method='BEAUTY',+ ngon_method='BEAUTY',+ )+ except Exception as error:+ print(+ "[StableGen Make Solid] Warning: "+ f"BMesh triangulation failed: {error}"+ )+ final_new_faces = [+ face for face in bm.faces if face[cap_layer] == 2+ ]+ for face in final_new_faces:+ face[cap_layer] = 1+ print(f"[StableGen Make Solid] Finalized {len(final_new_faces)} cap triangles in {time.perf_counter() - t0:.4f}s")++ # Inherit the surrounding face material instead of accepting+ # BMesh's default material slot 0. Direct boundary-edge votes are+ # preferred; vertex adjacency covers interior fill triangles.+ for cap_face in final_new_faces:+ material_votes = {}+ for edge in cap_face.edges:+ for adjacent in edge.link_faces:+ if adjacent in source_faces and adjacent.is_valid:+ material = adjacent.material_index+ material_votes[material] = (+ material_votes.get(material, 0.0)+ + max(edge.calc_length(), 1.0e-8) * 4.0+ )+ if not material_votes:+ for vert in cap_face.verts:+ for adjacent in vert.link_faces:+ if adjacent in source_faces and adjacent.is_valid:+ material = adjacent.material_index+ material_votes[material] = (+ material_votes.get(material, 0.0) + 1.0+ )+ if material_votes:+ cap_face.material_index = max(+ material_votes,+ key=material_votes.get,+ )+ cap_face.smooth = bool(smooth_caps)+t0 = time.perf_counter()- final_new_faces = []- for f in bm.faces:- center_key = tuple(round(c, 4) for c in f.calc_center_median())- if center_key not in visible_centers:- final_new_faces.append(f)++ # New cap loops otherwise receive zero/default custom-data values.+ # Copy UV, color, and generic corner attributes from the nearest+ # surviving loop on the same boundary vertex. This keeps existing+ # ProjectionUV attributes usable when solidifying after texturing.+ new_face_set = set(final_new_faces)+ layer_kinds = (+ "uv", "color", "float_color", "float",+ "float_vector", "int", "string",+ )+ for nf in final_new_faces:+ for dst_loop in nf.loops:+ src_loop = next(+ (+ loop for loop in dst_loop.vert.link_loops+ if loop.face not in new_face_set+ ),+ None,+ )+ if src_loop is None:+ continue+ for kind in layer_kinds:+ layers = getattr(bm.loops.layers, kind, None)+ if layers is None:+ continue+ for layer in layers.values():+ try:+ if kind == "uv":+ dst_loop[layer].uv = src_loop[layer].uv+ else:+ dst_loop[layer] = src_loop[layer]+ except (AttributeError, TypeError, ValueError):+ # Not every Blender version exposes every+ # generic layer through an assignable BMesh API.+ passif color_lay and final_new_faces:valid_face_info = [info for info in face_info if info[2] in visible_faces]@@ -2276,6 +2432,26 @@ def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None, keep_largesbm.to_mesh(solid_mesh)bm.free()+ # BMesh exposes face booleans through its integer custom-data layer.+ # Convert the internal 0/1 marker to a proper mesh Boolean attribute so+ # Geometry Nodes, shaders, diagnostics, and future post-processing can+ # consume it without guessing the storage convention.+ cap_attribute = solid_mesh.attributes.get("_SG_SolidCap")+ if (+ cap_attribute is not None+ and cap_attribute.data_type != 'BOOLEAN'+ ):+ cap_values = [+ bool(item.value) for item in cap_attribute.data+ ]+ solid_mesh.attributes.remove(cap_attribute)+ cap_attribute = solid_mesh.attributes.new(+ name="_SG_SolidCap",+ type='BOOLEAN',+ domain='FACE',+ )+ cap_attribute.data.foreach_set("value", cap_values)+if vis_centers is not None:import numpy as npn_faces = len(solid_mesh.polygons)@@ -2292,7 +2468,10 @@ def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None, keep_largesprint(f"[StableGen Make Solid] Total execution time: {time.perf_counter() - t_start:.4f}s")return solid_meshfinally:- eval_obj.to_mesh_clear()+ if eval_obj is not None:+ eval_obj.to_mesh_clear()+ elif temp and temp.name in bpy.data.meshes:+ bpy.data.meshes.remove(temp)def _extract_mesh_data(obj, apply_transforms, palette_rgbs, image):@@ -3503,4 +3682,3 @@ class Export3MFCancel(bpy.types.Operator):else:self.report({'WARNING'}, "No active 3MF export operator found.")return {'FINISHED'}-diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.pyindex 5bf9167..4137225 100644--- a/stablegen/texturing/projection.py+++ b/stablegen/texturing/projection.py@@ -2004,6 +2004,7 @@ def project_image(getattr(context.scene, 'sg_rework_projection_rebuild', False),getattr(context.scene, 'sg_rework_projection_guard', False),getattr(context.scene, 'sg_texel_ownership', False),+ getattr(context.scene, 'qwen_use_confidence_context', False),getattr(context.scene, 'qwen_use_projection_write_masks', False),getattr(context.scene, 'sg_rework_sdxl_registration', False),))@@ -2106,6 +2107,7 @@ def project_image(normalize_nodes = []script_nodes = []script_nodes_outputs = []+ confidence_quality_nodes = []add_camera_loc_nodes = []length_nodes = []camera_fov_nodes = []@@ -2151,7 +2153,12 @@ def project_image(links.new(mask_tex.outputs[0], to_float.inputs[0])return to_float- def _create_write_mask_weight(cam_index, mat_id_inner, binary=False):+ def _create_write_mask_weight(+ cam_index,+ mat_id_inner,+ binary=False,+ label_prefix="SequentialWrite",+ ):"""Sample the authoritative per-view sequential write mask."""mask_path = get_file_path(context,@@ -2173,7 +2180,7 @@ def project_image(mask_tex.image = mask_imagemask_tex.extension = 'CLIP'mask_tex.interpolation = 'Closest' if binary else 'Linear'- mask_tex.label = f"SequentialWriteMask-{cam_index}-{mat_id_inner}"+ mask_tex.label = f"{label_prefix}Mask-{cam_index}-{mat_id_inner}"mask_tex.location = (-500, -200 * cam_index - 300)uv_node = uv_map_nodes[cam_index]@@ -2184,7 +2191,7 @@ def project_image(to_float.operation = 'MULTIPLY'to_float.inputs[1].default_value = 1.0to_float.location = (-300, -200 * cam_index - 300)- to_float.label = f"SequentialWriteWeight-{cam_index}-{mat_id_inner}"+ to_float.label = f"{label_prefix}Weight-{cam_index}-{mat_id_inner}"links.new(mask_tex.outputs[0], to_float.inputs[0])return to_float@@ -2223,6 +2230,14 @@ def project_image(voronoi_active = (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')and getattr(context.scene, 'qwen_voronoi_mode', False)and context.scene.generation_method == 'sequential')+ confidence_context_active = (+ getattr(context.scene, 'qwen_use_confidence_context', False)+ and context.scene.model_architecture == 'qwen_image_edit'+ and context.scene.generation_method == 'sequential'+ and context.scene.qwen_generation_method == 'generate'+ and context.scene.qwen_context_render_mode+ in {'REPLACE_STYLE', 'ADDITIONAL'}+ )for i, camera in enumerate(cameras):# Add image texture node@@ -2623,6 +2638,7 @@ def project_image(and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}and getattr(context.scene, 'qwen_use_projection_write_masks', False))+ qwen_write_weight = Noneuse_sdxl_write_mask = (getattr(context.scene, 'sg_rework_sdxl_registration', False)and@@ -2637,6 +2653,8 @@ def project_image(write_weight = _create_write_mask_weight(i, mat_id, binary=use_qwen_write_mask)+ if use_qwen_write_mask:+ qwen_write_weight = write_weightif write_weight is not None:masked_weight = nodes.new("ShaderNodeMath")masked_weight.operation = 'MULTIPLY'@@ -2681,6 +2699,79 @@ def project_image(links.new(guard_floor.outputs[0], guarded.inputs[1])script_nodes_outputs[-1] = guarded+ # Confidence is deliberately independent from colour ownership.+ # Preserve the unnormalised source-camera quality before the mix+ # tree turns it into relative colour weights. Later Qwen cameras+ # may acquire confidence only inside the binary repair/write mask;+ # protected RGB copied through a full-frame edit cannot be+ # laundered into high-quality coverage.+ if (confidence_context_active and script_nodes_outputs+ and not isinstance(script_nodes_outputs[-1], tuple)):+ confidence_quality = script_nodes_outputs[-1]+ if i > stop_index:+ # Voronoi generation intentionally leaves future camera+ # placeholders active for colour segmentation. They are+ # not acquired observations and must never contribute to+ # source confidence.+ confidence_quality = nodes.new("ShaderNodeValue")+ confidence_quality.outputs[0].default_value = 0.0+ confidence_quality.label = f"ConfidenceFuture-{i}-{mat_id}"+ elif i > 0 and qwen_write_weight is None:+ confidence_write = _create_write_mask_weight(+ i,+ mat_id,+ binary=True,+ label_prefix="ConfidenceWrite",+ )+ if confidence_write is None:+ print(+ "[StableGen] WARNING: confidence write mask "+ f"missing for camera {i}; refusing to upgrade "+ "source confidence for that view."+ )+ confidence_quality = nodes.new("ShaderNodeValue")+ confidence_quality.outputs[0].default_value = 0.0+ confidence_quality.label = (+ f"ConfidenceWriteMissing-{i}-{mat_id}"+ )+ else:+ accepted_quality = nodes.new("ShaderNodeMath")+ accepted_quality.operation = 'MULTIPLY'+ accepted_quality.label = (+ f"ConfidenceAccepted-{i}-{mat_id}"+ )+ links.new(+ confidence_quality.outputs[0],+ accepted_quality.inputs[0],+ )+ links.new(+ confidence_write.outputs[0],+ accepted_quality.inputs[1],+ )+ confidence_quality = accepted_quality+ confidence_quality_nodes.append(confidence_quality)++ # Expose a confidence-only max chain for context rendering. This+ # node never selects or mixes RGB, so disabling texel ownership keeps+ # the continuous weighted material while still providing a genuine+ # best-source trust signal to Qwen.+ if confidence_context_active and confidence_quality_nodes:+ best_quality = nodes.new("ShaderNodeMath")+ best_quality.operation = 'MULTIPLY'+ best_quality.inputs[1].default_value = 1.0+ links.new(+ confidence_quality_nodes[0].outputs[0],+ best_quality.inputs[0],+ )+ for index, quality_node in enumerate(confidence_quality_nodes[1:], 1):+ next_best = nodes.new("ShaderNodeMath")+ next_best.operation = 'MAXIMUM'+ next_best.label = f"SGBestSourceQualityStep-{index}"+ links.new(best_quality.outputs[0], next_best.inputs[0])+ links.new(quality_node.outputs[0], next_best.inputs[1])+ best_quality = next_best+ best_quality.label = "SGBestSourceQuality"+# Build mix shader treeif mat.name in processed_materials and is_local_edit:# If we already processed this material, we don't need to rebuild the mix treediff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.pyindex ebb4090..9a18626 100644--- a/stablegen/texturing/rendering.py+++ b/stablegen/texturing/rendering.py@@ -7,6 +7,8 @@ import bpy, bmesh # pylint: disable=import-errorimport numpy as npimport mathutilsfrom ..utils import get_file_path, get_dir_path, get_compositor_node_tree, configure_output_node_paths, get_eevee_engine_id, sg_modal_active, remove_empty_dirs+from ..mesh_gen.rig_display import configure_gltf_not_exported_visibility+from .pose_lock import ensure_texturing_framefrom PIL import Imageimport cv2@@ -900,8 +902,7 @@ def _export_emit_image_impl(context, to_export, camera_id=None, bg_color=(0.5, 0:return: None"""print("[StableGen] Exporting emit render")- if not getattr(context.scene, 'sg_rework_consistent_frame', False):- context.scene.frame_set(1)+ ensure_texturing_frame(context.scene)# Store original materials and create temporary onesoriginal_materials = {}temporary_materials = {}@@ -1161,8 +1162,7 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)"""print("[StableGen] Exporting render using Workbench")- if not getattr(context.scene, 'sg_rework_consistent_frame', False):- context.scene.frame_set(1)+ ensure_texturing_frame(context.scene)# Setup output pathif output_dir is None:@@ -1521,21 +1521,26 @@ def _export_visibility_impl(context, to_export, obj=None, camera_visibility=Nonebpy.data.materials.remove(mat_copy)return False- # Confidence-owned sequential materials expose the original source- # quality explicitly. Build repair = visible surface & ~trusted from- # that socket instead of reverse-engineering RGB or summed blend- # weights. The copied material is used only by this render.- owner_quality = next(- (node for node in nodes if node.label == 'SGOwnerQuality'), None+ # Reworked sequential materials expose source acquisition quality+ # independently from RGB fusion. Prefer that max-quality signal; old+ # ownership graphs remain supported as a compatibility fallback.+ source_quality = next(+ (node for node in nodes if node.label == 'SGBestSourceQuality'),+ None,)- if owner_quality is not None:+ if source_quality is None:+ source_quality = next(+ (node for node in nodes if node.label == 'SGOwnerQuality'),+ None,+ )+ if source_quality is not None:trusted = nodes.new("ShaderNodeMath")trusted.operation = 'GREATER_THAN'trusted.inputs[1].default_value = float(getattr(context.scene, 'qwen_trust_threshold', 0.7)) - 1e-7trusted.label = "SGTrustedContext"- links.new(owner_quality.outputs[0], trusted.inputs[0])+ links.new(source_quality.outputs[0], trusted.inputs[0])repair = nodes.new("ShaderNodeMath")repair.operation = 'SUBTRACT'@@ -2085,49 +2090,17 @@ def _is_gltf_not_exported_helper(obj):return False-def _iter_collection_objects_recursive(collection):- seen = set()-- def visit(col):- for obj in col.objects:- if obj.name in seen:- continue- seen.add(obj.name)- yield obj- for child in col.children:- yield from visit(child)-- yield from visit(collection)---def _disable_not_exported_render_helpers(context=None):- """Prevent glTF helper/control geometry from occluding texture bakes."""- disabled_objects = 0- disabled_collections = 0-- for collection in bpy.data.collections:- if "not_exported" not in collection.name.lower():- continue-- if not collection.hide_render:- collection.hide_render = True- disabled_collections += 1-- for obj in _iter_collection_objects_recursive(collection):- if not obj.hide_render:- obj.hide_render = True- disabled_objects += 1-- if disabled_objects or disabled_collections:+def _configure_not_exported_helpers(context=None):+ """Keep glTF helpers out of bakes using visible collection controls."""+ stats = configure_gltf_not_exported_visibility(context or bpy.context)+ if stats["collections"]:print(- "[StableGen] Disabled render visibility for "- f"{disabled_objects} glTF not_exported helper object(s) "- f"across {disabled_collections} collection(s)."+ "[StableGen] Hid glTF not_exported helpers through "+ f"{stats['layer_collections']} view-layer eye toggle(s) and "+ f"{stats['collections']} collection render toggle(s); cleared "+ f"{stats['object_flags_cleared']} buried object flag(s).")- if context:- context.view_layer.update()-def _object_visible_in_view_layer(obj):if obj.hide_get():@@ -2283,7 +2256,7 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =:param obj: Blender object.:return: True if successful, False otherwise."""- _disable_not_exported_render_helpers(context)+ _configure_not_exported_helpers(context)if _is_gltf_not_exported_helper(obj) or _is_bone_custom_shape_object(obj):print(f"[StableGen] Skipping helper mesh during bake: {obj.name}")return False@@ -2577,7 +2550,7 @@ def bake_pbr_channel(context, obj, channel_name, texture_resolution, output_dir)if not obj.data.materials or not obj.active_material:return None- _disable_not_exported_render_helpers(context)+ _configure_not_exported_helpers(context)if _is_gltf_not_exported_helper(obj) or _is_bone_custom_shape_object(obj):print(f"[StableGen] Skipping helper mesh during PBR bake: {obj.name}")return None@@ -2585,131 +2558,128 @@ def bake_pbr_channel(context, obj, channel_name, texture_resolution, output_dir)# ── Save state ─────────────────────────────────────────────────orig_vt = context.scene.view_settings.view_transformorig_render = obj.hide_render+ original_material_state = _snapshot_material_state(obj)+ original_active_uv = (+ obj.data.uv_layers.active.name+ if obj.data.uv_layers.active else None+ )context.scene.view_settings.view_transform = 'Standard'obj.hide_render = Falsesource_uv_name = _first_source_uv_name(obj)_set_bake_uv_active(obj)# ── Copy material onto the object ──────────────────────────────- original_materials = list(obj.data.materials)- original_active = obj.active_material- mat_copy = original_active.copy()- obj.data.materials.clear()- obj.data.materials.append(mat_copy)- mat_copy.use_nodes = True- nodes = mat_copy.node_tree.nodes- links = mat_copy.node_tree.links-- # ── Find source socket in the copy ─────────────────────────────- sources = _find_pbr_bake_sources(mat_copy)- source_socket = sources.get(channel_name)- if source_socket is None:- _restore_materials(obj, original_materials, original_active)- bpy.data.materials.remove(mat_copy)- context.scene.view_settings.view_transform = orig_vt- obj.hide_render = orig_render- return None+ mat_copy = None+ try:+ mat_copy = obj.active_material.copy()+ obj.data.materials.clear()+ obj.data.materials.append(mat_copy)+ mat_copy.use_nodes = True+ nodes = mat_copy.node_tree.nodes+ links = mat_copy.node_tree.links- # ── Find Output node ───────────────────────────────────────────- output_node = None- for n in nodes:- if n.type == 'OUTPUT_MATERIAL':- output_node = n- break- if not output_node:- _restore_materials(obj, original_materials, original_active)- bpy.data.materials.remove(mat_copy)- context.scene.view_settings.view_transform = orig_vt- obj.hide_render = orig_render- return None+ # ── Find source socket in the copy ─────────────────────────+ sources = _find_pbr_bake_sources(mat_copy)+ source_socket = sources.get(channel_name)+ if source_socket is None:+ return None- # ── Rewire material for baking ───────────────────────────────- # Normal channel: use Cycles' built-in NORMAL bake which automatically- # converts to tangent space — game-engine / glTF compatible regardless- # of the original normal mode (world, bump, tangent).- # All other channels: rewire source → Emission → Output for EMIT bake.- bake_type = 'EMIT'- if channel_name == 'normal':- # Keep the Principled BSDF wired to the Output with the Normal- # input connected. Cycles NORMAL bake evaluates the shader's- # final shading normal and converts it to tangent space for us.- bake_type = 'NORMAL'- # Ensure the normal influence is at full strength for baking- principled = None- for n in nodes:- if n.type == 'BSDF_PRINCIPLED':- principled = n+ # ── Find Output node ───────────────────────────────────────+ output_node = None+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output_node = nodebreak- if principled and principled.inputs.get("Normal") and principled.inputs["Normal"].links:- nmap_node = principled.inputs["Normal"].links[0].from_node- if nmap_node.type == 'NORMAL_MAP':- nmap_node.inputs["Strength"].default_value = 1.0- else:- for link in list(output_node.inputs["Surface"].links):- links.remove(link)+ if not output_node:+ return None- emit_node = nodes.new("ShaderNodeEmission")- emit_node.location = (output_node.location[0] - 200,- output_node.location[1])- links.new(source_socket, emit_node.inputs["Color"])- links.new(emit_node.outputs["Emission"],- output_node.inputs["Surface"])-- # ── Bake target image ──────────────────────────────────────────- suffix = _PBR_CHANNEL_SUFFIXES.get(channel_name, channel_name)- img_name = f"{obj.name}_{suffix}"- bake_img = bpy.data.images.new(name=img_name,- width=texture_resolution,- height=texture_resolution)-- # Non-color channels (roughness, metallic, normal, height, AO) must be- # stored in linear / Non-Color so the round-trip is lossless:- # Cycles linear → raw 8-bit → PNG → load as Non-Color → linear.- # Without this, the default sRGB image applies gamma encoding on write,- # but add_baked_material() loads them as Non-Color (no decode) →- # values are gamma-shifted (e.g. roughness 0.22 → 0.50).- if channel_name not in ('base_color', 'emission'):- bake_img.colorspace_settings.name = 'Non-Color'+ # ── Rewire material for baking ─────────────────────────────+ # Normal channel uses Cycles' tangent-space NORMAL bake. All other+ # channels route their source through Emission for an exact value bake.+ bake_type = 'EMIT'+ if channel_name == 'normal':+ bake_type = 'NORMAL'+ principled = next(+ (node for node in nodes if node.type == 'BSDF_PRINCIPLED'),+ None,+ )+ if (principled and principled.inputs.get("Normal")+ and principled.inputs["Normal"].links):+ nmap_node = principled.inputs["Normal"].links[0].from_node+ if nmap_node.type == 'NORMAL_MAP':+ nmap_node.inputs["Strength"].default_value = 1.0+ else:+ for link in list(output_node.inputs["Surface"].links):+ links.remove(link)- tex_node = nodes.new("ShaderNodeTexImage")- tex_node.image = bake_img- nodes.active = tex_node+ emit_node = nodes.new("ShaderNodeEmission")+ emit_node.location = (+ output_node.location[0] - 200,+ output_node.location[1],+ )+ links.new(source_socket, emit_node.inputs["Color"])+ links.new(+ emit_node.outputs["Emission"],+ output_node.inputs["Surface"],+ )- # ── Select object + non-projection UV ──────────────────────────- op_context = _activate_mesh_for_object_ops(obj)- _pin_unlinked_image_textures_to_uv(- nodes, links, source_uv_name, exclude_nodes={tex_node})- _set_bake_uv_active(obj)+ # ── Bake target image ──────────────────────────────────────+ suffix = _PBR_CHANNEL_SUFFIXES.get(channel_name, channel_name)+ img_name = f"{obj.name}_{suffix}"+ bake_img = bpy.data.images.new(+ name=img_name,+ width=texture_resolution,+ height=texture_resolution,+ )+ if channel_name not in ('base_color', 'emission'):+ bake_img.colorspace_settings.name = 'Non-Color'- # ── Bake ─────────────────────────────────────────────────────- # Ensure OBJECT mode — bake fails silently in EDIT mode- with bpy.context.temp_override(**op_context):- if bpy.context.mode != 'OBJECT':- bpy.ops.object.mode_set(mode='OBJECT')- if bake_type == 'NORMAL':- bpy.ops.object.bake(type='NORMAL',- normal_space='TANGENT',- width=texture_resolution,- height=texture_resolution)- else:- bpy.ops.object.bake(type='EMIT',- width=texture_resolution,- height=texture_resolution)+ tex_node = nodes.new("ShaderNodeTexImage")+ tex_node.image = bake_img+ nodes.active = tex_node- # ── Save ───────────────────────────────────────────────────────- os.makedirs(output_dir, exist_ok=True)- out_path = os.path.join(output_dir, f"{obj.name}_{suffix}.png")- bake_img.filepath_raw = out_path- bake_img.file_format = 'PNG'- bake_img.save()- print(f"[StableGen] Saved PBR channel: {out_path}")+ # ── Select object + non-projection UV ──────────────────────+ op_context = _activate_mesh_for_object_ops(obj)+ _pin_unlinked_image_textures_to_uv(+ nodes, links, source_uv_name, exclude_nodes={tex_node})+ _set_bake_uv_active(obj)- # ── Cleanup ────────────────────────────────────────────────────- _restore_materials(obj, original_materials, original_active)- bpy.data.materials.remove(mat_copy)- context.scene.view_settings.view_transform = orig_vt- obj.hide_render = orig_render- return out_path+ # ── Bake ───────────────────────────────────────────────────+ with bpy.context.temp_override(**op_context):+ if bpy.context.mode != 'OBJECT':+ bpy.ops.object.mode_set(mode='OBJECT')+ if bake_type == 'NORMAL':+ bpy.ops.object.bake(+ type='NORMAL',+ normal_space='TANGENT',+ width=texture_resolution,+ height=texture_resolution,+ )+ else:+ bpy.ops.object.bake(+ type='EMIT',+ width=texture_resolution,+ height=texture_resolution,+ )++ # ── Save ───────────────────────────────────────────────────+ os.makedirs(output_dir, exist_ok=True)+ out_path = os.path.join(output_dir, f"{obj.name}_{suffix}.png")+ bake_img.filepath_raw = out_path+ bake_img.file_format = 'PNG'+ bake_img.save()+ print(f"[StableGen] Saved PBR channel: {out_path}")+ return out_path+ finally:+ # This must run for missing channels, missing outputs, failed Cycles+ # bakes, failed image saves, and successful bakes alike.+ _restore_material_state(obj, original_material_state)+ if mat_copy and mat_copy.name in bpy.data.materials:+ bpy.data.materials.remove(mat_copy)+ if original_active_uv and obj.data.uv_layers.get(original_active_uv):+ obj.data.uv_layers.active = obj.data.uv_layers[original_active_uv]+ context.scene.view_settings.view_transform = orig_vt+ obj.hide_render = orig_renderdef _flip_normal_green(filepath):@@ -2942,7 +2912,7 @@ class BakeTextures(bpy.types.Operator)::return: {'RUNNING_MODAL'}"""- _disable_not_exported_render_helpers(context)+ _configure_not_exported_helpers(context)self._objects, skipped = _texture_bake_targets(self._objects)if skipped:names = ", ".join(obj.name for obj in skipped[:5])diff --git a/stablegen/texturing/solidify.py b/stablegen/texturing/solidify.pynew file mode 100644index 0000000..178b561--- /dev/null+++ b/stablegen/texturing/solidify.py@@ -0,0 +1,274 @@+"""General-purpose StableGen mesh solidification.++Unlike the 3D-print debug/export path, this operates on base mesh data and+preserves the rig and live projection-material inputs.+"""++import bpy # pylint: disable=import-error++from ..utils import sg_modal_active+from .print_export import _make_solid_mesh_object+++def _weighted_membership_count(obj):+ return sum(len(vertex.groups) for vertex in obj.data.vertices)+++def _projection_attribute_names(mesh):+ return {+ attribute.name+ for attribute in mesh.attributes+ if (+ attribute.name.startswith("ProjectionUV_")+ or attribute.name.startswith("_SG_")+ )+ }+++def _mesh_topology_counts(mesh):+ """Return boundary/non-manifold edge counts without changing mesh state."""+ face_counts = {+ tuple(sorted(edge.vertices[:])): 0+ for edge in mesh.edges+ }+ for polygon in mesh.polygons:+ for edge_key in polygon.edge_keys:+ key = tuple(sorted(edge_key))+ face_counts[key] = face_counts.get(key, 0) + 1+ counts = tuple(face_counts.values())+ return {+ "boundary": sum(count == 1 for count in counts),+ "non_manifold": sum(count > 2 for count in counts),+ "loose": sum(count == 0 for count in counts),+ }+++def _restore_mesh_metadata(source, target):+ """Restore datablock metadata BMesh does not carry itself."""+ for material in source.materials:+ target.materials.append(material)++ active_uv = source.uv_layers.active.name if source.uv_layers.active else None+ render_uv = next(+ (+ layer.name for layer in source.uv_layers+ if getattr(layer, "active_render", False)+ ),+ None,+ )+ if active_uv and target.uv_layers.get(active_uv):+ target.uv_layers.active = target.uv_layers[active_uv]+ if render_uv and target.uv_layers.get(render_uv):+ target.uv_layers[render_uv].active_render = True+++def _restore_vertex_group_names(obj, names):+ """Reconnect preserved deform indices to their original bone names."""+ existing = [group.name for group in obj.vertex_groups]+ if existing == names:+ return+ if existing:+ raise RuntimeError(+ "replacement mesh exposed an unexpected vertex-group table "+ f"{existing!r}"+ )+ for name in names:+ obj.vertex_groups.new(name=name)+++def _validate_solid_result(+ obj, source, target, weighted_before, *, fill_gaps):+ """Reject a replacement that would damage rig or projection state."""+ if len(target.vertices) == 0 or len(target.polygons) == 0:+ raise RuntimeError("solidification produced an empty mesh")++ source_uvs = {layer.name for layer in source.uv_layers}+ target_uvs = {layer.name for layer in target.uv_layers}+ missing_uvs = sorted(source_uvs - target_uvs)+ if missing_uvs:+ raise RuntimeError(+ "solidification lost UV layer(s): " + ", ".join(missing_uvs)+ )++ missing_projection = sorted(+ _projection_attribute_names(source)+ - _projection_attribute_names(target)+ )+ if missing_projection:+ raise RuntimeError(+ "solidification lost projection attribute(s): "+ + ", ".join(missing_projection)+ )++ source_materials = list(source.materials)+ target_materials = list(target.materials)+ if source_materials != target_materials:+ raise RuntimeError("solidification changed the material slot layout")+ if any(+ polygon.material_index >= len(target_materials)+ for polygon in target.polygons+ ):+ raise RuntimeError("solidification produced an invalid face material")++ cap_attribute = target.attributes.get("_SG_SolidCap")+ if fill_gaps and cap_attribute is None:+ raise RuntimeError("solidification did not mark its generated caps")+ if cap_attribute is not None:+ if cap_attribute.domain != 'FACE':+ raise RuntimeError("_SG_SolidCap has the wrong attribute domain")+ cap_faces = [+ polygon+ for polygon, value in zip(target.polygons, cap_attribute.data)+ if bool(value.value)+ ]+ if any(polygon.area <= 1.0e-12 for polygon in cap_faces):+ raise RuntimeError("solidification produced a degenerate cap face")++ source_topology = _mesh_topology_counts(source)+ target_topology = _mesh_topology_counts(target)+ if (+ target_topology["non_manifold"]+ > source_topology["non_manifold"]+ ):+ raise RuntimeError(+ "solidification increased non-manifold edges "+ f"({source_topology['non_manifold']} -> "+ f"{target_topology['non_manifold']})"+ )+ if (+ fill_gaps+ and target_topology["boundary"] > source_topology["boundary"]+ ):+ raise RuntimeError(+ "solidification increased open boundary edges "+ f"({source_topology['boundary']} -> "+ f"{target_topology['boundary']})"+ )++ weighted_after = _weighted_membership_count(obj)+ if weighted_before and not weighted_after:+ raise RuntimeError("solidification removed all skinning weights")+++class StableGenMakeSolid(bpy.types.Operator):+ """Remove hidden interior surfaces and close resulting mesh boundaries."""++ bl_idname = "object.stablegen_make_solid"+ bl_label = "Make Solid"+ bl_description = (+ "Make the active mesh solid while preserving its rig, skinning "+ "weights, UV/projection data, and live StableGen materials"+ )+ bl_options = {'REGISTER', 'UNDO'}++ fill_gaps: bpy.props.BoolProperty(+ name="Fill Gaps",+ description="Close boundary loops left after hidden geometry removal",+ default=True,+ )+ keep_largest_island: bpy.props.BoolProperty(+ name="Keep Largest Island",+ description=(+ "Discard smaller disconnected components before closing gaps; "+ "disable this for characters with intentional detached parts"+ ),+ default=False,+ )+ raycast_count: bpy.props.IntProperty(+ name="Raycast Directions",+ description=(+ "Number of radial directions used to distinguish exterior from "+ "interior surfaces"+ ),+ default=12,+ min=4,+ max=64,+ )++ @classmethod+ def poll(cls, context):+ if sg_modal_active(context):+ cls.poll_message_set("Wait for the current StableGen operation to finish")+ return False+ obj = context.active_object+ if not obj or obj.type != 'MESH':+ cls.poll_message_set("Select an active mesh object")+ return False+ return True++ def invoke(self, context, event):+ return context.window_manager.invoke_props_dialog(self)++ def execute(self, context):+ obj = context.active_object+ if obj.mode != 'OBJECT':+ bpy.ops.object.mode_set(mode='OBJECT')++ source = obj.data+ if source.shape_keys and len(source.shape_keys.key_blocks) > 1:+ self.report(+ {'ERROR'},+ "Make Solid cannot safely preserve shape keys because it "+ "changes topology. Remove or apply them first.",+ )+ return {'CANCELLED'}++ materials_before = list(source.materials)+ active_material_index = obj.active_material_index+ vertex_groups_before = [group.name for group in obj.vertex_groups]+ weighted_before = _weighted_membership_count(obj)+ modifiers_before = list(obj.modifiers)++ solid = None+ try:+ solid = _make_solid_mesh_object(+ obj,+ fill_gaps=self.fill_gaps,+ keep_largest_island=self.keep_largest_island,+ use_evaluated_mesh=False,+ raycast_count=self.raycast_count,+ weld_distance=0.0,+ robust_fill=True,+ smooth_caps=True,+ )+ _restore_mesh_metadata(source, solid)+ obj.data = solid+ _restore_vertex_group_names(obj, vertex_groups_before)+ obj.active_material_index = min(+ active_material_index,+ max(0, len(materials_before) - 1),+ )+ _validate_solid_result(+ obj,+ source,+ solid,+ weighted_before,+ fill_gaps=self.fill_gaps,+ )++ vertex_groups_after = [+ group.name for group in obj.vertex_groups+ ]+ if vertex_groups_after != vertex_groups_before:+ raise RuntimeError(+ "solidification changed the vertex groups "+ f"({vertex_groups_before!r} -> {vertex_groups_after!r})"+ )+ if list(obj.modifiers) != modifiers_before:+ raise RuntimeError("solidification changed the modifier stack")++ if source.users == 0:+ bpy.data.meshes.remove(source)+ obj.data.update()+ self.report(+ {'INFO'},+ f"Made {obj.name} solid while preserving rig and materials",+ )+ return {'FINISHED'}+ except Exception as error:+ if obj.data == solid:+ obj.data = source+ if solid and solid.name in bpy.data.meshes and solid.users == 0:+ bpy.data.meshes.remove(solid)+ self.report({'ERROR'}, f"Make Solid failed safely: {error}")+ return {'CANCELLED'}diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.pyindex 4c8909d..2035305 100644--- a/stablegen/texturing/workflows.py+++ b/stablegen/texturing/workflows.py@@ -10,7 +10,13 @@ from datetime import datetimefrom ..util.workflow_templates import prompt_text_qwen_image_edit, prompt_text_flux2_kleinfrom ..utils import get_generation_dirsfrom ..timeout_config import get_timeout-from .graph_validation import validate_workflow_graph, qwen_style_semantic_slot, sdxl_final_mask_reference+from .graph_validation import (+ validate_workflow_graph,+ qwen_style_semantic_slot,+ qwen_reference_latent_slots,+ attach_qwen_latent_lock,+ sdxl_final_mask_reference,+)from io import BytesIOimport numpy as np@@ -186,7 +192,13 @@ class _TexturingWorkflowMixin:img_out.save(out_buf, format="PNG")return out_buf.getvalue()- def _build_qwen_reference_latent_chain(self, prompt, NODES, start_node_id=700):+ def _build_qwen_reference_latent_chain(+ self,+ prompt,+ NODES,+ start_node_id=700,+ latent_slots=("image1", "image2", "image3"),+ ):"""Build VAEEncode + ReferenceLatent chain for the Qwen unzoom fix.@@ -195,11 +207,13 @@ class _TexturingWorkflowMixin:a 1 MP rescale). We replicate the reference-latent injectionmanually so the latents match the actual output resolution.- For each active image (image1 / image2 / image3) still present in- the positive text-encode node, a VAEEncode node is created and a- ReferenceLatent node is chained onto both positive and negative- conditioning. The KSampler inputs are then updated to point at- the tail of the chain.+ For each selected, active image still present in the positive+ text-encode node, a VAEEncode node is created and a ReferenceLatent+ node is chained onto both positive and negative conditioning. The+ KSampler inputs are then updated to point at the tail of the chain.+ A slot omitted from ``latent_slots`` remains available to the Qwen+ visual-language encoder but exerts no full-resolution reference-latent+ pressure.When ``qwen_timestep_zero_ref`` is enabled on the scene, aFluxKontextMultiReferenceLatentMethod node is appended with@@ -216,8 +230,8 @@ class _TexturingWorkflowMixin:active_refs = []pos_inputs = prompt[pos_node]['inputs']for key in ('image1', 'image2', 'image3'):- if key in pos_inputs:- active_refs.append(pos_inputs[key])+ if key in pos_inputs and key in latent_slots:+ active_refs.append((key, pos_inputs[key]))if not active_refs:return@@ -230,7 +244,7 @@ class _TexturingWorkflowMixin:pos_cond_ref = [pos_node, 0]neg_cond_ref = [neg_node, 0]- for i, img_ref in enumerate(active_refs):+ for i, (slot, img_ref) in enumerate(active_refs):# --- VAEEncode for this image ---# For image1 we can reuse the existing node 8 which already# encodes the same image (also used as KSampler latent_image).@@ -245,7 +259,7 @@ class _TexturingWorkflowMixin:"vae": vae_ref},"class_type": "VAEEncode",- "_meta": {"title": f"VAE Encode (Ref {i + 1})"}+ "_meta": {"title": f"VAE Encode ({slot})"}}vae_enc_ref = [vae_enc_id, 0]@@ -258,7 +272,7 @@ class _TexturingWorkflowMixin:"latent": vae_enc_ref},"class_type": "ReferenceLatent",- "_meta": {"title": f"Reference Latent Pos {i + 1}"}+ "_meta": {"title": f"Reference Latent Pos ({slot})"}}pos_cond_ref = [ref_pos_id, 0]@@ -271,7 +285,7 @@ class _TexturingWorkflowMixin:"latent": vae_enc_ref},"class_type": "ReferenceLatent",- "_meta": {"title": f"Reference Latent Neg {i + 1}"}+ "_meta": {"title": f"Reference Latent Neg ({slot})"}}neg_cond_ref = [ref_neg_id, 0]@@ -607,7 +621,9 @@ class _TexturingWorkflowMixin:return {"error": "invalid_workflow"}# --- Save and Execute ---- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(+ prompt, revision_dir, workflow="qwen_refine", camera_id=camera_id+ )ws = self._connect_to_websocket(server_address, client_id)if ws is None:@@ -635,6 +651,7 @@ class _TexturingWorkflowMixin:NODES = {'sampler': "1",+ 'vae_loader': "4",'save_image': "5",'model_sampler': "6", # ModelSamplingAuraFlow'cfg_norm': "7", # CFGNorm@@ -864,7 +881,72 @@ class _TexturingWorkflowMixin:prompt[NODES['neg_prompt']]['inputs'][style_slot] = [scale_node_key, 0]# --- Reference Latent chain (Qwen unzoom fix) ---- self._build_qwen_reference_latent_chain(prompt, NODES)+ latent_slots = qwen_reference_latent_slots(+ context_mode,+ is_initial_image,+ getattr(context.scene, 'qwen_global_style_vlm_only', False),+ )+ if 'image3' not in latent_slots and 'image3' in prompt[NODES['pos_prompt']]['inputs']:+ print(+ "[StableGen] Qwen Image 3 global style is VLM-only; "+ "skipping its ReferenceLatent"+ )+ self._build_qwen_reference_latent_chain(+ prompt,+ NODES,+ latent_slots=latent_slots,+ )++ # --- Sampler-level latent-locked context inpainting ---+ # Unlike the RGB/magenta conditioning alone, this makes the exported+ # visibility repair mask authoritative inside the sampler. It is+ # available only for later sequential views that actually have a+ # context render; the initial view keeps the legacy depth-start latent.+ latent_lock_enabled = bool(getattr(+ context.scene, 'qwen_latent_locked_context', False+ ))+ latent_lock_active = (+ latent_lock_enabled+ and not is_initial_image+ and context_mode in {'REPLACE_STYLE', 'ADDITIONAL'}+ and context_render_info is not None+ )+ if latent_lock_active:+ repair_mask_info = self.operator._get_uploaded_image_info(+ context,+ "inpaint",+ subtype="visibility",+ camera_id=camera_id,+ )+ if not repair_mask_info:+ self.operator._error = (+ "Qwen latent-locked context is enabled, but the sequential "+ f"repair mask for camera {camera_id} is missing."+ )+ return {"error": "conn_failed"}+ attach_qwen_latent_lock(+ prompt,+ sampler_node_id=NODES['sampler'],+ vae_node_id=NODES['vae_loader'],+ context_image_name=context_render_info['name'],+ repair_mask_name=repair_mask_info['name'],+ )+ print(+ "[StableGen] Qwen latent-locked context active for camera "+ f"{camera_id}: trusted pixels are sampler-locked; repair "+ "pixels denoise."+ )+ elif latent_lock_enabled and is_initial_image:+ print(+ "[StableGen] Qwen latent-locked context enabled; initial view "+ "has no prior context and uses the normal sampler latent."+ )+ elif latent_lock_enabled:+ print(+ "[StableGen] Qwen latent-locked context enabled but inactive: "+ "use a later sequential view with Replace Style or Additional "+ "context."+ )# --- Configure Sampler ---prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed@@ -899,7 +981,9 @@ class _TexturingWorkflowMixin:return {"error": "invalid_workflow"}# --- Execute ---- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(+ prompt, revision_dir, workflow="qwen_edit", camera_id=camera_id+ )ws = self._connect_to_websocket(server_address, client_id)if ws is None:return {"error": "conn_failed"}@@ -1135,7 +1219,9 @@ class _TexturingWorkflowMixin:self._build_flux2_reference_chain(prompt, NODES, ref_images)# --- Execute ---- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(+ prompt, revision_dir, workflow="flux2_klein", camera_id=camera_id+ )ws = self._connect_to_websocket(server_address, client_id)if ws is None:return {"error": "conn_failed"}@@ -1189,7 +1275,7 @@ class _TexturingWorkflowMixin:prompt = self._build_controlnet_chain(prompt, context, controlnet_info, NODES)# Save prompt for debugging (in revision dir)- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(prompt, revision_dir, workflow="sdxl_generate")# Execute generation and get resultsws = self._connect_to_websocket(server_address, client_id)@@ -2308,8 +2394,7 @@ class _TexturingWorkflowMixin:prompt[NODES['sampler']]["inputs"]["negative"] = [NODES['neg_prompt'], 0]# Save prompt for debugging- with open(os.path.join(output_dir, "prompt.json"), 'w') as f:- json.dump(prompt, f)+ self._save_prompt_to_file(prompt, output_dir, workflow="sdxl_refine")# Execute generation and get resultsws = self._connect_to_websocket(server_address, client_id)@@ -2754,7 +2839,7 @@ class _TexturingWorkflowMixin:# Note: No negative prompt is connected.# Save prompt for debugging.- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(prompt, revision_dir, workflow="flux_generate")# Execute generation via websocket.# Execute generation and get results@@ -2953,7 +3038,7 @@ class _TexturingWorkflowMixin:prompt[NODES['flux_lora_image']]["inputs"]["image"] = controlnet_info["depth"]['name']# Save prompt for debugging- self._save_prompt_to_file(prompt, revision_dir)+ self._save_prompt_to_file(prompt, revision_dir, workflow="flux_refine")# Execute generation and get resultsws = self._connect_to_websocket(server_address, client_id)diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.pyindex cd643d2..1f0fa07 100644--- a/stablegen/ui/panel.py+++ b/stablegen/ui/panel.py@@ -975,6 +975,35 @@ class StableGenPanel(bpy.types.Panel):text="Proxy",icon="MOD_WIREFRAME")+ row = content_box.row(align=True)+ row.prop(+ scene,+ "trellis2_autorig_bone_heuristic",+ text="Bone Direction",+ )++ row = content_box.row(align=True)+ row.prop(+ scene,+ "trellis2_autorig_bone_display_type",+ text="Bone Display",+ )+ row.operator(+ "stablegen.apply_autorig_bone_display",+ text="Apply",+ icon="CHECKMARK",+ )+ if (+ scene.trellis2_autorig_bone_heuristic == 'BLENDER'+ and scene.trellis2_autorig_bone_display_type != 'IMPORTED'+ ):+ warning = content_box.row()+ warning.alert = True+ warning.label(+ text="Legacy axes: use Imported display for original joint markers",+ icon="INFO",+ )+row = content_box.row(align=True)row.operator_context = "INVOKE_DEFAULT"op = row.operator("stablegen.apply_rig_pose_preset",@@ -1376,6 +1405,31 @@ class StableGenPanel(bpy.types.Panel):experiments.prop(scene, "sg_rework_safe_render_state", text="Transactional Render State", toggle=True)experiments.prop(scene, "sg_rework_workflow_validation", text="Workflow Graph Validation", toggle=True)experiments.prop(scene, "sg_rework_qwen_workflow", text="Corrected Qwen Workflow Routing", toggle=True)+ row = experiments.row()+ row.enabled = bool(+ scene.model_architecture.startswith('qwen')+ and scene.qwen_generation_method == 'generate'+ and scene.qwen_context_render_mode == 'ADDITIONAL'+ )+ row.prop(+ scene,+ "qwen_global_style_vlm_only",+ text="Global Style Reference: VLM Only (Qwen Additional)",+ toggle=True,+ )+ row = experiments.row()+ row.enabled = bool(+ scene.model_architecture.startswith('qwen')+ and scene.qwen_generation_method == 'generate'+ and scene.generation_method == 'sequential'+ and scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}+ )+ row.prop(+ scene,+ "qwen_latent_locked_context",+ text="Latent-Locked Context Inpainting (Qwen Sequential)",+ toggle=True,+ )experiments.prop(scene, "sg_rework_final_display", text="Continuous Final Display Rebuild", toggle=True)# --- Output & Material Settings ---@@ -2216,6 +2270,9 @@ 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_make_solid", text="Make Solid", icon="MOD_REMESH")+ if width_mode == 'narrow':+ row = tools_box.row()row.operator_context = "INVOKE_DEFAULT"row.operator("object.stablegen_autorig_selected_mesh", text="Auto-Rig Selected Character", icon="ARMATURE_DATA")@@ -2260,9 +2317,37 @@ class StableGenPanel(bpy.types.Panel):row = debug_box.row()row.operator("stablegen.debug_ownership_diagnostic", text="Ownership Diagnostics", icon="SHADING_RENDERED")+ row = debug_box.row()+ row.operator(+ "stablegen.debug_skinning_weights",+ text="Skinning Weight Colors",+ icon="GROUP_VERTEX",+ )+ if width_mode == 'narrow':+ row = debug_box.row()+ row.operator(+ "stablegen.debug_clear_skinning_weights",+ text="Clear Skin Colors",+ icon="X",+ )++ row = debug_box.row()+ row.operator(+ "stablegen.debug_convert_fortune_rig",+ text="Convert Existing Rig to Fortune",+ icon="ARMATURE_DATA",+ )+row = debug_box.row()row.operator("stablegen.debug_make_solid", text="Debug Make Solid", icon="MOD_REMESH")+ row = debug_box.row()+ row.operator(+ "stablegen.debug_force_generation_idle",+ text="Force Generation Idle",+ icon="CANCEL",+ )+# --- Narrow panel hint ---if width_mode == 'narrow':hint_row = layout.row()diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.pyindex 05a22c9..8dd79ac 100644--- a/stablegen/ui/presets.py+++ b/stablegen/ui/presets.py@@ -39,6 +39,18 @@ PRESETS = {"QWEN VORONOI (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Voronoi projection with exponent 1000 for hard camera segmentation during generation, then resets to 15 for softer blending.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 1000.0, "weight_exponent_generation_only": True, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": True, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},}+# Diagnostic base-model preset: keep QWEN PRECISE's camera/context/projection+# behavior, but remove the 4-step Lightning LoRA and run the 2509 base model+# with the reference 40-step / CFG 4 sampling settings. It deliberately does+# not enable any texturing experiments; those remain independently testable.+PRESETS["QWEN 2509 FULL STEPS (EXPERIMENTAL)"] = {+ **PRESETS["QWEN PRECISE"],+ "description": "Experimental Qwen 2509 base-model comparison. Matches QWEN PRECISE except it removes the Lightning LoRA and uses 40 steps at CFG 4. Requires a regular Qwen-Image-Edit-2509 base model, not a Nunchaku checkpoint with Lightning baked in.",+ "steps": 40,+ "cfg": 4.0,+ "lora_units": [],+}+# Built-in presets intentionally start from the pre-rework behavior. Users can# enable experiments after applying a preset; custom presets persist explicit# feature choices through GEN_PARAMETERS below.@@ -115,6 +127,8 @@ GEN_PARAMETERS = ["sg_rework_consistent_frame","sg_rework_workflow_validation","sg_rework_qwen_workflow",+ "qwen_global_style_vlm_only",+ "qwen_latent_locked_context","sg_rework_final_display","differential_diffusion","differential_noise",@@ -212,6 +226,8 @@ GEN_PARAMETERS = ["trellis2_autorig_use_postprocess","trellis2_autorig_cleanup_cross_limb_weights","trellis2_autorig_garment_mode",+ "trellis2_autorig_bone_display_type",+ "trellis2_autorig_bone_heuristic","trellis2_autorig_top_k","trellis2_autorig_top_p","trellis2_autorig_temperature",diff --git a/stablegen/workflows.py b/stablegen/workflows.pyindex 5cc4ec8..d2d3f9e 100644--- a/stablegen/workflows.py+++ b/stablegen/workflows.py@@ -10,6 +10,7 @@ import email.utilsfrom datetime import datetime, timezone, timedeltafrom .timeout_config import get_timeout+from .prompt_archive import archive_promptfrom io import BytesIOimport numpy as np@@ -172,11 +173,35 @@ class _WorkflowBase:return False- def _save_prompt_to_file(self, prompt, output_dir):- """Saves the prompt to a file for debugging."""+ def _save_prompt_to_file(+ self,+ prompt,+ output_dir,+ *,+ workflow="workflow",+ camera_id=None,+ ):+ """Save the latest graph and a non-overwriting per-view debug copy."""try:- with open(os.path.join(output_dir, "prompt.json"), 'w') as f:- json.dump(prompt, f, indent=2) # Added indent for better readability+ operator = getattr(self, "operator", None)+ view_index = getattr(operator, "_current_image", None)+ camera_name = None++ cameras = getattr(operator, "_cameras", ()) or ()+ camera_lookup_index = camera_id+ if camera_lookup_index is None:+ camera_lookup_index = view_index+ if isinstance(camera_lookup_index, int) and 0 <= camera_lookup_index < len(cameras):+ camera_name = getattr(cameras[camera_lookup_index], "name", None)++ _, archive_path = archive_prompt(+ prompt,+ output_dir,+ workflow=workflow,+ view_index=view_index if isinstance(view_index, int) else None,+ camera_name=camera_name,+ )+ print(f"[StableGen] Saved workflow archive: {archive_path}")except Exception as e:print(f"[StableGen] Failed to save prompt to file: {str(e)}")