Skip to content

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

checkpoint experimental texturing pipeline rework

sakalonde6b1b0c57393
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index 6079376..453ee40 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -10,7 +10,7 @@ import bpy # pylint: disable=import-error
# -- UI / Operator classes ------------------------------------------------
from .ui.presets import (
ApplyPreset, SavePreset, DeletePreset,
- ResetQwenPrompt, SwitchToMeshGeneration,
+ ResetQwenPrompt, ResetTexturingExperiments, SwitchToMeshGeneration,
)
from .ui.panel import StableGenPanel, StableGenPrintPanel
from .ui.queue import (
@@ -170,6 +170,7 @@ classes = [
SavePreset,
DeletePreset,
ResetQwenPrompt,
+ ResetTexturingExperiments,
SwitchToMeshGeneration,
# Queue operators
SG_UL_SceneQueueList,
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 9a66e56..7b1b807 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -19,6 +19,7 @@ from .callbacks import (
update_print_dithered,
)
from . import ADDON_PKG
+from ..feature_flags import TEXTURING_REWORK_DEFAULTS
# ── Helper(s) used by properties ───────────────────────────────────────────
@@ -785,12 +786,92 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
bpy.types.Scene.sg_allow_backface_projection = bpy.props.BoolProperty(
name="Allow Backface Projection",
description="Use legacy two-sided projection weights. Leave disabled for characters and closed meshes so a camera cannot write through back-facing surfaces",
- default=False, update=update_parameters,
+ default=TEXTURING_REWORK_DEFAULTS["sg_allow_backface_projection"], update=update_parameters,
+ )
+
+ # Texturing pipeline rework feature gates. These deliberately default to
+ # False so a newly opened scene follows the rigging-branch projection and
+ # sequential-context behavior. Each gate controls one independently
+ # testable behavior instead of enabling the rework as an inseparable set.
+ bpy.types.Scene.sg_rework_camera_plan = bpy.props.BoolProperty(
+ name="Canonical Camera Plan",
+ description="Snapshot camera order, transforms, intrinsics, prompts, and per-camera resolutions for the whole run",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_camera_plan"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_aligned_resolution = bpy.props.BoolProperty(
+ name="Improved Aligned Resolution",
+ description="Use the new joint aspect/megapixel/alignment resolution search instead of legacy proportional rounding",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_aligned_resolution"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_full_resolution_scale = bpy.props.BoolProperty(
+ name="Force 100% Guide Resolution",
+ description="Temporarily force Blender resolution percentage to 100 so guides and Qwen inputs match the configured pixel dimensions",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_full_resolution_scale"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_safe_render_state = bpy.props.BoolProperty(
+ name="Transactional Render State",
+ description="Snapshot and restore render, compositor, material-slot, and scene state around pipeline renders",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_safe_render_state"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_reset_controls = bpy.props.BoolProperty(
+ name="Corrected Angle/Exponent Reset",
+ description="Reset normalized projection weights and baked visibility consistently on completion, cancellation, and errors",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_reset_controls"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_sdxl_registration = bpy.props.BoolProperty(
+ name="Corrected SDXL Mask Registration",
+ description="Use the corrected uncropped SDXL sequential mask and projection-alpha registration path",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_sdxl_registration"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_acquisition_quality = bpy.props.BoolProperty(
+ name="Acquisition Quality Weighting",
+ description="Weight views using projected density and source-camera acquisition quality in addition to legacy visibility/frontality",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_acquisition_quality"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_initial_view_priority = bpy.props.BoolProperty(
+ name="Confidence-Aware Initial View Priority",
+ description="Use early-view priority only as trusted-owner replacement resistance instead of the legacy recursive blend bias",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_initial_view_priority"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_projection_guard = bpy.props.BoolProperty(
+ name="Depth/Part Projection Guard",
+ description="Reject projection near depth, object-ID, and material-ID discontinuities to reduce foreground silhouettes on rear surfaces",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_projection_guard"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_projection_rebuild = bpy.props.BoolProperty(
+ name="Rebuild Sequential Projection Graph",
+ description="Rebuild the complete projection material after each generated view instead of using the legacy patch-in-place update",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_projection_rebuild"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_projection_geometry = bpy.props.BoolProperty(
+ name="Projection Geometry Corrections",
+ description="Use signed facing, parented camera transforms, camera shift, orthographic support, evaluated meshes, and scale-aware ray tolerances",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_projection_geometry"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_consistent_frame = bpy.props.BoolProperty(
+ name="Consistent Texturing Frame",
+ description="Evaluate guides, visibility, projection, and baking at the explicit Texturing Frame",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_consistent_frame"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_workflow_validation = bpy.props.BoolProperty(
+ name="Workflow Graph Validation",
+ description="Validate generated Qwen/SDXL workflow graphs and semantic image slots before submission",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_workflow_validation"], update=update_parameters,
+ )
+ bpy.types.Scene.sg_rework_qwen_workflow = bpy.props.BoolProperty(
+ name="Corrected Qwen Workflow Routing",
+ 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.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",
+ default=TEXTURING_REWORK_DEFAULTS["sg_rework_final_display"], update=update_parameters,
)
bpy.types.Scene.sg_silhouette_depth = bpy.props.FloatProperty(
name="Silhouette Depth",
- description="Minimum depth discontinuity as a fraction of model scale; pixel footprint is also considered so protection behaves consistently on tiny and huge characters",
- default=0.01, min=0.0001, max=0.25, step=1, precision=4, update=update_parameters,
+ description="Legacy Blender-unit depth threshold unless Projection Geometry Corrections is enabled, where it is interpreted relative to model scale",
+ default=0.05, min=0.001, max=1.0, step=1, precision=3, update=update_parameters,
)
bpy.types.Scene.sg_silhouette_rays = bpy.props.EnumProperty(
name="Silhouette Rays",
@@ -1135,6 +1216,16 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
description="Dilate fallback color regions in the context render before sending to Qwen.",
default=1, min=0, max=64, update=update_parameters
)
+ 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",
+ default=TEXTURING_REWORK_DEFAULTS["qwen_use_confidence_context"], update=update_parameters,
+ )
+ bpy.types.Scene.qwen_regularize_context_mask = bpy.props.BoolProperty(
+ name="Regularize Context Boundary",
+ description="Apply island, hole, strip, dilation, and part-aware cleanup to the explicit binary Qwen repair mask",
+ default=TEXTURING_REWORK_DEFAULTS["qwen_regularize_context_mask"], update=update_parameters,
+ )
bpy.types.Scene.qwen_trust_threshold = bpy.props.FloatProperty(
name="Trusted Source Threshold",
description="Minimum original source-camera acquisition quality required before RGB is protected in later Qwen context views",
@@ -1167,8 +1258,13 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
)
bpy.types.Scene.qwen_use_projection_write_masks = bpy.props.BoolProperty(
name="Protect Trusted Texture",
- description="Use the binary sequential visibility mask both to build exact magenta context and to restrict which pixels a later Qwen view may project",
- default=True, update=update_parameters
+ description="Restrict each later Qwen camera's projection contribution to its binary editable/write mask",
+ default=TEXTURING_REWORK_DEFAULTS["qwen_use_projection_write_masks"], update=update_parameters
+ )
+ bpy.types.Scene.qwen_reject_residual_fallback = bpy.props.BoolProperty(
+ name="Reject Residual Magenta",
+ description="Remove residual fallback-color pixels from a Qwen camera's explicit projection write mask",
+ default=TEXTURING_REWORK_DEFAULTS["qwen_reject_residual_fallback"], update=update_parameters,
)
bpy.types.Scene.qwen_residual_fallback_tolerance = bpy.props.IntProperty(
name="Residual Fallback Tolerance",
@@ -1935,6 +2031,15 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'visibility_vignette_blur',
'sg_silhouette_margin', 'sg_silhouette_depth', 'sg_silhouette_rays',
'sg_allow_backface_projection',
+ 'sg_rework_camera_plan', 'sg_rework_aligned_resolution',
+ 'sg_rework_full_resolution_scale',
+ 'sg_rework_safe_render_state', 'sg_rework_reset_controls',
+ 'sg_rework_sdxl_registration', 'sg_rework_acquisition_quality',
+ 'sg_rework_initial_view_priority',
+ '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_texel_ownership', 'sg_texel_replacement_margin',
'sg_allow_trusted_replacement', 'sg_ownership_blend_mode',
'sg_ownership_seam_width', 'sg_ownership_lowpass_sigma',
@@ -1972,7 +2077,9 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'qwen_guidance_fallback_color', 'qwen_guidance_background_color',
'qwen_context_cleanup', 'qwen_context_cleanup_hue_tolerance',
'qwen_context_cleanup_value_adjust', 'qwen_context_fallback_dilation',
+ 'qwen_use_confidence_context', 'qwen_regularize_context_mask',
'qwen_use_projection_write_masks', 'qwen_residual_fallback_tolerance',
+ 'qwen_reject_residual_fallback',
'qwen_trust_threshold', 'qwen_mask_min_island_area',
'qwen_mask_min_hole_area', 'qwen_mask_min_strip_width',
'qwen_mask_uncertainty_dilation',
diff --git a/stablegen/debug_tools.py b/stablegen/debug_tools.py
index 0e2c089..32bb052 100644
--- a/stablegen/debug_tools.py
+++ b/stablegen/debug_tools.py
@@ -14,6 +14,7 @@ import bpy
import os
import colorsys
import numpy as np
+from contextlib import contextmanager
from mathutils import Vector
from .texturing.projection import (
@@ -189,6 +190,42 @@ def _restore_cameras(hidden):
col.objects.link(cam)
+@contextmanager
+def _debug_projection_build_state(scene):
+ """Build diagnostics with the finished material's display controls.
+
+ Sequential generation may use a restrictive angle and then reset only the
+ material nodes for final display. Rebuilding a debug material from the
+ generation configuration made the new 70-degree graph look substantially
+ sharper than the actual 90-degree final graph (and than legacy diagnostics,
+ which mutated the scene value itself). Preserve the generation settings,
+ use the recorded material state when a completed run exists, and restore
+ everything after the diagnostic graph is built.
+ """
+ original = {
+ "overwrite_material": scene.overwrite_material,
+ "generation_method": scene.generation_method,
+ "generation_mode": scene.generation_mode,
+ "discard_factor": scene.discard_factor,
+ "weight_exponent": scene.weight_exponent,
+ }
+ if getattr(scene, "output_timestamp", ""):
+ scene.discard_factor = getattr(
+ scene, "sg_material_discard_factor", scene.discard_factor
+ )
+ scene.weight_exponent = getattr(
+ scene, "sg_material_weight_exponent", scene.weight_exponent
+ )
+ scene.overwrite_material = True
+ scene.generation_method = 'separate'
+ scene.generation_mode = 'standard'
+ try:
+ yield
+ finally:
+ for name, value in original.items():
+ setattr(scene, name, value)
+
+
# ═════════════════════════════════════════════════════════════════════════
# 1. Draw Solid Colors (calls the real project_image)
# ═════════════════════════════════════════════════════════════════════════
@@ -223,29 +260,66 @@ class SG_OT_DebugSolidColors(bpy.types.Operator):
rx, ry = _get_camera_resolution(cam, context.scene)
_save_solid_image(path, rx, ry, (*colors[i], 1.0))
- # Override scene settings so project_image() performs a full
- # fresh build: UV projections + new material tree. Without this,
- # sequential mode skips UV projections and enters the
- # "update-existing" branch which produces a blank material.
- orig_overwrite = context.scene.overwrite_material
- orig_gen_method = context.scene.generation_method
- orig_gen_mode = context.scene.generation_mode
- context.scene.overwrite_material = True
- context.scene.generation_method = 'separate'
- context.scene.generation_mode = 'standard'
- try:
- project_image(context, meshes, mat_id)
- finally:
- context.scene.overwrite_material = orig_overwrite
- context.scene.generation_method = orig_gen_method
- context.scene.generation_mode = orig_gen_mode
+ # Replay the real sequential material lifecycle. A one-shot
+ # ``separate`` build cannot detect failures in the incremental path
+ # (for example, a later camera image loading while its stop gate stays
+ # closed). stop_index=0 creates the UV projections/material; every
+ # later call patches or rebuilds it exactly as generation does.
+ with _debug_projection_build_state(context.scene):
+ context.scene.generation_method = 'sequential'
+ for stop_index in range(n_cams):
+ project_image(
+ context,
+ meshes,
+ mat_id,
+ stop_index=stop_index,
+ cameras=cameras,
+ )
+
+ validation_errors = []
+ inspected_materials = set()
+ for obj in meshes:
+ mat = obj.active_material
+ if mat is None or mat.as_pointer() in inspected_materials:
+ continue
+ inspected_materials.add(mat.as_pointer())
+ nodes = mat.node_tree.nodes
+ for i in range(n_cams):
+ image_node = next(
+ (node for node in nodes
+ if node.type == 'TEX_IMAGE' and node.label == f"{i}-{mat_id}"),
+ None,
+ )
+ expected_path = os.path.normcase(os.path.abspath(get_file_path(
+ context, "generated", camera_id=i, material_id=mat_id
+ )))
+ actual_path = (
+ os.path.normcase(os.path.abspath(bpy.path.abspath(image_node.image.filepath)))
+ if image_node is not None and image_node.image is not None else ""
+ )
+ if actual_path != expected_path:
+ validation_errors.append(
+ f"camera {i}: expected {os.path.basename(expected_path)}, "
+ f"got {os.path.basename(actual_path) or 'no image'}"
+ )
+ if any(node.label == f"StopGate-{i}-{mat_id}" for node in nodes):
+ validation_errors.append(f"camera {i}: sequential stop gate is still closed")
+
+ if validation_errors:
+ details = "; ".join(validation_errors[:4])
+ print(f"[StableGen] Solid-color sequential validation FAILED: {details}")
+ self.report({'ERROR'}, f"Sequential projection validation failed: {details}")
+ return {'CANCELLED'}
# Rename materials for easy identification / cleanup
for obj in meshes:
if obj.active_material:
obj.active_material.name = "SG_Debug_SolidColors"
- self.report({'INFO'}, f"Solid-colour projection applied ({n_cams} cameras)")
+ self.report(
+ {'INFO'},
+ f"Solid-colour sequential projection validated ({n_cams} cameras)",
+ )
return {'FINISHED'}
@@ -286,18 +360,8 @@ class SG_OT_DebugGridPattern(bpy.types.Operator):
rx, ry = _get_camera_resolution(cam, context.scene)
_save_grid_image(path, rx, ry, colors[i], self.grid_size)
- orig_overwrite = context.scene.overwrite_material
- orig_gen_method = context.scene.generation_method
- orig_gen_mode = context.scene.generation_mode
- context.scene.overwrite_material = True
- context.scene.generation_method = 'separate'
- context.scene.generation_mode = 'standard'
- try:
+ with _debug_projection_build_state(context.scene):
project_image(context, meshes, mat_id)
- finally:
- context.scene.overwrite_material = orig_overwrite
- context.scene.generation_method = orig_gen_method
- context.scene.generation_mode = orig_gen_mode
for obj in meshes:
if obj.active_material:
@@ -348,18 +412,8 @@ class SG_OT_DebugVisibilityMaterial(bpy.types.Operator):
rx, ry = _get_camera_resolution(cam, context.scene)
_save_solid_image(path, rx, ry, (*colors[i], 1.0))
- orig_overwrite = context.scene.overwrite_material
- orig_gen_method = context.scene.generation_method
- orig_gen_mode = context.scene.generation_mode
- context.scene.overwrite_material = True
- context.scene.generation_method = 'separate'
- context.scene.generation_mode = 'standard'
- try:
+ with _debug_projection_build_state(context.scene):
project_image(context, meshes, mat_id)
- finally:
- context.scene.overwrite_material = orig_overwrite
- context.scene.generation_method = orig_gen_method
- context.scene.generation_mode = orig_gen_mode
# Transform projection material into visibility mask
result = export_visibility(context, meshes, prepare_only=True)
diff --git a/stablegen/feature_flags.py b/stablegen/feature_flags.py
new file mode 100644
index 0000000..ca2766e
--- /dev/null
+++ b/stablegen/feature_flags.py
@@ -0,0 +1,38 @@
+"""StableGen texturing experiment switches and legacy-compatible defaults."""
+
+# This mapping is deliberately Blender-independent so tests and preset code can
+# verify the baseline without importing the add-on registration graph.
+TEXTURING_REWORK_DEFAULTS = {
+ "sg_rework_camera_plan": False,
+ "sg_rework_aligned_resolution": False,
+ "sg_rework_full_resolution_scale": False,
+ "sg_rework_safe_render_state": False,
+ "sg_rework_reset_controls": False,
+ "sg_rework_sdxl_registration": False,
+ "sg_rework_acquisition_quality": False,
+ "sg_rework_initial_view_priority": False,
+ "sg_rework_projection_guard": False,
+ "sg_rework_projection_rebuild": False,
+ "sg_rework_projection_geometry": False,
+ "sg_rework_consistent_frame": False,
+ "sg_rework_workflow_validation": False,
+ "sg_rework_qwen_workflow": False,
+ "sg_rework_final_display": False,
+ "qwen_use_confidence_context": False,
+ "qwen_regularize_context_mask": False,
+ "qwen_use_projection_write_masks": False,
+ "qwen_reject_residual_fallback": False,
+ "sg_texel_ownership": False,
+ "sg_auto_view_sequence": False,
+ "sg_freeze_ownership_after_generation": False,
+ # Legacy projection used abs(dot), i.e. two-sided/backface contribution.
+ "sg_allow_backface_projection": True,
+}
+
+
+def all_rework_features_disabled(scene):
+ """Return True when *scene* is configured for the legacy baseline."""
+ return all(
+ getattr(scene, name, default) == default
+ for name, default in TEXTURING_REWORK_DEFAULTS.items()
+ )
diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.py
index 8fdb5f8..e8da1e7 100644
--- a/stablegen/texturing/generator.py
+++ b/stablegen/texturing/generator.py
@@ -13,6 +13,8 @@ import urllib.parse
import socket
import threading
import traceback
+import io
+import colorsys
from datetime import datetime
import math
from PIL import Image, ImageEnhance
@@ -22,7 +24,7 @@ import blf # pylint: disable=import-error
from gpu_extras.batch import batch_for_shader # pylint: disable=import-error
from ..util.workflow_templates import prompt_text, prompt_text_img2img, prompt_text_qwen_image_edit
-from .rendering import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, render_edge_feather_mask, apply_uv_inpaint_texture, flatten_projection_material_for_refine, _RenderStateTransaction
+from .rendering import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, render_edge_feather_mask, apply_uv_inpaint_texture, flatten_projection_material_for_refine, _RenderStateTransaction, _legacy_render_dither, _prepare_compositor_render, _finish_compositor_render
from ..cameras.geometry import _SGCameraResolution, _get_camera_resolution
from ..cameras.overlays import _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay
from .projection import project_image, reinstate_compare_nodes, _bake_visibility_weights, reset_projection_material_nodes, _is_projection_mesh
@@ -46,6 +48,7 @@ from .quality_masks import (
build_depth_part_rejection_mask,
)
from .confidence import camera_direction_from_matrix, overlap_aware_order
+from ..feature_flags import TEXTURING_REWORK_DEFAULTS
import websocket
@@ -435,7 +438,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def _apply_qwen_binary_context_mask(self, context, camera_id, fallback_color):
"""Make the exported sequential mask authoritative for Qwen context."""
- if not getattr(context.scene, "qwen_use_projection_write_masks", True):
+ if not getattr(context.scene, "qwen_use_confidence_context", False):
return
if context.scene.qwen_context_render_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}:
return
@@ -483,34 +486,38 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
object_ids.astype(np.int32) * 256 + material_ids.astype(np.int32)
)
- repair_mask = regularize_repair_mask(
- repair_mask,
- threshold=127,
- dilation=getattr(context.scene, 'qwen_mask_uncertainty_dilation', 1),
- min_island_area=getattr(context.scene, 'qwen_mask_min_island_area', 16),
- min_hole_area=getattr(context.scene, 'qwen_mask_min_hole_area', 8),
- min_strip_width=getattr(context.scene, 'qwen_mask_min_strip_width', 2),
- boundary_labels=boundary_labels,
- keep_largest_components=getattr(
- context.scene, 'qwen_mask_keep_largest_components', 0
- ),
- )
+ if getattr(context.scene, 'qwen_regularize_context_mask', False):
+ repair_mask = regularize_repair_mask(
+ repair_mask,
+ threshold=127,
+ dilation=getattr(context.scene, 'qwen_mask_uncertainty_dilation', 1),
+ min_island_area=getattr(context.scene, 'qwen_mask_min_island_area', 16),
+ min_hole_area=getattr(context.scene, 'qwen_mask_min_hole_area', 8),
+ min_strip_width=getattr(context.scene, 'qwen_mask_min_strip_width', 2),
+ boundary_labels=boundary_labels,
+ keep_largest_components=getattr(
+ context.scene, 'qwen_mask_keep_largest_components', 0
+ ),
+ )
+ else:
+ repair_mask = np.where(repair_mask > 127, 255, 0).astype(np.uint8)
# Depth/ID discontinuities are never trusted context. Forcing these
# pixels to repair prevents front objects from imprinting silhouettes
# onto the surface behind them.
- guard_path = os.path.join(
- get_dir_path(context, "inpaint")["visibility"],
- f"projection_guard{camera_id}.png",
- )
- guard = cv2.imread(guard_path, cv2.IMREAD_GRAYSCALE)
- if guard is not None:
- if guard.shape != repair_mask.shape:
- guard = cv2.resize(
- guard,
- (repair_mask.shape[1], repair_mask.shape[0]),
- interpolation=cv2.INTER_NEAREST,
- )
- repair_mask[guard < 128] = 255
+ if getattr(context.scene, 'sg_rework_projection_guard', False):
+ guard_path = os.path.join(
+ get_dir_path(context, "inpaint")["visibility"],
+ f"projection_guard{camera_id}.png",
+ )
+ guard = cv2.imread(guard_path, cv2.IMREAD_GRAYSCALE)
+ if guard is not None:
+ if guard.shape != repair_mask.shape:
+ guard = cv2.resize(
+ guard,
+ (repair_mask.shape[1], repair_mask.shape[0]),
+ interpolation=cv2.INTER_NEAREST,
+ )
+ repair_mask[guard < 128] = 255
context_image = apply_binary_context_mask(
context_image, repair_mask, fallback_color
)
@@ -537,7 +544,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def _reject_qwen_fallback_writes(self, context, camera_id, image_path, fallback_color):
"""Keep residual sentinel pixels out of the projection material."""
- if not getattr(context.scene, "qwen_use_projection_write_masks", True):
+ if not getattr(context.scene, "qwen_reject_residual_fallback", False):
return
if context.scene.qwen_context_render_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}:
return
@@ -576,6 +583,103 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
residual_sentinel_percent=residual_percent,
)
+ def _dilate_qwen_context_fallback(self, context, camera_id, fallback_color):
+ """Legacy rigging-branch fallback-color dilation."""
+ dilation = int(max(0, context.scene.qwen_context_fallback_dilation))
+ if dilation <= 0:
+ return
+ image_path = get_file_path(
+ context, "inpaint", subtype="render", camera_id=camera_id
+ )
+ if not image_path or not os.path.exists(image_path):
+ return
+ try:
+ with Image.open(image_path) as img:
+ pixel_data = np.array(img.convert("RGBA"))
+ except Exception as err:
+ print(f"[StableGen] Failed to load context render for dilation at {image_path}: {err}")
+ return
+ fallback_rgb = np.array(
+ [int(round(component * 255.0)) for component in fallback_color],
+ dtype=np.uint8,
+ )
+ rgb = pixel_data[:, :, :3].astype(np.int16)
+ mask = np.all(
+ np.abs(rgb - fallback_rgb[np.newaxis, np.newaxis, :]) <= 3,
+ axis=2,
+ )
+ if not np.any(mask):
+ return
+ kernel_size = max(1, dilation * 2 + 1)
+ kernel = cv2.getStructuringElement(
+ cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)
+ )
+ dilated_mask = cv2.dilate(
+ mask.astype(np.uint8) * 255, kernel, iterations=1
+ ) > 0
+ pixel_data[dilated_mask, :3] = fallback_rgb
+ pixel_data[dilated_mask, 3] = 255
+ try:
+ Image.fromarray(pixel_data).save(image_path)
+ except Exception as err:
+ print(f"[StableGen] Failed to save dilated context render at {image_path}: {err}")
+ return
+ if hasattr(self, '_uploaded_images_cache') and self._uploaded_images_cache is not None:
+ self._uploaded_images_cache.pop(os.path.abspath(image_path), None)
+
+ def _apply_qwen_context_cleanup(self, context, image_bytes):
+ """Legacy rigging-branch global fallback-hue cleanup."""
+ hue_tolerance = max(context.scene.qwen_context_cleanup_hue_tolerance, 0.0)
+ value_adjust = context.scene.qwen_context_cleanup_value_adjust
+ fallback_color = tuple(context.scene.qwen_guidance_fallback_color)
+ try:
+ with Image.open(io.BytesIO(image_bytes)) as pil_image:
+ pixel_data = np.array(pil_image.convert("RGBA"))
+ except Exception as err:
+ print(f"[StableGen] Warning: failed to read Qwen image for cleanup: {err}")
+ return image_bytes
+ rgb = pixel_data[:, :, :3].astype(np.float32) / 255.0
+ alpha = pixel_data[:, :, 3]
+ maxc = rgb.max(axis=2)
+ minc = rgb.min(axis=2)
+ delta = maxc - minc
+ hue = np.zeros_like(maxc, dtype=np.float32)
+ non_gray = delta > 1e-6
+ safe_delta = np.where(non_gray, delta, 1.0)
+ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
+ idx = non_gray & (r == maxc)
+ hue[idx] = ((g[idx] - b[idx]) / safe_delta[idx]) % 6.0
+ idx = non_gray & (g == maxc)
+ hue[idx] = ((b[idx] - r[idx]) / safe_delta[idx]) + 2.0
+ idx = non_gray & (b == maxc)
+ hue[idx] = ((r[idx] - g[idx]) / safe_delta[idx]) + 4.0
+ hue = (hue / 6.0) % 1.0
+ try:
+ fallback_hue = colorsys.rgb_to_hsv(*fallback_color)[0]
+ except Exception:
+ fallback_hue = 0.0
+ hue_tol_normalized = max(hue_tolerance / 360.0, 0.0)
+ hue_diff = np.abs(hue - fallback_hue)
+ hue_diff = np.minimum(hue_diff, 1.0 - hue_diff)
+ target_mask = non_gray & (hue_diff <= hue_tol_normalized)
+ if not np.any(target_mask):
+ return image_bytes
+ adjusted_value = np.clip(maxc[target_mask] + value_adjust, 0.0, 1.0)
+ updated_rgb = np.array(rgb)
+ updated_rgb[target_mask] = np.repeat(adjusted_value[:, None], 3, axis=1)
+ updated_pixels = np.empty_like(pixel_data)
+ updated_pixels[:, :, :3] = np.clip(
+ np.round(updated_rgb * 255.0), 0, 255
+ ).astype(np.uint8)
+ updated_pixels[:, :, 3] = alpha
+ try:
+ buffer = io.BytesIO()
+ Image.fromarray(updated_pixels, mode="RGBA").save(buffer, format="PNG")
+ return buffer.getvalue()
+ except Exception as err:
+ print(f"[StableGen] Warning: failed to write cleaned Qwen image: {err}")
+ return image_bytes
+
def _record_confidence_artifacts(self, context, camera_id, **values):
"""Persist provenance/debug paths incrementally for regeneration."""
revision_dir = get_generation_dirs(context)["revision"]
@@ -648,6 +752,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
ComfyUIGenerate._is_running = True
print("[StableGen] Executing ComfyUI Generation")
+ enabled_experiments = [
+ name for name, default in TEXTURING_REWORK_DEFAULTS.items()
+ if getattr(context.scene, name, default) != default
+ ]
+ if enabled_experiments:
+ print("[StableGen] Texturing experiments enabled: " + ", ".join(enabled_experiments))
+ else:
+ print("[StableGen] Texturing feature set: legacy rigging-branch baseline")
if context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein') and not context.scene.generation_mode == 'project_only':
context.scene.generation_method = 'sequential' # Force sequential for edit models
@@ -661,7 +773,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._original_resolution_percentage = render.resolution_percentage
self._original_resolution_x = render.resolution_x
self._original_resolution_y = render.resolution_y
- render.resolution_percentage = 100
+ if getattr(context.scene, 'sg_rework_full_resolution_scale', False):
+ render.resolution_percentage = 100
resolution_x = render.resolution_x
resolution_y = render.resolution_y
@@ -686,10 +799,22 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
upper_bound = int(target_px * 1.2)
lower_bound = int(target_px * 0.8)
+ use_aligned_search = getattr(
+ context.scene, 'sg_rework_aligned_resolution', False
+ )
if context.scene.auto_rescale and ((total_pixels > upper_bound or total_pixels < lower_bound) or (resolution_x % align_step != 0 or resolution_y % align_step != 0)):
- render.resolution_x, render.resolution_y = choose_aligned_resolution(
- resolution_x, resolution_y, target_px, align_step
- )
+ if use_aligned_search:
+ render.resolution_x, render.resolution_y = choose_aligned_resolution(
+ resolution_x, resolution_y, target_px, align_step
+ )
+ else:
+ # Rigging-branch behavior: proportional scaling followed by
+ # independent round-down to the architecture alignment grid.
+ scale_factor = (target_px / total_pixels) ** 0.5
+ render.resolution_x = int(resolution_x * scale_factor)
+ render.resolution_y = int(resolution_y * scale_factor)
+ render.resolution_x -= render.resolution_x % align_step
+ render.resolution_y -= render.resolution_y % align_step
self.report({'INFO'}, f"Resolution automatically rescaled to {render.resolution_x}x{render.resolution_y}.")
elif total_pixels > upper_bound:
@@ -706,13 +831,29 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
render.resolution_x = self._original_resolution_x
render.resolution_y = self._original_resolution_y
return {'CANCELLED'}
+ use_camera_plan = getattr(context.scene, 'sg_rework_camera_plan', False)
order_names = []
if context.scene.sg_use_custom_camera_order and len(context.scene.sg_camera_order) > 0:
order_names = [item.name for item in context.scene.sg_camera_order]
- self._cameras = order_cameras(self._cameras, order_names)
-
- self._original_texturing_frame = context.scene.frame_current
- context.scene.frame_set(int(getattr(context.scene, 'sg_texturing_frame', 1)))
+ if use_camera_plan:
+ self._cameras = order_cameras(self._cameras, order_names)
+ else:
+ # Exact pre-rework ordering path.
+ self._cameras.sort(key=lambda camera: camera.name)
+ if order_names:
+ camera_by_name = {camera.name: camera for camera in self._cameras}
+ ordered = []
+ for name in order_names:
+ if name in camera_by_name:
+ ordered.append(camera_by_name.pop(name))
+ for camera in self._cameras:
+ if camera.name in camera_by_name:
+ ordered.append(camera)
+ self._cameras = ordered
+
+ if getattr(context.scene, 'sg_rework_consistent_frame', False):
+ self._original_texturing_frame = context.scene.frame_current
+ context.scene.frame_set(int(getattr(context.scene, 'sg_texturing_frame', 1)))
if (context.scene.generation_mode == 'standard'
and not order_names
@@ -749,7 +890,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
revision_dir = get_generation_dirs(context)["revision"]
manifest_path = os.path.join(revision_dir, "view_plan.json")
- if context.scene.generation_mode in {'regenerate_selected', 'project_only'}:
+ if (use_camera_plan
+ and context.scene.generation_mode in {'regenerate_selected', 'project_only'}):
try:
with open(manifest_path, "r", encoding="utf-8") as manifest_file:
persisted_manifest = json.load(manifest_file)
@@ -772,65 +914,73 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
crx, cry = int(cam["sg_res_x"]), int(cam["sg_res_y"])
c_total = crx * cry
if (c_total > upper_bound or c_total < lower_bound) or (crx % align_step != 0 or cry % align_step != 0):
- crx, cry = choose_aligned_resolution(
- crx, cry, target_px, align_step
- )
+ if use_aligned_search:
+ crx, cry = choose_aligned_resolution(
+ crx, cry, target_px, align_step
+ )
+ else:
+ scale_factor = (target_px / c_total) ** 0.5
+ crx = int(crx * scale_factor)
+ cry = int(cry * scale_factor)
+ crx -= crx % align_step
+ cry -= cry % align_step
cam["sg_res_x"] = crx
cam["sg_res_y"] = cry
- view_records = []
- for index, cam in enumerate(self._cameras):
- if "sg_view_uuid" not in cam:
- cam["sg_view_uuid"] = uuid.uuid4().hex
- cam_res_x = int(cam.get("sg_res_x", render.resolution_x))
- cam_res_y = int(cam.get("sg_res_y", render.resolution_y))
- prompt_item = next(
- (item for item in context.scene.camera_prompts if item.name == cam.name),
- None,
- )
- view_prompt = prompt_item.prompt if prompt_item and prompt_item.prompt else ""
- view_id = str(cam["sg_view_uuid"])
- matrix_world = tuple(
- tuple(float(value) for value in row) for row in cam.matrix_world
- )
- view_records.append(ViewRecord(
- view_id=view_id,
- index=index,
- name=cam.name,
- camera=cam,
- resolution_x=cam_res_x,
- resolution_y=cam_res_y,
- prompt=view_prompt,
- matrix_world=matrix_world,
- intrinsics={
- "type": cam.data.type,
- "lens": cam.data.lens,
- "sensor_width": cam.data.sensor_width,
- "sensor_height": cam.data.sensor_height,
- "shift_x": cam.data.shift_x,
- "shift_y": cam.data.shift_y,
- "ortho_scale": cam.data.ortho_scale,
- },
- file_identifiers={
- "generated": f"generated:{view_id}",
- "guide_depth": f"guide-depth:{view_id}",
- "guide_normal": f"guide-normal:{view_id}",
- "guide_canny": f"guide-canny:{view_id}",
- "context": f"context:{view_id}",
- "repair_mask": f"repair-mask:{view_id}",
- "write_mask": f"write-mask:{view_id}",
- },
- ))
- self._view_plan = tuple(view_records)
- self._cameras = tuple(record.camera for record in self._view_plan)
-
- os.makedirs(revision_dir, exist_ok=True)
- with open(manifest_path, "w", encoding="utf-8") as manifest_file:
- json.dump(
- {"schema": 1, "views": [record.to_manifest() for record in self._view_plan]},
- manifest_file,
- indent=2,
- )
+ self._view_plan = None
+ if use_camera_plan:
+ view_records = []
+ for index, cam in enumerate(self._cameras):
+ if "sg_view_uuid" not in cam:
+ cam["sg_view_uuid"] = uuid.uuid4().hex
+ cam_res_x = int(cam.get("sg_res_x", render.resolution_x))
+ cam_res_y = int(cam.get("sg_res_y", render.resolution_y))
+ prompt_item = next(
+ (item for item in context.scene.camera_prompts if item.name == cam.name),
+ None,
+ )
+ view_prompt = prompt_item.prompt if prompt_item and prompt_item.prompt else ""
+ view_id = str(cam["sg_view_uuid"])
+ matrix_world = tuple(
+ tuple(float(value) for value in row) for row in cam.matrix_world
+ )
+ view_records.append(ViewRecord(
+ view_id=view_id,
+ index=index,
+ name=cam.name,
+ camera=cam,
+ resolution_x=cam_res_x,
+ resolution_y=cam_res_y,
+ prompt=view_prompt,
+ matrix_world=matrix_world,
+ intrinsics={
+ "type": cam.data.type,
+ "lens": cam.data.lens,
+ "sensor_width": cam.data.sensor_width,
+ "sensor_height": cam.data.sensor_height,
+ "shift_x": cam.data.shift_x,
+ "shift_y": cam.data.shift_y,
+ "ortho_scale": cam.data.ortho_scale,
+ },
+ file_identifiers={
+ "generated": f"generated:{view_id}",
+ "guide_depth": f"guide-depth:{view_id}",
+ "guide_normal": f"guide-normal:{view_id}",
+ "guide_canny": f"guide-canny:{view_id}",
+ "context": f"context:{view_id}",
+ "repair_mask": f"repair-mask:{view_id}",
+ "write_mask": f"write-mask:{view_id}",
+ },
+ ))
+ self._view_plan = tuple(view_records)
+ self._cameras = tuple(record.camera for record in self._view_plan)
+ os.makedirs(revision_dir, exist_ok=True)
+ with open(manifest_path, "w", encoding="utf-8") as manifest_file:
+ json.dump(
+ {"schema": 1, "views": [record.to_manifest() for record in self._view_plan]},
+ manifest_file,
+ indent=2,
+ )
self._selected_camera_ids = [i for i, cam in enumerate(self._cameras) if cam in bpy.context.selected_objects] #TEST
if len(self._selected_camera_ids) == 0:
self._selected_camera_ids = list(range(len(self._cameras))) # All cameras selected if none are selected
@@ -845,7 +995,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
render.resolution_percentage = self._original_resolution_percentage
render.resolution_x = self._original_resolution_x
render.resolution_y = self._original_resolution_y
- context.scene.frame_set(self._original_texturing_frame)
+ if hasattr(self, '_original_texturing_frame'):
+ context.scene.frame_set(self._original_texturing_frame)
return {'CANCELLED'}
# If there are curves within the scene, warn the user
@@ -870,7 +1021,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
render.resolution_percentage = self._original_resolution_percentage
render.resolution_x = self._original_resolution_x
render.resolution_y = self._original_resolution_y
- context.scene.frame_set(self._original_texturing_frame)
+ if hasattr(self, '_original_texturing_frame'):
+ context.scene.frame_set(self._original_texturing_frame)
return {'CANCELLED'}
else: # all
self._to_texture = [obj for obj in bpy.context.view_layer.objects if obj.type == 'MESH' and not obj.hide_get()]
@@ -893,7 +1045,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
render.resolution_percentage = self._original_resolution_percentage
render.resolution_x = self._original_resolution_x
render.resolution_y = self._original_resolution_y
- context.scene.frame_set(self._original_texturing_frame)
+ if hasattr(self, '_original_texturing_frame'):
+ context.scene.frame_set(self._original_texturing_frame)
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')):
@@ -1071,7 +1224,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
# after the worker exits, before either success or error can
# return from the operator.
try:
- self._reset_projection_state(context)
+ if (getattr(context.scene, 'sg_rework_reset_controls', False)
+ or not self._error):
+ self._reset_projection_state(context)
except Exception as reset_error:
traceback.print_exc()
if not self._error:
@@ -1151,6 +1306,41 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def _reset_projection_state(self, context):
"""Restore final display controls after every worker termination."""
+ if not getattr(context.scene, 'sg_rework_reset_controls', False):
+ # Rigging-branch behavior: update only the original OSL/native
+ # inputs. This intentionally does not touch the normalized
+ # SharpW nodes or rebake attributes; the corrected behavior is a
+ # separate opt-in experiment.
+ applicable = (
+ getattr(self, '_generation_method_on_start', None) == 'sequential'
+ or context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ )
+ if context.scene.discard_factor_generation_only and applicable:
+ angle = context.scene.discard_factor_after_generation
+ for obj in getattr(self, '_to_texture', ()):
+ material = getattr(obj, 'active_material', None)
+ if not material or not material.use_nodes:
+ continue
+ for node in material.node_tree.nodes:
+ if node.type == 'SCRIPT' and 'AngleThreshold' in node.inputs:
+ node.inputs['AngleThreshold'].default_value = angle
+ elif (node.type == 'MATH' and node.operation == 'LESS_THAN'
+ and node.label.startswith('AngleThreshold-')):
+ node.inputs[1].default_value = angle
+ if context.scene.weight_exponent_generation_only and applicable:
+ exponent = context.scene.weight_exponent_after_generation
+ for obj in getattr(self, '_to_texture', ()):
+ material = getattr(obj, 'active_material', None)
+ if not material or not material.use_nodes:
+ continue
+ for node in material.node_tree.nodes:
+ if node.type == 'SCRIPT' and 'Power' in node.inputs:
+ node.inputs['Power'].default_value = exponent
+ elif (node.type == 'MATH' and node.operation == 'POWER'
+ and node.label == 'power_weight'):
+ node.inputs[1].default_value = exponent
+ return
+
applicable = (
getattr(self, '_generation_method_on_start', None) == 'sequential'
or context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
@@ -1312,6 +1502,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def _activate_view(self, context, index):
"""Reapply the immutable view snapshot before every camera stage."""
if not self._view_plan or not (0 <= index < len(self._view_plan)):
+ if 0 <= index < len(self._cameras or ()):
+ camera = self._cameras[index]
+ context.scene.camera = camera
+ return camera
return None
texturing_frame = int(getattr(context.scene, 'sg_texturing_frame', 1))
if context.scene.frame_current != texturing_frame:
@@ -1328,9 +1522,13 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
value = intrinsics.get(name)
if value is not None and hasattr(camera.data, name):
setattr(camera.data, name, value)
- camera['sg_res_x'] = int(record.resolution_x)
- camera['sg_res_y'] = int(record.resolution_y)
context.scene.camera = camera
+ # View activation is runtime state. Do not persist plan dimensions as
+ # camera custom properties: those properties are reserved for the
+ # user's intentional per-camera aspect feature. Persisting them here
+ # allowed an interrupted run to corrupt the next run's aspect plan.
+ context.scene.render.resolution_x = int(record.resolution_x)
+ context.scene.render.resolution_y = int(record.resolution_y)
return camera
def _prepare_maps(self, context):
@@ -1349,8 +1547,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
or (context.scene.model_architecture.startswith('qwen')
and context.scene.qwen_generation_method in ('refine', 'local_edit')
and context.scene.qwen_refine_use_depth)
- or (context.scene.generation_method == 'sequential'
- and getattr(context.scene, 'sg_silhouette_margin', 0) > 0)
+ or (getattr(context.scene, 'sg_rework_projection_guard', False)
+ and context.scene.generation_method == 'sequential')
+ or (getattr(context.scene, 'qwen_regularize_context_mask', False)
+ and context.scene.generation_method == 'sequential')
)
if need_depth and context.scene.generation_method != 'uv_inpaint':
for i, camera in enumerate(cameras):
@@ -1540,7 +1740,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
redraw_ui(context)
project_image(
context, self._to_texture, self._material_id,
- stop_index=self._current_image, view_plan=self._view_plan,
+ stop_index=self._current_image,
+ cameras=self._cameras,
+ view_plan=self._view_plan,
)
except Exception as e:
self._error = str(e)
@@ -1646,23 +1848,35 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
_cur_index = self._current_image if self._current_image < len(self._cameras) else self._current_image - 1
_cur_cam = self._activate_view(context, _cur_index)
with _SGCameraResolution(context, _cur_cam):
+ # Bind the output index to the operator's
+ # actual generation sequence. Relying on
+ # export_visibility's alphabetical
+ # rediscovery assigns custom-order
+ # renders to the wrong camera.
export_visibility(
context,
self._to_texture,
camera_visibility=_vis_cam,
camera_render=_cur_cam,
camera_id=self._current_image,
- ) # Export mask for current view
+ )
_emit_cam = _cur_cam
with _SGCameraResolution(context, _emit_cam):
if context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein'): # export custom bg and fallback for Qwen/Klein image edit
fallback_color, background_color = self._get_qwen_context_colors(context)
export_emit_image(context, self._to_texture, camera_id=self._current_image, bg_color=background_color, fallback_color=fallback_color) # Export render for next view
- self._apply_qwen_binary_context_mask(
- context,
- self._current_image,
- fallback_color,
- )
+ if getattr(context.scene, 'qwen_use_confidence_context', False):
+ self._apply_qwen_binary_context_mask(
+ context,
+ self._current_image,
+ fallback_color,
+ )
+ else:
+ self._dilate_qwen_context_fallback(
+ context,
+ self._current_image,
+ fallback_color,
+ )
else:
# Use a gray (neutral) background and fallback for other architectures
export_emit_image(context, self._to_texture, camera_id=self._current_image, bg_color=(0.5, 0.5, 0.5), fallback_color=(0.5, 0.5, 0.5))
@@ -1704,6 +1918,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._error = "Connection to ComfyUI server failed."
return # Error message set
+ if (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ and context.scene.generation_method == 'sequential'
+ and self._current_image > 0
+ and not getattr(context.scene, 'qwen_use_confidence_context', False)
+ and context.scene.qwen_context_cleanup
+ and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}):
+ image = self._apply_qwen_context_cleanup(context, image)
+
# Save the generated image using new path structure
if context.scene.generation_method == 'uv_inpaint':
image_path = get_file_path(context, "generated_baked", object_name=self._to_texture[self._current_image].name, material_id=self._material_id)
@@ -1764,7 +1986,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
redraw_ui(context)
project_image(
context, self._to_texture, self._material_id,
- stop_index=self._current_image, view_plan=self._view_plan,
+ stop_index=self._current_image,
+ cameras=self._cameras,
+ view_plan=self._view_plan,
)
except Exception as e:
self._error = str(e)
@@ -1894,6 +2118,23 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def image_project_callback():
if context.scene.generation_method == 'sequential':
# In sequential mode, projection happened per-camera inside the loop.
+ # Optionally rebuild the finished display without the binary
+ # generation-only Qwen write masks. This is intentionally
+ # opt-in so the default remains byte-for-byte compatible with
+ # the rigging-branch sequential material behavior.
+ if getattr(context.scene, 'sg_rework_final_display', False):
+ original_method = context.scene.generation_method
+ try:
+ context.scene.generation_method = 'separate'
+ project_image(
+ context,
+ self._to_texture,
+ self._material_id,
+ cameras=self._cameras,
+ view_plan=self._view_plan,
+ )
+ finally:
+ context.scene.generation_method = original_method
# PBR is projected onto the existing material after all cameras.
if getattr(context.scene, 'pbr_decomposition', False) and hasattr(self, '_pbr_maps') and self._pbr_maps:
from .pbr_projection import project_pbr_to_bsdf
@@ -1910,6 +2151,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
if context.scene.generation_method != 'uv_inpaint':
project_image(
context, self._to_texture, self._material_id,
+ cameras=self._cameras,
view_plan=self._view_plan,
)
else:
@@ -1966,11 +2208,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def _freeze_projection_ownership(self, context):
"""Bake live camera ownership into production UV textures when enabled."""
- ownership_active = (
+ ownership_active = bool(
getattr(context.scene, 'sg_texel_ownership', False)
- or (context.scene.model_architecture == 'qwen_image_edit'
- and context.scene.generation_method == 'sequential'
- and getattr(context.scene, 'qwen_use_projection_write_masks', True))
)
if not (ownership_active
and getattr(context.scene, 'sg_freeze_ownership_after_generation', False)):
@@ -2014,6 +2253,75 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
return context.window_manager.invoke_props_dialog(self, width=400)
return self.execute(context)
+ def _export_depthmap_legacy(self, context, camera_id=None):
+ """Rigging-branch depth exporter, intentionally kept unchanged."""
+ print("[StableGen] Exporting depth map")
+ original_engine = bpy.context.scene.render.engine
+ original_view_transform = bpy.context.scene.view_settings.view_transform
+ original_film_transparent = bpy.context.scene.render.film_transparent
+ original_use_compositing = bpy.context.scene.render.use_compositing
+ original_filepath = bpy.context.scene.render.filepath
+
+ bpy.context.scene.frame_set(1)
+
+ output_dir = get_dir_path(context, "controlnet")["depth"]
+ output_file = f"depth_map{camera_id}" if camera_id is not None else "depth_map"
+
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ view_layer = bpy.context.view_layer
+ bpy.context.scene.render.engine = 'BLENDER_WORKBENCH'
+ bpy.context.scene.display_settings.display_device = 'sRGB'
+ bpy.context.scene.view_settings.view_transform = 'Raw'
+
+ original_pass_z = view_layer.use_pass_z
+ view_layer.use_pass_z = True
+
+ bpy.context.scene.render.use_compositing = True
+ bpy.context.scene.use_nodes = True
+ node_tree = get_compositor_node_tree(bpy.context.scene)
+ nodes = node_tree.nodes
+ links = node_tree.links
+ compositor_state = _prepare_compositor_render(context.scene, node_tree)
+
+ bpy.context.scene.render.image_settings.file_format = 'PNG'
+
+ for node in nodes:
+ nodes.remove(node)
+
+ render_layers_node = nodes.new(type="CompositorNodeRLayers")
+ render_layers_node.location = (0, 0)
+
+ normalize_node = nodes.new(type="CompositorNodeNormalize")
+ normalize_node.location = (200, 0)
+ links.new(render_layers_node.outputs["Depth"], normalize_node.inputs[0])
+
+ invert_node = nodes.new(type="CompositorNodeInvert")
+ invert_node.location = (400, 0)
+ color_input = invert_node.inputs["Color"] if "Color" in invert_node.inputs else invert_node.inputs[1]
+ links.new(normalize_node.outputs[0], color_input)
+
+ output_node = nodes.new(type="CompositorNodeOutputFile")
+ output_node.location = (600, 0)
+ configure_output_node_paths(output_node, output_dir, output_file)
+ links.new(invert_node.outputs[0], output_node.inputs[0])
+
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ _finish_compositor_render(node_tree, compositor_state)
+
+ bpy.context.scene.view_settings.view_transform = 'Standard'
+ print(f"[StableGen] Depth map saved to: {os.path.join(output_dir, output_file)}.png")
+
+ bpy.context.scene.render.engine = original_engine
+ bpy.context.scene.view_settings.view_transform = original_view_transform
+ bpy.context.scene.render.film_transparent = original_film_transparent
+ bpy.context.scene.render.use_compositing = original_use_compositing
+ bpy.context.scene.render.filepath = original_filepath
+ view_layer.use_pass_z = original_pass_z
+
def _export_depthmap_impl(self, context, camera_id=None):
"""
Exports the depth map of the scene.
@@ -2022,6 +2330,8 @@ 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)
# Save original settings to restore later.
original_engine = bpy.context.scene.render.engine
original_view_transform = bpy.context.scene.view_settings.view_transform
@@ -2045,6 +2355,13 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
bpy.context.scene.render.engine = 'CYCLES'
bpy.context.scene.cycles.samples = 1
+ # Object/material indices are categorical data. Blender's default
+ # output dithering introduces one-LSB checkerboard noise into these
+ # passes, which makes almost every 3x3 neighbourhood look like an ID
+ # boundary on complex characters. The render transaction restores the
+ # user's original setting after this export.
+ bpy.context.scene.render.dither_intensity = 0.0
+
bpy.context.scene.display_settings.display_device = 'sRGB'
bpy.context.scene.view_settings.view_transform = 'Raw'
@@ -2076,6 +2393,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
node_tree = get_compositor_node_tree(bpy.context.scene)
nodes = node_tree.nodes
links = node_tree.links
+ compositor_state = _prepare_compositor_render(context.scene, node_tree)
# Ensure animation format is not selected
bpy.context.scene.render.image_settings.file_format = 'PNG'
@@ -2114,7 +2432,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
)
if actual_socket is None:
return False
- divide = nodes.new(type="CompositorNodeMath")
+ # Blender 5 removed the compositor-specific Math node idname.
+ # ShaderNodeMath is the shared Math node accepted by compositor
+ # trees in both the current API and supported Blender 4.x builds.
+ divide = nodes.new(type="ShaderNodeMath")
divide.operation = 'DIVIDE'
divide.inputs[1].default_value = 255.0
divide.location = (200, y)
@@ -2125,22 +2446,32 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
links.new(divide.outputs[0], index_output.inputs[0])
return True
- has_object_ids = _add_index_output(
+ use_projection_guard = getattr(
+ context.scene, 'sg_rework_projection_guard', False
+ )
+ use_part_ids = (
+ use_projection_guard
+ or getattr(context.scene, 'qwen_regularize_context_mask', False)
+ )
+ has_object_ids = use_part_ids and _add_index_output(
"IndexOB", f"object_id{camera_id}", -200
)
- has_material_ids = _add_index_output(
+ has_material_ids = use_part_ids and _add_index_output(
"IndexMA", f"material_id{camera_id}", -400
)
# Render the scene
- bpy.ops.render.render(write_still=True)
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ _finish_compositor_render(node_tree, compositor_state)
frame_suffix = "0001" if bpy.app.version < (5, 0, 0) else ""
depth_path = os.path.join(output_dir, f"{output_file}{frame_suffix}.png")
object_path = os.path.join(output_dir, f"object_id{camera_id}{frame_suffix}.png")
material_path = os.path.join(output_dir, f"material_id{camera_id}{frame_suffix}.png")
depth_image = cv2.imread(depth_path, cv2.IMREAD_GRAYSCALE)
- if depth_image is not None:
+ if use_projection_guard and depth_image is not None:
object_image = (
cv2.imread(object_path, cv2.IMREAD_GRAYSCALE)
if has_object_ids else None
@@ -2149,7 +2480,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
cv2.imread(material_path, cv2.IMREAD_GRAYSCALE)
if has_material_ids else None
)
- guard = build_depth_part_rejection_mask(
+ guard, guard_diagnostics = build_depth_part_rejection_mask(
depth_image,
object_image,
material_image,
@@ -2158,7 +2489,24 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
1,
round(float(getattr(context.scene, 'sg_silhouette_depth', 0.01)) * 255),
),
+ return_diagnostics=True,
)
+ if guard_diagnostics["fallback_triggered"]:
+ print(
+ "[StableGen] WARNING: Projection guard fallback triggered "
+ f"for camera {camera_id}: depth/object/material IDs would "
+ f"leave only {guard_diagnostics['id_guard_allowed_foreground_percent']:.2f}% "
+ "of foreground writable; using depth-only guard "
+ f"({guard_diagnostics['allowed_foreground_percent']:.2f}% writable)."
+ )
+ else:
+ allowed = guard_diagnostics["allowed_foreground_percent"]
+ allowed_text = f"{allowed:.2f}%" if allowed is not None else "n/a"
+ print(
+ f"[StableGen] Projection guard camera {camera_id}: "
+ f"mode={guard_diagnostics['mode']}, "
+ f"foreground writable={allowed_text}."
+ )
guard_dir = get_dir_path(context, "inpaint")["visibility"]
os.makedirs(guard_dir, exist_ok=True)
guard_path = os.path.join(
@@ -2172,6 +2520,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
object_id_map=object_path if has_object_ids else None,
material_id_map=material_path if has_material_ids else None,
projection_guard=guard_path,
+ projection_guard_mode=guard_diagnostics["mode"],
+ projection_guard_fallback=guard_diagnostics["fallback_triggered"],
+ projection_guard_id_allowed_foreground_percent=guard_diagnostics[
+ "id_guard_allowed_foreground_percent"
+ ],
+ projection_guard_allowed_foreground_percent=guard_diagnostics[
+ "allowed_foreground_percent"
+ ],
)
bpy.context.scene.view_settings.view_transform = 'Standard'
@@ -2187,6 +2543,25 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
view_layer.use_pass_z = original_pass_z
def export_depthmap(self, context, camera_id=None):
+ use_legacy_depth = not any((
+ getattr(context.scene, 'sg_rework_safe_render_state', False),
+ getattr(context.scene, 'sg_rework_projection_guard', False),
+ getattr(context.scene, 'qwen_regularize_context_mask', False),
+ getattr(context.scene, 'sg_rework_consistent_frame', False),
+ ))
+ if use_legacy_depth:
+ # The reworked depth/ID exporter deliberately disables output
+ # dithering because categorical ID passes must remain exact. Some
+ # files produced while that path was active therefore retain a
+ # scene dither value of zero. The legacy Workbench exporter used
+ # Blender's default 1.0 dither, which changes roughly ten percent
+ # of 8-bit depth samples by one LSB and makes its PNGs materially
+ # larger. Normalize only the all-off compatibility call, then
+ # restore the user's scene value so old/new depth inputs are
+ # deterministic even when the source .blend was previously used
+ # with rework features.
+ with _legacy_render_dither(context.scene):
+ return self._export_depthmap_legacy(context, camera_id=camera_id)
meshes = [obj for obj in context.view_layer.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, meshes):
return self._export_depthmap_impl(context, camera_id=camera_id)
@@ -2199,6 +2574,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
:param camera_id: ID of the camera.
:return: None
"""
+ if not getattr(context.scene, 'sg_rework_safe_render_state', False):
+ with _legacy_render_dither(context.scene):
+ return self._export_normal_impl(context, camera_id=camera_id)
meshes = [obj for obj in context.view_layer.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, meshes):
return self._export_normal_impl(context, camera_id=camera_id)
@@ -2206,6 +2584,8 @@ 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)
output_dir = get_dir_path(context, "controlnet")["normal"]
output_file = f"normal_map{camera_id}" if camera_id is not None else "normal_map"
@@ -2234,6 +2614,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
node_tree = get_compositor_node_tree(bpy.context.scene)
nodes = node_tree.nodes
links = node_tree.links
+ compositor_state = _prepare_compositor_render(context.scene, node_tree)
# Create the Render Layers node (provides the baked normal pass).
render_layers_node = nodes.new(type="CompositorNodeRLayers")
@@ -2258,7 +2639,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
links.new(alpha_over_node.outputs[0], output_node.inputs[0])
links.new(render_layers_node.outputs["Alpha"], alpha_over_node.inputs[0])
- bpy.ops.render.render(write_still=True)
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ _finish_compositor_render(node_tree, compositor_state)
# Restore original settings.
bpy.context.scene.render.engine = original_engine
diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.py
index a72dc76..5bf9167 100644
--- a/stablegen/texturing/projection.py
+++ b/stablegen/texturing/projection.py
@@ -13,7 +13,11 @@ _SG_BUFFER_UV_NAME = "_SG_ProjectionBuffer"
def _is_projection_mesh(obj):
"""Consistent render/visibility filter for production geometry."""
- if obj.type != 'MESH' or obj.hide_get() or obj.hide_render:
+ if obj.type != 'MESH' or obj.hide_get():
+ return False
+ if not getattr(bpy.context.scene, 'sg_rework_projection_geometry', False):
+ return True
+ if obj.hide_render:
return False
if obj.get("sg_rig_helper", False) or obj.get("sg_exclude_texturing", False):
return False
@@ -78,11 +82,17 @@ def _ensure_lowpass_texture(image_path, sigma=8.0):
def _camera_world_location(camera):
"""Return camera position in world space (including parent transforms)."""
- return camera.matrix_world.translation.copy()
+ if getattr(bpy.context.scene, 'sg_rework_projection_geometry', False):
+ return camera.matrix_world.translation.copy()
+ return camera.location.copy()
def _scene_ray_epsilon(context):
"""Scale ray tolerances to the scene instead of assuming metre-sized assets."""
+ if not getattr(context.scene, 'sg_rework_projection_geometry', False):
+ # The legacy native graph used +0.01 ray length and +0.001 hit
+ # tolerance; callers multiply this base by ten for ray length.
+ return 0.001
corners = []
for obj in context.view_layer.objects:
if not _is_projection_mesh(obj):
@@ -185,7 +195,11 @@ def _bake_visibility_weights(
filmw = tan(fov / 2)
aspect = cam_res_x / cam_res_y
filmh = filmw / aspect
- camera_type = camera.data.type
+ camera_type = (
+ camera.data.type
+ if getattr(scene, 'sg_rework_projection_geometry', False)
+ else 'PERSP'
+ )
ortho_half_h = max(float(camera.data.ortho_scale) * 0.5, 1e-8)
ortho_half_w = ortho_half_h * aspect
@@ -194,24 +208,32 @@ def _bake_visibility_weights(
np.array(cam_dir, dtype=np.float64),
np.array(cam_right, dtype=np.float64),
np.array(cam_up_vec, dtype=np.float64),
- filmw, filmh, float(camera.data.shift_x), float(camera.data.shift_y),
+ filmw, filmh,
+ float(camera.data.shift_x) if getattr(scene, 'sg_rework_projection_geometry', False) else 0.0,
+ float(camera.data.shift_y) if getattr(scene, 'sg_rework_projection_geometry', False) else 0.0,
cam_loc, # keep mathutils Vector for BVH calls
camera_type, ortho_half_w, ortho_half_h,
))
# Build scene-wide BVH for occlusion (matches ShaderNodeRaycast behaviour,
# which checks ALL visible scene geometry, not just the current object).
- depsgraph = context.evaluated_depsgraph_get()
+ use_corrected_geometry = getattr(scene, 'sg_rework_projection_geometry', False)
+ depsgraph = context.evaluated_depsgraph_get() if use_corrected_geometry else None
scene_bm = bmesh.new()
vert_offset = 0
for scene_obj in context.view_layer.objects:
if not _is_projection_mesh(scene_obj):
continue
tmp = bmesh.new()
- evaluated_obj = scene_obj.evaluated_get(depsgraph)
- evaluated_mesh = evaluated_obj.to_mesh()
- tmp.from_mesh(evaluated_mesh)
- tmp.transform(evaluated_obj.matrix_world)
+ evaluated_obj = None
+ if use_corrected_geometry:
+ evaluated_obj = scene_obj.evaluated_get(depsgraph)
+ evaluated_mesh = evaluated_obj.to_mesh()
+ tmp.from_mesh(evaluated_mesh)
+ tmp.transform(evaluated_obj.matrix_world)
+ else:
+ tmp.from_mesh(scene_obj.data)
+ tmp.transform(scene_obj.matrix_world)
for v in tmp.verts:
scene_bm.verts.new(v.co)
scene_bm.verts.ensure_lookup_table()
@@ -223,7 +245,8 @@ def _bake_visibility_weights(
pass # skip degenerate / duplicate faces
vert_offset += len(tmp.verts)
tmp.free()
- evaluated_obj.to_mesh_clear()
+ if evaluated_obj is not None:
+ evaluated_obj.to_mesh_clear()
scene_bm.normal_update()
scene_tree = BVHTree.FromBMesh(scene_bm)
scene_bm.free()
@@ -233,17 +256,22 @@ def _bake_visibility_weights(
n_cameras = len(cameras)
for obj_idx, obj in enumerate(objects):
bm = bmesh.new()
- evaluated_obj = obj.evaluated_get(depsgraph)
- evaluated_mesh = evaluated_obj.to_mesh()
- if len(evaluated_mesh.vertices) == len(obj.data.vertices):
- source_mesh = evaluated_mesh
- source_matrix = evaluated_obj.matrix_world
+ evaluated_obj = None
+ if use_corrected_geometry:
+ evaluated_obj = obj.evaluated_get(depsgraph)
+ evaluated_mesh = evaluated_obj.to_mesh()
+ if len(evaluated_mesh.vertices) == len(obj.data.vertices):
+ source_mesh = evaluated_mesh
+ source_matrix = evaluated_obj.matrix_world
+ else:
+ print(
+ f"[StableGen] Warning: '{obj.name}' modifiers change vertex count; "
+ "visibility weights use the base mesh because POINT attributes "
+ "cannot be mapped safely to evaluated topology."
+ )
+ source_mesh = obj.data
+ source_matrix = obj.matrix_world
else:
- print(
- f"[StableGen] Warning: '{obj.name}' modifiers change vertex count; "
- "visibility weights use the base mesh because POINT attributes "
- "cannot be mapped safely to evaluated topology."
- )
source_mesh = obj.data
source_matrix = obj.matrix_world
bm.from_mesh(source_mesh)
@@ -255,7 +283,8 @@ def _bake_visibility_weights(
positions_np = np.array([v.co[:] for v in bm.verts], dtype=np.float64)
normals_np = np.array([v.normal[:] for v in bm.verts], dtype=np.float64)
bm.free()
- evaluated_obj.to_mesh_clear()
+ if evaluated_obj is not None:
+ evaluated_obj.to_mesh_clear()
for cam_idx, camera in enumerate(cameras):
print(f"[StableGen] Baking visibility: object {obj_idx+1}/{len(objects)}, "
@@ -335,7 +364,9 @@ def _bake_visibility_weights(
positions_np[vi] - cam_dir_np * (dists[vi] + ray_epsilon * 10.0)
)
hit_loc, _, _, hit_dist = scene_tree.ray_cast(
- ray_origin, d_mu, float(dists[vi]) + ray_epsilon * 20.0)
+ ray_origin, d_mu, float(dists[vi]) + ray_epsilon * (
+ 20.0 if getattr(scene, 'sg_rework_projection_geometry', False) else 10.0
+ ))
if hit_loc is not None and dists[vi] > hit_dist + ray_epsilon:
occluded[vi] = True
@@ -395,22 +426,27 @@ def _bake_visibility_weights(
+ offset_world
)
h_loc, _, _, h_dist = scene_tree.ray_cast(
- offset_origin, d_off_mu, dist_v + ray_epsilon * 20.0)
- scene_scale = _scene_projection_scale(context)
- relative_depth = getattr(scene, 'sg_silhouette_depth', 0.01)
- if camera_type == 'ORTHO':
- pixel_footprint = (
- (2.0 * ortho_half_w) / max(cam_res_x_n, 1)
- * max(silhouette_margin_px, 1)
+ offset_origin, d_off_mu, dist_v + ray_epsilon * (
+ 20.0 if getattr(scene, 'sg_rework_projection_geometry', False) else 10.0
+ ))
+ if getattr(scene, 'sg_rework_projection_geometry', False):
+ scene_scale = _scene_projection_scale(context)
+ relative_depth = getattr(scene, 'sg_silhouette_depth', 0.05)
+ if camera_type == 'ORTHO':
+ pixel_footprint = (
+ (2.0 * ortho_half_w) / max(cam_res_x_n, 1)
+ * max(silhouette_margin_px, 1)
+ )
+ else:
+ pixel_footprint = (
+ dist_v * rad_per_px * max(silhouette_margin_px, 1)
+ )
+ depth_thr = max(
+ scene_scale * relative_depth,
+ pixel_footprint * 0.5,
)
else:
- pixel_footprint = (
- dist_v * rad_per_px * max(silhouette_margin_px, 1)
- )
- depth_thr = max(
- scene_scale * relative_depth,
- pixel_footprint * 0.5,
- )
+ depth_thr = getattr(scene, 'sg_silhouette_depth', 0.05)
if h_loc is not None and dist_v > h_dist + depth_thr:
is_edge = True
break
@@ -646,7 +682,10 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,
shift_x_amount = nodes.new("ShaderNodeMath")
shift_x_amount.operation = 'MULTIPLY'
- shift_x_amount.inputs[1].default_value = 2.0 * float(camera.data.shift_x)
+ shift_x_amount.inputs[1].default_value = (
+ 2.0 * float(camera.data.shift_x)
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
links.new(filmw.outputs[0], shift_x_amount.inputs[0])
centered_x = nodes.new("ShaderNodeMath")
centered_x.operation = 'SUBTRACT'
@@ -655,7 +694,10 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,
shift_y_amount = nodes.new("ShaderNodeMath")
shift_y_amount.operation = 'MULTIPLY'
- shift_y_amount.inputs[1].default_value = 2.0 * float(camera.data.shift_y)
+ shift_y_amount.inputs[1].default_value = (
+ 2.0 * float(camera.data.shift_y)
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
links.new(filmh.outputs[0], shift_y_amount.inputs[0])
centered_y = nodes.new("ShaderNodeMath")
centered_y.operation = 'SUBTRACT'
@@ -935,7 +977,10 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_
shift_x_amount = nodes.new("ShaderNodeMath")
shift_x_amount.operation = 'MULTIPLY'
- shift_x_amount.inputs[1].default_value = 2.0 * float(camera.data.shift_x)
+ shift_x_amount.inputs[1].default_value = (
+ 2.0 * float(camera.data.shift_x)
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
links.new(filmw.outputs[0], shift_x_amount.inputs[0])
centered_x = nodes.new("ShaderNodeMath")
centered_x.operation = 'SUBTRACT'
@@ -944,7 +989,10 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_
shift_y_amount = nodes.new("ShaderNodeMath")
shift_y_amount.operation = 'MULTIPLY'
- shift_y_amount.inputs[1].default_value = 2.0 * float(camera.data.shift_y)
+ shift_y_amount.inputs[1].default_value = (
+ 2.0 * float(camera.data.shift_y)
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
links.new(filmh.outputs[0], shift_y_amount.inputs[0])
centered_y = nodes.new("ShaderNodeMath")
centered_y.operation = 'SUBTRACT'
@@ -1411,13 +1459,15 @@ def project_image(
# Replace weight_nodes with sharpened-normalised nodes
weight_nodes = powered_nodes
- use_confidence_ownership = (
+ # Binary Qwen write masks and per-texel ownership solve different
+ # problems. Write masks prevent a later generated view from writing
+ # protected context; ownership selects exactly one camera for
+ # high-frequency detail and therefore creates harder territories.
+ # Keep ownership genuinely opt-in so disabling the UI toggle
+ # restores continuous weighted blending without disabling Qwen's
+ # protection masks.
+ use_confidence_ownership = bool(
getattr(context.scene, 'sg_texel_ownership', False)
- or (
- context.scene.model_architecture == 'qwen_image_edit'
- and context.scene.generation_method == 'sequential'
- and getattr(context.scene, 'qwen_use_projection_write_masks', True)
- )
)
legacy_blend = getattr(
context.scene, 'sg_ownership_blend_mode', 'OWNER'
@@ -1442,7 +1492,9 @@ def project_image(
))
priority_strength = (
float(getattr(context.scene, 'early_priority_strength', 0.5))
- if getattr(context.scene, 'early_priority', False) else 0.0
+ if (getattr(context.scene, 'early_priority', False)
+ and getattr(context.scene, 'sg_rework_initial_view_priority', False))
+ else 0.0
)
owner_camera = nodes_collection.new("ShaderNodeValue")
@@ -1664,7 +1716,14 @@ def project_image(
vert_offset = -200 * (i // 2)
sum_node = nodes_collection.new("ShaderNodeMath")
sum_node.operation = 'ADD'
- sum_node.location = (x_offset - 600, y_offset + vert_offset)
+ legacy_priority = (
+ context.scene.early_priority
+ and not getattr(context.scene, 'sg_rework_initial_view_priority', False)
+ )
+ sum_node.location = (
+ (x_offset - 800, y_offset + vert_offset)
+ if legacy_priority else (x_offset - 600, y_offset + vert_offset)
+ )
def get_weight_output(w_item):
if isinstance(w_item, tuple):
@@ -1723,10 +1782,19 @@ def project_image(
# Compute mix factor: weight_A / (weight_A+weight_B)
div_node = nodes_collection.new("ShaderNodeMath")
div_node.operation = 'DIVIDE'
- div_node.location = (x_offset - 400, y_offset + vert_offset)
+ div_node.location = (
+ (x_offset - 600, y_offset + vert_offset)
+ if legacy_priority else (x_offset - 400, y_offset + vert_offset)
+ )
links.new(w_out_2, div_node.inputs[0])
links.new(sum_node.outputs[0], div_node.inputs[1])
+ if legacy_priority:
+ map_range_node = nodes_collection.new("ShaderNodeMapRange")
+ map_range_node.location = (x_offset - 400, y_offset + vert_offset)
+ map_range_node.inputs[1].default_value = context.scene.early_priority_strength
+ links.new(div_node.outputs[0], map_range_node.inputs[0])
+
# Create a MixRGB node for color blending of the two inputs
mix_node = nodes_collection.new("ShaderNodeMixRGB")
mix_node.location = (x_offset - 200, y_offset + vert_offset)
@@ -1735,7 +1803,8 @@ def project_image(
links.new(shaders[i].outputs[0], mix_node.inputs["Color1"])
links.new(shaders[i+1].outputs[0], mix_node.inputs["Color2"])
# Use the computed mix factor
- links.new(div_node.outputs[0], mix_node.inputs["Fac"])
+ to_connect = map_range_node if legacy_priority else div_node
+ links.new(to_connect.outputs[0], mix_node.inputs["Fac"])
new_shaders.append(mix_node)
# The new effective weight is the sum (stored in sum_node)
@@ -1844,7 +1913,8 @@ def project_image(
# ── Optional: bake per-vertex visibility weights ──────────────────
use_baked_weights = (
getattr(context.scene, 'bake_visibility_weights', False)
- or any(camera.data.type == 'ORTHO' for camera in cameras)
+ or (getattr(context.scene, 'sg_rework_projection_geometry', False)
+ and any(camera.data.type == 'ORTHO' for camera in cameras))
)
if use_baked_weights:
# Always compute weights for ALL cameras (ignore stop_index).
@@ -1930,11 +2000,80 @@ def project_image(
original_uv_map = obj.data.uv_layers[1]
- if not is_local_edit:
- # Rebuild deterministically at every sequential step. Later views
- # acquire write masks, projection guards, low-pass companions, and
- # ownership confidence only after generation; patching the old
- # graph left those inputs stale and could launder poor context.
+ rework_requires_rebuild = any((
+ 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_projection_write_masks', False),
+ getattr(context.scene, 'sg_rework_sdxl_registration', False),
+ ))
+ legacy_incremental_update = (
+ ((context.scene.generation_method == 'sequential' and stop_index > 0)
+ or context.scene.generation_mode == 'regenerate_selected')
+ and not rework_requires_rebuild
+ )
+
+ if legacy_incremental_update:
+ # Exact rigging-branch behavior: patch the newly generated image
+ # into the existing graph and remove that view's stop-index gate.
+ script_node = None
+ for node in nodes:
+ if ((node.type == 'SCRIPT'
+ or (node.type == 'MATH' and node.operation == 'MULTIPLY'))
+ and (node.label == f"Angle-{stop_index}-{mat_id}"
+ or node.label == f"{stop_index}-{mat_id}")):
+ script_node = node
+ break
+ # New feature nodes may sit between Angle and the temporary gate.
+ # Identify the gate explicitly and reconnect its actual input source;
+ # retaining the old direct-child search keeps old saved graphs valid.
+ stop_gate = next(
+ (node for node in nodes
+ if node.label == f"StopGate-{stop_index}-{mat_id}"),
+ None,
+ )
+ if stop_gate is None and script_node:
+ stop_gate = next(
+ (link.to_node for link in script_node.outputs[0].links
+ if link.to_node.type == 'MATH'
+ and link.to_node.operation == 'LESS_THAN'),
+ None,
+ )
+ if stop_gate is not None:
+ gate_source = (
+ stop_gate.inputs[0].links[0].from_socket
+ if stop_gate.inputs[0].links else None
+ )
+ gate_destinations = [
+ link.to_socket for link in stop_gate.outputs[0].links
+ ]
+ nodes.remove(stop_gate)
+ if gate_source is not None:
+ for output_socket in gate_destinations:
+ links.new(gate_source, output_socket)
+ for node in nodes:
+ if node.type == 'TEX_IMAGE' and node.label == f"{stop_index}-{mat_id}":
+ image_path = get_file_path(
+ context, "generated", camera_id=stop_index, material_id=mat_id
+ )
+ if ((context.scene.generation_method in ('sequential', 'separate'))
+ and context.scene.sequential_ipadapter
+ and context.scene.sequential_ipadapter_regenerate
+ and not context.scene.use_ipadapter
+ and stop_index == 0
+ and context.scene.sequential_ipadapter_mode == 'first'):
+ image_path = image_path.replace(".png", "_ipadapter.png")
+ image = get_or_load_image(
+ image_path,
+ force_reload=context.scene.overwrite_material,
+ )
+ if image:
+ node.image = image
+ break
+ continue
+ elif not is_local_edit:
+ # Rebuild mode is required for per-view assets that only exist
+ # after generation (write masks, guards, and ownership inputs).
# Clear existing nodes
for node in nodes:
nodes.remove(node)
@@ -2051,6 +2190,8 @@ def project_image(
def _create_projection_guard_weight(cam_index, mat_id_inner):
"""Sample per-pixel depth/object/material silhouette rejection."""
+ if not getattr(context.scene, 'sg_rework_projection_guard', False):
+ return None
guard_path = os.path.join(
get_dir_path(context, "inpaint")["visibility"],
f"projection_guard{cam_index}.png",
@@ -2109,7 +2250,8 @@ def project_image(
tex_image_nodes.append(tex_image)
lowpass_node = tex_image
- if (getattr(context.scene, 'sg_ownership_blend_mode', 'OWNER') == 'OWNER'
+ if (getattr(context.scene, 'sg_texel_ownership', False)
+ and getattr(context.scene, 'sg_ownership_blend_mode', 'OWNER') == 'OWNER'
and i <= stop_index and tex_image.image is not None):
source_path = bpy.path.abspath(tex_image.image.filepath)
lowpass_path = _ensure_lowpass_texture(
@@ -2172,6 +2314,7 @@ def project_image(
if i > stop_index and not voronoi_active:
less_than = nodes.new("ShaderNodeMath")
less_than.operation = 'LESS_THAN'
+ less_than.label = f"StopGate-{i}-{mat_id}"
less_than.location = (-100, (-800) * i)
less_than.inputs[1].default_value = -1
links.new(passthrough.outputs[0], less_than.inputs[0])
@@ -2217,7 +2360,8 @@ def project_image(
final_weight_node = (angle_weight, feather_weight)
else:
final_weight_node = angle_weight
- if (context.scene.generation_method == 'sequential'
+ if (getattr(context.scene, 'sg_rework_acquisition_quality', False)
+ and context.scene.generation_method == 'sequential'
and context.scene.visibility_vignette):
frame_weight = create_native_feather(
nodes, links, normalize_node, camera_fov_node,
@@ -2236,6 +2380,7 @@ def project_image(
if i > stop_index and not voronoi_active:
less_than = nodes.new("ShaderNodeMath")
less_than.operation = 'LESS_THAN'
+ less_than.label = f"StopGate-{i}-{mat_id}"
less_than.location = (-200, (-800) * i)
less_than.inputs[1].default_value = -1
source_node = final_weight_node[0] if isinstance(final_weight_node, tuple) else final_weight_node
@@ -2290,9 +2435,15 @@ def project_image(
if "RayEpsilon" in script_angle.inputs:
script_angle.inputs["RayEpsilon"].default_value = _scene_ray_epsilon(context)
if "CameraShiftX" in script_angle.inputs:
- script_angle.inputs["CameraShiftX"].default_value = camera.data.shift_x
+ script_angle.inputs["CameraShiftX"].default_value = (
+ camera.data.shift_x
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
if "CameraShiftY" in script_angle.inputs:
- script_angle.inputs["CameraShiftY"].default_value = camera.data.shift_y
+ script_angle.inputs["CameraShiftY"].default_value = (
+ camera.data.shift_y
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
script_angle.label = f"Angle-{i}-{mat_id}"
scripts_to_connect = [script_angle]
@@ -2331,9 +2482,15 @@ def project_image(
script_feather.inputs["EdgeGamma"].default_value = 1.0
script_feather.label = f"Feather-{i}-{mat_id}"
if "CameraShiftX" in script_feather.inputs:
- script_feather.inputs["CameraShiftX"].default_value = camera.data.shift_x
+ script_feather.inputs["CameraShiftX"].default_value = (
+ camera.data.shift_x
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
if "CameraShiftY" in script_feather.inputs:
- script_feather.inputs["CameraShiftY"].default_value = camera.data.shift_y
+ script_feather.inputs["CameraShiftY"].default_value = (
+ camera.data.shift_y
+ if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0
+ )
scripts_to_connect.append(script_feather)
# Optionally add edge-feather mask as third multiplier
@@ -2345,13 +2502,15 @@ def project_image(
final_weight_node = (script_angle, script_feather)
elif is_local_edit_mode:
final_weight_node = (script_angle, script_feather)
- else:
+ elif getattr(context.scene, 'sg_rework_acquisition_quality', False):
frame_quality = nodes.new("ShaderNodeMath")
frame_quality.operation = 'MULTIPLY'
frame_quality.label = f"FrameEdgeQuality-{i}-{mat_id}"
links.new(script_angle.outputs[0], frame_quality.inputs[0])
links.new(script_feather.outputs[0], frame_quality.inputs[1])
final_weight_node = frame_quality
+ else:
+ final_weight_node = script_angle
else:
# Just use Angle script output directly
final_weight_node = script_angle
@@ -2362,6 +2521,7 @@ def project_image(
# Connect a temporary less than node to the script node
less_than = nodes.new("ShaderNodeMath")
less_than.operation = 'LESS_THAN'
+ less_than.label = f"StopGate-{i}-{mat_id}"
less_than.location = (-200, (-800) * i)
less_than.inputs[1].default_value = -1
@@ -2423,7 +2583,8 @@ def project_image(
# Add projected pixel density to live native/OSL paths. Baked
# acquisition attributes already contain this term.
- if (not use_baked_weights and script_nodes_outputs
+ if (getattr(context.scene, 'sg_rework_acquisition_quality', False)
+ and not use_baked_weights and script_nodes_outputs
and not isinstance(script_nodes_outputs[-1], tuple)
and length_nodes[-1] is not None):
cam_res_x, cam_res_y = _get_camera_resolution(camera, context.scene)
@@ -2460,9 +2621,11 @@ def project_image(
and context.scene.generation_method == 'sequential'
and context.scene.qwen_generation_method == 'generate'
and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}
- and getattr(context.scene, 'qwen_use_projection_write_masks', True)
+ and getattr(context.scene, 'qwen_use_projection_write_masks', False)
)
use_sdxl_write_mask = (
+ getattr(context.scene, 'sg_rework_sdxl_registration', False)
+ and
i > 0
and i <= stop_index
and context.scene.model_architecture == 'sdxl'
@@ -2495,11 +2658,27 @@ def project_image(
if script_nodes_outputs and not isinstance(script_nodes_outputs[-1], tuple):
guard_weight = _create_projection_guard_weight(i, mat_id)
if guard_weight is not None:
+ # A projection guard marks depth/object/material boundaries
+ # as unsafe for ownership, but it must not delete the last
+ # available coverage. Complex character meshes can have
+ # dense ID boundaries around hair, facial parts, fingers,
+ # clothing openings, and adjacent mesh pieces. If every
+ # camera is hard-zeroed at the same surface point, the
+ # ownership graph falls through to the material's black
+ # fallback. Keep a tiny, untrusted confidence floor: safe
+ # views still beat it overwhelmingly, while the best weak
+ # source fills a texel only when no guarded source exists.
+ guard_floor = nodes.new("ShaderNodeMath")
+ guard_floor.operation = 'MAXIMUM'
+ guard_floor.inputs[1].default_value = 0.001
+ guard_floor.label = f"ProjectionGuardFloor-{i}-{mat_id}"
+ links.new(guard_weight.outputs[0], guard_floor.inputs[0])
+
guarded = nodes.new("ShaderNodeMath")
guarded.operation = 'MULTIPLY'
guarded.label = f"DepthPartGuarded-{i}-{mat_id}"
links.new(script_nodes_outputs[-1].outputs[0], guarded.inputs[0])
- links.new(guard_weight.outputs[0], guarded.inputs[1])
+ links.new(guard_floor.outputs[0], guarded.inputs[1])
script_nodes_outputs[-1] = guarded
# Build mix shader tree
diff --git a/stablegen/texturing/quality_masks.py b/stablegen/texturing/quality_masks.py
index f6a9cd8..9735f57 100644
--- a/stablegen/texturing/quality_masks.py
+++ b/stablegen/texturing/quality_masks.py
@@ -261,6 +261,7 @@ def build_depth_part_rejection_mask(
*,
margin=3,
depth_threshold=3,
+ return_diagnostics=False,
):
"""Build a per-pixel projection guard around depth/part silhouettes.
@@ -273,9 +274,21 @@ def build_depth_part_rejection_mask(
if depth.ndim == 3:
depth = cv2.cvtColor(depth, cv2.COLOR_BGR2GRAY)
depth = depth.astype(np.uint8)
+ margin = max(0, int(margin))
+ if margin == 0:
+ guard = np.full(depth.shape, 255, dtype=np.uint8)
+ diagnostics = {
+ "mode": "disabled",
+ "fallback_triggered": False,
+ "id_guard_allowed_foreground_percent": 100.0,
+ "allowed_foreground_percent": 100.0,
+ }
+ return (guard, diagnostics) if return_diagnostics else guard
kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
depth_range = cv2.dilate(depth, kernel3) - cv2.erode(depth, kernel3)
- edge = depth_range > max(0, int(depth_threshold))
+ depth_edge = depth_range > max(0, int(depth_threshold))
+ edge = depth_edge.copy()
+ used_part_ids = False
for ids in (object_ids, material_ids):
if ids is None:
@@ -287,13 +300,49 @@ def build_depth_part_rejection_mask(
ids, (depth.shape[1], depth.shape[0]), interpolation=cv2.INTER_NEAREST
)
edge |= cv2.dilate(ids, kernel3) != cv2.erode(ids, kernel3)
+ used_part_ids = True
- edge_u8 = np.where(edge, 255, 0).astype(np.uint8)
- margin = max(0, int(margin))
- if margin:
- size = margin * 2 + 1
- edge_u8 = cv2.dilate(
- edge_u8,
- cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size)),
+ def _guard_from_edges(edges):
+ edge_u8 = np.where(edges, 255, 0).astype(np.uint8)
+ if margin:
+ size = margin * 2 + 1
+ edge_u8 = cv2.dilate(
+ edge_u8,
+ cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size)),
+ )
+ return np.where(edge_u8 > 0, 0, 255).astype(np.uint8)
+
+ guard = _guard_from_edges(edge)
+
+ # Categorical render passes must be noise-free, but older outputs and
+ # third-party render settings can contain one-LSB dither. Treating that as
+ # real object/material boundaries expands rejection across virtually the
+ # whole character. If part IDs would leave less than 10% of foreground
+ # writable, retain the depth-discontinuity protection and discard the
+ # contaminated ID contribution instead of blacking out the texture.
+ foreground = depth > 1
+ diagnostics = {
+ "mode": "depth_part" if used_part_ids else "depth_only",
+ "fallback_triggered": False,
+ "id_guard_allowed_foreground_percent": None,
+ "allowed_foreground_percent": None,
+ }
+ if used_part_ids and np.any(foreground):
+ allowed_fraction = float(np.count_nonzero((guard > 0) & foreground)) / float(
+ np.count_nonzero(foreground)
+ )
+ diagnostics["id_guard_allowed_foreground_percent"] = allowed_fraction * 100.0
+ if allowed_fraction < 0.10:
+ guard = _guard_from_edges(depth_edge)
+ diagnostics["mode"] = "depth_only_fallback"
+ diagnostics["fallback_triggered"] = True
+
+ if np.any(foreground):
+ diagnostics["allowed_foreground_percent"] = (
+ float(np.count_nonzero((guard > 0) & foreground))
+ * 100.0 / float(np.count_nonzero(foreground))
)
- return np.where(edge_u8 > 0, 0, 255).astype(np.uint8)
+
+ if return_diagnostics:
+ return guard, diagnostics
+ return guard
diff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.py
index eb5ea59..ebb4090 100644
--- a/stablegen/texturing/rendering.py
+++ b/stablegen/texturing/rendering.py
@@ -13,6 +13,54 @@ import cv2
_ADDON_PKG = __package__.rsplit('.', 1)[0]
+@contextmanager
+def _legacy_render_dither(scene):
+ """Use Blender's legacy output dithering without mutating the scene."""
+ original = scene.render.dither_intensity
+ scene.render.dither_intensity = 1.0
+ try:
+ yield
+ finally:
+ scene.render.dither_intensity = original
+
+
+def _prepare_compositor_render(scene, node_tree):
+ """Isolate one render from stale compositor File Output nodes.
+
+ The legacy path cleared the compositor before every export. Transactional
+ mode preserves the user's graph instead, so its existing output nodes are
+ muted for the render and all nodes created by the export are removed by
+ ``_finish_compositor_render``.
+ """
+ nodes = node_tree.nodes
+ if not getattr(scene, 'sg_rework_safe_render_state', False):
+ nodes.clear()
+ return None
+ state = {
+ "pointers": {node.as_pointer() for node in nodes},
+ "muted_outputs": [],
+ }
+ for node in nodes:
+ if node.bl_idname == 'CompositorNodeOutputFile' and hasattr(node, 'mute'):
+ state["muted_outputs"].append((node, bool(node.mute)))
+ node.mute = True
+ return state
+
+
+def _finish_compositor_render(node_tree, state):
+ if state is None:
+ return
+ for node in list(node_tree.nodes):
+ if node.as_pointer() not in state["pointers"]:
+ node_tree.nodes.remove(node)
+ for node, was_muted in state["muted_outputs"]:
+ try:
+ if node.id_data is not None:
+ node.mute = was_muted
+ except ReferenceError:
+ pass
+
+
def _snapshot_material_state(obj):
"""Capture exact slot order, active slot, and per-polygon assignments."""
return {
@@ -112,6 +160,7 @@ class _RenderStateTransaction:
"resolution_x": render.resolution_x,
"resolution_y": render.resolution_y,
"resolution_percentage": render.resolution_percentage,
+ "dither_intensity": render.dither_intensity,
"image_file_format": render.image_settings.file_format,
"scene_use_nodes": scene.use_nodes,
"display_device": scene.display_settings.display_device,
@@ -199,6 +248,7 @@ class _RenderStateTransaction:
scene.render.resolution_x = state["resolution_x"]
scene.render.resolution_y = state["resolution_y"]
scene.render.resolution_percentage = state["resolution_percentage"]
+ scene.render.dither_intensity = state["dither_intensity"]
scene.render.image_settings.file_format = state["image_file_format"]
scene.use_nodes = state["scene_use_nodes"]
scene.display_settings.display_device = state["display_device"]
@@ -466,6 +516,7 @@ def _render_edge_feather_mask_impl(context, to_export, camera, camera_index, fea
node_tree = get_compositor_node_tree(context.scene)
comp_nodes = node_tree.nodes
comp_links = node_tree.links
+ compositor_state = _prepare_compositor_render(context.scene, node_tree)
render_layers = comp_nodes.new('CompositorNodeRLayers')
try:
mix_node = comp_nodes.new('CompositorNodeMixRGB')
@@ -485,7 +536,10 @@ def _render_edge_feather_mask_impl(context, to_export, camera, camera_index, fea
comp_links.new(mix_node.outputs[0], output_node.inputs[0])
# ── Render ──────────────────────────────────────────────────────────────
- bpy.ops.render.render(write_still=True)
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ _finish_compositor_render(node_tree, compositor_state)
# ── Determine actual output path ────────────────────────────────────────
frame_suffix = "0001" if bpy.app.version < (5, 0, 0) else ""
@@ -558,6 +612,11 @@ def _render_edge_feather_mask_impl(context, to_export, camera, camera_index, fea
def render_edge_feather_mask(context, to_export, camera, camera_index, feather_width=30, softness=1.0):
+ if not getattr(context.scene, 'sg_rework_safe_render_state', False):
+ return _render_edge_feather_mask_impl(
+ context, to_export, camera, camera_index,
+ feather_width=feather_width, softness=softness,
+ )
all_meshes = [obj for obj in context.scene.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, all_meshes):
return _render_edge_feather_mask_impl(
@@ -841,6 +900,8 @@ 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)
# Store original materials and create temporary ones
original_materials = {}
temporary_materials = {}
@@ -989,6 +1050,7 @@ def _export_emit_image_impl(context, to_export, camera_id=None, bg_color=(0.5, 0
node_tree = get_compositor_node_tree(context.scene)
nodes = node_tree.nodes
links = node_tree.links
+ compositor_state = _prepare_compositor_render(context.scene, node_tree)
# Create nodes
render_layers = nodes.new('CompositorNodeRLayers')
@@ -1012,7 +1074,10 @@ def _export_emit_image_impl(context, to_export, camera_id=None, bg_color=(0.5, 0
links.new(mix_node.outputs[0], output_node.inputs[0])
# Render
- bpy.ops.render.render(write_still=True)
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ _finish_compositor_render(node_tree, compositor_state)
# Post-processing for visibility masks
if "visibility" in str(camera_id):
@@ -1066,6 +1131,12 @@ def _export_emit_image_impl(context, to_export, camera_id=None, bg_color=(0.5, 0
def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard', fallback_color=(0,0,0)):
+ if not getattr(context.scene, 'sg_rework_safe_render_state', False):
+ with _legacy_render_dither(context.scene):
+ return _export_emit_image_impl(
+ context, to_export, camera_id=camera_id, bg_color=bg_color,
+ view_transform=view_transform, fallback_color=fallback_color,
+ )
with _RenderStateTransaction(context, to_export):
with _temporary_render_copies(context, to_export) as (copies, _mapping):
return _export_emit_image_impl(
@@ -1090,6 +1161,9 @@ 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)
+
# Setup output path
if output_dir is None:
output_dir = get_dir_path(context, "misc")
@@ -1128,13 +1202,17 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)
node_tree = get_compositor_node_tree(context.scene)
nodes = node_tree.nodes
links = node_tree.links
+ compositor_state = _prepare_compositor_render(context.scene, node_tree)
render_layers = nodes.new('CompositorNodeRLayers')
output_node = nodes.new('CompositorNodeOutputFile')
configure_output_node_paths(output_node, output_dir, output_file)
links.new(render_layers.outputs['Image'], output_node.inputs[0])
# Render
- bpy.ops.render.render(write_still=True)
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ _finish_compositor_render(node_tree, compositor_state)
# Restore original render settings
render_layer.use_pass_combined = original_combined
@@ -1150,6 +1228,11 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)
def export_render(context, camera_id=None, output_dir=None, filename=None):
+ if not getattr(context.scene, 'sg_rework_safe_render_state', False):
+ with _legacy_render_dither(context.scene):
+ return _export_render_impl(
+ context, camera_id=camera_id, output_dir=output_dir, filename=filename
+ )
objects = [obj for obj in context.view_layer.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, objects):
return _export_render_impl(
@@ -1256,6 +1339,11 @@ def _export_viewport_impl(context, camera_id=None, output_dir=None, filename=Non
def export_viewport(context, camera_id=None, output_dir=None, filename=None):
"""Viewport export with full scene-state restoration on every exit path."""
+ if not getattr(context.scene, 'sg_rework_safe_render_state', False):
+ with _legacy_render_dither(context.scene):
+ return _export_viewport_impl(
+ context, camera_id=camera_id, output_dir=output_dir, filename=filename
+ )
objects = [obj for obj in context.view_layer.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, objects):
return _export_viewport_impl(
@@ -1705,6 +1793,12 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None,
context, to_export, obj=obj, camera_visibility=camera_visibility,
prepare_only=True, camera_render=camera_render, camera_id=camera_id,
)
+ if not getattr(context.scene, 'sg_rework_safe_render_state', False):
+ with _legacy_render_dither(context.scene):
+ return _export_visibility_impl(
+ context, to_export, obj=obj, camera_visibility=camera_visibility,
+ prepare_only=False, camera_render=camera_render, camera_id=camera_id,
+ )
with _RenderStateTransaction(context, objects):
with _temporary_render_copies(context, objects) as (copies, mapping):
mapped_obj = mapping.get(obj) if obj is not None else None
diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.py
index 944ecbe..4c8909d 100644
--- a/stablegen/texturing/workflows.py
+++ b/stablegen/texturing/workflows.py
@@ -25,6 +25,16 @@ def _immutable_view_prompt(operator):
plan = getattr(operator, '_view_plan', ()) or ()
if 0 <= index < len(plan):
return plan[index].prompt or ""
+ # Legacy camera-prompt lookup when the canonical-plan experiment is off.
+ cameras = getattr(operator, '_cameras', ()) or ()
+ if 0 <= index < len(cameras):
+ camera_name = cameras[index].name
+ item = next(
+ (entry for entry in bpy.context.scene.camera_prompts
+ if entry.name == camera_name),
+ None,
+ )
+ return item.prompt if item and item.prompt else ""
return ""
@@ -65,11 +75,12 @@ def _generation_prompt(scene):
class _TexturingWorkflowMixin:
def _queue_prompt(self, prompt, client_id, server_address):
"""Validate every dynamically edited texturing graph at submission."""
- issues = validate_workflow_graph(prompt)
- if issues:
- message = "Invalid texturing workflow: " + "; ".join(issues)
- self.operator._error = message
- raise ValueError(message)
+ if getattr(bpy.context.scene, 'sg_rework_workflow_validation', False):
+ issues = validate_workflow_graph(prompt)
+ if issues:
+ message = "Invalid texturing workflow: " + "; ".join(issues)
+ self.operator._error = message
+ raise ValueError(message)
return super()._queue_prompt(prompt, client_id, server_address)
"""Texturing workflow methods for WorkflowManager."""
@@ -106,8 +117,20 @@ class _TexturingWorkflowMixin:
f"({len(img_bytes)} bytes): {e} — returning raw bytes.")
return img_bytes
- # Never crop here. The old fixed eight-pixel crop changed camera/image
- # registration and the projection transform was not updated.
+ if not getattr(bpy.context.scene, 'sg_rework_sdxl_registration', False):
+ # Rigging-branch behavior used a fixed eight-pixel crop regardless
+ # of the call-site default.
+ legacy_border = 8
+ width, height = img.size
+ if width > 2 * legacy_border and height > 2 * legacy_border:
+ img = img.crop((
+ legacy_border,
+ legacy_border,
+ width - legacy_border,
+ height - legacy_border,
+ ))
+ # Corrected mode never crops because projection registration is not
+ # adjusted for a changed image extent.
w, h = img.size
# Convert to numpy for mask math
@@ -554,30 +577,31 @@ class _TexturingWorkflowMixin:
# --- Reference Latent chain (Qwen unzoom fix) ---
self._build_qwen_reference_latent_chain(prompt, NODES)
- prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
- prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
- prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
- prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler
- prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler
- prompt[NODES['sampler']]['inputs']['denoise'] = 1.0
+ if getattr(context.scene, 'sg_rework_qwen_workflow', False):
+ prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
+ prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
+ prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
+ prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler
+ prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler
+ prompt[NODES['sampler']]['inputs']['denoise'] = 1.0
- if is_nunchaku:
- prompt[NODES['unet_loader']] = {
- "inputs": {
- "model_name": context.scene.model_name,
- "cpu_offload": "auto",
- "num_blocks_on_gpu": 1,
- "use_pin_memory": "enable",
- },
- "class_type": "NunchakuQwenImageDiTLoader",
- "_meta": {"title": "Nunchaku Qwen-Image DiT Loader"},
- }
- else:
- prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
+ if is_nunchaku:
+ prompt[NODES['unet_loader']] = {
+ "inputs": {
+ "model_name": context.scene.model_name,
+ "cpu_offload": "auto",
+ "num_blocks_on_gpu": 1,
+ "use_pin_memory": "enable",
+ },
+ "class_type": "NunchakuQwenImageDiTLoader",
+ "_meta": {"title": "Nunchaku Qwen-Image DiT Loader"},
+ }
+ else:
+ prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
- graph_issues = validate_workflow_graph(
+ graph_issues = (validate_workflow_graph(
prompt, (NODES['pos_prompt'], NODES['neg_prompt'])
- )
+ ) if getattr(context.scene, 'sg_rework_workflow_validation', False) else [])
if graph_issues:
self.operator._error = "Invalid Qwen refine workflow: " + "; ".join(graph_issues)
return {"error": "invalid_workflow"}
@@ -724,7 +748,11 @@ class _TexturingWorkflowMixin:
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# Case 1b: TRELLIS.2 input image as style (when no external style configured)
- elif getattr(context.scene, 'architecture_mode', '') == 'trellis2' and getattr(context.scene, 'qwen_use_trellis2_style', False):
+ trellis_style_branch = (
+ getattr(context.scene, 'architecture_mode', '') == 'trellis2'
+ and getattr(context.scene, 'qwen_use_trellis2_style', False)
+ )
+ if not use_external_this_frame and trellis_style_branch:
use_t2_this_frame = True
if not is_initial_image and getattr(context.scene, 'qwen_trellis2_style_initial_only', False):
# Initial-only mode: fall back to sequential style for subsequent frames
@@ -741,8 +769,19 @@ class _TexturingWorkflowMixin:
pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
- # Case 2: Sequential generation (after first image)
- if style_image_info is None and not is_initial_image:
+ # Case 2: Sequential generation (after first image). The rigging
+ # branch used an ``elif`` after the TRELLIS branch, so an enabled
+ # initial-only TRELLIS style did not fall through on later views.
+ # Preserve that quirk unless the corrected routing experiment is on.
+ if getattr(context.scene, 'sg_rework_qwen_workflow', False):
+ use_sequential_style = style_image_info is None and not is_initial_image
+ else:
+ use_sequential_style = (
+ not use_external_this_frame
+ and not trellis_style_branch
+ and not is_initial_image
+ )
+ if use_sequential_style:
if context_mode == 'REPLACE_STYLE':
# The context render becomes the style image
style_image_info = context_render_info
@@ -816,7 +855,11 @@ class _TexturingWorkflowMixin:
}
# Point text-encode image2 at the scaled version so both
# VL processing and the reference latent chain see ~1 MP.
- style_slot = qwen_style_semantic_slot(context_mode, is_initial_image)
+ style_slot = (
+ qwen_style_semantic_slot(context_mode, is_initial_image)
+ if getattr(context.scene, 'sg_rework_qwen_workflow', False)
+ else 'image2'
+ )
prompt[NODES['pos_prompt']]['inputs'][style_slot] = [scale_node_key, 0]
prompt[NODES['neg_prompt']]['inputs'][style_slot] = [scale_node_key, 0]
@@ -848,9 +891,9 @@ class _TexturingWorkflowMixin:
else:
prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
- graph_issues = validate_workflow_graph(
+ graph_issues = (validate_workflow_graph(
prompt, (NODES['pos_prompt'], NODES['neg_prompt'])
- )
+ ) if getattr(context.scene, 'sg_rework_workflow_validation', False) else [])
if graph_issues:
self.operator._error = "Invalid Qwen edit workflow: " + "; ".join(graph_issues)
return {"error": "invalid_workflow"}
@@ -2444,10 +2487,16 @@ class _TexturingWorkflowMixin:
prompt[NODES['mask_image']]["inputs"]["image"] = mask_info['name']
prompt[NODES['input_image']]["inputs"]["image"] = render_info['name']
- # One authoritative processed mask drives every inpaint consumer.
- final_mask = sdxl_final_mask_reference(context.scene.blur_mask, NODES)
- prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = final_mask
- prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = final_mask
+ if getattr(context.scene, 'sg_rework_sdxl_registration', False):
+ # One authoritative processed mask drives every inpaint consumer.
+ final_mask = sdxl_final_mask_reference(context.scene.blur_mask, NODES)
+ prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = final_mask
+ prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = final_mask
+ elif not context.scene.blur_mask:
+ # Exact pre-rework graph mutation. With blur enabled, retain
+ # the template's original mask links.
+ prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = [NODES['grow_mask'], 0]
+ prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = [NODES['grow_mask'], 0]
# Set blur parameters
prompt[NODES['blur']]["inputs"]["sigma"] = context.scene.blur_mask_sigma
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 8c24695..cd643d2 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -7,6 +7,7 @@ import math
from ..utils import sg_modal_active
from ..core import get_addon_prefs
from .presets import PRESETS, GEN_PARAMETERS
+from ..feature_flags import all_rework_features_disabled
from . import queue as _queue_mod
_ADDON_PKG = __package__.rsplit('.', 1)[0]
@@ -1309,16 +1310,7 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "sg_texel_ownership", text="Per-Texel View Ownership", toggle=True, icon="UV")
- ownership_active = (
- scene.sg_texel_ownership
- or (scene.model_architecture == 'qwen_image_edit'
- and scene.generation_method == 'sequential'
- and scene.qwen_use_projection_write_masks)
- )
- if ownership_active:
- if not scene.sg_texel_ownership:
- row = content_box.row()
- row.label(text="Enabled automatically for protected Qwen sequential projection", icon="INFO")
+ if scene.sg_texel_ownership:
row = content_box.row()
row.prop(scene, "sg_texel_replacement_margin", text="Replacement Margin")
row = content_box.row()
@@ -1357,6 +1349,35 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "sg_allow_backface_projection", text="Allow Backface Projection")
+ experiments = content_box.box()
+ experiments.label(text="Texturing Rework Experiments (all opt-in)", icon="EXPERIMENTAL")
+ status = experiments.row(align=True)
+ if all_rework_features_disabled(scene):
+ status.label(text="Legacy baseline active", icon="CHECKMARK")
+ else:
+ status.alert = True
+ status.label(text="One or more experiments active", icon="INFO")
+ status.operator(
+ "stablegen.reset_texturing_experiments",
+ text="Disable All",
+ icon="LOOP_BACK",
+ )
+ experiments.prop(scene, "sg_rework_camera_plan", text="Canonical Camera Plan", toggle=True)
+ experiments.prop(scene, "sg_rework_aligned_resolution", text="Improved Aligned Resolution", toggle=True)
+ experiments.prop(scene, "sg_rework_full_resolution_scale", text="Force 100% Guide Resolution", toggle=True)
+ experiments.prop(scene, "sg_rework_acquisition_quality", text="Acquisition Quality Weighting", toggle=True)
+ experiments.prop(scene, "sg_rework_initial_view_priority", text="Confidence-Aware Initial View Priority", toggle=True)
+ experiments.prop(scene, "sg_rework_projection_guard", text="Depth/Part Projection Guard", toggle=True)
+ experiments.prop(scene, "sg_rework_projection_rebuild", text="Rebuild Sequential Projection Graph", toggle=True)
+ experiments.prop(scene, "sg_rework_projection_geometry", text="Projection Geometry Corrections", toggle=True)
+ experiments.prop(scene, "sg_rework_consistent_frame", text="Consistent Texturing Frame", toggle=True)
+ experiments.prop(scene, "sg_rework_reset_controls", text="Corrected Angle/Exponent Reset", toggle=True)
+ experiments.prop(scene, "sg_rework_sdxl_registration", text="Corrected SDXL Mask Registration", toggle=True)
+ 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)
+ experiments.prop(scene, "sg_rework_final_display", text="Continuous Final Display Rebuild", toggle=True)
+
# --- Output & Material Settings ---
if _show_diffusion_sections:
content_box = draw_collapsible_section(advanced_params_box, "show_output_material_settings", "Output & Material Settings", icon="MATERIAL")
@@ -1624,32 +1645,65 @@ class StableGenPanel(bpy.types.Panel):
row = colors_box.row()
row.prop(scene, "qwen_guidance_fallback_color", text="Fallback")
- protection_row = context_box.row()
- protection_row.prop(
+ context_box.prop(
scene,
- "qwen_use_projection_write_masks",
- text="Protect Trusted Texture",
+ "qwen_use_confidence_context",
+ text="Confidence-Gated Context",
toggle=True,
- icon="LOCKED",
+ icon="MOD_MASK",
)
- if scene.qwen_use_projection_write_masks:
+ if scene.qwen_use_confidence_context:
threshold_row = context_box.row()
threshold_row.prop(
scene, "qwen_trust_threshold", text="Trusted Quality"
)
- tolerance_row = context_box.row()
- tolerance_row.prop(
+ context_box.prop(
+ scene,
+ "qwen_regularize_context_mask",
+ text="Regularize Context Boundary",
+ toggle=True,
+ )
+ if scene.qwen_regularize_context_mask:
+ regularize_box = context_box.box()
+ regularize_box.label(text="Binary Boundary Regularization")
+ regularize_box.prop(scene, "qwen_mask_min_island_area", text="Min Trusted Island")
+ regularize_box.prop(scene, "qwen_mask_min_hole_area", text="Min Repair Hole")
+ regularize_box.prop(scene, "qwen_mask_min_strip_width", text="Min Context Strip")
+ regularize_box.prop(scene, "qwen_mask_uncertainty_dilation", text="Uncertainty Dilate")
+ regularize_box.prop(scene, "qwen_mask_keep_largest_components", text="Largest Components")
+ else:
+ dilation_row = context_box.row()
+ dilation_row.prop(scene, "qwen_context_fallback_dilation", text="Legacy Fallback Dilate (px)")
+ cleanup_row = context_box.row()
+ cleanup_row.prop(scene, "qwen_context_cleanup", text="Legacy Cleanup", toggle=True, icon="BRUSH_DATA")
+ if scene.qwen_context_cleanup:
+ row = context_box.row()
+ row.prop(scene, "qwen_context_cleanup_hue_tolerance", text="Hue Tol (°)")
+ row = context_box.row()
+ row.prop(scene, "qwen_context_cleanup_value_adjust", text="Value Adjust")
+
+ protection_row = context_box.row()
+ protection_row.prop(
+ scene,
+ "qwen_use_projection_write_masks",
+ text="Restrict Projection to Write Mask",
+ toggle=True,
+ icon="LOCKED",
+ )
+ residual_row = context_box.row()
+ residual_row.prop(
+ scene,
+ "qwen_reject_residual_fallback",
+ text="Reject Residual Magenta",
+ toggle=True,
+ )
+ if scene.qwen_reject_residual_fallback:
+ row = context_box.row()
+ row.prop(
scene,
"qwen_residual_fallback_tolerance",
text="Residual Magenta Tol.",
)
- regularize_box = context_box.box()
- regularize_box.label(text="Binary Boundary Regularization")
- regularize_box.prop(scene, "qwen_mask_min_island_area", text="Min Trusted Island")
- regularize_box.prop(scene, "qwen_mask_min_hole_area", text="Min Repair Hole")
- regularize_box.prop(scene, "qwen_mask_min_strip_width", text="Min Context Strip")
- regularize_box.prop(scene, "qwen_mask_uncertainty_dilation", text="Uncertainty Dilate")
- regularize_box.prop(scene, "qwen_mask_keep_largest_components", text="Largest Components")
elif scene.model_architecture == 'sdxl' or scene.model_architecture == 'flux1':
# IPAdapter Parameters
diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.py
index a403079..05a22c9 100644
--- a/stablegen/ui/presets.py
+++ b/stablegen/ui/presets.py
@@ -4,6 +4,7 @@ import math
import bpy # pylint: disable=import-error
import mathutils # pylint: disable=import-error
from ..utils import sg_modal_active
+from ..feature_flags import TEXTURING_REWORK_DEFAULTS
PRESETS = {
"DEFAULT": {"description": "Default settings for general purpose generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "hm-mvgd-hm", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "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, "pbr_decomposition": False, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
@@ -38,6 +39,11 @@ 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}]},
}
+# 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.
+EXPERIMENTAL_FEATURE_DEFAULTS = dict(TEXTURING_REWORK_DEFAULTS)
+
# Global list of all generation parameter names to check for a preset.
GEN_PARAMETERS = [
"control_after_generate",
@@ -95,6 +101,21 @@ GEN_PARAMETERS = [
"sg_anchor_camera",
"sg_texturing_frame",
"sg_freeze_ownership_after_generation",
+ "sg_rework_camera_plan",
+ "sg_rework_aligned_resolution",
+ "sg_rework_full_resolution_scale",
+ "sg_rework_safe_render_state",
+ "sg_rework_reset_controls",
+ "sg_rework_sdxl_registration",
+ "sg_rework_acquisition_quality",
+ "sg_rework_initial_view_priority",
+ "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",
"differential_diffusion",
"differential_noise",
"blur_mask",
@@ -120,7 +141,10 @@ GEN_PARAMETERS = [
"qwen_context_cleanup_hue_tolerance",
"qwen_context_cleanup_value_adjust",
"qwen_context_fallback_dilation",
+ "qwen_use_confidence_context",
+ "qwen_regularize_context_mask",
"qwen_use_projection_write_masks",
+ "qwen_reject_residual_fallback",
"qwen_trust_threshold",
"qwen_mask_min_island_area",
"qwen_mask_min_hole_area",
@@ -404,6 +428,22 @@ class ResetQwenPrompt(bpy.types.Operator):
self.report({'INFO'}, "Prompt reset to default.")
return {'FINISHED'}
+
+class ResetTexturingExperiments(bpy.types.Operator):
+ """Restore the explicit rigging-branch compatibility baseline."""
+
+ bl_idname = "stablegen.reset_texturing_experiments"
+ bl_label = "Disable All Texturing Experiments"
+ bl_description = "Set every texturing rework feature to its legacy-compatible default"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ def execute(self, context):
+ for name, default in TEXTURING_REWORK_DEFAULTS.items():
+ if hasattr(context.scene, name):
+ setattr(context.scene, name, default)
+ self.report({'INFO'}, "All texturing experiments disabled; legacy baseline active")
+ return {'FINISHED'}
+
class ApplyPreset(bpy.types.Operator):
"""Apply selected preset values to parameters"""
bl_idname = "stablegen.apply_preset"
@@ -418,6 +458,11 @@ class ApplyPreset(bpy.types.Operator):
preset = context.scene.stablegen_preset
if preset in PRESETS:
values = PRESETS[preset]
+
+ if not values.get("custom", False):
+ for key, value in EXPERIMENTAL_FEATURE_DEFAULTS.items():
+ if hasattr(context.scene, key):
+ setattr(context.scene, key, value)
# Apply architecture_mode first so dynamic enums that
# depend on it (e.g. sequential_ipadapter_mode) are valid