Skip to content

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

feat: preview gallery, studio lighting, elevation clamping, mesh scaling

sakalond041978fcb676
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index f146f3c..ddca576 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -75,11 +75,26 @@ def update_architecture_mode(self, context):
if scene.model_architecture != mode:
scene.model_architecture = mode # triggers update_combined
else:
- # Entering TRELLIS.2 mode — sync backbone only if texture_mode is diffusion
- tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'):
- if scene.model_architecture != tex_mode:
- scene.model_architecture = tex_mode # triggers update_combined
+ # Entering TRELLIS.2 mode — sync backbone for any diffusion need
+ _sync_trellis2_backbone(scene)
+
+
+def _sync_trellis2_backbone(scene):
+ """Pick the right diffusion backbone for the current TRELLIS.2 state.
+
+ If the texture-mode is a diffusion arch, use that. Otherwise fall
+ back to the initial-image arch (relevant when generate_from == prompt
+ and texture_mode is native/none).
+ """
+ tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
+ if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'):
+ target = tex_mode
+ elif getattr(scene, 'trellis2_generate_from', 'image') == 'prompt':
+ target = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
+ else:
+ return # no diffusion backbone needed
+ if scene.model_architecture != target:
+ scene.model_architecture = target # triggers update_combined
def update_trellis2_texture_mode(self, context):
@@ -89,9 +104,8 @@ def update_trellis2_texture_mode(self, context):
* If the chosen mode is a diffusion architecture and differs from the
current backbone, syncs ``model_architecture`` (which triggers a
checkpoint refresh).
- * If ``generate_from`` is *prompt* and the user picks ``none`` or
- ``native`` (no diffusion), auto-switch to ``sdxl`` so there is always
- a diffusion model available for the image-generation step.
+ * When ``generate_from`` is *prompt* and texture_mode is non-diffusion,
+ syncs the backbone from ``trellis2_initial_image_arch`` instead.
"""
scene = context.scene
if getattr(scene, 'architecture_mode', '') != 'trellis2':
@@ -99,34 +113,36 @@ def update_trellis2_texture_mode(self, context):
tex_mode = scene.trellis2_texture_mode
- # When prompt mode, a diffusion backbone is mandatory
- if getattr(scene, 'trellis2_generate_from', 'image') == 'prompt' and tex_mode in ('none', 'native'):
- scene.trellis2_texture_mode = 'sdxl'
- return # re-entrant; callback fires again
-
# Sync skip_texture flag used by the workflow code
scene.trellis2_skip_texture = (tex_mode != 'native')
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'):
- if scene.model_architecture != tex_mode:
- scene.model_architecture = tex_mode # triggers update_combined
+ _sync_trellis2_backbone(scene)
+
+
+def update_trellis2_initial_image_arch(self, context):
+ """Called when the user changes the initial-image architecture for TRELLIS.2.
+
+ Syncs the diffusion backbone when texture_mode is native/none so the
+ checkpoint list refreshes to match the chosen architecture.
+ """
+ scene = context.scene
+ if getattr(scene, 'architecture_mode', '') != 'trellis2':
+ return
+ _sync_trellis2_backbone(scene)
def update_trellis2_generate_from(self, context):
"""Called when the user switches between Image and Prompt input mode.
- If switching to *prompt* while the texture mode is ``none`` or
- ``native`` (no diffusion model selected), force ``trellis2_texture_mode``
- to ``sdxl`` so a checkpoint is available for image generation.
+ Syncs the diffusion backbone via ``_sync_trellis2_backbone`` so a
+ checkpoint is available for the initial-image generation step.
"""
scene = context.scene
if getattr(scene, 'architecture_mode', '') != 'trellis2':
return
if scene.trellis2_generate_from == 'prompt':
- tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- if tex_mode in ('none', 'native'):
- scene.trellis2_texture_mode = 'sdxl' # triggers update_trellis2_texture_mode
+ _sync_trellis2_backbone(scene)
def update_combined(self, context):
@@ -2068,6 +2084,18 @@ def register():
update=update_trellis2_texture_mode
)
+ bpy.types.Scene.trellis2_initial_image_arch = bpy.props.EnumProperty(
+ name="Initial Image Architecture",
+ description="Diffusion architecture used to generate the initial image when Generate From is set to Prompt and Texture Mode is Native or None",
+ items=[
+ ('sdxl', 'SDXL', 'Stable Diffusion XL'),
+ ('flux1', 'Flux 1', 'Flux 1 architecture'),
+ ('qwen_image_edit', 'Qwen Image Edit', 'Qwen Image Edit architecture'),
+ ],
+ default='sdxl',
+ update=update_trellis2_initial_image_arch
+ )
+
bpy.types.Scene.trellis2_camera_count = bpy.props.IntProperty(
name="Camera Count",
description="Number of cameras to place around the generated mesh for texture projection",
@@ -2076,6 +2104,152 @@ def register():
max=32
)
+ bpy.types.Scene.trellis2_placement_mode = bpy.props.EnumProperty(
+ name="Placement Mode",
+ description="Strategy for placing cameras around the generated mesh",
+ items=[
+ ('orbit_ring', "Orbit Ring", "Place cameras in a circle around the center"),
+ ('hemisphere', "Sphere Coverage", "Distribute cameras evenly across a sphere using a Fibonacci spiral"),
+ ('normal_weighted', "Normal-Weighted", "Automatically place cameras to cover the most surface area, using K-means on face normals weighted by area"),
+ ('pca_axes', "PCA Axes", "Place cameras along the mesh's principal axes of variation"),
+ ('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'
+ )
+
+ 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
+ )
+
+ bpy.types.Scene.trellis2_exclude_bottom = bpy.props.BoolProperty(
+ name="Exclude Bottom Faces",
+ description="Ignore downward-facing geometry when placing cameras",
+ default=True
+ )
+
+ bpy.types.Scene.trellis2_exclude_bottom_angle = bpy.props.FloatProperty(
+ name="Bottom Angle Threshold",
+ description="Faces whose normal points more than this many degrees below the horizon are excluded",
+ default=1.5533, # 89 degrees in radians
+ min=0.1745,
+ max=1.5708,
+ subtype='ANGLE',
+ unit='ROTATION'
+ )
+
+ bpy.types.Scene.trellis2_auto_aspect = bpy.props.EnumProperty(
+ name="Auto Aspect Ratio",
+ description="Automatically adjust render aspect ratio to match the mesh silhouette",
+ items=[
+ ('off', "Off", "Use current scene resolution for all cameras"),
+ ('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'
+ )
+
+ bpy.types.Scene.trellis2_occlusion_mode = bpy.props.EnumProperty(
+ name="Occlusion Handling",
+ description="How to account for self-occlusion when choosing camera directions",
+ items=[
+ ('none', "None (Fast)", "Back-face culling only — ignores self-occlusion"),
+ ('full_matrix', "Full Occlusion Matrix", "Build a complete BVH-validated visibility matrix. Most accurate but slower"),
+ ('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'
+ )
+
+ 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
+ )
+
+ 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
+ )
+
+ bpy.types.Scene.trellis2_coverage_target = bpy.props.FloatProperty(
+ name="Coverage Target",
+ description="Stop adding cameras when this fraction of surface area is visible (Greedy mode)",
+ default=0.95,
+ min=0.5,
+ max=1.0,
+ subtype='FACTOR'
+ )
+
+ bpy.types.Scene.trellis2_max_auto_cameras = bpy.props.IntProperty(
+ name="Max Cameras (Greedy)",
+ description="Upper limit on cameras for Greedy Coverage mode",
+ default=12,
+ min=2,
+ max=50
+ )
+
+ bpy.types.Scene.trellis2_fan_angle = bpy.props.FloatProperty(
+ name="Fan Angle",
+ description="Total angular spread of the fan in degrees",
+ default=90.0,
+ min=10.0,
+ max=350.0
+ )
+
+ bpy.types.Scene.trellis2_import_scale = bpy.props.FloatProperty(
+ name="Import Scale (BU)",
+ description="Scale imported TRELLIS.2 meshes so the longest axis equals this many Blender units. Set to 0 to keep the original size",
+ default=2.0,
+ min=0.0,
+ max=100.0,
+ soft_min=0.0,
+ soft_max=10.0,
+ )
+
+ 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,
+ )
+
+ bpy.types.Scene.trellis2_max_elevation = bpy.props.FloatProperty(
+ name="Max Elevation",
+ description="Maximum upward elevation angle. Cameras looking further up will be clamped",
+ default=1.2217, # 70 degrees
+ min=0.0,
+ max=1.5708, # 90 degrees
+ subtype='ANGLE',
+ unit='ROTATION',
+ )
+
+ bpy.types.Scene.trellis2_min_elevation = bpy.props.FloatProperty(
+ name="Min Elevation",
+ description="Minimum downward elevation angle. Cameras looking further down will be clamped",
+ default=-0.1745, # -10 degrees
+ min=-1.5708, # -90 degrees
+ max=0.0,
+ subtype='ANGLE',
+ unit='ROTATION',
+ )
+
+ 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,
+ )
+
+ bpy.types.Scene.trellis2_preview_gallery_count = bpy.props.IntProperty(
+ name="Gallery Count",
+ description="Number of images to generate per batch in the preview gallery",
+ default=4,
+ min=1,
+ max=16,
+ )
+
bpy.types.Scene.qwen_guidance_map_type = bpy.props.EnumProperty(
name="Guidance Map",
description="The type of guidance map to use for Qwen Image Edit",
@@ -2411,6 +2585,11 @@ def register():
description="Toggle TRELLIS.2 native texture settings",
default=False
)
+ bpy.types.Scene.show_trellis2_camera_settings = bpy.props.BoolProperty(
+ name="Show Camera Placement Settings",
+ description="Toggle TRELLIS.2 camera placement settings",
+ default=False
+ )
bpy.types.Scene.trellis2_last_input_image = bpy.props.StringProperty(
name="TRELLIS.2 Last Input Image",
description="Path to the image most recently used as TRELLIS.2 input (set automatically after generation)",
@@ -2528,16 +2707,19 @@ def register():
)
bpy.types.Scene.trellis2_max_tokens = bpy.props.IntProperty(
name="Max Tokens",
- description="Maximum tokens for shape generation. Lower = less VRAM. 24576 (~6GB) recommended for 16GB GPUs",
- default=24576,
+ description="Max sparse-voxel tokens during cascade upsampling (only affects cascade modes). "
+ "Higher = more detail but more VRAM. "
+ "Try 32768 or 24576 if running out of VRAM",
+ default=49152,
min=16384,
max=65536,
step=4096
)
bpy.types.Scene.trellis2_texture_size = bpy.props.IntProperty(
name="Texture Size",
- description="Output texture resolution in pixels",
- default=2048,
+ description="Resolution of the UV-baked texture in pixels. Higher values reduce aliasing at UV seams. "
+ "The native voxel grid is 1024, so values above 1024 interpolate existing data",
+ default=4096,
min=512,
max=8192,
step=512
@@ -2561,6 +2743,12 @@ def register():
"Disable to import the raw mesh for manual retopology",
default=True
)
+ 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
+ )
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",
@@ -2719,16 +2907,28 @@ def unregister():
trellis2_props = [
'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_pipeline_active', 'trellis2_pipeline_phase_start_pct',
'trellis2_pipeline_total_phases',
- 'trellis2_generate_from', 'trellis2_texture_mode', 'trellis2_camera_count',
+ 'trellis2_generate_from', 'trellis2_texture_mode', 'trellis2_initial_image_arch',
+ 'trellis2_camera_count',
+ 'trellis2_placement_mode', 'trellis2_auto_prompts',
+ 'trellis2_exclude_bottom', 'trellis2_exclude_bottom_angle',
+ 'trellis2_auto_aspect', 'trellis2_occlusion_mode',
+ 'trellis2_consider_existing', 'trellis2_delete_cameras',
+ 'trellis2_coverage_target',
+ 'trellis2_max_auto_cameras', 'trellis2_fan_angle',
+ 'trellis2_import_scale',
+ 'trellis2_clamp_elevation', 'trellis2_max_elevation', 'trellis2_min_elevation',
+ 'trellis2_preview_gallery_enabled', 'trellis2_preview_gallery_count',
'trellis2_input_image', 'trellis2_resolution', 'trellis2_vram_mode',
'trellis2_attn_backend', 'trellis2_seed', 'trellis2_ss_guidance',
'trellis2_ss_steps', 'trellis2_shape_guidance', 'trellis2_shape_steps',
'trellis2_tex_guidance', 'trellis2_tex_steps', 'trellis2_max_tokens',
'trellis2_texture_size', 'trellis2_decimation', 'trellis2_remesh',
'trellis2_post_processing_enabled',
+ 'trellis2_auto_lighting',
'trellis2_skip_texture', 'trellis2_low_vram', 'trellis2_background_color',
'trellis2_include_1024', 'trellis2_fill_holes',
]
diff --git a/stablegen/generator.py b/stablegen/generator.py
index 93da0dd..200dd52 100644
--- a/stablegen/generator.py
+++ b/stablegen/generator.py
@@ -17,6 +17,10 @@ import math
import colorsys
from PIL import Image, ImageEnhance
+import gpu # pylint: disable=import-error
+import blf # pylint: disable=import-error
+from gpu_extras.batch import batch_for_shader # pylint: disable=import-error
+
from .util.helpers import prompt_text, prompt_text_img2img, prompt_text_qwen_image_edit # pylint: disable=relative-beyond-top-level
from .render_tools import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, render_edge_feather_mask, _SGCameraResolution, _get_camera_resolution, _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay # pylint: disable=relative-beyond-top-level
from .utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs, get_compositor_node_tree, configure_output_node_paths, get_eevee_engine_id # pylint: disable=relative-beyond-top-level
@@ -1795,6 +1799,298 @@ class ComfyUIGenerate(bpy.types.Operator):
return None
+# ── Preview Gallery helpers ───────────────────────────────────────────
+
+def _draw_rect_2d(x1, y1, x2, y2, color):
+ """Draw a filled rectangle in 2D screen-space."""
+ shader = gpu.shader.from_builtin('UNIFORM_COLOR')
+ batch = batch_for_shader(
+ shader, 'TRIS',
+ {"pos": ((x1, y1), (x2, y1), (x2, y2), (x1, y2))},
+ indices=((0, 1, 2), (0, 2, 3)),
+ )
+ shader.bind()
+ shader.uniform_float("color", color)
+ gpu.state.blend_set('ALPHA')
+ batch.draw(shader)
+ gpu.state.blend_set('NONE')
+
+
+def _draw_texture_2d(texture, x1, y1, x2, y2):
+ """Draw a textured rectangle in 2D screen-space."""
+ shader = gpu.shader.from_builtin('IMAGE')
+ batch = batch_for_shader(
+ shader, 'TRIS',
+ {"pos": ((x1, y1), (x2, y1), (x2, y2), (x1, y2)),
+ "texCoord": ((0, 0), (1, 0), (1, 1), (0, 1))},
+ indices=((0, 1, 2), (0, 2, 3)),
+ )
+ shader.bind()
+ shader.uniform_sampler("image", texture)
+ gpu.state.blend_set('ALPHA')
+ batch.draw(shader)
+ gpu.state.blend_set('NONE')
+
+
+class _PreviewGalleryOverlay:
+ """Viewport overlay that shows N generated images and lets the user pick one.
+
+ Lifecycle:
+ 1. ``__init__`` — creates bpy.data.images + GPU textures, registers draw handler.
+ 2. ``handle_mouse_move`` / ``handle_click`` — called from Trellis2Generate.modal().
+ 3. ``update_images`` — called when "Generate More" produces a new batch.
+ 4. ``cleanup`` — removes draw handler and temp images.
+ """
+
+ def __init__(self, pil_images, seeds):
+ """*pil_images*: list[PIL.Image] *seeds*: list[int]"""
+ self._pil_images = list(pil_images)
+ self._seeds = list(seeds)
+ self._n = len(pil_images)
+ self._hover_idx = -1
+ self._more_hover = False
+ self._cancel_hover = False
+ self._selected_idx = -1
+ self.action = None # 'select' | 'more' | 'cancel'
+ self._cols = max(1, math.ceil(math.sqrt(self._n)))
+ self._rows = max(1, math.ceil(self._n / self._cols))
+ self._cell_rects: list[tuple] = []
+ self._more_rect: tuple | None = None
+ self._cancel_rect: tuple | None = None
+ self._bpy_images: list = []
+ self._textures: list = []
+ self._setup_textures()
+ self._draw_handle = bpy.types.SpaceView3D.draw_handler_add(
+ self._draw, (), 'WINDOW', 'POST_PIXEL')
+
+ # ── texture management ──
+
+ def _setup_textures(self):
+ self._clear_textures()
+ for i, pil_img in enumerate(self._pil_images):
+ name = f"_sg_gallery_{i}"
+ if name in bpy.data.images:
+ bpy.data.images.remove(bpy.data.images[name])
+ rgba = pil_img.convert('RGBA')
+ w, h = rgba.size
+ bpy_img = bpy.data.images.new(name, w, h, alpha=True)
+ # Mark as Non-Color so gpu.texture.from_image() stores raw
+ # sRGB values — the viewport's own output transform will
+ # apply the single correct sRGB curve on display.
+ bpy_img.colorspace_settings.name = 'Non-Color'
+ # Blender images are stored bottom-to-top; PIL is top-to-bottom
+ flipped = rgba.transpose(Image.FLIP_TOP_BOTTOM)
+ flat = np.array(flipped, dtype=np.float32).ravel() / 255.0
+ bpy_img.pixels.foreach_set(flat)
+ bpy_img.pack()
+ self._bpy_images.append(bpy_img)
+ self._textures.append(gpu.texture.from_image(bpy_img))
+
+ def _clear_textures(self):
+ self._textures.clear()
+ for img in self._bpy_images:
+ if img.name in bpy.data.images:
+ bpy.data.images.remove(img)
+ self._bpy_images.clear()
+
+ def update_images(self, pil_images, seeds):
+ """Replace the gallery with a new batch."""
+ self._pil_images = list(pil_images)
+ self._seeds = list(seeds)
+ self._n = len(pil_images)
+ self._cols = max(1, math.ceil(math.sqrt(self._n)))
+ self._rows = max(1, math.ceil(self._n / self._cols))
+ self._hover_idx = -1
+ self._more_hover = False
+ self._cancel_hover = False
+ self._selected_idx = -1
+ self.action = None
+ self._setup_textures()
+
+ def cleanup(self):
+ if self._draw_handle:
+ bpy.types.SpaceView3D.draw_handler_remove(self._draw_handle, 'WINDOW')
+ self._draw_handle = None
+ self._clear_textures()
+
+ # ── interaction ──
+
+ def handle_mouse_move(self, mx, my):
+ """Update hover state. Returns True if display should redraw."""
+ old = (self._hover_idx, self._more_hover, self._cancel_hover)
+ self._hover_idx = -1
+ self._more_hover = False
+ self._cancel_hover = False
+ for i, rect in enumerate(self._cell_rects):
+ x1, y1, x2, y2 = rect
+ if x1 <= mx <= x2 and y1 <= my <= y2:
+ self._hover_idx = i
+ break
+ if self._more_rect:
+ x1, y1, x2, y2 = self._more_rect
+ if x1 <= mx <= x2 and y1 <= my <= y2:
+ self._more_hover = True
+ if self._cancel_rect:
+ x1, y1, x2, y2 = self._cancel_rect
+ if x1 <= mx <= x2 and y1 <= my <= y2:
+ self._cancel_hover = True
+ return old != (self._hover_idx, self._more_hover, self._cancel_hover)
+
+ def handle_click(self, mx, my):
+ """Returns 'select', 'more', 'cancel', or None."""
+ if self._more_hover:
+ return 'more'
+ if self._cancel_hover:
+ return 'cancel'
+ if self._hover_idx >= 0:
+ self._selected_idx = self._hover_idx
+ return 'select'
+ return None
+
+ @property
+ def selected_seed(self):
+ if 0 <= self._selected_idx < len(self._seeds):
+ return self._seeds[self._selected_idx]
+ return None
+
+ @property
+ def selected_image_bytes(self):
+ """Return PNG bytes of the selected image (for TRELLIS workflow)."""
+ if 0 <= self._selected_idx < len(self._pil_images):
+ buf = io.BytesIO()
+ self._pil_images[self._selected_idx].save(buf, format='PNG')
+ return buf.getvalue()
+ return None
+
+ # ── drawing ──
+
+ def _draw(self):
+ """POST_PIXEL callback — draws the full-screen gallery overlay."""
+ context = bpy.context
+ region = context.region
+ if not region:
+ return
+ vw, vh = region.width, region.height
+ if vw < 100 or vh < 100:
+ return
+
+ # Detect sidebar (N-panel) width so the grid avoids being covered.
+ sidebar_w = 0
+ area = context.area
+ if area:
+ for r in area.regions:
+ if r.type == 'UI' and r.width > 1:
+ sidebar_w = r.width
+ break
+
+ # Layout constants
+ pad = 20
+ btn_h = 40
+ title_h = 30
+ bottom_area = btn_h + pad * 2
+ usable_w = vw - sidebar_w # exclude area behind the N-panel
+
+ # --- dark backdrop ---
+ _draw_rect_2d(0, 0, vw, vh, (0.08, 0.08, 0.08, 0.90))
+
+ # --- title ---
+ blf.size(0, 20)
+ title = "Select an image — or generate more"
+ tw, th = blf.dimensions(0, title)
+ blf.position(0, (usable_w - tw) / 2, vh - pad - th, 0)
+ blf.color(0, 1.0, 1.0, 1.0, 1.0)
+ blf.draw(0, title)
+
+ grid_top = vh - pad - title_h - pad
+ available_w = usable_w - pad * 2
+ available_h = grid_top - bottom_area - pad
+
+ cell_w = max(1, available_w // self._cols)
+ cell_h = max(1, available_h // self._rows)
+
+ # Maintain image aspect ratio
+ if self._pil_images:
+ img_aspect = self._pil_images[0].width / max(1, self._pil_images[0].height)
+ desired_h = cell_w / img_aspect
+ if desired_h > cell_h:
+ cell_w = int(cell_h * img_aspect)
+ else:
+ cell_h = int(desired_h)
+
+ inner = 6
+ total_grid_w = self._cols * cell_w
+ offset_x = (usable_w - total_grid_w) / 2.0
+
+ self._cell_rects.clear()
+
+ for i in range(self._n):
+ row = i // self._cols
+ col = i % self._cols
+ x1 = offset_x + col * cell_w + inner
+ y2 = grid_top - row * cell_h - inner
+ x2 = x1 + cell_w - inner * 2
+ y1 = y2 - cell_h + inner * 2
+ self._cell_rects.append((x1, y1, x2, y2))
+
+ # Hover highlight ring
+ if i == self._hover_idx:
+ _draw_rect_2d(x1 - 3, y1 - 3, x2 + 3, y2 + 3, (0.35, 0.65, 1.0, 0.85))
+
+ # Image texture
+ if i < len(self._textures):
+ _draw_texture_2d(self._textures[i], x1, y1, x2, y2)
+
+ # Number badge
+ blf.size(0, 15)
+ label = str(i + 1)
+ lw, lh = blf.dimensions(0, label)
+ _draw_rect_2d(x1, y2 - lh - 8, x1 + lw + 12, y2, (0.0, 0.0, 0.0, 0.70))
+ blf.position(0, x1 + 6, y2 - lh - 3, 0)
+ blf.color(0, 1.0, 1.0, 1.0, 1.0)
+ blf.draw(0, label)
+
+ # Seed label
+ blf.size(0, 11)
+ seed_txt = f"Seed: {self._seeds[i]}"
+ sw, sh = blf.dimensions(0, seed_txt)
+ _draw_rect_2d(x1, y1, x1 + sw + 10, y1 + sh + 6, (0, 0, 0, 0.6))
+ blf.position(0, x1 + 5, y1 + 3, 0)
+ blf.color(0, 0.7, 0.7, 0.7, 1.0)
+ blf.draw(0, seed_txt)
+
+ # --- buttons ---
+ btn_w = 160
+ btn_y1 = pad
+ btn_y2 = pad + btn_h
+
+ # "Generate More"
+ center_x = usable_w / 2.0
+ mx1 = center_x - btn_w - 10
+ mx2 = center_x - 10
+ c = (0.25, 0.55, 0.85, 0.95) if self._more_hover else (0.20, 0.35, 0.55, 0.85)
+ _draw_rect_2d(mx1, btn_y1, mx2, btn_y2, c)
+ self._more_rect = (mx1, btn_y1, mx2, btn_y2)
+ blf.size(0, 15)
+ mt = "Generate More"
+ mtw, mth = blf.dimensions(0, mt)
+ blf.position(0, (mx1 + mx2 - mtw) / 2, (btn_y1 + btn_y2 - mth) / 2, 0)
+ blf.color(0, 1.0, 1.0, 1.0, 1.0)
+ blf.draw(0, mt)
+
+ # "Cancel"
+ cx1 = center_x + 10
+ cx2 = center_x + btn_w + 10
+ c = (0.75, 0.25, 0.25, 0.95) if self._cancel_hover else (0.45, 0.20, 0.20, 0.85)
+ _draw_rect_2d(cx1, btn_y1, cx2, btn_y2, c)
+ self._cancel_rect = (cx1, btn_y1, cx2, btn_y2)
+ blf.size(0, 15)
+ ct = "Cancel"
+ ctw, cth = blf.dimensions(0, ct)
+ blf.position(0, (cx1 + cx2 - ctw) / 2, (btn_y1 + btn_y2 - cth) / 2, 0)
+ blf.color(0, 1.0, 1.0, 1.0, 1.0)
+ blf.draw(0, ct)
+
+
class Trellis2Generate(bpy.types.Operator):
"""Generate a 3D mesh from a reference image using TRELLIS.2 via ComfyUI.
@@ -1815,6 +2111,15 @@ class Trellis2Generate(bpy.types.Operator):
_stage = "Initializing"
workflow_manager: object = None
+ # ── Preview gallery state ─────────────────────────────────────────
+ _gallery_overlay: _PreviewGalleryOverlay | None = None
+ _gallery_event: threading.Event | None = None
+ _gallery_ready: bool = False
+ _gallery_action: str | None = None # 'select' | 'more' | 'cancel'
+ _gallery_selected_bytes: bytes | None = None
+ _gallery_selected_seed: int | None = None
+ _progress_remap: tuple | None = None # (base, span) for gallery sub-range scaling
+
# ── 3-tier progress ──────────────────────────────────────────────
_overall_progress: float = 0.0
_overall_stage: str = "Initializing"
@@ -1827,12 +2132,16 @@ class Trellis2Generate(bpy.types.Operator):
def _update_overall(self):
"""Recompute *_overall_progress* from current phase + phase progress."""
- if self._total_phases == 3:
+ layout = getattr(self, '_phase_layout', '')
+ if layout == 'txt2img+trellis+texturing': # 3 phases
starts = {1: 0, 2: 15, 3: 65}
weights = {1: 15, 2: 50, 3: 35}
- elif self._total_phases == 2:
+ elif layout == 'trellis+texturing': # 2 phases: big mesh, then texturing
starts = {1: 0, 2: 65}
weights = {1: 65, 2: 35}
+ elif layout == 'txt2img+trellis': # 2 phases: quick txt2img, then big mesh+native tex
+ starts = {1: 0, 2: 15}
+ weights = {1: 15, 2: 85}
else: # Single phase — scale to full 0-100
starts = {1: 0}
weights = {1: 100}
@@ -1893,15 +2202,29 @@ class Trellis2Generate(bpy.types.Operator):
self._texture_mode = tex_mode
self.workflow_manager = WorkflowManager(self)
+ # Gallery state reset
+ self._gallery_overlay = None
+ self._gallery_event = threading.Event()
+ self._gallery_ready = False
+ self._gallery_action = None
+ self._gallery_selected_bytes = None
+ self._gallery_selected_seed = None
+
# 3-tier progress init
has_txt2img = (gen_from == 'prompt')
has_texturing = (tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'))
if has_txt2img and has_texturing:
self._total_phases = 3
- elif has_txt2img or has_texturing:
+ self._phase_layout = 'txt2img+trellis+texturing'
+ elif has_txt2img:
+ self._total_phases = 2
+ self._phase_layout = 'txt2img+trellis'
+ elif has_texturing:
self._total_phases = 2
+ self._phase_layout = 'trellis+texturing'
else:
self._total_phases = 1
+ self._phase_layout = 'trellis_only'
self._current_phase = 0
self._overall_progress = 0.0
self._overall_stage = "Initializing"
@@ -1929,7 +2252,60 @@ class Trellis2Generate(bpy.types.Operator):
return {'RUNNING_MODAL'}
+ def _cleanup_gallery(self):
+ """Remove the gallery overlay and free GPU resources."""
+ if self._gallery_overlay:
+ self._gallery_overlay.cleanup()
+ self._gallery_overlay = None
+
def modal(self, context, event):
+ # ── Gallery mode: intercept mouse + keyboard ──────────────
+ if self._gallery_overlay is not None:
+ if event.type == 'MOUSEMOVE':
+ if self._gallery_overlay.handle_mouse_move(
+ event.mouse_region_x, event.mouse_region_y):
+ for area in context.screen.areas:
+ area.tag_redraw()
+ return {'RUNNING_MODAL'}
+
+ if event.type == 'LEFTMOUSE' and event.value == 'PRESS':
+ action = self._gallery_overlay.handle_click(
+ event.mouse_region_x, event.mouse_region_y)
+ if action == 'select':
+ self._gallery_selected_bytes = self._gallery_overlay.selected_image_bytes
+ self._gallery_selected_seed = self._gallery_overlay.selected_seed
+ self._gallery_action = 'select'
+ self._cleanup_gallery()
+ self._gallery_ready = False
+ self._gallery_event.set()
+ return {'RUNNING_MODAL'}
+ elif action == 'more':
+ self._gallery_action = 'more'
+ self._cleanup_gallery()
+ self._gallery_ready = False
+ self._gallery_event.set()
+ return {'RUNNING_MODAL'}
+ elif action == 'cancel':
+ self._gallery_action = 'cancel'
+ self._cleanup_gallery()
+ self._gallery_ready = False
+ self._gallery_event.set()
+ return {'RUNNING_MODAL'}
+ return {'RUNNING_MODAL'}
+
+ if event.type == 'ESC' and event.value == 'PRESS':
+ self._gallery_action = 'cancel'
+ self._cleanup_gallery()
+ self._gallery_ready = False
+ self._gallery_event.set()
+ return {'RUNNING_MODAL'}
+
+ if event.type == 'TIMER':
+ for area in context.screen.areas:
+ area.tag_redraw()
+ return {'RUNNING_MODAL'}
+
+ # ── Normal mode ───────────────────────────────────────────
if event.type != 'TIMER':
return {'PASS_THROUGH'}
@@ -1937,6 +2313,16 @@ class Trellis2Generate(bpy.types.Operator):
for area in context.screen.areas:
area.tag_redraw()
+ # Check if gallery is ready (thread waiting for user input)
+ if self._gallery_ready and self._gallery_overlay is None:
+ gallery_data = getattr(self, '_gallery_data', None)
+ if gallery_data:
+ pil_imgs, seeds = gallery_data
+ self._gallery_overlay = _PreviewGalleryOverlay(pil_imgs, seeds)
+ for area in context.screen.areas:
+ area.tag_redraw()
+ return {'RUNNING_MODAL'}
+
# Check if thread is still running
if self._thread and self._thread.is_alive():
return {'RUNNING_MODAL'}
@@ -1945,6 +2331,7 @@ class Trellis2Generate(bpy.types.Operator):
context.window_manager.event_timer_remove(self._timer)
self._timer = None
Trellis2Generate._is_running = False
+ self._cleanup_gallery()
if self._error:
self.report({'ERROR'}, f"TRELLIS.2 error: {self._error}")
@@ -1987,8 +2374,46 @@ class Trellis2Generate(bpy.types.Operator):
# Import GLB into Blender
bpy.ops.import_scene.gltf(filepath=glb_path)
- # --- Phase 3: If diffusion texturing, auto-place cameras + start generation ---
+ # --- Normalise imported mesh to a reasonable Blender-unit size ---
+ target_bu = getattr(context.scene, 'trellis2_import_scale', 2.0)
+ if target_bu > 0:
+ imported_objects = [obj for obj in context.selected_objects]
+ if imported_objects:
+ # Compute combined world-space bounding box across all
+ # imported objects (meshes, empties, armatures …).
+ all_corners = []
+ for obj in imported_objects:
+ for corner in obj.bound_box:
+ all_corners.append(obj.matrix_world @ mathutils.Vector(corner))
+ if all_corners:
+ xs = [c.x for c in all_corners]
+ ys = [c.y for c in all_corners]
+ zs = [c.z for c in all_corners]
+ extent = max(
+ max(xs) - min(xs),
+ max(ys) - min(ys),
+ max(zs) - min(zs),
+ )
+ if extent > 1e-6:
+ scale_factor = target_bu / extent
+ # Find the root objects (those without an imported parent)
+ roots = [o for o in imported_objects if o.parent not in imported_objects]
+ for root in roots:
+ root.scale *= scale_factor
+ # Apply scale so downstream code sees unit scale
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in imported_objects:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = imported_objects[0]
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ print(f"[TRELLIS2] Scaled mesh to {target_bu} BU (factor {scale_factor:.4f})")
+
+ # --- Optional studio lighting for native PBR textures ---
tex_mode = getattr(self, '_texture_mode', 'native')
+ if tex_mode == 'native' and getattr(context.scene, 'trellis2_auto_lighting', False):
+ self._setup_studio_lighting(context, target_bu)
+
+ # --- Phase 3: If diffusion texturing, auto-place cameras + start generation ---
if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'):
# Place cameras NOW (while operator context is still valid)
camera_count = getattr(context.scene, 'trellis2_camera_count', 8)
@@ -2018,15 +2443,29 @@ class Trellis2Generate(bpy.types.Operator):
break
try:
- bpy.ops.object.add_cameras(
- placement_mode='normal_weighted',
- num_cameras=camera_count,
- auto_prompts=True,
- review_placement=False,
- purge_others=True,
- exclude_bottom=True,
- )
- print(f"[TRELLIS2] Placed {camera_count} cameras (normal-weighted)")
+ _pm = getattr(context.scene, 'trellis2_placement_mode', 'normal_weighted')
+ _cam_kwargs = {
+ 'placement_mode': _pm,
+ 'num_cameras': camera_count,
+ 'auto_prompts': getattr(context.scene, 'trellis2_auto_prompts', True),
+ 'review_placement': False,
+ 'purge_others': True,
+ 'exclude_bottom': getattr(context.scene, 'trellis2_exclude_bottom', True),
+ 'exclude_bottom_angle': getattr(context.scene, 'trellis2_exclude_bottom_angle', 1.5533),
+ 'auto_aspect': getattr(context.scene, 'trellis2_auto_aspect', 'per_camera'),
+ 'occlusion_mode': getattr(context.scene, 'trellis2_occlusion_mode', 'none'),
+ 'consider_existing': getattr(context.scene, 'trellis2_consider_existing', True),
+ 'clamp_elevation': getattr(context.scene, 'trellis2_clamp_elevation', False),
+ 'max_elevation_angle': getattr(context.scene, 'trellis2_max_elevation', 1.2217),
+ 'min_elevation_angle': getattr(context.scene, 'trellis2_min_elevation', -0.1745),
+ }
+ if _pm == 'greedy_coverage':
+ _cam_kwargs['coverage_target'] = getattr(context.scene, 'trellis2_coverage_target', 0.95)
+ _cam_kwargs['max_auto_cameras'] = getattr(context.scene, 'trellis2_max_auto_cameras', 12)
+ if _pm == 'fan_from_camera':
+ _cam_kwargs['fan_angle'] = getattr(context.scene, 'trellis2_fan_angle', 90.0)
+ bpy.ops.object.add_cameras(**_cam_kwargs)
+ print(f"[TRELLIS2] Placed {camera_count} cameras ({_pm})")
except Exception as cam_err:
print(f"[TRELLIS2] Warning: Camera placement failed: {cam_err}")
traceback.print_exc()
@@ -2044,6 +2483,55 @@ class Trellis2Generate(bpy.types.Operator):
traceback.print_exc()
return {'CANCELLED'}
+ # -----------------------------------------------------------------
+ # Studio lighting (three-point rig for PBR showcase)
+ # -----------------------------------------------------------------
+ def _setup_studio_lighting(self, context, import_scale):
+ """Create a three-point studio lighting setup around the imported mesh."""
+ S = max(import_scale, 0.5) # Avoid degenerate positions
+ dist = S * 2.5 # Distance from origin
+
+ # (name, watts, size, color_rgb, azimuth_deg, elevation_deg)
+ light_defs = [
+ ("SG_Key", 200, 1.5 * S, (1.0, 0.96, 0.90), 45, 40),
+ ("SG_Fill", 80, 2.5 * S, (0.90, 0.94, 1.0), -60, 15),
+ ("SG_Rim", 120, 0.8 * S, (1.0, 1.0, 1.0), 170, 55),
+ ]
+
+ collection = context.collection
+ created = []
+
+ for name, power, size, color, az_deg, el_deg in light_defs:
+ # Remove any stale light with the same name
+ old = bpy.data.objects.get(name)
+ if old:
+ bpy.data.objects.remove(old, do_unlink=True)
+
+ az = math.radians(az_deg)
+ el = math.radians(el_deg)
+ x = dist * math.cos(el) * math.sin(az)
+ y = -dist * math.cos(el) * math.cos(az) # -Y = Blender front
+ z = dist * math.sin(el)
+
+ light_data = bpy.data.lights.new(name=name, type='AREA')
+ light_data.energy = power
+ light_data.size = size
+ light_data.color = color
+
+ light_obj = bpy.data.objects.new(name=name, object_data=light_data)
+ collection.objects.link(light_obj)
+
+ light_obj.location = (x, y, z)
+ # Aim at origin
+ direction = mathutils.Vector((0, 0, 0)) - mathutils.Vector((x, y, z))
+ rot = direction.to_track_quat('-Z', 'Y')
+ light_obj.rotation_euler = rot.to_euler()
+
+ created.append(light_obj)
+
+ print(f"[TRELLIS2] Studio lighting created: {[o.name for o in created]}")
+ return created
+
def _schedule_texture_generation(self, context):
"""Defer texture generation via a timer so Blender can digest the new cameras.
@@ -2106,11 +2594,27 @@ class Trellis2Generate(bpy.types.Operator):
traceback.print_exc()
return None # Run once
+ # Remember which cameras exist before texturing so we can delete
+ # the ones we placed if the user opted in.
+ _pre_tex_cameras = {obj.name for obj in bpy.context.scene.objects if obj.type == 'CAMERA'}
+
def _pipeline_watcher():
"""Clear the pipeline flag when texturing finishes."""
if bpy.context.scene.generation_status == 'idle':
bpy.context.scene.trellis2_pipeline_active = False
print("[TRELLIS2] Pipeline complete — overall bar removed")
+
+ # Delete auto-placed cameras if the user requested it
+ if getattr(bpy.context.scene, 'trellis2_delete_cameras', False):
+ to_remove = [obj for obj in bpy.context.scene.objects
+ if obj.type == 'CAMERA' and obj.name in _pre_tex_cameras]
+ if to_remove:
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in to_remove:
+ obj.select_set(True)
+ bpy.ops.object.delete()
+ print(f"[TRELLIS2] Deleted {len(to_remove)} auto-placed cameras")
+
return None # Stop timer
return 1.0 # Check again in 1s
@@ -2123,7 +2627,12 @@ class Trellis2Generate(bpy.types.Operator):
If *gen_from* is ``'prompt'`` the method first generates an input
image via a lightweight txt2img ComfyUI workflow, saves it to the
revision directory and passes that to the TRELLIS.2 mesh workflow.
+
+ When the preview gallery is enabled (``trellis2_preview_gallery_enabled``),
+ the prompt path generates N images with different seeds and pauses to
+ let the user pick one via the viewport overlay before continuing.
"""
+ import random as _rng
try:
# --- Phase 1: Image acquisition ---
if gen_from == 'prompt':
@@ -2145,10 +2654,84 @@ class Trellis2Generate(bpy.types.Operator):
self._detail_stage = "Starting txt2img"
- img_result = self.workflow_manager.generate_txt2img(context)
- if isinstance(img_result, dict) and "error" in img_result:
- self._error = f"txt2img failed: {img_result['error']}"
- return
+ gallery_enabled = getattr(context.scene, 'trellis2_preview_gallery_enabled', False)
+ gallery_count = max(1, int(getattr(context.scene, 'trellis2_preview_gallery_count', 4)))
+
+ if gallery_enabled and gallery_count >= 1:
+ # ── Preview gallery loop ──────────────────────────
+ img_result = None # will hold the chosen image bytes
+
+ # Seed a local RNG for deterministic gallery sequences.
+ # Same scene seed ➜ same gallery images every run.
+ base_seed = int(getattr(context.scene, 'seed', 0))
+ if base_seed == 0:
+ gallery_rng = _rng.Random() # truly random
+ else:
+ gallery_rng = _rng.Random(base_seed) # deterministic
+
+ while True:
+ pil_images = []
+ seeds = []
+ # Reset progress for each batch
+ self._phase_progress = 0
+ self._update_overall()
+ for i in range(gallery_count):
+ self._detail_stage = f"Generating preview {i + 1}/{gallery_count}"
+ # Set up remapping so WebSocket progress (0-100 per image)
+ # maps to the correct slice of the overall phase bar.
+ base = (i / gallery_count) * 90
+ span = (1 / gallery_count) * 90
+ self._progress_remap = (base, span)
+ self._phase_progress = base
+ self._update_overall()
+
+ rand_seed = gallery_rng.randint(1, 2**31 - 1)
+ result = self.workflow_manager.generate_txt2img(
+ context, seed_override=rand_seed)
+ if isinstance(result, dict) and "error" in result:
+ self._error = f"txt2img failed (seed {rand_seed}): {result['error']}"
+ return
+
+ pil_img = Image.open(io.BytesIO(result))
+ pil_images.append(pil_img)
+ seeds.append(rand_seed)
+
+ # Clear remapping before waiting
+ self._progress_remap = None
+
+ # Hand off to the main thread for user selection
+ self._gallery_data = (pil_images, seeds)
+ self._gallery_ready = True
+ self._detail_stage = "Waiting for selection"
+ self._phase_progress = 95
+ self._update_overall()
+
+ # Block until the modal sets the event
+ self._gallery_event.wait()
+ self._gallery_event.clear()
+
+ if self._gallery_action == 'select':
+ img_result = self._gallery_selected_bytes
+ chosen_seed = self._gallery_selected_seed
+ if chosen_seed is not None:
+ context.scene.seed = chosen_seed
+ break
+ elif self._gallery_action == 'more':
+ # Loop around and generate another batch
+ continue
+ else: # cancel
+ self._error = "Preview gallery cancelled"
+ return
+
+ if img_result is None:
+ self._error = "No image selected from gallery"
+ return
+ else:
+ # ── Single image (legacy path) ───────────────────
+ img_result = self.workflow_manager.generate_txt2img(context)
+ if isinstance(img_result, dict) and "error" in img_result:
+ self._error = f"txt2img failed: {img_result['error']}"
+ return
# Phase 1 complete
self._phase_progress = 100
diff --git a/stablegen/render_tools.py b/stablegen/render_tools.py
index ab53270..f27008f 100644
--- a/stablegen/render_tools.py
+++ b/stablegen/render_tools.py
@@ -2688,6 +2688,35 @@ class AddCameras(bpy.types.Operator):
default='none'
) # type: ignore
+ 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
+ ) # type: ignore
+
+ max_elevation_angle: bpy.props.FloatProperty(
+ name="Max Elevation",
+ description="Maximum upward elevation angle (degrees above horizon). "
+ "Cameras looking further up will be clamped to this angle",
+ default=1.2217, # 70 degrees in radians
+ min=0.0,
+ max=1.5708, # 90 degrees
+ subtype='ANGLE',
+ unit='ROTATION'
+ ) # type: ignore
+
+ min_elevation_angle: bpy.props.FloatProperty(
+ name="Min Elevation",
+ description="Minimum downward elevation angle (degrees below horizon). "
+ "Cameras looking further down will be clamped to this angle",
+ default=-0.1745, # -10 degrees in radians
+ min=-1.5708, # -90 degrees
+ max=0.0,
+ subtype='ANGLE',
+ unit='ROTATION'
+ ) # type: ignore
+
_timer = None
_camera_index = 0
_cameras = []
@@ -2729,6 +2758,11 @@ class AddCameras(bpy.types.Operator):
if self.exclude_bottom:
layout.prop(self, "exclude_bottom_angle")
layout.prop(self, "auto_prompts")
+ layout.prop(self, "clamp_elevation")
+ if self.clamp_elevation:
+ row = layout.row(align=True)
+ row.prop(self, "min_elevation_angle", text="Min")
+ row.prop(self, "max_elevation_angle", text="Max")
layout.prop(self, "review_placement")
layout.prop(self, "purge_others")
if not self.purge_others and is_auto:
@@ -3144,6 +3178,49 @@ class AddCameras(bpy.types.Operator):
ref_dir = np.array([-view_dir.x, -view_dir.y, -view_dir.z])
directions = _sort_directions_spatially(directions, ref_dir)
+ # --- Clamp elevation angles to avoid extreme top/bottom views ---
+ if self.clamp_elevation and directions:
+ min_rad = self.min_elevation_angle
+ max_rad = self.max_elevation_angle
+ clamped = []
+ for d in directions:
+ d_np = np.array(d, dtype=float)
+ norm = np.linalg.norm(d_np)
+ if norm < 1e-8:
+ continue
+ d_np /= norm
+ elev = math.asin(float(np.clip(d_np[2], -1.0, 1.0)))
+ if min_rad <= elev <= max_rad:
+ clamped.append(d_np)
+ continue
+ elev = max(min_rad, min(max_rad, elev))
+ horiz = math.sqrt(float(d_np[0]**2 + d_np[1]**2))
+ if horiz < 1e-8:
+ # Pure vertical direction – pick an arbitrary azimuth
+ azimuth = 0.0
+ else:
+ azimuth = math.atan2(float(d_np[1]), float(d_np[0]))
+ cos_e = math.cos(elev)
+ d_np = np.array([cos_e * math.cos(azimuth),
+ cos_e * math.sin(azimuth),
+ math.sin(elev)])
+ clamped.append(d_np)
+
+ # Deduplicate near-identical directions that may have been created
+ # by clamping several cameras to the same elevation limit.
+ _MERGE_COS = math.cos(math.radians(8.0)) # merge within 8°
+ deduped = []
+ for d in clamped:
+ if all(float(np.dot(d, existing)) < _MERGE_COS
+ for existing in deduped):
+ deduped.append(d)
+ n_before = len(directions)
+ directions = deduped
+ if len(directions) < n_before:
+ self.report({'INFO'},
+ f"Elevation clamp: {n_before} → {len(directions)} cameras "
+ f"(merged {n_before - len(directions)} near-duplicates)")
+
render = context.scene.render
total_px = render.resolution_x * render.resolution_y
center_np_for_aspect = verts_world.mean(axis=0)
diff --git a/stablegen/stablegen.py b/stablegen/stablegen.py
index 26bb116..f7f24b0 100644
--- a/stablegen/stablegen.py
+++ b/stablegen/stablegen.py
@@ -116,6 +116,65 @@ GEN_PARAMETERS = [
"refine_edge_feather_projection",
"refine_edge_feather_width",
"refine_edge_feather_softness",
+ # --- TRELLIS.2 ---
+ "trellis2_generate_from",
+ "trellis2_texture_mode",
+ "trellis2_initial_image_arch",
+ "trellis2_camera_count",
+ "trellis2_placement_mode",
+ "trellis2_auto_prompts",
+ "trellis2_exclude_bottom",
+ "trellis2_exclude_bottom_angle",
+ "trellis2_auto_aspect",
+ "trellis2_occlusion_mode",
+ "trellis2_consider_existing",
+ "trellis2_delete_cameras",
+ "trellis2_coverage_target",
+ "trellis2_max_auto_cameras",
+ "trellis2_fan_angle",
+ "trellis2_resolution",
+ "trellis2_vram_mode",
+ "trellis2_attn_backend",
+ "trellis2_seed",
+ "trellis2_ss_guidance",
+ "trellis2_ss_steps",
+ "trellis2_shape_guidance",
+ "trellis2_shape_steps",
+ "trellis2_tex_guidance",
+ "trellis2_tex_steps",
+ "trellis2_max_tokens",
+ "trellis2_texture_size",
+ "trellis2_decimation",
+ "trellis2_remesh",
+ "trellis2_post_processing_enabled",
+ "trellis2_low_vram",
+ "trellis2_background_color",
+ "trellis2_include_1024",
+ "trellis2_fill_holes",
+ "trellis2_import_scale",
+ "trellis2_clamp_elevation",
+ "trellis2_max_elevation",
+ "trellis2_min_elevation",
+ "trellis2_preview_gallery_enabled",
+ "trellis2_preview_gallery_count",
+ "trellis2_auto_lighting",
+
+ # --- General workflow settings (not prompt/seed/model/paths) ---
+ "use_ipadapter",
+ "sequential_ipadapter_regenerate_wo_controlnet",
+ "allow_modify_existing_textures",
+ "ask_object_prompts",
+ "weight_exponent_mask",
+ "mask_blocky",
+ "architecture_mode",
+ "use_camera_prompts",
+ "sg_use_custom_camera_order",
+ "apply_bsdf",
+ "generation_mode",
+ "texture_objects",
+ "use_flux_lora",
+ "qwen_use_trellis2_style",
+ "trellis2_skip_texture",
]
def get_preset_items(self, context):
@@ -529,11 +588,35 @@ class StableGenPanel(bpy.types.Panel):
split.label(text="Input Image:")
split.prop(scene, "trellis2_input_image", text="")
+ # Preview gallery (only when generate_from = prompt)
+ if scene.trellis2_generate_from == 'prompt':
+ row = params_container.row(align=True)
+ row.prop(scene, "trellis2_preview_gallery_enabled", text="Preview Gallery", toggle=True, icon="IMAGE_REFERENCE")
+ sub = row.row(align=True)
+ sub.enabled = scene.trellis2_preview_gallery_enabled
+ sub.prop(scene, "trellis2_preview_gallery_count", text="Count")
+
# Texture Generation Mode
split = params_container.split(factor=0.5)
split.label(text="Texture Mode:")
split.prop(scene, "trellis2_texture_mode", text="")
+ # Prompt + native/none: show initial-image architecture & checkpoint
+ _prompt_native = (
+ scene.trellis2_generate_from == 'prompt'
+ and trellis2_tex_mode in ('native', 'none')
+ )
+ if _prompt_native:
+ split = params_container.split(factor=0.5)
+ split.label(text="Initial Image Arch:")
+ split.prop(scene, "trellis2_initial_image_arch", text="")
+
+ split = params_container.split(factor=0.25)
+ split.label(text="Checkpoint:")
+ row = split.row(align=True)
+ row.prop(scene, "model_name", text="")
+ row.operator("stablegen.refresh_checkpoint_list", text="", icon='FILE_REFRESH')
+
# When diffusion texturing: show checkpoint, generation mode, camera count
if trellis2_diffusion_texturing:
split = params_container.split(factor=0.25)
@@ -548,9 +631,6 @@ class StableGenPanel(bpy.types.Panel):
split.prop(scene, "qwen_generation_method", text="")
else:
split.prop(scene, "generation_method", text="")
-
- row = params_container.row()
- row.prop(scene, "trellis2_camera_count", text="Camera Count")
else:
# --- Standard diffusion layout ---
# Split for model name
@@ -681,6 +761,75 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "trellis2_texture_size", text="Texture Size")
+ content_box.separator()
+ row = content_box.row()
+ row.prop(scene, "trellis2_auto_lighting", text="Studio Lighting", icon="LIGHT_AREA")
+
+ # --- TRELLIS.2: Camera Placement Settings (diffusion texturing) ---
+ if is_trellis2 and trellis2_diffusion_texturing:
+ content_box = draw_collapsible_section(advanced_params_box, "show_trellis2_camera_settings", "Camera Placement (TRELLIS.2)", icon="CAMERA_DATA")
+ if content_box:
+ _t2_pm = getattr(scene, 'trellis2_placement_mode', 'normal_weighted')
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_import_scale", text="Import Scale (BU)")
+
+ content_box.separator()
+
+ split = content_box.split(factor=0.4)
+ split.label(text="Placement:")
+ split.prop(scene, "trellis2_placement_mode", text="")
+
+ # Camera count (not used by greedy)
+ if _t2_pm != 'greedy_coverage':
+ row = content_box.row()
+ row.prop(scene, "trellis2_camera_count", text="Camera Count")
+
+ # Greedy-specific
+ if _t2_pm == 'greedy_coverage':
+ row = content_box.row(align=True)
+ row.prop(scene, "trellis2_coverage_target", text="Coverage Target")
+ row.prop(scene, "trellis2_max_auto_cameras", text="Max Cameras")
+
+ # Fan-specific
+ if _t2_pm == 'fan_from_camera':
+ row = content_box.row()
+ row.prop(scene, "trellis2_fan_angle", text="Fan Angle")
+
+ content_box.separator()
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_auto_prompts", text="Auto View Prompts", toggle=True, icon="OUTLINER_OB_CAMERA")
+
+ split = content_box.split(factor=0.4)
+ split.label(text="Auto Aspect:")
+ split.prop(scene, "trellis2_auto_aspect", text="")
+
+ split = content_box.split(factor=0.4)
+ split.label(text="Occlusion:")
+ split.prop(scene, "trellis2_occlusion_mode", text="")
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_exclude_bottom", text="Exclude Bottom Faces", toggle=True, icon="TRIA_DOWN_BAR")
+ if scene.trellis2_exclude_bottom:
+ row = content_box.row()
+ row.prop(scene, "trellis2_exclude_bottom_angle", text="Bottom Angle")
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_consider_existing", text="Consider Existing Cameras", toggle=True)
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_delete_cameras", text="Delete Cameras After", toggle=True, icon="TRASH")
+
+ content_box.separator()
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_clamp_elevation", text="Clamp Elevation", toggle=True, icon="CON_ROTLIMIT")
+ if scene.trellis2_clamp_elevation:
+ row = content_box.row(align=True)
+ row.prop(scene, "trellis2_min_elevation", text="Min")
+ row.prop(scene, "trellis2_max_elevation", text="Max")
+
# --- Diffusion-based advanced sections ---
# Each is individually guarded: shown for standard arches or TRELLIS.2 with diffusion texturing
_show_diffusion_sections = not is_trellis2 or trellis2_diffusion_texturing
diff --git a/stablegen/util/helpers.py b/stablegen/util/helpers.py
index 96135e0..f9df1af 100755
--- a/stablegen/util/helpers.py
+++ b/stablegen/util/helpers.py
@@ -1550,7 +1550,7 @@ prompt_text_trellis2 = """
"ss_sampling_steps": 12,
"shape_guidance_strength": 7.5,
"shape_sampling_steps": 12,
- "max_tokens": 24576
+ "max_tokens": 49152
},
"class_type": "Trellis2ImageToShape",
"_meta": {
@@ -1575,7 +1575,7 @@ prompt_text_trellis2 = """
"inputs": {
"voxelgrid_path": ["6", 1],
"decimation_target": 100000,
- "texture_size": 2048,
+ "texture_size": 4096,
"remesh": true,
"filename_prefix": "trellis2"
},
@@ -1642,7 +1642,7 @@ prompt_text_trellis2_shape_only = """
"ss_sampling_steps": 12,
"shape_guidance_strength": 7.5,
"shape_sampling_steps": 12,
- "max_tokens": 24576
+ "max_tokens": 49152
},
"class_type": "Trellis2ImageToShape",
"_meta": {
diff --git a/stablegen/workflows.py b/stablegen/workflows.py
index 01c92ce..b90535b 100644
--- a/stablegen/workflows.py
+++ b/stablegen/workflows.py
@@ -839,13 +839,18 @@ class WorkflowManager:
# Txt2Img — lightweight single-image generation for prompt-to-image
# ------------------------------------------------------------------
- def generate_txt2img(self, context):
+ def generate_txt2img(self, context, seed_override=None):
"""Generate a single image from the scene prompt and checkpoint.
Builds a minimal txt2img ComfyUI workflow (with LoRA support) and
returns the generated image as raw PNG bytes delivered via the
``SaveImageWebsocket`` node.
+ Args:
+ seed_override: If not None, overrides ``scene.seed`` in the
+ built workflow. Useful for preview-gallery generation from
+ a background thread where ``scene.seed`` may not propagate.
+
Returns:
bytes: Raw image data on success.
dict: ``{"error": "..."}`` on failure.
@@ -855,6 +860,14 @@ class WorkflowManager:
scene = context.scene
architecture = scene.model_architecture # synced from texture_mode
+ # When using TRELLIS.2 with native/none texturing the backbone is
+ # synced from trellis2_initial_image_arch instead of texture_mode.
+ # Double-check here in case the property wasn't synced yet.
+ if getattr(scene, 'architecture_mode', '') == 'trellis2':
+ tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
+ if tex_mode not in ('sdxl', 'flux1', 'qwen_image_edit'):
+ architecture = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
+
if architecture == 'qwen_image_edit':
prompt, save_node = self._build_qwen_txt2img(context)
elif architecture == 'flux1':
@@ -862,6 +875,15 @@ class WorkflowManager:
else:
prompt, save_node = self._build_sdxl_txt2img(context)
+ # Patch seed if caller supplies an override (thread-safe)
+ if seed_override is not None:
+ for _node in prompt.values():
+ _inp = _node.get('inputs', {})
+ if 'seed' in _inp:
+ _inp['seed'] = seed_override
+ if 'noise_seed' in _inp:
+ _inp['noise_seed'] = seed_override
+
ws = self._connect_to_websocket(server_address, client_id)
if ws is None:
return {"error": "WebSocket connection failed"}
@@ -1133,8 +1155,13 @@ class WorkflowManager:
# ── GLB mesh validation ───────────────────────────────────────────
_GLB_VERTEX_THRESHOLD = 10.0 # absolute coordinate cap
_GLB_OUTLIER_SIGMA = 8.0 # for absolute-value outlier check
- _GLB_LAPLACIAN_SIGMA = 6.0 # Laplacian displacement outlier threshold
- _GLB_SPIKE_FRACTION = 0.001 # if > 0.1% of verts are Laplacian outliers → corrupt
+ _GLB_LAPLACIAN_SIGMA = 8.0 # Laplacian displacement outlier threshold — set high
+ # (10σ) so only truly extreme needle-like spikes are
+ # flagged; legitimate sharp edges/corners sit at ~5-8σ
+ _GLB_SPIKE_FRACTION = 0.002 # 0.02% — very tight because at 10σ virtually all
+ # flagged vertices are genuine artifacts
+ _GLB_SPIKE_ABS_MAX = 25 # absolute cap — with 10σ even a handful of
+ # flagged vertices indicates corruption
@staticmethod
def _validate_glb_mesh(glb_bytes, threshold=None, sigma=None):
@@ -1307,9 +1334,16 @@ class WorkflowManager:
)
total_spikes += spike_count
- # Check overall spike fraction
+ # Check overall spike count (absolute cap + fraction)
if total_verts > 0 and total_spikes > 0:
frac = total_spikes / total_verts
+ abs_max = WorkflowManager._GLB_SPIKE_ABS_MAX
+ if total_spikes > abs_max:
+ return False, (
+ f"Mesh has {total_spikes} Laplacian-outlier vertices "
+ f"(exceeds absolute cap of {abs_max}). "
+ f"Likely cumesh corruption."
+ )
if frac > spike_frac:
return False, (
f"Mesh has {total_spikes} Laplacian-outlier vertices "
@@ -1689,6 +1723,33 @@ class WorkflowManager:
export_node_id = NODES[export_node_key]
glb_output_path = None
+ # Friendly node labels for the progress bars
+ NODE_LABELS = {
+ 'input_image': 'Loading Image',
+ 'load_models': 'Loading Models',
+ 'remove_bg': 'Removing Background',
+ 'get_conditioning': 'Conditioning',
+ 'image_to_shape': 'Generating Shape',
+ 'shape_to_textured_mesh': 'Generating Texture',
+ 'simplify': 'Simplifying Mesh',
+ 'export_trimesh': 'Exporting Mesh',
+ 'export_glb': 'Exporting GLB',
+ }
+
+ # Build a lookup of known step counts so we can identify
+ # which sampling sub-phase a within-node progress event
+ # belongs to (the TRELLIS nodes may emit separate runs of
+ # progress events for SS, shape, and texture sampling).
+ _ss_steps = scene.trellis2_ss_steps
+ _shape_steps = scene.trellis2_shape_steps
+ _tex_steps = getattr(scene, 'trellis2_tex_steps', 0)
+ _current_exec_node = None # node-key of the currently executing node
+
+ # Track accumulated sub-phases within a node so we can
+ # compute a node-internal overall progress.
+ _sub_phase_idx = 0 # resets when the executing node changes
+ _sub_phase_count = 1 # how many sub-phases this node has
+
while True:
try:
out = ws.recv()
@@ -1714,9 +1775,9 @@ class WorkflowManager:
break # Execution complete
else:
node_id = data['node']
- # Map node IDs to readable names for progress
node_names = {v: k for k, v in NODES.items()}
- node_label = node_names.get(node_id, node_id)
+ node_key = node_names.get(node_id, node_id)
+ node_label = NODE_LABELS.get(node_key, node_key)
print(f"[TRELLIS2] Executing: {node_label}")
self.operator._phase_stage = f"TRELLIS.2: {node_label}"
# Update progress based on node weight
@@ -1727,6 +1788,17 @@ class WorkflowManager:
self.operator._detail_stage = node_label
self.operator._detail_progress = 0
+ # Reset sub-phase tracking for the new node
+ _current_exec_node = node_key
+ _sub_phase_idx = 0
+ if node_key == 'image_to_shape':
+ # SS sampling + shape sampling = 2 sub-phases
+ _sub_phase_count = 2
+ elif node_key == 'shape_to_textured_mesh':
+ _sub_phase_count = 1
+ else:
+ _sub_phase_count = 1
+
elif message['type'] == 'executed':
# Capture output from export node (newer ComfyUI versions)
data = message.get('data', {})
@@ -1753,12 +1825,52 @@ class WorkflowManager:
break
elif message['type'] == 'progress':
- # Within-node progress (sampler steps)
- progress = (message['data']['value'] / message['data']['max']) * 100
- if progress != 0:
- self.operator._detail_progress = progress
- self.operator._detail_stage = f"Step {message['data']['value']}/{message['data']['max']}"
- print(f"[TRELLIS2] Progress: {progress:.1f}%")
+ # Within-node progress (sampler steps).
+ # TRELLIS.2 nodes may emit separate runs of progress
+ # events for each internal sampling phase. We detect
+ # the sub-phase by matching ``max`` against known step
+ # counts (SS, shape, texture).
+ p_data = message['data']
+ p_value = p_data['value']
+ p_max = p_data['max']
+ step_progress = (p_value / p_max) * 100 if p_max else 0
+
+ # ── Sub-phase identification ──
+ sub_label = ""
+ if _current_exec_node == 'image_to_shape':
+ if p_max == _ss_steps:
+ sub_label = "Sampling SS"
+ # First sub-phase: reset index if we see it again
+ if _sub_phase_idx == 0 or p_value == 1:
+ _sub_phase_idx = 0
+ elif p_max == _shape_steps:
+ sub_label = "Sampling Shape SLat"
+ if _sub_phase_idx < 1:
+ _sub_phase_idx = 1
+ else:
+ # Unknown max — show generic label
+ sub_label = "Sampling"
+ elif _current_exec_node == 'shape_to_textured_mesh':
+ if p_max == _tex_steps:
+ sub_label = "Sampling Texture"
+ else:
+ sub_label = "Sampling"
+ else:
+ sub_label = "Processing"
+
+ # Compute node-internal overall progress accounting for sub-phases
+ if _sub_phase_count > 1:
+ node_overall = ((_sub_phase_idx + step_progress / 100.0)
+ / _sub_phase_count) * 100.0
+ else:
+ node_overall = step_progress
+
+ if step_progress != 0:
+ self.operator._detail_progress = node_overall
+ self.operator._detail_stage = (
+ f"{sub_label}: Step {p_value}/{p_max}"
+ )
+ print(f"[TRELLIS2] {sub_label}: Step {p_value}/{p_max} ({step_progress:.0f}%)")
elif message['type'] == 'execution_error':
error_data = message.get('data', {})
@@ -2364,7 +2476,13 @@ class WorkflowManager:
if hasattr(self.operator, '_detail_progress'):
self.operator._detail_progress = progress
self.operator._detail_stage = f"Step {message['data']['value']}/{message['data']['max']}"
- self.operator._phase_progress = progress
+ # Remap progress into a sub-range when gallery mode is active
+ remap = getattr(self.operator, '_progress_remap', None)
+ if remap:
+ base, span = remap
+ self.operator._phase_progress = base + (progress / 100.0) * span
+ else:
+ self.operator._phase_progress = progress
if hasattr(self.operator, '_update_overall'):
self.operator._update_overall()
print(f"Progress: {progress:.1f}%")