Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
add depth-aware projection margins and occlusion feathering
sakalond47b3b94bcadc
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.pyindex 3b497b1..04e6d71 100644--- a/stablegen/core/properties.py+++ b/stablegen/core/properties.py@@ -813,7 +813,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,bpy.types.Scene.sg_silhouette_margin = bpy.props.IntProperty(name="Silhouette Margin",description="Pixel margin around occluder silhouettes where projection is suppressed. "- "Prevents thin outlines of foreground geometry (e.g. hands) bleeding onto surfaces behind them. 0 = disabled",+ "With Depth-Aware Margins, controls the farther/background side (e.g. dress behind a hand), not the image backdrop. "+ "Also controls the separate baked-visibility silhouette rays. 0 disables this margin; Foreground Margin is separate. Reproject to apply",default=3, min=0, max=20, update=update_parameters,)bpy.types.Scene.sg_allow_backface_projection = bpy.props.BoolProperty(@@ -821,6 +822,44 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,description="Use legacy two-sided projection weights. Leave disabled for characters and closed meshes so a camera cannot write through back-facing surfaces",default=TEXTURING_DEFAULTS["sg_allow_backface_projection"], update=update_parameters,)+ bpy.types.Scene.sg_silhouette_feather = bpy.props.IntProperty(+ name="Silhouette Feather",+ description="DPPG transition width beyond the rejected margin, in generation-image pixels. Feather Method controls interaction with the blending exponent. 0 restores the hard guard. Reproject to update",+ default=TEXTURING_DEFAULTS['sg_silhouette_feather'], min=0, max=128,+ update=update_parameters,+ )+ bpy.types.Scene.sg_projection_guard_scale = bpy.props.EnumProperty(+ name="Guard Resolution",+ description="Render DPPG masks at higher resolution to reduce jagged edges. Margin and feather retain their size in generation-image pixels; guidance images keep their original dimensions. Reproject to update",+ items=[('1', '1\u00d7', 'Generation resolution'),+ ('2', '2\u00d7', 'Double width and height'),+ ('4', '4\u00d7', 'Quadruple width and height; uses more memory')],+ default=TEXTURING_DEFAULTS['sg_projection_guard_scale'], update=update_parameters,+ )+ bpy.types.Scene.sg_guard_directional = bpy.props.BoolProperty(+ name="Depth-Aware Margins",+ description="Reject farther surfaces behind depth boundaries more strongly than the visible foreground. Boundaries with no clear depth order retain symmetric part protection. Reproject to apply",+ default=TEXTURING_DEFAULTS['sg_guard_directional'], update=update_parameters,+ )+ bpy.types.Scene.sg_guard_foreground_margin = bpy.props.IntProperty(+ name="Foreground Margin",+ description="Rejection margin on the nearer side of a depth boundary, in generation-image pixels. 0 preserves visible foreground such as the chin or a hand. Silhouette Margin controls the farther side. Reproject to apply",+ default=TEXTURING_DEFAULTS['sg_guard_foreground_margin'], min=0, max=128, update=update_parameters,+ )+ bpy.types.Scene.sg_guard_coverage_rescue = bpy.props.FloatProperty(+ name="Coverage Rescue",+ description="Ease DPPG rejection when the best remaining trusted view falls below this fraction of the original best view quality. 0 keeps legacy rejection; 0.25 requires at least 25% quality for full rejection. Visibility and image alpha remain enforced. Reproject to apply",+ default=TEXTURING_DEFAULTS['sg_guard_coverage_rescue'], min=0, max=1, update=update_parameters,+ )+ bpy.types.Scene.sg_guard_feather_method = bpy.props.EnumProperty(+ name="Feather Method",+ description="How DPPG feathering interacts with camera-weight sharpening. Reproject to apply",+ items=[('ORIGINAL', 'Original', 'Multiply sharpened weights by the feather; the exponent still affects the final transition'),+ ('LOCAL_UNSHARPEN', 'Local Unsharpen', 'Use unsharpened weights throughout the feather band, smoothly restoring the exponent farther inside safe regions'),+ ('BOUNDARY_CROSSFADE', 'Boundary Crossfade', 'Crossfade between normalized camera combinations as masks fade; the exponent controls each combination, not the crossfade curve'),+ ('SURFACE_BLEND', 'Surface Blend (Preview)', 'Solve camera contributions jointly along the mesh within the feather band. Requires Reproject; detail depends on mesh density. Base multi-view projection only')],+ default=TEXTURING_DEFAULTS['sg_guard_feather_method'], update=update_parameters,+ )# Scene values remain serializable. Research switches are gated at runtime# by the addon preference; CGC/AQW/DPPG are ordinary controls.diff --git a/stablegen/feature_flags.py b/stablegen/feature_flags.pyindex 6ebb31a..40d482a 100644--- a/stablegen/feature_flags.py+++ b/stablegen/feature_flags.py@@ -16,6 +16,12 @@ EXPERIMENTAL_FEATURE_DEFAULTS = dict.fromkeys((), False)TEXTURING_DEFAULTS = {**GRADUATED_FEATURE_DEFAULTS, **EXPERIMENTAL_FEATURE_DEFAULTS,+ 'sg_silhouette_feather': 12,+ 'sg_projection_guard_scale': '2',+ 'sg_guard_feather_method': 'ORIGINAL',+ 'sg_guard_directional': True,+ 'sg_guard_foreground_margin': 0,+ 'sg_guard_coverage_rescue': 0.25,}diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.pyindex c53a1d1..516ab17 100644--- a/stablegen/texturing/generator.py+++ b/stablegen/texturing/generator.py@@ -47,6 +47,9 @@ from .quality_masks import (reject_fallback_from_write_mask,residual_fallback_percentage,build_depth_part_rejection_mask,+ feather_projection_guard,+ projection_guard_feather_influence,+ projection_occlusion_fields,)from .confidence import camera_direction_from_matrix, overlap_aware_orderfrom .pose_lock import (@@ -1563,6 +1566,22 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):controlnet_units = self._controlnet_unitscameras = self._cameras+ if context.scene.generation_mode == 'project_only':+ # Reprojection must rebuild the pixel guard with today's margin,+ # depth threshold and geometry, including runs that never had one.+ # Other guidance maps and model inference are not needed here.+ if getattr(context.scene, 'sg_rework_projection_guard', False):+ for i, camera in enumerate(cameras):+ self._stage = f"Rebuilding Projection Guards ({i+1}/{len(cameras)})"+ def _render_guard(_i=i, _cam=camera):+ self._activate_view(context, _i)+ with _SGCameraResolution(context, _cam):+ self.export_depthmap(context, camera_id=_i)+ self._run_on_main_thread(_render_guard)+ if self._error:+ return+ return+if context.scene.generation_mode in ('standard', 'regenerate_selected'):need_depth = (any(u["unit_type"] == "depth" for u in controlnet_units)@@ -2398,6 +2417,25 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):use_projection_guard = getattr(context.scene, 'sg_rework_projection_guard', False)+ # Preserve calibrated camera distance for receiver-aware occlusion+ # feathering. The model's existing normalized depth input is unchanged.+ distance_scale = None+ if use_projection_guard:+ camera_position = context.scene.camera.matrix_world.translation+ distance_scale = max([1.0] + [+ (obj.matrix_world @ mathutils.Vector(corner) - camera_position).length+ for obj in context.view_layer.objects if obj.type == 'MESH' and not obj.hide_render+ for corner in obj.bound_box]) * 1.01+ distance_node = nodes.new('ShaderNodeMath')+ distance_node.operation = 'DIVIDE'+ distance_node.inputs[1].default_value = distance_scale+ links.new(render_layers_node.outputs['Depth'], distance_node.inputs[0])+ distance_output = nodes.new('CompositorNodeOutputFile')+ configure_output_node_paths(distance_output, output_dir, f'projection_distance{camera_id}')+ distance_output.format.file_format = 'PNG'+ distance_output.format.color_depth = '16'+ distance_output.format.color_mode = 'RGB'+ links.new(distance_node.outputs[0], distance_output.inputs[0])use_part_ids = (use_projection_guardor experimental_enabled(context.scene, 'qwen_regularize_context_mask')@@ -2433,7 +2471,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):depth_image,object_image,material_image,- margin=getattr(context.scene, 'sg_silhouette_margin', 3),+ margin=getattr(context.scene, 'sg_silhouette_margin', 3) * guard_scale,+ foreground_margin=(getattr(context.scene, 'sg_guard_foreground_margin', 0) * guard_scale+ if getattr(context.scene, 'sg_guard_directional', False) else None),depth_threshold=max(1,round(float(getattr(context.scene, 'sg_silhouette_depth', 0.01)) * 255),@@ -2462,6 +2502,42 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):guard_dir, f"projection_guard{camera_id}.png")cv2.imwrite(guard_path, guard)+ feather_width = getattr(context.scene, 'sg_silhouette_feather', 0)+ feather = feather_projection_guard(guard, feather_width * guard_scale)+ # Keep this field continuous through the rejected band. A white+ # core creates a second edge under bilinear sampling and a halo.+ # A constant shader floor preserves last-source coverage without+ # introducing another mask boundary.+ feather_path = os.path.join(guard_dir, f"projection_guard_feather{camera_id}.png")+ cv2.imwrite(feather_path, feather)+ occlusion, occlusion_influence = projection_occlusion_fields(+ depth_image, feather_width * guard_scale,+ max(1, round(float(getattr(context.scene, 'sg_silhouette_depth', 0.01)) * 255)),+ object_ids=object_image if not guard_diagnostics['fallback_triggered'] else None)+ distance_path = os.path.join(output_dir, f'projection_distance{camera_id}{frame_suffix}.png')+ distance_image = cv2.imread(distance_path, cv2.IMREAD_UNCHANGED)+ if distance_image is None or distance_image.dtype != np.uint16:+ raise RuntimeError('Projection occlusion distance pass is missing or not 16-bit')+ if distance_image.ndim == 3:+ distance_image = distance_image[:, :, 0]+ ramp, influence, reference = projection_occlusion_fields(+ depth_image, feather_width * guard_scale,+ max(1, round(float(getattr(context.scene, 'sg_silhouette_depth', 0.01)) * 255)),+ object_ids=object_image if not guard_diagnostics['fallback_triggered'] else None,+ surface_distance=distance_image.astype(np.float32) / 65535.0)+ # PNG channels R/G/B: continuous ramp, sharpening influence,+ # midpoint distance separating the occluder and receiving surface.+ geometry_path = os.path.join(guard_dir, f'projection_occlusion_geometry{camera_id}.png')+ cv2.imwrite(geometry_path, np.stack((+ np.rint(np.clip(reference, 0, 1) * 65535).astype(np.uint16),+ influence.astype(np.uint16) * 257, ramp.astype(np.uint16) * 257), axis=2))+ with open(os.path.join(guard_dir, f'projection_occlusion_geometry{camera_id}.json'), 'w') as stream:+ json.dump({'distance_scale': distance_scale}, stream)+ occlusion_path = os.path.join(guard_dir, f"projection_occlusion_feather{camera_id}.png")+ cv2.imwrite(occlusion_path, occlusion)+ cv2.imwrite(os.path.join(guard_dir, f"projection_guard_influence{camera_id}.png"),+ np.maximum(projection_guard_feather_influence(guard, feather_width * guard_scale),+ occlusion_influence))self._record_confidence_artifacts(context,camera_id,@@ -2469,6 +2545,16 @@ 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_feather=feather_path,+ projection_occlusion_feather=occlusion_path,+ projection_occlusion_geometry=geometry_path,+ projection_occlusion_distance_scale=distance_scale,+ projection_guard_scale=guard_scale,+ projection_guard_margin=getattr(context.scene, 'sg_silhouette_margin', 3),+ projection_guard_feather_width=feather_width,+ projection_guard_directional=getattr(context.scene, 'sg_guard_directional', False),+ projection_guard_foreground_margin=getattr(context.scene, 'sg_guard_foreground_margin', 0),+ projection_guard_coverage_rescue=getattr(context.scene, 'sg_guard_coverage_rescue', 0.0),projection_guard_mode=guard_diagnostics["mode"],projection_guard_fallback=guard_diagnostics["fallback_triggered"],projection_guard_id_allowed_foreground_percent=guard_diagnostics[@@ -2479,6 +2565,16 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):],)+ # Keep model guidance at the requested resolution; only the projection+ # masks retain supersampled resolution. IDs must remain categorical.+ if guard_scale > 1:+ for path, categorical in ((depth_path, False), (object_path, True), (material_path, True)):+ data = cv2.imread(path, cv2.IMREAD_UNCHANGED)+ if data is not None:+ size = (data.shape[1] // guard_scale, data.shape[0] // guard_scale)+ cv2.imwrite(path, cv2.resize(data, size, interpolation=(+ cv2.INTER_NEAREST if categorical else cv2.INTER_AREA)))+bpy.context.scene.view_settings.view_transform = 'Standard'print(f"[StableGen] Depth map saved to: {os.path.join(output_dir, output_file)}.png")@@ -2494,7 +2590,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):def export_depthmap(self, context, camera_id=None):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)+ scale = (int(getattr(context.scene, 'sg_projection_guard_scale', '1'))+ if getattr(context.scene, 'sg_rework_projection_guard', False) else 1)+ context.scene.render.resolution_x *= scale+ context.scene.render.resolution_y *= scale+ return self._export_depthmap_impl(context, camera_id=camera_id, guard_scale=scale)def export_normal(self, context, camera_id=None):"""diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.pyindex e2b6506..975a534 100644--- a/stablegen/texturing/projection.py+++ b/stablegen/texturing/projection.py@@ -283,6 +283,13 @@ def _bake_visibility_weights(# ── Vectorised frustum + angle pre-filter ──────────────────to_vert = positions_np - cam_loc_np # (N, 3)+ # Freeze receiver depth alongside visibility so moving/posing a+ # baked projection cannot change its foreground exemption.+ depth_name = f"_SG_ProjectionDepth_{cam_idx}_{mat_id}"+ depth_attr = obj.data.attributes.get(depth_name)+ if depth_attr is None:+ depth_attr = obj.data.attributes.new(name=depth_name, type='FLOAT', domain='POINT')+ depth_attr.data.foreach_set('value', np.einsum('ij,j->i', to_vert, cam_dir_np))if camera_type == 'ORTHO':dists = np.einsum('ij,j->i', to_vert, cam_dir_np)valid = dists > 1e-8@@ -339,7 +346,7 @@ def _bake_visibility_weights()hit_loc, _, _, hit_dist = scene_tree.ray_cast(ray_origin, d_mu, float(dists[vi]) + ray_epsilon * (- 20.0 if getattr(scene, 'sg_rework_projection_geometry', False) else 10.0+ 20.0))if hit_loc is not None and dists[vi] > hit_dist + ray_epsilon:occluded[vi] = True@@ -401,26 +408,23 @@ def _bake_visibility_weights()h_loc, _, _, h_dist = scene_tree.ray_cast(offset_origin, d_off_mu, dist_v + ray_epsilon * (- 20.0 if getattr(scene, 'sg_rework_projection_geometry', False) else 10.0+ 20.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,+ 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:- depth_thr = getattr(scene, 'sg_silhouette_depth', 0.05)+ pixel_footprint = (+ dist_v * rad_per_px * max(silhouette_margin_px, 1)+ )+ depth_thr = max(+ scene_scale * relative_depth,+ pixel_footprint * 0.5,+ )if h_loc is not None and dist_v > h_dist + depth_thr:is_edge = Truebreak@@ -1059,6 +1063,201 @@ def _get_voronoi_placeholder(color=(1.0, 0.0, 1.0)):return img+def _projection_feather_math(nodes, links, operation, label, a, b):+ node = nodes.new('ShaderNodeMath')+ node.operation = operation+ node.label = label+ if operation == 'COMPARE':+ node.inputs[2].default_value = 0.0+ for i, value in enumerate((a, b)):+ if isinstance(value, (int, float)):+ node.inputs[i].default_value = value+ else:+ links.new(value, node.inputs[i])+ return node+++def _apply_guard_coverage_rescue(nodes, links, guarded, raw, guards, feathers, threshold,+ occlusion_feathers=None, occlusion_influences=None,+ feather_method=None):+ """Ease rejection continuously when no comparable trusted view survives.++ Work with raw quality before exponentiation, retaining raycast, alpha and+ write-mask validity. Confidence continues using the original guarded graph.+ """+ def math(op, label, a, b):+ return _projection_feather_math(nodes, links, op, label, a, b).outputs[0]+ def protect_occlusions(fades):+ if occlusion_feathers is None:+ return fades+ if feather_method == 'BOUNDARY_CROSSFADE':+ # Restore the original crossfade handoff: each camera retains its+ # own rescued guard feather, limited by its occlusion feather.+ # Lifting every competitor exposed a hard guard edge on the cheek.+ return [math('MINIMUM', f'GuardOcclusionFade-{i}',+ fade if fade is not None else 1.0, occlusion)+ if occlusion is not None else fade+ for i, (fade, occlusion) in enumerate(zip(fades, occlusion_feathers))]+ # A handoff needs an unfaded receiving view. Suppressing that view+ # with the older guard feather rescales/compresses the occlusion ramp.+ # Share the occlusion transition region across ALL visible competitors,+ # not just the departing view. Retain part-seam feathering elsewhere,+ # returning to it smoothly over the occlusion field's outer shoulder.+ influence = 1.0 if occlusion_influences is None else 0.0+ for i, field in enumerate(occlusion_influences or []):+ if field is not None:+ visible = math('GREATER_THAN', f'OcclusionHandoffVisible-{i}', raw[i], 0.0)+ active = math('MULTIPLY', f'OcclusionHandoffActive-{i}', visible, field)+ influence = math('MAXIMUM', f'OcclusionHandoffRegion-{i}', influence, active)+ result = []+ for i, (fade, occlusion) in enumerate(zip(fades, occlusion_feathers)):+ if occlusion is None:+ result.append(fade)+ continue+ legacy = fade if fade is not None else 1.0+ lifted = math('ADD', f'OcclusionHandoffLegacy-{i}', legacy,+ math('MULTIPLY', f'OcclusionHandoffLift-{i}', influence,+ math('SUBTRACT', f'OcclusionHandoffMissing-{i}', 1.0, legacy)))+ result.append(math('MINIMUM', f'GuardOcclusionFade-{i}', lifted, occlusion))+ return result+ if not any(g is not None for g in guards):+ return guarded, protect_occlusions(feathers)+ best, trusted = 0.0, 0.0+ for i, (quality, guard, feather) in enumerate(zip(raw, guards, feathers)):+ best = math('MAXIMUM', f'GuardRescueBest-{i}', best, quality)+ reliability = guard if guard is not None else 1.0+ if feather is not None:+ reliability = math('MULTIPLY', f'GuardRescueReliability-{i}', reliability, feather)+ accepted = math('MULTIPLY', f'GuardRescueAccepted-{i}', quality, reliability)+ trusted = math('MAXIMUM', f'GuardRescueTrusted-{i}', trusted, accepted)+ threshold_product = math('MULTIPLY', 'GuardRescueThreshold', best, threshold)+ denominator = math('MAXIMUM', 'GuardRescueSafeThreshold', threshold_product, 1e-8)+ fraction = math('DIVIDE', 'GuardRescueFraction', trusted, denominator)+ t = math('MINIMUM', 'GuardRescueClamped', fraction, 1.0)+ smooth = math('MULTIPLY', 'GuardRescueSmooth', math('MULTIPLY', 'GuardRescueSquare', t, t),+ math('SUBTRACT', 'GuardRescueCurve', 3.0, math('MULTIPLY', 'GuardRescueTwice', 2.0, t)))+ # Threshold zero means rescue is OFF, not full rescue. Keep the graph+ # present so its threshold can later be changed from one shader control.+ active = math('GREATER_THAN', 'GuardRescueActive', threshold, 0.0)+ strength = math('SUBTRACT', 'GuardRescueStrength', 1.0,+ math('MULTIPLY', 'GuardRescueReduction', active,+ math('SUBTRACT', 'GuardRescueMissing', 1.0, smooth)))+ restored = math('SUBTRACT', 'GuardRescueRestored', 1.0, strength)+ outputs, fades = [], []+ for i, (quality, guard, feather) in enumerate(zip(raw, guards, feathers)):+ if guard is None:+ outputs.append(guarded[i]); fades.append(feather); continue+ effective = math('ADD', f'GuardRescueEffective-{i}', restored,+ math('MULTIPLY', f'GuardRescueRetained-{i}', strength, guard))+ floor = math('MAXIMUM', f'GuardRescueFloor-{i}', effective, 0.001)+ outputs.append(math('MULTIPLY', f'GuardCoverageWeight-{i}', quality, floor))+ fades.append(math('ADD', f'GuardRescueFeather-{i}', restored,+ math('MULTIPLY', f'GuardRescueFade-{i}', strength, feather))+ if feather is not None else None)+ # Rescue may restore a conservative guard, but cannot restore the fade+ # toward a real occluder. Apply this limit after rescue, before the common+ # post-exponent feather stage. Raw raycast/alpha validity stays untouched.+ return outputs, protect_occlusions(fades)+++def _crossfade_projection_feathers(nodes, links, weights, feathers, bases):+ """Integrate normalized camera combinations over feather thresholds.++ For two views with feathers f and 1 this is f * mix(A, B) + (1-f) * B.+ The same construction handles overlapping fades without independent weight+ caps. Equal thresholds share one interval; invisible views cannot open one.+ Normalize by the best feather to retain coverage when every view is unsafe.+ """+ def math(op, label, a, b):+ return _projection_feather_math(nodes, links, op, label, a, b).outputs[0]++ levels = []+ maximum = 0.0+ for i, (base, feather) in enumerate(zip(bases, feathers)):+ visible = math('GREATER_THAN', f'CrossfadeVisible-{i}', base, 0.0)+ floor = math('MAXIMUM', f'CrossfadeFloor-{i}', feather if feather is not None else 1.0, 0.001)+ level = math('MULTIPLY', f'CrossfadeLevel-{i}', floor, visible)+ levels.append(level)+ maximum = math('MAXIMUM', f'CrossfadeMaxLevel-{i}', maximum, level)++ result = [0.0] * len(weights)+ for i, level in enumerate(levels):+ lower, ties, best = 0.0, 0.0, 0.0+ selected = []+ for j, (other, base) in enumerate(zip(levels, bases)):+ below = math('GREATER_THAN', f'CrossfadeBelow-{i}-{j}', level, other)+ lower = math('MAXIMUM', f'CrossfadeLower-{i}-{j}', lower,+ math('MULTIPLY', f'CrossfadeLowerCandidate-{i}-{j}', other, below))+ ties = math('ADD', f'CrossfadeTies-{i}-{j}', ties,+ math('COMPARE', f'CrossfadeEqual-{i}-{j}', level, other))+ include = math('SUBTRACT', f'CrossfadeInclude-{i}-{j}', 1.0, below)+ quality = math('MULTIPLY', f'CrossfadeQuality-{i}-{j}', base, include)+ selected.append(quality)+ best = math('MAXIMUM', f'CrossfadeBest-{i}-{j}', best, quality)+ interval = math('DIVIDE', f'CrossfadeInterval-{i}',+ math('SUBTRACT', f'CrossfadeGap-{i}', level, lower),+ math('MULTIPLY', f'CrossfadeIntervalScale-{i}', maximum, ties))+ # Rescale each subset BEFORE sharpening: a weak but sole remaining+ # camera must not underflow to black at high exponents.+ powered, total = [], 0.0+ for j, quality in enumerate(selected):+ normalized = math('DIVIDE', f'CrossfadeNormalized-{i}-{j}', quality, best)+ power = math('POWER', f'SharpW-Feather-{i}-{j}', normalized, weights[j].inputs[1].default_value)+ powered.append(power)+ total = math('ADD', f'CrossfadeTotal-{i}-{j}', total, power)+ for j, power in enumerate(powered):+ share = math('DIVIDE', f'CrossfadeShare-{i}-{j}', power, total)+ result[j] = math('ADD', f'CrossfadeAccumulated-{i}-{j}', result[j],+ math('MULTIPLY', f'CrossfadeContribution-{i}-{j}', interval, share))+ return [_projection_feather_math(nodes, links, 'MULTIPLY', f'PostExponentFeather-{i}', value, 1.0)+ for i, value in enumerate(result)]+++def _apply_projection_feathers(nodes, links, weights, feathers, bases, influences, method):+ """Apply a continuous, post-exponent fade without replacing view preference.++ Keep the rejected core dark in the texture. A small constant floor retains+ last-source coverage without the white-core discontinuity that caused halos.+ """+ if not any(feather is not None for feather in feathers):+ return weights+ if method == 'BOUNDARY_CROSSFADE':+ return _crossfade_projection_feathers(nodes, links, weights, feathers, bases)+ if method == 'LOCAL_UNSHARPEN':+ def math(op, label, a, b):+ return _projection_feather_math(nodes, links, op, label, a, b).outputs[0]+ influence = 0.0+ for i, (base, field) in enumerate(zip(bases, influences)):+ if field is None:+ continue+ visible = math('GREATER_THAN', f'FeatherVisible-{i}', base, 0.0)+ active = math('MULTIPLY', f'FeatherActive-{i}', field, visible)+ influence = math('MAXIMUM', f'FeatherInfluence-{i}', influence, active)+ sharp_fraction = math('SUBTRACT', 'FeatherSharpFraction', 1.0, influence)+ weights = [+ _projection_feather_math(nodes, links, 'ADD', f'FeatherPreference-{i}',+ math('MULTIPLY', f'FeatherSharp-{i}', weight.outputs[0], sharp_fraction),+ math('MULTIPLY', f'FeatherSoft-{i}', base, influence))+ for i, (weight, base) in enumerate(zip(weights, bases))]+ result = []+ for i, (weight, feather) in enumerate(zip(weights, feathers)):+ if feather is None:+ result.append(weight)+ continue+ floor = nodes.new('ShaderNodeMath')+ floor.operation = 'MAXIMUM'+ floor.label = f'ProjectionFeatherFloor-{i}'+ floor.inputs[1].default_value = 0.001+ links.new(feather, floor.inputs[0])+ faded = nodes.new('ShaderNodeMath')+ faded.operation = 'MULTIPLY'+ faded.label = f'PostExponentFeather-{i}'+ links.new(weight.outputs[0], faded.inputs[0])+ links.new(floor.outputs[0], faded.inputs[1])+ result.append(faded)+ return result++def project_image(context,to_project,@@ -1072,6 +1271,17 @@ def project_image("""Projects an image onto all mesh objects using UV Project Modifier."""+ surface_blend = (getattr(context.scene, 'sg_guard_feather_method', 'ORIGINAL') == 'SURFACE_BLEND'+ and getattr(context.scene, 'sg_rework_projection_guard', False)+ and getattr(context.scene, 'sg_silhouette_feather', 0) > 0)+ if surface_blend:+ if (context.scene.generation_method in {'local_edit', 'refine'}+ or (context.scene.model_architecture.startswith('qwen')+ and context.scene.qwen_generation_method == 'local_edit')):+ raise ValueError('Surface Blend preview supports base multi-view projection; use Local Unsharpen for local refinement')+ # A newly generated view changes the joint solution. Do not reuse a+ # sequential material containing the previous camera set's field.+ force_rebuild = Truedef build_mix_tree(shaders, weight_nodes, nodes_collection, links, last_node=None, level=0, stop_index=1000000):"""Recursively builds a binary tree of mix shader nodes.@@ -1093,6 +1303,28 @@ def project_image(A tuple (final_shader, final_weight_node)."""+ if level == 0 and surface_blend and len(shaders) > 1:+ from .surface_blend import build+ key = build(context, to_project, cameras, shaders, mat, mat_id, stop_index)+ solved = []+ for idx, original in enumerate(weight_nodes):+ if isinstance(original, tuple):+ raise ValueError('Surface Blend preview requires ordinary multi-view projection')+ raw = original+ if raw.label.startswith('DepthPartFeathered-'):+ raw = raw.inputs[0].links[0].from_node+ if raw.label.startswith('DepthPartGuarded-'):+ raw = raw.inputs[0].links[0].from_node+ field = nodes_collection.new('ShaderNodeAttribute')+ field.attribute_name = key + f'Weight{idx}'+ field.label = f'SurfaceBlendWeight-{idx}'+ valid = _projection_feather_math(nodes_collection, links, 'GREATER_THAN',+ f'SurfaceBlendVisible-{idx}', raw.outputs[0], 0.)+ solved.append(_projection_feather_math(nodes_collection, links, 'MULTIPLY',+ f'SurfaceBlendFinal-{idx}', field.outputs['Fac'], valid.outputs[0]))+ return build_mix_tree(shaders, solved, nodes_collection, links, last_node, level=1,+ stop_index=stop_index)+def _combine_angle_feather(nodes_col, lnk, cr_angle_out, cr_feather_out, loc):"""Combine angle-ramp and feather-ramp outputs into a singlevisibility weight: ``angle_vis × feather_vis``.@@ -1363,10 +1595,48 @@ def project_image(# ── Step 2: Get base weight outputs (now power = 1) ───────all_w_outputs = []+ feather_outputs = []+ influence_outputs = []+ raw_outputs = []+ guard_outputs = []+ occlusion_outputs = []+ occlusion_influence_outputs = []for idx in range(len(weight_nodes)):v_off = -200 * idx- all_w_outputs.append(_get_weight_output(weight_nodes[idx], v_off))-+ influence = nodes_collection.get(f"SGFeatherInfluence-{idx}-{mat_id}")+ influence_outputs.append(influence.outputs[0] if influence else None)+ occlusion_influence = nodes_collection.get(f"SGOcclusionInfluence-{idx}-{mat_id}")+ occlusion_influence_outputs.append(occlusion_influence.outputs[0] if occlusion_influence else None)+ if occlusion_influence is not None:+ influence_outputs[-1] = _projection_feather_math(+ nodes_collection, links, 'MAXIMUM', f'OcclusionCombinedInfluence-{idx}',+ influence_outputs[-1] if influence_outputs[-1] is not None else 0.0,+ occlusion_influence.outputs[0]).outputs[0]+ occlusion = nodes_collection.get(f"SGOcclusionFeather-{idx}-{mat_id}")+ occlusion_outputs.append(occlusion.outputs[0] if occlusion else None)+ weight = weight_nodes[idx]+ if (not isinstance(weight, tuple)+ and weight.label.startswith('DepthPartFeathered-')):+ # Preserve the existing hard guard and source preference.+ # Apply only the extra continuous fade after sharpening.+ all_w_outputs.append(weight.inputs[0].links[0].from_socket)+ feather_outputs.append(weight.inputs[1].links[0].from_socket)+ else:+ all_w_outputs.append(_get_weight_output(weight, v_off))+ feather_outputs.append(None)+ guard_node = all_w_outputs[-1].node+ if guard_node.label.startswith('DepthPartGuarded-'):+ raw_outputs.append(guard_node.inputs[0].links[0].from_socket)+ guard_floor = guard_node.inputs[1].links[0].from_node+ guard_outputs.append(guard_floor.inputs[0].links[0].from_socket)+ else:+ raw_outputs.append(all_w_outputs[-1])+ guard_outputs.append(None)+ all_w_outputs, feather_outputs = _apply_guard_coverage_rescue(+ nodes_collection, links, all_w_outputs, raw_outputs, guard_outputs, feather_outputs,+ getattr(context.scene, 'sg_guard_coverage_rescue', 0.0), occlusion_outputs,+ occlusion_influence_outputs,+ getattr(context.scene, 'sg_guard_feather_method', 'ORIGINAL'))# ── Step 3: Find per-pixel maximum ────────────────────────max_node = nodes_collection.new("ShaderNodeMath")@@ -1399,6 +1669,7 @@ def project_image(# ── Step 4: Normalize + re-apply exponent ─────────────────powered_nodes = []+ normalized_outputs = []for idx, w_out in enumerate(all_w_outputs):# norm_w = base_w / max(base_w)div = nodes_collection.new("ShaderNodeMath")@@ -1422,9 +1693,13 @@ def project_image(pw.inputs[1].default_value = user_exponentlinks.new(div.outputs[0], pw.inputs[0])powered_nodes.append(pw)+ normalized_outputs.append(div.outputs[0])# Replace weight_nodes with sharpened-normalised nodes- weight_nodes = powered_nodes+ weight_nodes = _apply_projection_feathers(+ nodes_collection, links, powered_nodes, feather_outputs,+ normalized_outputs, influence_outputs,+ getattr(context.scene, 'sg_guard_feather_method', 'ORIGINAL'))new_shaders = []new_weight_nodes = []@@ -1551,6 +1826,10 @@ def project_image()else:cameras = list(cameras)++ if surface_blend:+ from .surface_blend import validate+ validate(context, to_project, cameras)# Force refresh of the UIfor area in context.screen.areas:@@ -1644,6 +1923,9 @@ def project_image(is_sequential = context.scene.generation_method == 'sequential'missing_bake = any(obj.data.attributes.get(f"_SG_VisWeight_{cam_idx}_{mat_id}") is None+ or (getattr(context.scene, 'sg_rework_projection_guard', False)+ and getattr(context.scene, 'sg_silhouette_feather', 0) > 0+ and obj.data.attributes.get(f"_SG_ProjectionDepth_{cam_idx}_{mat_id}") is None)for obj in to_project for cam_idx in range(len(cameras)))if not is_sequential or stop_index == 0 or missing_bake:@@ -1699,6 +1981,9 @@ def project_image(if original_mat != mat:obj.data.materials.append(original_mat)+ if surface_blend and mat.name in processed_materials:+ continue+# Enable use of nodesmat.use_nodes = Truenodes = mat.node_tree.nodes@@ -2393,6 +2678,95 @@ def project_image(links.new(script_nodes_outputs[-1].outputs[0], guarded.inputs[0])links.new(guard_floor.outputs[0], guarded.inputs[1])script_nodes_outputs[-1] = guarded+ if (len(cameras) > 1+ and getattr(context.scene, 'sg_silhouette_feather', 0) > 0):+ feather_path = os.path.join(+ get_dir_path(context, "inpaint")["visibility"],+ f"projection_guard_feather{i}.png",+ )+ if os.path.isfile(feather_path):+ feather_image = get_or_load_image(+ feather_path, force_reload=context.scene.overwrite_material)+ if feather_image is not None:+ feather_image.colorspace_settings.name = 'Non-Color'+ feather_tex = nodes.new("ShaderNodeTexImage")+ feather_tex.image = feather_image+ feather_tex.extension = 'CLIP'+ feather_tex.interpolation = 'Linear'+ feather_tex.label = f"ProjectionGuardFeather-{i}-{mat_id}"+ uv = uv_map_nodes[i]+ links.new(uv.outputs['Vector' if uv.type == 'ATTRIBUTE' else 'UV'],+ feather_tex.inputs['Vector'])+ feathered = nodes.new("ShaderNodeMath")+ feathered.operation = 'MULTIPLY'+ feathered.label = f"DepthPartFeathered-{i}-{mat_id}"+ links.new(guarded.outputs[0], feathered.inputs[0])+ links.new(feather_tex.outputs[0], feathered.inputs[1])+ script_nodes_outputs[-1] = feathered+ occlusion_path = os.path.join(os.path.dirname(feather_path),+ f"projection_occlusion_geometry{i}.png")+ calibration_path = os.path.splitext(occlusion_path)[0] + '.json'+ if os.path.isfile(occlusion_path) and os.path.isfile(calibration_path):+ import json+ with open(calibration_path) as stream:+ distance_scale = float(json.load(stream)['distance_scale'])+ occlusion_image = get_or_load_image(+ occlusion_path, force_reload=context.scene.overwrite_material)+ occlusion_image.colorspace_settings.name = 'Non-Color'+ occlusion_tex = nodes.new("ShaderNodeTexImage")+ occlusion_tex.label = f"ProjectionOcclusionFeather-{i}-{mat_id}"+ occlusion_tex.image = occlusion_image+ occlusion_tex.extension = 'CLIP'+ occlusion_tex.interpolation = 'Linear'+ links.new(feather_tex.inputs['Vector'].links[0].from_socket,+ occlusion_tex.inputs['Vector'])+ channels = nodes.new('ShaderNodeSeparateColor')+ links.new(occlusion_tex.outputs['Color'], channels.inputs[0])+ # Cycles' Z pass is camera-axis depth, not+ # Euclidean distance along the perspective ray.+ if use_baked_weights:+ receiver = nodes.new('ShaderNodeAttribute')+ receiver.attribute_name = f'_SG_ProjectionDepth_{i}_{mat_id}'+ depth_socket = receiver.outputs['Fac']+ divisor = distance_scale+ else:+ coordinates = nodes.new('ShaderNodeTexCoord')+ coordinates.object = camera+ camera_space = nodes.new('ShaderNodeSeparateXYZ')+ links.new(coordinates.outputs['Object'], camera_space.inputs[0])+ depth_socket = camera_space.outputs['Z']+ divisor = -distance_scale / max(camera.matrix_world.to_scale().z, 1e-12)+ normalized = _projection_feather_math(nodes, links, 'DIVIDE',+ f'OcclusionReceiverDepth-{i}', depth_socket, divisor)+ far = _projection_feather_math(nodes, links, 'GREATER_THAN',+ f'OcclusionReceiverFar-{i}', normalized.outputs[0], channels.outputs['Blue'])+ rejected = _projection_feather_math(nodes, links, 'SUBTRACT',+ f'OcclusionInverseFade-{i}', 1.0, channels.outputs['Red'])+ rejected = _projection_feather_math(nodes, links, 'MULTIPLY',+ f'OcclusionFarFade-{i}', far.outputs[0], rejected.outputs[0])+ protected = _projection_feather_math(nodes, links, 'SUBTRACT',+ f'OcclusionProtectedFade-{i}', 1.0, rejected.outputs[0])+ protected.name = f'SGOcclusionFeather-{i}-{mat_id}'+ # Merge the receiver-aware shoulder into local+ # unsharpen after loading the ordinary guard field.+ occlusion_shoulder = _projection_feather_math(nodes, links, 'MULTIPLY',+ f'OcclusionInfluence-{i}', far.outputs[0], channels.outputs['Green'])+ occlusion_shoulder.name = f'SGOcclusionInfluence-{i}-{mat_id}'+ if getattr(context.scene, 'sg_guard_feather_method', 'ORIGINAL') == 'LOCAL_UNSHARPEN':+ influence_path = os.path.join(os.path.dirname(feather_path),+ f"projection_guard_influence{i}.png")+ if os.path.isfile(influence_path):+ influence_image = get_or_load_image(+ influence_path, force_reload=context.scene.overwrite_material)+ influence_image.colorspace_settings.name = 'Non-Color'+ influence_tex = nodes.new("ShaderNodeTexImage")+ influence_tex.name = f"SGFeatherInfluence-{i}-{mat_id}"+ influence_tex.label = f"ProjectionGuardInfluence-{i}-{mat_id}"+ influence_tex.image = influence_image+ influence_tex.extension = 'CLIP'+ influence_tex.interpolation = 'Linear'+ links.new(feather_tex.inputs['Vector'].links[0].from_socket,+ influence_tex.inputs['Vector'])# Confidence is deliberately independent from colour ownership.# Preserve the unnormalised source-camera quality before the mix@@ -2641,6 +3015,9 @@ def reset_projection_material_nodes(material, angle_threshold, exponent):"""Reset display controls without changing stored source confidence."""if not material or not material.use_nodes:return False+ if material.get('sg_surface_blend') and any(n.label.startswith('SurfaceBlendWeight-') for n in material.node_tree.nodes):+ from .surface_blend import update+ update(material, angle_threshold, exponent)nodes = material.node_tree.nodeshas_sharp = any(node.type == 'MATH' and node.operation == 'POWER'diff --git a/stablegen/texturing/quality_masks.py b/stablegen/texturing/quality_masks.pyindex 9735f57..c8de872 100644--- a/stablegen/texturing/quality_masks.py+++ b/stablegen/texturing/quality_masks.py@@ -254,6 +254,102 @@ def residual_fallback_percentage(write_mask, generated_bgr, fallback_rgb, tolerareturn float(np.count_nonzero(editable & sentinel) * 100.0 / np.count_nonzero(editable))+def feather_projection_guard(guard, width):+ """Fade into safe pixels without admitting any rejected silhouette pixels."""+ width = max(0.0, float(width))+ if width == 0:+ return guard.copy()+ allowed = (guard > 0).astype(np.uint8)+ distance = cv2.distanceTransform(allowed, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)+ ramp = np.clip(distance / width, 0.0, 1.0)+ ramp = ramp * ramp * (3.0 - 2.0 * ramp)+ return np.rint(ramp * 255).astype(np.uint8)+++def projection_guard_feather_influence(guard, width):+ """Keep sharpening off across the fade; restore it over one extra width."""+ width = max(0.0, float(width))+ if width == 0:+ return np.zeros_like(guard)+ distance = cv2.distanceTransform((guard > 0).astype(np.uint8), cv2.DIST_L2, cv2.DIST_MASK_PRECISE)+ ramp = np.clip((distance - width) / width, 0.0, 1.0)+ ramp = ramp * ramp * (3.0 - 2.0 * ramp)+ return np.rint((1.0 - ramp) * 255).astype(np.uint8)+++def projection_occlusion_fields(depth, width, depth_threshold, object_ids=None, surface_distance=None):+ """Fade only the far surface approaching a resolved depth discontinuity.++ Unlike a part/margin guard, this field must survive coverage rescue. Carry+ the nearest boundary's occluder depth so its fade cannot spill onto the+ near surface (e.g. from the neck onto the visible chin). Object boundaries+ with a resolved depth order catch thin nearby occluders below the general+ depth threshold. Flat ID seams and foreground margins do not seed it.+ """+ if depth.ndim == 3:+ depth = cv2.cvtColor(depth, cv2.COLOR_BGR2GRAY)+ depth = depth.astype(np.uint8)+ width = max(0.0, float(width))+ white = np.full(depth.shape, 255, dtype=np.uint8)+ empty = np.zeros_like(depth)+ if width == 0:+ return (white, empty, np.zeros(depth.shape, np.float32)) if surface_distance is not None else (white, empty)+ threshold = max(0, int(depth_threshold))+ near = cv2.dilate(depth, np.ones((3, 3), np.uint8))+ seeds = near.astype(np.int16) - depth > threshold+ seed_threshold = np.full(depth.shape, threshold, dtype=np.int16)+ if object_ids is not None:+ if object_ids.ndim == 3:+ object_ids = cv2.cvtColor(object_ids, cv2.COLOR_BGR2GRAY)+ if object_ids.shape != depth.shape:+ object_ids = cv2.resize(object_ids, (depth.shape[1], depth.shape[0]),+ interpolation=cv2.INTER_NEAREST)+ padded_depth = np.pad(depth, 1, mode='edge')+ padded_ids = np.pad(object_ids, 1, mode='edge')+ object_near = depth.copy()+ for dy, dx in ((dy, dx) for dy in range(3) for dx in range(3) if (dy, dx) != (1, 1)):+ neighbor = padded_depth[dy:dy+depth.shape[0], dx:dx+depth.shape[1]]+ ids = padded_ids[dy:dy+depth.shape[0], dx:dx+depth.shape[1]]+ # Ignore a single quantization step and never infer ordering from+ # IDs alone. Compare against the OTHER object's depth explicitly.+ ordered = (ids != object_ids) & (neighbor.astype(np.int16) - depth > 1)+ object_near = np.maximum(object_near, np.where(ordered, neighbor, 0))+ object_seeds = object_near.astype(np.int16) - depth > 1+ near = np.where(object_seeds, object_near, near)+ seed_threshold[object_seeds] = 1+ seeds |= object_seeds+ if not np.any(seeds):+ return (white, empty, np.zeros(depth.shape, np.float32)) if surface_distance is not None else (white, empty)+ allowed = (~seeds).astype(np.uint8)+ # Labels identify the occluder belonging to the nearest boundary pixel.+ # Use the precise transform separately for the continuous feather width.+ _, labels = cv2.distanceTransformWithLabels(+ allowed, cv2.DIST_L2, 5, labelType=cv2.DIST_LABEL_PIXEL)+ references = np.zeros(int(labels.max()) + 1, dtype=np.int16)+ references[labels[seeds]] = near[seeds]+ thresholds = np.zeros_like(references)+ thresholds[labels[seeds]] = seed_threshold[seeds]+ far_side = references[labels] - depth > thresholds[labels]+ distance = cv2.distanceTransform(allowed, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)+ ramp = np.clip(distance / width, 0.0, 1.0)+ fade = ramp * ramp * (3.0 - 2.0 * ramp)+ shoulder = np.clip((distance - width) / width, 0.0, 1.0)+ influence = 1.0 - shoulder * shoulder * (3.0 - 2.0 * shoulder)+ if surface_distance is not None:+ # Keep the ramp continuous on BOTH sides of the image boundary.+ # The shader identifies the receiving surface by camera distance;+ # baking the foreground exemption into this image lets filtering+ # reintroduce the foreground's white value onto the far surface.+ nearest = cv2.erode(surface_distance, np.ones((3, 3), np.uint8))+ midpoint = (nearest + surface_distance) * 0.5+ reference = np.zeros(int(labels.max()) + 1, dtype=np.float32)+ reference[labels[seeds]] = midpoint[seeds]+ return (np.rint(fade * 255).astype(np.uint8),+ np.rint(influence * 255).astype(np.uint8), reference[labels])+ return (np.where(far_side, np.rint(fade * 255), 255).astype(np.uint8),+ np.where(far_side, np.rint(influence * 255), 0).astype(np.uint8))++def build_depth_part_rejection_mask(depth,object_ids=None,@@ -261,6 +357,7 @@ def build_depth_part_rejection_mask(*,margin=3,depth_threshold=3,+ foreground_margin=None,return_diagnostics=False,):"""Build a per-pixel projection guard around depth/part silhouettes.@@ -275,7 +372,7 @@ def build_depth_part_rejection_mask(depth = cv2.cvtColor(depth, cv2.COLOR_BGR2GRAY)depth = depth.astype(np.uint8)margin = max(0, int(margin))- if margin == 0:+ if margin == 0 and (foreground_margin is None or foreground_margin <= 0):guard = np.full(depth.shape, 255, dtype=np.uint8)diagnostics = {"mode": "disabled",@@ -288,6 +385,7 @@ def build_depth_part_rejection_mask(depth_range = cv2.dilate(depth, kernel3) - cv2.erode(depth, kernel3)depth_edge = depth_range > max(0, int(depth_threshold))edge = depth_edge.copy()+ id_edge = np.zeros(depth.shape, dtype=bool)used_part_ids = Falsefor ids in (object_ids, material_ids):@@ -299,7 +397,9 @@ def build_depth_part_rejection_mask(ids = cv2.resize(ids, (depth.shape[1], depth.shape[0]), interpolation=cv2.INTER_NEAREST)- edge |= cv2.dilate(ids, kernel3) != cv2.erode(ids, kernel3)+ boundary = cv2.dilate(ids, kernel3) != cv2.erode(ids, kernel3)+ id_edge |= boundary+ edge |= boundaryused_part_ids = Truedef _guard_from_edges(edges):@@ -312,7 +412,43 @@ def build_depth_part_rejection_mask()return np.where(edge_u8 > 0, 0, 255).astype(np.uint8)- guard = _guard_from_edges(edge)+ def _directional_guard(include_ids):+ # Inverted normalized depth: larger values are nearer the camera.+ # Carry the opposite side's depth while expanding a rejection band,+ # then compare at the destination. Ordinary dilation crosses onto the+ # foreground (e.g. the visible chin above a neck occlusion).+ threshold = max(0, int(depth_threshold))+ fg_margin = max(0, int(foreground_margin))+ near = cv2.dilate(depth, kernel3)+ far = cv2.erode(depth, kernel3)+ far_seed = near.astype(np.int16) - depth > threshold+ near_seed = depth.astype(np.int16) - far > threshold+ ambiguous = np.zeros_like(id_edge)+ if include_ids:+ radius = max(margin, fg_margin, 1) + 1+ neighborhood = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1))+ id_near, id_far = cv2.dilate(depth, neighborhood), cv2.erode(depth, neighborhood)+ far_ids = id_edge & (id_near.astype(np.int16) - depth > threshold)+ near_ids = id_edge & (depth.astype(np.int16) - id_far > threshold)+ near = np.where(far_ids, np.maximum(near, id_near), near)+ far = np.where(near_ids, np.minimum(far, id_far), far)+ far_seed |= far_ids+ near_seed |= near_ids+ # Without a resolvable depth order, keep symmetric part protection.+ ambiguous = id_edge & ((id_near.astype(np.int16) - id_far) <= threshold)+ rejected = np.zeros_like(id_edge)+ if margin > 0:+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*margin+1, 2*margin+1))+ nearer_reference = cv2.dilate(np.where(far_seed, near, 0).astype(np.uint8), kernel)+ rejected |= nearer_reference.astype(np.int16) - depth > threshold+ rejected |= cv2.dilate(ambiguous.astype(np.uint8), kernel) > 0+ if fg_margin > 0:+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*fg_margin+1, 2*fg_margin+1))+ farther_reference = cv2.erode(np.where(near_seed, far, 255).astype(np.uint8), kernel)+ rejected |= depth.astype(np.int16) - farther_reference > threshold+ return np.where(rejected, 0, 255).astype(np.uint8)++ guard = _guard_from_edges(edge) if foreground_margin is None else _directional_guard(used_part_ids)# Categorical render passes must be noise-free, but older outputs and# third-party render settings can contain one-LSB dither. Treating that as@@ -333,7 +469,8 @@ def build_depth_part_rejection_mask()diagnostics["id_guard_allowed_foreground_percent"] = allowed_fraction * 100.0if allowed_fraction < 0.10:- guard = _guard_from_edges(depth_edge)+ guard = (_guard_from_edges(depth_edge) if foreground_margin is None+ else _directional_guard(False))diagnostics["mode"] = "depth_only_fallback"diagnostics["fallback_triggered"] = Truediff --git a/stablegen/texturing/surface_blend.py b/stablegen/texturing/surface_blend.pynew file mode 100644index 0000000..a00709f--- /dev/null+++ b/stablegen/texturing/surface_blend.py@@ -0,0 +1,302 @@+"""Joint surface weights. Pure NumPy solver plus a Blender POINT-field adapter.++The field is continuous over mesh triangles, rather than a succession of+independently normalized camera subsets. Sampling accuracy is mesh dependent.+"""+import heapq+import json+import math+import numpy as np+++def normalize(values):+ return np.divide(values, values.sum(axis=1, keepdims=True),+ out=np.zeros_like(values), where=values.sum(axis=1, keepdims=True) > 0)+++def simplex(values, allowed):+ """Euclidean projection onto each vertex's valid-camera probability simplex."""+ count = allowed.sum(axis=1)+ ordered = np.sort(np.where(allowed, values, -1e30), axis=1)[:, ::-1]+ sums = np.cumsum(ordered, axis=1) - 1+ ranks = np.arange(1, values.shape[1] + 1)+ positive = (ordered - sums / ranks > 0) & (ranks <= count[:, None])+ rho = np.maximum(positive.sum(axis=1), 1)+ theta = sums[np.arange(len(values)), rho - 1] / rho+ result = np.where(allowed, np.maximum(values - theta[:, None], 0), 0)+ result[count == 0] = 0+ return result+++def transition_band(positions, edges, allowed, radius):+ """Geodesic distance from a camera-support boundary, in feather widths."""+ n = len(positions)+ if len(edges) == 0:+ return np.zeros(n, bool)+ a, b = edges.T+ lengths = np.linalg.norm(positions[a] - positions[b], axis=1)+ cost = lengths / np.maximum((radius[a] + radius[b]) * .5, 1e-12)+ boundary = np.any(allowed[a] != allowed[b], axis=1)+ distance = np.full(n, np.inf)+ adjacency = [[] for _ in range(n)]+ for i, j, c in zip(a, b, cost):+ adjacency[i].append((j, c)); adjacency[j].append((i, c))+ seeds = np.unique(edges[boundary])+ distance[seeds] = 0+ queue = [(0., int(i)) for i in seeds]+ heapq.heapify(queue)+ while queue:+ value, i = heapq.heappop(queue)+ if value != distance[i] or value >= 1:+ continue+ for j, c in adjacency[i]:+ candidate = value + c+ if candidate < min(distance[j], 1.):+ distance[j] = candidate+ heapq.heappush(queue, (candidate, int(j)))+ return distance < 1+++def solve(positions, edges, quality, guard, radius, exponent, rescue=.25,+ tolerance=1e-7, max_iterations=2000):+ """Minimize neighbor disagreement subject to visibility and sum-to-one.++ Preferences are fixed outside a geodesic band. Within it all camera+ contributions are solved together, with invalid components fixed at zero.+ Conservative guards may be relaxed for coverage; genuine visibility never is.+ """+ quality = np.maximum(np.asarray(quality, dtype=np.float64), 0)+ visible = quality > 0+ trusted = quality * np.clip(guard, 0, 1)+ best = quality.max(axis=1)+ recover = trusted.max(axis=1) < best * max(rescue, 0)+ allowed = visible & ((guard > .5) | recover[:, None])+ # No trusted source: explicitly retain genuine coverage. Never manufacture+ # an occluded source, and never normalize a zero vector into a color.+ empty = ~allowed.any(axis=1) & visible.any(axis=1)+ allowed[empty] = visible[empty]+ a, b = np.asarray(edges, dtype=np.int64).reshape(-1, 2).T+ # A camera must already be zero on the visible side of a sampled true+ # visibility boundary; runtime raycast must not cut an interpolated weight.+ safe = allowed.copy()+ for camera in range(quality.shape[1]):+ crossing = visible[a, camera] != visible[b, camera]+ safe[np.unique(np.concatenate((a[crossing], b[crossing]))), camera] = False+ narrow = ~safe.any(axis=1) & allowed.any(axis=1)+ safe[narrow] = allowed[narrow]+ allowed = safe+ preferred = np.where(allowed, quality, 0)+ maximum = preferred.max(axis=1, keepdims=True)+ preferred = np.divide(preferred, maximum, out=np.zeros_like(preferred), where=maximum > 0)+ preferred = normalize(preferred ** max(float(exponent), .001))+ band = transition_band(positions, edges, allowed, radius)+ active = band & (allowed.sum(axis=1) > 1)+ weights = preferred.copy()+ # Symmetric positive edge weights yield a convex Dirichlet energy. Do not+ # link separate objects or disconnected mesh components by spatial proximity.+ length = np.linalg.norm(positions[a] - positions[b], axis=1)+ conductance = 1 / np.maximum(length, 1e-9)+ src = np.concatenate((a, b)); dst = np.concatenate((b, a))+ conductance = np.concatenate((conductance, conductance))+ # Uncovered vertices cannot act as artificial black boundary conditions.+ covered = allowed.any(axis=1)+ conductance *= covered[src] & covered[dst]+ degree = np.bincount(src, weights=conductance, minlength=len(positions))+ active &= degree > 0+ change = 0.; iteration = 0+ if active.any():+ extrapolated = weights.copy(); momentum = 1.; settled = 0+ for iteration in range(1, max_iterations + 1):+ average = np.column_stack([+ np.bincount(src, weights=conductance * extrapolated[dst, c], minlength=len(positions))+ for c in range(quality.shape[1])])+ average /= np.maximum(degree[:, None], 1e-12)+ candidate = simplex(.5*(extrapolated[active]+average[active]), allowed[active])+ change = float(np.max(np.abs(candidate - weights[active])))+ # Accelerated projected gradient in the degree-weighted metric.+ # A half step bounds the normalized Laplacian spectrum by one.+ next_momentum = (1+math.sqrt(1+4*momentum*momentum))*.5+ delta = candidate-weights[active]+ restart = np.sum(degree[active,None]*(extrapolated[active]-candidate)*delta) > 0+ if restart:+ next_momentum = 1.+ extrapolated[active] = candidate+ else:+ extrapolated[active] = candidate+(momentum-1)/next_momentum*delta+ weights[active] = candidate; momentum = next_momentum+ settled = settled+1 if change < tolerance else 0+ if settled >= 8:+ break+ return weights, {'iterations': iteration, 'residual': change,+ 'converged': change < tolerance, 'band_vertices': int(active.sum()),+ 'uncovered_vertices': int((~covered).sum()),+ 'narrow_coverage_vertices': int(narrow.sum()),+ 'recovered_vertices': int((recover | empty).sum())}+++def _attribute(mesh, name, values=None, vector=False):+ attr = mesh.attributes.get(name)+ if values is None:+ if attr is None:+ raise RuntimeError('Surface Blend inputs are missing; Reproject to rebuild them')+ data = np.empty((len(mesh.vertices), 3) if vector else len(mesh.vertices), np.float32)+ attr.data.foreach_get('vector' if vector else 'value', data.ravel())+ return data+ if attr is None:+ attr = mesh.attributes.new(name, 'FLOAT_VECTOR' if vector else 'FLOAT', 'POINT')+ attr.data.foreach_set('vector' if vector else 'value', np.asarray(values, np.float32).ravel())+++def validate(context, objects, cameras):+ """Reject unsupported inputs before replacing any projection material."""+ if any(c.data.type not in {'PERSP','ORTHO'} for c in cameras):+ raise ValueError('Surface Blend preview supports perspective and orthographic cameras')+ depsgraph = context.evaluated_depsgraph_get(); seen = set()+ for obj in objects:+ identity = obj.data.as_pointer()+ if identity in seen:+ raise ValueError('Surface Blend preview requires single-user mesh data; make linked meshes single-user first')+ seen.add(identity)+ evaluated = obj.evaluated_get(depsgraph); mesh = evaluated.to_mesh()+ try:+ if len(mesh.vertices) != len(obj.data.vertices):+ raise ValueError(f'Surface Blend: apply topology-changing modifiers on {obj.name} before Reproject')+ finally:+ evaluated.to_mesh_clear()+++def update(material, angle, exponent):+ """Update cached preference/angle controls without repeating raycasts."""+ import bpy+ metadata = json.loads(material['sg_surface_blend'])+ if metadata.get('angle') == angle and metadata.get('exponent') == exponent:+ return+ reports = []+ for name in metadata['objects']:+ obj = bpy.data.objects.get(name)+ if obj is None:+ raise RuntimeError('Surface Blend mesh changed; Reproject to rebuild its field')+ mesh = obj.data; key = metadata['key']; count = metadata['cameras']+ positions = _attribute(mesh, key + 'Position', vector=True)+ edges = np.empty((len(mesh.edges), 2), np.int32)+ mesh.edges.foreach_get('vertices', edges.ravel())+ quality = np.column_stack([_attribute(mesh, key + f'Quality{i}') for i in range(count)])+ cosines = np.column_stack([_attribute(mesh, key + f'Cosine{i}') for i in range(count)])+ quality[cosines <= math.cos(math.radians(min(float(angle), 90.)))] = 0+ guards = np.column_stack([_attribute(mesh, key + f'Guard{i}') for i in range(count)])+ weights, report = solve(positions, edges, quality, guards,+ _attribute(mesh, key + 'Radius'), exponent, metadata['rescue'])+ for i in range(count):+ _attribute(mesh, key + f'Weight{i}', weights[:, i])+ mesh.update(); reports.append({'object': name, **report})+ metadata.update(angle=angle, exponent=exponent, reports=reports)+ material['sg_surface_blend'] = json.dumps(metadata)+ print('[StableGen] Surface Blend:', reports)+++def build(context, objects, cameras, images, material, mat_id, stop_index):+ """Sample evaluated geometry and projection masks; cache a surface field."""+ import bpy+ import cv2+ from mathutils import Vector+ from mathutils.bvhtree import BVHTree+ from .projection import _is_projection_mesh, _scene_ray_epsilon, _scene_projection_scale+ from ..utils import get_dir_path+ from ..cameras.geometry import _get_camera_resolution+ from pathlib import Path+ scene = context.scene; depsgraph = context.evaluated_depsgraph_get()+ vertices = []; polygons = []+ for ob in context.view_layer.objects:+ if not _is_projection_mesh(ob):+ continue+ evaluated = ob.evaluated_get(depsgraph); mesh = evaluated.to_mesh()+ try:+ offset = len(vertices)+ vertices.extend(evaluated.matrix_world @ v.co for v in mesh.vertices)+ polygons.extend(tuple(offset + i for i in p.vertices) for p in mesh.polygons)+ finally:+ evaluated.to_mesh_clear()+ tree = BVHTree.FromPolygons(vertices, polygons)+ epsilon = _scene_ray_epsilon(context); scale = _scene_projection_scale(context)+ key = f'_SG_Surface{mat_id}_'; paths = Path(get_dir_path(context, 'inpaint')['visibility'])+ cache = {}+ def sample(path, uv, default=1.):+ if path not in cache:+ cache[path] = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) if Path(path).is_file() else None+ image = cache[path]+ if image is None:+ return np.full(len(uv), default)+ x = np.clip(uv[:, 0] * image.shape[1] - .5, 0, image.shape[1]-1)+ y = np.clip((1-uv[:, 1]) * image.shape[0] - .5, 0, image.shape[0]-1)+ ix = x.astype(int); iy = y.astype(int); fx = x-ix; fy = y-iy+ if image.ndim == 3:+ # This adapter samples alpha from source images, scalar from masks.+ image = image[:, :, 3] if image.shape[2] == 4 else np.full(image.shape[:2], 255, np.uint8)+ value = ((1-fy)*((1-fx)*image[iy, ix]+fx*image[iy, np.minimum(ix+1,image.shape[1]-1)])+ +fy*((1-fx)*image[np.minimum(iy+1,image.shape[0]-1),ix]+ +fx*image[np.minimum(iy+1,image.shape[0]-1),np.minimum(ix+1,image.shape[1]-1)]))+ return value / (65535 if image.dtype == np.uint16 else 255)+ names = []+ for obj in objects:+ evaluated = obj.evaluated_get(depsgraph); mesh = evaluated.to_mesh()+ try:+ if len(mesh.vertices) != len(obj.data.vertices):+ raise RuntimeError(f'Surface Blend: {obj.name} has topology-changing modifiers; apply them before Reproject')+ positions = np.array([evaluated.matrix_world @ v.co for v in mesh.vertices])+ normal_matrix = evaluated.matrix_world.to_3x3().inverted().transposed()+ normals = np.array([(normal_matrix @ v.normal).normalized() for v in mesh.vertices])+ finally:+ evaluated.to_mesh_clear()+ mesh = obj.data; n = len(mesh.vertices)+ if n == 0:+ continue+ names.append(obj.name); _attribute(mesh, key+'Position', positions, vector=True)+ widths = []+ loops = np.empty(len(mesh.loops), np.int32); mesh.loops.foreach_get('vertex_index', loops)+ loop_counts = np.maximum(np.bincount(loops, minlength=n), 1)+ for i, camera in enumerate(cameras):+ uv_attr = mesh.attributes.get(f'ProjectionUV_{i}_{mat_id}')+ if uv_attr is None:+ raise RuntimeError('Surface Blend requires projection coordinates; run Reproject')+ coords = np.empty((len(uv_attr.data), 3), np.float32); uv_attr.data.foreach_get('vector', coords.ravel())+ uv = np.column_stack([np.bincount(loops, weights=coords[:, c], minlength=n)/loop_counts for c in range(2)]) if uv_attr.domain == 'CORNER' else coords[:, :2]+ location = np.array(camera.matrix_world.translation)+ delta = positions-location; distance = np.linalg.norm(delta, axis=1)+ forward = np.array(camera.matrix_world.to_quaternion() @ Vector((0,0,-1)))+ depth = delta @ forward+ direction = delta / np.maximum(distance[:, None], 1e-12)+ if camera.data.type == 'ORTHO':+ direction[:] = forward; distance = depth+ dot = -np.sum(normals*direction, axis=1)+ cosine = np.abs(dot) if scene.sg_allow_backface_projection else np.maximum(dot, 0)+ visible = (depth > 0) & np.all((uv >= 0) & (uv <= 1), axis=1)+ if i > stop_index or images[i].image is None or images[i].image.size[0] == 0:+ visible[:] = False+ for index in np.flatnonzero(visible):+ origin = location if camera.data.type != 'ORTHO' else positions[index]-forward*distance[index]+ hit, _, _, hit_distance = tree.ray_cast(Vector(origin),Vector(direction[index]),float(distance[index])+epsilon*10)+ visible[index] = hit is not None and abs(hit_distance-distance[index]) <= epsilon*2+ x, y = _get_camera_resolution(camera, scene)+ fov = camera.data.angle_x+ if y > x: fov = 2*math.atan(math.tan(fov/2)*x/y)+ world_pixel = (np.full(n,camera.data.ortho_scale/y) if camera.data.type == 'ORTHO'+ else 2*np.maximum(depth,epsilon)*math.tan(fov/2)/x)+ widths.append(world_pixel * scene.sg_silhouette_feather)+ quality = cosine * visible+ if scene.sg_rework_acquisition_quality:+ quality *= np.clip(scale/np.maximum(world_pixel,epsilon)/(max(.5*min(x,y),1)),0,1)+ if scene.visibility_vignette:+ w = max(min(scene.visibility_vignette_width,.49),1e-9)+ edge = np.max(np.abs(uv*2-1),axis=1)+ t = np.clip((edge-(1-w))/w,0,1)+ quality *= (1-t*t*(3-2*t)) ** max(scene.visibility_vignette_softness,.01)+ if images[i].image is not None:+ quality *= sample(bpy.path.abspath(images[i].image.filepath),uv)+ _attribute(mesh,key+f'Quality{i}',quality)+ _attribute(mesh,key+f'Cosine{i}',cosine)+ _attribute(mesh,key+f'Guard{i}',sample(paths/f'projection_guard{i}.png',uv))+ _attribute(mesh,key+'Radius',np.median(widths,axis=0))+ material['sg_surface_blend'] = json.dumps({'version':1,'objects':names,'key':key,+ 'cameras':len(cameras),'rescue':scene.sg_guard_coverage_rescue})+ update(material,scene.discard_factor,scene.weight_exponent)+ return keydiff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.pyindex 3a6b9a7..ae89855 100644--- a/stablegen/ui/panel.py+++ b/stablegen/ui/panel.py@@ -1364,7 +1364,7 @@ class StableGenPanel(bpy.types.Panel):content_box = Noneif content_box:# Row 1: Discard-Over Angle | Weight Exponent- split = content_box.split(factor=0.5, align=True)+ split = content_box.split(factor=0.5, align=False)sub = split.row()if 'discard_factor' in _diff_props:sub.alert = True@@ -1385,7 +1385,7 @@ class StableGenPanel(bpy.types.Panel):split.prop(scene, "weight_exponent_generation_only", text="Reset Exponent", toggle=True)if scene.discard_factor_generation_only or scene.weight_exponent_generation_only:- split = content_box.split(factor=0.5, align=True)+ split = content_box.split(factor=0.5, align=False)if scene.discard_factor_generation_only:split.prop(scene, "discard_factor_after_generation", text="Angle After")else:@@ -1414,8 +1414,31 @@ class StableGenPanel(bpy.types.Panel):row = content_box.row(align=True)row.prop(scene, "sg_rework_acquisition_quality", text="Acquisition Quality Weighting", toggle=True)content_box.prop(scene, "sg_rework_projection_guard", text="Depth/Part Projection Guard", toggle=True)- content_box.prop(scene, "sg_silhouette_margin", text="Silhouette Margin (px)")- content_box.prop(scene, "sg_silhouette_depth", text="Silhouette Depth Threshold")+ if scene.sg_rework_projection_guard:+ guard_box = content_box.box()+ guard_box.prop(scene, "sg_guard_directional", toggle=True)+ row = (guard_box.split(factor=0.5, align=False)+ if width_mode == 'wide' and scene.sg_guard_directional+ else guard_box.row(align=True))+ row.prop(scene, "sg_silhouette_margin", text=(+ "Background Margin (px)" if scene.sg_guard_directional else "Silhouette Margin (px)"))+ if scene.sg_guard_directional:+ if width_mode == 'narrow':+ row = guard_box.row(align=True)+ row.prop(scene, "sg_guard_foreground_margin", text="Foreground Margin (px)")+ row = (guard_box.split(factor=0.5, align=False) if width_mode == 'wide'+ else guard_box.row(align=True))+ row.prop(scene, "sg_silhouette_depth", text="Depth Threshold")+ if width_mode == 'narrow':+ row = guard_box.row(align=True)+ row.prop(scene, "sg_guard_coverage_rescue")+ row = guard_box.row(align=True)+ row.prop(scene, "sg_silhouette_feather", text="Silhouette Feather (px)")+ row = guard_box.row(align=True)+ row.prop(scene, "sg_projection_guard_scale", text="Guard Resolution")+ guard_box.prop(scene, "sg_guard_feather_method", text="Feather Method")+ if scene.sg_guard_feather_method == 'SURFACE_BLEND':+ guard_box.label(text="Reproject to solve; detail follows mesh density", icon='INFO')if _show_diffusion_sections and experiments_enabled(context):experiments = draw_collapsible_section(diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.pyindex e009337..ec50a84 100644--- a/stablegen/ui/presets.py+++ b/stablegen/ui/presets.py@@ -296,6 +296,12 @@ GEN_PARAMETERS = ['visibility_vignette_softness','visibility_vignette_blur','sg_silhouette_margin',+ 'sg_silhouette_feather',+ 'sg_projection_guard_scale',+ 'sg_guard_feather_method',+ 'sg_guard_directional',+ 'sg_guard_foreground_margin',+ 'sg_guard_coverage_rescue','sg_silhouette_depth','sg_silhouette_rays','sg_allow_backface_projection',