Skip to content

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

feat: license docs, bg removal bypass, configurable timeouts, preset detection fix

sakalondace4cf02d623
diff --git a/README.md b/README.md
index 8360733..34ecbd8 100644
--- a/README.md
+++ b/README.md
@@ -387,6 +387,33 @@ We welcome contributions! Whether it's bug reports, feature suggestions, code co
StableGen is released under the **GNU General Public License v3.0**. See the `LICENSE` file for details.
+### Third-Party Licenses: TRELLIS.2 Image-to-3D
+
+> **Note:** This section applies **only** to the TRELLIS.2 Image-to-3D feature. StableGen's standard texturing pipelines (SDXL, FLUX.1-dev, Qwen Image Edit) do not use any of the libraries listed below and are unaffected by these licensing restrictions.
+
+The TRELLIS.2 feature relies on several third-party components, each with its own license. **Users should be aware of these licenses, particularly the non-commercial restrictions on certain NVIDIA libraries used in the TRELLIS.2 textured output pipeline.**
+
+| Component | License | Commercial Use Permitted? |
+|---|---|---|
+| [TRELLIS.2](https://github.com/microsoft/TRELLIS.2) (Microsoft) | MIT | ✅ Yes |
+| [TRELLIS.2-4B model weights](https://huggingface.co/microsoft/TRELLIS.2-4B) | MIT | ✅ Yes |
+| [ComfyUI-TRELLIS2](https://github.com/PozzettiAndrea/ComfyUI-TRELLIS2) | MIT | ✅ Yes |
+| [DINOv3](https://github.com/facebookresearch/dinov3) (Meta, image conditioning) | [DINOv3 License](https://ai.meta.com/resources/models-and-libraries/dinov3-license/) | ✅ Yes |
+| [BiRefNet](https://github.com/ZhengPeng7/BiRefNet) (background removal) | MIT | ✅ Yes |
+| [FlexGEMM](https://github.com/JeffreyXiang/FlexGEMM) (sparse convolutions) | MIT | ✅ Yes |
+| [CuMesh](https://github.com/JeffreyXiang/CuMesh) (mesh operations) | MIT | ✅ Yes |
+| O-Voxel (voxel processing, part of TRELLIS.2) | MIT | ✅ Yes |
+| [nvdiffrast](https://github.com/NVlabs/nvdiffrast) (NVIDIA) | NVIDIA Source Code License (1-Way Commercial) | ❌ **Non-commercial only** |
+| [nvdiffrec](https://github.com/NVlabs/nvdiffrec) (NVIDIA) | NVIDIA Source Code License | ❌ **Non-commercial only** |
+
+**Important:** The NVIDIA libraries (`nvdiffrast` and `nvdiffrec`) are only used when the TRELLIS.2 **Texture Mode** is set to **"Native (TRELLIS.2)"** — specifically for UV rasterization and PBR texture baking. Their license restricts usage to *"research or evaluation purposes only and not for any direct or indirect monetary gain"* (Section 3.3). Only NVIDIA and its affiliates may use these libraries commercially.
+
+**All other TRELLIS.2 modes do not introduce NVIDIA licensing restrictions:**
+* **Shape-only mode ("None")** — does not use nvdiffrast/nvdiffrec. All other pipeline components are permissively licensed (MIT/Apache 2.0 + DINOv3 License).
+* **Projection-based texture modes ("SDXL", "Flux 1", "Qwen Image Edit")** — does not use nvdiffrast/nvdiffrec. The licensing terms of the selected diffusion model apply as usual (e.g., FLUX.1-dev has its own license terms separate from the TRELLIS.2 pipeline).
+
+If you require commercial use of the "Native (TRELLIS.2)" texture mode, consider contacting NVIDIA regarding commercial licensing for nvdiffrast/nvdiffrec.
+
---
## 🙏 Acknowledgements
diff --git a/installer.py b/installer.py
index db5d7e1..f71b4c2 100644
--- a/installer.py
+++ b/installer.py
@@ -492,7 +492,7 @@ DEPENDENCIES: Dict[str, Dict[str, Any]] = {
"commit": "6b0b2148f45bbafa0b86bfd25c63602b63a7aae0",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-TRELLIS2",
- "license": "MIT", "packages": ["trellis2"],
+ "license": "MIT (Note: textured pipeline uses NVIDIA non-commercial libs)", "packages": ["trellis2"],
"pip_packages": ["comfy-env==0.2.0"],
"run_install_script": True,
"post_clone_patches": [
@@ -595,7 +595,9 @@ MENU_PACKAGES: Dict[str, Dict[str, Any]] = {
'8': {"name": "[TRELLIS.2] Image-to-3D Node",
"tags": ["trellis2"],
"size_gb": 0.1,
- "description_suffix": "*Installs ComfyUI-TRELLIS2 custom node. Models are downloaded automatically on first use by the node.*"},
+ "description_suffix": "*Installs ComfyUI-TRELLIS2 custom node. Models are downloaded automatically on first use by the node.*\n"
+ " *LICENSE NOTICE: Only the 'Native (TRELLIS.2)' texture mode uses nvdiffrast/nvdiffrec*\n"
+ " *(NVIDIA Source Code License — non-commercial use only). See README.md for full details.*",
}
# --- Helper Functions ---
@@ -971,7 +973,42 @@ def main():
print("Installation of this package cancelled by user.")
print_separator()
continue
-
+
+ # Display TRELLIS.2 license notice if installing that package
+ if "trellis2" in selected_option["tags"]:
+ print_separator(char='!')
+ print("TRELLIS.2 THIRD-PARTY LICENSE NOTICE")
+ print_separator(char='!')
+ print("NOTE: This notice applies ONLY to the TRELLIS.2 Image-to-3D feature.")
+ print("StableGen's standard texturing pipelines (SDXL, FLUX, Qwen) are unaffected.")
+ print()
+ print("ComfyUI-TRELLIS2 and the TRELLIS.2 model are MIT-licensed.")
+ print("However, the TRELLIS.2 TEXTURED mesh pipeline uses the following NVIDIA")
+ print("libraries that are restricted to NON-COMMERCIAL use only:")
+ print()
+ print(" - nvdiffrast (NVIDIA Source Code License, 1-Way Commercial)")
+ print(" - nvdiffrec (NVIDIA Source Code License)")
+ print()
+ print("These licenses restrict usage to 'research or evaluation purposes only")
+ print("and not for any direct or indirect monetary gain' (Section 3.3).")
+ print("Only NVIDIA and its affiliates may use them commercially.")
+ print()
+ print("These libraries are ONLY used when Texture Mode is set to")
+ print("'Native (TRELLIS.2)' for UV rasterization and PBR texture baking.")
+ print()
+ print("All other modes do not introduce additional NVIDIA restrictions:")
+ print(" - Texture Mode 'None' (shape-only) - permissively licensed")
+ print(" - Projection texture modes (SDXL, Flux, Qwen) - the selected")
+ print(" diffusion model's own license applies as usual")
+ print()
+ print("For full details, see the README.md License section.")
+ print_separator(char='!')
+ ack = input("Acknowledge and continue? (y/n, Enter for yes): ").strip().lower()
+ if not (ack == "" or ack == 'y'):
+ print("Installation cancelled.")
+ print_separator()
+ continue
+
print_separator(char='*')
for item_details in items_to_process_this_round:
if item_details["id"] in processed_during_this_session: # Should not happen if items_to_process_this_round is built correctly
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index ddca576..014835c 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -78,6 +78,9 @@ def update_architecture_mode(self, context):
# Entering TRELLIS.2 mode — sync backbone for any diffusion need
_sync_trellis2_backbone(scene)
+ # Trigger preset detection
+ update_parameters(self, context)
+
def _sync_trellis2_backbone(scene):
"""Pick the right diffusion backbone for the current TRELLIS.2 state.
@@ -118,6 +121,9 @@ def update_trellis2_texture_mode(self, context):
_sync_trellis2_backbone(scene)
+ # Trigger preset detection
+ update_parameters(self, context)
+
def update_trellis2_initial_image_arch(self, context):
"""Called when the user changes the initial-image architecture for TRELLIS.2.
@@ -130,6 +136,9 @@ def update_trellis2_initial_image_arch(self, context):
return
_sync_trellis2_backbone(scene)
+ # Trigger preset detection
+ update_parameters(self, context)
+
def update_trellis2_generate_from(self, context):
"""Called when the user switches between Image and Prompt input mode.
@@ -144,6 +153,9 @@ def update_trellis2_generate_from(self, context):
if scene.trellis2_generate_from == 'prompt':
_sync_trellis2_backbone(scene)
+ # Trigger preset detection
+ update_parameters(self, context)
+
def update_combined(self, context):
# This now primarily updates the preset status and might trigger Enum updates implicitly
@@ -167,7 +179,7 @@ def update_combined(self, context):
return None
# Check if server is reachable
- if not check_server_availability(context.preferences.addons[__package__].preferences.server_address, timeout=0.5):
+ if not check_server_availability(context.preferences.addons[__package__].preferences.server_address, timeout=get_timeout('ping')):
context.preferences.addons[__package__].preferences.server_online = False
print("ComfyUI server is not reachable.")
return None
@@ -176,7 +188,7 @@ def update_combined(self, context):
# Auto-detect TRELLIS.2 availability
trellis2_found = check_trellis2_available(
- context.preferences.addons[__package__].preferences.server_address, timeout=1.0
+ context.preferences.addons[__package__].preferences.server_address, timeout=get_timeout('ping')
)
context.scene.trellis2_available = trellis2_found
@@ -326,6 +338,46 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
default=False
) # type: ignore
+ timeout_ping: bpy.props.FloatProperty(
+ name="Ping Timeout (s)",
+ description="Timeout for quick server availability checks (connectivity pings)",
+ default=1.0,
+ min=0.1,
+ max=30.0,
+ step=10,
+ precision=1,
+ ) # type: ignore
+
+ timeout_api: bpy.props.FloatProperty(
+ name="API Timeout (s)",
+ description="Timeout for standard API requests (VRAM flush, queue prompt, server info)",
+ default=10.0,
+ min=1.0,
+ max=120.0,
+ step=100,
+ precision=0,
+ ) # type: ignore
+
+ timeout_transfer: bpy.props.FloatProperty(
+ name="Transfer Timeout (s)",
+ description="Timeout for large data transfers (image upload, file download)",
+ default=120.0,
+ min=10.0,
+ max=600.0,
+ step=100,
+ precision=0,
+ ) # type: ignore
+
+ timeout_reboot: bpy.props.FloatProperty(
+ name="Reboot Timeout (s)",
+ description="How long to wait for ComfyUI server to come back after a reboot",
+ default=120.0,
+ min=10.0,
+ max=600.0,
+ step=100,
+ precision=0,
+ ) # type: ignore
+
def draw(self, context):
"""
Draws the preferences panel.
@@ -377,6 +429,14 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
adv_box.prop(self, "overlay_color")
adv_box.prop(self, "enable_debug")
+ adv_box.separator()
+ adv_box.label(text="Timeouts:", icon="TIME")
+ col = adv_box.column(align=True)
+ col.prop(self, "timeout_ping")
+ col.prop(self, "timeout_api")
+ col.prop(self, "timeout_transfer")
+ col.prop(self, "timeout_reboot")
+
class CheckServerStatus(bpy.types.Operator):
"""Checks if the ComfyUI server is reachable."""
bl_idname = "stablegen.check_server_status"
@@ -398,7 +458,7 @@ class CheckServerStatus(bpy.types.Operator):
print(f"Checking server status at {server_addr}...")
# Use the existing check function with a short timeout
- is_online = check_server_availability(server_addr, timeout=0.75) # Use slightly longer than 0.5?
+ is_online = check_server_availability(server_addr, timeout=get_timeout('ping')) # Use slightly longer than 0.5?
prefs.server_online = is_online # Update the preference property
@@ -525,6 +585,9 @@ class RefreshControlNetMappings(bpy.types.Operator):
self.report({'INFO'}, f"Refreshed ControlNet list: {len(models_to_add)} added, {len(models_to_remove)} removed.")
return {'FINISHED'}
+from .timeout_config import get_timeout # noqa: E402 – placed here to avoid circular imports
+
+
def check_server_availability(server_address, timeout=0.5):
"""
Quickly checks if the ComfyUI server is responding.
@@ -619,7 +682,7 @@ def fetch_from_comfyui_api(context, endpoint):
# Return None to signify a configuration issue preventing the API call
return None
- if not check_server_availability(server_address, timeout=0.5): # Use a strict timeout here
+ if not check_server_availability(server_address, timeout=get_timeout('ping')): # Use a strict timeout here
# Error message printed by check_server_availability
return None # Server unreachable or timed out on initial check
@@ -630,7 +693,7 @@ def fetch_from_comfyui_api(context, endpoint):
url = f"http://{server_address}{endpoint}"
try:
- response = requests.get(url, timeout=5) # Add a timeout
+ response = requests.get(url, timeout=get_timeout('api')) # Add a timeout
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
data = response.json()
@@ -2101,7 +2164,8 @@ def register():
description="Number of cameras to place around the generated mesh for texture projection",
default=8,
min=2,
- max=32
+ max=32,
+ update=update_parameters
)
bpy.types.Scene.trellis2_placement_mode = bpy.props.EnumProperty(
@@ -2115,19 +2179,22 @@ def register():
('greedy_coverage', "Greedy Coverage", "Iteratively add cameras that maximise new visible surface. Automatically determines the number of cameras needed"),
('fan_from_camera', "Fan from Camera", "Spread cameras in an arc around the active camera's orbit position"),
],
- default='normal_weighted'
+ default='normal_weighted',
+ update=update_parameters
)
bpy.types.Scene.trellis2_auto_prompts = bpy.props.BoolProperty(
name="Auto View Prompts",
description="Automatically generate view-direction prompts for each camera (e.g. 'front view', 'rear view, from above')",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_exclude_bottom = bpy.props.BoolProperty(
name="Exclude Bottom Faces",
description="Ignore downward-facing geometry when placing cameras",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_exclude_bottom_angle = bpy.props.FloatProperty(
@@ -2137,7 +2204,8 @@ def register():
min=0.1745,
max=1.5708,
subtype='ANGLE',
- unit='ROTATION'
+ unit='ROTATION',
+ update=update_parameters
)
bpy.types.Scene.trellis2_auto_aspect = bpy.props.EnumProperty(
@@ -2148,7 +2216,8 @@ def register():
('shared', "Shared", "Average silhouette aspect across all cameras and set a single scene resolution"),
('per_camera', "Per Camera", "Each camera gets its own optimal aspect ratio"),
],
- default='per_camera'
+ default='per_camera',
+ update=update_parameters
)
bpy.types.Scene.trellis2_occlusion_mode = bpy.props.EnumProperty(
@@ -2160,19 +2229,22 @@ def register():
('two_pass', "Two-Pass Refinement", "Fast back-face pass, then targeted BVH refinement"),
('vis_weighted', "Visibility-Weighted", "Weight faces by visibility fraction; mostly-occluded faces have reduced influence"),
],
- default='none'
+ default='none',
+ update=update_parameters
)
bpy.types.Scene.trellis2_consider_existing = bpy.props.BoolProperty(
name="Consider Existing Cameras",
description="Treat existing cameras as already-placed directions so auto modes avoid duplicating their coverage",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_delete_cameras = bpy.props.BoolProperty(
name="Delete Cameras After",
description="Automatically delete cameras placed during the TRELLIS.2 pipeline once generation and texturing are complete",
- default=False
+ default=False,
+ update=update_parameters
)
bpy.types.Scene.trellis2_coverage_target = bpy.props.FloatProperty(
@@ -2181,7 +2253,8 @@ def register():
default=0.95,
min=0.5,
max=1.0,
- subtype='FACTOR'
+ subtype='FACTOR',
+ update=update_parameters
)
bpy.types.Scene.trellis2_max_auto_cameras = bpy.props.IntProperty(
@@ -2189,7 +2262,8 @@ def register():
description="Upper limit on cameras for Greedy Coverage mode",
default=12,
min=2,
- max=50
+ max=50,
+ update=update_parameters
)
bpy.types.Scene.trellis2_fan_angle = bpy.props.FloatProperty(
@@ -2197,7 +2271,8 @@ def register():
description="Total angular spread of the fan in degrees",
default=90.0,
min=10.0,
- max=350.0
+ max=350.0,
+ update=update_parameters
)
bpy.types.Scene.trellis2_import_scale = bpy.props.FloatProperty(
@@ -2208,12 +2283,14 @@ def register():
max=100.0,
soft_min=0.0,
soft_max=10.0,
+ update=update_parameters
)
bpy.types.Scene.trellis2_clamp_elevation = bpy.props.BoolProperty(
name="Clamp Elevation",
description="Restrict camera elevation to avoid extreme top-down or bottom-up views that diffusion models often struggle with",
default=False,
+ update=update_parameters
)
bpy.types.Scene.trellis2_max_elevation = bpy.props.FloatProperty(
@@ -2224,6 +2301,7 @@ def register():
max=1.5708, # 90 degrees
subtype='ANGLE',
unit='ROTATION',
+ update=update_parameters
)
bpy.types.Scene.trellis2_min_elevation = bpy.props.FloatProperty(
@@ -2234,12 +2312,14 @@ def register():
max=0.0,
subtype='ANGLE',
unit='ROTATION',
+ update=update_parameters
)
bpy.types.Scene.trellis2_preview_gallery_enabled = bpy.props.BoolProperty(
name="Preview Gallery",
description="When in prompt mode, generate multiple images with different seeds and let you pick the best one before proceeding to 3D generation",
default=False,
+ update=update_parameters
)
bpy.types.Scene.trellis2_preview_gallery_count = bpy.props.IntProperty(
@@ -2248,6 +2328,7 @@ def register():
default=4,
min=1,
max=16,
+ update=update_parameters
)
bpy.types.Scene.qwen_guidance_map_type = bpy.props.EnumProperty(
@@ -2599,7 +2680,14 @@ def register():
bpy.types.Scene.qwen_use_trellis2_style = bpy.props.BoolProperty(
name="Use TRELLIS.2 Input as Style",
description="Use the TRELLIS.2 input image as the Qwen style reference",
- default=False
+ default=False,
+ update=update_parameters
+ )
+ bpy.types.Scene.qwen_trellis2_style_initial_only = bpy.props.BoolProperty(
+ name="TRELLIS.2 Style for Initial Only",
+ description="Use the TRELLIS.2 input image only for the first image, then fall back to sequential style for subsequent images",
+ default=False,
+ update=update_parameters
)
# 3-tier progress pipeline flags (written by Trellis2Generate, read by UI)
bpy.types.Scene.trellis2_pipeline_active = bpy.props.BoolProperty(
@@ -2631,7 +2719,8 @@ def register():
('1024_cascade', '1024 Cascade', 'Medium resolution with cascade (recommended)'),
('1536_cascade', '1536 Cascade', 'High resolution with cascade, most VRAM'),
],
- default='1024_cascade'
+ default='1024_cascade',
+ update=update_parameters
)
bpy.types.Scene.trellis2_vram_mode = bpy.props.EnumProperty(
name="VRAM Mode",
@@ -2640,7 +2729,8 @@ def register():
('keep_loaded', 'Keep Loaded', 'Keep all models in VRAM (fastest, ~12GB VRAM)'),
('disk_offload', 'Disk Offload', 'Load models on demand from disk (recommended for <=16GB VRAM)'),
],
- default='disk_offload'
+ default='disk_offload',
+ update=update_parameters
)
bpy.types.Scene.trellis2_attn_backend = bpy.props.EnumProperty(
name="Attention Backend",
@@ -2651,7 +2741,8 @@ def register():
('sdpa', 'SDPA', 'PyTorch native, always available'),
('sageattn', 'SageAttention', 'SageAttention backend (requires sageattn package)'),
],
- default='flash_attn'
+ default='flash_attn',
+ update=update_parameters
)
bpy.types.Scene.trellis2_seed = bpy.props.IntProperty(
name="Seed",
@@ -2666,14 +2757,16 @@ def register():
default=7.5,
min=1.0,
max=20.0,
- step=10
+ step=10,
+ update=update_parameters
)
bpy.types.Scene.trellis2_ss_steps = bpy.props.IntProperty(
name="SS Steps",
description="Sparse structure sampling steps. More steps = better quality but slower",
default=12,
min=1,
- max=50
+ max=50,
+ update=update_parameters
)
bpy.types.Scene.trellis2_shape_guidance = bpy.props.FloatProperty(
name="Shape Guidance",
@@ -2681,14 +2774,16 @@ def register():
default=7.5,
min=1.0,
max=20.0,
- step=10
+ step=10,
+ update=update_parameters
)
bpy.types.Scene.trellis2_shape_steps = bpy.props.IntProperty(
name="Shape Steps",
description="Shape sampling steps. More steps = better quality but slower",
default=12,
min=1,
- max=50
+ max=50,
+ update=update_parameters
)
bpy.types.Scene.trellis2_tex_guidance = bpy.props.FloatProperty(
name="Texture Guidance",
@@ -2696,14 +2791,16 @@ def register():
default=7.5,
min=1.0,
max=20.0,
- step=10
+ step=10,
+ update=update_parameters
)
bpy.types.Scene.trellis2_tex_steps = bpy.props.IntProperty(
name="Texture Steps",
description="Texture sampling steps. More steps = better quality but slower",
default=12,
min=1,
- max=50
+ max=50,
+ update=update_parameters
)
bpy.types.Scene.trellis2_max_tokens = bpy.props.IntProperty(
name="Max Tokens",
@@ -2713,7 +2810,8 @@ def register():
default=49152,
min=16384,
max=65536,
- step=4096
+ step=4096,
+ update=update_parameters
)
bpy.types.Scene.trellis2_texture_size = bpy.props.IntProperty(
name="Texture Size",
@@ -2722,7 +2820,8 @@ def register():
default=4096,
min=512,
max=8192,
- step=512
+ step=512,
+ update=update_parameters
)
bpy.types.Scene.trellis2_decimation = bpy.props.IntProperty(
name="Decimation Target",
@@ -2730,34 +2829,51 @@ def register():
default=100000,
min=1000,
max=5000000,
- step=10000
+ step=10000,
+ update=update_parameters
)
bpy.types.Scene.trellis2_remesh = bpy.props.BoolProperty(
name="Remesh",
description="Apply remeshing for cleaner topology",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_post_processing_enabled = bpy.props.BoolProperty(
name="Post-Processing",
description="Run ComfyUI-side mesh post-processing (decimation + remeshing). "
"Disable to import the raw mesh for manual retopology",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_auto_lighting = bpy.props.BoolProperty(
name="Auto Studio Lighting",
description="Create a three-point studio lighting rig (key, fill, rim) after import "
"to showcase PBR materials",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_skip_texture = bpy.props.BoolProperty(
name="Skip Texture",
description="Export shape-only mesh (no PBR textures). Much faster and uses less VRAM",
- default=False
+ default=False,
+ update=update_parameters
)
bpy.types.Scene.trellis2_low_vram = bpy.props.BoolProperty(
name="Low VRAM BG Removal",
description="Use low VRAM mode for background removal (BiRefNet)",
- default=False
+ default=False,
+ update=update_parameters
+ )
+ bpy.types.Scene.trellis2_bg_removal = bpy.props.EnumProperty(
+ name="Background Removal",
+ description="Method for removing the image background before TRELLIS.2 processing",
+ items=[
+ ('auto', 'Auto (BiRefNet)', 'Automatically remove background using BiRefNet model'),
+ ('skip', 'Skip (Use Alpha)', 'Skip background removal — use the input image\'s alpha channel as mask. '
+ 'Use this when your image already has a transparent background'),
+ ],
+ default='auto',
+ update=update_parameters
)
bpy.types.Scene.trellis2_background_color = bpy.props.EnumProperty(
name="Background Color",
@@ -2767,17 +2883,20 @@ def register():
('gray', 'Gray', 'Gray background'),
('white', 'White', 'White background'),
],
- default='black'
+ default='black',
+ update=update_parameters
)
bpy.types.Scene.trellis2_include_1024 = bpy.props.BoolProperty(
name="Include 1024 Conditioning",
description="Include 1024-resolution conditioning. Disable for lower VRAM usage with 512 resolution",
- default=True
+ default=True,
+ update=update_parameters
)
bpy.types.Scene.trellis2_fill_holes = bpy.props.BoolProperty(
name="Fill Holes",
description="Fill holes in the mesh during simplification (shape-only mode)",
- default=True
+ default=True,
+ update=update_parameters
)
def unregister():
@@ -2908,7 +3027,7 @@ def unregister():
'trellis2_available', 'show_trellis2_params', 'show_trellis2_advanced',
'show_trellis2_mesh_settings', 'show_trellis2_texture_settings',
'show_trellis2_camera_settings',
- 'trellis2_last_input_image', 'qwen_use_trellis2_style',
+ 'trellis2_last_input_image', 'qwen_use_trellis2_style', 'qwen_trellis2_style_initial_only',
'trellis2_pipeline_active', 'trellis2_pipeline_phase_start_pct',
'trellis2_pipeline_total_phases',
'trellis2_generate_from', 'trellis2_texture_mode', 'trellis2_initial_image_arch',
@@ -2929,7 +3048,7 @@ def unregister():
'trellis2_texture_size', 'trellis2_decimation', 'trellis2_remesh',
'trellis2_post_processing_enabled',
'trellis2_auto_lighting',
- 'trellis2_skip_texture', 'trellis2_low_vram', 'trellis2_background_color',
+ 'trellis2_skip_texture', 'trellis2_low_vram', 'trellis2_bg_removal', 'trellis2_background_color',
'trellis2_include_1024', 'trellis2_fill_holes',
]
for prop in trellis2_props:
diff --git a/stablegen/generator.py b/stablegen/generator.py
index 200dd52..73b6f6b 100644
--- a/stablegen/generator.py
+++ b/stablegen/generator.py
@@ -27,6 +27,7 @@ from .utils import get_last_material_index, get_generation_dirs, get_file_path,
from .project import project_image, reinstate_compare_nodes # pylint: disable=relative-beyond-top-level
from .workflows import WorkflowManager
from .util.mirror_color import MirrorReproject, _get_viewport_ref_np, _apply_color_match_to_file
+from .timeout_config import get_timeout
# Import wheels
import websocket
@@ -298,7 +299,7 @@ def upload_image_to_comfyui(server_address, image_path, image_type="input"):
data = {'overwrite': 'true', 'type': image_type}
# Increased timeout for potentially large images or slow networks
- response = requests.post(upload_url, files=files, data=data, timeout=120)
+ response = requests.post(upload_url, files=files, data=data, timeout=get_timeout('transfer'))
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
response_data = response.json()
@@ -2567,14 +2568,14 @@ class Trellis2Generate(bpy.types.Operator):
f"http://{srv}/free", data=flush_data,
headers={"Content-Type": "application/json"}
)
- urllib.request.urlopen(flush_req, timeout=10)
+ urllib.request.urlopen(flush_req, timeout=get_timeout('api'))
# 2. Clear history/cache
hist_data = json.dumps({"clear": True}).encode('utf-8')
hist_req = urllib.request.Request(
f"http://{srv}/history", data=hist_data,
headers={"Content-Type": "application/json"}
)
- urllib.request.urlopen(hist_req, timeout=10)
+ urllib.request.urlopen(hist_req, timeout=get_timeout('api'))
# 3. Wait for VRAM release
import time
time.sleep(3)
diff --git a/stablegen/stablegen.py b/stablegen/stablegen.py
index f7f24b0..7c8660d 100644
--- a/stablegen/stablegen.py
+++ b/stablegen/stablegen.py
@@ -148,6 +148,7 @@ GEN_PARAMETERS = [
"trellis2_remesh",
"trellis2_post_processing_enabled",
"trellis2_low_vram",
+ "trellis2_bg_removal",
"trellis2_background_color",
"trellis2_include_1024",
"trellis2_fill_holes",
@@ -174,6 +175,7 @@ GEN_PARAMETERS = [
"texture_objects",
"use_flux_lora",
"qwen_use_trellis2_style",
+ "qwen_trellis2_style_initial_only",
"trellis2_skip_texture",
]
@@ -748,8 +750,12 @@ class StableGenPanel(bpy.types.Panel):
# Misc
content_box.label(text="Misc:", icon="PREFERENCES")
- row = content_box.row()
- row.prop(scene, "trellis2_low_vram", text="Low VRAM Background Removal", toggle=True, icon="GHOST_ENABLED")
+ split = content_box.split(factor=0.5)
+ split.label(text="BG Removal:")
+ split.prop(scene, "trellis2_bg_removal", text="")
+ if scene.trellis2_bg_removal == 'auto':
+ row = content_box.row()
+ row.prop(scene, "trellis2_low_vram", text="Low VRAM Background Removal", toggle=True, icon="GHOST_ENABLED")
# --- TRELLIS.2: Native Texture Settings ---
if is_trellis2 and trellis2_tex_mode == 'native':
@@ -1051,6 +1057,19 @@ class StableGenPanel(bpy.types.Panel):
subsequent_box.prop(scene, "sequential_desaturate_factor", text="Desaturate")
subsequent_box.prop(scene, "sequential_contrast_factor", text="Reduce Contrast")
+ if getattr(scene, 'architecture_mode', '') == 'trellis2' and scene.qwen_use_trellis2_style:
+ t2_style_box = content_box.box()
+ row = t2_style_box.row()
+ row.prop(scene, "qwen_trellis2_style_initial_only", text="TRELLIS.2 Style for Initial Only", toggle=True)
+ if scene.qwen_trellis2_style_initial_only:
+ subsequent_box = t2_style_box.box()
+ split = subsequent_box.split(factor=0.5)
+ split.label(text="Subsequent mode:")
+ split.prop(scene, "sequential_ipadapter_mode", text="")
+ if scene.sequential_ipadapter_mode == 'recent':
+ subsequent_box.prop(scene, "sequential_desaturate_factor", text="Desaturate")
+ subsequent_box.prop(scene, "sequential_contrast_factor", text="Reduce Contrast")
+
if not scene.qwen_use_external_style_image and scene.generation_method in ['sequential', 'separate']:
row = content_box.row()
row.prop(scene, "sequential_ipadapter", text="Use Previous Image as Style", toggle=True, icon="MODIFIER")
diff --git a/stablegen/timeout_config.py b/stablegen/timeout_config.py
new file mode 100644
index 0000000..9eab434
--- /dev/null
+++ b/stablegen/timeout_config.py
@@ -0,0 +1,23 @@
+"""Timeout configuration helper for StableGen."""
+
+import bpy # pylint: disable=import-error
+
+_DEFAULTS = {'ping': 1.0, 'api': 10.0, 'transfer': 120.0, 'reboot': 120.0}
+
+
+def get_timeout(category, default=None):
+ """Return a timeout value (seconds) from the addon preferences.
+
+ Args:
+ category: One of ``'ping'``, ``'api'``, ``'transfer'``, ``'reboot'``.
+ default: Fallback value if the preference cannot be read.
+ When *None*, built-in defaults are:
+ ping=1.0, api=10.0, transfer=120.0, reboot=120.0.
+ """
+ if default is None:
+ default = _DEFAULTS.get(category, 10.0)
+ try:
+ prefs = bpy.context.preferences.addons[__package__].preferences
+ return getattr(prefs, f'timeout_{category}', default)
+ except Exception:
+ return default
diff --git a/stablegen/workflows.py b/stablegen/workflows.py
index b90535b..e6c283a 100644
--- a/stablegen/workflows.py
+++ b/stablegen/workflows.py
@@ -12,6 +12,7 @@ from datetime import datetime, timedelta
from .util.helpers import prompt_text_qwen_image_edit, prompt_text_trellis2, prompt_text_trellis2_shape_only
from .utils import get_generation_dirs
+from .timeout_config import get_timeout
from io import BytesIO
import numpy as np
@@ -532,16 +533,22 @@ class WorkflowManager:
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# Case 1b: TRELLIS.2 input image as style (when no external style configured)
- elif getattr(context.scene, 'qwen_use_trellis2_style', False) and is_initial_image:
- t2_path = getattr(context.scene, 'trellis2_last_input_image', '')
- if t2_path and os.path.exists(bpy.path.abspath(t2_path)):
- style_image_info = self.operator._get_uploaded_image_info(context, "custom", filename=bpy.path.abspath(t2_path))
- if style_image_info:
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = (context.scene.qwen_custom_prompt_initial).format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
- prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
+ elif getattr(context.scene, 'qwen_use_trellis2_style', False):
+ use_t2_this_frame = True
+ if not is_initial_image and getattr(context.scene, 'qwen_trellis2_style_initial_only', False):
+ # Initial-only mode: fall back to sequential style for subsequent frames
+ use_t2_this_frame = False
+ context.scene.sequential_ipadapter = True
+ if use_t2_this_frame:
+ t2_path = getattr(context.scene, 'trellis2_last_input_image', '')
+ if t2_path and os.path.exists(bpy.path.abspath(t2_path)):
+ style_image_info = self.operator._get_uploaded_image_info(context, "custom", filename=bpy.path.abspath(t2_path))
+ if style_image_info:
+ if context.scene.qwen_use_custom_prompts:
+ pos_prompt_text = (context.scene.qwen_custom_prompt_initial).format(main_prompt=user_prompt)
+ else:
+ pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# Case 2: Sequential generation (after first image)
elif not is_initial_image:
@@ -717,8 +724,10 @@ class WorkflowManager:
# Return the generated image from the save_image node
return images[NODES['save_image']][0]
- def _check_server_alive(self, server_address, timeout=5):
+ def _check_server_alive(self, server_address, timeout=None):
"""Return True if the ComfyUI server responds to a lightweight request."""
+ if timeout is None:
+ timeout = get_timeout('ping')
try:
req = urllib.request.Request(
f"http://{server_address}/system_stats",
@@ -735,7 +744,7 @@ class WorkflowManager:
req = urllib.request.Request(
f"http://{server_address}/system_stats", method='GET'
)
- resp = json.loads(urllib.request.urlopen(req, timeout=5).read())
+ resp = json.loads(urllib.request.urlopen(req, timeout=get_timeout('api')).read())
dev = resp.get("devices", [{}])[0]
vram_free = dev.get("vram_free", 0) / (1024 * 1024)
vram_total = dev.get("vram_total", 0) / (1024 * 1024)
@@ -775,7 +784,7 @@ class WorkflowManager:
f"http://{server_address}/free", data=d,
headers={'Content-Type': 'application/json'}, method='POST'
)
- urllib.request.urlopen(r, timeout=10)
+ urllib.request.urlopen(r, timeout=get_timeout('api'))
def _clear_history():
d = json.dumps({"clear": True}).encode('utf-8')
@@ -783,7 +792,7 @@ class WorkflowManager:
f"http://{server_address}/history", data=d,
headers={'Content-Type': 'application/json'}, method='POST'
)
- urllib.request.urlopen(r, timeout=10)
+ urllib.request.urlopen(r, timeout=get_timeout('api'))
def _clear_queue():
d = json.dumps({"clear": True}).encode('utf-8')
@@ -791,7 +800,7 @@ class WorkflowManager:
f"http://{server_address}/queue", data=d,
headers={'Content-Type': 'application/json'}, method='POST'
)
- urllib.request.urlopen(r, timeout=10)
+ urllib.request.urlopen(r, timeout=get_timeout('api'))
for attempt in range(1, retries + 1):
try:
@@ -1395,7 +1404,7 @@ class WorkflowManager:
print(f"[TRELLIS2] Failed to clear Triton cache {cache_dir}: {e}")
return cleared
- def _reboot_comfyui(self, server_address, poll_timeout=120):
+ def _reboot_comfyui(self, server_address, poll_timeout=None):
"""
Attempt to reboot ComfyUI via the ComfyUI Manager ``/manager/reboot``
endpoint, then wait for the server to come back online.
@@ -1406,12 +1415,15 @@ class WorkflowManager:
"""
import time
+ if poll_timeout is None:
+ poll_timeout = get_timeout('reboot')
+
reboot_url = f"http://{server_address}/manager/reboot"
print(f"[TRELLIS2] Requesting ComfyUI reboot via {reboot_url} ...")
try:
req = urllib.request.Request(reboot_url, method='GET')
- resp = urllib.request.urlopen(req, timeout=10)
+ resp = urllib.request.urlopen(req, timeout=get_timeout('api'))
status = resp.getcode()
if status not in (200, 201, 204):
print(f"[TRELLIS2] Reboot endpoint returned unexpected status {status}")
@@ -1622,8 +1634,20 @@ class WorkflowManager:
prompt[NODES['load_models']]["inputs"]["vram_mode"] = scene.trellis2_vram_mode
prompt[NODES['load_models']]["inputs"]["attn_backend"] = scene.trellis2_attn_backend
- # Configure remove background
- prompt[NODES['remove_bg']]["inputs"]["low_vram"] = scene.trellis2_low_vram
+ # Configure background removal (or bypass it)
+ skip_bg = getattr(scene, 'trellis2_bg_removal', 'auto') == 'skip'
+ if skip_bg:
+ # Remove the RemoveBackground node from the workflow.
+ # Wire GetConditioning to use LoadImage outputs directly:
+ # LoadImage[0] → image, LoadImage[1] → mask (alpha channel).
+ # If the input has no alpha, ComfyUI's LoadImage provides an
+ # all-white mask (= entire image is foreground).
+ remove_bg_node_id = NODES.pop('remove_bg')
+ del prompt[remove_bg_node_id]
+ prompt[NODES['get_conditioning']]["inputs"]["image"] = [NODES['input_image'], 0]
+ prompt[NODES['get_conditioning']]["inputs"]["mask"] = [NODES['input_image'], 1]
+ else:
+ prompt[NODES['remove_bg']]["inputs"]["low_vram"] = scene.trellis2_low_vram
# Configure conditioning
prompt[NODES['get_conditioning']]["inputs"]["background_color"] = scene.trellis2_background_color
@@ -1700,23 +1724,25 @@ class WorkflowManager:
NODE_PROGRESS = {
NODES['input_image']: 2,
NODES['load_models']: 3,
- NODES['remove_bg']: 12,
NODES['get_conditioning']: 25,
NODES['image_to_shape']: 80,
NODES['simplify']: 90,
NODES['export_trimesh']: 98,
}
+ if not skip_bg:
+ NODE_PROGRESS[NODES['remove_bg']] = 12
else:
# Full textured pipeline (single submission)
NODE_PROGRESS = {
NODES['input_image']: 2,
NODES['load_models']: 3,
- NODES['remove_bg']: 10,
NODES['get_conditioning']: 18,
NODES['image_to_shape']: 55,
NODES['shape_to_textured_mesh']: 85,
NODES['export_glb']: 98,
}
+ if not skip_bg:
+ NODE_PROGRESS[NODES['remove_bg']] = 10
# Wait for execution to complete via WebSocket
# Also capture 'executed' events which may contain the output path
@@ -2362,7 +2388,7 @@ class WorkflowManager:
"""
try:
history_url = f"http://{server_address}/history/{prompt_id}"
- history = json.loads(urllib.request.urlopen(history_url, timeout=30).read())
+ history = json.loads(urllib.request.urlopen(history_url, timeout=get_timeout('transfer')).read())
outputs = history.get(prompt_id, {}).get("outputs", {}).get(node_id, {})
image_list = outputs.get("images", [])
result = []
@@ -2374,7 +2400,7 @@ class WorkflowManager:
f"filename={urllib.parse.quote(filename)}"
f"&subfolder={urllib.parse.quote(subfolder)}"
f"&type={urllib.parse.quote(img_type)}")
- data = urllib.request.urlopen(view_url, timeout=60).read()
+ data = urllib.request.urlopen(view_url, timeout=get_timeout('transfer')).read()
result.append(data)
return result
except Exception as e: