Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
feat: emission extraction, PBR bake pipeline, game-engine export, AO, custom tiling
sakalond9c2f8d728d71
diff --git a/installer.py b/installer.pyindex cc841da..909b8c5 100644--- a/installer.py+++ b/installer.py@@ -594,6 +594,16 @@ DEPENDENCIES: Dict[str, Dict[str, Any]] = {},]},+ # --- VLM Emission (Grounding DINO + SAM 2) ---+ "cn_comfyui_segment_anything": {+ "id": "cn_comfyui_segment_anything", "type": "node",+ "name": "ComfyUI Segment Anything (GroundingDINO + SAM)",+ "git_url": "https://github.com/storyicon/comfyui_segment_anything.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "comfyui_segment_anything",+ "license": "Apache 2.0", "packages": ["vlm_emission"],+ "pip_packages": ["segment_anything"],+ },}# Define what items each menu option entails by listing package tags@@ -646,6 +656,13 @@ MENU_PACKAGES: Dict[str, Dict[str, Any]] = {"description_suffix": "*Installs ComfyUI_StableDelight_ll custom node + downloads the*\n"" *Stable-X/yoso-delight-v0-4-base model (~3.3GB fp16) for specular-free albedo.*",},+ '11': {"name": "[VLM EMISSION] Grounding DINO + SAM Segmentation Node",+ "tags": ["vlm_emission"],+ "size_gb": 0.01,+ "description_suffix": "*Installs comfyui_segment_anything custom node for VLM-driven emission extraction.*\n"+ " *GroundingDINO_SwinB (~938MB) and sam_vit_h (~2.56GB) models are downloaded*\n"+ " *automatically on first use.*",+ },}# --- Helper Functions ---@@ -1050,7 +1067,7 @@ def main():while True:display_menu(comfyui_base_path)- choice = input("Enter your choice (1-9, or q to quit): ").strip().lower()+ choice = input("Enter your choice (1-11, or q to quit): ").strip().lower()if choice == 'q':print("Exiting installer.")diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex eb4c194..8fedc19 100644--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -1,7 +1,7 @@""" This script registers the addon. """import bpy # pylint: disable=import-errorfrom .stablegen import StableGenPanel, ApplyPreset, SavePreset, DeletePreset, get_preset_items, update_parameters, ResetQwenPrompt-from .render_tools import BakeTextures, AddCameras, CloneCamera, MirrorCamera, ToggleCameraLabels, SwitchMaterial, ExportOrbitGIF, CollectCameraPrompts, CameraPromptItem, CameraOrderItem, SG_UL_CameraOrderList, SyncCameraOrder, MoveCameraOrder, ApplyCameraOrderPreset+from .render_tools import BakeTextures, AddCameras, CloneCamera, MirrorCamera, ToggleCameraLabels, SwitchMaterial, ExportOrbitGIF, ExportForGameEngine, CollectCameraPrompts, CameraPromptItem, CameraOrderItem, SG_UL_CameraOrderList, SyncCameraOrder, MoveCameraOrder, ApplyCameraOrderPresetfrom .debug_tools import debug_classes as _debug_classesfrom .utils import AddHDRI, ApplyModifiers, CurvesToMeshfrom .generator import ComfyUIGenerate, Reproject, Regenerate, MirrorReproject, Trellis2Generate@@ -32,6 +32,7 @@ classes = [ToggleCameraLabels,SwitchMaterial,ExportOrbitGIF,+ ExportForGameEngine,CollectCameraPrompts,CameraPromptItem,CameraOrderItem,@@ -1947,6 +1948,16 @@ def register():default=True,update=update_parameters)+ bpy.types.Scene.bake_visibility_weights = bpy.props.BoolProperty(+ name="Bake Visibility Weights",+ description="Pre-compute per-vertex visibility weights in Python instead of "+ "using shader Raycast nodes. Makes projected textures survive "+ "object transforms (move/rotate/scale) at the cost of vertex-level "+ "weight resolution instead of per-pixel. Recommended for meshes "+ "with >500 faces",+ default=False,+ update=update_parameters+ )bpy.types.Scene.discard_factor = bpy.props.FloatProperty(name="Discard Factor",description="If the texture is facing the camera at an angle greater than this value, it will be discarded. This is useful for preventing artifacts from the very edge of the generated texture appearing when keeping high discard factor (use ~65 for best results when generating textures around an object)",@@ -2148,6 +2159,42 @@ def register():update=update_parameters,)+ bpy.types.Scene.sg_silhouette_margin = bpy.props.IntProperty(+ name="Silhouette Margin",+ description="Pixel margin around occluder silhouettes where projection is suppressed. "+ "Prevents thin outlines of foreground geometry (e.g. hands) bleeding onto "+ "surfaces behind them. 0 = disabled",+ default=3,+ min=0,+ max=20,+ update=update_parameters,+ )++ bpy.types.Scene.sg_silhouette_depth = bpy.props.FloatProperty(+ name="Silhouette Depth",+ description="Minimum depth difference (Blender units) between the vertex and an offset "+ "ray hit to consider it a silhouette edge. Raise if too much is eroded, "+ "lower if outlines remain",+ default=0.05,+ min=0.001,+ max=1.0,+ step=1,+ precision=3,+ update=update_parameters,+ )++ bpy.types.Scene.sg_silhouette_rays = bpy.props.EnumProperty(+ name="Silhouette Rays",+ description="Number of offset directions for silhouette detection. "+ "4 = cardinal only (faster), 8 = cardinal + diagonal (better coverage)",+ items=[+ ('4', "4 (Cardinal)", "Right, Left, Up, Down"),+ ('8', "8 (Cardinal + Diagonal)", "Cardinal + 4 diagonal directions"),+ ],+ default='4',+ update=update_parameters,+ )+# Refine Mode Ramp Controlsbpy.types.Scene.refine_angle_ramp_active = bpy.props.BoolProperty(name="Use Angle Ramp",@@ -3096,6 +3143,9 @@ def register():('delight', "StableDelight (Delighted)","Specular-removed image via StableDelight — preserves diffuse ""shading and texture detail, only strips highlights"),+ ('lighting', "Marigold IID-Lighting (Vibrant)",+ "Albedo from Marigold IID-Lighting — tends to produce more "+ "vibrant, saturated colours than IID-Appearance"),],default='marigold',update=update_parameters,@@ -3168,12 +3218,139 @@ def register():step=0.1,update=update_parameters)- bpy.types.Scene.pbr_map_depth = bpy.props.BoolProperty(- name="Depth / Height",- description="Extract depth map for displacement/height",+ bpy.types.Scene.pbr_map_height = bpy.props.BoolProperty(+ name="Height",+ description="Extract height/displacement map via Marigold depth estimation",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.pbr_height_scale = bpy.props.FloatProperty(+ name="Height Scale",+ description="Displacement scale for the height map. "+ "Higher values produce more pronounced surface displacement",+ default=0.1,+ min=0.001,+ max=2.0,+ step=0.01,+ precision=3,+ update=update_parameters+ )+ bpy.types.Scene.pbr_map_ao = bpy.props.BoolProperty(+ name="AO",+ description="Bake an Ambient Occlusion map from mesh geometry "+ "(uses Blender's built-in bake, no ML required)",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.pbr_ao_samples = bpy.props.IntProperty(+ name="AO Samples",+ description="Number of samples for AO baking. "+ "Higher = cleaner but slower",+ default=16,+ min=1,+ max=128,+ update=update_parameters+ )+ bpy.types.Scene.pbr_ao_distance = bpy.props.FloatProperty(+ name="AO Distance",+ description="Maximum ray distance for AO baking. "+ "0 = scene size (automatic)",+ default=0.0,+ min=0.0,+ max=100.0,+ step=0.1,+ update=update_parameters+ )+ bpy.types.Scene.pbr_map_emission = bpy.props.BoolProperty(+ name="Emission",+ description="Extract an emission map (experimental). "+ "Identifies self-illuminating regions in the generated texture",default=False,update=update_parameters)+ bpy.types.Scene.pbr_emission_method = bpy.props.EnumProperty(+ name="Emission Method",+ description="Algorithm used to detect emissive regions",+ items=[+ ('residual', "IID-Lighting Residual",+ "Run Marigold IID-Lighting and extract the residual "+ "(image − albedo × shading). Most accurate but requires "+ "an additional model pass"),+ ('hsv', "HSV Threshold",+ "Isolate pixels with high saturation + high value in HSV "+ "space. Fast, zero model cost, best for neon/sci-fi styles"),+ ('vlm_seg', "VLM Segmentation",+ "Use Grounding DINO + SAM 2 to segment objects matching "+ "emissive keywords (neon, screen, fire, LED …). Context-aware "+ "but requires GroundingDINO + SAM2 ComfyUI nodes"),+ ],+ default='residual',+ update=update_parameters+ )+ bpy.types.Scene.pbr_emission_threshold = bpy.props.FloatProperty(+ name="Emission Threshold",+ description="Minimum brightness/residual value to consider as emission. "+ "Higher = fewer false positives, lower = catches subtle glow",+ default=0.2,+ min=0.0,+ max=1.0,+ step=0.05,+ precision=2,+ update=update_parameters+ )+ bpy.types.Scene.pbr_emission_saturation_min = bpy.props.FloatProperty(+ name="Saturation Min",+ description="(HSV method) Minimum saturation for a pixel to be "+ "considered emissive. Glowing objects retain colour "+ "intensity while lit surfaces wash out",+ default=0.5,+ min=0.0,+ max=1.0,+ step=0.05,+ precision=2,+ update=update_parameters+ )+ bpy.types.Scene.pbr_emission_value_min = bpy.props.FloatProperty(+ name="Value Min",+ description="(HSV method) Minimum value/brightness for a pixel "+ "to be considered emissive",+ default=0.85,+ min=0.0,+ max=1.0,+ step=0.05,+ precision=2,+ update=update_parameters+ )+ bpy.types.Scene.pbr_emission_bloom = bpy.props.FloatProperty(+ name="Bloom Radius",+ description="(HSV method) Gaussian blur radius applied to the "+ "emission mask to simulate bloom / glow bleed. "+ "0 = sharp mask, higher = more bloom",+ default=5.0,+ min=0.0,+ max=50.0,+ step=1.0,+ precision=1,+ update=update_parameters+ )+ bpy.types.Scene.pbr_emission_keywords = bpy.props.StringProperty(+ name="Emission Keywords",+ description="(VLM Segmentation method) Comma-separated keywords "+ "for Grounding DINO to search for emissive objects",+ default="neon sign, LED, fire, candle flame, screen display, "+ "laser, hologram, glowing crystal",+ update=update_parameters+ )+ bpy.types.Scene.pbr_emission_strength = bpy.props.FloatProperty(+ name="Emission Strength",+ description="Strength of the emission channel in the Principled BSDF",+ default=5.0,+ min=0.0,+ max=100.0,+ step=0.5,+ precision=1,+ update=update_parameters+ )bpy.types.Scene.pbr_use_native_resolution = bpy.props.BoolProperty(name="Use Native Resolution",description="Process PBR maps at the image's native resolution (longest "@@ -3191,12 +3368,46 @@ def register():('off', "Off", "No tiling — process the full image in one pass"),('selective', "Selective", "Tile albedo only (StableDelight and/or ""IID albedo). Normals, roughness, metallic "- "and depth are processed normally"),- ('all', "All", "Tile every PBR model including normals and depth"),+ "and height are processed normally"),+ ('all', "All", "Tile every PBR model including normals and height"),+ ('custom', "Custom", "Choose which maps to tile individually. "+ "Models are run as efficiently as possible"),],default='selective',update=update_parameters)+ bpy.types.Scene.pbr_tile_albedo = bpy.props.BoolProperty(+ name="Tile Albedo",+ description="Tile the albedo map for higher detail",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.pbr_tile_material = bpy.props.BoolProperty(+ name="Tile Material",+ description="Tile the roughness and metallic maps (both come from "+ "the same IID-Appearance material output)",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.pbr_tile_normal = bpy.props.BoolProperty(+ name="Tile Normal",+ description="Tile the normal map for higher detail",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.pbr_tile_height = bpy.props.BoolProperty(+ name="Tile Height",+ description="Tile the height/displacement map for higher detail",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.pbr_tile_emission = bpy.props.BoolProperty(+ name="Tile Emission",+ description="Tile the IID-Lighting residual used for emission "+ "(only applies to the Residual emission method)",+ default=False,+ update=update_parameters+ )bpy.types.Scene.pbr_tile_grid = bpy.props.IntProperty(name="Tile Grid",description="N\u00d7N grid size for tiling. 2 = 4 tiles (4\u00d7 detail), "@@ -3333,6 +3544,7 @@ def unregister():del bpy.types.Scene.generation_statusdel bpy.types.Scene.generation_progressdel bpy.types.Scene.overwrite_material+ del bpy.types.Scene.bake_visibility_weightsdel bpy.types.Scene.discard_factordel bpy.types.Scene.discard_factor_generation_onlydel bpy.types.Scene.discard_factor_after_generation@@ -3358,6 +3570,9 @@ def unregister():del bpy.types.Scene.visibility_vignettedel bpy.types.Scene.visibility_vignette_widthdel bpy.types.Scene.visibility_vignette_softness+ del bpy.types.Scene.sg_silhouette_margin+ del bpy.types.Scene.sg_silhouette_depth+ del bpy.types.Scene.sg_silhouette_raysdel bpy.types.Scene.refine_edge_feather_projectiondel bpy.types.Scene.refine_edge_feather_widthdel bpy.types.Scene.refine_edge_feather_softness@@ -3421,10 +3636,17 @@ def unregister():pbr_props = ['pbr_decomposition', 'pbr_albedo_source','pbr_map_albedo', 'pbr_map_roughness', 'pbr_map_metallic',- 'pbr_map_normal', 'pbr_map_depth',+ 'pbr_map_normal', 'pbr_map_height', 'pbr_height_scale',+ 'pbr_map_ao', 'pbr_ao_samples', 'pbr_ao_distance',+ 'pbr_map_emission', 'pbr_emission_method',+ 'pbr_emission_threshold', 'pbr_emission_saturation_min',+ 'pbr_emission_value_min', 'pbr_emission_bloom',+ 'pbr_emission_keywords', 'pbr_emission_strength','pbr_normal_mode', 'pbr_normal_strength','pbr_delight_strength',- 'pbr_use_native_resolution', 'pbr_tiling', 'pbr_tile_grid', 'pbr_tile_superres',+ 'pbr_use_native_resolution', 'pbr_tiling',+ 'pbr_tile_albedo', 'pbr_tile_material', 'pbr_tile_normal', 'pbr_tile_height',+ 'pbr_tile_emission', 'pbr_tile_grid', 'pbr_tile_superres','pbr_processing_resolution', 'pbr_denoise_steps', 'pbr_ensemble_size','pbr_replace_color_with_albedo', 'pbr_auto_lighting','pbr_model_variant', # legacy, kept for compatdiff --git a/stablegen/generator.py b/stablegen/generator.pyindex b369dcc..11cfce7 100644--- a/stablegen/generator.py+++ b/stablegen/generator.py@@ -7,6 +7,7 @@ import cv2import uuidimport jsonimport urllib.request+import urllib.parseimport socketimport threadingimport requests@@ -273,9 +274,18 @@ class Reproject(bpy.types.Operator):# Check if the camera has a corresponding generated imageimage_path = get_file_path(context, "generated", camera_id=i, material_id=max_id)if not os.path.exists(image_path):- self.report({'ERROR'}, f"Camera {i} does not have a corresponding generated image.")- print(f"{image_path} does not exist")- return {'CANCELLED'}+ # Try to recover from a packed/embedded Blender image+ # (e.g. after saving and reopening the .blend file when the+ # original output directory no longer exists).+ recovered = self._recover_image_from_blend(+ image_path, to_texture, max_id)+ if not recovered:+ self.report(+ {'ERROR'},+ f"Camera {i} does not have a corresponding "+ f"generated image.")+ print(f"{image_path} does not exist")+ return {'CANCELLED'}self._original_method = context.scene.generation_methodself._original_overwrite_material = context.scene.overwrite_material@@ -293,14 +303,88 @@ class Reproject(bpy.types.Operator):# Switch to modal and wait for completionprint("Going modal")return {'RUNNING_MODAL'}-- def modal(self, context, event):- """- Handles modal events.- :param context: Blender context.- :param event: Blender event.- :return: {'PASS_THROUGH'}++ @staticmethod+ def _recover_image_from_blend(image_path, to_texture, material_id):+ """Try to recover a generated image from bpy.data.images.++ When a .blend file is saved after generation, the generated+ textures are packed/embedded as Blender image data-blocks. If+ the original output directory no longer exists (e.g. moved PC,+ temp folder cleared), we can find the image in the material's+ node tree and re-save it to the expected path.++ Returns True if the file was successfully recovered."""+ target_name = os.path.basename(image_path)++ def _try_save_image(img):+ """Attempt to write an image data-block to *image_path*."""+ os.makedirs(os.path.dirname(image_path), exist_ok=True)++ # Case 1: packed file — write raw bytes+ if img.packed_file:+ try:+ with open(image_path, 'wb') as f:+ f.write(img.packed_file.data)+ print(f"[StableGen] Recovered packed image: "+ f"{target_name}")+ return True+ except Exception as err:+ print(f"[StableGen] Packed write failed: {err}")++ # Case 2: image has a valid filepath elsewhere — copy it+ existing_path = bpy.path.abspath(img.filepath_raw)+ if existing_path and os.path.isfile(existing_path):+ try:+ import shutil+ shutil.copy2(existing_path, image_path)+ print(f"[StableGen] Copied image from "+ f"{existing_path} → {image_path}")+ return True+ except Exception as err:+ print(f"[StableGen] File copy failed: {err}")++ # Case 3: pixel data in memory — save via render+ try:+ if img.has_data or len(img.pixels) > 0:+ img.save_render(image_path)+ print(f"[StableGen] Recovered image via save_render: "+ f"{target_name}")+ return True+ except Exception:+ pass++ return False++ # Strategy 1: scan Image Texture nodes in the target materials+ # (most reliable — images are directly referenced by the object+ # being reprojected, so we won't accidentally pick up images+ # from a different model/object that share the same filename).+ for obj in to_texture:+ if not hasattr(obj, 'data') or not obj.data.materials:+ continue+ for mat in obj.data.materials:+ if not mat or not mat.use_nodes:+ continue+ for node in mat.node_tree.nodes:+ if node.type == 'TEX_IMAGE' and node.image:+ node_filename = os.path.basename(+ node.image.filepath_raw)+ if node_filename == target_name:+ if _try_save_image(node.image):+ return True++ # Strategy 2: direct name lookup in bpy.data.images (fallback)+ for img in bpy.data.images:+ if img.name == target_name or os.path.basename(+ img.filepath_raw) == target_name:+ if _try_save_image(img):+ return True++ return False++ def modal(self, context, event):if event.type == 'TIMER':running = Falseif ComfyUIGenerate._is_running:@@ -424,6 +508,12 @@ class ComfyUIGenerate(bpy.types.Operator):_current_image = 0_total_images = 0_wait_event = None+ # PBR progress (model-level steps across all cameras)+ _pbr_active = False+ _pbr_step = 0+ _pbr_total_steps = 0+ _pbr_cam = 0 # current camera index within current step+ _pbr_cam_total = 1 # total cameras in current step# Add new properties at the top of the class_object_prompts: dict = {}@@ -444,6 +534,11 @@ class ComfyUIGenerate(bpy.types.Operator):self._current_image = 0self._stage = ""self._progress = 0+ self._pbr_active = False+ self._pbr_step = 0+ self._pbr_total_steps = 0+ self._pbr_cam = 0+ self._pbr_cam_total = 1self._wait_event = threading.Event()self.workflow_manager = WorkflowManager(self)@@ -1612,8 +1707,10 @@ class ComfyUIGenerate(bpy.types.Operator):map_checks.append('metallic')if getattr(scene, 'pbr_map_normal', True):map_checks.append('normal')- if getattr(scene, 'pbr_map_depth', False):- map_checks.append('depth')+ if getattr(scene, 'pbr_map_height', False):+ map_checks.append('height')+ if getattr(scene, 'pbr_map_emission', False):+ map_checks.append('emission')if not map_checks:return None@@ -1962,10 +2059,13 @@ class ComfyUIGenerate(bpy.types.Operator):want_roughness = getattr(scene, 'pbr_map_roughness', True)want_metallic = getattr(scene, 'pbr_map_metallic', True)want_normal = getattr(scene, 'pbr_map_normal', True)- want_depth = getattr(scene, 'pbr_map_depth', False)+ want_height = getattr(scene, 'pbr_map_height', False)+ want_emission = getattr(scene, 'pbr_map_emission', False)+ emission_method = getattr(scene, 'pbr_emission_method', 'residual')albedo_source = getattr(scene, 'pbr_albedo_source', 'delight')use_delight = (want_albedo and albedo_source == 'delight')+ use_lighting_albedo = (want_albedo and albedo_source == 'lighting')# ── Determine which Marigold models to run ────────────────────need_appearance = (@@ -1974,7 +2074,12 @@ class ComfyUIGenerate(bpy.types.Operator):or want_metallic)need_normals = want_normal- need_depth = want_depth+ need_height = want_height+ # IID-Lighting is needed for 'residual' emission OR 'lighting' albedo+ need_iid_lighting = (+ (want_emission and emission_method == 'residual')+ or use_lighting_albedo+ )models_to_run = []if need_appearance:@@ -1987,17 +2092,35 @@ class ComfyUIGenerate(bpy.types.Operator):'prs-eth/marigold-normals-lcm-v0-1',['normal'],))- if need_depth:+ if need_height:models_to_run.append(('prs-eth/marigold-depth-lcm-v1-0',- ['depth'],+ ['height'],+ ))+ if need_iid_lighting:+ models_to_run.append((+ 'prs-eth/marigold-iid-lighting-v1-1',+ ['_lighting_albedo', '_lighting_shading', '_lighting_residual'],))- total_model_steps = len(models_to_run) + (1 if use_delight else 0)+ # Count extra post-processing steps (HSV / VLM emission)+ extra_emission_steps = 0+ if want_emission and emission_method in ('hsv', 'vlm_seg'):+ extra_emission_steps = 1++ total_model_steps = (len(models_to_run)+ + (1 if use_delight else 0)+ + extra_emission_steps)if total_model_steps == 0:print("[StableGen] No PBR maps enabled, skipping decomposition")return+ # Activate PBR progress tracking for the UI+ self._pbr_active = True+ self._pbr_step = 0+ self._pbr_total_steps = total_model_steps+ self._pbr_cam_total = num_cams+# Ensure every camera has an entry in _pbr_mapsfor cam_idx in cam_ids:if cam_idx not in self._pbr_maps:@@ -2008,23 +2131,75 @@ class ComfyUIGenerate(bpy.types.Operator):tile_grid = getattr(scene, 'pbr_tile_grid', 2)tile_model_keys = set()++ # Custom mode per-map toggles (read once, used later)+ custom_tile_albedo = False+ custom_tile_material = False+ custom_tile_normal = False+ custom_tile_height = False+ custom_tile_emission = False+ # Whether IID-Appearance is the albedo provider+ appearance_provides_albedo = (not use_delight+ and not use_lighting_albedo)+if tiling_mode == 'selective':- tile_model_keys = {'appearance'}+ # When using lighting albedo, don't tile appearance+ # (its albedo will be discarded — only material channels needed).+ if not use_lighting_albedo:+ tile_model_keys.add('appearance')+ if use_lighting_albedo:+ tile_model_keys.add('lighting')elif tiling_mode == 'all':- tile_model_keys = {'appearance', 'normals', 'depth'}+ tile_model_keys = {'appearance', 'normals', 'depth', 'lighting'}+ elif tiling_mode == 'custom':+ custom_tile_albedo = getattr(scene, 'pbr_tile_albedo', True)+ custom_tile_material = getattr(scene, 'pbr_tile_material', False)+ custom_tile_normal = getattr(scene, 'pbr_tile_normal', False)+ custom_tile_height = getattr(scene, 'pbr_tile_height', False)+ custom_tile_emission = (+ getattr(scene, 'pbr_tile_emission', False)+ and want_emission+ and emission_method == 'residual'+ )++ # IID-Appearance: tile if ANY of its outputs are tiled+ need_tile_appearance = (+ custom_tile_material+ or (custom_tile_albedo and appearance_provides_albedo)+ )+ if need_tile_appearance:+ tile_model_keys.add('appearance')++ # IID-Lighting: tile if albedo or residual/emission output+ # needs tiling+ need_tile_lighting = (+ (use_lighting_albedo and custom_tile_albedo)+ or custom_tile_emission+ )+ if need_tile_lighting:+ tile_model_keys.add('lighting')++ # Single-output models+ if custom_tile_normal:+ tile_model_keys.add('normals')+ if custom_tile_height:+ tile_model_keys.add('depth')model_step = 0# ── StableDelight pass (all cameras) ──────────────────────────if use_delight:model_step += 1- tile_delight = tiling_mode in ('selective', 'all')+ self._pbr_step = model_step+ tile_delight = (tiling_mode in ('selective', 'all')+ or (tiling_mode == 'custom' and custom_tile_albedo))tile_label = f" (tiled {tile_grid}×{tile_grid})" if tile_delight else ""print(f"[StableGen] Model {model_step}/{total_model_steps}: "f"StableDelight{tile_label}")for ci, cam_idx in enumerate(cam_ids):image_path = camera_images[cam_idx]+ self._pbr_cam = ciself._stage = (f"PBR: StableDelight "f"(cam {ci+1}/{num_cams})")self._progress = 0@@ -2061,9 +2236,11 @@ class ComfyUIGenerate(bpy.types.Operator):# ── Marigold model passes (all cameras per model) ─────────────for model_name, map_names in models_to_run:model_step += 1+ self._pbr_step = model_stepmodel_short = model_name.split('/')[-1]should_tile = any(k in model_short for k in tile_model_keys)is_iid = 'appearance' in model_short+ is_iid_lighting = 'lighting' in model_shorttile_label = f" (tiled {tile_grid}×{tile_grid})" if should_tile else ""print(f"[StableGen] Model {model_step}/{total_model_steps}: "@@ -2071,18 +2248,62 @@ class ComfyUIGenerate(bpy.types.Operator):for ci, cam_idx in enumerate(cam_ids):image_path = camera_images[cam_idx]+ self._pbr_cam = ciself._stage = (f"PBR: {model_short} "f"(cam {ci+1}/{num_cams})")self._progress = 0- # ── Selective IID dual-run ─────────────────────────- dual_run_iid = (- should_tile and is_iid- and tiling_mode == 'selective'- and not use_delight- )-- extra = " + untiled material" if dual_run_iid else ""+ # ── Dual-run logic ─────────────────────────────────+ # Dual-run = run tiled + untiled, then stitch outputs.+ # Needed when some outputs of a multi-output model+ # should be tiled and others should not.+ dual_run_iid = False+ dual_run_iid_reverse = False # tile material, untile albedo+ dual_run_lighting = False++ if tiling_mode == 'selective':+ dual_run_iid = (+ should_tile and is_iid and not use_delight+ )+ dual_run_lighting = (+ should_tile and is_iid_lighting+ and use_lighting_albedo+ )+ elif tiling_mode == 'custom' and should_tile:+ if is_iid:+ # IID-Appearance: [albedo, material]+ want_tiled_albedo = (custom_tile_albedo+ and appearance_provides_albedo)+ want_tiled_material = custom_tile_material+ # Dual-run only when there's a mismatch+ if want_tiled_albedo and not want_tiled_material:+ dual_run_iid = True+ elif want_tiled_material and not want_tiled_albedo:+ dual_run_iid = True+ dual_run_iid_reverse = True+ # If both tiled → full tile (no dual-run)+ # If neither → shouldn't reach here (should_tile=False)+ elif is_iid_lighting:+ # IID-Lighting: [albedo, shading, residual]+ # Determine per-output tiling needs+ want_tiled_l_albedo = (use_lighting_albedo+ and custom_tile_albedo)+ want_tiled_l_residual = custom_tile_emission+ # Shading is always untiled (no benefit).+ # Dual-run when at least one output is tiled+ # but not all (shading is never tiled, so dual-run+ # is needed whenever ANY lighting output is tiled).+ any_tiled = want_tiled_l_albedo or want_tiled_l_residual+ if any_tiled:+ dual_run_lighting = True++ extra = ""+ if dual_run_iid and not dual_run_iid_reverse:+ extra = " + untiled material"+ elif dual_run_iid and dual_run_iid_reverse:+ extra = " + untiled albedo"+ elif dual_run_lighting:+ extra = " + untiled shading"print(f" Camera {cam_idx} ({ci+1}/{num_cams}){extra}…")if dual_run_iid:@@ -2094,7 +2315,12 @@ class ComfyUIGenerate(bpy.types.Operator):and len(result_tiled) >= 2and isinstance(result_untiled, list)and len(result_untiled) >= 2):- result = [result_tiled[0], result_untiled[1]]+ if dual_run_iid_reverse:+ # Tile material, keep albedo untiled+ result = [result_untiled[0], result_tiled[1]]+ else:+ # Tile albedo, keep material untiled+ result = [result_tiled[0], result_untiled[1]]elif isinstance(result_tiled, dict):result = result_tiledelif isinstance(result_untiled, dict):@@ -2103,7 +2329,44 @@ class ComfyUIGenerate(bpy.types.Operator):result = (result_tiledif isinstance(result_tiled, list)else result_untiled)- elif should_tile and not (is_iid and use_delight):+ elif dual_run_lighting:+ # IID-Lighting: stitch per-output from tiled/untiled+ result_tiled = self._process_model_tiled(+ context, image_path, model_name)+ result_untiled = self.workflow_manager.generate_pbr_maps(+ context, image_path, model_name=model_name)+ if (isinstance(result_tiled, list)+ and len(result_tiled) >= 3+ and isinstance(result_untiled, list)+ and len(result_untiled) >= 3):+ # Per-output: pick tiled or untiled based on toggles+ if tiling_mode == 'custom':+ tile_l_albedo = (use_lighting_albedo+ and custom_tile_albedo)+ tile_l_residual = custom_tile_emission+ else:+ # selective: tile albedo only+ tile_l_albedo = True+ tile_l_residual = False+ r_albedo = (result_tiled[0] if tile_l_albedo+ else result_untiled[0])+ r_shading = result_untiled[1] # always untiled+ r_residual = (result_tiled[2] if tile_l_residual+ else result_untiled[2])+ result = [r_albedo, r_shading, r_residual]+ elif isinstance(result_tiled, dict):+ result = result_tiled+ elif isinstance(result_untiled, dict):+ result = result_untiled+ else:+ result = (result_tiled+ if isinstance(result_tiled, list)+ else result_untiled)+ elif should_tile:+ # Tile the model even when StableDelight handles albedo —+ # the IID-Appearance albedo output is discarded by+ # _save_pbr_map_outputs, but roughness/metallic still+ # benefit from tiling.result = self._process_model_tiled(context, image_path, model_name)else:@@ -2121,14 +2384,66 @@ class ComfyUIGenerate(bpy.types.Operator):context, result, map_names, cam_idx,want_roughness=want_roughness,want_metallic=want_metallic,- use_delight=use_delight)+ use_delight=use_delight,+ use_lighting_albedo=use_lighting_albedo)++ # ── Post-Marigold emission passes ─────────────────────────────+ if want_emission:+ if emission_method == 'residual':+ # IID-Lighting residual was already saved by the model+ # loop above – now gate it with roughness/metallic.+ model_step += 1+ self._pbr_step = model_step+ self._progress = 0+ print(f"[StableGen] Post-processing emission (residual "+ f"gating) – step {model_step}/{total_model_steps}")+ for ci, cam_idx in enumerate(cam_ids):+ self._pbr_cam = ci+ self._stage = (f"PBR: Emission gating "+ f"(cam {ci+1}/{num_cams})")+ self._progress = (ci / num_cams) * 100+ self._gate_emission_residual(context, cam_idx)+ self._progress = 100++ elif emission_method == 'hsv':+ model_step += 1+ self._pbr_step = model_step+ self._progress = 0+ print(f"[StableGen] Emission via HSV threshold "+ f"– step {model_step}/{total_model_steps}")+ for ci, cam_idx in enumerate(cam_ids):+ self._pbr_cam = ci+ self._stage = (f"PBR: HSV emission "+ f"(cam {ci+1}/{num_cams})")+ self._progress = (ci / num_cams) * 100+ image_path = camera_images[cam_idx]+ self._generate_emission_hsv(context, cam_idx, image_path)+ self._progress = 100++ elif emission_method == 'vlm_seg':+ model_step += 1+ self._pbr_step = model_step+ self._progress = 0+ print(f"[StableGen] Emission via VLM segmentation "+ f"– step {model_step}/{total_model_steps}")+ for ci, cam_idx in enumerate(cam_ids):+ self._pbr_cam = ci+ self._stage = (f"PBR: VLM emission "+ f"(cam {ci+1}/{num_cams})")+ image_path = camera_images[cam_idx]+ self._generate_emission_vlm(context, cam_idx, image_path)++ # Deactivate PBR progress tracking+ self._pbr_active = False+ self._pbr_step = 0+ self._pbr_total_steps = 0print(f"[StableGen] PBR decomposition complete for "f"{num_cams} camera(s)")def _save_pbr_map_outputs(self, context, result, map_names, camera_id,want_roughness=True, want_metallic=True,- use_delight=False):+ use_delight=False, use_lighting_albedo=False):"""Save the output images from a single model run to disk.Handles the IID material channel split (R=roughness, G=metallic)@@ -2182,13 +2497,46 @@ class ComfyUIGenerate(bpy.types.Operator):print(f" Failed to save metallic: {err}")continue+ # ── IID-Lighting intermediate outputs ─────────────────+ # These are prefixed with '_lighting_' to avoid toggle+ # checks. The residual is saved for later gating; albedo+ # and shading are discarded unless using lighting albedo.+ if map_name.startswith('_lighting_'):+ lighting_key = map_name # e.g. '_lighting_residual'+ lighting_path = get_file_path(+ context, "pbr", subtype=lighting_key.lstrip('_'),+ camera_id=camera_id,+ material_id=self._material_id)+ try:+ with open(lighting_path, 'wb') as f:+ f.write(map_bytes)+ self._pbr_maps[camera_id][lighting_key] = lighting_path+ print(f" Saved {lighting_key} → "+ f"{os.path.basename(lighting_path)}")++ # When using IID-Lighting as albedo source, copy the+ # lighting albedo to the main albedo slot as well.+ if map_name == '_lighting_albedo' and use_lighting_albedo:+ albedo_path = get_file_path(+ context, "pbr", subtype="albedo",+ camera_id=camera_id,+ material_id=self._material_id)+ with open(albedo_path, 'wb') as f:+ f.write(map_bytes)+ self._pbr_maps[camera_id]['albedo'] = albedo_path+ print(f" Saved albedo (IID-Lighting) → "+ f"{os.path.basename(albedo_path)}")+ except Exception as err:+ print(f" Failed to save {lighting_key}: {err}")+ continue+# Skip maps the user didn't enabletoggle_attr = f"pbr_map_{map_name}"if hasattr(scene, toggle_attr) and not getattr(scene, toggle_attr):continue- # Skip Marigold albedo when StableDelight is handling it- if map_name == 'albedo' and use_delight:+ # Skip Marigold IID-Appearance albedo when another source handles it+ if map_name == 'albedo' and (use_delight or use_lighting_albedo):continuepbr_path = get_file_path(@@ -2211,6 +2559,278 @@ class ComfyUIGenerate(bpy.types.Operator):except Exception as err:print(f" Failed to save PBR map {map_name}: {err}")+ # ── Emission extraction methods ───────────────────────────────────++ def _gate_emission_residual(self, context, camera_id):+ """Gate the IID-Lighting residual with roughness/metallic to+ produce a cleaner emission map.++ emission = residual × (1 − metallic) × roughness_mask, then+ threshold. High-metallic + low-roughness regions are likely+ specular reflections, not true emission.+ """+ scene = context.scene+ cam_maps = self._pbr_maps.get(camera_id, {})+ residual_path = cam_maps.get('_lighting_residual')+ if not residual_path or not os.path.exists(residual_path):+ print(f" Emission residual not found for camera {camera_id}")+ return++ threshold = getattr(scene, 'pbr_emission_threshold', 0.2)++ try:+ residual = np.array(Image.open(residual_path).convert('RGB')).astype(np.float32) / 255.0++ # Optionally gate with metallic if available — high metallic+ # surfaces produce strong specular that isn't true emission.+ metal_path = cam_maps.get('metallic')+ if metal_path and os.path.exists(metal_path):+ metal_img = Image.open(metal_path).convert('L')+ # Resize metallic to match residual dims (they may differ+ # when tiling/super-res settings aren't identical).+ res_h, res_w = residual.shape[:2]+ if metal_img.size != (res_w, res_h):+ metal_img = metal_img.resize(+ (res_w, res_h), Image.Resampling.BILINEAR)+ metallic = np.array(metal_img).astype(np.float32) / 255.0+ gate = (1.0 - metallic)[:, :, np.newaxis]+ residual = residual * gate++ # Apply soft threshold — pixels below the threshold are+ # smoothly faded out rather than hard-clipped.+ luminance = np.mean(residual, axis=2)+ # Smooth fade: rescale [0, threshold] → 0, [threshold, 1] → preserved+ fade = np.clip((luminance - threshold * 0.5) / max(threshold * 0.5, 1e-6),+ 0.0, 1.0)[:, :, np.newaxis]+ emission = residual * fade++ emission_img = Image.fromarray(+ np.clip(emission * 255, 0, 255).astype(np.uint8), mode='RGB')+ emission_path = get_file_path(+ context, "pbr", subtype="emission",+ camera_id=camera_id,+ material_id=self._material_id)+ emission_img.save(emission_path)+ self._pbr_maps[camera_id]['emission'] = emission_path+ print(f" Saved emission (residual gated) → "+ f"{os.path.basename(emission_path)}")+ except Exception as err:+ print(f" Failed to generate emission (residual): {err}")+ import traceback; traceback.print_exc()++ def _generate_emission_hsv(self, context, camera_id, image_path):+ """Extract emission via high-saturation + high-value thresholding+ in HSV space. Glowing objects retain colour intensity while+ normally-lit surfaces desaturate under bright light.+ """+ scene = context.scene+ sat_min = getattr(scene, 'pbr_emission_saturation_min', 0.5)+ val_min = getattr(scene, 'pbr_emission_value_min', 0.85)+ bloom_radius = getattr(scene, 'pbr_emission_bloom', 5.0)+ threshold = getattr(scene, 'pbr_emission_threshold', 0.3)++ try:+ original = np.array(Image.open(image_path).convert('RGB'))+ rgb_f = original.astype(np.float32) / 255.0++ # RGB → HSV+ maxc = rgb_f.max(axis=2)+ minc = rgb_f.min(axis=2)+ delta = maxc - minc+ saturation = np.where(maxc > 1e-6, delta / maxc, 0.0)+ value = maxc++ # Build binary mask: high saturation AND high value+ mask = ((saturation >= sat_min) & (value >= val_min)).astype(np.float32)++ # Apply bloom (Gaussian blur) to soften edges+ if bloom_radius > 0:+ try:+ import cv2+ ksize = int(bloom_radius * 4) | 1 # must be odd+ mask = cv2.GaussianBlur(mask, (ksize, ksize), bloom_radius)+ except ImportError:+ # Fallback: simple box blur via PIL+ from PIL import ImageFilter+ mask_pil = Image.fromarray(+ (mask * 255).astype(np.uint8), mode='L')+ mask_pil = mask_pil.filter(+ ImageFilter.GaussianBlur(radius=bloom_radius))+ mask = np.array(mask_pil).astype(np.float32) / 255.0++ # Apply threshold on the blurred mask+ mask = np.where(mask > threshold, mask, 0.0)++ # Multiply mask by original RGB to get coloured emission+ emission = rgb_f * mask[:, :, np.newaxis]++ emission_img = Image.fromarray(+ np.clip(emission * 255, 0, 255).astype(np.uint8), mode='RGB')+ emission_path = get_file_path(+ context, "pbr", subtype="emission",+ camera_id=camera_id,+ material_id=self._material_id)+ emission_img.save(emission_path)+ self._pbr_maps[camera_id]['emission'] = emission_path+ print(f" Saved emission (HSV threshold) → "+ f"{os.path.basename(emission_path)}")+ except Exception as err:+ print(f" Failed to generate emission (HSV): {err}")+ import traceback; traceback.print_exc()++ def _generate_emission_vlm(self, context, camera_id, image_path):+ """Extract emission via Grounding DINO + SAM 2 segmentation.++ Uses ComfyUI nodes to run Grounding DINO with emissive keywords,+ then SAM 2 to get pixel-perfect masks, and multiplies with the+ original image for a coloured emission map.+ """+ scene = context.scene+ keywords = getattr(scene, 'pbr_emission_keywords',+ 'neon sign, LED, fire, candle flame, '+ 'screen display, laser, hologram, glowing crystal')+ threshold = getattr(scene, 'pbr_emission_threshold', 0.3)++ server_address = context.preferences.addons[+ __package__].preferences.server_address++ # Check that required nodes exist+ required_nodes = [+ 'GroundingDinoModelLoader (segment anything)',+ 'GroundingDinoSAMSegment (segment anything)',+ 'SAMModelLoader (segment anything)',+ ]+ for node_class in required_nodes:+ try:+ resp = urllib.request.urlopen(+ f"http://{server_address}/object_info/{urllib.parse.quote(node_class)}",+ timeout=get_timeout('api')+ )+ data = json.loads(resp.read())+ except Exception:+ print(f" VLM emission: ComfyUI node '{node_class}' not found. "+ f"Skipping VLM emission. Install comfyui_segment_anything.")+ self._warning = (f"VLM Emission requires comfyui_segment_anything. "+ f"Node '{node_class}' not found.")+ return++ # Upload image+ from .generator import upload_image_to_comfyui+ image_info = upload_image_to_comfyui(server_address, image_path)+ if image_info is None:+ print(f" Failed to upload image for VLM emission")+ return++ uploaded_name = image_info.get("name", os.path.basename(image_path))++ # Build the ComfyUI workflow:+ # LoadImage → GroundingDINO detect → SAM segment → mask output+ prompt = {+ "1": {+ "class_type": "LoadImage",+ "inputs": {"image": uploaded_name}+ },+ "2": {+ "class_type": "GroundingDinoModelLoader (segment anything)",+ "inputs": {+ "model_name": "GroundingDINO_SwinB (938MB)"+ }+ },+ "3": {+ "class_type": "SAMModelLoader (segment anything)",+ "inputs": {+ "model_name": "sam_vit_h (2.56GB)"+ }+ },+ "4": {+ "class_type": "GroundingDinoSAMSegment (segment anything)",+ "inputs": {+ "grounding_dino_model": ["2", 0],+ "sam_model": ["3", 0],+ "image": ["1", 0],+ "prompt": keywords,+ "threshold": threshold,+ }+ },+ # SAM output 1 is MASK; convert to IMAGE for SaveImageWebsocket+ "4b": {+ "class_type": "MaskToImage",+ "inputs": {"mask": ["4", 1]}+ },+ "5": {+ "class_type": "SaveImageWebsocket",+ "inputs": {"images": ["4b", 0]}+ }+ }++ NODES = {"save_image": "5"}++ client_id = str(uuid.uuid4())+ ws = self.workflow_manager._connect_to_websocket(+ server_address, client_id)+ if ws is None:+ print(f" VLM emission: WebSocket connection failed")+ return++ try:+ images = self.workflow_manager._execute_prompt_and_get_images(+ ws, prompt, client_id, server_address, NODES+ )+ finally:+ try:+ ws.close()+ except Exception:+ pass++ if (images is None or not isinstance(images, dict)+ or "5" not in images or not images["5"]):+ print(f" VLM emission: No mask output received. "+ f"The scene may not contain recognisable emissive objects.")+ # Fall back to a black emission map+ try:+ orig = Image.open(image_path).convert('RGB')+ black = Image.new('RGB', orig.size, (0, 0, 0))+ emission_path = get_file_path(+ context, "pbr", subtype="emission",+ camera_id=camera_id,+ material_id=self._material_id)+ black.save(emission_path)+ self._pbr_maps[camera_id]['emission'] = emission_path+ print(f" Saved emission (VLM – no emissive objects) → "+ f"{os.path.basename(emission_path)}")+ except Exception:+ pass+ return++ mask_bytes = images["5"][0]+ try:+ mask = np.array(Image.open(io.BytesIO(mask_bytes)).convert('L')).astype(np.float32) / 255.0+ original = np.array(Image.open(image_path).convert('RGB')).astype(np.float32) / 255.0++ # Resize mask if dimensions differ+ if mask.shape[:2] != original.shape[:2]:+ mask_pil = Image.fromarray((mask * 255).astype(np.uint8), mode='L')+ mask_pil = mask_pil.resize(+ (original.shape[1], original.shape[0]),+ Image.Resampling.BILINEAR)+ mask = np.array(mask_pil).astype(np.float32) / 255.0++ emission = original * mask[:, :, np.newaxis]++ emission_img = Image.fromarray(+ np.clip(emission * 255, 0, 255).astype(np.uint8), mode='RGB')+ emission_path = get_file_path(+ context, "pbr", subtype="emission",+ camera_id=camera_id,+ material_id=self._material_id)+ emission_img.save(emission_path)+ self._pbr_maps[camera_id]['emission'] = emission_path+ print(f" Saved emission (VLM segmentation) → "+ f"{os.path.basename(emission_path)}")+ except Exception as err:+ print(f" Failed to generate emission (VLM): {err}")+ import traceback; traceback.print_exc()+def _apply_qwen_context_cleanup(self, context, image_bytes):hue_tolerance = max(context.scene.qwen_context_cleanup_hue_tolerance, 0.0)value_adjust = context.scene.qwen_context_cleanup_value_adjustdiff --git a/stablegen/project.py b/stablegen/project.pyindex dbeda14..b4ce530 100644--- a/stablegen/project.py+++ b/stablegen/project.py@@ -35,6 +35,245 @@ def _copy_uv_to_attribute(obj, uv_layer_name, attr_name):obj.data.update()+def _bake_visibility_weights(context, objects, cameras, mat_id, stop_index=1000000):+ """Pre-compute per-vertex, per-camera visibility weights and store them+ as ``FLOAT`` ``POINT``-domain mesh attributes.++ Attribute naming: ``_SG_VisWeight_{cam_idx}_{mat_id}``++ The computation replicates the same logic as the runtime+ ``create_native_raycast_visibility`` + ``create_native_feather`` shader+ nodes but runs once in Python so the resulting material has no world-space+ dependencies — projected textures survive object transforms.++ Uses NumPy for bulk frustum/angle/feather computation and only falls back+ to per-vertex BVH raycasting for the subset that passes initial checks.+ """+ import bmesh+ import numpy as np+ from mathutils.bvhtree import BVHTree+ from math import pow as fpow++ scene = context.scene+ angle_threshold = scene.discard_factor # degrees+ power_exponent = scene.weight_exponent+ feather_active = scene.visibility_vignette+ feather_width = scene.visibility_vignette_width if feather_active else 0.0+ feather_gamma = scene.visibility_vignette_softness if feather_active else 1.0+ feather_width = max(0.0, min(feather_width, 0.49))++ # Pre-compute camera data once -----------------------------------------------+ cam_data = []+ for camera in cameras:+ cam_loc = camera.location.copy()+ quat = camera.matrix_world.to_quaternion()+ cam_dir = quat @ Vector((0, 0, -1))+ cam_up = quat @ Vector((0, 1, 0))+ cam_right = cam_dir.cross(cam_up).normalized()+ cam_up_vec = cam_right.cross(cam_dir).normalized()++ cam_res_x, cam_res_y = _get_camera_resolution(camera, scene)+ fov = camera.data.angle_x+ if cam_res_y > cam_res_x:+ fov = 2 * atan(tan(fov / 2) * cam_res_x / cam_res_y)+ filmw = tan(fov / 2)+ aspect = cam_res_x / cam_res_y+ filmh = filmw / aspect++ cam_data.append((+ np.array(cam_loc, dtype=np.float64),+ np.array(cam_dir, dtype=np.float64),+ np.array(cam_right, dtype=np.float64),+ np.array(cam_up_vec, dtype=np.float64),+ filmw, filmh,+ cam_loc, # keep mathutils Vector for BVH calls+ ))++ # Build scene-wide BVH for occlusion (matches ShaderNodeRaycast behaviour,+ # which checks ALL visible scene geometry, not just the current object).+ scene_bm = bmesh.new()+ vert_offset = 0+ for scene_obj in context.view_layer.objects:+ if scene_obj.type != 'MESH' or scene_obj.hide_get():+ continue+ tmp = bmesh.new()+ tmp.from_mesh(scene_obj.data)+ tmp.transform(scene_obj.matrix_world)+ for v in tmp.verts:+ scene_bm.verts.new(v.co)+ scene_bm.verts.ensure_lookup_table()+ for f in tmp.faces:+ try:+ scene_bm.faces.new(+ [scene_bm.verts[v.index + vert_offset] for v in f.verts])+ except ValueError:+ pass # skip degenerate / duplicate faces+ vert_offset += len(tmp.verts)+ tmp.free()+ scene_bm.normal_update()+ scene_tree = BVHTree.FromBMesh(scene_bm)+ scene_bm.free()+ print(f"[StableGen] Scene BVH built ({vert_offset} verts across visible meshes)")++ # Per-object bake -------------------------------------------------------------+ n_cameras = len(cameras)+ for obj_idx, obj in enumerate(objects):+ bm = bmesh.new()+ bm.from_mesh(obj.data)+ bm.transform(obj.matrix_world)+ bm.normal_update()++ n_verts = len(bm.verts)+ # Build numpy arrays (Nx3) for positions and normals+ positions_np = np.array([v.co[:] for v in bm.verts], dtype=np.float64)+ normals_np = np.array([v.normal[:] for v in bm.verts], dtype=np.float64)+ bm.free()++ for cam_idx, camera in enumerate(cameras):+ print(f"[StableGen] Baking visibility: object {obj_idx+1}/{len(objects)}, "+ f"camera {cam_idx+1}/{n_cameras} ({n_verts} verts)")++ weights = np.zeros(n_verts, dtype=np.float64)++ if cam_idx > stop_index:+ # Store zeros (camera disabled) and continue+ attr_name = f"_SG_VisWeight_{cam_idx}_{mat_id}"+ existing = obj.data.attributes.get(attr_name)+ if existing:+ obj.data.attributes.remove(existing)+ attr = obj.data.attributes.new(+ name=attr_name, type='FLOAT', domain='POINT')+ attr.data.foreach_set("value", weights.tolist())+ continue++ cam_loc_np, cam_dir_np, cam_right_np, cam_up_np, filmw, filmh, cam_loc_mu = cam_data[cam_idx]++ # ── Vectorised frustum + angle pre-filter ──────────────────+ to_vert = positions_np - cam_loc_np # (N, 3)+ dists = np.linalg.norm(to_vert, axis=1) # (N,)+ valid = dists > 1e-8+ direction = np.zeros_like(to_vert)+ direction[valid] = to_vert[valid] / dists[valid, None]++ # Frustum: d_neg_fwd < 0 (vertex is in front of camera)+ d_neg_fwd = np.einsum('ij,j->i', direction, -cam_dir_np)+ valid &= d_neg_fwd < 0++ neg_cam_z = np.where(valid, -d_neg_fwd, 1.0) # avoid /0+ d_right = np.einsum('ij,j->i', direction, cam_right_np)+ d_up = np.einsum('ij,j->i', direction, cam_up_np)+ x_proj = d_right / neg_cam_z+ y_proj = d_up / neg_cam_z++ valid &= (np.abs(x_proj) < filmw) & (np.abs(y_proj) < filmh)++ # Angle threshold+ dot_dn = np.abs(np.einsum('ij,ij->i', direction, normals_np))+ dot_dn = np.clip(dot_dn, 0.0, 1.0)+ angle_deg = np.degrees(np.arccos(dot_dn))+ valid &= angle_deg < angle_threshold++ # ── BVH raycast only for candidates that passed filters ───+ candidate_indices = np.nonzero(valid)[0]+ occluded = np.zeros(n_verts, dtype=bool)+ for vi in candidate_indices:+ d_mu = Vector(direction[vi])+ hit_loc, _, _, hit_dist = scene_tree.ray_cast(+ cam_loc_mu, d_mu, float(dists[vi]) + 0.01)+ if hit_loc is not None and dists[vi] > hit_dist + 0.001:+ occluded[vi] = True++ valid &= ~occluded++ # ── Silhouette erosion ─────────────────────────────────────+ # Cast offset rays around each visible vertex. If any offset+ # ray hits an occluder significantly closer, this vertex is+ # near a depth discontinuity (e.g. hand edge on body) and its+ # weight should be zeroed so another camera fills that area.+ silhouette_margin_px = getattr(scene, 'sg_silhouette_margin', 3)+ if silhouette_margin_px > 0:+ # Angular offset per pixel (radians)+ cam_res_x_n, cam_res_y_n = _get_camera_resolution(camera, scene)+ rad_per_px = fov / max(cam_res_x_n, 1)+ offset_angle = rad_per_px * silhouette_margin_px++ visible_indices = np.nonzero(valid)[0]+ near_silhouette = np.zeros(n_verts, dtype=bool)++ # Offset directions in camera space+ offsets_right = cam_right_np * offset_angle+ offsets_up = cam_up_np * offset_angle++ use_8_rays = getattr(scene, 'sg_silhouette_rays', '4') == '8'+ if use_8_rays:+ diag = offset_angle * 0.7071067811865476 # 1/sqrt(2)+ offsets_diag_ru = cam_right_np * diag + cam_up_np * diag+ offsets_diag_rd = cam_right_np * diag - cam_up_np * diag+ all_offsets = (offsets_right, -offsets_right,+ offsets_up, -offsets_up,+ offsets_diag_ru, -offsets_diag_ru,+ offsets_diag_rd, -offsets_diag_rd)+ else:+ all_offsets = (offsets_right, -offsets_right,+ offsets_up, -offsets_up)++ for vi in visible_indices:+ d_base = direction[vi]+ dist_v = float(dists[vi])+ is_edge = False+ for off in all_offsets:+ d_off = d_base + off+ # Normalise (offset is small, so direction barely changes)+ norm = float(np.linalg.norm(d_off))+ if norm < 1e-8:+ continue+ d_off_mu = Vector(d_off / norm)+ h_loc, _, _, h_dist = scene_tree.ray_cast(+ cam_loc_mu, d_off_mu, dist_v + 0.01)+ depth_thr = getattr(scene, 'sg_silhouette_depth', 0.05)+ if h_loc is not None and dist_v > h_dist + depth_thr:+ is_edge = True+ break+ if is_edge:+ near_silhouette[vi] = True++ valid &= ~near_silhouette++ # ── Vectorised weight + feather ────────────────────────────+ w = np.power(np.maximum(dot_dn, 1e-12), power_exponent)++ if feather_width > 0:+ nx = np.abs(x_proj) / filmw+ ny = np.abs(y_proj) / filmh+ edge = np.maximum(nx, ny)+ low = 1.0 - feather_width+ need_feather = edge > low+ t = np.clip((edge - low) / feather_width, 0.0, 1.0)+ ss = t * t * (3.0 - 2.0 * t) # smoothstep+ ff = np.power(np.maximum(1.0 - ss, 0.0),+ max(feather_gamma, 0.01))+ w = np.where(need_feather, w * ff, w)++ weights[valid] = w[valid]++ # Store as FLOAT POINT-domain attribute on the *base* mesh+ attr_name = f"_SG_VisWeight_{cam_idx}_{mat_id}"+ existing = obj.data.attributes.get(attr_name)+ if existing:+ obj.data.attributes.remove(existing)+ attr = obj.data.attributes.new(+ name=attr_name, type='FLOAT', domain='POINT')+ attr.data.foreach_set("value", weights.tolist())++ # Force UI update between cameras to keep Blender responsive+ if context.window:+ context.window.cursor_set('WAIT')+ for area in context.screen.areas:+ area.tag_redraw()++ obj.data.update()++def create_native_raycast_visibility(nodes, links, camera, geometry, context, i, mat_id, stop_index):"""Creates a visibility weight node group using the native Raycast shader node (Blender 5.1+).@@ -1049,6 +1288,19 @@ def project_image(context, to_project, mat_id, stop_index=1000000):if buffer_uv:obj.data.uv_layers.remove(buffer_uv)+ # ── Optional: bake per-vertex visibility weights ──────────────────+ use_baked_weights = getattr(context.scene, 'bake_visibility_weights', False)+ if use_baked_weights:+ # Always compute weights for ALL cameras (ignore stop_index).+ #+ # Needs further testing, maybe will need to revert this.++ # In sequential mode, only bake on the first call (stop_index=0)+ # to avoid recomputing the same weights N times.+ is_sequential = context.scene.generation_method == 'sequential'+ if not is_sequential or stop_index == 0:+ _bake_visibility_weights(context, to_project, cameras, mat_id)+# Switch to Cycles (needed for Raycast shader node on all versions)context.scene.render.engine = 'CYCLES'# Force CPU + OSL only for Blender < 5.1 (native Raycast nodes don't need it)@@ -1271,7 +1523,49 @@ def project_image(context, to_project, mat_id, stop_index=1000000):# Compute the dot product of the direction vector and geometry normal- if use_native_raycast:+ if use_baked_weights:+ # ── Baked-weights path (transform-stable) ──+ # Read pre-computed per-vertex weight from mesh attribute.+ # A pass-through Math node is used so outputs[0] provides the+ # scalar float (ShaderNodeAttribute outputs[0] is Color).+ vis_attr = nodes.new("ShaderNodeAttribute")+ vis_attr.attribute_name = f"_SG_VisWeight_{i}_{mat_id}"+ vis_attr.attribute_type = 'GEOMETRY'+ vis_attr.location = (-400, (-800) * i)+ vis_attr.label = f"BakedVis-{i}-{mat_id}"++ passthrough = nodes.new("ShaderNodeMath")+ passthrough.operation = 'MULTIPLY'+ passthrough.inputs[1].default_value = 1.0+ passthrough.location = (-200, (-800) * i)+ passthrough.label = f"Angle-{i}-{mat_id}"+ links.new(vis_attr.outputs["Fac"], passthrough.inputs[0])++ scripts_to_connect = []+ final_weight_node = passthrough++ script_nodes.append(scripts_to_connect)++ if i > stop_index and not voronoi_active:+ less_than = nodes.new("ShaderNodeMath")+ less_than.operation = 'LESS_THAN'+ less_than.location = (-100, (-800) * i)+ less_than.inputs[1].default_value = -1+ links.new(passthrough.outputs[0], less_than.inputs[0])+ script_nodes_outputs.append(less_than)+ else:+ script_nodes_outputs.append(final_weight_node)++ subtract_nodes.append(None)+ normalize_nodes.append(None)+ add_camera_loc_nodes.append(None)+ length_nodes.append(None)+ camera_fov_nodes.append(None)+ camera_aspect_ratio_nodes.append(None)+ camera_direction_nodes.append(None)+ camera_up_nodes.append(None)++ elif use_native_raycast:# ── Native Raycast path (Blender 5.1+) ──result = create_native_raycast_visibility(nodes, links, camera, geometry, context, i, mat_id, stop_index@@ -1479,7 +1773,12 @@ def project_image(context, to_project, mat_id, stop_index=1000000):uv_output = "Vector" if uv_map_node.type == 'ATTRIBUTE' else "UV"links.new(uv_map_node.outputs[uv_output], tex_image.inputs["Vector"])- if not use_native_raycast:+ if use_baked_weights or use_native_raycast:+ # Baked-weights path: all links already made during creation.+ # Native raycast path: all links already made inside+ # create_native_raycast_visibility / create_native_feather.+ pass+ else:# OSL path: connect subtract, normalize, script inputs, lengthsubtract = subtract_nodes[i]normalize = normalize_nodes[i]@@ -1827,9 +2126,10 @@ def project_pbr_to_bsdf(context, to_texture, pbr_maps, material_id=None):channel_wiring['metallic'] = 'Metallic'if getattr(scene, 'pbr_map_normal', True):special_wiring['normal'] = 'normal'- if getattr(scene, 'pbr_map_depth', False):- special_wiring['depth'] = 'displacement'-+ if getattr(scene, 'pbr_map_height', False):+ special_wiring['height'] = 'displacement'+ if getattr(scene, 'pbr_map_emission', False):+ special_wiring['emission'] = 'emission'processed_materials = set()for obj in to_texture:@@ -1927,9 +2227,14 @@ def project_pbr_to_bsdf(context, to_texture, pbr_maps, material_id=None):if not pbr_img:continue- # Non-Color for data maps+ # Colorspace: roughness/metallic are always linear data.+ # Albedo from IID-Lighting is also linear; IID-Appearance+ # albedo is sRGB (Blender's default for PNG), so leave it.if channel in ('roughness', 'metallic'):pbr_img.colorspace_settings.name = 'Non-Color'+ elif (channel == 'albedo'+ and getattr(scene, 'pbr_albedo_source', 'marigold') == 'lighting'):+ pbr_img.colorspace_settings.name = 'Non-Color'pbr_tex = nodes.new("ShaderNodeTexImage")pbr_tex.image = pbr_img@@ -2098,7 +2403,8 @@ def project_pbr_to_bsdf(context, to_texture, pbr_maps, material_id=None):principled.inputs["Normal"])elif sp_type == 'displacement':- # Create Displacement node → Material Output Displacement+ # ── Displacement / Height Map ─────────────────────+ height_scale = getattr(scene, 'pbr_height_scale', 0.1)output_node = Nonefor node in nodes:if node.type == 'OUTPUT_MATERIAL':@@ -2110,12 +2416,29 @@ def project_pbr_to_bsdf(context, to_texture, pbr_maps, material_id=None):output_node.location[0] - 300,output_node.location[1] - 200)disp_node.label = "PBR Displacement"- disp_node.inputs["Scale"].default_value = 0.1+ disp_node.inputs["Scale"].default_value = height_scaledisp_node.inputs["Midlevel"].default_value = 0.5links.new(sp_output, disp_node.inputs["Height"])links.new(disp_node.outputs["Displacement"],output_node.inputs["Displacement"])+ elif sp_type == 'emission':+ # ── Emission Map ──────────────────────────────────+ emission_strength = getattr(+ scene, 'pbr_emission_strength', 5.0)+ if "Emission Color" in principled.inputs:+ links.new(sp_output,+ principled.inputs["Emission Color"])+ principled.inputs[+ "Emission Strength"].default_value = emission_strength+ elif "Emission" in principled.inputs:+ # Older Blender versions use "Emission" not "Emission Color"+ links.new(sp_output,+ principled.inputs["Emission"])+ if "Emission Strength" in principled.inputs:+ principled.inputs[+ "Emission Strength"].default_value = emission_strength+channel_idx += 1# ── Set BSDF default values ───────────────────────────────────@@ -2126,4 +2449,84 @@ def project_pbr_to_bsdf(context, to_texture, pbr_maps, material_id=None):processed_materials.add(mat.name)+ # ── AO Bake (geometry-based, per-object) ──────────────────────────+ if getattr(scene, 'pbr_map_ao', False):+ _bake_ao_for_objects(context, to_texture, scene)+++def _bake_ao_for_objects(context, to_texture, scene):+ """Add shader-based Ambient Occlusion to materials.++ Inserts a Blender ``Ambient Occlusion`` shader node into each+ material and multiplies it with the Base Color input of the+ Principled BSDF. This is evaluated at render time — zero bake+ time and works with any poly count.+ """+ ao_samples = getattr(scene, 'pbr_ao_samples', 16)+ ao_distance = getattr(scene, 'pbr_ao_distance', 0.0)++ print(f"[StableGen] Adding shader-based AO "+ f"({ao_samples} samples, distance={ao_distance})…")++ processed = set()+ for oi, obj in enumerate(to_texture):+ if not hasattr(obj, 'active_material') or not obj.active_material:+ continue+ mat = obj.active_material+ if mat.name in processed:+ continue+ if not mat.use_nodes:+ continue++ nodes = mat.node_tree.nodes+ links = mat.node_tree.links++ # Find Principled BSDF+ principled = None+ for node in nodes:+ if node.type == 'BSDF_PRINCIPLED':+ principled = node+ break+ if principled is None:+ continue++ print(f" Adding AO node to {mat.name} "+ f"({oi+1}/{len(to_texture)})…")++ # Create Ambient Occlusion shader node+ ao_node = nodes.new("ShaderNodeAmbientOcclusion")+ ao_node.samples = ao_samples+ ao_node.label = "PBR AO"+ ao_node.location = (+ principled.location[0] - 500,+ principled.location[1] + 350)+ if ao_distance > 0:+ ao_node.inputs["Distance"].default_value = ao_distance++ # Wire AO into the material:+ # Intercept Base Color → Principled BSDF with a Multiply mix.+ base_input = principled.inputs.get("Base Color")+ if base_input and base_input.links:+ old_source = base_input.links[0].from_socket++ mix_node = nodes.new("ShaderNodeMix")+ mix_node.data_type = 'RGBA'+ mix_node.blend_type = 'MULTIPLY'+ mix_node.inputs["Factor"].default_value = 1.0+ mix_node.location = (+ principled.location[0] - 200,+ principled.location[1] + 200)+ mix_node.label = "AO Multiply"++ links.new(old_source, mix_node.inputs[6]) # A (base colour)+ links.new(ao_node.outputs["AO"], mix_node.inputs[7]) # B (AO)+ links.new(mix_node.outputs[2], base_input) # Result → Base Color+ else:+ # No existing link — just plug AO colour directly+ links.new(ao_node.outputs["Color"], base_input)++ processed.add(mat.name)++ print(f"[StableGen] AO shader nodes added "+ f"({len(processed)} material(s))")diff --git a/stablegen/render_tools.py b/stablegen/render_tools.pyindex ad62633..1a39ad1 100644--- a/stablegen/render_tools.py+++ b/stablegen/render_tools.py@@ -4432,6 +4432,34 @@ def prepare_baking(context):else:bpy.context.scene.cycles.use_osl = Truebpy.context.scene.cycles.device = 'CPU'+ else:+ # Blender 5.1+: prefer GPU baking for massive speedup on high-poly.+ # Setting cycles.device = 'GPU' alone is not enough — we must also+ # set compute_device_type on Cycles preferences and ensure the GPU+ # device is enabled, otherwise Blender silently falls back to CPU.+ try:+ cycles_prefs = bpy.context.preferences.addons['cycles'].preferences+ # Probe all available backends in order of preference+ for backend in ('CUDA', 'OPTIX', 'HIP', 'ONEAPI', 'METAL'):+ try:+ cycles_prefs.compute_device_type = backend+ cycles_prefs.get_devices()+ gpu_devs = [d for d in cycles_prefs.devices+ if d.type == backend]+ if gpu_devs:+ for d in gpu_devs:+ d.use = True+ bpy.context.scene.cycles.device = 'GPU'+ print(f"[StableGen] Baking with {backend} GPU: "+ f"{', '.join(d.name for d in gpu_devs)}")+ break+ except TypeError:+ # This backend is not available on this platform+ continue+ else:+ print("[StableGen] No GPU backend found, baking on CPU")+ except Exception:+ pass # Fall back to whatever the user had# Set bake type to diffuse and contributions to color onlybpy.context.scene.cycles.bake_type = 'DIFFUSE'@@ -4443,6 +4471,13 @@ def prepare_baking(context):# Set steps to 1 for faster bakingbpy.context.scene.cycles.samples = 1+ # Minimize light bounces — not needed for EMIT or color-only DIFFUSE bakes+ bpy.context.scene.cycles.max_bounces = 0++ # Keep the BVH in memory between consecutive bakes (huge win for PBR+ # where we bake 5-7 channels of the same mesh back-to-back)+ bpy.context.scene.render.use_persistent_data = True+def unwrap(obj, method, overlap_only):"""Unwraps the UVs of the given object using the selected method.@@ -4522,6 +4557,8 @@ def unwrap(obj, method, overlap_only):bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001)elif method == 'smart':bpy.ops.uv.smart_project()+ elif method == 'cube':+ bpy.ops.uv.cube_project(cube_size=1.0)elif method == 'lightmap':bpy.ops.uv.lightmap_pack()elif method == 'pack':@@ -4602,9 +4639,24 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =links.new(before_output.outputs[0], bsdf_node.inputs[0])# Connect the BSDF node to the output nodelinks.new(bsdf_node.outputs[0], output.inputs[0])++ # Disconnect Metallic so the DIFFUSE color-only pass returns the+ # true Base Color. Principled BSDF multiplies diffuse by+ # (1 - Metallic), which would dim metallic areas incorrectly.+ for node in nodes:+ if node.type == 'BSDF_PRINCIPLED':+ met = node.inputs.get("Metallic")+ if met:+ for link in list(met.links):+ links.remove(link)+ met.default_value = 0.0+ break# Bake the texture- bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL', filepath=image.filepath, width=texture_resolution, height=texture_resolution)+ # Ensure OBJECT mode — bake fails silently in EDIT mode+ if bpy.context.mode != 'OBJECT':+ bpy.ops.object.mode_set(mode='OBJECT')+ bpy.ops.object.bake(type='DIFFUSE', width=texture_resolution, height=texture_resolution)# Save the image if requiredif not os.path.exists(output_dir):@@ -4629,19 +4681,25 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =# First append the original active materialif original_active_material:obj.data.materials.append(original_active_material)- for mat in original_materials:- if mat != original_active_material:- obj.data.materials.append(mat)+ for mat_item in original_materials:+ if mat_item != original_active_material:+ obj.data.materials.append(mat_item)++ # Remove the temporary material copy (prevent leak)+ bpy.data.materials.remove(mat)return Truedef _has_non_projection_uv(obj):+ """Return True if the object has at least one UV map that can be used+ for baking (not a StableGen projection UV or buffer)."""if not obj or obj.type != 'MESH':return Falseif not obj.data.uv_layers:return Falsefor uv in obj.data.uv_layers:- if not uv.name.startswith("ProjectionUV"):+ if (not uv.name.startswith("ProjectionUV")+ and uv.name != "_SG_ProjectionBuffer"):return Truereturn False@@ -4663,6 +4721,317 @@ def _uvs_likely_overlap(obj, uv_name=None):seen.add(key)return False++# ── PBR Channel Baking Helpers ─────────────────────────────────────────++# Standard export suffixes per PBR channel+_PBR_CHANNEL_SUFFIXES = {+ 'base_color': 'BaseColor',+ 'roughness': 'Roughness',+ 'metallic': 'Metallic',+ 'normal': 'Normal',+ 'emission': 'Emission',+ 'height': 'Height',+ 'ao': 'AO',+}+++def _find_pbr_bake_sources(mat):+ """Inspect a Principled BSDF material and return bakeable PBR channel sources.++ Returns:+ dict: ``{channel_name: output_socket}`` for each connected PBR+ channel on the material's Principled BSDF.+ """+ if not mat or not mat.use_nodes:+ return {}++ nodes = mat.node_tree.nodes+ sources = {}++ # Find Principled BSDF+ principled = None+ for node in nodes:+ if node.type == 'BSDF_PRINCIPLED':+ principled = node+ break+ if not principled:+ return {}++ # ── Base Color + AO ──────────────────────────────────────────────+ base_input = principled.inputs.get("Base Color")+ if base_input and base_input.links:+ src_node = base_input.links[0].from_node+ is_ao_mult = (+ getattr(src_node, 'label', '') == 'AO Multiply'+ or (src_node.type == 'MIX'+ and getattr(src_node, 'data_type', '') == 'RGBA'+ and getattr(src_node, 'blend_type', '') == 'MULTIPLY'))+ if is_ao_mult:+ # A input (index 6) = base colour, B input (index 7) = AO+ a_in = src_node.inputs[6]+ if a_in.links:+ sources['base_color'] = a_in.links[0].from_socket+ b_in = src_node.inputs[7]+ if b_in.links:+ sources['ao'] = b_in.links[0].from_socket+ else:+ sources['base_color'] = base_input.links[0].from_socket++ # ── Roughness ────────────────────────────────────────────────────+ ri = principled.inputs.get("Roughness")+ if ri and ri.links:+ sources['roughness'] = ri.links[0].from_socket++ # ── Metallic ─────────────────────────────────────────────────────+ mi = principled.inputs.get("Metallic")+ if mi and mi.links:+ sources['metallic'] = mi.links[0].from_socket++ # ── Normal (raw colours before Normal Map node) ──────────────────+ ni = principled.inputs.get("Normal")+ if ni and ni.links:+ n_node = ni.links[0].from_node+ if n_node.type == 'NORMAL_MAP':+ ci = n_node.inputs.get("Color")+ if ci and ci.links:+ sources['normal'] = ci.links[0].from_socket++ # ── Emission ─────────────────────────────────────────────────────+ ei = principled.inputs.get("Emission Color") or principled.inputs.get("Emission")+ if ei and ei.links:+ sources['emission'] = ei.links[0].from_socket++ # ── Height (from Displacement node → Material Output) ────────────+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ di = node.inputs.get("Displacement")+ if di and di.links:+ d_node = di.links[0].from_node+ if d_node.type == 'DISPLACEMENT':+ hi = d_node.inputs.get("Height")+ if hi and hi.links:+ sources['height'] = hi.links[0].from_socket+ break++ return sources+++def _restore_materials(obj, original_materials, original_active):+ """Restore an object's material slots back to their original state."""+ obj.data.materials.clear()+ if original_active:+ obj.data.materials.append(original_active)+ for m in original_materials:+ if m != original_active:+ obj.data.materials.append(m)+++def bake_pbr_channel(context, obj, channel_name, texture_resolution, output_dir):+ """Bake one PBR channel via the Emit technique.++ Copies the material, finds the source socket for *channel_name*,+ rewires it through an Emission shader to the Material Output, bakes+ ``EMIT``, and saves the result to ``output_dir/{obj.name}_{Suffix}.png``.++ Returns:+ File path of the baked image, or ``None`` on failure.+ """+ if not obj.data.materials or not obj.active_material:+ return None++ # ── Save state ─────────────────────────────────────────────────+ orig_vt = context.scene.view_settings.view_transform+ orig_render = obj.hide_render+ context.scene.view_settings.view_transform = 'Standard'+ obj.hide_render = False++ # ── Copy material onto the object ──────────────────────────────+ original_materials = list(obj.data.materials)+ original_active = obj.active_material+ mat_copy = original_active.copy()+ obj.data.materials.clear()+ obj.data.materials.append(mat_copy)+ mat_copy.use_nodes = True+ nodes = mat_copy.node_tree.nodes+ links = mat_copy.node_tree.links++ # ── Find source socket in the copy ─────────────────────────────+ sources = _find_pbr_bake_sources(mat_copy)+ source_socket = sources.get(channel_name)+ if source_socket is None:+ _restore_materials(obj, original_materials, original_active)+ bpy.data.materials.remove(mat_copy)+ context.scene.view_settings.view_transform = orig_vt+ obj.hide_render = orig_render+ return None++ # ── Find Output node ───────────────────────────────────────────+ output_node = None+ for n in nodes:+ if n.type == 'OUTPUT_MATERIAL':+ output_node = n+ break+ if not output_node:+ _restore_materials(obj, original_materials, original_active)+ bpy.data.materials.remove(mat_copy)+ context.scene.view_settings.view_transform = orig_vt+ obj.hide_render = orig_render+ return None++ # ── Rewire material for baking ───────────────────────────────+ # Normal channel: use Cycles' built-in NORMAL bake which automatically+ # converts to tangent space — game-engine / glTF compatible regardless+ # of the original normal mode (world, bump, tangent).+ # All other channels: rewire source → Emission → Output for EMIT bake.+ bake_type = 'EMIT'+ if channel_name == 'normal':+ # Keep the Principled BSDF wired to the Output with the Normal+ # input connected. Cycles NORMAL bake evaluates the shader's+ # final shading normal and converts it to tangent space for us.+ bake_type = 'NORMAL'+ # Ensure the normal influence is at full strength for baking+ principled = None+ for n in nodes:+ if n.type == 'BSDF_PRINCIPLED':+ principled = n+ break+ if principled and principled.inputs.get("Normal") and principled.inputs["Normal"].links:+ nmap_node = principled.inputs["Normal"].links[0].from_node+ if nmap_node.type == 'NORMAL_MAP':+ nmap_node.inputs["Strength"].default_value = 1.0+ else:+ for link in list(output_node.inputs["Surface"].links):+ links.remove(link)++ emit_node = nodes.new("ShaderNodeEmission")+ emit_node.location = (output_node.location[0] - 200,+ output_node.location[1])+ links.new(source_socket, emit_node.inputs["Color"])+ links.new(emit_node.outputs["Emission"],+ output_node.inputs["Surface"])++ # ── Bake target image ──────────────────────────────────────────+ suffix = _PBR_CHANNEL_SUFFIXES.get(channel_name, channel_name)+ img_name = f"{obj.name}_{suffix}"+ bake_img = bpy.data.images.new(name=img_name,+ width=texture_resolution,+ height=texture_resolution)++ # Non-color channels (roughness, metallic, normal, height, AO) must be+ # stored in linear / Non-Color so the round-trip is lossless:+ # Cycles linear → raw 8-bit → PNG → load as Non-Color → linear.+ # Without this, the default sRGB image applies gamma encoding on write,+ # but add_baked_material() loads them as Non-Color (no decode) →+ # values are gamma-shifted (e.g. roughness 0.22 → 0.50).+ if channel_name not in ('base_color', 'emission'):+ bake_img.colorspace_settings.name = 'Non-Color'++ tex_node = nodes.new("ShaderNodeTexImage")+ tex_node.image = bake_img+ nodes.active = tex_node++ # ── Select object + non-projection UV ──────────────────────────+ bpy.ops.object.select_all(action='DESELECT')+ context.view_layer.objects.active = obj+ obj.select_set(True)+ for uv in obj.data.uv_layers:+ if "ProjectionUV" not in uv.name and uv.name != "_SG_ProjectionBuffer":+ obj.data.uv_layers.active = uv+ break++ # ── Bake ─────────────────────────────────────────────────────+ # Ensure OBJECT mode — bake fails silently in EDIT mode+ if bpy.context.mode != 'OBJECT':+ bpy.ops.object.mode_set(mode='OBJECT')+ if bake_type == 'NORMAL':+ bpy.ops.object.bake(type='NORMAL',+ normal_space='TANGENT',+ width=texture_resolution,+ height=texture_resolution)+ else:+ bpy.ops.object.bake(type='EMIT',+ width=texture_resolution,+ height=texture_resolution)++ # ── Save ───────────────────────────────────────────────────────+ os.makedirs(output_dir, exist_ok=True)+ out_path = os.path.join(output_dir, f"{obj.name}_{suffix}.png")+ bake_img.filepath_raw = out_path+ bake_img.file_format = 'PNG'+ bake_img.save()+ print(f" Saved PBR channel: {out_path}")++ # ── Cleanup ────────────────────────────────────────────────────+ _restore_materials(obj, original_materials, original_active)+ bpy.data.materials.remove(mat_copy)+ context.scene.view_settings.view_transform = orig_vt+ obj.hide_render = orig_render+ return out_path+++def _flip_normal_green(filepath):+ """Flip the green channel of a normal map (OpenGL ↔ DirectX)."""+ if not os.path.exists(filepath):+ return+ try:+ import numpy as np+ img = bpy.data.images.load(filepath, check_existing=False)+ w, h = img.size+ px = np.array(img.pixels[:]).reshape(h, w, 4)+ px[:, :, 1] = 1.0 - px[:, :, 1]+ img.pixels = px.flatten().tolist()+ img.save()+ bpy.data.images.remove(img)+ print(f" Flipped normal green channel (DirectX): {filepath}")+ except Exception as e:+ print(f"[StableGen] Failed to flip normal green channel: {e}")+++def _pack_orm_texture(output_dir, obj_name):+ """Pack AO, Roughness, Metallic into an ORM texture.++ Channel layout: R = AO, G = Roughness, B = Metallic (Unreal / glTF).+ Requires at least Roughness and Metallic to exist.+ """+ import numpy as np++ rough_path = os.path.join(output_dir, f"{obj_name}_Roughness.png")+ metal_path = os.path.join(output_dir, f"{obj_name}_Metallic.png")+ if not os.path.exists(rough_path) or not os.path.exists(metal_path):+ return None++ rough_img = bpy.data.images.load(rough_path, check_existing=True)+ metal_img = bpy.data.images.load(metal_path, check_existing=True)+ w, h = rough_img.size++ rough_px = np.array(rough_img.pixels[:]).reshape(h, w, 4)+ metal_px = np.array(metal_img.pixels[:]).reshape(h, w, 4)++ ao_path = os.path.join(output_dir, f"{obj_name}_AO.png")+ if os.path.exists(ao_path):+ ao_img = bpy.data.images.load(ao_path, check_existing=True)+ ao_px = np.array(ao_img.pixels[:]).reshape(h, w, 4)+ ao_chan = ao_px[:, :, 0]+ else:+ ao_chan = np.ones((h, w), dtype=np.float32)++ orm = np.ones((h, w, 4), dtype=np.float32)+ orm[:, :, 0] = ao_chan+ orm[:, :, 1] = rough_px[:, :, 0]+ orm[:, :, 2] = metal_px[:, :, 0]++ orm_img = bpy.data.images.new(name=f"{obj_name}_ORM", width=w, height=h)+ orm_img.pixels = orm.flatten().tolist()++ orm_path = os.path.join(output_dir, f"{obj_name}_ORM.png")+ orm_img.filepath_raw = orm_path+ orm_img.file_format = 'PNG'+ orm_img.save()+ print(f" Packed ORM texture: {orm_path}")+ return orm_path++class BakeTextures(bpy.types.Operator):"""Bakes textures using the cycles render engine.@@ -4686,8 +5055,9 @@ class BakeTextures(bpy.types.Operator):description="Method to unwrap UVs before baking",items=[('none', 'None', 'Skip UV unwrapping'),- ('basic', 'Basic Unwrap', 'Use basic angle-based unwrapping'),- ('smart', 'Smart UV Project', 'Use Smart UV Project with default parameters'),+ ('cube', 'Cube Project', 'Fast cube projection — great for high-poly / TRELLIS meshes (handles 1M+ faces instantly)'),+ ('smart', 'Smart UV Project', 'Smart UV Project — good balance of quality and speed'),+ ('basic', 'Basic Unwrap', 'Angle-based unwrap — best quality but very slow on high-poly meshes'),('lightmap', 'Lightmap Pack', 'Use Lightmap Pack with default parameters'),('pack', 'Pack Islands', 'Use Pack Islands with default parameters')],@@ -4712,6 +5082,29 @@ class BakeTextures(bpy.types.Operator):default=False) # type: ignore+ bake_pbr: bpy.props.BoolProperty(+ name="Bake PBR Maps",+ description="Bake individual PBR channel maps (BaseColor, Roughness, Metallic, Normal, Emission, Height, AO) "+ "with standard naming for game-engine import",+ default=True+ ) # type: ignore++ export_orm: bpy.props.BoolProperty(+ name="Pack ORM Texture",+ description="Create a packed ORM texture (R=AO, G=Roughness, B=Metallic) for Unreal Engine / glTF workflows",+ default=False+ ) # type: ignore++ normal_convention: bpy.props.EnumProperty(+ name="Normal Convention",+ description="Normal map Y-axis convention",+ items=[+ ('opengl', 'OpenGL (Y+)', 'Standard OpenGL / glTF / Unity / Blender convention'),+ ('directx', 'DirectX (Y-)', 'DirectX / Unreal Engine convention (flips green channel)'),+ ],+ default='opengl'+ ) # type: ignore+_timer = None_objects = []_current_index = 0@@ -4763,6 +5156,13 @@ class BakeTextures(bpy.types.Operator):layout.prop(self, "overlap_only")layout.prop(self, "add_material")layout.prop(self, "flatten_for_refine")+ layout.separator()+ layout.label(text="PBR Export:")+ layout.prop(self, "bake_pbr")+ pbr_col = layout.column()+ pbr_col.enabled = self.bake_pbr+ pbr_col.prop(self, "export_orm")+ pbr_col.prop(self, "normal_convention")def invoke(self, context, event):"""@@ -4790,14 +5190,27 @@ class BakeTextures(bpy.types.Operator):self.original_engine = bpy.context.scene.render.engineself.original_shading = bpy.context.space_data.shading.type- # Set render engine to CYCLES+ self.original_device = bpy.context.scene.cycles.device+ self.original_samples = bpy.context.scene.cycles.samples+ self.original_max_bounces = bpy.context.scene.cycles.max_bounces+ self.original_persistent = bpy.context.scene.render.use_persistent_data+ # Save Cycles compute_device_type so we can restore after GPU bake+ try:+ self._original_compute_device_type = (+ bpy.context.preferences.addons['cycles'].preferences.compute_device_type+ )+ except Exception:+ self._original_compute_device_type = None+ # Set render engine to CYCLES (required for baking)bpy.context.scene.render.engine = 'CYCLES'- # Set viewport shading to "MATERIAL_PREVIEW"+ # Switch to Solid shading to avoid conflicts with Rendered mode+ # (Rendered viewport + bake = crash). Solid is engine-independent+ # and won't cause pink textures like Material Preview (EEVEE) does.for area in context.screen.areas:if area.type == 'VIEW_3D':for space in area.spaces:if space.type == 'VIEW_3D':- space.shading.type = 'MATERIAL'+ space.shading.type = 'SOLID'breakprepare_baking(context)@@ -4819,6 +5232,38 @@ class BakeTextures(bpy.types.Operator):area.tag_redraw()redraw()+ # ── PBR channel bake (flat queue, one item per tick) ──────+ if self._phase == 'bake_pbr':+ if self._pbr_queue_idx < len(self._pbr_queue):+ obj, channel = self._pbr_queue[self._pbr_queue_idx]+ nice = _PBR_CHANNEL_SUFFIXES.get(channel, channel)+ self._stage = f"PBR {nice} — {obj.name}"+ self._progress = (self._pbr_queue_idx / len(self._pbr_queue)) * 100+ redraw()+ bake_pbr_channel(+ context, obj, channel,+ self.texture_resolution,+ get_dir_path(context, "baked"))+ self._pbr_queue_idx += 1+ else:+ # DirectX normal flip+ if self.normal_convention == 'directx':+ out_dir = get_dir_path(context, "baked")+ for obj in self._objects:+ _flip_normal_green(+ os.path.join(out_dir,+ f"{obj.name}_Normal.png"))+ # Pack ORM+ if self.export_orm:+ self.report({'INFO'}, "Packing ORM textures...")+ self._phase = 'pack_orm'+ self._current_index = 0+ else:+ self.report({'INFO'}, "Applying materials...")+ self._phase = 'apply_material'+ self._current_index = 0+ return {'PASS_THROUGH'}+if self._current_index < len(self._objects):obj = self._objects[self._current_index]if self._phase == 'unwrap':@@ -4828,33 +5273,46 @@ class BakeTextures(bpy.types.Operator):if self.try_unwrap != 'none':if not _has_non_projection_uv(obj):+ # No usable UV exists — must unwrapunwrap(obj, self.try_unwrap, self.overlap_only)+ elif self.overlap_only:+ # Only re-unwrap if existing UVs overlap+ if _uvs_likely_overlap(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+ # Always re-unwrap when overlap_only is disabled+ unwrap(obj, self.try_unwrap, self.overlap_only)self._progress = 100elif self._phase == 'bake':- self._stage = f"Baking {obj.name}"+ if self.bake_pbr:+ # PBR mode bakes BaseColor via EMIT — skip the+ # redundant DIFFUSE bake entirely.+ self._progress = 100+ else:+ self._stage = f"Baking {obj.name}"+ self._progress = 0+ redraw()+ if not bake_texture(context, obj, self.texture_resolution, output_dir=get_dir_path(context, "baked")):+ 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 = 100+ elif self._phase == 'pack_orm':+ self._stage = f"Packing ORM — {obj.name}"self._progress = 0redraw()- if not bake_texture(context, obj, self.texture_resolution, output_dir=get_dir_path(context, "baked")):- 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}")-+ _pack_orm_texture(get_dir_path(context, "baked"), obj.name)self._progress = 100elif self._phase == 'apply_material' and self.add_material:self._stage = f"Applying Material to {obj.name}"@@ -4871,13 +5329,44 @@ class BakeTextures(bpy.types.Operator):self._phase = 'bake'self._current_index = 0elif self._phase == 'bake':+ if self.bake_pbr:+ self.report({'INFO'}, "Baking PBR channels...")+ self._phase = 'bake_pbr'+ self._pbr_queue = []+ for obj in self._objects:+ if obj.active_material:+ for ch in _find_pbr_bake_sources(obj.active_material):+ self._pbr_queue.append((obj, ch))+ self._pbr_queue_idx = 0+ if not self._pbr_queue:+ # No PBR sources — skip straight to apply+ self.report({'INFO'}, "No PBR channels found, skipping PBR bake...")+ self._phase = 'apply_material'+ self._current_index = 0+ else:+ self.report({'INFO'}, "Applying materials...")+ self._phase = 'apply_material'+ self._current_index = 0+ elif self._phase == 'pack_orm':self.report({'INFO'}, "Applying materials...")self._phase = 'apply_material'self._current_index = 0else:context.window_manager.event_timer_remove(self._timer)bpy.context.scene.render.engine = self.original_engine- # Restore original shading type+ bpy.context.scene.cycles.device = self.original_device+ bpy.context.scene.cycles.samples = self.original_samples+ bpy.context.scene.cycles.max_bounces = self.original_max_bounces+ bpy.context.scene.render.use_persistent_data = self.original_persistent+ # Restore Cycles compute_device_type+ if self._original_compute_device_type is not None:+ try:+ bpy.context.preferences.addons['cycles'].preferences.compute_device_type = (+ self._original_compute_device_type+ )+ except Exception:+ pass+ # Restore original viewport shadingfor area in context.screen.areas:if area.type == 'VIEW_3D':for space in area.spaces:@@ -4890,63 +5379,196 @@ class BakeTextures(bpy.types.Operator):return {'PASS_THROUGH'}def add_baked_material(self, context, obj):+ """Create a baked material with standard PBR textures (game-engine ready).++ When ``bake_pbr`` is enabled, looks for ``{obj.name}_{Channel}.png``+ files in the baked output directory and wires them to a Principled+ BSDF. Falls back to the single-texture path when PBR maps are absent.+ """+ output_dir = get_dir_path(context, "baked")+mat = bpy.data.materials.new(name=f"{obj.name}_baked")obj.data.materials.append(mat)-mat.use_nodes = Truenodes = mat.node_tree.nodeslinks = mat.node_tree.links- # Remove all existing nodesfor node in nodes:nodes.remove(node)- # Switch the active material to the new material (Switch to edit mode, select all, assign the material)+ # Assign the new material to all facesobj.active_material_index = len(obj.material_slots) - 1bpy.context.view_layer.objects.active = objbpy.ops.object.mode_set(mode='EDIT')bpy.ops.mesh.select_all(action='SELECT')bpy.ops.object.material_slot_assign()bpy.ops.object.mode_set(mode='OBJECT')-- # Add output node- output_node = nodes.new("ShaderNodeOutputMaterial")- output_node.location = (600, 0)-- # Add principled shader node- principled_node = nodes.new("ShaderNodeBsdfPrincipled")- principled_node.location = (400, 0)- principled_node.inputs["Roughness"].default_value = 1.0-- # Add uv map node- uv_map_node = nodes.new("ShaderNodeUVMap")- # If there is "BakeUV" uv map, use it+ # Output node+ output_node = nodes.new("ShaderNodeOutputMaterial")+ output_node.location = (800, 0)++ # Principled BSDF+ principled = nodes.new("ShaderNodeBsdfPrincipled")+ principled.location = (400, 0)+ # Fallback values when PBR textures are absent:+ # max roughness + zero metallic → matte, non-reflective surface.+ principled.inputs["Roughness"].default_value = 1.0+ principled.inputs["Metallic"].default_value = 0.0++ # UV Map+ uv_node = nodes.new("ShaderNodeUVMap")if "BakeUV" in [uv.name for uv in obj.data.uv_layers]:- uv_map_node.uv_map = "BakeUV"+ uv_node.uv_map = "BakeUV"else:- uv_map_node.uv_map = obj.data.uv_layers[0].name- uv_map_node.location = (-200, 0)+ uv_node.uv_map = obj.data.uv_layers[0].name+ uv_node.location = (-600, 0)++ # ── Base Color ────────────────────────────────────────────────+ base_path = os.path.join(output_dir, f"{obj.name}_BaseColor.png")+ if not os.path.exists(base_path):+ # Fallback to standard diffuse bake+ base_path = get_file_path(context, "baked", object_name=obj.name)++ has_base = os.path.exists(base_path)+ if has_base:+ tex_base = nodes.new("ShaderNodeTexImage")+ tex_base.image = bpy.data.images.load(base_path)+ tex_base.location = (-200, 200)+ tex_base.label = "BaseColor"+ links.new(uv_node.outputs["UV"], tex_base.inputs["Vector"])++ if context.scene.apply_bsdf or self.bake_pbr:+ links.new(tex_base.outputs["Color"],+ principled.inputs["Base Color"])+ links.new(principled.outputs[0],+ output_node.inputs["Surface"])+ else:+ links.new(tex_base.outputs["Color"],+ output_node.inputs["Surface"])+ return+ else:+ links.new(principled.outputs[0],+ output_node.inputs["Surface"])- mat.use_nodes = True- nodes = mat.node_tree.nodes- links = mat.node_tree.links+ if not self.bake_pbr:+ return++ # ── PBR channel textures ──────────────────────────────────────+ y_pos = -100++ # Roughness+ rough_path = os.path.join(output_dir, f"{obj.name}_Roughness.png")+ if os.path.exists(rough_path):+ y_pos -= 250+ tex = nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(rough_path)+ tex.image.colorspace_settings.name = 'Non-Color'+ tex.location = (-200, y_pos)+ tex.label = "Roughness"+ links.new(uv_node.outputs["UV"], tex.inputs["Vector"])+ links.new(tex.outputs["Color"],+ principled.inputs["Roughness"])++ # Metallic+ metal_path = os.path.join(output_dir, f"{obj.name}_Metallic.png")+ if os.path.exists(metal_path):+ y_pos -= 250+ tex = nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(metal_path)+ tex.image.colorspace_settings.name = 'Non-Color'+ tex.location = (-200, y_pos)+ tex.label = "Metallic"+ links.new(uv_node.outputs["UV"], tex.inputs["Vector"])+ links.new(tex.outputs["Color"],+ principled.inputs["Metallic"])++ # Normal+ normal_path = os.path.join(output_dir, f"{obj.name}_Normal.png")+ if os.path.exists(normal_path):+ y_pos -= 250+ tex = nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(normal_path)+ tex.image.colorspace_settings.name = 'Non-Color'+ tex.location = (-200, y_pos)+ tex.label = "Normal"+ links.new(uv_node.outputs["UV"], tex.inputs["Vector"])+ nmap = nodes.new("ShaderNodeNormalMap")+ nmap.location = (100, y_pos)+ nmap.label = "Normal Map"+ # The normal bake uses Cycles NORMAL pass with tangent space,+ # so the texture is always tangent-space regardless of the+ # original projection material's normal mode (world/bump/tangent).+ nmap.space = 'TANGENT'++ links.new(tex.outputs["Color"], nmap.inputs["Color"])+ if "Normal" in principled.inputs:+ links.new(nmap.outputs["Normal"],+ principled.inputs["Normal"])++ # Emission+ emission_path = os.path.join(output_dir,+ f"{obj.name}_Emission.png")+ if os.path.exists(emission_path):+ y_pos -= 250+ tex = nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(emission_path)+ tex.location = (-200, y_pos)+ tex.label = "Emission"+ links.new(uv_node.outputs["UV"], tex.inputs["Vector"])+ em_in = (principled.inputs.get("Emission Color")+ or principled.inputs.get("Emission"))+ if em_in:+ links.new(tex.outputs["Color"], em_in)+ if "Emission Strength" in principled.inputs:+ principled.inputs[+ "Emission Strength"].default_value = 1.0++ # Height → Displacement+ height_path = os.path.join(output_dir,+ f"{obj.name}_Height.png")+ if os.path.exists(height_path):+ y_pos -= 250+ tex = nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(height_path)+ tex.image.colorspace_settings.name = 'Non-Color'+ tex.location = (-200, y_pos)+ tex.label = "Height"+ links.new(uv_node.outputs["UV"], tex.inputs["Vector"])+ disp = nodes.new("ShaderNodeDisplacement")+ disp.location = (600, -300)+ disp.label = "Displacement"+ disp.inputs["Scale"].default_value = 0.1+ disp.inputs["Midlevel"].default_value = 0.5+ links.new(tex.outputs["Color"], disp.inputs["Height"])+ links.new(disp.outputs["Displacement"],+ output_node.inputs["Displacement"])++ # AO → multiply with Base Color+ ao_path = os.path.join(output_dir, f"{obj.name}_AO.png")+ if (os.path.exists(ao_path)+ and principled.inputs["Base Color"].links):+ y_pos -= 250+ tex_ao = nodes.new("ShaderNodeTexImage")+ tex_ao.image = bpy.data.images.load(ao_path)+ tex_ao.image.colorspace_settings.name = 'Non-Color'+ tex_ao.location = (-200, y_pos)+ tex_ao.label = "AO"+ links.new(uv_node.outputs["UV"], tex_ao.inputs["Vector"])+ # Intercept Base Color → Principled with a Multiply+ old_src = principled.inputs[+ "Base Color"].links[0].from_socket+ mix = nodes.new("ShaderNodeMix")+ mix.data_type = 'RGBA'+ mix.blend_type = 'MULTIPLY'+ mix.inputs["Factor"].default_value = 1.0+ mix.location = (200, 150)+ mix.label = "AO Multiply"+ links.new(old_src, mix.inputs[6]) # A+ links.new(tex_ao.outputs["Color"], mix.inputs[7]) # B+ links.new(mix.outputs[2],+ principled.inputs["Base Color"])- # Add image texture node- tex_image = nodes.new("ShaderNodeTexImage")- # Load the saved image- tex_image.image = bpy.data.images.load(get_file_path(context, "baked", object_name=obj.name))- tex_image.location = (0, 0)- # Connect nodes- links.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])-- if context.scene.apply_bsdf:- links.new(tex_image.outputs["Color"], principled_node.inputs["Base Color"])- 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"""bl_idname = "object.export_orbit_gif"@@ -5030,6 +5652,9 @@ class ExportOrbitGIF(bpy.types.Operator):items=[('FIXED', "Fixed","Camera orbits, HDRI stays fixed — reflections shift naturally"),+ ('LOCKED', "Locked",+ "HDRI co-rotates with the camera — lighting stays identical "+ "from every angle (consistent showcase)"),('COUNTER', "Counter-Rotate","HDRI rotates opposite to camera — 2× apparent light change"),('ENV_ONLY', "Environment Only",@@ -5339,6 +5964,9 @@ class ExportOrbitGIF(bpy.types.Operator):# For env-only: rotate in positive directionif self.env_mode == 'COUNTER':end_z = start_z - math.radians(360)+ elif self.env_mode == 'LOCKED':+ # Co-rotate: same direction as camera orbit (+Z)+ end_z = start_z + math.radians(360)else:end_z = start_z + math.radians(360)@@ -5421,8 +6049,8 @@ class ExportOrbitGIF(bpy.types.Operator):# The preference alone doesn't always take effect on Blender 5.x.self._force_fcurve_interpolation(self._temp_empty, self.interpolation)- # Animate HDRI environment rotation (counter-rotate or env-only)- if self.use_hdri and self.env_mode in ('COUNTER', 'ENV_ONLY'):+ # Animate HDRI environment rotation (locked, counter-rotate, or env-only)+ if self.use_hdri and self.env_mode in ('LOCKED', 'COUNTER', 'ENV_ONLY'):self._animate_hdri_rotation(context, total_frames)@@ -5848,4 +6476,154 @@ class ExportOrbitGIF(bpy.types.Operator):self.report({'ERROR'}, f"Failed during output file creation process: {e}")import tracebacktraceback.print_exc()- return False\ No newline at end of file+ return False+++class ExportForGameEngine(bpy.types.Operator):+ """Export textured objects for game engines with PBR textures.++ Wraps Blender's glTF / FBX exporters with game-engine-optimal settings+ and auto-saves to the StableGen output directory."""+ bl_idname = "object.export_game_engine"+ bl_label = "Export for Game Engine"+ bl_options = {'REGISTER'}++ export_format: bpy.props.EnumProperty(+ name="Format",+ description="Export file format",+ items=[+ ('GLB', 'glTF Binary (.glb)',+ 'Single-file binary glTF — best for web, Unity, Godot'),+ ('GLTF_SEPARATE', 'glTF + Textures (.gltf)',+ 'Separate .gltf, .bin and texture files'),+ ('FBX', 'FBX (.fbx)',+ 'Autodesk FBX with embedded textures — Unreal Engine'),+ ],+ default='GLB'+ ) # type: ignore++ export_scope: bpy.props.EnumProperty(+ name="Objects",+ description="Which objects to export",+ items=[+ ('SELECTED', 'Selected', 'Export selected mesh objects'),+ ('ALL_MESH', 'All Mesh', 'Export all visible mesh objects'),+ ],+ default='SELECTED'+ ) # type: ignore++ apply_transforms: bpy.props.BoolProperty(+ name="Apply Transforms",+ description="Apply location, rotation and scale before export",+ default=True+ ) # type: ignore++ export_animations: bpy.props.BoolProperty(+ name="Export Animations",+ description="Include animations in the export",+ default=False+ ) # type: ignore++ @classmethod+ def poll(cls, context):+ addon_prefs = context.preferences.addons[__package__].preferences+ return os.path.exists(addon_prefs.output_dir)++ def draw(self, context):+ layout = self.layout+ layout.prop(self, "export_format")+ layout.prop(self, "export_scope")+ layout.prop(self, "apply_transforms")+ layout.prop(self, "export_animations")++ def invoke(self, context, event):+ return context.window_manager.invoke_props_dialog(self)++ def execute(self, context):+ # ── Prepare selection ─────────────────────────────────────────+ original_selection = list(context.selected_objects)+ original_active = context.view_layer.objects.active++ if self.export_scope == 'ALL_MESH':+ bpy.ops.object.select_all(action='DESELECT')+ meshes = [o for o in context.view_layer.objects+ if o.type == 'MESH' and not o.hide_get()]+ for o in meshes:+ o.select_set(True)+ if meshes:+ context.view_layer.objects.active = meshes[0]+ else:+ meshes = [o for o in context.selected_objects+ if o.type == 'MESH']+ if not meshes:+ self.report({'ERROR'}, "No mesh objects selected.")+ return {'CANCELLED'}++ # ── Output path ───────────────────────────────────────────────+ output_base = get_dir_path(context, "baked")+ os.makedirs(output_base, exist_ok=True)++ # Build filename from first object name+ base_name = meshes[0].name if meshes else "export"++ if self.export_format == 'FBX':+ ext = ".fbx"+ elif self.export_format == 'GLTF_SEPARATE':+ ext = ".gltf"+ else:+ ext = ".glb"+ filepath = os.path.join(output_base, f"{base_name}{ext}")++ # ── Apply transforms if requested ─────────────────────────────+ if self.apply_transforms:+ for o in meshes:+ o.select_set(True)+ bpy.ops.object.transform_apply(+ location=True, rotation=True, scale=True)++ # ── Export ────────────────────────────────────────────────────+ try:+ if self.export_format in ('GLB', 'GLTF_SEPARATE'):+ bpy.ops.export_scene.gltf(+ filepath=filepath,+ export_format=self.export_format,+ use_selection=True,+ export_materials='EXPORT',+ export_image_format='AUTO',+ export_tangents=True,+ export_yup=True,+ export_apply=False,+ export_animations=self.export_animations,+ )+ else: # FBX+ bpy.ops.export_scene.fbx(+ filepath=filepath,+ use_selection=True,+ apply_scale_options='FBX_SCALE_ALL',+ path_mode='COPY',+ embed_textures=True,+ bake_anim=self.export_animations,+ mesh_smooth_type='FACE',+ )++ self.report({'INFO'},+ f"Exported to {filepath}")+ except Exception as e:+ self.report({'ERROR'}, f"Export failed: {e}")+ import traceback+ traceback.print_exc()++ # ── Restore selection ─────────────────────────────────────────+ bpy.ops.object.select_all(action='DESELECT')+ for o in original_selection:+ try:+ o.select_set(True)+ except ReferenceError:+ pass+ if original_active:+ try:+ context.view_layer.objects.active = original_active+ except ReferenceError:+ pass++ return {'FINISHED'}\ No newline at end of filediff --git a/stablegen/stablegen.py b/stablegen/stablegen.pyindex 77362a7..d51e3b2 100644--- a/stablegen/stablegen.py+++ b/stablegen/stablegen.py@@ -121,6 +121,9 @@ GEN_PARAMETERS = ["visibility_vignette_width","visibility_vignette_softness","visibility_vignette_blur",+ "sg_silhouette_margin",+ "sg_silhouette_depth",+ "sg_silhouette_rays","refine_feather_ramp_pos_0","refine_feather_ramp_pos_1","refine_edge_feather_projection",@@ -493,25 +496,51 @@ class StableGenPanel(bpy.types.Panel):operator_instance = next((op for win in context.window_manager.windows for op in win.modal_operators if op.bl_idname == 'OBJECT_OT_test_stable'), None)if operator_instance:progress_col = layout.column()- progress_text = f"{getattr(operator_instance, '_stage', 'Generating')} ({getattr(operator_instance, '_progress', 0):.0f}%)"- progress_factor = getattr(operator_instance, '_progress', 0) / 100.0- progress_col.progress(text=progress_text, factor=max(0.0, min(progress_factor, 1.0))) # Ensure factor is <= 1.0 (logic maintained)-- total_images = getattr(operator_instance, '_total_images', 0)- if total_images > 1:- current_image_idx = getattr(operator_instance, '_current_image', 0)- current_image_decimal_progress = max(0.0, min(progress_factor, 1.0))-- # Ensure total_images is not zero to prevent division by zero- overall_progress_factor = (current_image_idx + current_image_decimal_progress) / total_images if total_images > 0 else 0- overall_progress_factor_clamped = max(0.0, min(overall_progress_factor, 1.0))-- current_img = min(current_image_idx + 1, total_images) # Clamp to total_images-+ raw_progress = getattr(operator_instance, '_progress', 0) / 100.0+ pbr_active = getattr(operator_instance, '_pbr_active', False)++ if pbr_active:+ # During PBR: top bar shows camera progress within+ # the current model step (no raw ComfyUI jitter).+ pbr_step = getattr(operator_instance, '_pbr_step', 0)+ pbr_total = max(getattr(operator_instance, '_pbr_total_steps', 1), 1)+ pbr_cam = getattr(operator_instance, '_pbr_cam', 0)+ pbr_cam_total = max(getattr(operator_instance, '_pbr_cam_total', 1), 1)++ # Top bar: camera X out of N within this step+ cam_frac = pbr_cam / pbr_cam_total+ stage_text = getattr(operator_instance, '_stage', 'PBR Decomposition')progress_col.progress(- text=f"Overall: Image {current_img}/{total_images}",- factor=overall_progress_factor_clamped # Ensure factor is <= 1.0 (logic maintained)+ text=stage_text,+ factor=max(0.0, min(cam_frac, 1.0)))+ # Bottom bar: overall PBR progress+ pbr_factor = max(0.0, min(+ ((pbr_step - 1) + cam_frac) / pbr_total, 1.0))+ progress_col.progress(+ text=f"PBR: Step {pbr_step}/{pbr_total}",+ factor=pbr_factor+ )+ else:+ # Normal generation progress+ progress_text = f"{getattr(operator_instance, '_stage', 'Generating')} ({getattr(operator_instance, '_progress', 0):.0f}%)"+ progress_col.progress(text=progress_text, factor=max(0.0, min(raw_progress, 1.0)))++ total_images = getattr(operator_instance, '_total_images', 0)+ if total_images > 1:+ current_image_idx = getattr(operator_instance, '_current_image', 0)+ current_image_decimal_progress = max(0.0, min(raw_progress, 1.0))++ # Ensure total_images is not zero to prevent division by zero+ overall_progress_factor = (current_image_idx + current_image_decimal_progress) / total_images if total_images > 0 else 0+ overall_progress_factor_clamped = max(0.0, min(overall_progress_factor, 1.0))++ current_img = min(current_image_idx + 1, total_images) # Clamp to total_images++ progress_col.progress(+ text=f"Overall: Image {current_img}/{total_images}",+ factor=overall_progress_factor_clamped # Ensure factor is <= 1.0 (logic maintained)+ )elif context.scene.generation_status == 'waiting':action_row.operator("object.test_stable", text="Waiting for Cancellation", icon="TIME")@@ -543,6 +572,11 @@ class StableGenPanel(bpy.types.Panel):factor=overall_bake_progress if overall_bake_progress <=1.0 else 1.0 # Ensure factor is <= 1.0)+ export_row = layout.row()+ export_row.operator("object.export_game_engine",+ text="Export for Game Engine",+ icon="EXPORT")+# --- Preset Management ---preset_box = layout.box()row = preset_box.row(align=True)@@ -1016,7 +1050,18 @@ 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, "bake_visibility_weights", text="Bake Visibility (Transform-Stable)", toggle=True, icon="MESH_DATA")++ row = content_box.row()+ row.prop(scene, "sg_silhouette_margin", text="Silhouette Margin (px)")++ row = content_box.row()+ row.prop(scene, "sg_silhouette_depth", text="Silhouette Depth Threshold")++ row = content_box.row()+ row.prop(scene, "sg_silhouette_rays", text="Silhouette Rays")# --- Output & Material Settings ---if _show_diffusion_sections:@@ -1057,13 +1102,38 @@ class StableGenPanel(bpy.types.Panel):grid.prop(scene, "pbr_map_roughness", toggle=True, icon="MATFLUID")grid.prop(scene, "pbr_map_metallic", toggle=True, icon="META_BALL")grid.prop(scene, "pbr_map_normal", toggle=True, icon="NORMALS_FACE")- grid.prop(scene, "pbr_map_depth", toggle=True, icon="MOD_DISPLACE")+ grid.prop(scene, "pbr_map_height", toggle=True, icon="MOD_DISPLACE")+ grid.prop(scene, "pbr_map_ao", toggle=True, icon="SHADING_RENDERED")+ grid.prop(scene, "pbr_map_emission", toggle=True, icon="LIGHT_POINT")# ── Per-map adjustment controls ──if scene.pbr_map_normal:adj_row = sub.row()adj_row.prop(scene, "pbr_normal_mode", text="Normal Mode")adj_row = sub.row()adj_row.prop(scene, "pbr_normal_strength", text="Normal Strength", slider=True)+ if scene.pbr_map_height:+ adj_row = sub.row()+ adj_row.prop(scene, "pbr_height_scale", text="Height Scale", slider=True)+ if scene.pbr_map_ao:+ ao_row = sub.row(align=True)+ ao_row.prop(scene, "pbr_ao_samples", text="AO Samples")+ ao_row.prop(scene, "pbr_ao_distance", text="AO Distance")+ if scene.pbr_map_emission:+ adj_row = sub.row()+ adj_row.prop(scene, "pbr_emission_method", text="Method")+ adj_row = sub.row()+ adj_row.prop(scene, "pbr_emission_threshold", text="Threshold", slider=True)+ adj_row = sub.row()+ adj_row.prop(scene, "pbr_emission_strength", text="Emission Strength", slider=True)+ if scene.pbr_emission_method == 'hsv':+ hsv_row = sub.row(align=True)+ hsv_row.prop(scene, "pbr_emission_saturation_min", text="Sat Min", slider=True)+ hsv_row.prop(scene, "pbr_emission_value_min", text="Val Min", slider=True)+ hsv_row = sub.row()+ hsv_row.prop(scene, "pbr_emission_bloom", text="Bloom Radius", slider=True)+ elif scene.pbr_emission_method == 'vlm_seg':+ kw_row = sub.row()+ kw_row.prop(scene, "pbr_emission_keywords", text="Keywords")# ── Albedo source selector (only when albedo enabled) ──if scene.pbr_map_albedo:sub.separator()@@ -1081,6 +1151,13 @@ class StableGenPanel(bpy.types.Panel):row = sub.row(align=True)row.prop(scene, "pbr_tile_grid", text="Tile Grid (N×N)")row.prop(scene, "pbr_tile_superres", text="Super Res", toggle=True, icon="IMAGE_PLANE")+ if scene.pbr_tiling == 'custom':+ row = sub.row(align=True)+ row.prop(scene, "pbr_tile_albedo", text="Albedo", toggle=True)+ row.prop(scene, "pbr_tile_material", text="Material", toggle=True)+ row.prop(scene, "pbr_tile_normal", text="Normal", toggle=True)+ row.prop(scene, "pbr_tile_height", text="Height", toggle=True)+ row.prop(scene, "pbr_tile_emission", text="Emission", toggle=True)if not scene.pbr_use_native_resolution:row = sub.row()row.prop(scene, "pbr_processing_resolution", text="Processing Resolution")@@ -1841,6 +1918,13 @@ class ApplyPreset(bpy.types.Operator):context.scene.lora_units.remove(len(context.scene.lora_units) - 1)return {'CANCELLED'}+ # Reverse-sync: if the preset set model_architecture but didn't+ # include architecture_mode, update the visible dropdown to match.+ if "architecture_mode" not in values:+ arch = context.scene.model_architecture+ if arch in ('sdxl', 'flux1', 'qwen_image_edit'):+ context.scene.architecture_mode = arch+if skipped:self.report({'WARNING'}, f"Preset '{preset}' applied (skipped {len(skipped)} incompatible setting(s)).")else:diff --git a/stablegen/utils.py b/stablegen/utils.pyindex d328c9d..86dbe19 100644--- a/stablegen/utils.py+++ b/stablegen/utils.py@@ -210,7 +210,7 @@ def get_last_material_index(obj):if obj.data.materials:for mat in obj.data.materials:if mat and mat.use_nodes:- for node in obj.active_material.node_tree.nodes:+ for node in mat.node_tree.nodes:if node.type == 'MATH' and node.operation == 'SUBTRACT':if node.inputs[0].default_value > highest_index:highest_index = node.inputs[0].default_valuediff --git a/stablegen/workflows.py b/stablegen/workflows.pyindex d7734a5..8befb21 100644--- a/stablegen/workflows.py+++ b/stablegen/workflows.py@@ -1257,7 +1257,12 @@ class WorkflowManager:"images": ["1", 0],"strength": getattr(scene, 'pbr_delight_strength', 1.0),"resolution": proc_res,- "upscale_method": "bilinear",+ # Official Stable-X Predictor uses LANCZOS for resize.+ # F.interpolate (used by MarigoldImageProcessor) doesn't+ # support lanczos, but "bicubic" is the closest PyTorch+ # equivalent and much sharper than "bilinear" for both+ # input downscale and output upscale.+ "upscale_method": "bicubic",}},"4": {