Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
Merge pull request #63 from ManglerFTW/refine-mirror-support into a new branch to prepare for further merging
ManglerFTW0cb5caad6e26
diff --git a/stablegen/__init__.py b/stablegen/__init__.pyold mode 100755new mode 100644index 311d7eb..df51924--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -3,7 +3,7 @@ import bpy # pylint: disable=import-errorfrom .stablegen import StableGenPanel, ApplyPreset, SavePreset, DeletePreset, get_preset_items, update_parameters, ResetQwenPromptfrom .render_tools import BakeTextures, AddCameras, SwitchMaterial, ExportOrbitGIF, CollectCameraPrompts, CameraPromptItemfrom .utils import AddHDRI, ApplyModifiers, CurvesToMesh-from .generator import ComfyUIGenerate, Reproject, Regenerate+from .generator import ComfyUIGenerate, Reproject, Regenerate, MirrorReprojectimport osimport requestsimport json@@ -35,7 +35,8 @@ classes = [CurvesToMesh,ComfyUIGenerate,Reproject,- Regenerate+ Regenerate,+ MirrorReproject,]# Global caches for model lists fetched via API@@ -1456,6 +1457,7 @@ def register():max=180.0,update=update_parameters)+bpy.types.Scene.discard_factor_generation_only = bpy.props.BoolProperty(name="Reset Discard Angle After Generation",description="If enabled, the 'Discard Factor' will be reset to a specified value after generation completes. Useful for sequential/Qwen modes where a low discard angle is needed during generation but not for final blending",@@ -1470,6 +1472,34 @@ def register():max=180.0,update=update_parameters)+ bpy.types.Scene.view_blend_use_color_match = bpy.props.BoolProperty(+ name="Match Colors to Viewport",+ description="Match each generated view’s colors to the current viewport texture before blending",+ default=False,+ update=update_parameters,+ )+ bpy.types.Scene.view_blend_color_match_method = bpy.props.EnumProperty(+ name="Color Match Method",+ description="Algorithm used when matching view colors to the viewport texture",+ items=[+ ("mkl", "MKL", ""),+ ("hm", "Histogram", ""),+ ("reinhard", "Reinhard", ""),+ ("mvgd", "MVGD", ""),+ ("hm-mvgd-hm", "HM–MVGD–HM", ""),+ ("hm-mkl-hm", "HM–MKL–HM", ""),+ ],+ default="reinhard",+ update=update_parameters,+ )+ bpy.types.Scene.view_blend_color_match_strength = bpy.props.FloatProperty(+ name="Match Strength",+ description="Blend between original and viewport-matched colors",+ default=1.0,+ min=0.0,+ max=2.0,+ update=update_parameters,+ )bpy.types.Scene.weight_exponent = bpy.props.FloatProperty(name="Weight Exponent",description="Controls the falloff curve for viewpoint weighting based on the angle to the surface normal (θ). "@@ -1609,6 +1639,29 @@ def register():default=False,update=update_parameters)+ bpy.types.Scene.visibility_vignette = bpy.props.BoolProperty(+ name="Feather Visibility Edges",+ description="Multiply visibility masks by a soft vignette near the frame edges to reduce seams at camera borders",+ default=True,+ update=update_parameters,+ )++ bpy.types.Scene.visibility_vignette_width = bpy.props.FloatProperty(+ name="Vignette Width",+ description="Fraction of the image radius used as a feather band (0 = no feather, 0.5 = very soft edges)",+ default=0.15,+ min=0.0,+ max=0.5,+ update=update_parameters,+ )+ bpy.types.Scene.visibility_vignette_softness = bpy.props.FloatProperty(+ name="Vignette Softness",+ description="Exponent shaping feather falloff (<1 = softer, >1 = sharper)",+ default=1.0,+ min=0.1,+ max=5.0,+ update=update_parameters,+ )bpy.types.Scene.differential_diffusion = bpy.props.BoolProperty(name="Differential Diffusion",description="Replace standard inpainting with a differential diffusion based workflow\n\n - Generally works better and reduces artifacts.\n - Using a Smooth Visibilty Map is recommended for Sequential Mode.",@@ -1934,6 +1987,22 @@ def register():default=True,update=update_parameters)+ bpy.types.Scene.stablegen_mirror_axis_x = bpy.props.BoolProperty(+ name="X",+ description="Mirror across X=0 (YZ plane)",+ default=True,+ )+ bpy.types.Scene.stablegen_mirror_axis_y = bpy.props.BoolProperty(+ name="Y",+ description="Mirror across Y=0 (XZ plane)",+ default=False,+ )+ bpy.types.Scene.stablegen_mirror_axis_z = bpy.props.BoolProperty(+ name="Z",+ description="Mirror across Z=0 (XY plane)",+ default=False,+ )+# IPADAPTER parameters@@ -2005,6 +2074,9 @@ def unregister():del bpy.types.Scene.sequential_factordel bpy.types.Scene.grow_mask_bydel bpy.types.Scene.mask_blocky+ del bpy.types.Scene.visibility_vignette+ del bpy.types.Scene.visibility_vignette_width+ del bpy.types.Scene.visibility_vignette_softnessdel bpy.types.Scene.differential_diffusiondel bpy.types.Scene.differential_noisedel bpy.types.Scene.blur_mask@@ -2053,6 +2125,9 @@ def unregister():del bpy.types.Scene.qwen_context_cleanup_hue_tolerancedel bpy.types.Scene.qwen_context_cleanup_value_adjustdel bpy.types.Scene.qwen_context_fallback_dilation+ del bpy.types.Scene.stablegen_mirror_axis_x+ del bpy.types.Scene.stablegen_mirror_axis_y+ del bpy.types.Scene.stablegen_mirror_axis_zfor cls in reversed(classes):bpy.utils.unregister_class(cls)diff --git a/stablegen/color_match.py b/stablegen/color_match.pynew file mode 100644index 0000000..69e5644--- /dev/null+++ b/stablegen/color_match.py@@ -0,0 +1,243 @@+# stablegen/color_match.py++from __future__ import annotations+import numpy as np++def _rgb_to_yuv(rgb: np.ndarray) -> np.ndarray:+ """+ Convert RGB [0,1] to YUV (BT.601-ish).+ rgb: (..., 3)+ """+ r = rgb[..., 0]+ g = rgb[..., 1]+ b = rgb[..., 2]++ y = 0.299 * r + 0.587 * g + 0.114 * b+ u = -0.14713 * r - 0.28886 * g + 0.436 * b+ v = 0.615 * r - 0.51499 * g - 0.10001 * b++ return np.stack((y, u, v), axis=-1)+++def _yuv_to_rgb(yuv: np.ndarray) -> np.ndarray:+ """+ Convert YUV back to RGB [0,1] and clamp.+ yuv: (..., 3)+ """+ y = yuv[..., 0]+ u = yuv[..., 1]+ v = yuv[..., 2]++ r = y + 1.13983 * v+ g = y - 0.39465 * u - 0.58060 * v+ b = y + 2.03211 * u++ rgb = np.stack((r, g, b), axis=-1)+ return np.clip(rgb, 0.0, 1.0)++def _boost_chroma_yuv(+ tgt_rgb: np.ndarray,+ matched_rgb: np.ndarray,+ extra: float,+) -> np.ndarray:+ """+ Exaggerate the chroma shift from tgt_rgb -> matched_rgb, while+ preserving luminance from tgt_rgb.++ extra: in [0, 1], where 0 = no extra, 1 = max extra.+ """+ extra = float(max(0.0, min(extra, 1.0)))++ yuv_tgt = _rgb_to_yuv(tgt_rgb) # Y from target+ yuv_mat = _rgb_to_yuv(matched_rgb) # UV from matched++ y = yuv_tgt[..., 0]+ uv_t = yuv_tgt[..., 1:]+ uv_m = yuv_mat[..., 1:]++ # Extrapolate UV away from target toward matched:+ # extra = 0 -> uv = uv_m (no extra beyond matched)+ # extra = 1 -> uv = uv_t + 2 * (uv_m - uv_t)+ scale = 1.0 + extra+ uv = uv_t + scale * (uv_m - uv_t)++ yuv = np.empty_like(yuv_tgt)+ yuv[..., 0] = y+ yuv[..., 1:] = uv++ return _yuv_to_rgb(yuv)++def _split_rgb_alpha(img: np.ndarray):+ """Return (rgb, alpha or None) from [H, W, 3/4] float32 [0, 1]."""+ if img.ndim != 3 or img.shape[2] not in (3, 4):+ raise ValueError(f"Expected [H, W, 3 or 4], got {img.shape}")+ if img.shape[2] == 4:+ return img[..., :3], img[..., 3:4]+ return img, None+++def _merge_rgb_alpha(rgb: np.ndarray, alpha: np.ndarray | None, like: np.ndarray) -> np.ndarray:+ """Rebuild into 3 or 4 channels to match `like`."""+ if like.shape[2] == 4:+ if alpha is None:+ alpha = like[..., 3:4]+ return np.concatenate([rgb, alpha], axis=-1)+ return rgb+++def _reinhard_preserve_luma(ref_rgb: np.ndarray, tgt_rgb: np.ndarray) -> np.ndarray:+ """+ Reinhard-style color transfer that matches only chroma (U/V),+ while preserving the target luminance (Y).++ This avoids the typical darkening/brightening side effects and+ is better suited for 'make it bluer' style corrections.+ """+ ref_yuv = _rgb_to_yuv(ref_rgb)+ tgt_yuv = _rgb_to_yuv(tgt_rgb)++ # Flatten U/V for stats+ ref_uv = ref_yuv[..., 1:].reshape(-1, 2)+ tgt_uv = tgt_yuv[..., 1:].reshape(-1, 2)++ ref_mu = ref_uv.mean(axis=0)+ ref_sigma = ref_uv.std(axis=0) + 1e-6++ tgt_mu = tgt_uv.mean(axis=0)+ tgt_sigma = tgt_uv.std(axis=0) + 1e-6++ out = np.copy(tgt_yuv)++ uv = out[..., 1:]+ uv = (uv - tgt_mu) / tgt_sigma+ uv = uv * ref_sigma + ref_mu+ out[..., 1:] = uv # keep Y as-is, only adjust U/V++ return _yuv_to_rgb(out)++++def _hist_match(ref_rgb: np.ndarray, tgt_rgb: np.ndarray) -> np.ndarray:+ """Simple per-channel histogram matching."""+ out = tgt_rgb.copy()+ ref = (np.clip(ref_rgb, 0, 1) * 255.0).astype(np.float32)+ tgt = (np.clip(tgt_rgb, 0, 1) * 255.0).astype(np.float32)++ for c in range(3):+ ref_c = ref[..., c].ravel()+ tgt_c = tgt[..., c].ravel()++ tgt_vals, tgt_idx, tgt_counts = np.unique(+ tgt_c, return_inverse=True, return_counts=True+ )+ ref_vals, ref_counts = np.unique(ref_c, return_counts=True)++ tgt_cdf = np.cumsum(tgt_counts).astype(np.float64)+ tgt_cdf /= tgt_cdf[-1]++ ref_cdf = np.cumsum(ref_counts).astype(np.float64)+ ref_cdf /= ref_cdf[-1]++ mapped = np.interp(tgt_cdf, ref_cdf, ref_vals)+ matched = mapped[tgt_idx].reshape(tgt_rgb.shape[:2])+ out[..., c] = matched / 255.0++ return np.clip(out, 0.0, 1.0)+++def _mvgd(ref_rgb: np.ndarray, tgt_rgb: np.ndarray) -> np.ndarray:+ """Covariance-based color transfer (MVGD-ish)."""+ eps = 1e-6+ ref_flat = ref_rgb.reshape(-1, 3).astype(np.float64)+ tgt_flat = tgt_rgb.reshape(-1, 3).astype(np.float64)++ mu_ref = ref_flat.mean(axis=0, keepdims=True)+ mu_tgt = tgt_flat.mean(axis=0, keepdims=True)++ ref_c = ref_flat - mu_ref+ tgt_c = tgt_flat - mu_tgt++ cov_ref = np.cov(ref_c, rowvar=False) + np.eye(3) * eps+ cov_tgt = np.cov(tgt_c, rowvar=False) + np.eye(3) * eps++ eval_t, evec_t = np.linalg.eigh(cov_tgt)+ eval_r, evec_r = np.linalg.eigh(cov_ref)++ D_t_inv_sqrt = np.diag(1.0 / np.sqrt(eval_t))+ D_r_sqrt = np.diag(np.sqrt(eval_r))++ W_t = evec_t @ D_t_inv_sqrt @ evec_t.T # whitening+ C_r = evec_r @ D_r_sqrt @ evec_r.T # coloring++ tgt_whitened = tgt_c @ W_t.T+ tgt_colored = tgt_whitened @ C_r.T++ matched_flat = tgt_colored + mu_ref+ matched = matched_flat.reshape(tgt_rgb.shape)+ return np.clip(matched, 0.0, 1.0).astype(np.float32)+++def _apply_core(ref_rgb: np.ndarray, tgt_rgb: np.ndarray, method: str) -> np.ndarray:+ m = (method or "reinhard").lower()+ if m == "reinhard":+ return _reinhard_preserve_luma(ref_rgb, tgt_rgb)+ elif m == "hm":+ return _hist_match(ref_rgb, tgt_rgb)+ elif m in ("mvgd", "mkl"): # treat MKL ~ MVGD+ return _mvgd(ref_rgb, tgt_rgb)+ elif m == "hm-mvgd-hm":+ s1 = _hist_match(ref_rgb, tgt_rgb)+ s2 = _mvgd(ref_rgb, s1)+ s3 = _hist_match(ref_rgb, s2)+ return s3+ elif m == "hm-mkl-hm":+ s1 = _hist_match(ref_rgb, tgt_rgb)+ s2 = _mvgd(ref_rgb, s1)+ s3 = _hist_match(ref_rgb, s2)+ return s3+ else:+ return _reinhard(ref_rgb, tgt_rgb)+++def color_match_single(+ ref: np.ndarray,+ target: np.ndarray,+ method: str = "reinhard",+ strength: float = 1.0,+) -> np.ndarray:+ """+ Color-match a single target to a reference.+ ref / target: [H, W, 3 or 4] in [0, 1].++ UI strength is interpreted as:+ 0.0–1.0 : blend from original -> matched+ 1.0–2.0 : full match + extra chroma push (no big luminance change)+ """+ if ref.shape[:2] != target.shape[:2]:+ raise ValueError(+ f"Size mismatch: ref {ref.shape[:2]} vs target {target.shape[:2]}"+ )++ # Split out RGB / A+ ref_rgb, _ = _split_rgb_alpha(ref)+ tgt_rgb, tgt_a = _split_rgb_alpha(target)++ # Full-strength match result (what "1.0" really means)+ base_matched_rgb = _apply_core(ref_rgb, tgt_rgb, method)++ # Clamp UI strength to [0, 2]+ ui_s = float(max(0.0, min(strength, 2.0)))++ if ui_s <= 1.0:+ # 0–1: regular blend between target and matched+ s = ui_s+ matched_rgb = tgt_rgb * (1.0 - s) + base_matched_rgb * s+ else:+ # >1: start from fully matched, then push chroma harder+ matched_rgb = base_matched_rgb+ extra = ui_s - 1.0 # in (0, 1]+ matched_rgb = _boost_chroma_yuv(tgt_rgb, matched_rgb, extra)++ matched_rgb = np.clip(matched_rgb, 0.0, 1.0)+ out = _merge_rgb_alpha(matched_rgb, tgt_a, like=target)+ return out.astype(np.float32)diff --git a/stablegen/generator.py b/stablegen/generator.pyindex 0030670..5693164 100644--- a/stablegen/generator.py+++ b/stablegen/generator.py@@ -1,8 +1,10 @@import osimport bpy # pylint: disable=import-errorimport numpy as np+from PIL import Image, ImageEnhanceimport cv2+from .color_match import color_match_singleimport uuidimport jsonimport urllib.request@@ -16,7 +18,9 @@ from datetime import datetimeimport mathimport colorsys-from PIL import Image, ImageEnhance++import mathutils+from mathutils import Vectorfrom .util.helpers import prompt_text, prompt_text_img2img, prompt_text_qwen_image_edit # pylint: disable=relative-beyond-top-levelfrom .render_tools import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap # pylint: disable=relative-beyond-top-level@@ -322,6 +326,592 @@ def upload_image_to_comfyui(server_address, image_path, image_type="input"):return None+def _build_mirrored_camera_matrix(+ cam: bpy.types.Object,+ mirror_x: bool,+ mirror_y: bool,+ mirror_z: bool,+) -> mathutils.Matrix:+ """+ Mirror a camera across the selected global axes (X=0, Y=0, Z=0 planes),+ then rebuild a proper rotation so we don't end up with negative scale+ / flipped handedness.+ """+ m = cam.matrix_world.copy()+ loc = m.to_translation()+ basis = m.to_3x3()++ # Camera conventions: looks along local -Z, local +Y is "up"+ forward = -(basis @ Vector((0.0, 0.0, 1.0))) # world-space view dir+ up = (basis @ Vector((0.0, 1.0, 0.0))) # world-space up++ # Reflection factors per axis+ sx = -1.0 if mirror_x else 1.0+ sy = -1.0 if mirror_y else 1.0+ sz = -1.0 if mirror_z else 1.0++ # Apply reflection to position and direction vectors+ loc_m = Vector((sx * loc.x, sy * loc.y, sz * loc.z))+ f_m = Vector((sx * forward.x, sy * forward.y, sz * forward.z))+ u_m = Vector((sx * up.x, sy * up.y, sz * up.z))++ f = f_m.normalized()+ u0 = u_m.normalized()++ # Build an orthonormal basis: right, up, -forward+ r = f.cross(u0)+ if r.length < 1e-6:+ # Degenerate case: fall back to world Z as "up"+ r = f.cross(Vector((0.0, 0.0, 1.0)))+ r.normalize()+ u = r.cross(f).normalized()++ # Columns: X = right, Y = up, Z = -forward (camera looks along -Z)+ ori3 = mathutils.Matrix((r, u, -f)).transposed()+ ori4 = ori3.to_4x4()+ ori4.translation = loc_m+ return ori4+++def mirror_camera_matrix_x(cam: bpy.types.Object) -> mathutils.Matrix:+ """+ Convenience wrapper: mirror a camera across the global X=0 plane.+ Uses the shared helper to avoid code duplication.+ """+ return _build_mirrored_camera_matrix(cam, mirror_x=True, mirror_y=False, mirror_z=False)+++class MirrorReproject(bpy.types.Operator):+ """Duplicate & mirror the last projection camera and image.++ - In standard / non-refine workflows: mirrors the image and camera, then calls Reproject.+ - In refine+preserve workflows: mirrors as a *new refine layer* using project_image directly.+ """+ bl_idname = "object.stablegen_mirror_reproject"+ bl_label = "Mirror Last Projection"+ bl_options = {'REGISTER', 'UNDO'}++ _original_method = None+ _original_overwrite_material = None+ _timer = None++ @classmethod+ def poll(cls, context):+ # Same checks as Reproject+ scene = context.scene+ if scene.output_timestamp == "":+ return False++ if scene.generation_status == 'waiting':+ return False++ blocked_ids = {+ 'OBJECT_OT_add_cameras',+ 'OBJECT_OT_bake_textures',+ 'OBJECT_OT_collect_camera_prompts',+ 'OBJECT_OT_test_stable',+ 'OBJECT_OT_stablegen_reproject',+ 'OBJECT_OT_stablegen_regenerate',+ 'OBJECT_OT_stablegen_mirror_reproject',+ }++ wm = context.window_manager+ for window in wm.windows:+ for op in window.modal_operators:+ if op.bl_idname in blocked_ids:+ return False++ return True++ def _mirror_image_file(+ self,+ src_path: str,+ dst_path: str,+ flip_x: bool = True,+ flip_y: bool = False,+ ):+ """+ Load an image from src_path, mirror it according to flip_x / flip_y, save to dst_path.++ flip_x: mirror horizontally (left/right)+ flip_y: mirror vertically (top/bottom)+ """+ os.makedirs(os.path.dirname(dst_path), exist_ok=True)++ img = bpy.data.images.load(src_path)+ try:+ w, h = img.size+ pixels = list(img.pixels[:]) # flat RGBA array+ mirrored = [0.0] * len(pixels)+ row_stride = w * 4 # RGBA per pixel++ # y in *destination* space+ for y in range(h):+ src_y = h - 1 - y if flip_y else y+ src_row_start = src_y * row_stride+ dst_row_start = y * row_stride++ # x in *destination* space+ for x in range(w):+ src_x = w - 1 - x if flip_x else x+ src_idx = src_row_start + src_x * 4+ dst_idx = dst_row_start + x * 4+ mirrored[dst_idx:dst_idx + 4] = pixels[src_idx:src_idx + 4]++ img.pixels[:] = mirrored+ img.filepath_raw = dst_path+ img.file_format = 'PNG'+ img.save()+ finally:+ bpy.data.images.remove(img)++ def _mirror_camera_matrix(+ self,+ cam: bpy.types.Object,+ mirror_x: bool,+ mirror_y: bool,+ mirror_z: bool,+ ) -> mathutils.Matrix:+ """+ Thin wrapper around _build_mirrored_camera_matrix so it can be used+ from methods (and swapped if needed later).+ """+ return _build_mirrored_camera_matrix(cam, mirror_x, mirror_y, mirror_z)++ def _get_to_texture(self, context):+ if context.scene.texture_objects == 'all':+ return [+ obj for obj in bpy.context.view_layer.objects+ if obj.type == 'MESH' and not obj.hide_get()+ ]+ else:+ return [+ obj for obj in bpy.context.selected_objects+ if obj.type == 'MESH'+ ]++ def _get_sorted_cameras(self, context):+ cams = [obj for obj in context.scene.objects if obj.type == 'CAMERA']+ cams.sort(key=lambda c: c.name)+ return cams++ def _compute_latest_material_id(self, to_texture):+ max_id = -1+ for obj in to_texture:+ mat_id = get_last_material_index(obj)+ if mat_id > max_id:+ max_id = mat_id+ return max_id++ def _do_refine_mirror(self, context, to_texture):+ """+ Special path for generation_method == 'refine' and refine_preserve == True.++ For each selected axis (X / Y / Z), we:+ - Duplicate & mirror the active camera around that axis.+ - Create a mirrored image for that camera in a NEW refine layer (material_id = base_id + 1).+ Then we call project_image once for that new layer.+ """+ import shutil # (optionally move this to the top of the file)++ scene = context.scene++ # 1) Base material id (from existing stack)+ base_id = self._compute_latest_material_id(to_texture)+ if base_id < 0:+ self.report({'ERROR'}, "No StableGen materials found to mirror.")+ return {'CANCELLED'}++ # New refine layer id+ new_material_id = base_id + 1++ # 2) Original cameras & active camera index (before adding mirrored cameras)+ cameras_orig = self._get_sorted_cameras(context)+ if not cameras_orig:+ self.report({'ERROR'}, "No cameras found in the scene.")+ return {'CANCELLED'}++ orig_cam = scene.camera if scene.camera in cameras_orig else cameras_orig[0]+ src_cam_idx = cameras_orig.index(orig_cam)++ # --- Mirror axes from Scene (UI toggles), same pattern as standard mirror ---+ axis_configs = [+ (+ "X",+ getattr(scene, "stablegen_mirror_axis_x", True),+ dict(mirror_x=True, mirror_y=False, mirror_z=False),+ (True, False), # flip_x, flip_y+ ),+ (+ "Y",+ getattr(scene, "stablegen_mirror_axis_y", False),+ dict(mirror_x=False, mirror_y=True, mirror_z=False),+ (False, True),+ ),+ (+ "Z",+ getattr(scene, "stablegen_mirror_axis_z", False),+ dict(mirror_x=False, mirror_y=False, mirror_z=True),+ (True, True),+ ),+ ]++ axes_to_mirror = [cfg for cfg in axis_configs if cfg[1]]+ if not axes_to_mirror:+ # Safety: default to X only if everything is off+ axes_to_mirror = [axis_configs[0]]++ # 3) Copy base layer images -> new refine layer for ALL original cameras+ for cam_idx, _cam_obj in enumerate(cameras_orig):+ src_path = get_file_path(+ context,+ "generated",+ camera_id=cam_idx,+ material_id=base_id,+ )+ dst_path = get_file_path(+ context,+ "generated",+ camera_id=cam_idx,+ material_id=new_material_id,+ )++ if not os.path.exists(src_path):+ print(+ f"[MirrorReproject] No base image for cam {cam_idx} at {src_path}, "+ f"skipping copy."+ )+ continue++ os.makedirs(os.path.dirname(dst_path), exist_ok=True)+ shutil.copyfile(src_path, dst_path)+ print(+ f"[MirrorReproject] Copied base image for cam {cam_idx}\n"+ f" {src_path}\n-> {dst_path}"+ )++ # We'll always mirror from the original camera's base image+ src_path_for_mirror = get_file_path(+ context,+ "generated",+ camera_id=src_cam_idx,+ material_id=base_id,+ )+ if not os.path.exists(src_path_for_mirror):+ self.report(+ {'ERROR'},+ (+ f"No generated image found for active camera index {src_cam_idx} at:\n"+ f"{src_path_for_mirror}"+ ),+ )+ return {'CANCELLED'}++ created_cams = []++ # 4) For each selected axis, create a mirrored camera + mirrored image+ for axis_name, _flag, matrix_kwargs, (flip_x, flip_y) in axes_to_mirror:+ # Duplicate & mirror from the original camera+ mir_cam = orig_cam.copy()+ mir_cam.data = orig_cam.data.copy()+ scene.collection.objects.link(mir_cam)++ mir_cam.matrix_world = self._mirror_camera_matrix(orig_cam, **matrix_kwargs)+ mir_cam.name = f"{orig_cam.name}_MIRROR_{axis_name}"+ created_cams.append(mir_cam)++ # After linking, get its index in the updated camera list+ cameras_all = self._get_sorted_cameras(context)+ dst_cam_idx = cameras_all.index(mir_cam)++ dst_path = get_file_path(+ context,+ "generated",+ camera_id=dst_cam_idx,+ material_id=new_material_id,+ )+ print(+ f"[MirrorReproject] Refine mirror ({axis_name})\n"+ f" {src_path_for_mirror}\n-> {dst_path}"+ )++ self._mirror_image_file(+ src_path_for_mirror,+ dst_path,+ flip_x=flip_x,+ flip_y=flip_y,+ )++ # 5) Call project_image once as a new refine layer+ project_image(context, to_texture, new_material_id)++ # 6) Delete the temporary mirrored cameras+ for cam in created_cams:+ try:+ bpy.data.objects.remove(cam, do_unlink=True)+ except Exception:+ pass++ axis_labels = ", ".join(cfg[0] for cfg in axes_to_mirror)+ self.report(+ {'INFO'},+ (+ f"Refine mirror applied as new layer (material id {new_material_id}) "+ f"with {len(created_cams)} mirrored camera(s) ({axis_labels}). "+ f"Temporary cameras removed."+ ),+ )+ return {'FINISHED'}++ def _schedule_delete_camera_later(self, cam_name: str):+ """Delete the temporary camera after StableGen reprojection finishes."""+ import bpy++ def _delete():+ # Wait until the generate/reproject operator is done+ if ComfyUIGenerate._is_running:+ return 0.5 # check again in 0.5 seconds++ cam = bpy.data.objects.get(cam_name)+ if cam is not None:+ try:+ bpy.data.objects.remove(cam, do_unlink=True)+ print(f"[MirrorReproject] Deleted temporary camera '{cam_name}'")+ except Exception as exc:+ print(f"[MirrorReproject] Failed to delete camera '{cam_name}': {exc}")+ return None # stop the timer++ bpy.app.timers.register(_delete, first_interval=1.0)++ def _do_standard_mirror(self, context, to_texture):+ """+ Standard / non-refine workflow:+ - For each selected axis (X / Y / Z), duplicate & mirror the active camera+ around that single axis.+ - For each mirrored camera, mirror the image on disk for the same material id.+ - Then let the existing Reproject operator do its thing once.+ """+ scene = context.scene++ # 1) Find the latest StableGen material id+ base_id = self._compute_latest_material_id(to_texture)+ if base_id < 0:+ self.report({'ERROR'}, "No StableGen materials found to mirror.")+ return {'CANCELLED'}++ # 2) Get cameras in the same order StableGen uses+ cameras = self._get_sorted_cameras(context)+ if not cameras:+ self.report({'ERROR'}, "No cameras found in the scene.")+ return {'CANCELLED'}++ # Use active scene camera if possible, otherwise first camera+ orig_cam = scene.camera if scene.camera in cameras else cameras[0]+ src_cam_idx = cameras.index(orig_cam)++ # --- Mirror axes from Scene (UI toggles) ---+ axis_configs = [+ (+ "X",+ getattr(scene, "stablegen_mirror_axis_x", True),+ dict(mirror_x=True, mirror_y=False, mirror_z=False),+ (True, False), # flip_x, flip_y+ ),+ (+ "Y",+ getattr(scene, "stablegen_mirror_axis_y", False),+ dict(mirror_x=False, mirror_y=True, mirror_z=False),+ (False, True),+ ),+ (+ "Z",+ getattr(scene, "stablegen_mirror_axis_z", False),+ dict(mirror_x=False, mirror_y=False, mirror_z=True),+ (True, True),+ ),+ ]++ axes_to_mirror = [cfg for cfg in axis_configs if cfg[1]]++ # Safety: if user turned everything off, default back to X-only+ if not axes_to_mirror:+ axes_to_mirror = [axis_configs[0]] # X++ # Source image for the active camera+ src_path = get_file_path(+ context,+ "generated",+ camera_id=src_cam_idx,+ material_id=base_id,+ )+ if not os.path.exists(src_path):+ self.report(+ {'ERROR'},+ (+ f"No generated image found for active camera index {src_cam_idx} at:\n"+ f"{src_path}"+ ),+ )+ return {'CANCELLED'}++ created_cam_names = []++ # 3) For each selected axis, create a mirrored camera + mirrored image+ for axis_name, _flag, matrix_kwargs, (flip_x, flip_y) in axes_to_mirror:+ # Duplicate & mirror from the original camera each time+ mir_cam = orig_cam.copy()+ mir_cam.data = orig_cam.data.copy()+ scene.collection.objects.link(mir_cam)++ mir_cam.matrix_world = self._mirror_camera_matrix(orig_cam, **matrix_kwargs)+ mir_cam.name = f"{orig_cam.name}_MIRROR_{axis_name}"+ created_cam_names.append(mir_cam.name)++ # Rebuild sorted list so we know this mirrored camera's index+ cameras = self._get_sorted_cameras(context)+ dst_cam_idx = cameras.index(mir_cam)++ dst_path = get_file_path(+ context,+ "generated",+ camera_id=dst_cam_idx,+ material_id=base_id,+ )+ print(+ f"[MirrorReproject] Standard mirror ({axis_name})\n"+ f" {src_path}\n-> {dst_path}"+ )++ # Flip image for this axis+ self._mirror_image_file(src_path, dst_path, flip_x=flip_x, flip_y=flip_y)++ # 4) Hand off to the existing Reproject operator once+ try:+ bpy.ops.object.stablegen_reproject('INVOKE_DEFAULT')+ except Exception as exc:+ self.report(+ {'ERROR'},+ f"Failed to start StableGen reprojection after mirroring: {exc}",+ )+ return {'CANCELLED'}++ # 5) Schedule deletion of all temporary mirrored cameras+ for cam_name in created_cam_names:+ self._schedule_delete_camera_later(cam_name)++ axis_labels = ", ".join(cfg[0] for cfg in axes_to_mirror)+ self.report(+ {'INFO'},+ (+ f"Standard mirror: created {len(created_cam_names)} mirrored camera(s) "+ f"({axis_labels}), mirrored images, and started reprojection "+ f"(temporary cameras will be removed afterwards)."+ ),+ )+ return {'FINISHED'}++ def execute(self, context):+ scene = context.scene+ to_texture = self._get_to_texture(context)++ if not to_texture:+ self.report({'ERROR'}, "No mesh objects found for texturing.")+ return {'CANCELLED'}++ # Branch: refine+preserve vs everything else+ if scene.generation_method == 'refine' and getattr(scene, "refine_preserve", False):+ return self._do_refine_mirror(context, to_texture)+ else:+ return self._do_standard_mirror(context, to_texture)++def _get_viewport_ref_np(obj):+ """+ Try to grab the current viewport/base color texture for this object as [H, W, 3] float32 [0,1].+ Returns None if no suitable image is found.+ """+ mat = getattr(obj, "active_material", None)+ if not mat or not mat.use_nodes:+ return None++ nt = mat.node_tree+ if not nt:+ return None++ img = None+ # Try the first image texture in the node tree that is plugged into Base Color+ for node in nt.nodes:+ if node.type == 'TEX_IMAGE' and node.image is not None:+ img = node.image+ break++ if img is None:+ return None++ # Ensure the image has pixels loaded+ if not img.has_data:+ img.pixels[0] # force load++ w, h = img.size+ # Blender stores pixels as linear RGBA floats in [0,1]+ buf = np.array(img.pixels[:], dtype=np.float32).reshape(h, w, 4)+ rgb_lin = buf[..., :3]++ # Convert from linear to sRGB so it matches the PNGs we read via Pillow+ x = np.clip(rgb_lin, 0.0, 1.0)+ a = 0.055+ rgb_srgb = np.where(+ x <= 0.0031308,+ 12.92 * x,+ (1.0 + a) * np.power(x, 1.0 / 2.4) - a,+ )++ return rgb_srgb++def _apply_color_match_to_file(image_path, ref_rgb, scene):+ """+ Load image from disk, color-match to ref_rgb if enabled, and overwrite on disk.+ """+ if not scene.view_blend_use_color_match:+ return image_path # no-op++ try:+ with Image.open(image_path) as pil_img:+ pil_img = pil_img.convert("RGBA")+ w, h = pil_img.size+ tgt_np = np.array(pil_img, dtype=np.float32) / 255.0 # [H, W, 4]++ # Resize ref_rgb to match target resolution if needed+ if ref_rgb.shape[:2] != (h, w):+ ref_uint8 = np.clip(ref_rgb * 255.0, 0, 255).astype("uint8")+ ref_img = Image.fromarray(ref_uint8, mode="RGB")+ ref_img = ref_img.resize((w, h), Image.BILINEAR)+ ref_resized = np.array(ref_img, dtype=np.float32) / 255.0+ else:+ ref_resized = ref_rgb++ # Build a fake alpha channel of 1s so ref has 4 channels+ ref_rgba = np.concatenate(+ [ref_resized, np.ones((*ref_resized.shape[:2], 1), dtype=np.float32)],+ axis=-1,+ )++ matched_np = color_match_single(+ ref=ref_rgba,+ target=tgt_np,+ method=scene.view_blend_color_match_method,+ strength=scene.view_blend_color_match_strength,+ )++ matched_np = np.clip(matched_np * 255.0, 0, 255).astype("uint8")+ matched_img = Image.fromarray(matched_np, mode="RGBA")+ matched_img.save(image_path)+ print(f"[StableGen] Color matched: {image_path}")+ return image_path++ except Exception as e:+ print(f"[StableGen] Color match failed for {image_path}: {e}")+ return image_path+class ComfyUIGenerate(bpy.types.Operator):"""Generate textures using ComfyUI (to all mesh objects using all cameras in the scene)@@ -677,6 +1267,24 @@ class ComfyUIGenerate(bpy.types.Operator):# Export visibility masks for each objectexport_visibility(context, None, obj)++ if context.scene.view_blend_use_color_match and self._to_texture:+ # Use the first target object as the reference for viewport color+ ref_np = _get_viewport_ref_np(self._to_texture[0])+ if ref_np is not None:+ # Apply color match to ALL generated camera images for this material+ for cam_idx, cam in enumerate(self._cameras):+ image_path = get_file_path(+ context,+ "generated",+ camera_id=cam_idx,+ material_id=self._material_id,+ )+ _apply_color_match_to_file(+ image_path=image_path,+ ref_rgb=ref_np,+ scene=context.scene,+ )self.prompt_text = context.scene.comfyui_prompt@@ -990,11 +1598,18 @@ class ComfyUIGenerate(bpy.types.Operator):if context.scene.generation_method == 'sequential':def image_project_callback():redraw_ui(context)- project_image(context, self._to_texture, self._material_id, stop_index=self._current_image)- # Set the event to signal the end of the process+ project_image(+ context,+ self._to_texture,+ self._material_id,+ stop_index=self._current_image,+ )self._wait_event.set()return Nonebpy.app.timers.register(image_project_callback)+ self._wait_event.wait()+ self._wait_event.clear()+ bpy.app.timers.register(image_project_callback)# Wait for the event to be setself._wait_event.wait()self._wait_event.clear()@@ -1060,10 +1675,10 @@ class ComfyUIGenerate(bpy.types.Operator):if context.scene.bake_texture:self._stage = "Baking Textures & Projecting"redraw_ui(context)+if context.scene.generation_method != 'uv_inpaint':project_image(context, self._to_texture, self._material_id)else:- # Apply the UV inpainted textures to each meshfrom .render_tools import apply_uv_inpaint_texturefor obj in self._to_texture:texture_path = get_file_path(@@ -1071,6 +1686,24 @@ class ComfyUIGenerate(bpy.types.Operator):)apply_uv_inpaint_texture(context, obj, texture_path)return None++ if context.scene.view_blend_use_color_match and self._to_texture:+ # Use the first object in the target list as the color reference+ ref_np = _get_viewport_ref_np(self._to_texture[0])+ if ref_np is not None:+ # Loop all cameras we generated for+ for cam_idx, cam in enumerate(self._cameras):+ image_path = get_file_path(+ context,+ "generated",+ camera_id=cam_idx,+ material_id=self._material_id,+ )+ _apply_color_match_to_file(+ image_path=image_path,+ ref_rgb=ref_np,+ scene=context.scene,+ )bpy.app.timers.register(image_project_callback)diff --git a/stablegen/project.py b/stablegen/project.pyindex f9ecf66..acd377c 100644--- a/stablegen/project.py+++ b/stablegen/project.py@@ -6,335 +6,416 @@ from .utils import get_last_material_index, get_file_path, get_dir_pathfrom .render_tools import prepare_baking, bake_texture, unwrapfrom mathutils import Vector+import bpy+import os+from math import atan, tan++from .utils import get_last_material_index, get_file_path, get_dir_path+from .render_tools import prepare_baking, bake_texture, unwrap+from mathutils import Vector++def project_image(context, to_project, mat_id, stop_index=1000000):- """- Projects an image onto all mesh objects using UV Project Modifier."""- def build_mix_tree(shaders, weight_nodes, nodes_collection, links, last_node=None, level=0, stop_index=1000000):+ Projects an image onto all mesh objects using UV Project Modifier.+ """++ scene = context.scene+ render = scene.render++ # Common flags / shortcuts+ gen_method = scene.generation_method+ gen_mode = scene.generation_mode+ is_sequential = gen_method == "sequential"+ is_refine = gen_method == "refine"+ refine_preserve = scene.refine_preserve+ bake_texture_flag = scene.bake_texture+ overwrite_material = scene.overwrite_material+ regenerate_selected = gen_mode == "regenerate_selected"++ # -------------------------------------------------------------------------+ # Nested helper: build mix tree for image shaders+ # -------------------------------------------------------------------------+ def 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.+The mix factor between two shader nodes is computed dynamically using- the outputs of weight_nodes assumed to come from OSL/maths nodes.-- For each pair, the total weight is created using an ADD node.- Then a DIVIDE node computes:- mix_factor = weight_A / (weight_A + weight_B)- which is connected to the Mix Shader node's Fac input.-- Params:- shaders: list of shader nodes (e.g., Principled BSDF nodes).- weight_nodes: list of nodes whose outputs provide the dynamic weight values.- (e.g. the less_than nodes outputs)- nodes_collection: the node tree's nodes collection.- links: the node tree's links collection.+ the outputs of weight_nodes (e.g. SCRIPT/LESS_THAN nodes).+Returns:- A tuple (final_shader, final_weight_node).+ (final_shader_node, final_weight_node)"""+# Compute offsets based on recursion level- if context.scene.refine_preserve:- x_offset = 1000 + level * 800 + last_node.location[0] + 200 if context.scene.early_priority else 1000 + level * 600 + last_node.location[0] + 200+ # (exact math preserved, just made more readable)+ step = 800 if scene.early_priority else 600+ if refine_preserve:+ base = (last_node.location[0] + 1200) if last_node else 1200else:- x_offset = 1000 + level * 800 if context.scene.early_priority else 1000 + level * 600+ base = 1000+ x_offset = base + level * stepy_offset = 0++ # ---------------------------------------------------------------------+ # Base case: only one shader left -> mix against fallback color+ # ---------------------------------------------------------------------if len(shaders) == 1:- # Base-case: Mix single color with fallback magentafinal_mix = nodes_collection.new("ShaderNodeMixRGB")final_mix.location = (x_offset - 200, y_offset)- # Convert fallback_color from 3 to 4 components by appending alpha 1.0- final_mix.inputs["Color2"].default_value = (*context.scene.fallback_color, 1.0)++ # Convert fallback_color from (r,g,b) -> (r,g,b,a)+ final_mix.inputs["Color2"].default_value = (*scene.fallback_color, 1.0)+# Connect the single color output to Color1links.new(shaders[0].outputs[0], final_mix.inputs["Color1"])+if last_node:- # Connect the final mix node to the last node+ # Connect the previous node into Color2 if preservinglinks.new(last_node.outputs[0], final_mix.inputs["Color2"])- # Create a compare node to drive the mix factor-- if context.scene.generation_method == 'refine' and context.scene.refine_preserve:++ # Compare/threshold node for driving the factor+ if is_refine and refine_preserve:compare_node = nodes_collection.new("ShaderNodeValToRGB")compare_node.location = (x_offset - 500, y_offset)- compare_node.color_ramp.elements[0].position = 0.0- compare_node.color_ramp.elements[0].color = (1, 1, 1, 1)- compare_node.color_ramp.elements[1].position = 0.6- compare_node.color_ramp.elements[1].color = (0, 0, 0, 1)- compare_node.color_ramp.interpolation = 'LINEAR'+ cr = compare_node.color_ramp+ cr.elements[0].position = 0.0+ cr.elements[0].color = (1, 1, 1, 1)+ cr.elements[1].position = 0.6+ cr.elements[1].color = (0, 0, 0, 1)+ cr.interpolation = "LINEAR"else:compare_node = nodes_collection.new("ShaderNodeMath")- compare_node.operation = 'COMPARE'- # Value to compare against (Value 2)- compare_node.inputs[1].default_value = 0.0- # Epsilon for comparison- compare_node.inputs[2].default_value = 0.0+ compare_node.operation = "COMPARE"+ compare_node.inputs[1].default_value = 0.0 # value2+ compare_node.inputs[2].default_value = 0.0 # epsiloncompare_node.location = (x_offset - 500, y_offset)- # Connect final add node to compare node++ # Connect final weight node to compare nodelinks.new(weight_nodes[0].outputs[0], compare_node.inputs[0])links.new(compare_node.outputs[0], final_mix.inputs["Fac"])-- if not context.scene.apply_bsdf:++ if not scene.apply_bsdf:return final_mix, compare_node-- # Add a principle shader for the mixed color++ # Decide whether to reuse existing Principled or make a new oneshould_add_principled = True- if context.scene.generation_method == 'refine' and context.scene.refine_preserve:- # Final principled is at last_node's output if it is BSDF+ if is_refine and refine_preserve and last_node is not None:+ # Final Principled is at last_node's output if BSDFfinal_principled = last_node.outputs[0].links[0].to_node- if final_principled.type == 'BSDF_PRINCIPLED':+ if final_principled.type == "BSDF_PRINCIPLED":should_add_principled = False-+if should_add_principled:final_principled = nodes_collection.new("ShaderNodeBsdfPrincipled")final_principled.location = (x_offset, y_offset)final_principled.inputs["Roughness"].default_value = 1.0-+links.new(final_mix.outputs[0], final_principled.inputs[0])return final_principled, compare_node+ # ---------------------------------------------------------------------+ # Recursive case: pair up shaders and merge them in a tree+ # ---------------------------------------------------------------------new_shaders = []new_weight_nodes = []i = 0+while i < len(shaders):if i + 1 < len(shaders):- # Sum the weightsvert_offset = -200 * (i // 2)++ # Sum the weightssum_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.operation = "ADD"+ sum_node.location = (x_offset - (800 if scene.early_priority else 600), y_offset + vert_offset)links.new(weight_nodes[i].outputs[0], sum_node.inputs[0])- links.new(weight_nodes[i+1].outputs[0], sum_node.inputs[1])+ links.new(weight_nodes[i + 1].outputs[0], sum_node.inputs[1])- # Compute mix factor: weight_A / (weight_A+weight_B)+ # Compute mix factor: weight_B / (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)- links.new(weight_nodes[i+1].outputs[0], div_node.inputs[0])+ div_node.operation = "DIVIDE"+ div_node.location = (+ x_offset - (600 if scene.early_priority else 400),+ y_offset + vert_offset,+ )+ links.new(weight_nodes[i + 1].outputs[0], div_node.inputs[0])links.new(sum_node.outputs[0], div_node.inputs[1])- if context.scene.early_priority:- # Add map range node+ if scene.early_priority: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+ map_range_node.inputs[1].default_value = scene.early_priority_strengthlinks.new(div_node.outputs[0], map_range_node.inputs[0])+ factor_node = map_range_node+ else:+ factor_node = div_node- # Create a MixRGB node for color blending of the two inputs+ # Mix node for RGBA colorsmix_node = nodes_collection.new("ShaderNodeMixRGB")mix_node.location = (x_offset - 200, y_offset + vert_offset)mix_node.use_clamp = True- # Connect first color to Color1 and second color to Color2+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(shaders[i + 1].outputs[0], mix_node.inputs["Color2"])+ links.new(factor_node.outputs[0], mix_node.inputs["Fac"])new_shaders.append(mix_node)- # The new effective weight is the sum (stored in sum_node)new_weight_nodes.append(sum_node)i += 2else:new_shaders.append(shaders[i])new_weight_nodes.append(weight_nodes[i])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']+ return build_mix_tree(+ new_shaders,+ new_weight_nodes,+ nodes_collection,+ links,+ last_node=last_node,+ level=level + 1,+ stop_index=stop_index,+ )++ # -------------------------------------------------------------------------+ # Camera list and UI refresh+ # -------------------------------------------------------------------------+ cameras = [obj for obj in scene.objects if obj.type == "CAMERA"]cameras.sort(key=lambda x: x.name)-+# Force refresh of the UIfor area in context.screen.areas:area.tag_redraw()-- # Apply projection to all mesh objects for each camera++ # -------------------------------------------------------------------------+ # UV Projection + baking (per-camera, per-object)+ # -------------------------------------------------------------------------for i, camera in enumerate(cameras):- for x, obj in enumerate(to_project):- # We can skip the UV Projection step in sequential mode for i > 0- if context.scene.generation_method != 'sequential' or stop_index == 0 or context.scene.bake_texture:+ for obj in to_project:+ # We can skip UV Project in some sequential cases+ if (not is_sequential) or stop_index == 0 or bake_texture_flag:# Deselect all objects- bpy.ops.object.select_all(action='DESELECT')+ bpy.ops.object.select_all(action="DESELECT")+# Select object as active (needed for applying the modifier)context.view_layer.objects.active = objobj.select_set(True)-+# Make object data single-user before applying modifierbpy.ops.object.make_single_user(object=True, obdata=True)- # Check if the data is now single userif obj.data.users > 1:- # If not, we need to make it single user againprint("Warning: Cannot make object data single user. Making a copy.")obj.data = obj.data.copy()obj.data.name = f"{obj.name}_data"obj.data.update()- # Check againif obj.data.users > 1:print("Error: Cannot make object data single user. Exiting.")return Exception("Cannot make object data single user. Exiting.")- # Add new UV map if not present (with same name)- # Check if "ProjectionUV" UV map already exists+ # Determine UV map to useuv_map = None-- if context.scene.overwrite_material and not context.scene.bake_texture:+ if overwrite_material and not bake_texture_flag:for uv in obj.data.uv_layers:if uv.name == f"ProjectionUV_{i}_{mat_id}":uv_map = uvbreak-- # If the objects has no UV map and we are baking textures, create a new one- if not obj.data.uv_layers and context.scene.bake_texture:++ # If object has no UV map and we are baking textures, create a new one+ if not obj.data.uv_layers and bake_texture_flag:obj.data.uv_layers.new(name="BakeUV")- if not uv_map:+ if uv_map is None:uv_map = obj.data.uv_layers.new(name=f"ProjectionUV_{i}_{mat_id}")- # Add the UV Project Modifier if not present- uv_project_mod = obj.modifiers.new(name="UVProject", type='UV_PROJECT')+ # Add UV Project modifier+ uv_project_mod = obj.modifiers.new(name="UVProject", type="UV_PROJECT")- # Assign the active camera to the UV Project modifierif not camera:return Falseuv_project_mod.projectors[0].object = camera- # Set the UV map for the modifier+ # Set UV layertry:uv_project_mod.uv_layer = uv_map.name- except:- # Throw custom exception: Not enough UV map slots- raise Exception("Not enough UV map slots. Please remove some UV maps.")+ except Exception:+ raise Exception(+ "Not enough UV map slots. Please remove some UV maps."+ )- # Calculate and set the aspect ratio- render = context.scene.render+ # Aspect ratio for projectionaspect_ratio = render.resolution_x / render.resolution_yuv_project_mod.aspect_x = aspect_ratio if aspect_ratio > 1 else 1uv_project_mod.aspect_y = 1 / aspect_ratio if aspect_ratio < 1 else 1- # Apply the modifierbpy.ops.object.modifier_apply(modifier=uv_project_mod.name)+ original_uv_map = obj.data.uv_layers[0] # saved but used later- original_uv_map = obj.data.uv_layers[0]-- # If we are running in sequential mode, we already have baked textures for i < stop_index- if context.scene.bake_texture:- if (stop_index > 0 and context.scene.generation_method == 'sequential'):- # Deselect all objects- bpy.ops.object.select_all(action='DESELECT')- # Select object as active (needed for applying the modifier)+ # Baking path+ if bake_texture_flag:+ if stop_index > 0 and is_sequential:+ bpy.ops.object.select_all(action="DESELECT")context.view_layer.objects.active = objobj.select_set(True)- if i <= stop_index and (not context.scene.generation_method == 'sequential' or i == stop_index):++ if i <= stop_index and (not is_sequential or i == stop_index):simple_project_bake(context, i, obj, mat_id)- obj.data.uv_layers.remove(obj.data.uv_layers[-1]) # Remove the last UV map- for obj in to_project:+ # Remove last UV map (the one we just added for this projection)+ obj.data.uv_layers.remove(obj.data.uv_layers[-1])++ # -------------------------------------------------------------------------+ # Shader + OSL network setup per object+ # -------------------------------------------------------------------------+ # Switch render engine to Cycles + OSL (same as before, just not per-camera)+ scene.render.engine = "CYCLES"+ scene.cycles.device = "CPU"+ scene.cycles.shading_system = True- # Deselect all objects- bpy.ops.object.select_all(action='DESELECT')+ for obj in to_project:+ bpy.ops.object.select_all(action="DESELECT")context.view_layer.objects.active = objobj.select_set(True)- # Create the material- to_switch = False- if context.scene.generation_method == "refine" and context.scene.refine_preserve and not context.scene.overwrite_material:- # Copy active material+ # Choose or create material+ if (+ is_refine+ and refine_preserve+ and not overwrite_material+ ):mat = obj.active_material.copy()obj.data.materials.append(mat)to_switch = True- elif obj.active_material and (context.scene.overwrite_material or (context.scene.generation_method == "refine" and context.scene.refine_preserve) \- or (context.scene.generation_method == 'sequential' and stop_index > 0) or context.scene.generation_mode == 'regenerate_selected'):- # Use active material+ elif obj.active_material and (+ overwrite_material+ or (is_refine and refine_preserve)+ or (is_sequential and stop_index > 0)+ or regenerate_selected+ ):mat = obj.active_material+ to_switch = Falseelse:mat = bpy.data.materials.new(name="ProjectionMaterial")obj.data.materials.append(mat)- # Mark as active materialobj.active_material_index = obj.material_slots.find(mat.name)to_switch = True-+if to_switch:original_materials = obj.data.materials[:]- # Clear existing materialsobj.data.materials.clear()- # Add the new materialobj.data.materials.append(mat)- # Add the rest of the original materialsfor original_mat in original_materials:if original_mat != mat:obj.data.materials.append(original_mat)- # Enable use of nodesmat.use_nodes = Truenodes = mat.node_tree.nodeslinks = mat.node_tree.links-+previous_node = Noneoutput = None-original_uv_map = obj.data.uv_layers[0]-- if (context.scene.generation_method == 'sequential' and stop_index > 0) or context.scene.generation_mode == 'regenerate_selected':- # We just need to remove the compare nodes which are connected to script node at stop_index+ # ---------------------------------------------------------------------+ # Sequential regenerate path: remove compare nodes for a specific view+ # ---------------------------------------------------------------------+ if (is_sequential and stop_index > 0) or regenerate_selected:script_node = None- # First find all script nodes with label {stop_index}-{mat_id}++ # Find script node for this stop index/material idfor node in nodes:- if node.type == 'SCRIPT' and node.label == f"{stop_index}-{mat_id}":+ if node.type == "SCRIPT" and node.label == f"{stop_index}-{mat_id}":script_node = nodebreak+compare_output_sockets = set()if script_node:- # Find all compare nodes connected to the script node- for link in script_node.outputs[0].links:- if link.to_node.type == 'MATH' and link.to_node.operation == 'LESS_THAN':- # Save all outputs (nodes connected to) of compare nodes- for link2 in link.to_node.outputs[0].links:+ # Remove compare nodes feeding from this script+ for link in list(script_node.outputs[0].links):+ if (+ link.to_node.type == "MATH"+ and link.to_node.operation == "LESS_THAN"+ ):+ for link2 in list(link.to_node.outputs[0].links):compare_output_sockets.add(link2.to_socket)- # Remove the compare nodenodes.remove(link.to_node)- # Connect the script node to all outputs- for output in compare_output_sockets:- links.new(script_node.outputs[0], output)- # We also need to set the generated image to the texture node with label {stop_index}-{mat_id}++ # Reconnect script directly+ for to_socket in compare_output_sockets:+ links.new(script_node.outputs[0], to_socket)++ # Update TEX_IMAGE node for this viewfor node in nodes:- if node.type == 'TEX_IMAGE' and node.label == f"{stop_index}-{mat_id}":- if not context.scene.bake_texture:- image_path = get_file_path(context, "generated", camera_id=stop_index, material_id=mat_id)- if (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate') and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate \- and not context.scene.use_ipadapter and stop_index == 0 and context.scene.sequential_ipadapter_mode == 'first':- image_path = get_file_path(context, "generated", camera_id=stop_index, material_id=mat_id).replace(".png", "_ipadapter.png")+ if node.type == "TEX_IMAGE" and node.label == f"{stop_index}-{mat_id}":+ if not bake_texture_flag:+ image_path = get_file_path(+ context,+ "generated",+ camera_id=stop_index,+ material_id=mat_id,+ )+ if (+ gen_method in ("sequential", "separate")+ and scene.sequential_ipadapter+ and scene.sequential_ipadapter_regenerate+ and not scene.use_ipadapter+ and stop_index == 0+ and scene.sequential_ipadapter_mode == "first"+ ):+ image_path = image_path.replace(".png", "_ipadapter.png")else:- # Use baked texture- image_path = get_file_path(context, "generated_baked", camera_id=stop_index, material_id=mat_id, object_name=obj.name)-- image = get_or_load_image(image_path, force_reload=context.scene.overwrite_material)+ image_path = get_file_path(+ context,+ "generated_baked",+ camera_id=stop_index,+ material_id=mat_id,+ object_name=obj.name,+ )++ image = get_or_load_image(+ image_path, force_reload=overwrite_material+ )if image:node.image = imagebreak- # Now we can continue to the next object- continue-- elif not context.scene.refine_preserve or not context.scene.generation_method == 'refine':- # Clear existing nodes- for node in nodes:- nodes.remove(node)++ continue # go to next object++ # ---------------------------------------------------------------------+ # Non-refine or no-preserve path: clear nodes+ # ---------------------------------------------------------------------+ if not (is_refine and refine_preserve):+ nodes.clear()+ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (3000, 0)else:- # Find the node connected to the output node+ # Find material output and its upstream nodefor node in nodes:- if node.type == 'OUTPUT_MATERIAL':+ if node.type == "OUTPUT_MATERIAL":output = nodebreak- if output:- # Save the node connected to the output node into a variable- if output.inputs[0].links[0].from_node.type == 'BSDF_PRINCIPLED':- previous_node = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ if output and output.inputs[0].links:+ from_node = output.inputs[0].links[0].from_node+ if from_node.type == "BSDF_PRINCIPLED" and from_node.inputs[0].links:+ previous_node = from_node.inputs[0].links[0].from_nodeelse:- previous_node = output.inputs[0].links[0].from_node-- if not (context.scene.generation_method == 'refine' and context.scene.refine_preserve):- output = nodes.new("ShaderNodeOutputMaterial")- output.location = (3000, 0)-+ previous_node = from_node++ if output is None:+ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (3000, 0)++ # Geometry nodegeometry = nodes.new("ShaderNodeNewGeometry")geometry.location = (-600, 0)@@ -351,109 +432,137 @@ def project_image(context, to_project, mat_id, stop_index=1000000):camera_direction_nodes = []camera_up_nodes = []+ # ---------------------------------------------------------------------+ # Per-camera nodes+ # ---------------------------------------------------------------------for i, camera in enumerate(cameras):- # Add image texture node+ # Image nodetex_image = nodes.new("ShaderNodeTexImage")+ tex_image.location = (0, -200 * i)+ tex_image.extension = "CLIP"+ tex_image.label = f"{i}-{mat_id}"+if i <= stop_index:- if not context.scene.bake_texture:- image_path = get_file_path(context, "generated", camera_id=i, material_id=mat_id)- if (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate') and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate \- and not context.scene.use_ipadapter and i == 0 and context.scene.sequential_ipadapter_mode == 'first':- image_path = get_file_path(context, "generated", camera_id=i, material_id=mat_id).replace(".png", "_ipadapter.png")+ if not bake_texture_flag:+ image_path = get_file_path(+ context, "generated", camera_id=i, material_id=mat_id+ )+ if (+ gen_method in ("sequential", "separate")+ and scene.sequential_ipadapter+ and scene.sequential_ipadapter_regenerate+ and not scene.use_ipadapter+ and i == 0+ and scene.sequential_ipadapter_mode == "first"+ ):+ image_path = image_path.replace(".png", "_ipadapter.png")else:- # Use baked texture- image_path = get_file_path(context, "generated_baked", camera_id=i, material_id=mat_id, object_name=obj.name)-- image = get_or_load_image(image_path, force_reload=context.scene.overwrite_material)+ image_path = get_file_path(+ context,+ "generated_baked",+ camera_id=i,+ material_id=mat_id,+ object_name=obj.name,+ )++ image = get_or_load_image(image_path, force_reload=overwrite_material)if image:tex_image.image = image- tex_image.location = (0, -200 * i)- tex_image.extension = 'CLIP'- tex_image.label = f"{i}-{mat_id}"tex_image_nodes.append(tex_image)-- # Add UV map node++ # UV mapuv_map_node = nodes.new("ShaderNodeUVMap")- if not context.scene.bake_texture:- uv_map_node.uv_map = f"ProjectionUV_{i}_{mat_id}"- else:- # Use the original UV map- uv_map_node.uv_map = original_uv_map.name- uv_map_node.location = (-200, -200 * (i+1))+ uv_map_node.location = (-200, -200 * (i + 1))+ uv_map_node.uv_map = (+ f"ProjectionUV_{i}_{mat_id}"+ if not bake_texture_flag+ else original_uv_map.name+ )uv_map_nodes.append(uv_map_node)-- # Compute the dot product of the direction vector and geometry normal+ # Direction vector (from camera to position -> normalized)subtract = nodes.new("ShaderNodeVectorMath")- subtract.operation = 'SUBTRACT'+ subtract.operation = "SUBTRACT"subtract.location = (-400, -300 + (-800) * i)subtract.inputs[1].default_value = camera.locationsubtract_nodes.append(subtract)normalize = nodes.new("ShaderNodeVectorMath")- normalize.operation = 'NORMALIZE'- normalize.location = (-400, -500 + (-800) * (i))+ normalize.operation = "NORMALIZE"+ normalize.location = (-400, -500 + (-800) * i)normalize_nodes.append(normalize)-- # Switch to Cycles for OSL support- context.scene.render.engine = 'CYCLES'- context.scene.cycles.device = 'CPU'- context.scene.cycles.shading_system = True-- # Add a script node+ # Script node (OSL raycast)script = nodes.new("ShaderNodeScript")- script.location = (-400, (-800) * i)- script.mode = 'EXTERNAL'+ script.location = (-400, -800 * i)+ script.mode = "EXTERNAL"script.filepath = os.path.join(os.path.dirname(__file__), "raycast.osl")- script.inputs["AngleThreshold"].default_value = context.scene.discard_factor- script.inputs["Power"].default_value = context.scene.weight_exponentscript.label = f"{i}-{mat_id}"++ # Angle / power from UI+ script.inputs["AngleThreshold"].default_value = scene.discard_factor+ script.inputs["Power"].default_value = scene.weight_exponent++ # Frustum feather controls from UI+ if scene.visibility_vignette:+ script.inputs["EdgeFeather"].default_value = scene.visibility_vignette_width+ script.inputs["EdgeGamma"].default_value = scene.visibility_vignette_softness+ else:+ script.inputs["EdgeFeather"].default_value = 0.0+ script.inputs["EdgeGamma"].default_value = 1.0+script_nodes.append(script)+if i > stop_index:- # Connect a temporary less than node to the script nodeless_than = nodes.new("ShaderNodeMath")- less_than.operation = 'LESS_THAN'- less_than.location = (-200, (-800) * i)+ less_than.operation = "LESS_THAN"+ less_than.location = (-200, -800 * i)less_than.inputs[1].default_value = -1links.new(script.outputs[0], less_than.inputs[0])script_nodes_outputs.append(less_than)else:script_nodes_outputs.append(script)- # Add additional add node, which will contain camera's FOV in first default value, and camera's aspect ratio in second default value+ # Camera FOV (corrected for vertical aspect when needed)camera_fov = nodes.new("ShaderNodeValue")camera_fov.location = (-600, 200 + 300 * i)fov = camera.data.angle_x- # Correct the FOV for vertical aspect ratio- if context.scene.render.resolution_y > context.scene.render.resolution_x:- fov = 2 * atan(tan(fov / 2) * context.scene.render.resolution_x / context.scene.render.resolution_y)+ if render.resolution_y > render.resolution_x:+ fov = 2 * atan(+ tan(fov / 2) * render.resolution_x / render.resolution_y+ )camera_fov.outputs[0].default_value = fovcamera_fov_nodes.append(camera_fov)++ # Camera aspect ratiocamera_aspect_ratio = nodes.new("ShaderNodeValue")camera_aspect_ratio.location = (-600, 200 + 300 * i)-- # Add camera direction and up nodes (combine XYZ)+ camera_aspect_ratio.outputs[0].default_value = (+ render.resolution_x / render.resolution_y+ )+ camera_aspect_ratio_nodes.append(camera_aspect_ratio)++ # Camera direction (forward) and up vectors+ cam_quat = camera.matrix_world.to_quaternion()+camera_direction = nodes.new("ShaderNodeCombineXYZ")camera_direction.location = (-600, 200 + 300 * i)- # Get the camera direction vector- camera_direction.inputs[0].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))).x- camera_direction.inputs[1].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))).y- camera_direction.inputs[2].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))).z+ forward = cam_quat @ Vector((0, 0, -1))+ camera_direction.inputs[0].default_value = forward.x+ camera_direction.inputs[1].default_value = forward.y+ camera_direction.inputs[2].default_value = forward.zcamera_direction_nodes.append(camera_direction)+camera_up = nodes.new("ShaderNodeCombineXYZ")camera_up.location = (-600, 200 + 300 * i)- # Get the camera up vector- camera_up.inputs[0].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 1, 0))).x- camera_up.inputs[1].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 1, 0))).y- camera_up.inputs[2].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 1, 0))).z+ up_vec = cam_quat @ Vector((0, 1, 0))+ camera_up.inputs[0].default_value = up_vec.x+ camera_up.inputs[1].default_value = up_vec.y+ camera_up.inputs[2].default_value = up_vec.zcamera_up_nodes.append(camera_up)-- camera_aspect_ratio.outputs[0].default_value = context.scene.render.resolution_x / context.scene.render.resolution_y- camera_aspect_ratio_nodes.append(camera_aspect_ratio)- # Add combine XYZ node+ # Camera origin (Combine XYZ)add_camera_loc = nodes.new("ShaderNodeCombineXYZ")add_camera_loc.location = (-600, 200 + 300 * i)add_camera_loc.inputs[0].default_value = camera.location.x@@ -461,33 +570,42 @@ def project_image(context, to_project, mat_id, stop_index=1000000):add_camera_loc.inputs[2].default_value = camera.location.zadd_camera_loc_nodes.append(add_camera_loc)- # Add length node+ # Distance (length of ray from camera to position)length = nodes.new("ShaderNodeVectorMath")- length.operation = 'LENGTH'- length.location = (-400, 200 * (i+1))+ length.operation = "LENGTH"+ length.location = (-400, 200 * (i + 1))length_nodes.append(length)- # Build mix shader tree- mix_node, _ = build_mix_tree(tex_image_nodes, script_nodes_outputs, nodes, links, previous_node, stop_index=stop_index)+ # ---------------------------------------------------------------------+ # Mix textures together with weight tree+ # ---------------------------------------------------------------------+ mix_node, _ = build_mix_tree(+ tex_image_nodes,+ script_nodes_outputs,+ nodes,+ links,+ last_node=previous_node,+ stop_index=stop_index,+ )links.new(mix_node.outputs[0], output.inputs["Surface"])-- # Move output node right to the mix_nodeoutput.location = (mix_node.location[0] + 400, mix_node.location[1])- for i, camera in enumerate(cameras):+ # ---------------------------------------------------------------------+ # Wire up common inputs to each camera's nodes+ # ---------------------------------------------------------------------+ for i, _camera in enumerate(cameras):tex_image = tex_image_nodes[i]uv_map_node = uv_map_nodes[i]- subtract = subtract_nodes[i]- normalize = normalize_nodes[i]+ subtract = subtract_nodes[i]+ normalize = normalize_nodes[i]script = script_nodes[i]- add_camera_loc = add_camera_loc_nodes[i]- length = length_nodes[i]+ add_camera_loc = add_camera_loc_nodes[i]+ length = length_nodes[i]camera_fov = camera_fov_nodes[i]camera_aspect_ratio = camera_aspect_ratio_nodes[i]camera_direction = camera_direction_nodes[i]camera_up = camera_up_nodes[i]- # Connect common nodeslinks.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])links.new(geometry.outputs["Position"], subtract.inputs[0])links.new(subtract.outputs["Vector"], normalize.inputs[0])@@ -501,85 +619,118 @@ def project_image(context, to_project, mat_id, stop_index=1000000):links.new(camera_up.outputs[0], script.inputs["CameraUp"])links.new(subtract.outputs["Vector"], length.inputs[0])- # Add material index node (subtract node)+ # Material index node (kept as-is, though unused in your snippet)subtract_node = nodes.new("ShaderNodeMath")- subtract_node.operation = 'SUBTRACT'+ subtract_node.operation = "SUBTRACT"subtract_node.inputs[0].default_value = mat_idsubtract_node.location = (-1000, 0)+return Truedef simple_project_bake(context, camera_id, obj, mat_id):- # Create a temporary material for the projection+ scene = context.scene+ view_layer = context.view_layer++ # -------------------------------------------------------------------------+ # Create and assign temporary projection material+ # -------------------------------------------------------------------------mat = bpy.data.materials.new(name="ProjectionMaterialTemp")obj.data.materials.append(mat)- # Switch the active material to the new material (Switch to edit mode, select all, assign the material)+ # Make the new material active and assign it to all facesobj.active_material_index = len(obj.material_slots) - 1- bpy.context.view_layer.objects.active = obj+ view_layer.objects.active = obj+bpy.ops.object.mode_set(mode='EDIT')bpy.ops.mesh.select_all(action='DESELECT')bpy.ops.mesh.select_all(action='SELECT')bpy.ops.object.material_slot_assign()bpy.ops.object.mode_set(mode='OBJECT')+ # -------------------------------------------------------------------------# Unwrap (only for the first camera)+ # -------------------------------------------------------------------------if camera_id == 0:- unwrap(obj, context.scene.bake_unwrap_method, context.scene.bake_unwrap_overlap_only)+ unwrap(obj, scene.bake_unwrap_method, scene.bake_unwrap_overlap_only)- # Enable use of nodes+ # -------------------------------------------------------------------------+ # Node setup for temporary material+ # -------------------------------------------------------------------------mat.use_nodes = Truenodes = mat.node_tree.nodeslinks = mat.node_tree.links- # Clear existing nodes- for node in nodes:- nodes.remove(node)+ nodes.clear()- # Add image texture node+ # Image texturetex_image = nodes.new("ShaderNodeTexImage")-- file_path = get_file_path(context, "generated", camera_id=camera_id, material_id=mat_id)- if (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate') and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate \- and not context.scene.use_ipadapter and camera_id == 0 and context.scene.sequential_ipadapter_mode == 'first':- file_path = get_file_path(context, "generated", camera_id=camera_id, material_id=mat_id).replace(".png", "_ipadapter.png")-- image = get_or_load_image(file_path, force_reload=context.scene.overwrite_material)++ # Resolve file path (with sequential IPAdapter override if applicable)+ file_path = get_file_path(+ context,+ "generated",+ camera_id=camera_id,+ material_id=mat_id,+ )++ if (+ scene.generation_method in {'sequential', 'separate'}+ and scene.sequential_ipadapter+ and scene.sequential_ipadapter_regenerate+ and not scene.use_ipadapter+ and camera_id == 0+ and scene.sequential_ipadapter_mode == 'first'+ ):+ file_path = file_path.replace(".png", "_ipadapter.png")++ image = get_or_load_image(file_path, force_reload=scene.overwrite_material)if image:tex_image.image = image- # Add UV map node+ # UV map nodeuv_map_node = nodes.new("ShaderNodeUVMap")uv_map_node.uv_map = f"ProjectionUV_{camera_id}_{mat_id}"-- # Add BSDF node++ # BSDF + outputbsdf = nodes.new("ShaderNodeBsdfPrincipled")bsdf.inputs["Roughness"].default_value = 1.0- # Add output nodeoutput = nodes.new("ShaderNodeOutputMaterial")++ # Wiring: UV → Texture → BSDF/Outputlinks.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])- # Connect the nodes- if context.scene.apply_bsdf:++ if scene.apply_bsdf:links.new(tex_image.outputs["Color"], bsdf.inputs["Base Color"])links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])else:links.new(tex_image.outputs["Color"], output.inputs["Surface"])-- # Bake texture using BakeTextures.bake_texture- texture_size = context.scene.bake_texture_size- original_engine = context.scene.render.engine++ # -------------------------------------------------------------------------+ # Baking+ # -------------------------------------------------------------------------+ texture_size = scene.bake_texture_size+ original_engine = scene.render.engine+prepare_baking(context)-- # If the object has no UV map, create one++ # Ensure object has at least one UV map for bakingif not obj.data.uv_layers:obj.data.uv_layers.new(name="UVMap")-- bake_texture(context, obj, texture_size, suffix=f"{camera_id}-{mat_id}", output_dir=get_dir_path(context, "generated_baked"))- context.scene.render.engine = original_engine- # Remove the temporary material- bpy.ops.object.material_slot_remove()+ bake_texture(+ context,+ obj,+ texture_size,+ suffix=f"{camera_id}-{mat_id}",+ output_dir=get_dir_path(context, "generated_baked"),+ )++ # Restore original render engine+ scene.render.engine = original_engine+ # Remove the temporary material slot (the active one we just used)+ bpy.ops.object.material_slot_remove()def get_or_load_image(filepath, force_reload=False):"""diff --git a/stablegen/raycast.osl b/stablegen/raycast.oslindex 4cfd278..ced3363 100644--- a/stablegen/raycast.osl+++ b/stablegen/raycast.osl@@ -1,69 +1,88 @@-shader raycast(- vector Origin = P, // Camera position in world space- vector Direction = N, // Ray direction in world space- vector SurfaceNormal = N,- float threshold = 1,- float CameraAspect = 1.77778, // width/height ratio (e.g., 16:9)- float CameraFOV = 1.0, // horizontal FOV in radians- vector CameraDir = vector(0,0,-1), // Camera look direction in world space- 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)- output float Result = 0-)-{- // Normalize the world-space ray direction.- vector d = normalize(Direction);-- // Build camera basis.- vector forward = normalize(CameraDir);- vector r = normalize(cross(forward, CameraUp));- vector upVector = normalize(cross(r, forward));-- // Transform the ray direction into the camera's coordinate system.- float cam_x = dot(d, r);- float cam_y = dot(d, upVector);- float cam_z = dot(d, -forward); // should be negative for rays in front of the camera-- // Only process rays that are in front of the camera.- if (cam_z >= 0) {- Result = 0;- return;- }-- // Compute film extents at a virtual film plane at z = -1.- float filmw = tan(CameraFOV * 0.5);- float filmh = filmw / CameraAspect;-- // Project the ray direction onto the film plane.- float x_proj = cam_x / -cam_z;- float y_proj = cam_y / -cam_z;-- // If the projected point falls outside the film bounds, exit.- if (abs(x_proj) > filmw || abs(y_proj) > filmh) {- Result = 0;- return;- }-- // Continue with the raycast.- float Distance = 99999999.99;- if (trace(Origin, d))- {- getmessage("trace", "hitdist", Distance);- if ((Distance + 0.001) < threshold)- Result = 0;- else {- float dot_val = dot(d, normalize(SurfaceNormal));- float orthogonality = abs(clamp(dot_val, -1.0, 1.0));- float angle = acos(orthogonality) * 180.0 / M_PI;- if (angle > AngleThreshold) {- Result = 0;- } else {- Result = pow(orthogonality, Power);- }- }- }- else {- Result = 0;- }-}+shader raycast(+ vector Origin = P, // Camera position in world space+ vector Direction = N, // Ray direction in world space+ vector SurfaceNormal = N,+ float threshold = 1,+ float CameraAspect = 1.77778, // width/height ratio (e.g., 16:9)+ float CameraFOV = 1.0, // horizontal FOV in radians+ vector CameraDir = vector(0,0,-1), // Camera look direction in world space+ 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 EdgeFeather = 2.0, // Fraction of radius used for feather (0 = off)+ float EdgeGamma = 1.0, // Softness of feather (<1 = softer, >1 = sharper)+ output float Result = 0+)+{+ // Normalize the world-space ray direction.+ vector d = normalize(Direction);++ // Build camera basis.+ vector forward = normalize(CameraDir);+ vector r = normalize(cross(forward, CameraUp));+ vector upVector = normalize(cross(r, forward));++ // Transform the ray direction into the camera's coordinate system.+ float cam_x = dot(d, r);+ float cam_y = dot(d, upVector);+ float cam_z = dot(d, -forward); // should be negative for rays in front of the camera++ // Only process rays that are in front of the camera.+ if (cam_z >= 0) {+ Result = 0;+ return;+ }++ // Compute film extents at a virtual film plane at z = -1.+ float filmw = tan(CameraFOV * 0.5);+ float filmh = filmw / CameraAspect;++ // Project the ray direction onto the film plane.+ float x_proj = cam_x / -cam_z;+ float y_proj = cam_y / -cam_z;++ // If the projected point falls outside the film bounds, exit.+ if (abs(x_proj) > filmw || abs(y_proj) > filmh) {+ Result = 0;+ return;+ }++ // Normalized distance to film edge: 0 at center, 1 at border.+ float nx = abs(x_proj) / filmw;+ float ny = abs(y_proj) / filmh;+ float edge = max(nx, ny);++ // Default: no feathering+ float edge_factor = 1.0;+ float feather = clamp(EdgeFeather, 0.0, 0.49);++ if (feather > 0.0) {+ // Soft feather near frustum border+ edge_factor = 1.0 - smoothstep(1.0 - feather, 1.0, edge);+ edge_factor = pow(edge_factor, max(0.01, EdgeGamma));+ }++ // Continue with the raycast.+ float Distance = 99999999.99;+ if (trace(Origin, d))+ {+ getmessage("trace", "hitdist", Distance);+ if ((Distance + 0.001) < threshold)+ Result = 0;+ else {+ float dot_val = dot(d, normalize(SurfaceNormal));+ float orthogonality = abs(clamp(dot_val, -1.0, 1.0));+ float angle = acos(orthogonality) * 180.0 / M_PI;+ if (angle > AngleThreshold) {+ Result = 0;+ } else {+ // Original angle-based weight, modulated by edge feather.+ float base_weight = pow(orthogonality, Power);+ Result = base_weight * edge_factor;+ }+ }+ }+ else {+ Result = 0;+ }+}diff --git a/stablegen/render_tools.py b/stablegen/render_tools.pyindex e91f9f2..b00a49b 100644--- a/stablegen/render_tools.py+++ b/stablegen/render_tools.py@@ -18,260 +18,580 @@ import cv2import imageioimport imageio_ffmpeg+def purge_orphans():+ """+ Purge unused datablocks (images, materials, node groups, etc).+ Uses Blender's Outliner orphan purge.+ """+ try:+ # Blender 3.x/4.x: call recursively a few times to fully purge+ for _ in range(5):+ result = bpy.ops.outliner.orphans_purge(do_recursive=True)+ # If it reports "CANCELLED" or does nothing, we're done+ if 'CANCELLED' in result:+ break+ except Exception as e:+ print(f"[StableGen] Orphan purge failed: {e}")++def apply_vignette_to_mask(mask_file_path, feather_width=0.15, gamma=1.0):+ """+ Soften hard edges in a grayscale visibility mask.++ Instead of only darkening a thin border at the image edges, this applies+ a Gaussian blur whose radius is proportional to the image size. That means+ *any* 0→1 transition in the mask (occlusion edges, camera frustum edges,+ etc.) becomes a smooth ramp, which the shader can use for a soft blend.++ feather_width: fraction of min(image_w, image_h) used as blur radius.+ 0.0 = no blur, 0.5 = very soft edges.+ gamma: optional gamma applied to the blurred mask (1.0 = none).+ """+ log_prefix = "[StableGen] Vignette:"++ # -------------------------------------------------------------------------+ # Basic guards+ # -------------------------------------------------------------------------+ if feather_width <= 0.0:+ return++ if not isinstance(mask_file_path, str):+ print(f"{log_prefix} mask_file_path must be a string, got {type(mask_file_path)}")+ return++ if not os.path.exists(mask_file_path):+ print(f"{log_prefix} mask file not found: {mask_file_path}")+ return++ img = cv2.imread(mask_file_path, cv2.IMREAD_GRAYSCALE)+ if img is None:+ print(f"{log_prefix} failed to read mask: {mask_file_path}")+ return++ # -------------------------------------------------------------------------+ # Blur-based feathering+ # -------------------------------------------------------------------------+ h, w = img.shape[:2]+ base = img.astype(np.float32) / 255.0++ # Radius as a fraction of the smallest dimension+ min_dim = float(min(h, w))+ radius = max(1.0, feather_width * min_dim)++ # Kernel size must be odd and at least 3+ ksize = int(max(3, int(radius) | 1))++ blurred = cv2.GaussianBlur(base, (ksize, ksize), 0)++ if gamma != 1.0:+ blurred = np.power(blurred, gamma)++ result = np.clip(blurred, 0.0, 1.0)+ result_u8 = (result * 255.0).astype(np.uint8)+ cv2.imwrite(mask_file_path, result_u8)++ print(+ f"{log_prefix} soft-edge blur applied to mask: {mask_file_path} "+ f"(ksize={ksize}, fw={feather_width}, gamma={gamma})"+ )def apply_uv_inpaint_texture(context, obj, baked_image_path):"""- Applies the UV inpainted texture to the active material by replacing- the fallback color node in the node tree.+ Apply a UV inpainted/baked texture to the active material.++ Priority:+ 1) StableGen projection chain: replace LAST MixRGB with "Projection" in name (Color2).+ 2) Fallback: traverse from Material Output and find a suitable MIX_RGB (Color2 unlinked+ or linked from TEX_IMAGE), then replace that (Color2).++ In both cases:+ - Insert TexImage + UVMap (first non-ProjectionUV layer) feeding Color2.+ - Remove existing Color2 links.+ - If replacing a projection input, also remove the old TexImage node and orphaned image."""+mat = obj.active_material- if not mat or not mat.use_nodes:+ if not mat or not mat.use_nodes or not mat.node_tree:+ print("[StableGen] No active material or no node tree.")return+nodes = mat.node_tree.nodeslinks = mat.node_tree.links- # Locate the Output Material node- output_node = None- for node in nodes:- if node.type == 'OUTPUT_MATERIAL':- output_node = node- break+ # -----------------------------+ # Load baked image+ # -----------------------------+ try:+ img = bpy.data.images.load(baked_image_path)+ except Exception as e:+ print("[StableGen] Failed to load baked image", baked_image_path, e)+ return++ # -----------------------------+ # Helpers+ # -----------------------------+ def pick_uv_name():+ uv_layers = getattr(obj.data, "uv_layers", None)+ if not uv_layers or len(uv_layers) == 0:+ return None+ for uv_layer in uv_layers:+ if not uv_layer.name.startswith("ProjectionUV"):+ return uv_layer.name+ return uv_layers.active.name++ def clear_color2_links(mix_node, cleanup_teximage=False):+ """Remove links to Color2. Optionally remove upstream TexImage nodes & orphaned images."""+ for link in list(mix_node.inputs["Color2"].links):+ src = link.from_node+ links.remove(link)++ if cleanup_teximage and src and src.type == "TEX_IMAGE":+ old_img = src.image+ try:+ nodes.remove(src)+ except Exception:+ pass+ if old_img and old_img.users == 0:+ try:+ bpy.data.images.remove(old_img)+ except Exception:+ pass++ def inject_tex_uv_into_color2(mix_node):+ """Create TexImage+UVMap and connect into mix_node Color2."""+ tex = nodes.new("ShaderNodeTexImage")+ tex.image = img+ tex.label = "BakedProjection"+ tex.location = (mix_node.location[0] - 300, mix_node.location[1])++ uv = nodes.new("ShaderNodeUVMap")+ uv_name = pick_uv_name()+ if uv_name:+ uv.uv_map = uv_name+ uv.location = (tex.location[0] - 300, tex.location[1] - 200)++ links.new(uv.outputs["UV"], tex.inputs["Vector"])+ links.new(tex.outputs["Color"], mix_node.inputs["Color2"])++ # ============================================================+ # 1) StableGen projection chain path+ # ============================================================+ proj_mix_nodes = [n for n in nodes if n.type == "MIX_RGB" and "Projection" in n.name]+ if proj_mix_nodes:+ mix_node = sorted(proj_mix_nodes, key=lambda n: n.name)[-1]++ # Remove previous projection input, clean up old TexImage nodes+ clear_color2_links(mix_node, cleanup_teximage=True)++ # Inject baked texture+ inject_tex_uv_into_color2(mix_node)++ print(f"[StableGen] Injected baked projection into projection chain ({mix_node.name}) on {obj.name}")+ return++ # ============================================================+ # 2) Fallback traversal path (your original logic)+ # ============================================================+ output_node = next((n for n in nodes if n.type == "OUTPUT_MATERIAL"), None)if not output_node or not output_node.inputs["Surface"].links:+ print("[StableGen] No Material Output surface link found for fallback.")return- # Traverse from the output input to find a MIX_RGB node with unlinked Color2- mix_node = Nonebefore_output = output_node.inputs["Surface"].links[0].from_node- if before_output.type == 'BSDF_PRINCIPLED':- current_node = output_node.inputs[0].links[0].from_node.inputs[0].links[0].from_node++ if before_output.type == "BSDF_PRINCIPLED":+ # Follow: Output.Surface -> Principled -> Base Color -> upstream node+ base_color = before_output.inputs.get("Base Color")+ if base_color and base_color.links:+ current_node = base_color.links[0].from_node+ else:+ current_node = Noneelse:- # Already a color mix nodecurrent_node = before_output- while current_node:- # Base case: Found a MIX_RGB node with unlinked Color2 or linked to image texture- if (current_node.type == 'MIX_RGB' and- (not current_node.inputs["Color2"].is_linked or current_node.inputs["Color2"].links[0].from_node.type == 'TEX_IMAGE')):- mix_node = current_node- break- # If possible, traverse one step back using the first input link- if current_node.inputs["Color2"].links:- current_node = current_node.inputs["Color2"].links[0].from_node++ mix_node = None+ visited = set()++ while current_node and current_node.as_pointer() not in visited:+ visited.add(current_node.as_pointer())++ if current_node.type == "MIX_RGB":+ c2 = current_node.inputs.get("Color2")+ if c2:+ if (not c2.is_linked) or (c2.is_linked and c2.links and c2.links[0].from_node.type == "TEX_IMAGE"):+ mix_node = current_node+ break++ c2 = current_node.inputs.get("Color2")+ if c2 and c2.links:+ current_node = c2.links[0].from_nodeelse:current_node = Noneif not mix_node:+ print("[StableGen] No suitable fallback MixRGB node found.")return- # Insert the texture node feeding into the mix node- tex_node = nodes.new("ShaderNodeTexImage")+ # Remove any existing links on Color2 (fallback does NOT aggressively delete nodes/images)+ clear_color2_links(mix_node, cleanup_teximage=False)++ # Insert baked texture + UVMap+ inject_tex_uv_into_color2(mix_node)++ print(f"[StableGen] Injected baked projection into fallback chain ({mix_node.name}) on {obj.name}")+++def flatten_projection_material_for_refine(context, obj, baked_image_path):+ """+ Replace the StableGen ProjectionMaterial on this object with a minimal+ baked-base material that still matches the expectations of:+ - export_emit_image / _setup_emit_material+ - project_image refine_preserve logic++ Final graph:+ UV Map -> Baked Image -> MixRGB -> Principled BSDF -> Output+ """+ import ostry:img = bpy.data.images.load(baked_image_path)except Exception as e:- print("Failed to load image", baked_image_path, e)+ print(f"[StableGen] Failed to load baked image for {obj.name}: {baked_image_path} ({e})")return++ # -------------------------------------------------------------------------+ # 1) Find or create a suitable material+ # -------------------------------------------------------------------------+ target_mat = None+ for slot in obj.material_slots:+ mat = slot.material+ if mat and mat.name.startswith("ProjectionMaterial"):+ target_mat = mat+ break++ if target_mat is None:+ target_mat = obj.active_material++ if target_mat is None:+ target_mat = bpy.data.materials.new(name="ProjectionMaterial")+ obj.data.materials.append(target_mat)++ obj.active_material = target_mat+ if obj.active_material_index < 0:+ if target_mat not in obj.data.materials:+ obj.data.materials.append(target_mat)+ obj.active_material_index = obj.material_slots.find(target_mat.name)++ # -------------------------------------------------------------------------+ # 2) Build: UV -> Tex -> MixRGB -> Principled -> Output+ # -------------------------------------------------------------------------+ target_mat.use_nodes = True+ nodes = target_mat.node_tree.nodes+ links = target_mat.node_tree.links++ # Clear old nodes+ for node in list(nodes):+ nodes.remove(node)++ # Output+ output_node = nodes.new("ShaderNodeOutputMaterial")+ output_node.location = (800, 0)++ # Principled+ principled_node = nodes.new("ShaderNodeBsdfPrincipled")+ principled_node.location = (500, 0)+ principled_node.inputs["Roughness"].default_value = 1.0++ # MixRGB that _setup_emit_material expects to sit before the Principled+ mix_node = nodes.new("ShaderNodeMixRGB")+ mix_node.location = (200, 0)+ mix_node.use_clamp = True+ # Fac=0 -> output = Color1 (baked tex)+ mix_node.inputs["Fac"].default_value = 0.0++ # Baked texture+ tex_node = nodes.new("ShaderNodeTexImage")+ tex_node.location = (-100, 0)tex_node.image = img- tex_node.location = (mix_node.location[0] - 300, mix_node.location[1])- # Remove any existing links on Color2 and connect new texture output- for link in mix_node.inputs["Color2"].links:- links.remove(link)- links.new(tex_node.outputs["Color"], mix_node.inputs["Color2"])- # Add UV map node- uv_map_node = nodes.new("ShaderNodeUVMap")- # Find first UV map which doesn't start with "ProjectionUV"- uv_map_name = None- for uv_map in obj.data.uv_layers:- if uv_map.name.startswith("ProjectionUV"):- continue- uv_map_name = uv_map.name- break- if uv_map_name:- uv_map_node.uv_map = uv_map_name- else:- uv_map_node.uv_map = obj.data.uv_layers.active.name- uv_map_node.location = (tex_node.location[0] - 300, tex_node.location[1] - 200)- # Connect UV map node to texture node- links.new(uv_map_node.outputs["UV"], tex_node.inputs["Vector"])-def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard', fallback_color=(0,0,0)):- """- Exports a emit-only render of the scene from a camera's perspective.- :param context: Blender context.- :param camera_id: ID of the camera.- :return: None- """- print("Exporting emit render")- # Set animation frame to 1- bpy.context.scene.frame_set(1)-- # Store original materials and create temporary ones- original_materials = {}- original_active_material = {}- temporary_materials = {}-- # Check if there is BSDF applied-- # We need to temporarily disconnect BDSF nodes and connect their inputs directly to the output-- for obj in to_export:- # Store original materials+ # UV map+ uv_node = nodes.new("ShaderNodeUVMap")+ uv_node.location = (-400, -150)++ # -------------------------------------------------------------------------+ # 3) Choose a stable UV map (avoid ProjectionUV)+ # -------------------------------------------------------------------------+ uv_name = None+ for uv in obj.data.uv_layers:+ if not uv.name.startswith("ProjectionUV"):+ uv_name = uv.name+ break++ if not uv_name:+ uv_names = [uv.name for uv in obj.data.uv_layers]+ if "BakeUV" in uv_names:+ uv_name = "BakeUV"+ else:+ uv_layer = obj.data.uv_layers.new(name="BakeUV")+ uv_name = uv_layer.name++ uv_node.uv_map = uv_name++ # -------------------------------------------------------------------------+ # 4) Wire up the graph+ # -------------------------------------------------------------------------+ links.new(uv_node.outputs["UV"], tex_node.inputs["Vector"])+ links.new(tex_node.outputs["Color"], mix_node.inputs["Color1"])++ links.new(mix_node.outputs["Color"], principled_node.inputs["Base Color"])++ # Drive emission too (Blender 4.x uses "Emission Color")+ if "Emission Color" in principled_node.inputs:+ links.new(mix_node.outputs["Color"], principled_node.inputs["Emission Color"])+ elif "Emission" in principled_node.inputs:+ links.new(mix_node.outputs["Color"], principled_node.inputs["Emission"])++ if "Emission Strength" in principled_node.inputs:+ principled_node.inputs["Emission Strength"].default_value = 1.0++ links.new(principled_node.outputs["BSDF"], output_node.inputs["Surface"])+++ print(f"[StableGen] Flattened ProjectionMaterial for '{obj.name}' to baked texture '{os.path.basename(baked_image_path)}'")++def export_emit_image(+ context,+ to_export,+ camera_id=None,+ bg_color=(0.5, 0.5, 0.5),+ view_transform="Standard",+ fallback_color=(0, 0, 0),+):+ """+ Exports an emit-only render of the scene from a camera's perspective.+ :param context: Blender context.+ :param to_export: Iterable of objects to process.+ :param camera_id: ID of the camera or a string containing 'visibility' for mask renders.+ """+ print("Exporting emit render")++ scene = context.scene+ view_layer = context.view_layer+ world = scene.world++ # -------------------------------------------------------------------------+ # Basic scene setup+ # -------------------------------------------------------------------------+ scene.frame_set(1)++ if not world:+ world = bpy.data.worlds.new("World")+ scene.world = world++ # Cache some original settings we *do* already restore in the original code+ original_engine = scene.render.engine+ original_film_transparent = scene.render.film_transparent+ original_world_use_nodes = world.use_nodes+ original_world_color = world.color.copy() if not world.use_nodes else None+ original_view_transform = scene.view_settings.view_transform++ # Precompute flags / strings+ camera_id_str = "" if camera_id is None else str(camera_id)+ is_visibility_render = "visibility" in camera_id_str++ # -------------------------------------------------------------------------+ # Material setup per object+ # -------------------------------------------------------------------------+ original_materials = {}+ original_active_material = {}+ temporary_materials = {}++ def _setup_emit_material(obj):+ """Copy active material, remap it for fallback background, and assign."""+ mat = obj.active_material+ if not mat:+ return++ # Store original materials+ original_materials[obj] = list(obj.data.materials)+ original_active_material[obj] = obj.active_material++ # Create a temporary copy of the active material+ mat_copy = mat.copy()+ temporary_materials[obj] = mat_copy++ # Replace all slots with the temp material+ obj.data.materials.clear()+ obj.data.materials.append(mat_copy)++ # Ensure node setup+ mat_copy.use_nodes = True+ nodes = mat_copy.node_tree.nodes+ links = mat_copy.node_tree.links++ # Find material output node+ output = None+ for node in nodes:+ if node.type == "OUTPUT_MATERIAL":+ output = node+ break++ if not output:+ return++ if not output.inputs[0].links:+ return++ before_output = output.inputs[0].links[0].from_node++ # Figure out which node is the color mix we want to drive+ if before_output.type == "BSDF_PRINCIPLED":+ # Assuming the Color input is driven by a Mix node+ if not before_output.inputs[0].links:+ return+ color_mix = before_output.inputs[0].links[0].from_node+ else:+ # Already a color mix node feeding the output+ color_mix = before_output++ # Only set fallback color if this is not a visibility render+ if not is_visibility_render:+ color_mix.inputs["Color2"].default_value = (+ float(fallback_color[0]),+ float(fallback_color[1]),+ float(fallback_color[2]),+ 1.0,+ )++ # Ensure the color mix drives the output directly+ links.new(color_mix.outputs[0], output.inputs[0])++ # Apply the temporary emit material setup+ for obj in to_export:+ # Only store materials for objects we actually touch+ if obj not in original_materials:original_materials[obj] = list(obj.data.materials)original_active_material[obj] = obj.active_material-- # Copy active material and switch to it- mat = obj.active_material- if not mat:- continue- mat_copy = mat.copy()+ _setup_emit_material(obj)- # Clear materials and assign temp material- obj.data.materials.clear()- obj.data.materials.append(mat_copy)-- # Store the temporary material for later deletion- temporary_materials[obj] = mat_copy+ # -------------------------------------------------------------------------+ # Output path setup+ # -------------------------------------------------------------------------+ inpaint_paths = get_dir_path(context, "inpaint")+ output_dir = inpaint_paths["visibility"] if is_visibility_render else inpaint_paths["render"]+ output_file = f"render{camera_id}" if camera_id is not None else "render"- # Enable use of nodes- mat_copy.use_nodes = True- nodes = mat_copy.node_tree.nodes- links = mat_copy.node_tree.links+ # -------------------------------------------------------------------------+ # World & render settings for flat background and emit-only pass+ # -------------------------------------------------------------------------+ # Flat background, no world nodes+ world.use_nodes = False+ world.color = bg_color++ render = scene.render+ cycles = scene.cycles++ render.engine = "CYCLES"+ render.film_transparent = False+ cycles.use_osl = True+ cycles.device = "CPU"+ cycles.samples = 1 # Minimum samples for speed++ # Color management+ scene.display_settings.display_device = "sRGB"+ scene.view_settings.view_transform = view_transform++ # Emit-only pass settings+ view_layer.use_pass_diffuse_color = False+ view_layer.use_pass_diffuse_direct = False+ view_layer.use_pass_diffuse_indirect = False+ view_layer.use_pass_ambient_occlusion = False+ view_layer.use_pass_shadow = False+ view_layer.use_pass_emit = True+ view_layer.use_pass_environment = True++ # -------------------------------------------------------------------------+ # Compositor setup+ # -------------------------------------------------------------------------+ scene.use_nodes = True+ comp_tree = scene.node_tree+ comp_nodes = comp_tree.nodes+ comp_links = comp_tree.links++ comp_nodes.clear()++ render_layers = comp_nodes.new("CompositorNodeRLayers")++ mix_node = comp_nodes.new("CompositorNodeMixRGB")+ mix_node.blend_type = "ADD"+ mix_node.inputs[0].default_value = 1.0++ output_node = comp_nodes.new("CompositorNodeOutputFile")+ output_node.base_path = output_dir+ output_node.file_slots[0].path = output_file- # Find the output node- output = None- for node in nodes:- if node.type == 'OUTPUT_MATERIAL':- output = node- break-- # Check the type of the node which connects to output- before_output = output.inputs[0].links[0].from_node- if before_output.type == 'BSDF_PRINCIPLED':- # Find the last color mix node- color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node- # Set color 2 to fallback color- if not "visibility" in str(camera_id):- color_mix.inputs["Color2"].default_value = (fallback_color[0], fallback_color[1], fallback_color[2], 1.0)- else:- # Already a color mix node- color_mix = before_output- # Set color 2 to fallback color- if not "visibility" in str(camera_id):- color_mix.inputs["Color2"].default_value = (fallback_color[0], fallback_color[1], fallback_color[2], 1.0)- continue+ comp_links.new(render_layers.outputs["Emit"], mix_node.inputs[1])+ comp_links.new(render_layers.outputs["Env"], mix_node.inputs[2])+ comp_links.new(mix_node.outputs[0], output_node.inputs[0])- # Find the last color mix node- color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node- # Connect the color mix node directly to the output- links.new(color_mix.outputs[0], output.inputs[0])-- output_dir = get_dir_path(context, "inpaint")["visibility"] if "visibility" in str(camera_id) else get_dir_path(context, "inpaint")["render"]- output_file = f"render{camera_id}" if camera_id is not None else "render"-- # Store and set world settings- world = context.scene.world- if not world:- world = bpy.data.worlds.new("World")- context.scene.world = world-- # Store original settings- original_engine = context.scene.render.engine- original_film_transparent = context.scene.render.film_transparent- original_use_nodes = world.use_nodes- original_color = world.color.copy() if not world.use_nodes else None-- # Now setting the world color should work- world.color = bg_color- # Disable world nodes temporarily- world.use_nodes = False- # Switch to CYCLES render engine and configure settings- context.scene.render.engine = 'CYCLES'- # Enable OSL- context.scene.cycles.use_osl = True- context.scene.cycles.device = 'CPU'- context.scene.render.film_transparent = False- # Change color management to standard- bpy.context.scene.display_settings.display_device = 'sRGB'- bpy.context.scene.view_settings.view_transform = view_transform- context.scene.cycles.samples = 1 # Minimum samples for speed- # Configure view layer settings for diffuse-only- view_layer = context.view_layer- view_layer.use_pass_diffuse_color = False- view_layer.use_pass_diffuse_direct = False- view_layer.use_pass_diffuse_indirect = False-- # Disable all other passes- view_layer.use_pass_ambient_occlusion = False- view_layer.use_pass_shadow = False- view_layer.use_pass_emit = True- view_layer.use_pass_environment = True--- # Set up nodes for diffuse-only output- context.scene.use_nodes = True- nodes = context.scene.node_tree.nodes- links = context.scene.node_tree.links-- # Clear existing nodes- nodes.clear()-- # Create nodes- render_layers = nodes.new('CompositorNodeRLayers')- mix_node = nodes.new('CompositorNodeMixRGB')- mix_node.blend_type = 'ADD'- mix_node.inputs[0].default_value = 1- output_node = nodes.new('CompositorNodeOutputFile')- output_node.base_path = output_dir- output_node.file_slots[0].path = output_file-- # Connect emission to output- links.new(render_layers.outputs['Emit'], mix_node.inputs[1])- links.new(render_layers.outputs['Env'], mix_node.inputs[2])- links.new(mix_node.outputs[0], output_node.inputs[0])-- # Render- bpy.ops.render.render(write_still=True)-- if context.scene.mask_blocky:- # If this is a visibility mask, expand it to blocks- if "visibility" in str(camera_id):- # Load the rendered image- image_path = os.path.join(output_dir, f"{output_file}.png")- image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)-- image_path = image_path.replace(".png", "0001.png")+ # -------------------------------------------------------------------------+ # Render+ # -------------------------------------------------------------------------+ bpy.ops.render.render(write_still=True)- # Expand the mask to blocks- expanded_mask = expand_mask_to_blocks(image_path, block_size=8)-- # Scale float32 to uint8 [0, 255]- expanded_mask = (expanded_mask * 255).astype(np.uint8)-- cv2.imwrite(image_path, expanded_mask)+ base_path = os.path.join(output_dir, f"{output_file}.png")+ final_path = base_path++ # -------------------------------------------------------------------------+ # Post-processing for visibility masks+ # -------------------------------------------------------------------------+ if is_visibility_render:+ final_path = base_path.replace(".png", "0001.png")++ if scene.visibility_vignette:+ # Smooth edge feathering, no blocky mask+ apply_vignette_to_mask(+ final_path,+ feather_width=scene.visibility_vignette_width,+ gamma=1.0,+ )+ elif scene.mask_blocky:+ # Only do blocky mask if vignette is OFF+ expanded_mask = expand_mask_to_blocks(final_path, block_size=8)+ if expanded_mask is not None:+ expanded_mask_u8 = (expanded_mask * 255).astype(np.uint8)+ cv2.imwrite(final_path, expanded_mask_u8)++ # -------------------------------------------------------------------------+ # Restore original scene settings (same behavior as original)+ # -------------------------------------------------------------------------+ render.engine = original_engine+ render.film_transparent = original_film_transparent++ if original_world_use_nodes:+ world.use_nodes = True+ elif original_world_color:+ world.color = original_world_color++ scene.view_settings.view_transform = original_view_transform++ # Restore original materials and active material+ for obj, materials in original_materials.items():+ obj.data.materials.clear()- # Restore original settings- context.scene.render.engine = original_engine- context.scene.render.film_transparent = original_film_transparent- if original_use_nodes:- world.use_nodes = True- elif original_color:- world.color = original_color- bpy.context.scene.view_settings.view_transform = 'Standard'+ active_mat = original_active_material.get(obj)+ if active_mat:+ obj.data.materials.append(active_mat)++ for mat in materials:+ if mat is not active_mat:+ obj.data.materials.append(mat)++ # Clean up temporary materials+ for temp_mat in temporary_materials.values():+ if temp_mat and temp_mat.name in bpy.data.materials:+ bpy.data.materials.remove(temp_mat)++ print(f"Emission render saved to: {os.path.join(output_dir, output_file)}.png")- # 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)-- print(f"Emmision render saved to: {os.path.join(output_dir, output_file)}.png")def export_render(context, camera_id=None):"""@@ -634,6 +954,13 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None):image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX)# Save the imagecv2.imwrite(image_path, image)++ if context.scene.visibility_vignette:+ apply_vignette_to_mask(+ image_path,+ feather_width=context.scene.visibility_vignette_width,+ gamma=1.0,+ )else:# Make sure the camera is active and set to rendercameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']@@ -1243,6 +1570,34 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =return True+def _has_non_projection_uv(obj):+ if not obj or obj.type != 'MESH':+ return False+ if not obj.data.uv_layers:+ return False+ for uv in obj.data.uv_layers:+ if not uv.name.startswith("ProjectionUV"):+ return True+ return False++def _uvs_likely_overlap(obj, uv_name=None):+ me = obj.data+ if not me.uv_layers:+ return False+ uv_layer = me.uv_layers.get(uv_name) if uv_name else me.uv_layers.active+ if not uv_layer:+ return False++ seen = set()+ for poly in me.polygons:+ for li in poly.loop_indices:+ uv = uv_layer.data[li].uv+ key = (round(uv.x, 5), round(uv.y, 5))+ if key in seen:+ return True+ seen.add(key)+ return False+class BakeTextures(bpy.types.Operator):"""Bakes textures using the cycles render engine.@@ -1280,6 +1635,12 @@ class BakeTextures(bpy.types.Operator):default=True) # type: ignore+ flatten_for_refine: bpy.props.BoolProperty(+ name="Bake & Continue Refining",+ description="After baking, apply the baked texture to the StableGen projection material and clean up previous projection images",+ default=False+ ) # type: ignore+overlap_only: bpy.props.BoolProperty(name="Overlap Only",description="Only unwrap objects with overlapping UVs",@@ -1330,6 +1691,14 @@ class BakeTextures(bpy.types.Operator):# Check if there are any textures to bakereturn True+ def draw(self, context):+ layout = self.layout+ layout.prop(self, "texture_resolution")+ layout.prop(self, "try_unwrap")+ layout.prop(self, "overlap_only")+ layout.prop(self, "add_material")+ layout.prop(self, "flatten_for_refine")+def invoke(self, context, event):"""Invokes the operator.@@ -1391,7 +1760,17 @@ class BakeTextures(bpy.types.Operator):self._stage = f"Unwrapping {obj.name}"self._progress = 0redraw()- unwrap(obj, self.try_unwrap, self.overlap_only)++ if self.try_unwrap != 'none':+ if not _has_non_projection_uv(obj):+ unwrap(obj, self.try_unwrap, self.overlap_only)+ else:+ if self.overlap_only:+ if _uvs_likely_overlap(obj):+ unwrap(obj, self.try_unwrap, self.overlap_only)+ else:+ pass+self._progress = 100elif self._phase == 'bake':self._stage = f"Baking {obj.name}"@@ -1401,6 +1780,16 @@ class BakeTextures(bpy.types.Operator):self.report({'ERROR'}, f"Failed to bake texture for {obj.name}. No materials found.")context.window_manager.event_timer_remove(self._timer)return {'CANCELLED'}++ # NEW: optionally flatten into the projection material so you can keep refining+ if self.flatten_for_refine:+ try:+ baked_path = get_file_path(context, "baked", object_name=obj.name)+ flatten_projection_material_for_refine(context, obj, baked_path)+ purge_orphans()+ except Exception as e:+ print(f"[StableGen] Failed to flatten projection material for {obj.name}: {e}")+self._progress = 100elif self._phase == 'apply_material' and self.add_material:self._stage = f"Applying Material to {obj.name}"@@ -1491,7 +1880,6 @@ class BakeTextures(bpy.types.Operator):links.new(principled_node.outputs["BSDF"], output_node.inputs["Surface"])else:links.new(tex_image.outputs["Color"], output_node.inputs["Surface"])-class ExportOrbitGIF(bpy.types.Operator):"""Exports a GIF and MP4 animation orbiting the active object"""diff --git a/stablegen/stablegen.py b/stablegen/stablegen.pyold mode 100755new mode 100644index 80b19fb..beb7b57--- a/stablegen/stablegen.py+++ b/stablegen/stablegen.py@@ -7,7 +7,7 @@ import math # pylint: disable=import-error# Stock presetsPRESETS = {- "DEFAULT": {"description": "Default settings for general purpose generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 90.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},+ "DEFAULT": {"description": "Default settings for general purpose generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 90.0, "weight_exponent": 3.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "hm-mvgd-hm", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},"MODEL IS IMPORTANT": {"description": "Same as default, but is more guided by the model", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 90.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.75, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},"CHARACTERS": {"description": "Optimized settings for character generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.1, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},"CHARACTERS (ALTERNATIVE MASKING)": {"description": "Optimized for character generation. Uses alternative masking parameters to be more consistent between images, but may produce more artifacts. Try if \"Characters\" fails.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.5, "sequential_factor_smooth": 0.3499999940395355, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 10, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},@@ -72,6 +72,9 @@ GEN_PARAMETERS = ["blur_mask","blur_mask_radius","blur_mask_sigma",+ "view_blend_use_color_match",+ "view_blend_color_match_method",+ "view_blend_color_match_strength","grow_mask_by","canny_threshold_low","canny_threshold_high",@@ -509,6 +512,15 @@ class StableGenPanel(bpy.types.Panel):if scene.early_priority:row = content_box.row()row.prop(scene, "early_priority_strength", text="Priority Strength")++ row = content_box.row()+ row.prop(scene, "view_blend_use_color_match", text="Match Colors to Viewport", toggle=True)++ if scene.view_blend_use_color_match:+ row = content_box.row(align=True)+ row.prop(scene, "view_blend_color_match_method", text="Method")+ row = content_box.row()+ row.prop(scene, "view_blend_color_match_strength", text="Strength")# --- Output & Material Settings ---@@ -737,7 +749,7 @@ class StableGenPanel(bpy.types.Panel):row = content_box.row()row.prop(scene, "blur_mask", text="Blur Mask", toggle=True, icon="SURFACE_NSPHERE")-+if scene.blur_mask:row = content_box.row()row.prop(scene, "blur_mask_radius", text="Blur Radius")@@ -752,25 +764,31 @@ class StableGenPanel(bpy.types.Panel):# --- Generation Mode Specifics ---mode_specific_outer_box = draw_collapsible_section(advanced_params_box, "show_mode_specific_settings", "Generation Mode Specifics", icon="OPTIONS")if mode_specific_outer_box: # This is the box where all mode-specific UIs should go-++ method = scene.generation_method++ # -------------------------# Grid Mode Parameters- if scene.generation_method == 'grid':+ # -------------------------+ if method == 'grid':# Draw Grid parameters directly into mode_specific_outer_boxrow = mode_specific_outer_box.row()row.alignment = 'CENTER'row.label(text="Grid Mode Parameters", icon="MESH_GRID")-+row = mode_specific_outer_box.row()- row.prop(scene, "refine_images", text="Refine Images", toggle=True, icon="SHADERFX")+ row.prop(scene, "refine_images",+ text="Refine Images",+ toggle=True, icon="SHADERFX")if scene.refine_images:split = mode_specific_outer_box.split(factor=0.5)split.label(text="Refine Sampler:")split.prop(scene, "refine_sampler", text="")-+split = mode_specific_outer_box.split(factor=0.5)split.label(text="Refine Scheduler:")split.prop(scene, "refine_scheduler", text="")-+row = mode_specific_outer_box.row()row.prop(scene, "denoise", text="Denoise")if width_mode == 'narrow':@@ -780,40 +798,46 @@ class StableGenPanel(bpy.types.Panel):row = mode_specific_outer_box.row()row.prop(scene, "refine_steps", text="Refine Steps")- row = mode_specific_outer_box.row()+ row = mode_specific_outer_box.row()split = mode_specific_outer_box.split(factor=0.25)split.label(text="Refine Prompt:")split.prop(scene, "refine_prompt", text="")-- split = mode_specific_outer_box.split(factor=0.5)- split.label(text="Refine Upscale:")++ split = mode_specific_outer_box.split(factor=0.5)+ split.label(text="Refine Upscale:")split.prop(scene, "refine_upscale_method", text="")+ # -------------------------# Separate Mode Parameters- elif scene.generation_method == 'separate':+ # -------------------------+ elif method == 'separate':row = mode_specific_outer_box.row()row.alignment = 'CENTER'row.label(text="Separate Mode Parameters", icon='FORCE_FORCE')-- row = mode_specific_outer_box.row()- row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Separate Mode", toggle=True, icon="MODIFIER")- if scene.sequential_ipadapter:++ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_ipadapter",+ text="Use IPAdapter for Separate Mode",+ toggle=True, icon="MODIFIER")+ if scene.sequential_ipadapter:sub_ip_box_separate = mode_specific_outer_box.box()-- split = sub_ip_box_separate.split(factor=0.5)++ split = sub_ip_box_separate.split(factor=0.5)split.label(text="Mode:")- split.prop(scene, "sequential_ipadapter_mode", text="")+ split.prop(scene, "sequential_ipadapter_mode", text="")if scene.sequential_ipadapter_mode == 'recent':- sub_ip_box_separate.prop(scene, "sequential_desaturate_factor", text="Desaturate")- sub_ip_box_separate.prop(scene, "sequential_contrast_factor", text="Reduce Contrast")+ sub_ip_box_separate.prop(+ scene, "sequential_desaturate_factor", text="Desaturate")+ sub_ip_box_separate.prop(+ scene, "sequential_contrast_factor", text="Reduce Contrast")if context.scene.model_architecture != 'qwen_image_edit':- split = sub_ip_box_separate.split(factor=0.5)+ split = sub_ip_box_separate.split(factor=0.5)if context.scene.model_architecture == 'sdxl':split.label(text="Weight Type:")split.prop(scene, "ipadapter_weight_type", text="")-+row = sub_ip_box_separate.row()row.prop(scene, "ipadapter_strength", text="Strength")if width_mode == 'narrow':@@ -821,38 +845,63 @@ class StableGenPanel(bpy.types.Panel):row.prop(scene, "ipadapter_start", text="Start")if width_mode == 'narrow':row = sub_ip_box_separate.row()- row.prop(scene, "ipadapter_end", text="End")-+ row.prop(scene, "ipadapter_end", text="End")+if context.scene.sequential_ipadapter_mode == 'first':row = sub_ip_box_separate.row()- row.prop(scene, "sequential_ipadapter_regenerate", text="Regenerate First Image", toggle=True, icon="FILE_REFRESH")+ row.prop(scene, "sequential_ipadapter_regenerate",+ text="Regenerate First Image",+ toggle=True, icon="FILE_REFRESH")if context.scene.sequential_ipadapter_regenerate:row = sub_ip_box_separate.row()- row.prop(scene, "sequential_ipadapter_regenerate_wo_controlnet", text="Generate reference without ControlNet", toggle=True, icon="HIDE_OFF")-+ row.prop(+ scene,+ "sequential_ipadapter_regenerate_wo_controlnet",+ text="Generate reference without ControlNet",+ toggle=True, icon="HIDE_OFF",+ )++ # -------------------------# Refine Mode Parameters- elif scene.generation_method == 'refine':+ # -------------------------+ elif method == 'refine':row = mode_specific_outer_box.row()row.alignment = 'CENTER'row.label(text="Refine Mode Parameters", icon='SHADERFX')++ row = mode_specific_outer_box.row()+ row.prop(scene, "denoise", text="Denoise")+row = mode_specific_outer_box.row()- row.prop(scene, "denoise", text="Denoise")+ row.prop(+ scene,+ "refine_preserve",+ text="Preserve Original Textures",+ toggle=True,+ icon="TEXTURE",+ )+row = mode_specific_outer_box.row()- row.prop(scene, "refine_preserve", text="Preserve Original Textures", toggle=True, icon="TEXTURE")- row = mode_specific_outer_box.row()- row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Refine Mode", toggle=True, icon="MODIFIER")- if scene.sequential_ipadapter:+ row.prop(+ scene,+ "sequential_ipadapter",+ text="Use IPAdapter for Refine Mode",+ toggle=True,+ icon="MODIFIER",+ )++ if scene.sequential_ipadapter:sub_ip_box_separate = mode_specific_outer_box.box()-- split = sub_ip_box_separate.split(factor=0.5)++ split = sub_ip_box_separate.split(factor=0.5)split.label(text="Mode:")- split.prop(scene, "sequential_ipadapter_mode", text="")+ split.prop(scene, "sequential_ipadapter_mode", text="")- split = sub_ip_box_separate.split(factor=0.5)+ split = sub_ip_box_separate.split(factor=0.5)if context.scene.model_architecture == 'sdxl':split.label(text="Weight Type:")split.prop(scene, "ipadapter_weight_type", text="")-+row = sub_ip_box_separate.row()row.prop(scene, "ipadapter_strength", text="Strength")if width_mode == 'narrow':@@ -860,87 +909,186 @@ class StableGenPanel(bpy.types.Panel):row.prop(scene, "ipadapter_start", text="Start")if width_mode == 'narrow':row = sub_ip_box_separate.row()- row.prop(scene, "ipadapter_end", text="End")-+ row.prop(scene, "ipadapter_end", text="End")+if context.scene.sequential_ipadapter_mode == 'first':row = sub_ip_box_separate.row()- row.prop(scene, "sequential_ipadapter_regenerate", text="Regenerate First Image", toggle=True, icon="FILE_REFRESH")+ row.prop(+ scene,+ "sequential_ipadapter_regenerate",+ text="Regenerate First Image",+ toggle=True,+ icon="FILE_REFRESH",+ )if context.scene.sequential_ipadapter_regenerate:row = sub_ip_box_separate.row()- row.prop(scene, "sequential_ipadapter_regenerate_wo_controlnet", text="Generate reference without ControlNet", toggle=True, icon="HIDE_OFF")-+ row.prop(+ scene,+ "sequential_ipadapter_regenerate_wo_controlnet",+ text="Generate reference without ControlNet",+ toggle=True,+ icon="HIDE_OFF",+ )++ # -------------------------# UV Inpainting Parameters- elif scene.generation_method == 'uv_inpaint':+ # -------------------------+ elif method == 'uv_inpaint':row = mode_specific_outer_box.row()row.alignment = 'CENTER'row.label(text="UV Inpainting Parameters", icon="IMAGE_PLANE")+row = mode_specific_outer_box.row()- row.prop(scene, "allow_modify_existing_textures", text="Allow Modifying Existing Textures", toggle=True, icon="TEXTURE")+ row.prop(+ scene,+ "allow_modify_existing_textures",+ text="Allow Modifying Existing Textures",+ toggle=True,+ icon="TEXTURE",+ )+row = mode_specific_outer_box.row()- row.prop(scene, "ask_object_prompts", text="Ask for Object Specific Prompts", toggle=True, icon="QUESTION")+ row.prop(+ scene,+ "ask_object_prompts",+ text="Ask for Object Specific Prompts",+ toggle=True,+ icon="QUESTION",+ )+ # -------------------------# Sequential Mode Parameters- elif scene.generation_method == 'sequential':+ # -------------------------+ elif method == 'sequential':row = mode_specific_outer_box.row()row.alignment = 'CENTER'row.label(text="Sequential Mode Parameters", icon="SEQUENCE")-+split = mode_specific_outer_box.split(factor=0.5)split.label(text="Custom Camera Order:")split.prop(scene, "sequential_custom_camera_order", text="")-- if not (scene.differential_diffusion and not scene.differential_noise):++ if not (scene.differential_diffusion and not scene.differential_noise):row = mode_specific_outer_box.row()- row.prop(scene, "sequential_smooth", text="Use Smooth Visibility Map", toggle=True, icon="MOD_SMOOTH")+ row.prop(+ scene,+ "sequential_smooth",+ text="Use Smooth Visibility Map",+ toggle=True,+ icon="MOD_SMOOTH",+ )if width_mode == 'narrow':row = mode_specific_outer_box.row()- row.prop(scene, "weight_exponent_mask", text="Exponent for Visibility Map", toggle=True, icon="IPO_EXPO")-+ row.prop(+ scene,+ "weight_exponent_mask",+ text="Exponent for Visibility Map",+ toggle=True,+ icon="IPO_EXPO",+ )+if not scene.sequential_smooth:row = mode_specific_outer_box.row()- row.prop(scene, "sequential_factor", text="Visibility Threshold")+ row.prop(+ scene,+ "sequential_factor",+ text="Visibility Threshold",+ )else:row = mode_specific_outer_box.row()- row.prop(scene, "sequential_factor_smooth", text="Smooth Visibility Black Point")+ row.prop(+ scene,+ "sequential_factor_smooth",+ text="Smooth Visibility Black Point",+ )if width_mode == 'narrow':row = mode_specific_outer_box.row()- row.prop(scene, "sequential_factor_smooth_2", text="Smooth Visibility White Point")-+ row.prop(+ scene,+ "sequential_factor_smooth_2",+ text="Smooth Visibility White Point",+ )+row = mode_specific_outer_box.row()- row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Sequential Mode", toggle=True, icon="MODIFIER")+ row.prop(+ scene,+ "sequential_ipadapter",+ text="Use IPAdapter for Sequential Mode",+ toggle=True,+ icon="MODIFIER",+ )if scene.sequential_ipadapter:sub_ip_seq_box = mode_specific_outer_box.box()-+split = sub_ip_seq_box.split(factor=0.5)split.label(text="Mode:")split.prop(scene, "sequential_ipadapter_mode", text="")if scene.sequential_ipadapter_mode == 'recent':- sub_ip_seq_box.prop(scene, "sequential_desaturate_factor", text="Desaturate")- sub_ip_seq_box.prop(scene, "sequential_contrast_factor", text="Reduce Contrast")+ sub_ip_seq_box.prop(+ scene, "sequential_desaturate_factor", text="Desaturate")+ sub_ip_seq_box.prop(+ scene, "sequential_contrast_factor", text="Reduce Contrast")if context.scene.model_architecture != 'qwen_image_edit':split = sub_ip_seq_box.split(factor=0.5)if context.scene.model_architecture == 'sdxl':split.label(text="Weight Type:")split.prop(scene, "ipadapter_weight_type", text="")-+row = sub_ip_seq_box.row()row.prop(scene, "ipadapter_strength", text="Strength")if width_mode == 'narrow':row = sub_ip_seq_box.row()row.prop(scene, "ipadapter_start", text="Start")- if width_mode == 'narrow':+ if width_mode == 'narrow':row = sub_ip_seq_box.row()- row.prop(scene, "ipadapter_end", text="End")-+ row.prop(scene, "ipadapter_end", text="End")+if context.scene.sequential_ipadapter_mode == 'first':row = sub_ip_seq_box.row()- row.prop(scene, "sequential_ipadapter_regenerate", text="Regenerate First Image", toggle=True, icon="FILE_REFRESH")+ row.prop(+ scene,+ "sequential_ipadapter_regenerate",+ text="Regenerate First Image",+ toggle=True,+ icon="FILE_REFRESH",+ )if context.scene.sequential_ipadapter_regenerate:row = sub_ip_seq_box.row()- row.prop(scene, "sequential_ipadapter_regenerate_wo_controlnet", text="Generate reference without ControlNet", toggle=True, icon="HIDE_OFF")-+ row.prop(+ scene,+ "sequential_ipadapter_regenerate_wo_controlnet",+ text="Generate reference without ControlNet",+ toggle=True,+ icon="HIDE_OFF",+ )++ # -------------------------+ # Shared visibility controls+ # -------------------------+ if method in {'uv_inpaint', 'sequential', 'refine'}:+ row = mode_specific_outer_box.row()+ row.prop(+ scene,+ "visibility_vignette",+ text="Feather Visibility Edges",+ icon="MATERIAL",+ )+ if scene.visibility_vignette:+ row = mode_specific_outer_box.row()+ row.prop(+ scene,+ "visibility_vignette_width",+ text="Feather Width",+ )+ row = mode_specific_outer_box.row()+ row.prop(+ scene,+ "visibility_vignette_softness",+ text="Feather Softness",+ )+# --- Tools ---layout.separator()tools_box = layout.box()@@ -972,7 +1120,14 @@ class StableGenPanel(bpy.types.Panel):row = tools_box.row()row.operator("object.stablegen_reproject", text="Reproject Textures", icon="FILE_REFRESH")- layout.separator()+ row = tools_box.row()+ row.operator("object.stablegen_mirror_reproject", text="Mirror Last Projection", icon="MOD_MIRROR")++ row = tools_box.row(align=True)+ row.label(text="Mirror Axes:")+ row.prop(scene, "stablegen_mirror_axis_x", text="X", toggle=True)+ row.prop(scene, "stablegen_mirror_axis_y", text="Y", toggle=True)+ row.prop(scene, "stablegen_mirror_axis_z", text="Z", toggle=True)class ResetQwenPrompt(bpy.types.Operator):diff --git a/stablegen/workflows.py b/stablegen/workflows.pyindex 7dacdf3..169d433 100644--- a/stablegen/workflows.py+++ b/stablegen/workflows.py@@ -9,6 +9,10 @@ import urllib.requestfrom .util.helpers import prompt_text_qwen_image_editfrom .utils import get_generation_dirs+from io import BytesIO+import numpy as np+from PIL import Image+class WorkflowManager:def __init__(self, operator):"""@@ -19,6 +23,102 @@ class WorkflowManager:"""self.operator = operator+ def _crop_and_vignette(+ self,+ img_bytes,+ border_px: int = 8,+ feather: float = 0.15,+ gamma: float = 0.7,+ ):+ """+ Crop a constant border from the image and apply an *alpha* vignette+ that fades the image out toward the edges.++ IMPORTANT:+ - RGB is NOT darkened here, only alpha is shaped.+ - This assumes the shader uses alpha to blend with the underlying+ surface (e.g. Mix using alpha as Fac).++ border_px : how many pixels to remove on each side.+ feather : fraction of min(width, height) that is used as the feather band.+ gamma : exponent applied to the feather mask (1.0 = linear).+ """++ if img_bytes is None:+ return None++ # --- Load image as RGBA without touching color ---+ buf = BytesIO(img_bytes)+ img = Image.open(buf).convert("RGBA")++ w, h = img.size+ if w <= 2 * border_px or h <= 2 * border_px:+ # Too small to crop; just return as-is+ out_buf = BytesIO()+ img.save(out_buf, format="PNG")+ return out_buf.getvalue()++ # --- Crop hard Comfy border first ---+ left = border_px+ top = border_px+ right = w - border_px+ bottom = h - border_px+ img = img.crop((left, top, right, bottom))+ w, h = img.size++ # Convert to numpy for mask math+ arr = np.asarray(img, dtype=np.float32) / 255.0 # [H, W, 4]+ rgb = arr[..., :3]+ alpha_orig = arr[..., 3]++ # If there was no alpha, assume fully opaque as starting point+ if np.all(alpha_orig == 0):+ alpha_orig = np.ones_like(alpha_orig, dtype=np.float32)++ # --- Build rectangular feather mask based on distance to nearest edge ---++ # Normalized distance (in pixels) to each edge+ yy, xx = np.mgrid[0:h, 0:w]+ dist_to_left = xx+ dist_to_right = (w - 1) - xx+ dist_to_top = yy+ dist_to_bottom = (h - 1) - yy++ dist_to_edge = np.minimum(+ np.minimum(dist_to_left, dist_to_right),+ np.minimum(dist_to_top, dist_to_bottom),+ ).astype(np.float32)++ # Feather band thickness in pixels+ # (0.0–0.5 of the smaller dimension is reasonable)+ min_dim = float(min(w, h))+ feather_px = max(1.0, feather * 0.5 * min_dim)++ # 0 at the border, 1 in the interior beyond the feather band+ mask = dist_to_edge / feather_px+ mask = np.clip(mask, 0.0, 1.0)++ # Shape the transition with gamma (only on the mask, not on RGB!)+ if gamma != 1.0:+ # stronger bias toward 1.0 in mid-range+ mask = np.clip(mask, 1e-6, 1.0)+ mask = np.power(mask, gamma)++ # Compose final alpha: original alpha * vignette mask+ alpha_new = alpha_orig * mask++ # Reassemble RGBA, leaving RGB completely unchanged+ out = np.empty_like(arr)+ out[..., :3] = rgb+ out[..., 3] = alpha_new+ out = np.clip(out * 255.0, 0, 255).astype(np.uint8)++ img_out = Image.fromarray(out, mode="RGBA")++ out_buf = BytesIO()+ img_out.save(out_buf, format="PNG")+ return out_buf.getvalue()+def _get_qwen_default_prompts(self, context, is_initial_image):"""Gets the default Qwen prompts based on the current context."""# Check if we are in a real generation context vs. just resetting a prompt@@ -793,10 +893,19 @@ class WorkflowManager:if images is None or isinstance(images, dict) and "error" in images:return {"error": "conn_failed"}- print(f"Image refined with prompt: {context.scene.refine_prompt if context.scene.refine_prompt else context.scene.comfyui_prompt}")-- # Return the refined image- return images[NODES['save_image']][0]+ print(f"Image refined with prompt: ...")++ img_bytes = images[NODES['save_image']][0]++ # Remove Comfy’s hard border and add a soft alpha vignette+ img_bytes = self._crop_and_vignette(+ img_bytes,+ border_px=8, # tweak this if your Comfy border is wider/narrower+ feather=0.08, # thicker feather band+ gamma=0.5, # stronger fade near edge+ )++ return img_bytesdef _create_img2img_base_prompt(self, context):"""Creates and configures the base prompt for img2img refinement."""