Skip to content

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

revert refactor in export_image_edit but keep the new functionality

sakalondcb8dabe713bd
diff --git a/stablegen/render_tools.py b/stablegen/render_tools.py
index b00a49b..811702c 100644
--- a/stablegen/render_tools.py
+++ b/stablegen/render_tools.py
@@ -357,240 +357,192 @@ def flatten_projection_material_for_refine(context, obj, baked_image_path):
print(f"[StableGen] Flattened ProjectionMaterial for '{obj.name}' to baked texture '{os.path.basename(baked_image_path)}'")
-def export_emit_image(
- context,
- to_export,
- camera_id=None,
- bg_color=(0.5, 0.5, 0.5),
- view_transform="Standard",
- fallback_color=(0, 0, 0),
-):
- """
- Exports an emit-only render of the scene from a camera's perspective.
- :param context: Blender context.
- :param to_export: Iterable of objects to process.
- :param camera_id: ID of the camera or a string containing 'visibility' for mask renders.
- """
- print("Exporting emit render")
-
- scene = context.scene
- view_layer = context.view_layer
- world = scene.world
-
- # -------------------------------------------------------------------------
- # Basic scene setup
- # -------------------------------------------------------------------------
- scene.frame_set(1)
-
- if not world:
- world = bpy.data.worlds.new("World")
- scene.world = world
-
- # Cache some original settings we *do* already restore in the original code
- original_engine = scene.render.engine
- original_film_transparent = scene.render.film_transparent
- original_world_use_nodes = world.use_nodes
- original_world_color = world.color.copy() if not world.use_nodes else None
- original_view_transform = scene.view_settings.view_transform
-
- # Precompute flags / strings
- camera_id_str = "" if camera_id is None else str(camera_id)
- is_visibility_render = "visibility" in camera_id_str
-
- # -------------------------------------------------------------------------
- # Material setup per object
- # -------------------------------------------------------------------------
- original_materials = {}
- original_active_material = {}
- temporary_materials = {}
-
- def _setup_emit_material(obj):
- """Copy active material, remap it for fallback background, and assign."""
- mat = obj.active_material
- if not mat:
- return
-
- # Store original materials
- original_materials[obj] = list(obj.data.materials)
- original_active_material[obj] = obj.active_material
-
- # Create a temporary copy of the active material
- mat_copy = mat.copy()
- temporary_materials[obj] = mat_copy
-
- # Replace all slots with the temp material
- obj.data.materials.clear()
- obj.data.materials.append(mat_copy)
-
- # Ensure node setup
- mat_copy.use_nodes = True
- nodes = mat_copy.node_tree.nodes
- links = mat_copy.node_tree.links
-
- # Find material output node
- output = None
- for node in nodes:
- if node.type == "OUTPUT_MATERIAL":
- output = node
- break
-
- if not output:
- return
-
- if not output.inputs[0].links:
- return
+def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard', fallback_color=(0,0,0)):
+ """
+ Exports a emit-only render of the scene from a camera's perspective.
+ :param context: Blender context.
+ :param camera_id: ID of the camera.
+ :return: None
+ """
+ print("Exporting emit render")
+ # Set animation frame to 1
+ bpy.context.scene.frame_set(1)
- before_output = output.inputs[0].links[0].from_node
+ # Store original materials and create temporary ones
+ original_materials = {}
+ original_active_material = {}
+ temporary_materials = {}
- # Figure out which node is the color mix we want to drive
- if before_output.type == "BSDF_PRINCIPLED":
- # Assuming the Color input is driven by a Mix node
- if not before_output.inputs[0].links:
- return
- color_mix = before_output.inputs[0].links[0].from_node
- else:
- # Already a color mix node feeding the output
- color_mix = before_output
-
- # Only set fallback color if this is not a visibility render
- if not is_visibility_render:
- color_mix.inputs["Color2"].default_value = (
- float(fallback_color[0]),
- float(fallback_color[1]),
- float(fallback_color[2]),
- 1.0,
- )
+ # Check if there is BSDF applied
- # Ensure the color mix drives the output directly
- links.new(color_mix.outputs[0], output.inputs[0])
+ # We need to temporarily disconnect BDSF nodes and connect their inputs directly to the output
- # Apply the temporary emit material setup
- for obj in to_export:
- # Only store materials for objects we actually touch
- if obj not in original_materials:
+ for obj in to_export:
+ # Store original materials
original_materials[obj] = list(obj.data.materials)
original_active_material[obj] = obj.active_material
- _setup_emit_material(obj)
- # -------------------------------------------------------------------------
- # Output path setup
- # -------------------------------------------------------------------------
- inpaint_paths = get_dir_path(context, "inpaint")
- output_dir = inpaint_paths["visibility"] if is_visibility_render else inpaint_paths["render"]
- output_file = f"render{camera_id}" if camera_id is not None else "render"
-
- # -------------------------------------------------------------------------
- # World & render settings for flat background and emit-only pass
- # -------------------------------------------------------------------------
- # Flat background, no world nodes
- world.use_nodes = False
- world.color = bg_color
-
- render = scene.render
- cycles = scene.cycles
-
- render.engine = "CYCLES"
- render.film_transparent = False
- cycles.use_osl = True
- cycles.device = "CPU"
- cycles.samples = 1 # Minimum samples for speed
-
- # Color management
- scene.display_settings.display_device = "sRGB"
- scene.view_settings.view_transform = view_transform
-
- # Emit-only pass settings
- view_layer.use_pass_diffuse_color = False
- view_layer.use_pass_diffuse_direct = False
- view_layer.use_pass_diffuse_indirect = False
- view_layer.use_pass_ambient_occlusion = False
- view_layer.use_pass_shadow = False
- view_layer.use_pass_emit = True
- view_layer.use_pass_environment = True
-
- # -------------------------------------------------------------------------
- # Compositor setup
- # -------------------------------------------------------------------------
- scene.use_nodes = True
- comp_tree = scene.node_tree
- comp_nodes = comp_tree.nodes
- comp_links = comp_tree.links
-
- comp_nodes.clear()
-
- render_layers = comp_nodes.new("CompositorNodeRLayers")
-
- mix_node = comp_nodes.new("CompositorNodeMixRGB")
- mix_node.blend_type = "ADD"
- mix_node.inputs[0].default_value = 1.0
-
- output_node = comp_nodes.new("CompositorNodeOutputFile")
- output_node.base_path = output_dir
- output_node.file_slots[0].path = output_file
-
- comp_links.new(render_layers.outputs["Emit"], mix_node.inputs[1])
- comp_links.new(render_layers.outputs["Env"], mix_node.inputs[2])
- comp_links.new(mix_node.outputs[0], output_node.inputs[0])
-
- # -------------------------------------------------------------------------
- # Render
- # -------------------------------------------------------------------------
- bpy.ops.render.render(write_still=True)
-
- base_path = os.path.join(output_dir, f"{output_file}.png")
- final_path = base_path
-
- # -------------------------------------------------------------------------
- # Post-processing for visibility masks
- # -------------------------------------------------------------------------
- if is_visibility_render:
- final_path = base_path.replace(".png", "0001.png")
+ # Copy active material and switch to it
+ mat = obj.active_material
+ if not mat:
+ continue
+ mat_copy = mat.copy()
- if scene.visibility_vignette:
- # Smooth edge feathering, no blocky mask
- apply_vignette_to_mask(
- final_path,
- feather_width=scene.visibility_vignette_width,
- gamma=1.0,
- )
- elif scene.mask_blocky:
- # Only do blocky mask if vignette is OFF
- expanded_mask = expand_mask_to_blocks(final_path, block_size=8)
- if expanded_mask is not None:
- expanded_mask_u8 = (expanded_mask * 255).astype(np.uint8)
- cv2.imwrite(final_path, expanded_mask_u8)
+ # Clear materials and assign temp material
+ obj.data.materials.clear()
+ obj.data.materials.append(mat_copy)
- # -------------------------------------------------------------------------
- # Restore original scene settings (same behavior as original)
- # -------------------------------------------------------------------------
- render.engine = original_engine
- render.film_transparent = original_film_transparent
+ # Store the temporary material for later deletion
+ temporary_materials[obj] = mat_copy
- if original_world_use_nodes:
- world.use_nodes = True
- elif original_world_color:
- world.color = original_world_color
+ # Enable use of nodes
+ mat_copy.use_nodes = True
+ nodes = mat_copy.node_tree.nodes
+ links = mat_copy.node_tree.links
- scene.view_settings.view_transform = original_view_transform
+ # Find the output node
+ output = None
+ for node in nodes:
+ if node.type == 'OUTPUT_MATERIAL':
+ output = node
+ break
- # Restore original materials and active material
- for obj, materials in original_materials.items():
- obj.data.materials.clear()
+ # Check the type of the node which connects to output
+ before_output = output.inputs[0].links[0].from_node
+ if before_output.type == 'BSDF_PRINCIPLED':
+ # Find the last color mix node
+ color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node
+ # Set color 2 to fallback color
+ if not "visibility" in str(camera_id):
+ color_mix.inputs["Color2"].default_value = (fallback_color[0], fallback_color[1], fallback_color[2], 1.0)
+ else:
+ # Already a color mix node
+ color_mix = before_output
+ # Set color 2 to fallback color
+ if not "visibility" in str(camera_id):
+ color_mix.inputs["Color2"].default_value = (fallback_color[0], fallback_color[1], fallback_color[2], 1.0)
+ continue
- active_mat = original_active_material.get(obj)
- if active_mat:
- obj.data.materials.append(active_mat)
+ # Find the last color mix node
+ color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node
+ # Connect the color mix node directly to the output
+ links.new(color_mix.outputs[0], output.inputs[0])
+
+ output_dir = get_dir_path(context, "inpaint")["visibility"] if "visibility" in str(camera_id) else get_dir_path(context, "inpaint")["render"]
+ output_file = f"render{camera_id}" if camera_id is not None else "render"
+
+ # Store and set world settings
+ world = context.scene.world
+ if not world:
+ world = bpy.data.worlds.new("World")
+ context.scene.world = world
+
+ # Store original settings
+ original_engine = context.scene.render.engine
+ original_film_transparent = context.scene.render.film_transparent
+ original_use_nodes = world.use_nodes
+ original_color = world.color.copy() if not world.use_nodes else None
+
+ # Now setting the world color should work
+ world.color = bg_color
+ # Disable world nodes temporarily
+ world.use_nodes = False
+ # Switch to CYCLES render engine and configure settings
+ context.scene.render.engine = 'CYCLES'
+ # Enable OSL
+ context.scene.cycles.use_osl = True
+ context.scene.cycles.device = 'CPU'
+ context.scene.render.film_transparent = False
+ # Change color management to standard
+ bpy.context.scene.display_settings.display_device = 'sRGB'
+ bpy.context.scene.view_settings.view_transform = view_transform
+ context.scene.cycles.samples = 1 # Minimum samples for speed
+ # Configure view layer settings for diffuse-only
+ view_layer = context.view_layer
+ view_layer.use_pass_diffuse_color = False
+ view_layer.use_pass_diffuse_direct = False
+ view_layer.use_pass_diffuse_indirect = False
+
+ # Disable all other passes
+ view_layer.use_pass_ambient_occlusion = False
+ view_layer.use_pass_shadow = False
+ view_layer.use_pass_emit = True
+ view_layer.use_pass_environment = True
+
+
+ # Set up nodes for diffuse-only output
+ context.scene.use_nodes = True
+ nodes = context.scene.node_tree.nodes
+ links = context.scene.node_tree.links
+
+ # Clear existing nodes
+ nodes.clear()
+
+ # Create nodes
+ render_layers = nodes.new('CompositorNodeRLayers')
+ mix_node = nodes.new('CompositorNodeMixRGB')
+ mix_node.blend_type = 'ADD'
+ mix_node.inputs[0].default_value = 1
+ output_node = nodes.new('CompositorNodeOutputFile')
+ output_node.base_path = output_dir
+ output_node.file_slots[0].path = output_file
+
+ # Connect emission to output
+ links.new(render_layers.outputs['Emit'], mix_node.inputs[1])
+ links.new(render_layers.outputs['Env'], mix_node.inputs[2])
+ links.new(mix_node.outputs[0], output_node.inputs[0])
+
+ # Render
+ bpy.ops.render.render(write_still=True)
+
+ # Post-processing for visibility masks
+ if "visibility" in str(camera_id):
+ # Load the rendered image
+ image_path = os.path.join(output_dir, f"{output_file}.png")
+ # Blender output node might append frame number, e.g. render0001.png
+ # But here we assume standard naming or handle it if needed.
+ # The original code replaced .png with 0001.png, let's stick to that pattern if it matches
+ final_path = image_path.replace(".png", "0001.png")
+
+ if context.scene.visibility_vignette:
+ # Smooth edge feathering, no blocky mask
+ apply_vignette_to_mask(
+ final_path,
+ feather_width=context.scene.visibility_vignette_width,
+ gamma=1.0,
+ )
+ elif context.scene.mask_blocky:
+ # Only do blocky mask if vignette is OFF
+ expanded_mask = expand_mask_to_blocks(final_path, block_size=8)
+ if expanded_mask is not None:
+ expanded_mask_u8 = (expanded_mask * 255).astype(np.uint8)
+ cv2.imwrite(final_path, expanded_mask_u8)
+
+ # Restore original settings
+ context.scene.render.engine = original_engine
+ context.scene.render.film_transparent = original_film_transparent
+ if original_use_nodes:
+ world.use_nodes = True
+ elif original_color:
+ world.color = original_color
+ bpy.context.scene.view_settings.view_transform = 'Standard'
- for mat in materials:
- if mat is not active_mat:
- obj.data.materials.append(mat)
+ # Restore original materials
+ for obj, materials in original_materials.items():
+ obj.data.materials.clear()
+ # First append the original active material
+ if original_active_material[obj]:
+ obj.data.materials.append(original_active_material[obj])
+ for mat in materials:
+ if mat != original_active_material[obj]:
+ obj.data.materials.append(mat)
- # Clean up temporary materials
- for temp_mat in temporary_materials.values():
- if temp_mat and temp_mat.name in bpy.data.materials:
- bpy.data.materials.remove(temp_mat)
+ # Clean up temporary materials
+ for _, temp_mat in temporary_materials.items():
+ if temp_mat and temp_mat.name in bpy.data.materials:
+ bpy.data.materials.remove(temp_mat)
- print(f"Emission render saved to: {os.path.join(output_dir, output_file)}.png")
+ print(f"Emmision render saved to: {os.path.join(output_dir, output_file)}.png")
def export_render(context, camera_id=None):
@@ -1880,6 +1832,7 @@ class BakeTextures(bpy.types.Operator):
links.new(principled_node.outputs["BSDF"], output_node.inputs["Surface"])
else:
links.new(tex_image.outputs["Color"], output_node.inputs["Surface"])
+
class ExportOrbitGIF(bpy.types.Operator):
"""Exports a GIF and MP4 animation orbiting the active object"""