Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
add option to only target selected mesh objects, improve checkpoint and lora selection handling
sakalonde1ed98db2ce7
diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex 4119749..ca502ce 100755--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -36,6 +36,33 @@ classes = [def update_combined(self, context): # Combined with load_handler to load controlnet unit on first setupupdate_parameters(self, context)load_handler(None)++ # Checkpoint model reset+ current_checkpoint = context.scene.model_name+ checkpoint_items = update_model_list(self, context)+ valid_checkpoint_ids = {item[0] for item in checkpoint_items}++ placeholder_id = 'NONE_AVAILABLE'++ if current_checkpoint not in valid_checkpoint_ids:+ if placeholder_id in valid_checkpoint_ids:+ context.scene.model_name = placeholder_id+ elif checkpoint_items: # If no placeholder but other items, pick first+ context.scene.model_name = checkpoint_items[0][0]++ # LoRA unit reset+ if hasattr(context.scene, 'lora_units'):+ lora_items = get_lora_models(self, context)+ valid_lora_ids = {item[0] for item in lora_items}++ for id, lora_unit in enumerate(context.scene.lora_units):+ if lora_unit.model_name not in valid_lora_ids or lora_unit.model_name == "NONE_AVAILABLE":+ # Remove the unit+ context.scene.lora_units.remove(id)+ # Check if the current LoRA unit index is valid+ if context.scene.lora_units_index >= len(context.scene.lora_units) or context.scene.lora_units_index < 0:+ context.scene.lora_units_index = max(0, len(context.scene.lora_units) - 1)+return Noneclass StableGenAddonPreferences(bpy.types.AddonPreferences):@@ -196,9 +223,6 @@ def update_model_list(self, context):all_model_items.append(get_models_from_directory(comfy_ckpts_path, ('.safetensors', '.ckpt', '.pth'), "Checkpoint"))- else: # Add placeholder if ComfyUI dir itself is not set- all_model_items.append([("NO_COMFYUI_DIR_CKPT", "ComfyUI Dir Not Set (Checkpoints)", "Set in Prefs")])-# 2. Scan External Checkpoints Pathif external_ckpts_dir and os.path.isdir(external_ckpts_dir):@@ -320,8 +344,6 @@ def get_lora_models(self, context):all_lora_items.append(get_models_from_directory(comfy_loras_path, ('.safetensors', '.ckpt', '.pt', '.pth'), "LoRA"))- else: # Add placeholder if ComfyUI dir itself is not set- all_lora_items.append([("NO_COMFYUI_DIR_LORA", "ComfyUI Dir Not Set (LoRAs)", "Set in Prefs")])# 2. Scan External LoRAs Path@@ -1199,6 +1221,18 @@ def register():default=False,update=update_parameters)++ bpy.types.Scene.texture_objects = bpy.props.EnumProperty(+ name="Objects to Texture",+ description="Select the objects to texture",+ items=[+ ('all', 'All Visible', 'Texture all visible objects in the scene'),+ ('selected', 'Selected', 'Texture only selected objects'),+ ],+ default='all',+ update=update_parameters+ )+# IPADAPTER parametersbpy.types.Scene.controlnet_units = bpy.props.CollectionProperty(type=ControlNetUnit)@@ -1289,6 +1323,7 @@ def unregister():del bpy.types.Scene.project_onlydel bpy.types.Scene.early_priority_strengthdel bpy.types.Scene.early_priority+ del bpy.types.Scene.texture_objectsfor cls in reversed(classes):bpy.utils.unregister_class(cls)diff --git a/stablegen/generator.py b/stablegen/generator.pyindex fdabd47..124078e 100644--- a/stablegen/generator.py+++ b/stablegen/generator.py@@ -66,10 +66,14 @@ class Reproject(bpy.types.Operator)::param context: Blender context.:return: {'FINISHED'}"""+ if context.scene.texture_objects == 'all':+ to_texture = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']+ else: # selected+ to_texture = [obj for obj in bpy.context.selected_objects if obj.type == 'MESH']+# Search for largest material id- meshes = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']max_id = -1- for obj in meshes:+ for obj in to_texture:mat_id = get_last_material_index(obj)if mat_id > max_id:max_id = mat_id@@ -144,6 +148,8 @@ class ComfyUIGenerate(bpy.types.Operator):_grid_width = 0_grid_height = 0_material_id = -1+ _to_texture = None+ _original_visibility = Noneproceed_with_high_res: bpy.props.BoolProperty(default=False)# Add properties to track progress@@ -285,43 +291,53 @@ class ComfyUIGenerate(bpy.types.Operator):uv_slots_needed = len(self._cameras)+ if context.scene.texture_objects == 'selected':+ self._to_texture = [obj for obj in bpy.context.selected_objects if obj.type == 'MESH']+ # If empty, cancel the operation+ if not self._to_texture:+ self.report({'ERROR'}, "No mesh objects selected for texturing.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}+ else: # all+ self._to_texture = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']+# Find all mesh objects, check their material ids and store the highest one- for obj in bpy.context.scene.objects:- if obj.type == 'MESH':- for slot in obj.material_slots:- material_id = get_last_material_index(obj)- if (material_id > self._material_id):- self._material_id = material_id- # Check if there are enough UV map slots- if not context.scene.bake_texture and context.scene.generation_method != 'uv_inpaint':- if not context.scene.overwrite_material or (context.scene.generation_method == 'refine' and context.scene.refine_preserve):- if 8 - len(obj.data.uv_layers) < uv_slots_needed:+ for obj in self._to_texture:+ for slot in obj.material_slots:+ material_id = get_last_material_index(obj)+ if (material_id > self._material_id):+ self._material_id = material_id+ # Check if there are enough UV map slots+ if not context.scene.bake_texture and context.scene.generation_method != 'uv_inpaint':+ if not context.scene.overwrite_material or (context.scene.generation_method == 'refine' and context.scene.refine_preserve):+ if 8 - len(obj.data.uv_layers) < uv_slots_needed:+ self.report({'ERROR'}, "Not enough UV map slots for all cameras.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}+ else:+ # Make a set to count unique uv maps+ uv_maps = set()+ mesh = obj.data+ uv_maps = [uv_layer.name for uv_layer in mesh.uv_layers]+ if len(uv_maps) == 1:+ # Probably a baked texture, check if there is enough uv slots+ if 8 - len(obj.data.uv_layers) - 1 < uv_slots_needed:self.report({'ERROR'}, "Not enough UV map slots for all cameras.")context.scene.generation_status = 'idle'ComfyUIGenerate._is_running = Falsereturn {'CANCELLED'}- else:- # Make a set to count unique uv maps- uv_maps = set()- mesh = obj.data- uv_maps = [uv_layer.name for uv_layer in mesh.uv_layers]- if len(uv_maps) == 1:- # Probably a baked texture, check if there is enough uv slots- if 8 - len(obj.data.uv_layers) - 1 < uv_slots_needed:- self.report({'ERROR'}, "Not enough UV map slots for all cameras.")- context.scene.generation_status = 'idle'- ComfyUIGenerate._is_running = False- return {'CANCELLED'}- elif 8 - len(obj.data.uv_layers) + len(uv_maps) < uv_slots_needed:- print(f"8 - {len(obj.data.uv_layers)} + {len(uv_maps)} < {uv_slots_needed}")- self.report({'ERROR'}, "Not enough UV map slots for all cameras.")- context.scene.generation_status = 'idle'- ComfyUIGenerate._is_running = False- return {'CANCELLED'}-- else:- if 8 - len(obj.data.uv_layers) < 1:- self.report({'ERROR'}, "Not enough UV map slots for baking. At least 1 slot is required.")+ elif 8 - len(obj.data.uv_layers) + len(uv_maps) < uv_slots_needed:+ print(f"8 - {len(obj.data.uv_layers)} + {len(uv_maps)} < {uv_slots_needed}")+ self.report({'ERROR'}, "Not enough UV map slots for all cameras.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}++ else:+ if 8 - len(obj.data.uv_layers) < 1:+ self.report({'ERROR'}, "Not enough UV map slots for baking. At least 1 slot is required.")if not context.scene.overwrite_material or self._material_id == -1 or (context.scene.generation_method == 'refine' and context.scene.refine_preserve):self._material_id += 1@@ -382,31 +398,37 @@ class ComfyUIGenerate(bpy.types.Operator):if context.scene.generation_method == 'grid':self._threads_left = 1if context.scene.generation_method == 'uv_inpaint':- mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']- self._threads_left = len(mesh_objects)+ self._threads_left = len(self._to_texture)else:self._threads_left = len(self._cameras)-++ self._original_visibility = {}+ if context.scene.texture_objects == 'selected':+ # Hide unselected objects for rendering+ for obj in bpy.context.scene.objects:+ if obj.type == 'MESH' and obj not in self._to_texture:+ # Save original visibility+ self._original_visibility[obj.name] = obj.hide_render+ obj.hide_render = True# Refine mode preparationif context.scene.generation_method == 'refine':for i, camera in enumerate(self._cameras):bpy.context.scene.camera = camera- export_emit_image(context, camera_id=i)+ export_emit_image(context, self._to_texture, camera_id=i)# UV inpainting mode preparationif context.scene.generation_method == 'uv_inpaint':# Check if there are baked textures for all objects- mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']if self.show_prompt_dialog:# Start the prompt collection process with the first objectif not self._object_prompts: # Only if prompts haven't been collected- self.current_object_name = mesh_objects[0].name+ self.current_object_name = self._to_texture[0].namereturn context.window_manager.invoke_props_dialog(self, width=400)# Continue with normal execution if all prompts are collected- for obj in mesh_objects:+ for obj in self._to_texture:# Use get_file_path to check for baked texture existencebaked_texture_path = get_file_path(context, "baked", object_name=obj.name)if not os.path.exists(baked_texture_path):@@ -433,7 +455,7 @@ class ComfyUIGenerate(bpy.types.Operator):if context.scene.refine_images:self._total_images += len(self._cameras) # Add refinement stepselif context.scene.generation_method == 'uv_inpaint':- self._total_images = len(mesh_objects)+ self._total_images = len(self._to_texture)# Add modal timercontext.window_manager.modal_handler_add(self)@@ -462,6 +484,11 @@ class ComfyUIGenerate(bpy.types.Operator):if not self._thread.is_alive():context.window_manager.event_timer_remove(self._timer)ComfyUIGenerate._is_running = False+ # Restore original visibility for non-selected objects+ if context.scene.texture_objects == 'selected':+ for obj in bpy.context.scene.objects:+ if obj.type == 'MESH' and obj.name in self._original_visibility:+ obj.hide_render = self._original_visibility[obj.name]if self._error:if self._error == "'25'" or self._error == "'111'":# Probably canceled by user, quietly return@@ -498,16 +525,15 @@ class ComfyUIGenerate(bpy.types.Operator):# Handle prompt collection for UV inpaintingif context.scene.generation_method == 'uv_inpaint' and self.show_prompt_dialog:- mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']- current_index = next((i for i, obj in enumerate(mesh_objects)+ current_index = next((i for i, obj in enumerate(self._to_texture)if obj.name == self.current_object_name), -1)# Store the current promptself._object_prompts[self.current_object_name] = self.current_object_prompt# Move to next object or finish- if current_index < len(mesh_objects) - 1:- self.current_object_name = mesh_objects[current_index + 1].name+ if current_index < len(self._to_texture) - 1:+ self.current_object_name = self._to_texture[current_index + 1].nameself.current_object_prompt = ""return context.window_manager.invoke_props_dialog(self, width=400)else:@@ -539,10 +565,6 @@ class ComfyUIGenerate(bpy.types.Operator):"""self._error = Nonetry:- mesh_objects = None- if (context.scene.generation_method == 'uv_inpaint'):- mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']-depth_path = Nonecanny_path = Nonenormal_path = None@@ -571,7 +593,7 @@ class ComfyUIGenerate(bpy.types.Operator):normal_path = get_file_path(context, "controlnet", subtype="normal", camera_id=camera_id) if camera_id is not None else get_file_path(context, "controlnet", subtype="normal")else:# Get paths for UV inpainting for the current object- current_obj_name = mesh_objects[self._current_image].name+ current_obj_name = self._to_texture[self._current_image].namemask_path = get_file_path(context, "uv_inpaint", subtype="visibility", object_name=current_obj_name)render_path = get_file_path(context, "baked", object_name=current_obj_name) # Use baked texture as input render@@ -612,7 +634,7 @@ class ComfyUIGenerate(bpy.types.Operator):# Save the generated image using new path structureif context.scene.generation_method == 'uv_inpaint':- image_path = get_file_path(context, "generated_baked", object_name=mesh_objects[self._current_image].name, material_id=self._material_id)+ image_path = get_file_path(context, "generated_baked", object_name=self._to_texture[self._current_image].name, material_id=self._material_id)elif camera_id is not None:image_path = get_file_path(context, "generated", camera_id=camera_id, material_id=self._material_id)else: # Grid mode initial generation@@ -646,11 +668,11 @@ class ComfyUIGenerate(bpy.types.Operator):if context.scene.generation_method == 'sequential':def image_project_callback():redraw_ui(context)- project_image(context, self._material_id, stop_index=self._current_image)+ project_image(context, self._to_texture, self._material_id, stop_index=self._current_image)if self._current_image < len(self._cameras) - 1:next_camera_id = self._current_image + 1- export_visibility(context, camera_visibility=self._cameras[self._current_image]) # Export mask for current view- export_emit_image(context, camera_id=next_camera_id, bg_color=context.scene.fallback_color) # Export render for next view+ export_visibility(context, self._to_texture, camera_visibility=self._cameras[self._current_image]) # Export mask for current view+ export_emit_image(context, self._to_texture, camera_id=next_camera_id, bg_color=context.scene.fallback_color) # Export render for next view# Set the event to signal the end of the processself._wait_event.set()return None@@ -721,12 +743,11 @@ class ComfyUIGenerate(bpy.types.Operator):self._stage = "Baking Textures & Projecting"redraw_ui(context)if context.scene.generation_method != 'uv_inpaint':- project_image(context, self._material_id)+ project_image(context, self._to_texture, self._material_id)else:# Apply the UV inpainted textures to each meshfrom .render_tools import apply_uv_inpaint_texture- mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']- for obj in mesh_objects:+ for obj in self._to_texture:texture_path = get_file_path(context, "generated_baked", object_name=obj.name, material_id=self._material_id)@@ -1781,9 +1802,11 @@ class ComfyUIGenerate(bpy.types.Operator):if context.scene.generation_method == 'uv_inpaint':# Reset object prompts on every runself._object_prompts = {}- self._mesh_objects = [obj.name for obj in bpy.context.scene.objects if obj.type == 'MESH']+ self._to_texture = [obj.name for obj in bpy.context.scene.objects if obj.type == 'MESH']+ if context.scene.texture_objects == 'selected':+ self._to_texture = [obj.name for obj in bpy.context.selected_objects if obj.type == 'MESH']self.mesh_index = 0- self.current_object_name = self._mesh_objects[0] if self._mesh_objects else ""+ self.current_object_name = self._to_texture[0] if self._to_texture else ""# If "Ask for object prompts" is disabled, don’t prompt per objectif not context.scene.ask_object_prompts:self.show_prompt_dialog = Falsediff --git a/stablegen/project.py b/stablegen/project.pyindex f549055..83e23d9 100644--- a/stablegen/project.py+++ b/stablegen/project.py@@ -6,7 +6,7 @@ from .utils import get_last_material_index, get_file_path, get_dir_pathfrom .render_tools import prepare_baking, bake_texture, unwrapfrom mathutils import Vector-def project_image(context, mat_id, stop_index=1000000):+def project_image(context, to_project, mat_id, stop_index=1000000):"""Projects an image onto all mesh objects using UV Project Modifier."""@@ -141,18 +141,13 @@ def project_image(context, mat_id, stop_index=1000000):cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']cameras.sort(key=lambda x: x.name)- # The image is saved as png binary in the image variable- stage_ref = "Projecting images (this may take a while)..."- if context.scene.generation_method == 'sequential' and stop_index > 0:- stage_ref = f"Editing node tree..."# Force refresh of the UIfor area in context.screen.areas:area.tag_redraw()# Apply projection to all mesh objects for each camerafor i, camera in enumerate(cameras):- object_Mesh = [obj for obj in context.scene.objects if obj.type == 'MESH']- for x, obj in enumerate(object_Mesh):+ for x, obj in enumerate(to_project):# We can skip the UV Projection step in sequential mode for i > 0if context.scene.generation_method != 'sequential' or stop_index == 0 or context.scene.bake_texture:# Deselect all objects@@ -232,9 +227,7 @@ def project_image(context, mat_id, stop_index=1000000):simple_project_bake(context, i, obj, mat_id)obj.data.uv_layers.remove(obj.data.uv_layers[-1]) # Remove the last UV map- for obj in context.scene.objects:- if obj.type != 'MESH':- continue+ for obj in to_project:# Deselect all objectsbpy.ops.object.select_all(action='DESELECT')diff --git a/stablegen/render_tools.py b/stablegen/render_tools.pyindex 11084b5..7d154bc 100644--- a/stablegen/render_tools.py+++ b/stablegen/render_tools.py@@ -87,7 +87,7 @@ def apply_uv_inpaint_texture(context, obj, baked_image_path):# Connect UV map node to texture nodelinks.new(uv_map_node.outputs["UV"], tex_node.inputs["Vector"])-def export_emit_image(context, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard'):+def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard'):"""Exports a emit-only render of the scene from a camera's perspective.:param context: Blender context.@@ -102,58 +102,55 @@ def export_emit_image(context, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_troriginal_materials = {}original_active_material = {}temporary_materials = {}-- use_emission = True# Check if there is BSDF applied# We need to temporarily disconnect BDSF nodes and connect their inputs directly to the output- for obj in context.scene.objects:- if obj.type == 'MESH':- # Store original materials- original_materials[obj] = list(obj.data.materials)- original_active_material[obj] = obj.active_material+ for obj in to_export:+ # Store original materials+ original_materials[obj] = list(obj.data.materials)+ original_active_material[obj] = obj.active_material++ # Copy active material and switch to it+ mat = obj.active_material+ if not mat:+ continue+ mat_copy = mat.copy()++ # Clear materials and assign temp material+ obj.data.materials.clear()+ obj.data.materials.append(mat_copy)- # Copy active material and switch to it- mat = obj.active_material- if not mat:- continue- mat_copy = mat.copy()+ # Store the temporary material for later deletion+ temporary_materials[obj] = mat_copy- # Clear materials and assign temp material- obj.data.materials.clear()- obj.data.materials.append(mat_copy)-- # Store the temporary material for later deletion- temporary_materials[obj] = mat_copy-- # Enable use of nodes- mat_copy.use_nodes = True- nodes = mat_copy.node_tree.nodes- links = mat_copy.node_tree.links-- # Find the output node- output = None- for node in nodes:- if node.type == 'OUTPUT_MATERIAL':- output = node- break-- # Check the type of the node which connects to output- before_output = output.inputs[0].links[0].from_node- if before_output.type == 'BSDF_PRINCIPLED':- # Find the last color mix node- color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node- else:- # Already a color mix node- color_mix = before_output- continue+ # Enable use of nodes+ mat_copy.use_nodes = True+ nodes = mat_copy.node_tree.nodes+ links = mat_copy.node_tree.links+ # Find the output node+ output = None+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output = node+ break++ # Check the type of the node which connects to output+ before_output = output.inputs[0].links[0].from_node+ if before_output.type == 'BSDF_PRINCIPLED':# Find the last color mix nodecolor_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node- # Connect the color mix node directly to the output- links.new(color_mix.outputs[0], output.inputs[0])+ else:+ # Already a color mix node+ color_mix = before_output+ continue++ # Find the last color mix node+ color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ # Connect the color mix node directly to the output+ links.new(color_mix.outputs[0], output.inputs[0])output_dir = get_dir_path(context, "inpaint")["visibility"] if "visibility" in str(camera_id) else get_dir_path(context, "inpaint")["render"]output_file = f"render{camera_id}" if camera_id is not None else "render"@@ -474,7 +471,7 @@ def expand_mask_to_blocks(mask_file_path, block_size=8):return None-def export_visibility(context, obj=None, camera_visibility=None):+def export_visibility(context, to_export, obj=None, camera_visibility=None):"""Exports the visibility of the mesh by temporarily altering the shading nodes.:param context: Blender context.@@ -594,10 +591,10 @@ def export_visibility(context, obj=None, camera_visibility=None):return True# Prepare the material- mesh_objects = [obj for obj in context.scene.objects if obj.type == 'MESH']+if not obj:# Prepare for all objects- for obj in mesh_objects:+ for obj in to_export:if not prepare_material(obj):return Falseelse:@@ -625,8 +622,7 @@ def export_visibility(context, obj=None, camera_visibility=None):camera_render_index = (camera_visibility_index + 1) % len(cameras)camera_render = cameras[camera_render_index]context.scene.camera = camera_render- export_emit_image(context, camera_id=f"{camera_render_index}_visibility", bg_color=(1, 1, 1), view_transform='Raw')- ### if camera_index == 1: return False # test+ export_emit_image(context, to_export, camera_id=f"{camera_render_index}_visibility", bg_color=(1, 1, 1), view_transform='Raw')# Restore original materialsfor obj, materials in original_materials.items():@@ -1317,7 +1313,10 @@ class BakeTextures(bpy.types.Operator)::param event: Blender event.:return: {'RUNNING_MODAL'}"""- self._objects = [obj for obj in context.scene.objects if obj.type == 'MESH']+ if context.scene.texture_objects == 'all':+ self._objects = [obj for obj in context.scene.objects if obj.type == 'MESH']+ else: # 'selected'+ self._objects = [obj for obj in context.selected_objects if obj.type == 'MESH']self._current_index = 0self._phase = 'unwrap'self._total_objects = len(self._objects)diff --git a/stablegen/stablegen.py b/stablegen/stablegen.pyindex 2b1f81e..338732c 100755--- a/stablegen/stablegen.py+++ b/stablegen/stablegen.py@@ -313,6 +313,7 @@ class StableGenPanel(bpy.types.Panel):split = params_container.split(factor=0.25)split.label(text="Checkpoint:")split.prop(scene, "model_name", text="")+# Split for model architecturesplit = params_container.split(factor=0.5)@@ -324,6 +325,11 @@ class StableGenPanel(bpy.types.Panel):split.label(text="Generation Mode:")split.prop(scene, "generation_method", text="")+ # Split for object selection+ split = params_container.split(factor=0.5)+ split.label(text="Target Objects:")+ split.prop(scene, "texture_objects", text="")+# --- Helper to create collapsible sections ---def draw_collapsible_section(parent_layout, toggle_prop_name, title, icon="NONE"):if not hasattr(scene, toggle_prop_name):