Skip to content

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

rework sequential texturing confidence pipeline

sakalonde3f085f41a91
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index cde13bc..623e470 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -782,6 +782,11 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
"Prevents thin outlines of foreground geometry (e.g. hands) bleeding onto surfaces behind them. 0 = disabled",
default=3, min=0, max=20, update=update_parameters,
)
+ 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,
+ )
bpy.types.Scene.sg_silhouette_depth = bpy.props.FloatProperty(
name="Silhouette Depth",
description="Minimum depth difference (Blender units) between the vertex and an offset ray hit to consider it a silhouette edge. Raise if too much is eroded, lower if outlines remain",
@@ -1130,6 +1135,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_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
+ )
+ bpy.types.Scene.qwen_residual_fallback_tolerance = bpy.props.IntProperty(
+ name="Residual Fallback Tolerance",
+ description="RGB distance used only inside the known repair mask to reject magenta pixels left by Qwen",
+ default=8, min=0, max=64, update=update_parameters
+ )
bpy.types.Scene.qwen_prompt_gray_background = bpy.props.BoolProperty(
name="Gray Background Prompt",
description="Include 'Replace the background with solid gray' in the default context-render prompt. Disable to let the model choose the background freely",
@@ -1212,15 +1227,25 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
default='standard', update=update_parameters
)
bpy.types.Scene.early_priority_strength = bpy.props.FloatProperty(
- name="Prioritize Initial Views",
- description="Strength of the priority applied to initial views. Higher values will make the earlier cameras more important than the later ones. Every view will be prioritized over the next one.\n - Very high values may cause various artifacts.",
+ name="Priority Strength",
+ description="Strength of the bounded global camera-rank prior. At maximum strength the final view receives one quarter of the first view's prior before confidence normalization",
default=0.5, min=0.0, max=1.0, update=update_parameters
)
bpy.types.Scene.early_priority = bpy.props.BoolProperty(
- name="Priority Strength",
- description="Enable blending priority for earlier cameras.\n - This may prevent artifacts caused by later cameras overwriting earlier ones.\n - You will have to place the important cameras first.",
+ name="Prioritize Initial Views",
+ description="Apply a predictable global rank prior so earlier cameras win close confidence decisions. Put detail-critical cameras first",
+ default=False, update=update_parameters
+ )
+ bpy.types.Scene.sg_texel_ownership = bpy.props.BoolProperty(
+ name="Per-Texel View Ownership",
+ description="Select one camera per surface point and keep its detail until a later camera has meaningfully higher confidence. This creates harder camera boundaries than weighted blending",
default=False, update=update_parameters
)
+ bpy.types.Scene.sg_texel_replacement_margin = bpy.props.FloatProperty(
+ name="Ownership Replacement Margin",
+ description="Extra confidence a later camera needs before replacing the current per-texel owner",
+ default=0.05, min=0.0, max=1.0, update=update_parameters
+ )
bpy.types.Scene.texture_objects = bpy.props.EnumProperty(
name="Objects to Texture", description="Select the objects to texture",
items=[
@@ -1828,6 +1853,8 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'visibility_vignette', 'visibility_vignette_width', 'visibility_vignette_softness',
'visibility_vignette_blur',
'sg_silhouette_margin', 'sg_silhouette_depth', 'sg_silhouette_rays',
+ 'sg_allow_backface_projection',
+ 'sg_texel_ownership', 'sg_texel_replacement_margin',
'refine_angle_ramp_active', 'refine_angle_ramp_pos_0', 'refine_angle_ramp_pos_1',
'refine_feather_ramp_pos_0', 'refine_feather_ramp_pos_1',
'refine_edge_feather_projection', 'refine_edge_feather_width', 'refine_edge_feather_softness',
@@ -1859,6 +1886,7 @@ 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_projection_write_masks', 'qwen_residual_fallback_tolerance',
'qwen_prompt_gray_background',
]
for prop in _simple_scene_props:
diff --git a/stablegen/raycast.osl b/stablegen/raycast.osl
index 2fdd469..0dcf86a 100644
--- a/stablegen/raycast.osl
+++ b/stablegen/raycast.osl
@@ -9,6 +9,8 @@ shader raycast(
vector CameraUp = vector(0,1,0), // Camera up vector in world space
float AngleThreshold = 90.0, // Maximum angle in degrees between ray and normal
float Power = 4.0, // Exponent for weight falloff (higher = sharper)
+ float AllowBackface = 0.0, // Non-zero preserves legacy two-sided projection
+ float RayEpsilon = 0.001, // Scene-scale occlusion tolerance
output float Result = 0
)
{
@@ -50,11 +52,16 @@ shader raycast(
if (trace(Origin, d))
{
getmessage("trace", "hitdist", Distance);
- if ((Distance + 0.001) < threshold)
+ if ((Distance + RayEpsilon) < threshold)
Result = 0;
else {
float dot_val = dot(d, normalize(SurfaceNormal));
- float orthogonality = abs(clamp(dot_val, -1.0, 1.0));
+ float clamped_dot = clamp(dot_val, -1.0, 1.0);
+ // Direction is camera -> surface, so front-facing outward normals
+ // have a negative dot product.
+ float orthogonality = AllowBackface != 0.0
+ ? abs(clamped_dot)
+ : max(-clamped_dot, 0.0);
float angle = acos(orthogonality) * 180.0 / M_PI;
if (angle > AngleThreshold) {
Result = 0;
diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.py
index c74a973..55e0336 100644
--- a/stablegen/texturing/generator.py
+++ b/stablegen/texturing/generator.py
@@ -27,13 +27,19 @@ from ..util.workflow_templates import prompt_text, prompt_text_img2img, prompt_t
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
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
+from .projection import project_image, reinstate_compare_nodes, _bake_visibility_weights
from ..utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs, get_compositor_node_tree, configure_output_node_paths, get_eevee_engine_id, sg_modal_active
from ..util.mirror_color import MirrorReproject, _get_viewport_ref_np, _apply_color_match_to_file
from ..timeout_config import get_timeout
from .._generator_utils import redraw_ui, setup_studio_lighting, _pbr_setup_studio_lights, upload_image_to_comfyui
from .pbr import _PBRMixin
from .gallery import _PreviewGalleryOverlay
+from .view_plan import ViewRecord, choose_aligned_resolution, order_cameras
+from .quality_masks import (
+ apply_binary_context_mask,
+ regularize_repair_mask,
+ reject_fallback_from_write_mask,
+)
import websocket
@@ -346,6 +352,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
_active_ws = None # WebSocket reference for cancel-time close
_threads_left = 0
_cameras = None
+ _view_plan = None
_selected_camera_ids = None
_grid_width = 0
_grid_height = 0
@@ -420,6 +427,63 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
background = tuple(context.scene.qwen_guidance_background_color)
return fallback, background
+ 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):
+ return
+ if context.scene.qwen_context_render_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}:
+ return
+
+ context_path = get_file_path(
+ context, "inpaint", subtype="render", camera_id=camera_id
+ )
+ mask_path = get_file_path(
+ context, "inpaint", subtype="visibility", camera_id=camera_id
+ )
+ context_image = cv2.imread(context_path, cv2.IMREAD_COLOR)
+ repair_mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
+ if context_image is None or repair_mask is None:
+ print(f"[StableGen] Binary Qwen context skipped; missing context or mask for camera {camera_id}")
+ return
+
+ repair_mask = regularize_repair_mask(
+ repair_mask,
+ threshold=127,
+ dilation=context.scene.qwen_context_fallback_dilation,
+ )
+ context_image = apply_binary_context_mask(
+ context_image, repair_mask, fallback_color
+ )
+ cv2.imwrite(context_path, context_image)
+ cv2.imwrite(mask_path, repair_mask)
+
+ # These files are generated immediately before their first upload, but
+ # invalidate defensively for regeneration/debug workflows.
+ if hasattr(self, '_uploaded_images_cache'):
+ self._uploaded_images_cache.pop(context_path, None)
+ self._uploaded_images_cache.pop(mask_path, None)
+
+ 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):
+ return
+ if context.scene.qwen_context_render_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}:
+ return
+ mask_path = get_file_path(
+ context, "inpaint", subtype="visibility", camera_id=camera_id
+ )
+ write_mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
+ generated = cv2.imread(image_path, cv2.IMREAD_COLOR)
+ if write_mask is None or generated is None:
+ return
+ write_mask = reject_fallback_from_write_mask(
+ write_mask,
+ generated,
+ fallback_color,
+ tolerance=getattr(context.scene, "qwen_residual_fallback_tolerance", 8),
+ )
+ cv2.imwrite(mask_path, write_mask)
+
@classmethod
def poll(cls, context):
if cls._is_running:
@@ -515,12 +579,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
lower_bound = int(target_px * 0.8)
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)):
- scale_factor = (target_px / total_pixels) ** 0.5
- render.resolution_x = int(resolution_x * scale_factor)
- render.resolution_y = int(resolution_y * scale_factor)
- # Round down to nearest multiple of align_step
- render.resolution_x -= render.resolution_x % align_step
- render.resolution_y -= render.resolution_y % align_step
+ render.resolution_x, render.resolution_y = choose_aligned_resolution(
+ resolution_x, resolution_y, target_px, align_step
+ )
self.report({'INFO'}, f"Resolution automatically rescaled to {render.resolution_x}x{render.resolution_y}.")
elif total_pixels > upper_bound:
@@ -537,22 +598,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
render.resolution_x = self._original_resolution_x
render.resolution_y = self._original_resolution_y
return {'CANCELLED'}
- # Sort cameras by name
- self._cameras.sort(key=lambda x: x.name)
-
- # Apply custom generation order if enabled (non-destructive reorder)
+ 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]
- cam_by_name = {cam.name: cam for cam in self._cameras}
- ordered = []
- for name in order_names:
- if name in cam_by_name:
- ordered.append(cam_by_name.pop(name))
- # Append any cameras not in the order list (newly added cameras)
- for cam in self._cameras:
- if cam.name in cam_by_name:
- ordered.append(cam)
- self._cameras = ordered
+ self._cameras = order_cameras(self._cameras, order_names)
# Hide crop and label overlays during generation
_sg_remove_crop_overlay()
@@ -565,13 +614,35 @@ 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):
- sf = (target_px / c_total) ** 0.5
- crx = int(crx * sf)
- cry = int(cry * sf)
- crx -= crx % align_step
- cry -= cry % align_step
+ crx, cry = choose_aligned_resolution(
+ crx, cry, target_px, align_step
+ )
cam["sg_res_x"] = crx
cam["sg_res_y"] = cry
+
+ self._view_plan = []
+ 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))
+ self._view_plan.append(ViewRecord(
+ view_id=str(cam["sg_view_uuid"]),
+ index=index,
+ name=cam.name,
+ camera=cam,
+ resolution_x=cam_res_x,
+ resolution_y=cam_res_y,
+ ))
+
+ revision_dir = get_generation_dirs(context)["revision"]
+ os.makedirs(revision_dir, exist_ok=True)
+ with open(os.path.join(revision_dir, "view_plan.json"), "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
@@ -862,17 +933,66 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
continue
nodes = obj.active_material.node_tree.nodes
+ has_normalized_sharpness = any(
+ node.type == 'MATH'
+ and node.operation == 'POWER'
+ and node.label.startswith('SharpW-')
+ for node in nodes
+ )
for node in nodes:
- # OSL script nodes: update 'Power' input
- if node.type == 'SCRIPT':
- if 'Power' in node.inputs:
- node.inputs['Power'].default_value = new_exponent
- # Native MATH POWER nodes (Blender 5.1+ native path)
- elif node.type == 'MATH' and node.operation == 'POWER' and node.label == 'power_weight':
+ if (node.type == 'MATH'
+ and node.operation == 'POWER'
+ and node.label.startswith('SharpW-')):
node.inputs[1].default_value = new_exponent
+ elif node.type == 'SCRIPT' and 'Power' in node.inputs:
+ # Normalized materials sharpen at SharpW; their
+ # per-camera source must remain the base weight.
+ node.inputs['Power'].default_value = (
+ 1.0 if has_normalized_sharpness else new_exponent
+ )
+ elif (node.type == 'MATH'
+ and node.operation == 'POWER'
+ and node.label == 'power_weight'):
+ node.inputs[1].default_value = (
+ 1.0 if has_normalized_sharpness else new_exponent
+ )
+ elif (node.type == 'MATH'
+ and node.operation == 'MULTIPLY'
+ and node.label.startswith('InitialViewPrior-')
+ and "sg_desired_prior" in node):
+ node.inputs[1].default_value = float(
+ node["sg_desired_prior"]
+ ) ** (1.0 / max(float(new_exponent), 1e-6))
print("[StableGen] Weight exponent reset complete.")
+ # Baked visibility stores the angle/exponent numerically in
+ # mesh attributes, so changing shader nodes alone cannot reset
+ # it. Recompute once using the final display settings.
+ reset_angle = (
+ context.scene.discard_factor_after_generation
+ if context.scene.discard_factor_generation_only
+ else context.scene.discard_factor
+ )
+ reset_exponent = (
+ context.scene.weight_exponent_after_generation
+ if context.scene.weight_exponent_generation_only
+ else context.scene.weight_exponent
+ )
+ if (context.scene.bake_visibility_weights
+ and (context.scene.discard_factor_generation_only
+ or context.scene.weight_exponent_generation_only)
+ and self._cameras):
+ print("[StableGen] Rebaking visibility weights for final display settings...")
+ _bake_visibility_weights(
+ context,
+ self._to_texture,
+ self._cameras,
+ self._material_id,
+ angle_threshold=reset_angle,
+ power_exponent=reset_exponent,
+ )
+
# If viewport rendering mode is 'Rendered' and mode is 'regenerate_selected', switch to 'Solid' and then back to 'Rendered' to refresh the viewport
if context.scene.generation_mode == 'regenerate_selected' and context.area.spaces.active.shading.type == 'RENDERED':
context.area.spaces.active.shading.type = 'SOLID'
@@ -1151,7 +1271,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def image_reproject_callback():
try:
redraw_ui(context)
- project_image(context, self._to_texture, self._material_id, stop_index=self._current_image)
+ project_image(
+ context, self._to_texture, self._material_id,
+ stop_index=self._current_image, cameras=self._cameras,
+ )
except Exception as e:
self._error = str(e)
traceback.print_exc()
@@ -1255,13 +1378,24 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
_vis_cam = self._cameras[self._current_image - 1]
_cur_cam = self._cameras[self._current_image] if self._current_image < len(self._cameras) else _vis_cam
with _SGCameraResolution(context, _cur_cam):
- export_visibility(context, self._to_texture, camera_visibility=_vis_cam) # Export mask for current view
+ 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
+ context.scene.camera = _emit_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._dilate_qwen_context_fallback(context, self._current_image, fallback_color)
+ self._apply_qwen_binary_context_mask(
+ 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))
@@ -1321,6 +1455,17 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
with open(image_path, 'wb') as f:
f.write(image)
+ if (context.scene.model_architecture == 'qwen_image_edit'
+ and context.scene.generation_method == 'sequential'
+ and self._current_image > 0):
+ fallback_color, _ = self._get_qwen_context_colors(context)
+ self._reject_qwen_fallback_writes(
+ context,
+ self._current_image,
+ image_path,
+ fallback_color,
+ )
+
# Use hack to re-generate the image using IPAdapter to match IPAdapter style
if camera_id == 0 and (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate' or context.scene.generation_method in ('refine', 'local_edit'))\
@@ -1357,7 +1502,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
def image_project_callback():
try:
redraw_ui(context)
- project_image(context, self._to_texture, self._material_id, stop_index=self._current_image)
+ project_image(
+ context, self._to_texture, self._material_id,
+ stop_index=self._current_image, cameras=self._cameras,
+ )
except Exception as e:
self._error = str(e)
traceback.print_exc()
@@ -1499,7 +1647,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._stage = "Projecting Image"
redraw_ui(context)
if context.scene.generation_method != 'uv_inpaint':
- project_image(context, self._to_texture, self._material_id)
+ project_image(
+ context, self._to_texture, self._material_id,
+ cameras=self._cameras,
+ )
else:
# Apply the UV inpainted textures to each mesh
from .rendering import apply_uv_inpaint_texture
diff --git a/stablegen/texturing/graph_validation.py b/stablegen/texturing/graph_validation.py
new file mode 100644
index 0000000..bbc83ae
--- /dev/null
+++ b/stablegen/texturing/graph_validation.py
@@ -0,0 +1,61 @@
+"""Pure validation helpers for dynamically edited ComfyUI workflow graphs."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+
+
+def _is_node_reference(value) -> bool:
+ return (
+ isinstance(value, list)
+ and len(value) == 2
+ and isinstance(value[0], (str, int))
+ and isinstance(value[1], int)
+ )
+
+
+def validate_workflow_graph(prompt: Mapping, semantic_node_ids=()) -> list[str]:
+ """Return graph errors without changing the workflow.
+
+ Checks every ComfyUI link target and, for Qwen text encoders, verifies
+ that image slots are consistent and do not accidentally alias one another.
+ """
+ issues: list[str] = []
+ node_ids = {str(node_id) for node_id in prompt}
+ for node_id, node in prompt.items():
+ for input_name, value in node.get("inputs", {}).items():
+ if _is_node_reference(value) and str(value[0]) not in node_ids:
+ issues.append(
+ f"node {node_id} input {input_name} references missing node {value[0]}"
+ )
+
+ semantic_refs = {}
+ for node_id in semantic_node_ids:
+ node = prompt.get(str(node_id))
+ if node is None:
+ issues.append(f"semantic text encoder node {node_id} is missing")
+ continue
+ inputs = node.get("inputs", {})
+ slots = {
+ key: tuple(inputs[key])
+ for key in ("image1", "image2", "image3")
+ if key in inputs and _is_node_reference(inputs[key])
+ }
+ reverse = {}
+ for slot, reference in slots.items():
+ reverse.setdefault(reference, []).append(slot)
+ for reference, aliases in reverse.items():
+ if len(aliases) > 1:
+ issues.append(
+ f"semantic node {node_id} aliases {', '.join(aliases)} to {reference[0]}"
+ )
+ semantic_refs[str(node_id)] = slots
+
+ if len(semantic_refs) > 1:
+ reference_slots = next(iter(semantic_refs.values()))
+ for node_id, slots in list(semantic_refs.items())[1:]:
+ if slots != reference_slots:
+ issues.append(
+ f"semantic image slots differ between text encoders and node {node_id}"
+ )
+ return issues
diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.py
index 25d177e..b01e9fc 100644
--- a/stablegen/texturing/projection.py
+++ b/stablegen/texturing/projection.py
@@ -11,6 +11,33 @@ from mathutils import Vector
_SG_BUFFER_UV_NAME = "_SG_ProjectionBuffer"
+def _camera_world_location(camera):
+ """Return camera position in world space (including parent transforms)."""
+ return camera.matrix_world.translation.copy()
+
+
+def _scene_ray_epsilon(context):
+ """Scale ray tolerances to the scene instead of assuming metre-sized assets."""
+ corners = []
+ for obj in context.view_layer.objects:
+ if obj.type != 'MESH' or obj.hide_get():
+ continue
+ corners.extend(obj.matrix_world @ Vector(corner) for corner in obj.bound_box)
+ if not corners:
+ return 1e-5
+ min_corner = Vector((
+ min(point.x for point in corners),
+ min(point.y for point in corners),
+ min(point.z for point in corners),
+ ))
+ max_corner = Vector((
+ max(point.x for point in corners),
+ max(point.y for point in corners),
+ max(point.z for point in corners),
+ ))
+ return max((max_corner - min_corner).length * 1e-5, 1e-7)
+
+
def _copy_uv_to_attribute(obj, uv_layer_name, attr_name):
"""Copy UV data from a UV layer to a named FLOAT_VECTOR corner-domain attribute.
Uses FLOAT_VECTOR (3-component) instead of FLOAT2 so the attribute does NOT
@@ -37,7 +64,15 @@ def _copy_uv_to_attribute(obj, uv_layer_name, attr_name):
obj.data.update()
-def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=1000000):
+def _bake_visibility_weights(
+ context,
+ objects,
+ cameras,
+ mat_id,
+ stop_index=1000000,
+ angle_threshold=None,
+ power_exponent=None,
+):
"""Pre-compute per-vertex, per-camera visibility weights and store them
as ``FLOAT`` ``POINT``-domain mesh attributes.
@@ -57,8 +92,12 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
from math import pow as fpow
scene = context.scene
- angle_threshold = scene.discard_factor # degrees
- power_exponent = scene.weight_exponent
+ angle_threshold = (
+ scene.discard_factor if angle_threshold is None else angle_threshold
+ )
+ power_exponent = (
+ scene.weight_exponent if power_exponent is None else power_exponent
+ )
feather_active = scene.visibility_vignette
feather_width = scene.visibility_vignette_width if feather_active else 0.0
feather_gamma = scene.visibility_vignette_softness if feather_active else 1.0
@@ -67,7 +106,7 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
# Pre-compute camera data once -----------------------------------------------
cam_data = []
for camera in cameras:
- cam_loc = camera.location.copy()
+ cam_loc = _camera_world_location(camera)
quat = camera.matrix_world.to_quaternion()
cam_dir = quat @ Vector((0, 0, -1))
cam_up = quat @ Vector((0, 1, 0))
@@ -93,14 +132,17 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
# 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()
scene_bm = bmesh.new()
vert_offset = 0
for scene_obj in context.view_layer.objects:
if scene_obj.type != 'MESH' or scene_obj.hide_get():
continue
tmp = bmesh.new()
- tmp.from_mesh(scene_obj.data)
- tmp.transform(scene_obj.matrix_world)
+ evaluated_obj = scene_obj.evaluated_get(depsgraph)
+ evaluated_mesh = evaluated_obj.to_mesh()
+ tmp.from_mesh(evaluated_mesh)
+ tmp.transform(evaluated_obj.matrix_world)
for v in tmp.verts:
scene_bm.verts.new(v.co)
scene_bm.verts.ensure_lookup_table()
@@ -112,6 +154,7 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
pass # skip degenerate / duplicate faces
vert_offset += len(tmp.verts)
tmp.free()
+ evaluated_obj.to_mesh_clear()
scene_bm.normal_update()
scene_tree = BVHTree.FromBMesh(scene_bm)
scene_bm.free()
@@ -121,8 +164,21 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
n_cameras = len(cameras)
for obj_idx, obj in enumerate(objects):
bm = bmesh.new()
- bm.from_mesh(obj.data)
- bm.transform(obj.matrix_world)
+ 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
+ bm.from_mesh(source_mesh)
+ bm.transform(source_matrix)
bm.normal_update()
n_verts = len(bm.verts)
@@ -130,6 +186,7 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
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()
for cam_idx, camera in enumerate(cameras):
print(f"[StableGen] Baking visibility: object {obj_idx+1}/{len(objects)}, "
@@ -170,7 +227,13 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
valid &= (np.abs(x_proj) < filmw) & (np.abs(y_proj) < filmh)
# Angle threshold
- dot_dn = np.abs(np.einsum('ij,ij->i', direction, normals_np))
+ raw_dot = np.einsum('ij,ij->i', direction, normals_np)
+ if getattr(scene, 'sg_allow_backface_projection', False):
+ dot_dn = np.abs(raw_dot)
+ else:
+ # ``direction`` points camera -> surface, so a visible front
+ # face has a negative dot product with its outward normal.
+ dot_dn = np.maximum(-raw_dot, 0.0)
dot_dn = np.clip(dot_dn, 0.0, 1.0)
angle_deg = np.degrees(np.arccos(dot_dn))
valid &= angle_deg < angle_threshold
@@ -178,11 +241,12 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
# ── BVH raycast only for candidates that passed filters ───
candidate_indices = np.nonzero(valid)[0]
occluded = np.zeros(n_verts, dtype=bool)
+ ray_epsilon = _scene_ray_epsilon(context)
for vi in candidate_indices:
d_mu = Vector(direction[vi])
hit_loc, _, _, hit_dist = scene_tree.ray_cast(
- cam_loc_mu, d_mu, float(dists[vi]) + 0.01)
- if hit_loc is not None and dists[vi] > hit_dist + 0.001:
+ cam_loc_mu, d_mu, float(dists[vi]) + ray_epsilon * 10.0)
+ if hit_loc is not None and dists[vi] > hit_dist + ray_epsilon:
occluded[vi] = True
valid &= ~occluded
@@ -231,7 +295,7 @@ def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=10000
continue
d_off_mu = Vector(d_off / norm)
h_loc, _, _, h_dist = scene_tree.ray_cast(
- cam_loc_mu, d_off_mu, dist_v + 0.01)
+ cam_loc_mu, d_off_mu, dist_v + ray_epsilon * 10.0)
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
@@ -294,15 +358,16 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,
# --- Camera location (CombineXYZ) ---
add_camera_loc = nodes.new("ShaderNodeCombineXYZ")
add_camera_loc.location = (-600, 200 + 300 * i)
- add_camera_loc.inputs[0].default_value = camera.location.x
- add_camera_loc.inputs[1].default_value = camera.location.y
- add_camera_loc.inputs[2].default_value = camera.location.z
+ camera_location = _camera_world_location(camera)
+ add_camera_loc.inputs[0].default_value = camera_location.x
+ add_camera_loc.inputs[1].default_value = camera_location.y
+ add_camera_loc.inputs[2].default_value = camera_location.z
# --- Direction: Geometry.Position - CameraLoc ---
subtract = nodes.new("ShaderNodeVectorMath")
subtract.operation = 'SUBTRACT'
subtract.location = (x_base, -300 + y_base)
- subtract.inputs[1].default_value = camera.location
+ subtract.inputs[1].default_value = camera_location
normalize_node = nodes.new("ShaderNodeVectorMath")
normalize_node.operation = 'NORMALIZE'
@@ -486,14 +551,15 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,
threshold_plus = nodes.new("ShaderNodeMath")
threshold_plus.operation = 'ADD'
threshold_plus.location = (x_base + 100, y_base + 100)
- threshold_plus.inputs[1].default_value = 0.01
+ ray_epsilon = _scene_ray_epsilon(context)
+ threshold_plus.inputs[1].default_value = ray_epsilon * 10.0
links.new(length_node.outputs["Value"], threshold_plus.inputs[0])
links.new(threshold_plus.outputs[0], raycast.inputs["Length"])
hit_dist_plus = nodes.new("ShaderNodeMath")
hit_dist_plus.operation = 'ADD'
hit_dist_plus.location = (x_base + 400, y_base + 50)
- hit_dist_plus.inputs[1].default_value = 0.001
+ hit_dist_plus.inputs[1].default_value = ray_epsilon
links.new(raycast.outputs["Hit Distance"], hit_dist_plus.inputs[0])
dist_check = nodes.new("ShaderNodeMath")
@@ -529,15 +595,28 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,
clamp_dot2.inputs[1].default_value = 1.0
links.new(clamp_dot.outputs[0], clamp_dot2.inputs[0])
- abs_dot = nodes.new("ShaderNodeMath")
- abs_dot.operation = 'ABSOLUTE'
- abs_dot.location = (x_base + 600, y_base - 150)
- links.new(clamp_dot2.outputs[0], abs_dot.inputs[0])
+ facing_dot = nodes.new("ShaderNodeMath")
+ facing_dot.location = (x_base + 600, y_base - 150)
+ if getattr(context.scene, 'sg_allow_backface_projection', False):
+ facing_dot.operation = 'ABSOLUTE'
+ links.new(clamp_dot2.outputs[0], facing_dot.inputs[0])
+ else:
+ # camera->surface dot outward-normal is negative for a front face.
+ facing_dot.operation = 'MULTIPLY'
+ facing_dot.inputs[1].default_value = -1.0
+ links.new(clamp_dot2.outputs[0], facing_dot.inputs[0])
+
+ facing_clamp = nodes.new("ShaderNodeMath")
+ facing_clamp.operation = 'MAXIMUM'
+ facing_clamp.location = (x_base + 650, y_base - 200)
+ facing_clamp.inputs[1].default_value = 0.0
+ links.new(facing_dot.outputs[0], facing_clamp.inputs[0])
+ facing_dot = facing_clamp
acos_node = nodes.new("ShaderNodeMath")
acos_node.operation = 'ARCCOSINE'
acos_node.location = (x_base + 700, y_base - 150)
- links.new(abs_dot.outputs[0], acos_node.inputs[0])
+ links.new(facing_dot.outputs[0], acos_node.inputs[0])
to_degrees = nodes.new("ShaderNodeMath")
to_degrees.operation = 'MULTIPLY'
@@ -557,7 +636,7 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,
power_node.location = (x_base + 700, y_base - 250)
power_node.inputs[1].default_value = context.scene.weight_exponent
power_node.label = 'power_weight'
- links.new(abs_dot.outputs[0], power_node.inputs[0])
+ links.new(facing_dot.outputs[0], power_node.inputs[0])
# ========================================
# COMBINE ALL: frustum_ok * occlusion_ok * angle_ok * weight
@@ -789,7 +868,7 @@ def _get_voronoi_placeholder(color=(1.0, 0.0, 1.0)):
return img
-def project_image(context, to_project, mat_id, stop_index=1000000):
+def project_image(context, to_project, mat_id, stop_index=1000000, cameras=None):
"""
Projects an image onto all mesh objects using UV Project Modifier.
"""
@@ -1034,6 +1113,32 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
v_off = -200 * idx
all_w_outputs.append(_get_weight_output(weight_nodes[idx], v_off))
+ # Apply initial-view priority once, globally, before max
+ # normalization. The old recursive Map Range changed meaning as
+ # cameras were paired, so results depended on camera count/tree
+ # shape rather than only on view rank.
+ if context.scene.early_priority:
+ from .view_plan import initial_view_prior
+ ranked_outputs = []
+ for idx, weight_output in enumerate(all_w_outputs):
+ prior = nodes_collection.new("ShaderNodeMath")
+ prior.operation = 'MULTIPLY'
+ prior.location = (x_offset - 1700, y_offset - 120 * idx)
+ prior.label = f"InitialViewPrior-{idx}"
+ desired_prior = initial_view_prior(
+ idx, len(all_w_outputs), context.scene.early_priority_strength
+ )
+ prior["sg_desired_prior"] = desired_prior
+ # This node sits before SharpW. Apply the inverse exponent
+ # so the requested rank prior remains bounded after
+ # sharpening (especially for Voronoi exponents near 1000).
+ prior.inputs[1].default_value = desired_prior ** (
+ 1.0 / max(float(user_exponent), 1e-6)
+ )
+ links.new(weight_output, prior.inputs[0])
+ ranked_outputs.append(prior.outputs[0])
+ all_w_outputs = ranked_outputs
+
# ── Step 3: Find per-pixel maximum ────────────────────────
max_node = nodes_collection.new("ShaderNodeMath")
max_node.operation = 'MAXIMUM'
@@ -1077,21 +1182,105 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
# sharp_w = pow(norm_w, user_exponent)
# (inputs are in [0, 1] → no underflow possible)
- if user_exponent != 1.0:
- pw = nodes_collection.new("ShaderNodeMath")
- pw.operation = 'POWER'
- pw.location = (div.location[0] + 200,
- div.location[1])
- pw.label = f"SharpW-{idx}"
- pw.inputs[1].default_value = user_exponent
- links.new(div.outputs[0], pw.inputs[0])
- powered_nodes.append(pw)
- else:
- powered_nodes.append(div)
+ # Always keep an explicit sharpening node. This makes the
+ # post-generation reset deterministic even when the material
+ # was initially built with exponent 1.
+ pw = nodes_collection.new("ShaderNodeMath")
+ pw.operation = 'POWER'
+ pw.location = (div.location[0] + 200,
+ div.location[1])
+ pw.label = f"SharpW-{idx}"
+ pw.inputs[1].default_value = user_exponent
+ links.new(div.outputs[0], pw.inputs[0])
+ powered_nodes.append(pw)
# Replace weight_nodes with sharpened-normalised nodes
weight_nodes = powered_nodes
+ if getattr(context.scene, 'sg_texel_ownership', False):
+ # Sequential hard ownership with hysteresis:
+ # replace only when new_confidence > owner + margin. An
+ # uncovered texel has owner confidence 0 and is accepted by
+ # any positive new confidence.
+ owner_color = shaders[0]
+ owner_weight = weight_nodes[0]
+ margin = max(
+ 0.0,
+ float(getattr(context.scene, 'sg_texel_replacement_margin', 0.05)),
+ )
+ for idx in range(1, len(shaders)):
+ margin_node = nodes_collection.new("ShaderNodeMath")
+ margin_node.operation = 'ADD'
+ margin_node.location = (x_offset - 200, y_offset - 180 * idx)
+ margin_node.inputs[1].default_value = margin
+ margin_node.label = f"OwnerMargin-{idx}"
+ links.new(owner_weight.outputs[0], margin_node.inputs[0])
+
+ replace = nodes_collection.new("ShaderNodeMath")
+ replace.operation = 'GREATER_THAN'
+ replace.location = (x_offset, y_offset - 180 * idx)
+ replace.label = f"OwnerReplace-{idx}"
+ links.new(weight_nodes[idx].outputs[0], replace.inputs[0])
+ links.new(margin_node.outputs[0], replace.inputs[1])
+
+ owner_empty = nodes_collection.new("ShaderNodeMath")
+ owner_empty.operation = 'COMPARE'
+ owner_empty.location = (x_offset, y_offset - 180 * idx - 70)
+ owner_empty.inputs[1].default_value = 0.0
+ owner_empty.inputs[2].default_value = 0.0
+ owner_empty.label = f"OwnerEmpty-{idx}"
+ links.new(owner_weight.outputs[0], owner_empty.inputs[0])
+
+ replace_or_empty = nodes_collection.new("ShaderNodeMath")
+ replace_or_empty.operation = 'MAXIMUM'
+ replace_or_empty.location = (x_offset + 100, y_offset - 180 * idx)
+ replace_or_empty.label = f"OwnerAccept-{idx}"
+ links.new(replace.outputs[0], replace_or_empty.inputs[0])
+ links.new(owner_empty.outputs[0], replace_or_empty.inputs[1])
+
+ select_color = nodes_collection.new("ShaderNodeMixRGB")
+ select_color.location = (x_offset + 200, y_offset - 180 * idx)
+ select_color.label = f"TexelOwner-{idx}"
+ links.new(replace_or_empty.outputs[0], select_color.inputs["Fac"])
+ links.new(owner_color.outputs[0], select_color.inputs["Color1"])
+ links.new(shaders[idx].outputs[0], select_color.inputs["Color2"])
+
+ confidence_delta = nodes_collection.new("ShaderNodeMath")
+ confidence_delta.operation = 'SUBTRACT'
+ confidence_delta.location = (x_offset + 200, y_offset - 180 * idx - 90)
+ links.new(weight_nodes[idx].outputs[0], confidence_delta.inputs[0])
+ links.new(owner_weight.outputs[0], confidence_delta.inputs[1])
+ selected_delta = nodes_collection.new("ShaderNodeMath")
+ selected_delta.operation = 'MULTIPLY'
+ selected_delta.location = (x_offset + 350, y_offset - 180 * idx - 90)
+ links.new(confidence_delta.outputs[0], selected_delta.inputs[0])
+ links.new(replace_or_empty.outputs[0], selected_delta.inputs[1])
+ selected_confidence = nodes_collection.new("ShaderNodeMath")
+ selected_confidence.operation = 'ADD'
+ selected_confidence.location = (x_offset + 500, y_offset - 180 * idx - 90)
+ selected_confidence.label = f"OwnerConfidence-{idx}"
+ links.new(owner_weight.outputs[0], selected_confidence.inputs[0])
+ links.new(selected_delta.outputs[0], selected_confidence.inputs[1])
+ owner_color = select_color
+ owner_weight = selected_confidence
+
+ final_mix = nodes_collection.new("ShaderNodeMixRGB")
+ final_mix.location = (x_offset + 450, y_offset)
+ final_mix.inputs["Color2"].default_value = (
+ *context.scene.fallback_color, 1.0
+ )
+ links.new(owner_color.outputs[0], final_mix.inputs["Color1"])
+ if last_node:
+ links.new(last_node.outputs[0], final_mix.inputs["Color2"])
+ uncovered = nodes_collection.new("ShaderNodeMath")
+ uncovered.operation = 'COMPARE'
+ uncovered.inputs[1].default_value = 0.0
+ uncovered.inputs[2].default_value = 0.0
+ uncovered.label = "OwnerUncovered"
+ links.new(owner_weight.outputs[0], uncovered.inputs[0])
+ links.new(uncovered.outputs[0], final_mix.inputs["Fac"])
+ return final_mix, owner_weight
+
new_shaders = []
new_weight_nodes = []
i = 0
@@ -1101,7 +1290,7 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
vert_offset = -200 * (i // 2)
sum_node = nodes_collection.new("ShaderNodeMath")
sum_node.operation = 'ADD'
- sum_node.location = (x_offset - 800, y_offset + vert_offset) if context.scene.early_priority else (x_offset - 600, y_offset + vert_offset)
+ sum_node.location = (x_offset - 600, y_offset + vert_offset)
def get_weight_output(w_item):
if isinstance(w_item, tuple):
@@ -1160,19 +1349,10 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
# Compute mix factor: weight_A / (weight_A+weight_B)
div_node = nodes_collection.new("ShaderNodeMath")
div_node.operation = 'DIVIDE'
- div_node.location = (x_offset - 600, y_offset + vert_offset) if context.scene.early_priority else (x_offset - 400, y_offset + vert_offset)
+ div_node.location = (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 context.scene.early_priority:
- # Add map range node
- map_range_node = nodes_collection.new("ShaderNodeMapRange")
- map_range_node.location = (x_offset - 400, y_offset + vert_offset)
- # to_min, to_max, from_max are set to 0.0 and 1.0 by default
- # set to prioritize earlier images
- 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)
@@ -1181,8 +1361,7 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
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
- to_connect = div_node if not context.scene.early_priority else map_range_node
- links.new(to_connect.outputs[0], mix_node.inputs["Fac"])
+ links.new(div_node.outputs[0], mix_node.inputs["Fac"])
new_shaders.append(mix_node)
# The new effective weight is the sum (stored in sum_node)
@@ -1194,8 +1373,13 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
i += 1
return build_mix_tree(new_shaders, new_weight_nodes, nodes_collection, links, last_node, level+1)
- cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']
- cameras.sort(key=lambda x: x.name)
+ if cameras is None:
+ from .view_plan import order_cameras
+ cameras = order_cameras(
+ obj for obj in context.scene.objects if obj.type == 'CAMERA'
+ )
+ else:
+ cameras = list(cameras)
# Force refresh of the UI
for area in context.screen.areas:
@@ -1469,6 +1653,43 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
links.new(mask_tex.outputs[0], to_float.inputs[0])
return to_float
+ def _create_qwen_write_mask_weight(cam_index, mat_id_inner):
+ """Sample the binary repair mask saved for a sequential Qwen view."""
+ mask_path = get_file_path(
+ context,
+ "inpaint",
+ subtype="visibility",
+ camera_id=cam_index,
+ )
+ if not os.path.exists(mask_path):
+ return None
+ mask_image = get_or_load_image(
+ mask_path,
+ force_reload=context.scene.overwrite_material,
+ )
+ if mask_image is None:
+ return None
+ mask_image.colorspace_settings.name = 'Non-Color'
+
+ mask_tex = nodes.new("ShaderNodeTexImage")
+ mask_tex.image = mask_image
+ mask_tex.extension = 'CLIP'
+ mask_tex.interpolation = 'Closest'
+ mask_tex.label = f"QwenWriteMask-{cam_index}-{mat_id_inner}"
+ mask_tex.location = (-500, -200 * cam_index - 300)
+
+ uv_node = uv_map_nodes[cam_index]
+ uv_out = "Vector" if uv_node.type == 'ATTRIBUTE' else "UV"
+ links.new(uv_node.outputs[uv_out], mask_tex.inputs["Vector"])
+
+ to_float = nodes.new("ShaderNodeMath")
+ to_float.operation = 'MULTIPLY'
+ to_float.inputs[1].default_value = 1.0
+ to_float.location = (-300, -200 * cam_index - 300)
+ to_float.label = f"QwenWriteWeight-{cam_index}-{mat_id_inner}"
+ links.new(mask_tex.outputs[0], to_float.inputs[0])
+ return to_float
+
# Voronoi mode flag: keep natural weights for non-generated cameras
voronoi_active = (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
and getattr(context.scene, 'qwen_voronoi_mode', False)
@@ -1608,7 +1829,7 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
subtract = nodes.new("ShaderNodeVectorMath")
subtract.operation = 'SUBTRACT'
subtract.location = (-400, -300 + (-800) * i)
- subtract.inputs[1].default_value = camera.location
+ subtract.inputs[1].default_value = _camera_world_location(camera)
subtract_nodes.append(subtract)
normalize = nodes.new("ShaderNodeVectorMath")
@@ -1627,10 +1848,18 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
script_angle.script = raycast_osl_text
else:
script_angle.mode = 'EXTERNAL'
- script_angle.filepath = os.path.join(os.path.dirname(__file__), "raycast.osl")
+ script_angle.filepath = os.path.join(
+ os.path.dirname(os.path.dirname(__file__)), "raycast.osl"
+ )
script_angle.inputs["AngleThreshold"].default_value = context.scene.discard_factor
script_angle.inputs["Power"].default_value = context.scene.weight_exponent
+ if "AllowBackface" in script_angle.inputs:
+ script_angle.inputs["AllowBackface"].default_value = float(
+ getattr(context.scene, 'sg_allow_backface_projection', False)
+ )
+ if "RayEpsilon" in script_angle.inputs:
+ script_angle.inputs["RayEpsilon"].default_value = _scene_ray_epsilon(context)
script_angle.label = f"Angle-{i}-{mat_id}"
scripts_to_connect = [script_angle]
@@ -1648,7 +1877,9 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
script_feather.script = feather_osl_text
else:
script_feather.mode = 'EXTERNAL'
- script_feather.filepath = os.path.join(os.path.dirname(__file__), "feather.osl")
+ script_feather.filepath = os.path.join(
+ os.path.dirname(os.path.dirname(__file__)), "feather.osl"
+ )
if context.scene.visibility_vignette: # Only set if feathering is active
script_feather.inputs["EdgeFeather"].default_value = context.scene.visibility_vignette_width
@@ -1725,9 +1956,10 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
# Add combine XYZ node
add_camera_loc = nodes.new("ShaderNodeCombineXYZ")
add_camera_loc.location = (-600, 200 + 300 * i)
- add_camera_loc.inputs[0].default_value = camera.location.x
- add_camera_loc.inputs[1].default_value = camera.location.y
- add_camera_loc.inputs[2].default_value = camera.location.z
+ camera_location = _camera_world_location(camera)
+ add_camera_loc.inputs[0].default_value = camera_location.x
+ add_camera_loc.inputs[1].default_value = camera_location.y
+ add_camera_loc.inputs[2].default_value = camera_location.z
add_camera_loc_nodes.append(add_camera_loc)
# Add length node
@@ -1736,6 +1968,28 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
length.location = (-400, 200 * (i+1))
length_nodes.append(length)
+ use_qwen_write_mask = (
+ i > 0
+ and i <= stop_index
+ and context.scene.model_architecture == 'qwen_image_edit'
+ and context.scene.generation_method == 'sequential'
+ and context.scene.qwen_generation_method == 'generate'
+ and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}
+ and getattr(context.scene, 'qwen_use_projection_write_masks', True)
+ )
+ if use_qwen_write_mask and script_nodes_outputs:
+ current_weight = script_nodes_outputs[-1]
+ if not isinstance(current_weight, tuple):
+ write_weight = _create_qwen_write_mask_weight(i, mat_id)
+ if write_weight is not None:
+ masked_weight = nodes.new("ShaderNodeMath")
+ masked_weight.operation = 'MULTIPLY'
+ masked_weight.location = (0, (-800) * i + 100)
+ masked_weight.label = f"QwenWriteMasked-{i}-{mat_id}"
+ links.new(current_weight.outputs[0], masked_weight.inputs[0])
+ links.new(write_weight.outputs[0], masked_weight.inputs[1])
+ script_nodes_outputs[-1] = masked_weight
+
# Build mix shader tree
if mat.name in processed_materials and is_local_edit:
# If we already processed this material, we don't need to rebuild the mix tree
@@ -1810,7 +2064,7 @@ def get_or_create_osl_text(filename):
Loads an OSL script into a Blender internal text block.
This ensures the script is embedded in the .blend file (portable).
"""
- filepath = os.path.join(os.path.dirname(__file__), filename)
+ filepath = os.path.join(os.path.dirname(os.path.dirname(__file__)), filename)
if not os.path.exists(filepath):
print(f"[StableGen] Error: OSL script not found at {filepath}")
return None
diff --git a/stablegen/texturing/quality_masks.py b/stablegen/texturing/quality_masks.py
new file mode 100644
index 0000000..24dd1b9
--- /dev/null
+++ b/stablegen/texturing/quality_masks.py
@@ -0,0 +1,64 @@
+"""Binary context/write-mask helpers for sequential edit-model texturing."""
+
+from __future__ import annotations
+
+import cv2
+import numpy as np
+
+
+def regularize_repair_mask(mask, threshold=127, dilation=0):
+ """Return an exact uint8 binary repair mask (255 means editable)."""
+ if mask is None:
+ raise ValueError("mask is required")
+ if mask.ndim == 3:
+ mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
+ binary = np.where(mask > int(threshold), 255, 0).astype(np.uint8)
+ dilation = max(0, int(dilation))
+ if dilation:
+ size = dilation * 2 + 1
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
+ binary = cv2.dilate(binary, kernel, iterations=1)
+ return binary
+
+
+def apply_binary_context_mask(context_bgr, repair_mask, fallback_rgb):
+ """Replace every editable context pixel with the exact fallback colour."""
+ if context_bgr is None:
+ raise ValueError("context image is required")
+ if context_bgr.shape[:2] != repair_mask.shape[:2]:
+ repair_mask = cv2.resize(
+ repair_mask,
+ (context_bgr.shape[1], context_bgr.shape[0]),
+ interpolation=cv2.INTER_NEAREST,
+ )
+ result = context_bgr.copy()
+ fallback_bgr = np.array(
+ [round(fallback_rgb[2] * 255), round(fallback_rgb[1] * 255), round(fallback_rgb[0] * 255)],
+ dtype=np.uint8,
+ )
+ result[repair_mask > 0, :3] = fallback_bgr
+ return result
+
+
+def reject_fallback_from_write_mask(
+ write_mask,
+ generated_bgr,
+ fallback_rgb,
+ tolerance=8,
+):
+ """Disable write pixels where Qwen left the sentinel colour behind."""
+ if generated_bgr.shape[:2] != write_mask.shape[:2]:
+ generated_bgr = cv2.resize(
+ generated_bgr,
+ (write_mask.shape[1], write_mask.shape[0]),
+ interpolation=cv2.INTER_LINEAR,
+ )
+ fallback_bgr = np.array(
+ [round(fallback_rgb[2] * 255), round(fallback_rgb[1] * 255), round(fallback_rgb[0] * 255)],
+ dtype=np.int16,
+ )
+ delta = generated_bgr[:, :, :3].astype(np.int32) - fallback_bgr.astype(np.int32)[None, None, :]
+ sentinel = np.sqrt(np.sum(delta * delta, axis=2)) <= max(0, int(tolerance))
+ result = write_mask.copy()
+ result[(write_mask > 0) & sentinel] = 0
+ return result
diff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.py
index 9c1caae..c86ade1 100644
--- a/stablegen/texturing/rendering.py
+++ b/stablegen/texturing/rendering.py
@@ -12,6 +12,36 @@ import cv2
_ADDON_PKG = __package__.rsplit('.', 1)[0]
+def _snapshot_material_state(obj):
+ """Capture exact slot order, active slot, and per-polygon assignments."""
+ return {
+ "materials": list(obj.data.materials),
+ "active_index": int(obj.active_material_index),
+ "polygon_indices": [polygon.material_index for polygon in obj.data.polygons],
+ }
+
+
+def _restore_material_state(obj, state):
+ """Restore a material snapshot without active-first slot reordering."""
+ obj.data.materials.clear()
+ for material in state["materials"]:
+ obj.data.materials.append(material)
+ if obj.data.materials:
+ obj.active_material_index = min(
+ state["active_index"], len(obj.data.materials) - 1
+ )
+ polygon_indices = state["polygon_indices"]
+ if len(polygon_indices) == len(obj.data.polygons):
+ max_index = max(len(obj.data.materials) - 1, 0)
+ for polygon, material_index in zip(obj.data.polygons, polygon_indices):
+ polygon.material_index = min(material_index, max_index)
+ else:
+ print(
+ f"[StableGen] Warning: polygon count changed while exporting '{obj.name}'; "
+ "material slots were restored but polygon indices could not be."
+ )
+
+
def purge_orphans():
"""
Purge unused datablocks (images, materials, node groups, etc).
@@ -613,7 +643,6 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
# Store original materials and create temporary ones
original_materials = {}
- original_active_material = {}
temporary_materials = {}
# Check if there is BSDF applied
@@ -622,8 +651,7 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
for obj in to_export:
# Store original materials
- original_materials[obj] = list(obj.data.materials)
- original_active_material[obj] = obj.active_material
+ original_materials[obj] = _snapshot_material_state(obj)
# Copy active material and switch to it
mat = obj.active_material
@@ -829,14 +857,8 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
bpy.context.scene.view_settings.view_transform = 'Standard'
# Restore original materials
- for obj, materials in original_materials.items():
- obj.data.materials.clear()
- # First append the original active material
- if original_active_material[obj]:
- obj.data.materials.append(original_active_material[obj])
- for mat in materials:
- if mat != original_active_material[obj]:
- obj.data.materials.append(mat)
+ for obj, material_state in original_materials.items():
+ _restore_material_state(obj, material_state)
# Clean up temporary materials
for _, temp_mat in temporary_materials.items():
@@ -860,15 +882,15 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
# Store original materials and create temporary ones
original_materials = {}
- original_active_material = {}
+ temporary_materials = []
for obj in context.view_layer.objects:
if obj.type == 'MESH':
# Store original materials
- original_materials[obj] = list(obj.data.materials)
- original_active_material[obj] = obj.active_material
+ original_materials[obj] = _snapshot_material_state(obj)
# Create temporary material
temp_mat = bpy.data.materials.new(name="TempRenderMaterial")
+ temporary_materials.append(temp_mat)
temp_mat.use_nodes = True # Even Workbench uses nodes for basic color
nodes = temp_mat.node_tree.nodes
links = temp_mat.node_tree.links
@@ -940,23 +962,16 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
bpy.ops.render.render(write_still=True)
# Restore original materials
- for obj, materials in original_materials.items():
- obj.data.materials.clear()
- # First append the original active material
- if original_active_material[obj]:
- obj.data.materials.append(original_active_material[obj])
- for mat in materials:
- if mat != original_active_material[obj]:
- obj.data.materials.append(mat)
+ for obj, material_state in original_materials.items():
+ _restore_material_state(obj, material_state)
# Restore original render settings
render_layer.use_pass_combined = original_combined
# Clean up temporary materials
- # Use a while loop to safely remove materials while iterating
- temp_mats = [m for m in bpy.data.materials if m.name.startswith("TempRenderMaterial")]
- for mat in temp_mats:
- bpy.data.materials.remove(mat)
+ for mat in temporary_materials:
+ if mat.name in bpy.data.materials:
+ bpy.data.materials.remove(mat)
# Restore original render settings
@@ -1179,7 +1194,8 @@ def expand_mask_to_blocks(mask_file_path, block_size=8):
return None
-def export_visibility(context, to_export, obj=None, camera_visibility=None, prepare_only=False):
+def export_visibility(context, to_export, obj=None, camera_visibility=None,
+ prepare_only=False, camera_render=None, camera_id=None):
"""
Exports the visibility of the mesh by temporarily altering the shading nodes.
:param context: Blender context.
@@ -1193,17 +1209,22 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None, prep
"""
# Store original materials and create temporary ones
original_materials = {}
- original_active_material = {}
temporary_materials = {}
+ def restore_prepared_materials():
+ for prepared_obj, material_state in original_materials.items():
+ _restore_material_state(prepared_obj, material_state)
+ for temp_mat in temporary_materials.values():
+ if temp_mat and temp_mat.name in bpy.data.materials:
+ bpy.data.materials.remove(temp_mat)
+
def prepare_material(obj):
mat = obj.active_material
if not mat:
return False
# Store original materials
- original_materials[obj] = list(obj.data.materials)
- original_active_material[obj] = obj.active_material # Store original active material
+ original_materials[obj] = _snapshot_material_state(obj)
# Store original active mat
@@ -1213,13 +1234,6 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None, prep
return False
mat_copy = mat.copy()
- # Clear materials and assign temp material
- obj.data.materials.clear()
- obj.data.materials.append(mat_copy)
-
- # Store temporary material for later deletion
- temporary_materials[obj] = mat_copy
-
# Enable use of nodes
mat_copy.use_nodes = True
nodes = mat_copy.node_tree.nodes
@@ -1233,9 +1247,11 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None, prep
break
if not output:
+ bpy.data.materials.remove(mat_copy)
return False
if not output.inputs[0].links:
+ bpy.data.materials.remove(mat_copy)
return False
# Determine which input to used based on existence of BSDF node before the output
@@ -1244,12 +1260,19 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None, prep
if not principled.inputs[0].links:
# Principled BSDF exists but nothing is connected to its
# Base Color – this is not a projection material.
+ bpy.data.materials.remove(mat_copy)
return False
color_mix = principled.inputs[0].links[0].from_node
input = principled.inputs[0]
else:
color_mix = output.inputs[0].links[0].from_node
input = output.inputs[0]
+
+ # Validation succeeded; only now replace the object's slots. This
+ # prevents an early return from leaving a complex mesh modified.
+ obj.data.materials.clear()
+ obj.data.materials.append(mat_copy)
+ temporary_materials[obj] = mat_copy
# Add equal node between color mix and bsdf
equal = nodes.new("ShaderNodeMath")
@@ -1405,9 +1428,11 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None, prep
# Prepare for all objects
for obj in to_export:
if not prepare_material(obj):
+ restore_prepared_materials()
return False
else:
if not prepare_material(obj):
+ restore_prepared_materials()
return False
if prepare_only:
@@ -1440,28 +1465,21 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None, prep
)
else:
# Make sure the camera is active and set to render
- cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']
- cameras.sort(key=lambda x: x.name)
- camera_visibility_index = [i for i, camera in enumerate(cameras) if camera == camera_visibility][0]
- camera_render_index = (camera_visibility_index + 1) % len(cameras)
- camera_render = cameras[camera_render_index]
+ if camera_render is None:
+ from .view_plan import order_cameras
+ cameras = order_cameras(
+ obj for obj in context.scene.objects if obj.type == 'CAMERA'
+ )
+ camera_visibility_index = cameras.index(camera_visibility)
+ camera_render_index = (camera_visibility_index + 1) % len(cameras)
+ camera_render = cameras[camera_render_index]
+ else:
+ camera_render_index = camera_id
context.scene.camera = camera_render
export_emit_image(context, to_export, camera_id=f"{camera_render_index}_visibility", bg_color=(1, 1, 1), view_transform='Raw', fallback_color=(1,1,1))
# Restore original materials
- for obj, materials in original_materials.items():
- obj.data.materials.clear()
- # First append the original active material
- if original_active_material[obj]:
- obj.data.materials.append(original_active_material[obj])
- for mat in materials:
- if mat != original_active_material[obj]:
- obj.data.materials.append(mat)
-
- # Clean up temporary materials
- for _, temp_mat in temporary_materials.items():
- if temp_mat and temp_mat.name in bpy.data.materials:
- bpy.data.materials.remove(temp_mat)
+ restore_prepared_materials()
return True
diff --git a/stablegen/texturing/view_plan.py b/stablegen/texturing/view_plan.py
new file mode 100644
index 0000000..5cc613f
--- /dev/null
+++ b/stablegen/texturing/view_plan.py
@@ -0,0 +1,141 @@
+"""Pure helpers for deterministic texturing view plans.
+
+This module intentionally has no Blender imports so camera ordering and aligned
+resolution selection can be regression-tested outside Blender.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import math
+import re
+from typing import Any, Iterable, Sequence
+
+
+_NATURAL_PARTS = re.compile(r"(\d+)")
+
+
+def natural_name_key(name: str) -> tuple:
+ """Return a stable natural-sort key (``Camera_2`` before ``Camera_10``)."""
+ return tuple(
+ int(part) if part.isdigit() else part.casefold()
+ for part in _NATURAL_PARTS.split(name or "")
+ )
+
+
+def order_cameras(cameras: Iterable[Any], custom_names: Sequence[str] = ()) -> list[Any]:
+ """Order camera-like objects once for an entire generation run."""
+ natural = sorted(list(cameras), key=lambda camera: natural_name_key(camera.name))
+ by_name = {camera.name: camera for camera in natural}
+ ordered: list[Any] = []
+ seen: set[str] = set()
+ for name in custom_names:
+ if name in by_name and name not in seen:
+ ordered.append(by_name[name])
+ seen.add(name)
+ ordered.extend(camera for camera in natural if camera.name not in seen)
+ return ordered
+
+
+def choose_aligned_resolution(
+ width: int,
+ height: int,
+ target_pixels: int,
+ alignment: int,
+ search_radius: int = 4,
+) -> tuple[int, int]:
+ """Rescale to the best nearby aligned dimensions without padding."""
+ width = max(1, int(width))
+ height = max(1, int(height))
+ target_pixels = max(1, int(target_pixels))
+ alignment = max(1, int(alignment))
+
+ scale = math.sqrt(target_pixels / float(width * height))
+ ideal_w = width * scale
+ ideal_h = height * scale
+ target_ratio = width / float(height)
+
+ center_w = max(1, round(ideal_w / alignment))
+ center_h = max(1, round(ideal_h / alignment))
+ candidates: list[tuple[float, int, int]] = []
+ for wi in range(max(1, center_w - search_radius), center_w + search_radius + 1):
+ for hi in range(max(1, center_h - search_radius), center_h + search_radius + 1):
+ candidate_w = wi * alignment
+ candidate_h = hi * alignment
+ ratio_error = abs(math.log((candidate_w / candidate_h) / target_ratio))
+ area_error = abs(math.log((candidate_w * candidate_h) / target_pixels))
+ scale_error = (
+ abs(math.log(candidate_w / ideal_w))
+ + abs(math.log(candidate_h / ideal_h))
+ )
+ score = ratio_error * 8.0 + area_error + scale_error * 0.25
+ candidates.append((score, candidate_w, candidate_h))
+
+ _, best_w, best_h = min(candidates, key=lambda item: (item[0], item[1] * item[2]))
+ return best_w, best_h
+
+
+def initial_view_prior(index: int, count: int, strength: float) -> float:
+ """Return a bounded global rank prior for an ordered camera view.
+
+ At maximum strength the final camera receives 25% of the first camera's
+ prior. Applying this once to all weights avoids the grouping-dependent
+ behavior of recursive pairwise remapping.
+ """
+ count = max(1, int(count))
+ index = min(max(0, int(index)), count - 1)
+ strength = min(max(float(strength), 0.0), 1.0)
+ rank = index / float(max(count - 1, 1))
+ return 1.0 - (0.75 * strength * rank)
+
+
+def should_replace_owner(
+ currently_covered: bool,
+ owner_confidence: float,
+ new_confidence: float,
+ replacement_margin: float,
+) -> bool:
+ """Reference rule used by the shader-node ownership implementation."""
+ return (
+ not currently_covered
+ or float(new_confidence)
+ > float(owner_confidence) + max(0.0, float(replacement_margin))
+ )
+
+
+@dataclass(frozen=True)
+class ViewRecord:
+ """Immutable camera identity used by every stage of one generation run."""
+
+ view_id: str
+ index: int
+ name: str
+ camera: Any
+ resolution_x: int
+ resolution_y: int
+
+ def to_manifest(self) -> dict[str, Any]:
+ camera_data = getattr(self.camera, "data", None)
+ matrix = getattr(self.camera, "matrix_world", None)
+ matrix_rows = None
+ if matrix is not None:
+ try:
+ matrix_rows = [[float(value) for value in row] for row in matrix]
+ except (TypeError, ValueError):
+ matrix_rows = None
+ return {
+ "schema": 1,
+ "view_id": self.view_id,
+ "index": self.index,
+ "name": self.name,
+ "resolution": [self.resolution_x, self.resolution_y],
+ "matrix_world": matrix_rows,
+ "camera": {
+ "type": getattr(camera_data, "type", None),
+ "lens": getattr(camera_data, "lens", None),
+ "sensor_width": getattr(camera_data, "sensor_width", None),
+ "sensor_height": getattr(camera_data, "sensor_height", None),
+ "shift_x": getattr(camera_data, "shift_x", None),
+ "shift_y": getattr(camera_data, "shift_y", None),
+ },
+ }
diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.py
index 3e2e015..0c70433 100644
--- a/stablegen/texturing/workflows.py
+++ b/stablegen/texturing/workflows.py
@@ -10,6 +10,7 @@ from datetime import datetime
from ..util.workflow_templates import prompt_text_qwen_image_edit, prompt_text_flux2_klein
from ..utils import get_generation_dirs
from ..timeout_config import get_timeout
+from .graph_validation import validate_workflow_graph
from io import BytesIO
import numpy as np
@@ -546,6 +547,13 @@ class _TexturingWorkflowMixin:
# --- Reference Latent chain (Qwen unzoom fix) ---
self._build_qwen_reference_latent_chain(prompt, NODES)
+
+ graph_issues = validate_workflow_graph(
+ prompt, (NODES['pos_prompt'], NODES['neg_prompt'])
+ )
+ if graph_issues:
+ self.operator._error = "Invalid Qwen refine workflow: " + "; ".join(graph_issues)
+ return {"error": "invalid_workflow"}
# --- Save and Execute ---
self._save_prompt_to_file(prompt, revision_dir)
@@ -815,6 +823,13 @@ class _TexturingWorkflowMixin:
else:
prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
+ graph_issues = validate_workflow_graph(
+ prompt, (NODES['pos_prompt'], NODES['neg_prompt'])
+ )
+ if graph_issues:
+ self.operator._error = "Invalid Qwen edit workflow: " + "; ".join(graph_issues)
+ return {"error": "invalid_workflow"}
+
# --- Execute ---
self._save_prompt_to_file(prompt, revision_dir)
ws = self._connect_to_websocket(server_address, client_id)
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 17aa09b..b31ceac 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -1307,6 +1307,12 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "early_priority_strength", text="Priority Strength")
+ row = content_box.row()
+ row.prop(scene, "sg_texel_ownership", text="Per-Texel View Ownership", toggle=True, icon="UV")
+ if scene.sg_texel_ownership:
+ row = content_box.row()
+ row.prop(scene, "sg_texel_replacement_margin", text="Replacement Margin")
+
row = content_box.row()
row.prop(scene, "bake_visibility_weights", text="Bake Visibility (Transform-Stable)", toggle=True, icon="MESH_DATA")
@@ -1319,6 +1325,9 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "sg_silhouette_rays", text="Silhouette Rays")
+ row = content_box.row()
+ row.prop(scene, "sg_allow_backface_projection", text="Allow Backface Projection")
+
# --- Output & Material Settings ---
if _show_diffusion_sections:
content_box = draw_collapsible_section(advanced_params_box, "show_output_material_settings", "Output & Material Settings", icon="MATERIAL")
@@ -1589,6 +1598,22 @@ class StableGenPanel(bpy.types.Panel):
dilation_row = context_box.row()
dilation_row.prop(scene, "qwen_context_fallback_dilation", text="Fallback Dilate (px)")
+ protection_row = context_box.row()
+ protection_row.prop(
+ scene,
+ "qwen_use_projection_write_masks",
+ text="Protect Trusted Texture",
+ toggle=True,
+ icon="LOCKED",
+ )
+ if scene.qwen_use_projection_write_masks:
+ tolerance_row = context_box.row()
+ tolerance_row.prop(
+ scene,
+ "qwen_residual_fallback_tolerance",
+ text="Residual Magenta Tol.",
+ )
+
cleanup_row = context_box.row()
cleanup_row.prop(scene, "qwen_context_cleanup", text="Apply Cleanup", toggle=True, icon="BRUSH_DATA")
if scene.qwen_context_cleanup:
diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.py
index 8cc6112..add065d 100644
--- a/stablegen/ui/presets.py
+++ b/stablegen/ui/presets.py
@@ -85,6 +85,8 @@ GEN_PARAMETERS = [
"ipadapter_end",
"early_priority",
"early_priority_strength",
+ "sg_texel_ownership",
+ "sg_texel_replacement_margin",
"differential_diffusion",
"differential_noise",
"blur_mask",
@@ -110,6 +112,8 @@ GEN_PARAMETERS = [
"qwen_context_cleanup_hue_tolerance",
"qwen_context_cleanup_value_adjust",
"qwen_context_fallback_dilation",
+ "qwen_use_projection_write_masks",
+ "qwen_residual_fallback_tolerance",
"qwen_prompt_gray_background",
"qwen_rescale_alignment",
"qwen_generation_method",
@@ -126,6 +130,7 @@ GEN_PARAMETERS = [
"sg_silhouette_margin",
"sg_silhouette_depth",
"sg_silhouette_rays",
+ "sg_allow_backface_projection",
"refine_feather_ramp_pos_0",
"refine_feather_ramp_pos_1",
"refine_edge_feather_projection",