Skip to content

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

make the new panel the default sidebar panel

sakalondc0002b187cba
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index 3d0aefc..cd7bf85 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -13,9 +13,6 @@ from .ui.presets import (
ResetQwenPrompt, ResetTexturingExperiments, SwitchToMeshGeneration,
)
from .ui.panel import StableGenPanel, StableGenPrintPanel
-from .ui.panel_variants import (
- VARIANT_UI_CLASSES, register_variant_properties, unregister_variant_properties,
-)
from .ui.studio import STUDIO_UI_CLASSES, register_studio_ui, unregister_studio_ui
from .ui.queue import (
SG_UL_SceneQueueList, SceneQueueAdd, SceneQueueRemove, SceneQueueClear,
@@ -203,7 +200,6 @@ classes = [
classes.extend(_debug_classes)
classes.extend(REGRESSION_CLASSES)
classes.extend(masked_edit.MASKED_EDIT_CLASSES)
-classes.extend(VARIANT_UI_CLASSES)
classes.extend(STUDIO_UI_CLASSES)
classes.extend(camera_display.CLASSES)
@@ -223,7 +219,6 @@ def register():
_sg_queue_load_handler=_sg_queue_load_handler,
_sg_queue_load=_sg_queue_load,
)
- register_variant_properties()
register_studio_ui()
camera_display.register()
server_monitor.register()
@@ -233,7 +228,6 @@ def unregister():
server_monitor.unregister()
camera_display.unregister()
unregister_studio_ui()
- unregister_variant_properties()
masked_edit.unregister_properties()
from .mesh_gen.batch import unregister_batch
from .dae_import.batch_texture import unregister_batch_texture
diff --git a/stablegen/core/__init__.py b/stablegen/core/__init__.py
index 10c34e7..3b87004 100644
--- a/stablegen/core/__init__.py
+++ b/stablegen/core/__init__.py
@@ -15,3 +15,9 @@ def get_addon_prefs(context=None):
ctx = context or bpy.context
wrapper = ctx.preferences.addons.get(ADDON_PKG)
return wrapper.preferences if wrapper else None
+
+
+def legacy_panel_enabled(context=None):
+ """Whether the sidebar shows the legacy panel instead of the Studio panel."""
+ prefs = get_addon_prefs(context)
+ return bool(prefs and prefs.use_legacy_panel)
diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.py
index 68165bd..3580d00 100644
--- a/stablegen/core/preferences.py
+++ b/stablegen/core/preferences.py
@@ -55,6 +55,14 @@ class ControlNetModelMappingItem(bpy.types.PropertyGroup):
# ── Addon Preferences ─────────────────────────────────────────────────────
+def _redraw_sidebars(self, context):
+ """Swap the Studio and legacy panels immediately in every 3D Viewport."""
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+
+
class StableGenAddonPreferences(bpy.types.AddonPreferences):
"""Preferences for the StableGen addon."""
bl_idname = ADDON_PKG
@@ -99,9 +107,16 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
update=update_parameters
) # type: ignore
+ use_legacy_panel: bpy.props.BoolProperty(
+ name="Use Legacy Panel",
+ description="Show the original StableGen sidebar panel instead of the Studio panel",
+ default=False,
+ update=_redraw_sidebars
+ ) # type: ignore
+
enable_print_tab: bpy.props.BoolProperty(
- name="Enable 3D Print Tab",
- description="Show 3D Printing Palette and Exporters in a separate Sidebar tab",
+ name="Enable 3D Printing",
+ description="Show the 3D printing palette and exporters; the legacy panel shows them in a separate Sidebar tab",
default=False,
update=update_parameters
) # type: ignore
@@ -199,6 +214,9 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
row.prop(self, "server_address")
row.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')
+ row = layout.row()
+ row.prop(self, "use_legacy_panel")
+ row.operator("stablegen.reset_tips", icon='LOOP_BACK')
layout.prop(self, "save_blend_file")
layout.prop(self, "enable_print_tab")
layout.prop(self, "enable_texturing_experiments")
diff --git a/stablegen/texturing/masked_edit.py b/stablegen/texturing/masked_edit.py
index e7e68bd..e03d5d4 100644
--- a/stablegen/texturing/masked_edit.py
+++ b/stablegen/texturing/masked_edit.py
@@ -16,7 +16,7 @@ import uuid
import bpy
import numpy as np
-from ..core import ADDON_PKG
+from ..core import ADDON_PKG, legacy_panel_enabled
from ..utils import sg_modal_active, get_file_path
from .rendering import _RenderStateTransaction
@@ -1140,6 +1140,11 @@ class SG_PT_MaskedEdit(bpy.types.Panel):
bl_category = 'StableGen'
bl_options = {'DEFAULT_CLOSED'}
+ @classmethod
+ def poll(cls, context):
+ # Studio shows these controls in its own mode settings.
+ return legacy_panel_enabled(context)
+
def draw(self, context):
draw_masked_edit_controls(self.layout, context)
diff --git a/stablegen/ui/brand.py b/stablegen/ui/brand.py
new file mode 100644
index 0000000..11b93d7
--- /dev/null
+++ b/stablegen/ui/brand.py
@@ -0,0 +1,161 @@
+"""StableGen's logo: a lens projecting onto a cube, painting the faces it can see.
+
+The geometry lives here once. The Studio header rasterizes it at the current
+UI scale, and tools/export_brand.py writes the SVG and PNG assets from it.
+Pure Python + numpy so it also runs outside Blender.
+"""
+import math
+
+import numpy as np
+
+GOLD, ORANGE, ROSE = '#FFC25C', '#FF8642', '#E8487A'
+CLAY = '#8E93AD'
+INK = '#14151F'
+S3 = math.sqrt(3) / 2
+
+
+def _iso(x, y, z, cx, cy, r):
+ """Isometric unit cube; (1, 1, 1) is the front-top corner at (cx, cy)."""
+ c = r * S3
+ return (cx + c * (x - y), cy - r + r / 2 * (x + y) - r * (z - 1))
+
+
+def _face(name, cx, cy, r):
+ on = {'top': lambda s, t: (s, t, 1), 'left': lambda s, t: (s, 1, t), 'right': lambda s, t: (1, s, t)}[name]
+ return [_iso(*on(s, t), cx, cy, r) for s, t in ((0, 0), (1, 0), (1, 1), (0, 1))]
+
+
+def _projector(lens, centre, r, lens_r, unlit):
+ """Layers of (shape, paint), back to front, in 0..100 units.
+
+ Shapes: ('poly', points) for convex polygons, ('circle', (x, y, r)),
+ ('rrect', (x, y, w, h, radius)). Paints: ('solid', hex, alpha) or
+ ('linear', (x1, y1, x2, y2), [(offset, hex, alpha), ...]).
+ """
+ cx, cy = centre
+ outline = [_iso(*v, cx, cy, r) for v in ((0, 0, 1), (1, 0, 1), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 1))]
+ angle = lambda v: math.atan2(v[1] - lens[1], v[0] - lens[0])
+ lo, hi = min(outline, key=angle), max(outline, key=angle)
+ ax, ay = cx - lens[0], cy - lens[1]
+ length = math.hypot(ax, ay)
+ ux, uy = ax / length, ay / length
+ rim = lens_r * .62
+ e1 = (lens[0] - uy * rim, lens[1] + ux * rim)
+ e2 = (lens[0] + uy * rim, lens[1] - ux * rim)
+ if angle(e1) > angle(e2):
+ e1, e2 = e2, e1
+ top, left, right = _face('top', cx, cy, r), _face('left', cx, cy, r), _face('right', cx, cy, r)
+ return [
+ # The beam ends on the cube's silhouette; the cube covers the rest of it.
+ (('poly', [e1, lo, hi, e2]), ('linear', (*lens, cx, cy), [(0, GOLD, .04), (1, GOLD, .5)])),
+ (('poly', top), ('linear', (*top[0], *top[2]), [(0, '#FFD98A', 1), (1, GOLD, 1)])),
+ (('poly', left), ('linear', (*left[3], *left[1]), [(0, ORANGE, 1), (1, '#F0606A', 1)])),
+ (('poly', right), ('solid', unlit, 1)),
+ (('circle', (*lens, lens_r)), ('linear', (lens[0] - lens_r, lens[1] - lens_r, lens[0] + lens_r,
+ lens[1] + lens_r), [(0, GOLD, 1), (1, ORANGE, 1)])),
+ (('circle', (*lens, lens_r * .5)), ('solid', '#FFF7E8', 1)),
+ (('circle', (*lens, lens_r * .19)), ('solid', ORANGE, 1)),
+ ]
+
+
+LOGO = _projector((21.5, 21.5), (60, 58), 31, 10.5, CLAY)
+# The square around the logo's visible extent, for small sizes like the Studio header.
+LOGO_BOX = (9.5, 10.5, 88.5, 89.5)
+
+ICON = [(('rrect', (4, 4, 92, 92, 22)), ('linear', (0, 4, 0, 96), [(0, '#23253A', 1), (1, INK, 1)]))] + \
+ _projector((29, 29), (59.5, 57.5), 24.5, 8.5, '#4A4E68')
+ICON_BOX = (0, 0, 100, 100)
+
+
+def _rgb(value):
+ return np.array([int(value[i:i + 2], 16) / 255 for i in (1, 3, 5)], np.float32)
+
+
+def _inside(shape, xs, ys):
+ kind, data = shape
+ if kind == 'circle':
+ x, y, r = data
+ return (xs - x) ** 2 + (ys - y) ** 2 <= r * r
+ if kind == 'rrect':
+ x, y, w, h, radius = data
+ qx = np.abs(xs - (x + w / 2)) - (w / 2 - radius)
+ qy = np.abs(ys - (y + h / 2)) - (h / 2 - radius)
+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) <= radius
+ points = data
+ area = sum(x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(points, points[1:] + points[:1]))
+ inside = np.ones(xs.shape, bool)
+ for (x1, y1), (x2, y2) in zip(points, points[1:] + points[:1]):
+ cross = (x2 - x1) * (ys - y1) - (y2 - y1) * (xs - x1)
+ inside &= cross * area >= 0
+ return inside
+
+
+def _paint(paint, xs, ys):
+ if paint[0] == 'solid':
+ return np.broadcast_to(_rgb(paint[1]), xs.shape + (3,)), np.full(xs.shape, paint[2], np.float32)
+ x1, y1, x2, y2 = paint[1]
+ dx, dy = x2 - x1, y2 - y1
+ t = np.clip(((xs - x1) * dx + (ys - y1) * dy) / (dx * dx + dy * dy), 0, 1)
+ stops = paint[2]
+ offsets = [s[0] for s in stops]
+ rgb = np.stack([np.interp(t, offsets, [_rgb(s[1])[k] for s in stops]) for k in range(3)], -1)
+ return rgb, np.interp(t, offsets, [s[2] for s in stops]).astype(np.float32)
+
+
+def rasterize(layers, size, box=(0, 0, 100, 100), samples=4, strip=128):
+ """Straight-alpha RGBA float array (size x size x 4), top row first.
+
+ Supersampled with exact inside tests, so faces that share an edge meet
+ without the seams per-shape anti-aliasing leaves.
+ """
+ x0, y0, x1, y1 = box
+ unit = size / (x1 - x0)
+ out = np.zeros((size, size, 4), np.float32)
+ sx = x0 + (np.arange(size * samples) + .5) / samples / unit
+ for row in range(0, size, strip):
+ rows = min(strip, size - row)
+ sy = y0 + (row + (np.arange(rows * samples) + .5) / samples) / unit
+ xs, ys = np.meshgrid(sx, sy)
+ colour = np.zeros(xs.shape + (3,), np.float32)
+ alpha = np.zeros(xs.shape, np.float32)
+ for shape, paint in layers:
+ rgb, a = _paint(paint, xs, ys)
+ a = a * _inside(shape, xs, ys)
+ colour = colour * (1 - a)[..., None] + rgb * a[..., None]
+ alpha = alpha * (1 - a) + a
+ colour = colour.reshape(rows, samples, size, samples, 3).mean((1, 3))
+ alpha = alpha.reshape(rows, samples, size, samples).mean((1, 3))
+ out[row:row + rows, :, :3] = colour / np.maximum(alpha, 1e-6)[..., None]
+ out[row:row + rows, :, 3] = alpha
+ return out
+
+
+def to_svg(layers, box=(0, 0, 100, 100), mono=None):
+ """SVG markup for the layers. *mono* maps layer index to opacity for a one-colour version."""
+ defs, body = [], []
+ for i, (shape, paint) in enumerate(layers):
+ if mono is not None:
+ if i not in mono:
+ continue
+ fill = f'fill="currentColor" opacity="{mono[i]}"'
+ elif paint[0] == 'solid':
+ fill = f'fill="{paint[1]}"' + (f' fill-opacity="{paint[2]}"' if paint[2] != 1 else '')
+ else:
+ x1, y1, x2, y2 = paint[1]
+ stops = ''.join(f'<stop offset="{o}" stop-color="{c}"' + (f' stop-opacity="{a}"' if a != 1 else '') + '/>'
+ for o, c, a in paint[2])
+ defs.append(f'<linearGradient id="g{i}" gradientUnits="userSpaceOnUse" x1="{x1:.2f}" y1="{y1:.2f}" '
+ f'x2="{x2:.2f}" y2="{y2:.2f}">{stops}</linearGradient>')
+ fill = f'fill="url(#g{i})"'
+ kind, data = shape
+ if kind == 'circle':
+ body.append(f'<circle cx="{data[0]:.2f}" cy="{data[1]:.2f}" r="{data[2]:.2f}" {fill}/>')
+ elif kind == 'rrect':
+ x, y, w, h, radius = data
+ body.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{radius}" {fill}/>')
+ else:
+ points = ' '.join(f'{x:.2f},{y:.2f}' for x, y in data)
+ body.append(f'<polygon points="{points}" {fill}/>')
+ x0, y0, x1, y1 = box
+ return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{x0} {y0} {x1 - x0} {y1 - y0}">'
+ f'<defs>{"".join(defs)}</defs>{"".join(body)}</svg>\n')
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index a400d1f..47f853b 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -6,7 +6,7 @@ import mathutils # pylint: disable=import-error
from ..generation_status import draw_stage_progress, server_status_active
import math
from ..utils import sg_modal_active
-from ..core import get_addon_prefs
+from ..core import get_addon_prefs, legacy_panel_enabled
from .presets import PRESETS, GEN_PARAMETERS
from ..feature_flags import experiments_enabled, active_experiments
from ..architecture_options import (
@@ -127,7 +127,9 @@ class StableGenPanel(bpy.types.Panel):
@classmethod
def poll(cls, context):
- return context.mode in {'OBJECT', 'PAINT_TEXTURE'}
+ # The Studio panel replaces this one unless the legacy panel is chosen
+ # in preferences. Studio still captures draw() for its content.
+ return context.mode in {'OBJECT', 'PAINT_TEXTURE'} and legacy_panel_enabled(context)
def draw_header(self, _):
"""
@@ -2504,8 +2506,9 @@ class StableGenPrintPanel(bpy.types.Panel):
@classmethod
def poll(cls, context):
+ # Studio integrates 3D printing as one of its pages.
prefs = get_addon_prefs(context)
- return bool(prefs and prefs.enable_print_tab)
+ return bool(prefs and prefs.enable_print_tab and prefs.use_legacy_panel)
def draw(self, context):
layout = self.layout
diff --git a/stablegen/ui/panel_variants.py b/stablegen/ui/panel_variants.py
deleted file mode 100644
index e3f02de..0000000
--- a/stablegen/ui/panel_variants.py
+++ /dev/null
@@ -1,465 +0,0 @@
-"""Three live UI alternatives alongside the unchanged legacy sidebar."""
-import bpy
-
-from ..utils import sg_modal_active
-from .presentation import capture_panel
-
-PAGES = (
- ('GENERATE', 'Generate', 'Generation, models and guidance', 'RENDER_STILL', 0),
- ('CAMERAS', 'Cameras', 'Viewpoints, framing and order', 'CAMERA_DATA', 1),
- ('BLEND', 'Blending', 'Projection, visibility and DPPG', 'MOD_MASK', 2),
- ('OUTPUT', 'Output', 'Materials, PBR and export', 'MATERIAL', 3),
- ('MESH', 'Mesh & Rig', 'TRELLIS.2 geometry and rigging', 'MESH_DATA', 4),
- ('TOOLS', 'Tools & Batch', 'Utilities and queued scenes', 'TOOL_SETTINGS', 5),
- ('DEBUG', 'Diagnostics', 'Debug tools and experimental settings', 'GHOST_ENABLED', 6),
- ('PRINT', 'Printing', 'Palette and print exports', 'OUTLINER_OB_MESH', 7),
-)
-PAGE_LABELS = {item[0]: (item[1], item[3]) for item in PAGES}
-STAGES = (
- ('SETUP', 'Set up', 'Model, prompt and generation settings', 'SETTINGS', 0),
- ('VIEWS', 'Arrange views', 'Camera setup and view descriptions', 'CAMERA_DATA', 1),
- ('RUN', 'Generate', 'Generation mode and execution', 'PLAY', 2),
- ('PROJECT', 'Blend & inspect', 'Projection and diagnostics', 'MOD_MASK', 3),
- ('DELIVER', 'Bake & export', 'Materials and deliverables', 'EXPORT', 4),
- ('UTILITY', 'Utilities', 'Batch workflows and remaining tools', 'TOOL_SETTINGS', 5),
-)
-STATE_NAMES = {'STUDIO': 'sg_ui_studio', 'WORKBENCH': 'sg_ui_workbench', 'FOCUS': 'sg_ui_focus'}
-DEFAULT_OPEN = 'main|show_core_settings|show_mode_specific_settings|show_scene_understanding_settings|show_output_material_settings|camera_tools|export'
-
-
-def _redraw(self, context):
- for window in context.window_manager.windows:
- for area in window.screen.areas:
- if area.type == 'VIEW_3D':
- area.tag_redraw()
-
-
-class SGPanelVariantState(bpy.types.PropertyGroup):
- page: bpy.props.EnumProperty(items=PAGES, default='GENERATE', update=_redraw)
- stage: bpy.props.EnumProperty(items=STAGES, default='SETUP', update=_redraw)
- query: bpy.props.StringProperty(name='Find a setting', description='Search available section titles, controls and tooltips', update=_redraw)
- open_sections: bpy.props.StringProperty(default=DEFAULT_OPEN)
- pinned_sections: bpy.props.StringProperty(default='')
- overview: bpy.props.BoolProperty(default=True)
- show_pins: bpy.props.BoolProperty(name='Pinned Settings', default=True, update=_redraw)
- camera_index: bpy.props.IntProperty(default=0)
-
-
-class SG_OT_PanelNavigate(bpy.types.Operator):
- bl_idname = 'stablegen.panel_navigate'
- bl_label = 'Open Settings'
- bl_description = 'Open this part of the StableGen panel'
- bl_options = {'INTERNAL'}
- variant: bpy.props.EnumProperty(items=[(key, key.title(), '') for key in STATE_NAMES])
- destination: bpy.props.StringProperty()
- section: bpy.props.StringProperty()
- mode: bpy.props.EnumProperty(items=[('PAGE', 'Page', ''), ('STAGE', 'Stage', ''), ('OVERVIEW', 'Overview', '')])
-
- def execute(self, context):
- state = getattr(context.window_manager, STATE_NAMES[self.variant])
- if self.mode == 'STAGE':
- state.stage = self.destination
- elif self.mode == 'OVERVIEW':
- state.overview = True
- state.query = ''
- else:
- state.page = self.destination
- state.overview = False
- state.query = ''
- if self.section:
- keys = set(filter(None, state.open_sections.split('|')))
- keys.add(self.section)
- state.open_sections = '|'.join(sorted(keys))
- elif self.mode == 'PAGE' and self.destination == 'DEBUG':
- keys = set(filter(None, state.open_sections.split('|')))
- keys.add('debug')
- state.open_sections = '|'.join(sorted(keys))
- _redraw(self, context)
- return {'FINISHED'}
-
-
-class SG_OT_PanelSection(bpy.types.Operator):
- bl_idname = 'stablegen.panel_section'
- bl_label = 'Expand Section'
- bl_description = 'Expand or collapse this section, or pin it to the Workbench overview'
- bl_options = {'INTERNAL'}
- variant: bpy.props.EnumProperty(items=[(key, key.title(), '') for key in STATE_NAMES])
- section: bpy.props.StringProperty()
- pin: bpy.props.BoolProperty(default=False)
-
- def execute(self, context):
- state = getattr(context.window_manager, STATE_NAMES[self.variant])
- field = 'pinned_sections' if self.pin else 'open_sections'
- keys = set(filter(None, getattr(state, field).split('|')))
- if self.section in keys:
- keys.remove(self.section)
- else:
- keys.add(self.section)
- setattr(state, field, '|'.join(sorted(keys)))
- _redraw(self, context)
- return {'FINISHED'}
-
-
-class SG_OT_PanelCamera(bpy.types.Operator):
- bl_idname = 'stablegen.panel_camera'
- bl_label = 'View Camera'
- bl_description = 'Select this camera and look through it in the viewport'
- bl_options = {'INTERNAL'}
- camera_name: bpy.props.StringProperty()
-
- @classmethod
- def poll(cls, context):
- return not sg_modal_active(context)
-
- def execute(self, context):
- camera = context.scene.objects.get(self.camera_name)
- if camera is None or camera.type != 'CAMERA':
- self.report({'ERROR'}, 'Camera is no longer in this scene')
- return {'CANCELLED'}
- from ..cameras.operators import switch_viewport_to_camera
- switch_viewport_to_camera(context, camera)
- if camera.name in context.view_layer.objects:
- for obj in context.selected_objects:
- obj.select_set(False)
- camera.select_set(True)
- context.view_layer.objects.active = camera
- return {'FINISHED'}
-
-
-class SG_UL_PanelCameras(bpy.types.UIList):
- """A compact view selector with editable per-view descriptions."""
- bl_idname = 'SG_UL_PanelCameras'
-
- def draw_item(self, context, layout, data, item, icon, active_data, active_property, index):
- camera = item
- cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']
- prompt = context.scene.camera_prompts.get(camera.name)
- row = layout.row(align=True)
- row.label(text=f'{cameras.index(camera) + 1:02}', icon='CAMERA_DATA')
- row.label(text=item.name)
- button = row.operator('stablegen.panel_camera', text='', icon='HIDE_OFF')
- button.camera_name = item.name
- if context.region.width >= 430 and prompt:
- row.prop(prompt, 'prompt', text='')
-
- def filter_items(self, context, data, property):
- return [self.bitflag_filter_item if obj.type == 'CAMERA' else 0
- for obj in getattr(data, property)], []
-
-
-def _state(context, variant):
- return getattr(context.window_manager, STATE_NAMES[variant])
-
-
-def _nav_button(layout, variant, destination, text, icon, *, active=False, mode='PAGE', section=''):
- op = layout.operator('stablegen.panel_navigate', text=text, icon=icon, depress=active)
- op.variant, op.destination, op.mode, op.section = variant, destination, mode, section
-
-
-def _section(layout, section, state, variant, *, force_open=False, pinnable=False, title=None):
- expanded = force_open or section.key in state.open_sections.split('|')
- box = layout.box()
- header = box.row(align=True)
- if force_open:
- header.label(text='', icon='VIEWZOOM')
- else:
- button = header.operator('stablegen.panel_section', text='',
- icon='TRIA_DOWN' if expanded else 'TRIA_RIGHT', emboss=False)
- button.variant, button.section = variant, section.key
- header.label(text=title or section.title, icon=section.icon)
- if pinnable:
- pin = header.operator('stablegen.panel_section', text='',
- icon='SOLO_ON' if section.key in state.pinned_sections.split('|') else 'SOLO_OFF',
- emboss=False)
- pin.variant, pin.section, pin.pin = variant, section.key, True
- if expanded:
- section.content.render(box.column(), contents=True,
- omit_properties={'architecture_mode'} if section.key == 'main' else (),
- narrow=bpy.context.region.width < 420 if bpy.context.region else False)
-
-
-def _available_pages(document):
- keys = {section.page for section in document.sections}
- return [item for item in PAGES if item[0] in keys]
-
-
-def _effective_page(document, requested):
- pages = [item[0] for item in _available_pages(document)]
- return requested if requested in pages else ('GENERATE' if 'GENERATE' in pages else next(iter(pages), None))
-
-
-def _header(layout, context, variant, subtitle, document):
- scene = context.scene
- row = layout.row()
- row.scale_y = 1.15
- row.label(text=variant.title(), icon={'STUDIO': 'WORKSPACE', 'WORKBENCH': 'NODETREE', 'FOCUS': 'SEQ_SEQUENCER'}[variant])
- right = row.row()
- right.alignment = 'RIGHT'
- right.label(text=subtitle)
- row = layout.row(align=True)
- architecture = row.row()
- architecture.alert = document.architecture_alert
- architecture.prop(scene, 'architecture_mode', text='')
- cameras = sum(obj.type == 'CAMERA' for obj in scene.objects)
- row.label(text=f'{cameras} views', icon='CAMERA_DATA')
- for target in document.architecture_targets:
- layout.label(text=target)
-
-
-def _shared(layout, context, document, *, idle_generation=True):
- if document.presets:
- document.presets.render(layout, contents=True)
- for notice in document.notices:
- notice.render(layout)
- for action in document.actions:
- # Baking remains available on Output; active baking progress stays
- # shared across pages, like generation and cancellation.
- if action.has_operator('object.bake_textures'):
- continue
- active = any(c.method == 'progress' or (c.method == 'operator' and
- (c.kwargs.get('icon') in {'CANCEL', 'TIME'} or c.args[0] == 'stablegen.resolve_masked_edit'))
- for c in action.controls())
- if not idle_generation and not active and action.has_operator(
- 'object.test_stable', 'object.stablegen_regenerate', 'object.trellis2_generate',
- 'object.trellis2_batch_generate', 'stablegen.masked_edit'):
- continue
- action.render(layout)
-
-
-def _output_actions(layout, document):
- for action in document.actions:
- if action.has_operator('object.bake_textures'):
- action.render(layout)
-
-
-def _deliver(layout, document, state, variant, sections):
- # Configure material output before baking, then choose export formats.
- ordered = list(sections)
- for section in ordered:
- if section.key == 'show_output_material_settings':
- _section(layout, section, state, variant, pinnable=variant == 'WORKBENCH')
- _output_actions(layout, document)
- for section in ordered:
- if section.key != 'show_output_material_settings':
- _section(layout, section, state, variant, pinnable=variant == 'WORKBENCH')
-
-
-def _camera_browser(layout, context, state):
- if any(obj.type == 'CAMERA' for obj in context.scene.objects):
- box = layout.box()
- row = box.row()
- row.label(text='View Navigator', icon='CAMERA_DATA')
- box.template_list('SG_UL_PanelCameras', '', context.scene, 'objects', state, 'camera_index', rows=4, maxrows=6)
-
-
-class SG_MT_WorkbenchPages(bpy.types.Menu):
- bl_idname = 'SG_MT_WorkbenchPages'
- bl_label = 'Workbench Pages'
-
- def draw(self, context):
- for key, label, description, icon, number in _available_pages(capture_panel(context)):
- _nav_button(self.layout, 'WORKBENCH', key, label, icon)
-
-
-class _VariantPanel:
- bl_space_type = 'VIEW_3D'
- bl_region_type = 'UI'
- bl_options = set()
-
- @classmethod
- def poll(cls, context):
- return context.mode in {'OBJECT', 'PAINT_TEXTURE'}
-
-
-class SG_PT_Studio(_VariantPanel, bpy.types.Panel):
- bl_idname = 'SG_PT_Studio'
- bl_label = 'StableGen Studio'
- bl_category = 'SG Studio'
-
- def draw(self, context):
- layout = self.layout
- state = _state(context, 'STUDIO')
- document = capture_panel(context)
- _header(layout, context, 'STUDIO', 'Task workspace', document)
- _shared(layout, context, document)
- available = _available_pages(document)
- page = _effective_page(document, state.page)
- nav = layout.grid_flow(row_major=True, columns=3 if context.region.width >= 360 else 2,
- even_columns=True, even_rows=True, align=True)
- for key, label, description, icon, number in available:
- _nav_button(nav, 'STUDIO', key, label, icon, active=page == key)
- layout.separator(factor=0.6)
- if page == 'CAMERAS':
- _camera_browser(layout, context, state)
- if page == 'OUTPUT':
- _deliver(layout, document, state, 'STUDIO', (s for s in document.sections if s.page == page))
- return
- for section in document.sections:
- if section.page == page:
- _section(layout, section, state, 'STUDIO')
-
-
-def _card_summary(section, scene):
- summaries = {
- 'main': 'Prompt, model & generation mode',
- 'camera_tools': 'Create, clone & frame views',
- 'export': 'Materials & game engine formats',
- 'show_texturing_experiments': 'Optional research controls',
- 'print': 'Palette, slices & print exports',
- 'show_trellis2_texture_settings': 'Native texture generation',
- 'show_trellis2_camera_settings': 'Place views for texturing',
- 'show_masking_inpainting_settings': 'Masks & texture repair',
- 'show_core_settings': f'{scene.steps} steps · CFG {scene.cfg:g}',
- 'show_lora_settings': f'{len(scene.lora_units)} LoRA units',
- 'show_image_guidance_settings': 'References & context render',
- 'show_mode_specific_settings': 'Controls for the current mode',
- 'show_scene_understanding_settings': f'Angle {scene.discard_factor:g}° · exponent {scene.weight_exponent:g}',
- 'show_camera_options': 'Prompts & generation order',
- 'show_output_material_settings': 'PBR, display & resolution',
- 'show_trellis2_mesh_settings': 'Geometry & post-processing',
- 'show_trellis2_autorig_settings': 'Rigging, poses & animation',
- 'queue': 'Queued scenes & recording',
- 'tools': 'Import, prepare & process',
- 'debug': 'Materials, measurements & tests',
- }
- return summaries.get(section.key, 'Open settings')
-
-
-class SG_PT_Workbench(_VariantPanel, bpy.types.Panel):
- bl_idname = 'SG_PT_Workbench'
- bl_label = 'StableGen Workbench'
- bl_category = 'SG Workbench'
-
- def draw(self, context):
- layout = self.layout
- state = _state(context, 'WORKBENCH')
- document = capture_panel(context)
- _header(layout, context, 'WORKBENCH', 'Feature browser', document)
- _shared(layout, context, document)
- page = _effective_page(document, state.page)
- row = layout.row(align=True)
- _nav_button(row, 'WORKBENCH', '', 'Overview', 'HOME', active=state.overview, mode='OVERVIEW')
- label, icon = ('Pages', 'SHORTDISPLAY') if state.overview else PAGE_LABELS.get(page, ('Pages', 'SHORTDISPLAY'))
- row.menu('SG_MT_WorkbenchPages', text=label, icon=icon)
- layout.prop(state, 'query', text='', icon='VIEWZOOM')
- query = state.query.strip().casefold()
- if query:
- matches = [section for section in document.sections if query in section.search_text()]
- layout.label(text=f'{len(matches)} matching {"section" if len(matches) == 1 else "sections"}', icon='FILTER')
- for section in matches:
- _section(layout, section, state, 'WORKBENCH', force_open=True, pinnable=True)
- if not matches:
- layout.label(text='No matching settings.', icon='INFO')
- layout.label(text='Check the architecture or mode.')
- return
- if not state.overview:
- if page == 'CAMERAS':
- _camera_browser(layout, context, state)
- if page == 'OUTPUT':
- _deliver(layout, document, state, 'WORKBENCH', (s for s in document.sections if s.page == page))
- return
- for section in document.sections:
- if section.page == page:
- _section(layout, section, state, 'WORKBENCH', pinnable=True)
- return
- pinned = [section for section in document.sections if section.key in state.pinned_sections.split('|')]
- if pinned:
- layout.prop(state, 'show_pins', text=f'Pinned Settings ({len(pinned)})',
- icon='TRIA_DOWN' if state.show_pins else 'TRIA_RIGHT', emboss=False)
- if state.show_pins:
- for section in pinned:
- _section(layout, section, state, 'WORKBENCH', pinnable=True)
- layout.label(text='Browse Features', icon='SHORTDISPLAY')
- for page, label, description, icon, number in _available_pages(document):
- layout.label(text=label, icon=icon)
- grid = layout.grid_flow(row_major=True, columns=2 if context.region.width >= 410 else 1,
- even_columns=True, even_rows=False, align=False)
- for section in document.sections:
- if section.page != page:
- continue
- box = grid.box()
- row = box.row(align=True)
- _nav_button(row, 'WORKBENCH', page, section.title, section.icon, section=section.key)
- box.label(text=_card_summary(section, context.scene))
-
-
-def _focus_sections(document, stage):
- pages = {
- 'SETUP': {'GENERATE', 'MESH'}, 'VIEWS': {'CAMERAS'},
- 'RUN': {'GENERATE'}, 'PROJECT': {'BLEND', 'DEBUG'},
- 'DELIVER': {'OUTPUT', 'PRINT'}, 'UTILITY': {'TOOLS', 'DEBUG'},
- }[stage]
- for section in document.sections:
- if section.page not in pages:
- continue
- if stage == 'SETUP' and section.key in {'show_mode_specific_settings', 'show_masking_inpainting_settings'}:
- continue
- if stage == 'RUN' and section.key not in {'show_mode_specific_settings', 'show_masking_inpainting_settings', 'show_image_guidance_settings', 'main'}:
- continue
- if stage == 'PROJECT' and section.key == 'show_texturing_experiments':
- continue
- yield section
-
-
-class SG_PT_Focus(_VariantPanel, bpy.types.Panel):
- bl_idname = 'SG_PT_Focus'
- bl_label = 'StableGen Focus'
- bl_category = 'SG Focus'
-
- def draw(self, context):
- layout = self.layout
- state = _state(context, 'FOCUS')
- document = capture_panel(context)
- _header(layout, context, 'FOCUS', 'Guided workflow', document)
- _shared(layout, context, document, idle_generation=state.stage == 'RUN')
- rail = layout.grid_flow(row_major=True, columns=2, even_columns=True, even_rows=True, align=True)
- for key, label, description, icon, number in STAGES:
- _nav_button(rail, 'FOCUS', key, f'{number + 1} {label}', icon,
- active=state.stage == key, mode='STAGE')
- layout.separator(factor=0.6)
- instructions = {
- 'SETUP': 'Choose models and generation settings.',
- 'VIEWS': 'Arrange cameras and view prompts.',
- 'RUN': 'Review the prompt, then generate.',
- 'PROJECT': 'Inspect coverage and blending.',
- 'DELIVER': 'Set materials, bake, then export.',
- 'UTILITY': 'Tools, scene queue and experiments.',
- }
- layout.label(text=instructions[state.stage], icon='INFO')
- if state.stage == 'VIEWS':
- _camera_browser(layout, context, state)
- sections = list(_focus_sections(document, state.stage))
- if state.stage == 'DELIVER':
- _deliver(layout, document, state, 'FOCUS', sections)
- else:
- for section in sections:
- title = None
- if section.key == 'main':
- title = 'Model & Generation Setup' if state.stage == 'SETUP' else 'Review Prompt & Model'
- _section(layout, section, state, 'FOCUS', title=title)
- if not sections:
- layout.label(text='No additional settings for this stage in the current mode.', icon='INFO')
- navigation = layout.row(align=True)
- keys = [item[0] for item in STAGES]
- index = keys.index(state.stage)
- if index:
- _nav_button(navigation, 'FOCUS', keys[index - 1], 'Previous', 'BACK', mode='STAGE')
- if index < len(keys) - 1:
- _nav_button(navigation, 'FOCUS', keys[index + 1], 'Next', 'FORWARD', mode='STAGE')
-
-
-VARIANT_UI_CLASSES = [SGPanelVariantState, SG_OT_PanelNavigate, SG_OT_PanelSection,
- SG_OT_PanelCamera, SG_UL_PanelCameras,
- SG_MT_WorkbenchPages,
- SG_PT_Studio, SG_PT_Workbench, SG_PT_Focus]
-
-
-def register_variant_properties():
- for name in STATE_NAMES.values():
- setattr(bpy.types.WindowManager, name, bpy.props.PointerProperty(type=SGPanelVariantState, options={'SKIP_SAVE'}))
-
-
-def unregister_variant_properties():
- for name in STATE_NAMES.values():
- if hasattr(bpy.types.WindowManager, name):
- delattr(bpy.types.WindowManager, name)
diff --git a/stablegen/ui/presentation.py b/stablegen/ui/presentation.py
index 0524470..e4531e1 100644
--- a/stablegen/ui/presentation.py
+++ b/stablegen/ui/presentation.py
@@ -34,6 +34,27 @@ STRUCTURAL_PROPERTIES = {
*SECTION_INFO, 'show_generation_params', 'show_advanced_params', 'sg_show_queue',
}
+# Group utilities by the data they operate on within the Tools tab.
+# Studio cards and native alternate panels share these groups.
+TOOL_SECTIONS = {
+ 'mesh_tools': ('Mesh & rig utilities', 'TOOLS', 'MESH_DATA', (
+ ('object.apply_all_mesh_modifiers', 'Apply all modifiers', 'modifier'),
+ ('object.curves_to_mesh', 'Convert curves to mesh', 'curve'),
+ ('object.stablegen_local_postprocess', 'Local post-processing', 'modifier'),
+ ('object.stablegen_make_solid', 'Make solid', 'modifier'),
+ ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig'),
+ )),
+ 'material_tools': ('Material utilities', 'TOOLS', 'MATERIAL', (
+ ('object.switch_material', 'Switch material', 'material'),
+ )),
+ 'projection_tools': ('Projection utilities', 'TOOLS', 'MOD_MIRROR', (
+ ('object.stablegen_mirror_reproject', 'Mirror last projection', 'mirror'),
+ )),
+ 'presentation_tools': ('Presentation export', 'TOOLS', 'RENDER_ANIMATION', (
+ ('object.export_orbit_gif', 'Export orbit GIF / MP4', 'camera'),
+ )),
+}
+
class ExpandedData:
"""Override only presentation expansion flags; forward all real scene data."""
@@ -256,6 +277,34 @@ def _main_content(node):
return node
+def _tool_sections(source):
+ """Split utility controls without losing inherited states or invoke context."""
+ moved = {name for _, _, _, commands in TOOL_SECTIONS.values()
+ for name, _, _ in commands}
+
+ def select(node, names, remaining=False):
+ result = Layout(node.method, node.args, dict(node.kwargs))
+ result.attributes.update(node.attributes)
+ for child in node.children:
+ if isinstance(child, Layout):
+ selected = select(child, names, remaining)
+ if selected.children:
+ result.children.append(selected)
+ elif child.method == 'operator' and child.args[0] in names:
+ if not remaining:
+ result.children.append(child)
+ elif remaining:
+ result.children.append(child)
+ return result
+
+ yield Section('tools', 'Tools', 'TOOLS', 'TOOL_SETTINGS',
+ select(source, moved, remaining=True))
+ for key, (title, page, icon, commands) in TOOL_SECTIONS.items():
+ content = select(source, {name for name, _, _ in commands})
+ if list(content.controls()):
+ yield Section(key, title, page, icon, content)
+
+
def capture_panel(context):
root = Layout()
StableGenPanel.draw(SimpleNamespace(layout=root), ExpandedContext(context))
@@ -282,7 +331,7 @@ def capture_panel(context):
elif child.has_operator('stablegen.debug_solid_colors'):
document.sections.append(Section('debug', 'Debug / Diagnostics', 'DEBUG', 'GHOST_ENABLED', child))
elif child.has_operator('object.switch_material'):
- document.sections.append(Section('tools', 'Tools', 'TOOLS', 'TOOL_SETTINGS', child))
+ document.sections.extend(_tool_sections(child))
elif child.has_operator(*action_ops) or any(c.method == 'progress' for c in child.controls()):
document.actions.append(child)
elif child.has_operator('object.add_cameras', 'object.clone_camera', 'object.collect_camera_prompts',
diff --git a/stablegen/ui/studio.py b/stablegen/ui/studio.py
index ce5ce27..7025ae1 100644
--- a/stablegen/ui/studio.py
+++ b/stablegen/ui/studio.py
@@ -18,15 +18,20 @@ from . import studio_model as model
from . import studio_diagnostics as diagnostics
from . import studio_hierarchy as hierarchy_model
from . import studio_cards as cards
-from .presentation import Layout, Control, Section, STRUCTURAL_PROPERTIES
+from . import studio_help as help_text
+from . import studio_actions as action_style
+from . import studio_lora as lora
+from . import studio_tips as tips
+from .presentation import Layout, Control, Section, STRUCTURAL_PROPERTIES, TOOL_SECTIONS
from .studio_text import TextBuffer, wrap
from .studio_widgets import (Painter, FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP,
TEXT_LINE_HEIGHT, TEXT_PADDING, font_size)
from .presets import PRESETS
from ..utils import sg_modal_active
-from ..core import ADDON_PKG
+from ..core import ADDON_PKG, legacy_panel_enabled
+from ..generation_status import WAITING_STAGES
-TAB = 'SG Studio UI'
+TAB = 'StableGen'
PAGES = [('GENERATE', 'Texture'), ('CAMERAS', 'Cameras'), ('BLEND', 'Blending')]
MORE = [('TOOLS', 'Tools'), ('QUEUE', 'Scene queue'), ('DEBUG', 'Diagnostics'),
('MESH', 'Mesh & rig'), ('PRINT', '3D printing'), ('EXPERIMENTS', 'Experiments')]
@@ -96,6 +101,9 @@ class StudioSession:
self.last_refresh = 0
self.edit = None
self.drag = None
+ self.camera_drag = None
+ self.camera_rows = []
+ self.camera_clip = None
self.menu = None
self.query = ''
self.popup = False
@@ -112,10 +120,14 @@ class StudioSession:
self.ctrl = False
self.camera_images = {}
self.card_bounds = {}
+ # Narrowest width while the widen callout was shown in this session.
+ self.callout_width = None
def valid(self):
try:
- return (self.alive and self.window in bpy.context.window_manager.windows[:]
+ # Choosing the legacy panel in preferences ends every Studio session.
+ return (self.alive and not legacy_panel_enabled()
+ and self.window in bpy.context.window_manager.windows[:]
and self.area in self.window.screen.areas[:] and self.area.type == 'VIEW_3D'
and self.region in self.area.regions[:])
except ReferenceError:
@@ -189,10 +201,10 @@ class StudioSession:
self.clear_hover(leave=True)
return None
inside = self.pointer_inside()
- if self.drag or self.edit and self.edit['selecting']:
+ if self.camera_drag or self.drag or self.edit and self.edit['selecting']:
self.clear_hover()
if cursor:
- self.set_cursor('MOVE_X' if self.drag else 'TEXT')
+ self.set_cursor('MOVE_Y' if self.camera_drag else 'MOVE_X' if self.drag else 'TEXT')
return None
if not inside:
self.clear_hover()
@@ -214,7 +226,7 @@ class StudioSession:
return target
def tooltip_target(self, targets=None):
- if (not bpy.context.preferences.view.show_tooltips or self.drag or self.popup
+ if (not bpy.context.preferences.view.show_tooltips or self.camera_drag or self.drag or self.popup
or self.notice and time.monotonic() < self.notice_until):
return None
target = self.hit_target(targets) if self.pointer_inside() else None
@@ -226,11 +238,18 @@ class StudioSession:
def tick(self, now):
if not self.active() or self.popup:
+ self.camera_drag = None
self.clear_hover(leave=True)
return
if now - self.last_refresh >= .25:
self.refresh()
self.update_hover()
+ if self.camera_drag and self.camera_clip and self.pointer_inside():
+ _, top, _, height = self.camera_clip
+ dy = -10 if self.pointer[1] < top + 24 else 10 if self.pointer[1] > top + height - 24 else 0
+ if dy:
+ self.scroll['CAMERAS'] = max(0, min(getattr(self, 'max_scroll', 0), self.scroll.get('CAMERAS', 0) + dy))
+ self.area.tag_redraw()
tooltip = self.tooltip_target()
if (tooltip.key if tooltip else '') != self.tooltip_key:
self.area.tag_redraw()
@@ -246,6 +265,7 @@ class StudioSession:
self.page = 'MESH' if self.architecture == 'trellis2' else 'GENERATE'
if ctx.scene.as_pointer() != self.scene_pointer:
self.edit = self.drag = self.menu = None
+ self.camera_drag = None
self.scene_pointer = ctx.scene.as_pointer()
self.last_projection = None
self.dirty_projection = False
@@ -262,6 +282,13 @@ class StudioSession:
self.last_projection = values
if self.busy and self.edit:
self.edit = None
+ if (self.edit and 'lora_snapshot' in self.edit
+ and self.edit['lora_snapshot'] != lora.snapshot(ctx.scene)):
+ self.edit = None
+ if self.menu and self.menu.get('kind') == 'lora' and not lora.valid_menu(self, self.menu):
+ self.menu = None
+ if self.camera_drag and (self.busy or self.camera_drag['names'] != tuple(c.name for c in self.ordered_cameras())):
+ self.camera_drag = None
self.area.tag_redraw()
def tell(self, message):
@@ -288,6 +315,9 @@ class StudioSession:
result = op(mode, **(properties or {}))
if name == 'stablegen.studio_diagnostic' and 'FINISHED' in result:
_undo('Change diagnostic display')
+ if name == 'stablegen.studio_lora' and 'FINISHED' in result:
+ operation = (properties or {}).get('operation', 'REPLACE').title()
+ _undo(operation + ' LoRA adapter')
if name in {'object.stablegen_reproject', 'object.test_stable', 'object.stablegen_regenerate'} and 'CANCELLED' not in result:
self.dirty_projection = False
self.refresh()
@@ -314,6 +344,8 @@ class StudioSession:
return
try:
with _context(self):
+ if 'lora_snapshot' in edit and edit['lora_snapshot'] != lora.snapshot(bpy.context.scene):
+ raise ReferenceError('The adapter list changed while this value was being edited.')
binding, text = edit['binding'], edit['buffer'].text
prop = binding.rna(bpy.context)
value = float(text) if prop.type == 'FLOAT' else int(text) if prop.type == 'INT' else text
@@ -353,6 +385,8 @@ class StudioSession:
'rect': target.rect, 'lines': self.text_fields.get(target.key, ([],0))[0],
'scroll': self.text_scroll.get(target.key, 0), 'follow_caret': False,
'multiline': bool(target.action[2]), 'selecting': False}
+ if binding and binding.path.startswith('lora_units['):
+ self.edit['lora_snapshot'] = lora.snapshot(bpy.context.scene)
self.menu = None
self.area.tag_redraw()
@@ -376,6 +410,7 @@ class StudioSession:
def navigate(self, page):
self.commit()
+ self.camera_drag = None
self.page, self.menu = page, None
self.clear_hover()
if page == 'SEARCH':
@@ -426,8 +461,13 @@ class StudioSession:
self.drag = {'binding': action[1], 'min': action[2], 'max': action[3],
'rect': target.rect, 'before': before}
self.slide(self.pointer[0])
+ elif action[0] == 'camera-drag':
+ self.commit()
+ self.camera_drag = {'name': action[1], 'names': tuple(c.name for c in self.ordered_cameras())}
elif action[0] == 'menu-item':
menu = self.menu
+ if action[1] in menu.get('disabled', ()):
+ return
self.menu = None
if menu.get('binding'):
self.set_value(menu['binding'], action[1])
@@ -437,6 +477,12 @@ class StudioSession:
menu['callback'](action[1])
else:
self.navigate(action[1])
+ elif action[0] == 'menu-lora-close':
+ self.menu = None
+ elif action[0] == 'menu-lora-search':
+ lora.select_search(self)
+ elif action[0] == 'menu-lora-folder':
+ lora.folders(self)
self.area.tag_redraw()
def slide(self, x):
@@ -447,6 +493,41 @@ class StudioSession:
value = drag['min'] + max(0, min(1, (x - left) / width)) * (drag['max'] - drag['min'])
self.set_value(drag['binding'], value, undo=False)
+ def ordered_cameras(self):
+ from ..texturing.view_plan import order_cameras
+ scene = bpy.context.scene
+ return order_cameras((o for o in scene.objects if o.type == 'CAMERA'),
+ [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ())
+
+ def camera_drop(self, y):
+ """Insertion boundary among the remaining rows; no scene edits during drag."""
+ rows = [(name, rect) for name, rect in self.camera_rows if name != self.camera_drag['name']]
+ for name, rect in rows:
+ if y < rect[1] + rect[3] / 2:
+ return name, rect[1] - 4
+ return '', rows[-1][1][1] + rows[-1][1][3] + 4 if rows else y
+
+ def finish_camera_drag(self, cancel=False):
+ drag = self.camera_drag
+ if not drag:
+ return
+ before, _ = self.camera_drop(self.pointer[1])
+ self.camera_drag = None
+ # Leaving the canvas cancels, as do scene edits while a drag is pending.
+ if (not cancel and not self.busy and self.pointer_inside() and self.camera_clip
+ and self.camera_clip[1] <= self.pointer[1] <= self.camera_clip[1] + self.camera_clip[3]
+ and drag['names'] == tuple(c.name for c in self.ordered_cameras())):
+ self.call('stablegen.studio_reorder_camera', {'camera_name': drag['name'], 'before_name': before}, mode='EXEC_DEFAULT')
+ self.update_hover()
+ self.area.tag_redraw()
+
+ def camera_order_menu(self, rect):
+ self.commit()
+ prop = model.operator('stablegen.apply_camera_order_preset').get_rna_type().properties['strategy']
+ self.menu = {'anchor': rect, 'items': [(i.identifier, i.name, i.description) for i in prop.enum_items],
+ 'query': '', 'binding': None, 'index': 0, 'scroll': 0,
+ 'callback': lambda strategy: self.call('stablegen.studio_sort_cameras', {'strategy': strategy}, mode='EXEC_DEFAULT')}
+
def select_caret(self, x, y, extend=False):
edit = self.edit
if not edit or not edit['lines']:
@@ -535,6 +616,7 @@ class StudioSession:
mouse_event = event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE', 'LEFTMOUSE', 'RIGHTMOUSE',
'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'TRACKPADPAN'}
if event.type == 'WINDOW_DEACTIVATE':
+ self.camera_drag = None
_window_mouse.pop(self.key[0], None)
self.clear_hover(leave=True)
return {'PASS_THROUGH'}
@@ -545,11 +627,26 @@ class StudioSession:
inside = self.pointer_inside()
x, y = self.pointer
if not self.active() or self.popup:
+ self.camera_drag = None
self.clear_hover(leave=True)
if not self.active():
self.commit()
self.menu = None
return {'PASS_THROUGH'}
+ if self.camera_drag:
+ if event.type in {'ESC', 'RIGHTMOUSE'} and event.value == 'PRESS':
+ self.finish_camera_drag(cancel=True)
+ return {'RUNNING_MODAL'}
+ if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':
+ self.finish_camera_drag()
+ return {'RUNNING_MODAL'}
+ if event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE'}:
+ self.clear_hover()
+ self.set_cursor('MOVE_Y')
+ self.area.tag_redraw()
+ return {'RUNNING_MODAL'}
+ # Keep shortcuts and other commands from changing the scene mid-drag.
+ return {'RUNNING_MODAL'}
if event.value == 'PRESS' and event.type == 'ESC' and self.drag:
drag, self.drag = self.drag, None
self.set_value(drag['binding'], drag['before'], undo=False)
@@ -571,7 +668,7 @@ class StudioSession:
self.area.tag_redraw()
return {'RUNNING_MODAL'}
target = self.update_hover(moved=True)
- if target and self.menu:
+ if target and target.enabled and self.menu and isinstance(target.action, tuple) and target.action[0] == 'menu-item':
self.menu['index'] = next((i for i, item in enumerate(self.menu_items())
if item[0] == target.action[1]), self.menu['index'])
# The GPU canvas covers native controls; do not let those steal hover.
@@ -605,16 +702,21 @@ class StudioSession:
self.area.tag_redraw()
self.update_hover()
return {'RUNNING_MODAL'}
+ if self.menu.get('kind') == 'lora' and lora.keyboard(self, event):
+ return {'RUNNING_MODAL'}
if event.value == 'PRESS' and event.type in {'UP_ARROW', 'DOWN_ARROW', 'RET', 'NUMPAD_ENTER', 'BACK_SPACE'} or (event.value == 'PRESS' and getattr(event, 'unicode', '')):
- self.clear_hover(leave=True)
+ self.clear_hover()
items = self.menu_items()
if event.type in {'UP_ARROW', 'DOWN_ARROW'}:
- self.menu['index'] = max(0, min(len(items) - 1, self.menu['index'] + (-1 if event.type == 'UP_ARROW' else 1)))
- self.menu['scroll'] = max(0, self.menu['index'] - 5)
+ direction = -1 if event.type == 'UP_ARROW' else 1
+ available = [i for i, item in enumerate(items) if item[0] not in self.menu.get('disabled', ())]
+ choices = [i for i in available if (i - self.menu['index']) * direction > 0]
+ self.menu['index'] = (min(choices) if direction > 0 else max(choices)) if choices else self.menu['index']
+ self.menu['scroll'] = max(0, self.menu['index'] - self.menu.get('rows', 6) + 1)
elif event.type in {'RET', 'NUMPAD_ENTER'} and items:
item = items[min(self.menu['index'], len(items) - 1)]
from .studio_widgets import Target
- self.activate(Target('menu', (0, 0, 0, 0), ('menu-item', item[0])))
+ self.activate(Target('menu', (0, 0, 0, 0), ('menu-item', item[0]), item[0] not in self.menu.get('disabled', ())))
elif event.type == 'BACK_SPACE':
self.menu['query'] = self.menu['query'][:-1]
self.menu['index'] = self.menu['scroll'] = 0
@@ -646,7 +748,7 @@ class StudioSession:
return {'RUNNING_MODAL'}
if event.type == 'LEFTMOUSE' and event.value in {'PRESS', 'DOUBLE_CLICK'}:
target = self.hit_target()
- if self.menu and (target is None or not isinstance(target.action, tuple) or target.action[0] != 'menu-item'):
+ if self.menu and (target is None or not isinstance(target.action, tuple) or not target.action[0].startswith('menu-')):
self.menu = None
self.area.tag_redraw()
return {'RUNNING_MODAL'}
@@ -668,6 +770,11 @@ class StudioSession:
if event.value == 'PRESS' and (event.ctrl or event.oskey) and event.type == 'K':
self.navigate('SEARCH')
return {'RUNNING_MODAL'}
+ # Keep the canvas panel's covered header from collapsing (A, Enter)
+ # or being pinned to other tabs from its context menu.
+ if event.value == 'PRESS' and (event.type == 'RIGHTMOUSE' or event.type in {'A', 'RET', 'NUMPAD_ENTER'}
+ and not (event.ctrl or event.oskey or event.alt or event.shift)):
+ return {'RUNNING_MODAL'}
if (event.value == 'PRESS' and not mouse_event and event.type not in
{'LEFT_SHIFT', 'RIGHT_SHIFT', 'LEFT_CTRL', 'RIGHT_CTRL', 'LEFT_ALT', 'RIGHT_ALT', 'OSKEY'}):
# Native shortcuts can open dialogs that have their own cursor handling.
@@ -680,13 +787,15 @@ class StudioSession:
def draw_binding(self, painter, binding, label, x, y, width, *, enabled=True, multiline=False, height=112, corners='ALL'):
ctx = bpy.context
prop, value = binding.rna(ctx), binding.value(ctx)
+ hint = help_text.property_hint(binding, ctx)
+ label_y = y
key = _binding_key(binding)
enabled = enabled and not self.busy and not prop.is_readonly
if prop.type == 'BOOLEAN':
lines = wrap(label, width - 40, painter.measure)
height = max(CONTROL_HEIGHT, len(lines) * 16 + 6)
painter.switch(key, (x, y, width, height), label, value, ('toggle', binding),
- enabled=enabled, hint=prop.description, hover=self.hovered(key))
+ enabled=enabled, hint=hint, hover=self.hovered(key))
return height + CONTROL_GAP
inline = (prop.type in {'INT', 'FLOAT'} and not prop.is_array and width >= 210
and not multiline and painter.measure(label) <= width - 100)
@@ -709,7 +818,7 @@ class StudioSession:
display = editing['buffer'].text if editing else value
lines, scroll = painter.text_field(key, (x, y, width, height), display,
('edit', binding, True), enabled=enabled,
- hint=prop.description, editing=editing['buffer'] if editing else None,
+ hint=hint, editing=editing['buffer'] if editing else None,
scroll=editing['scroll'] if editing else self.text_scroll.get(key, 0), multiline=True,
follow_caret=editing.get('follow_caret', True) if editing else False)
self.text_scroll[key] = scroll
@@ -718,6 +827,8 @@ class StudioSession:
editing.update(rect=(x, y, width, height), lines=lines, scroll=scroll, follow_caret=False)
painter.text(f'{len(str(display).split())} words', x + width - 55, y + height + 5, 10, 'muted')
painter.text('Ctrl Enter to finish' if editing else 'Click to edit · Enter adds a line', x, y + height + 5, 10, 'muted', width - 68)
+ painter.target(key + ':label', (x, label_y, label_width, label_height),
+ ('hint', None, False), False, hint)
return height + label_height + 24
if prop.type == 'ENUM':
label_value = model.enum_label(binding, ctx)
@@ -725,14 +836,14 @@ class StudioSession:
border='hover_border' if enabled and self.hovered(key) else 'menu_border', corners=corners)
painter.text(label_value, x + 8, y + 5, FONT_SIZE, 'menu_text' if enabled else 'disabled', width - 33)
painter.icon('down', x + width - 16, y + 6, 10, 'menu_text' if enabled else 'disabled')
- painter.target(key, (x, y, width, CONTROL_HEIGHT), ('enum', binding), enabled, prop.description)
+ painter.target(key, (x, y, width, CONTROL_HEIGHT), ('enum', binding), enabled, hint)
elif prop.type in {'STRING', 'INT', 'FLOAT'} and not getattr(prop, 'is_array', False):
display = editing['buffer'].text if editing else f'{value:.{prop.precision}f}'.rstrip('0').rstrip('.') if isinstance(value, float) and prop.precision > 0 else str(value)
filepath = prop.type == 'STRING' and prop.subtype in {'FILE_PATH', 'DIR_PATH'}
field_width = 90 if inline else width - 27 if filepath else width
field_x = x + width - field_width if inline else x
lines, scroll = painter.text_field(key, (field_x, y, field_width, CONTROL_HEIGHT), display,
- ('edit', binding, False), enabled=enabled, hint=prop.description,
+ ('edit', binding, False), enabled=enabled, hint=hint,
editing=editing['buffer'] if editing else None,
kind='number' if prop.type in {'INT','FLOAT'} else 'field')
if editing:
@@ -744,14 +855,19 @@ class StudioSession:
else:
color = getattr(prop, 'subtype', '') in {'COLOR', 'COLOR_GAMMA'} and prop.is_array
painter.button(key, (x, y, width - 34 if color else width, CONTROL_HEIGHT), 'Open color picker' if color else 'Edit ' + label, lambda: self.native(binding=binding),
- icon='settings', style='outlined', enabled=enabled, hint=prop.description)
+ icon='settings', style='outlined', enabled=enabled, hint=hint)
if color:
rgb = [max(0, min(1, c)) for c in value[:3]]
if prop.subtype == 'COLOR':
rgb = [12.92*c if c <= .0031308 else 1.055*c**(1/2.4)-.055 for c in rgb]
painter.rect(x + width - 27, y + 2, 24, CONTROL_HEIGHT - 4, (*rgb, 1), 3)
painter.target(key + ':color', (x + width - 30, y, 30, CONTROL_HEIGHT),
- lambda: self.native(binding=binding), enabled, prop.description)
+ lambda: self.native(binding=binding), enabled, hint)
+ # Help-only bounds are disjoint from editable fields. They do not start
+ # edits, join keyboard traversal, or capture prompt scrolling.
+ painter.target(key + ':label', (x, label_y, width - 100 if inline else label_width,
+ CONTROL_HEIGHT if inline else label_height),
+ ('hint', None, False), False, hint)
return label_height + CONTROL_HEIGHT + CONTROL_GAP
def binding(self, name):
@@ -784,6 +900,8 @@ class StudioSession:
'accent' if enabled else 'disabled', radius)
p.target(key + ':slider', (x, track_y - 7, width, 17), ('slider', binding, minimum, maximum),
enabled, binding.rna(bpy.context).description)
+ p.target(key + ':label', (x, y, width if narrow else width - edit_width - 8, 16),
+ ('hint', None, False), False, binding.rna(bpy.context).description)
return 65 if narrow else 46
def section_summary(self, key):
@@ -800,7 +918,12 @@ class StudioSession:
def draw_section(self, p, section, x, y, width, force=False, omit=()):
key = section.key
+ if key in TOOL_SECTIONS:
+ title, _page, _icon, commands = TOOL_SECTIONS[key]
+ return self.draw_actions(p, title, commands, x, y, width)
expanded = force or key in self.open
+ if key == 'show_lora_settings' and expanded:
+ return lora.draw_section(self, p, section, x, y, width)
summary = self.section_summary(key)
h = 40 if summary and not expanded else 29
if self.hovered('section:' + key):
@@ -871,7 +994,7 @@ class StudioSession:
card_body=card_body), child_anchors)
return end
- def draw_plain_control(self, p, live, x, y, width, section, index, label=None):
+ def draw_plain_control(self, p, live, x, y, width, section, index, label=None, *, corners='ALL'):
control = live.control
enabled = live.enabled
if control.method == 'prop':
@@ -910,20 +1033,33 @@ class StudioSession:
label = 'Move earlier' if control.properties.get('direction') == 'UP' else 'Move later'
with _viewport(self):
available = enabled and op.poll()
- icon = {'object.bake_textures': 'grid', 'object.switch_material': 'layers',
- 'object.export_game_engine': 'download', 'stablegen.prepare_mask_paint': 'settings'}.get(name, 'arrow')
- p.button(f'op:{section}:{index}:{name}', (x, y, width, CONTROL_HEIGHT), label,
- ('operator', name, control.properties), icon=icon, style='quiet',
- enabled=available, hover=self.hovered(f'op:{section}:{index}:{name}'),
- hint=op.get_rna_type().description)
+ hint = help_text.operator_hint(name, bpy.context, available, busy=self.busy)
+ key = f'op:{section}:{index}:{name}'
+ selection = action_style.selection(control)
+ if selection:
+ prop, value, kind = selection
+ p.selection(key, (x, y, width, CONTROL_HEIGHT), f'{kind} {value + 1}',
+ ('operator', name, control.properties), getattr(bpy.context.scene, prop) == value,
+ enabled=available, hint=hint)
+ else:
+ if section == 'print' and name == 'object.export_textured_print_obj':
+ label = 'Textured OBJ (Image Map)'
+ p.button(key, (x, y, width, CONTROL_HEIGHT), label,
+ ('operator', name, control.properties), icon=action_style.icon(control), style='outlined',
+ enabled=available, hover=self.hovered(key), hint=hint, corners=corners)
return y + CONTROL_HEIGHT + CONTROL_GAP
elif control.method == 'progress':
factor = max(0, min(1, control.kwargs.get('factor', 0)))
text = re.sub(r'\s*\(\s*\d+(?:\.\d+)?%\)\s*$', '', control.kwargs.get('text', ''))
p.text(text, x, y, 11, 'secondary', width - 38)
- p.text(f'{factor:.0%}', x + width - 34, y, 11, 'secondary')
+ waiting = any(text.startswith(stage + ' · ') for stage in WAITING_STAGES)
+ if not waiting or re.search(r'\(\s*\d+(?:\.\d+)?%\)\s*$', control.kwargs.get('text', '')):
+ p.text(f'{factor:.0%}', x + width - 34, y, 11, 'secondary')
p.rect(x, y + 17, width, 3, 'line', 1)
p.rect(x, y + 17, width * factor, 3, 'blue', 1)
+ if control.tooltip:
+ p.target(f'progress:{section}:{index}', (x, y, width, 22), None,
+ enabled=False, hint=control.tooltip)
return y + 28
elif control.method == 'template_list' and len(control.args) >= 6:
owner, name, index_owner, index_name = control.args[2:6]
@@ -940,12 +1076,62 @@ class StudioSession:
if status:
p.text(status.replace('_', ' ').capitalize(), x, y, 10, 'muted', width)
y += 17
- label = label or control.kwargs.get('text') or {'template_list': 'Edit list', 'template_curve_mapping': 'Edit curve',
- 'operator_menu_enum': 'Choose action'}.get(control.method, 'Open editor')
+ label, hint = help_text.native_help(control, label)
p.button(f'native:{section}:{index}', (x, y, width, CONTROL_HEIGHT), label,
- ('native', section, index), icon='settings', style='outlined', enabled=enabled and not self.busy)
+ ('native', section, index), icon='settings', style='outlined', enabled=enabled and not self.busy,
+ hint=hint)
return y + CONTROL_HEIGHT + CONTROL_GAP
+ def draw_operator_row(self, p, controls, x, y, width, section, enabled, alert):
+ """Join related native commands; reflow without truncating their labels."""
+ heading, captions = action_style.print_group(controls, section)
+ if heading:
+ p.text(heading, x, y, FONT_SIZE, 'secondary', width)
+ y += 19
+ labels = [captions.get(c.args[0]) or c.kwargs.get('text') or model.operator(c.args[0]).get_rna_type().name
+ for c in controls]
+ columns = len(controls)
+ while columns > 1 and any(p.measure(label) + (35 if action_style.icon(c) else 20) > width / columns
+ for c, label in zip(controls, labels)):
+ columns -= 1
+ for first in range(0, len(controls), columns):
+ row = controls[first:first + columns]
+ cw = width / len(row)
+ for i, c in enumerate(row):
+ corners = 'ALL' if len(row) == 1 else 'LEFT' if i == 0 else 'RIGHT' if i == len(row) - 1 else 'NONE'
+ self.draw_plain_control(p, model.LiveControl(c, enabled, alert), x + i * cw, y, cw,
+ section, self.control_index(section, c), labels[first + i], corners=corners)
+ y += CONTROL_HEIGHT + CONTROL_GAP
+ return y
+
+ def draw_color_selection(self, p, selector, color, x, y, width, section, enabled, alert):
+ """Keep native filament selection and color editing in one clear row."""
+ prop, value, kind = action_style.selection(selector)
+ op = model.operator(selector.args[0])
+ with _viewport(self):
+ available = enabled and op.poll()
+ hint = help_text.operator_hint(selector.args[0], bpy.context, available, busy=self.busy)
+ key = f'op:{section}:{self.control_index(section, selector)}:{selector.args[0]}'
+ picker_width = min(112, width * .47)
+ p.selection(key, (x, y, width, 28), f'{kind} {value + 1}',
+ ('operator', selector.args[0], selector.properties), getattr(bpy.context.scene, prop) == value,
+ enabled=available, hint=hint, accessory_width=picker_width + 10)
+ binding = model.Binding.from_data(color.args[0], color.args[1])
+ key = _binding_key(binding)
+ field = binding.rna(bpy.context)
+ editable = enabled and not self.busy and not field.is_readonly
+ cx, cy = x + width - picker_width - 3, y + 3
+ p.outline(cx, cy, picker_width, CONTROL_HEIGHT, 'raised',
+ 'hover_border' if editable and self.hovered(key) else 'tool_border', 2)
+ p.text('Edit color', cx + 8, cy + 4, FONT_SIZE, 'text' if editable else 'disabled', picker_width - 39)
+ rgb = [max(0, min(1, c)) for c in binding.value(bpy.context)[:3]]
+ if field.subtype == 'COLOR':
+ rgb = [12.92*c if c <= .0031308 else 1.055*c**(1/2.4)-.055 for c in rgb]
+ p.outline(cx + picker_width - 26, cy + 2, 24, CONTROL_HEIGHT - 4, (*rgb, 1), 'tool_border', 2)
+ p.target(key, (cx, cy, picker_width, CONTROL_HEIGHT), lambda: self.native(binding=binding),
+ editable, help_text.property_hint(binding, bpy.context))
+ return y + 28 + CONTROL_GAP
+
def draw_node(self, p, node, x, y, width, section, enabled=True, alert=False, omit=None, hierarchy=None, anchors=None, card_body=False):
omit = omit or set()
if hierarchy is None:
@@ -972,9 +1158,18 @@ class StudioSession:
continue
children.append(child)
flat = list(node.controls())
+ if node.method in {'row', 'split', 'column'} and len(children) >= 2 and all(
+ isinstance(c, Control) and c.method == 'operator' and not action_style.selection(c)
+ for c in children):
+ return self.draw_operator_row(p, children, x, y, width, section, enabled, alert)
if node.method in {'row', 'split'}:
labels = [c for c in flat if c.method == 'label' and c.kwargs.get('text') and not omitted(c)]
fields = [c for c in flat if c.method in {'prop', 'operator'} and not omitted(c)]
+ selectors = [c for c in fields if action_style.selection(c)]
+ colors = [c for c in fields if c.method == 'prop'
+ and c.args[0].bl_rna.properties[c.args[1]].subtype in {'COLOR', 'COLOR_GAMMA'}]
+ if len(fields) == 2 and len(selectors) == len(colors) == 1 and not labels:
+ return self.draw_color_selection(p, selectors[0], colors[0], x, y, width, section, enabled, alert)
if (len(labels) == 1 and len(fields) == 1
and not labels[0].kwargs['text'].startswith('→')
and not (fields[0].method == 'operator'
@@ -996,7 +1191,7 @@ class StudioSession:
with _viewport(self):
available = enabled and not self.busy and op.poll()
p.button(key, (x + width - 46, y - 4, 22, CONTROL_HEIGHT), '',
- ('operator',other.args[0],other.properties), icon='reset', enabled=available,
+ ('operator',other.args[0],other.properties), icon='reset', style='outlined', enabled=available,
hover=self.hovered(key), hint=op.get_rna_type().description)
return self.draw_control(p, model.LiveControl(prompts[0],enabled,alert),x,y,width,section,
self.control_index(section,prompts[0]), hierarchy=hierarchy, anchors=anchors, card_body=card_body)
@@ -1011,7 +1206,21 @@ class StudioSession:
cw = (width - 10 * (columns - 1)) / columns
return max(self.draw_control(p, model.LiveControl(c, enabled, alert), x + i * (cw + 10), y, cw,
section, self.control_index(section, c), hierarchy=hierarchy, anchors=anchors, card_body=card_body) for i, c in enumerate(children))
+ grouped = set()
for index, child in enumerate(children):
+ if index in grouped:
+ continue
+ if node.method == 'column':
+ commands = []
+ for following in children[index:]:
+ if not (isinstance(following, Control) and following.method == 'operator'
+ and not action_style.selection(following)):
+ break
+ commands.append(following)
+ if len(commands) > 1:
+ y = self.draw_operator_row(p, commands, x, y, width, section, enabled, alert)
+ grouped.update(range(index + 1, index + len(commands)))
+ continue
if isinstance(child, Control) and child.method == 'label' and index + 1 < len(children) and isinstance(children[index+1],Layout):
fields = [c for c in children[index+1].controls() if c.method == 'prop']
caption = child.kwargs.get('text','').rstrip(':').casefold()
@@ -1066,7 +1275,7 @@ class StudioSession:
'query': '', 'binding': None, 'index': 0, 'scroll': 0}
def draw_header(self, p, x, width):
- p.icon('layers', x, 12, 18, 'accent')
+ p.logo(x, 12, 18)
p.text('StableGen', x + 26, 12, 13, 'text')
p.button('search-button', (x + width - 50, 9, 22, CONTROL_HEIGHT), '', lambda: self.navigate('SEARCH'),
icon='search', hover=self.hovered('search-button'), hint='Find a setting · Ctrl K')
@@ -1087,18 +1296,19 @@ class StudioSession:
enabled = model.operator(name).poll() and not self.busy
key = 'toolbar:' + name
p.button(key, (x + i * width / 2 + 1, y + 1, width / 2 - 2, CONTROL_HEIGHT), text,
- ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key), hint=model.operator(name).get_rna_type().description)
+ ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),
+ hint=help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
p.rect(x + width / 2, y + 1, 1, CONTROL_HEIGHT, 'line')
p.rect(x + 1, y + 24, width - 2, 1, 'divider')
tools = [('object.clone_camera', 'Clone', 'clone'), ('object.mirror_camera', 'Mirror', 'mirror'),
- ('object.apply_auto_aspect', 'Auto aspect' if width >= 360 else 'Aspect', 'expand'), ('object.toggle_camera_labels', 'Labels', 'labels')]
+ ('object.apply_auto_aspect', 'Auto aspect' if width >= 360 else 'Aspect', 'expand'), ('stablegen.camera_display', 'Display', 'labels')]
for i, (name, text, icon) in enumerate(tools):
with _viewport(self):
- enabled = model.operator(name).poll() and not self.busy
+ enabled = model.operator(name).poll() and (not self.busy or name == 'stablegen.camera_display')
key = 'toolbar:' + name
p.button(key, (x + i * width / 4 + 1, y + 25, width / 4 - 2, 20), text,
('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),
- hint=model.operator(name).get_rna_type().description)
+ hint=help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
y += 56
cw = (width - 12) / 2
left = self.draw_binding(p, self.binding('architecture_mode'), 'Architecture', x, y, cw)
@@ -1123,7 +1333,7 @@ class StudioSession:
with _viewport(self):
op = model.operator(c.args[0])
enabled = item.enabled and not self.busy and op.poll()
- hint = op.get_rna_type().description
+ hint = help_text.operator_hint(c.args[0], bpy.context, enabled, busy=self.busy)
p.button('preset:' + c.args[0], (button_x, y + right - CONTROL_HEIGHT - CONTROL_GAP,
button_width, CONTROL_HEIGHT), label,
('operator', c.args[0], c.properties), icon=icon, style='outlined', enabled=enabled, hint=hint,
@@ -1168,6 +1378,43 @@ class StudioSession:
bpy.context.view_layer.objects.active = next((o for o in bpy.context.selected_objects if o.type == 'MESH'), None)
self.refresh()
+ def dismiss_tip(self, name):
+ tips.dismiss(name)
+ self.area.tag_redraw()
+
+ def draw_widen_hint(self, p, x, width, bottom):
+ """One-line reminder above the footer while the sidebar is too narrow."""
+ y = bottom - 26
+ p.rect(1, y, p.width - 2, 1, 'divider')
+ p.icon('widen', x + 2, y + 6, 14, 'muted')
+ p.text('Drag the sidebar edge to widen', x + 24, y + 6, 10, 'muted', width - 50)
+ p.target('tip:widen-hint', (x, y, width - 24, 26), ('hint', None, False), False,
+ 'Drag the left edge of the sidebar outward. Wider panels place settings side by side.')
+ key = 'tip:widen-hint-dismiss'
+ p.button(key, (x + width - 20, y + 3, 20, 20), '', lambda: self.dismiss_tip(tips.WIDEN_HINT),
+ icon='x', hover=self.hovered(key), hint="Don't show this tip again")
+ return y
+
+ def draw_widen_callout(self, p, top, width):
+ """First-run tip pointing at the sidebar edge; dismissal lasts across files."""
+ x, w, y = 16, min(width - 8, 240), top + 10
+ body = 'StableGen has more room for settings when the sidebar is wider. Drag this edge to the left.'
+ lines = wrap(body, w - 24, lambda s: p.measure(s, 10))
+ h = 34 + len(lines) * 15 + 40
+ p.rect(x - 1, y + 3, w + 2, h + 2, 'panel_shadow', 6)
+ p.outline(x, y, w, h, 'tooltip', 'tooltip_line', 5)
+ p.polygon([(x + 1, y + 16), (x - 9, y + 24), (x + 1, y + 32)], 'tooltip')
+ p.rect(0, y + 8, 3, 32, 'blue', 1)
+ p.icon('widen', x + 12, y + 10, 15, 'tooltip_text')
+ p.text('Widen the sidebar', x + 34, y + 10, 11, 'tooltip_text', w - 44)
+ for i, (_, _, line) in enumerate(lines):
+ p.text(line, x + 12, y + 32 + i * 15, 10, 'tooltip_text', w - 24)
+ # Keep clicks on the bubble from reaching the controls underneath.
+ p.target('tip:widen-callout', (x - 9, y, w + 9, h), ('hint', None, False), False)
+ key = 'tip:widen-callout-ok'
+ p.button(key, (x + w - 72, y + h - 30, 62, 22), 'Got it', lambda: self.dismiss_tip(tips.WIDEN_CALLOUT),
+ style='primary', hover=self.hovered(key))
+
def draw_footer(self, p, x, width):
progress = [item for n in self.document.actions for item in model.controls(n) if item.control.method == 'progress']
decision = [item for n in self.document.actions for item in model.controls(n)
@@ -1191,8 +1438,8 @@ class StudioSession:
p.text('Choose a supported architecture to continue.', x, y, 11, 'muted', width)
return top
if progress:
- for item in progress:
- y = self.draw_control(p, item, x, y, width, 'actions', 0)
+ for index, item in enumerate(progress):
+ y = self.draw_control(p, item, x, y, width, 'actions', index)
cancel = next((item for n in self.document.actions for item in model.controls(n)
if item.control.method == 'operator' and
(item.control.kwargs.get('icon') == 'CANCEL' or 'Cancel' in item.control.kwargs.get('text', '') or item.control.args[0] == 'stablegen.stop_masked_edit')), None)
@@ -1227,6 +1474,8 @@ class StudioSession:
text = primary.control.kwargs.get('text', '')
if any(word in text.lower() for word in ('cannot', 'enable online', 'select an image')):
disabled_reason = text.replace('Cannot generate: ', '').replace('Cannot edit: ', '')
+ if prefs.server_address and not prefs.server_online and not checking_server:
+ disabled_reason = 'ComfyUI offline · ' + prefs.server_address
scope = 'TRELLIS.2 · Shape and texture' if native else f'{len(selected)} selected views' if selected else f'{count} views · ' + ('Selected objects' if scene.texture_objects == 'selected' else 'All visible objects')
p.text('Checking server…' if checking_server else disabled_reason or ('Reproject changes before baking' if self.dirty_projection else scope), x, y, 10,
'warning' if disabled_reason or self.dirty_projection else 'muted', width - 64)
@@ -1250,7 +1499,7 @@ class StudioSession:
p.button('generate', (x, y, width - refresh_width, 28), label, ('operator', c.args[0], c.properties),
icon='play', style='primary', enabled=available and not self.busy and not checking_server,
corners='LEFT' if refresh_server else 'ALL',
- hint=disabled_reason or model.operator(c.args[0]).get_rna_type().description)
+ hint=disabled_reason or help_text.operator_hint(c.args[0], bpy.context, available, busy=self.busy))
if refresh_server:
with _viewport(self):
refresh_available = model.operator('stablegen.check_server_status').poll() and not self.busy
@@ -1275,7 +1524,7 @@ class StudioSession:
key = 'footer:' + name
p.button(key, (x + i * (cw + 8), y, cw, CONTROL_HEIGHT), label, ('operator', name, {}), icon=icon,
style='outlined', enabled=enabled, active=name == 'object.stablegen_reproject' and self.dirty_projection,
- hover=self.hovered(key), hint='Reproject changed settings before baking' if name == 'object.bake_textures' and self.dirty_projection else model.operator(name).get_rna_type().description)
+ hover=self.hovered(key), hint='Reproject changed settings before baking' if name == 'object.bake_textures' and self.dirty_projection else help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
def live_operator(self, name):
return next((item for section in self.document.sections for item in model.controls(section.content)
@@ -1304,28 +1553,26 @@ class StudioSession:
with _viewport(self):
op = model.operator(name)
enabled = item.enabled and op.poll()
- hint = op.get_rna_type().description
+ hint = help_text.operator_hint(name, bpy.context, enabled, busy=self.busy)
cancellation = name in {'stablegen.batch_texture_dae_cancel', 'stablegen.stop_texturing_regression',
'stablegen.debug_force_generation_idle', 'stablegen.interactive_discard_cancel',
'stablegen.interactive_discard_apply'}
enabled = enabled and (not self.busy or cancellation)
+ if not enabled and self.busy and not cancellation:
+ hint = help_text.operator_hint(name, bpy.context, False, busy=True)
rows.append((name, label, icon, item.control.properties, enabled, hint))
if not rows:
return y
- return cards.actions(self, p, rows, x, y, width)
+ # Tool cards stay a single column at every width, also in search results;
+ # only Diagnostics may go side by side.
+ return cards.actions(self, p, rows, x, y, width, max_columns=2 if self.page == 'DEBUG' else 1)
def draw_tools(self, p, x, y, width):
- scene = bpy.context.scene
y = self.draw_actions(p, 'Scene setup', [
- ('object.add_hdri', 'Add HDRI lighting', 'light'),
- ('object.apply_all_mesh_modifiers', 'Apply all modifiers', 'modifier'),
- ('object.curves_to_mesh', 'Convert curves to mesh', 'curve')], x, y, width)
- y = self.draw_actions(p, 'Texture utilities', [
- ('object.switch_material', 'Switch material', 'material'),
- ('object.stablegen_mirror_reproject', 'Mirror last projection', 'mirror'),
- ('object.stablegen_local_postprocess', 'Local post-processing', 'settings')], x, y, width)
- y = self.draw_actions(p, 'Presentation', [
- ('object.export_orbit_gif', 'Export orbit GIF / MP4', 'camera')], x, y, width)
+ ('object.add_hdri', 'Add HDRI lighting', 'light')], x, y, width)
+ for section in self.document.sections:
+ if section.key in TOOL_SECTIONS:
+ y = self.draw_section(p, section, x, y, width)
y = self.draw_actions(p, 'Import & batch', [
('stablegen.import_dae', 'Import DAE', 'download'),
('stablegen.batch_import_dae', 'Batch import DAE', 'folder'),
@@ -1340,10 +1587,6 @@ class StudioSession:
y += 31
y = self.draw_actions(p, 'Running batch', [
('stablegen.batch_texture_dae_cancel', 'Stop batch', 'stop')], x, y, width)
- if scene.architecture_mode != 'trellis2':
- y = self.draw_actions(p, 'Mesh & rig', [
- ('object.stablegen_make_solid', 'Make solid', 'material'),
- ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig')], x, y, width)
return y
def diagnostic_camera_menu(self, rect):
@@ -1367,7 +1610,7 @@ class StudioSession:
with _viewport(self):
available = model.operator('stablegen.studio_diagnostic').poll()
y += self.draw_binding(p, model.Binding.from_data(state, 'mode'), 'Display', x + 8, y + 8, width - 16, enabled=available) + 8
- description = next(item[2] for item in diagnostics.MODES if item[0] == state.mode)
+ description = diagnostics.DISPLAY_SUMMARIES[state.mode]
for _, _, line in wrap(description, width - 16, p.measure):
p.text(line, x + 8, y, 10, 'secondary')
y += 15
@@ -1471,7 +1714,7 @@ class StudioSession:
y += self.draw_binding(p, self.binding('model_name'), 'Checkpoint', x, y, width - 31)
p.button('refresh-models', (x + width - 25, y - CONTROL_HEIGHT - CONTROL_GAP, 25, CONTROL_HEIGHT), '',
('operator', 'stablegen.refresh_checkpoint_list', {}), icon='reset', enabled=not self.busy,
- hint='Refresh the real ComfyUI model list')
+ hint='Refresh the available ComfyUI models after connecting the server or adding model files')
masked = (scene.qwen_generation_method if scene.model_architecture.startswith('qwen') else scene.generation_method) == 'masked_edit' and scene.architecture_mode != 'trellis2'
prompt = 'sg_masked_prompt' if masked else 'comfyui_prompt'
if hasattr(scene, prompt) and not trellis:
@@ -1484,7 +1727,7 @@ class StudioSession:
if not native:
mode_key = 'qwen_generation_method' if scene.model_architecture.startswith('qwen') else 'generation_method'
cw = (width - 12) / 2
- left = self.draw_binding(p, self.binding(mode_key), 'Generation mode', x, y, cw)
+ left = self.draw_binding(p, self.binding(mode_key), 'Texture workflow', x, y, cw)
right = self.draw_binding(p, self.binding('texture_objects'), 'Target objects', x + cw + 12, y, cw)
y += max(left, right)
if masked:
@@ -1569,26 +1812,29 @@ class StudioSession:
for section in self.document.sections:
if self.section_page(section) == 'MESH':
y = self.draw_section(p, section, x, y, width)
- return self.draw_actions(p, 'Mesh & rig utilities', [
- ('object.stablegen_make_solid', 'Make solid', 'material'),
- ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig')], x, y, width)
+ return y
def draw_cameras(self, p, x, y, width):
scene = bpy.context.scene
- from ..texturing.view_plan import order_cameras
- cameras = order_cameras((o for o in scene.objects if o.type == 'CAMERA'),
- [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ())
+ cameras = self.ordered_cameras()
+ self.camera_rows = []
+ self.camera_clip = p.clip_rect
p.text('Scene cameras', x, y, 13)
p.text(f'{len(cameras)} views', x + width - 58, y + 2, 10, 'muted')
y += 29
def setup(cx, cy, cw):
- cy += self.draw_binding(p, self.binding('use_camera_prompts'), 'Use camera descriptions', cx, cy, cw)
+ cy += self.draw_binding(p, self.binding('use_camera_prompts'), 'Use view prompts', cx, cy, cw)
return cy + self.draw_binding(p, self.binding('sg_use_custom_camera_order'), 'Custom generation order', cx, cy, cw)
y = cards.group(p, 'View setup', x, y, width, setup, 'camera')
- camera_options = next((s for s in self.document.sections if s.key == 'show_camera_options'), None)
- if camera_options and scene.sg_use_custom_camera_order:
- y = cards.sections(self, p, camera_options, x, y, width,
- omit={'use_camera_prompts', 'sg_use_custom_camera_order'})
+ if cameras:
+ # The displayed camera cards are the order editor. Avoid a second,
+ # disconnected native list and its up/down-button cluster.
+ sort_rect = (x + width - 124, y, 124, CONTROL_HEIGHT)
+ p.text('Generation order', x, y + 5, FONT_SIZE)
+ p.button('camera-sort', sort_rect, 'Sort…', lambda: self.camera_order_menu(sort_rect),
+ icon='down', style='outlined', enabled=not self.busy,
+ hint='Choose an ordering preset. Enables custom generation order.')
+ y += CONTROL_HEIGHT + 8
if not cameras:
p.text('Add cameras using the toolbar above.', x, y, FONT_SIZE, 'muted', width)
y += 27
@@ -1597,20 +1843,24 @@ class StudioSession:
p.begin_group()
selected = camera.select_get()
hovered = self.hovered('camera:' + camera.name) and not self.busy
- tx = x + 12 if selected else x + 85
+ tx = x + 32 if selected else x + 103
p.text(f'{i + 1:02} · {camera.name}', tx, y + 16, FONT_SIZE, 'text', x + width - tx - 44)
image = self.camera_images.get(camera.name)
prompt = scene.camera_prompts.get(camera.name)
if not selected:
title = prompt.prompt if prompt and prompt.prompt else 'Generated' if image else 'No generated image'
- p.text(title, tx, y + 36, 10, 'secondary', width - 124)
- p.target('camera:' + camera.name, (x + 1, y + 1, width - 43, 38 if selected else 82),
+ p.text(title, tx, y + 36, 10, 'secondary', width - 146)
+ p.target('camera:' + camera.name, (x + 25, y + 1, width - 67, 38 if selected else 82),
lambda name=camera.name: self.call('stablegen.studio_select_camera', {'camera_name': name, 'extend': self.ctrl}),
not self.busy, camera.name + ' · Ctrl click to add to selection')
+ grip = (x + 4, y + 5, 23, 28)
+ p.icon('grip', grip[0] + 4, grip[1] + 7, 14, 'disabled' if self.busy else 'accent' if self.hovered('camera-drag:' + camera.name) else 'secondary')
+ p.target('camera-drag:' + camera.name, grip, ('camera-drag', camera.name), not self.busy,
+ 'Drag to change generation order. Dropping enables custom order; Esc cancels.')
p.button('look:' + camera.name, (x + width - 37, y + (10 if selected else 28), 25, CONTROL_HEIGHT), '',
('operator', 'stablegen.panel_camera', {'camera_name': camera.name}), icon='eye', enabled=not self.busy,
hint='Look through ' + camera.name)
- image_rect = (x + 12, y + 43, 70, 160) if selected else (x + 12, y + 12, 60, 60)
+ image_rect = (x + 12, y + 43, 70, 160) if selected else (x + 30, y + 12, 60, 60)
p.outline(*image_rect, 'menu', 'menu_border', 2)
if image:
p.image(image, image_rect)
@@ -1621,23 +1871,35 @@ class StudioSession:
y += 43
y += self.draw_binding(p, model.Binding.from_data(camera, 'name'), 'Camera name', x + 98, y, width - 110)
if prompt and scene.use_camera_prompts:
- y += self.draw_binding(p, model.Binding.from_data(prompt, 'prompt'), 'View description', x + 98, y, width - 110,
+ y += self.draw_binding(p, model.Binding.from_data(prompt, 'prompt'), 'View prompt', x + 98, y, width - 110,
multiline=True, height=93)
y = max(y, image_rect[1] + image_rect[3]) + 12
else:
y += 84
+ self.camera_rows.append((camera.name, (x, start, width, y - start)))
p.end_group((x, start, width, y - start), 'subbox', 'accent' if selected else 'hover_border' if hovered else 'section_border', 3)
y += 8
+ if self.camera_drag and self.camera_rows:
+ _, line_y = self.camera_drop(self.pointer[1])
+ p.rect(x + 3, line_y - 1, width - 6, 2, 'accent')
+ source = next((rect for name, rect in self.camera_rows if name == self.camera_drag['name']), None)
+ if source:
+ sx, sy, sw, sh = source
+ p.line([(sx, sy), (sx + sw, sy), (sx + sw, sy + sh), (sx, sy + sh), (sx, sy)], 'accent')
for section in self.document.sections:
if section.page == 'CAMERAS' and section.key not in {'camera_tools', 'show_camera_options'}:
y = self.draw_section(p, section, x, y + 8, width, omit={'use_camera_prompts','sg_use_custom_camera_order'})
return y
def menu_items(self):
+ if self.menu.get('kind') == 'lora':
+ return lora.menu_items(self.menu)
query = self.menu['query'].casefold()
return [item for item in self.menu['items'] if query in item[1].casefold()]
def draw_menu(self, p):
+ if self.menu.get('kind') == 'lora':
+ return lora.draw_menu(self, p)
menu = self.menu
items = self.menu_items()
ax, ay, aw, ah = menu['anchor']
@@ -1681,6 +1943,17 @@ class StudioSession:
return y + 30
found = False
for section in self.document.sections:
+ if section.key == 'show_lora_settings':
+ searchable = 'LoRA adapters add remove refresh models'
+ for item in model.controls(section.content):
+ control = item.control
+ if control.method == 'prop':
+ prop = control.args[0].bl_rna.properties[control.args[1]]
+ searchable += ' ' + prop.name + ' ' + prop.description
+ if query in searchable.casefold():
+ found = True
+ y = lora.draw_section(self, p, section, x, y, width) + 6
+ continue
for i, item in enumerate(model.controls(section.content)):
control = item.control
if control.method not in {'prop', 'operator'}:
@@ -1708,7 +1981,7 @@ class StudioSession:
return y
binding, label, previous = self.prompt_editor
p.button('close-editor', (x, y, width, CONTROL_HEIGHT), 'Back to ' + dict(self.pages() + MORE).get(previous, 'settings'),
- lambda: self.navigate(previous), icon='arrow', active=True)
+ lambda: self.navigate(previous), style='outlined')
y += 34
return y + self.draw_binding(p, binding, label, x, y, width, multiline=True,
height=max(100, bottom - y - 60))
@@ -1729,6 +2002,9 @@ class StudioSession:
x, width = 12, p.width - 24
top = self.draw_header(p, x, width)
bottom = self.draw_footer(p, x, width)
+ narrow = width < cards.SIDE_BY_SIDE_WIDTH
+ if narrow and not tips.dismissed(tips.WIDEN_HINT):
+ bottom = self.draw_widen_hint(p, x, width, bottom)
clip = (1, top + 1, p.width - 2, max(0, bottom - top - 2))
p.clip(clip)
offset = self.scroll.get(self.page, 0)
@@ -1753,10 +2029,6 @@ class StudioSession:
sections = [section for section in self.document.sections if self.section_page(section) == self.page]
for section in sections:
y = self.draw_section(p, section, x, y, width)
- if self.page == 'MESH':
- y = self.draw_actions(p, 'Mesh & rig utilities', [
- ('object.stablegen_make_solid', 'Make solid', 'material'),
- ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig')], x, y, width)
self.max_scroll = max(0, y + offset + 20 - bottom)
if offset > self.max_scroll:
self.scroll[self.page] = self.max_scroll
@@ -1766,6 +2038,13 @@ class StudioSession:
thumb = max(24, available * available / (available + self.max_scroll))
p.rect(p.width - 5, top + offset / self.max_scroll * max(0, available - thumb), 2, thumb, 'muted', 1)
p.clip(None)
+ if not tips.dismissed(tips.WIDEN_CALLOUT):
+ if self.callout_width is not None and width > self.callout_width + 20:
+ # Dragging the edge wider shows the tip has done its job.
+ tips.dismiss(tips.WIDEN_CALLOUT)
+ elif narrow:
+ self.callout_width = width if self.callout_width is None else min(self.callout_width, width)
+ self.draw_widen_callout(p, top, width)
if self.menu:
self.draw_menu(p)
# Layout changes can put a different control under a stationary mouse.
@@ -1843,6 +2122,7 @@ class SG_OT_StudioSession(bpy.types.Operator):
return session.event(event)
except (ReferenceError, RuntimeError, ValueError, TypeError) as exc:
session.edit = session.drag = session.menu = None
+ session.camera_drag = None
session.clear_hover(leave=True)
session.tell(str(exc).split('\n')[0])
_log.exception('Studio input error')
@@ -1904,6 +2184,61 @@ class SG_OT_StudioNative(bpy.types.Operator):
self.finish()
+class SG_OT_StudioReorderCamera(bpy.types.Operator):
+ bl_idname = 'stablegen.studio_reorder_camera'
+ bl_label = 'Reorder Camera'
+ bl_description = 'Move this camera to the indicated position in generation order'
+ bl_options = {'UNDO', 'INTERNAL'}
+ camera_name: bpy.props.StringProperty()
+ before_name: bpy.props.StringProperty()
+
+ @classmethod
+ def poll(cls, context):
+ return not sg_modal_active(context)
+
+ def execute(self, context):
+ from ..texturing.view_plan import order_cameras
+ scene = context.scene
+ cameras = order_cameras((o for o in scene.objects if o.type == 'CAMERA'),
+ [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ())
+ names = [c.name for c in cameras]
+ if self.camera_name not in names or self.before_name == self.camera_name:
+ return {'CANCELLED'}
+ if self.before_name and self.before_name not in names:
+ return {'CANCELLED'}
+ ordered = [name for name in names if name != self.camera_name]
+ ordered.insert(ordered.index(self.before_name) if self.before_name else len(ordered), self.camera_name)
+ if ordered == names:
+ return {'CANCELLED'}
+ scene.sg_camera_order.clear()
+ for name in ordered:
+ scene.sg_camera_order.add().name = name
+ scene.sg_camera_order_index = ordered.index(self.camera_name)
+ scene.sg_use_custom_camera_order = True
+ return {'FINISHED'}
+
+
+class SG_OT_StudioSortCameras(bpy.types.Operator):
+ bl_idname = 'stablegen.studio_sort_cameras'
+ bl_label = 'Sort Cameras'
+ bl_description = 'Apply a generation-order preset and enable custom order'
+ bl_options = {'UNDO', 'INTERNAL'}
+ strategy: bpy.props.StringProperty()
+
+ @classmethod
+ def poll(cls, context):
+ return not sg_modal_active(context)
+
+ def execute(self, context):
+ prop = bpy.ops.stablegen.apply_camera_order_preset.get_rna_type().properties['strategy']
+ if self.strategy not in {item.identifier for item in prop.enum_items}:
+ return {'CANCELLED'}
+ result = bpy.ops.stablegen.apply_camera_order_preset('EXEC_DEFAULT', strategy=self.strategy)
+ if 'FINISHED' in result:
+ context.scene.sg_use_custom_camera_order = True
+ return result
+
+
class SG_OT_StudioSelectCamera(bpy.types.Operator):
bl_idname = 'stablegen.studio_select_camera'
bl_label = 'Select Camera'
@@ -1968,15 +2303,21 @@ def _ensure_session(context):
class SG_PT_StudioCanvas(bpy.types.Panel):
bl_idname = 'SG_PT_StudioCanvas'
- bl_label = 'StableGen Studio UI'
+ bl_label = 'StableGen'
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = TAB
- bl_options = {'HIDE_HEADER'}
+ # Keep the native header: Blender sorts header-less panels, and with them
+ # their tab, above its own sidebar tabs. Studio draws over the header.
+ bl_options = set()
@classmethod
def poll(cls, context):
- return context.mode in {'OBJECT', 'PAINT_TEXTURE'}
+ return context.mode in {'OBJECT', 'PAINT_TEXTURE'} and not legacy_panel_enabled(context)
+
+ def draw_header(self, context):
+ # Blender skips draw() while the hidden panel is collapsed.
+ _ensure_session(context)
def draw(self, context):
_ensure_session(context)
@@ -2030,8 +2371,9 @@ def _load_pre(_):
_pending.clear()
-STUDIO_UI_CLASSES = diagnostics.CLASSES + [SG_OT_StudioSession, SG_OT_StudioNative, SG_OT_StudioSelectCamera,
- SG_OT_StudioPreferences, SG_PT_StudioCanvas]
+STUDIO_UI_CLASSES = diagnostics.CLASSES + [lora.SG_OT_StudioLoRA, SG_OT_StudioSession, SG_OT_StudioNative, SG_OT_StudioSelectCamera,
+ SG_OT_StudioReorderCamera, SG_OT_StudioSortCameras,
+ SG_OT_StudioPreferences, tips.SG_OT_ResetTips, SG_PT_StudioCanvas]
def register_studio_ui():
diff --git a/stablegen/ui/studio_actions.py b/stablegen/ui/studio_actions.py
new file mode 100644
index 0000000..29c710c
--- /dev/null
+++ b/stablegen/ui/studio_actions.py
@@ -0,0 +1,82 @@
+"""Presentation metadata for Studio actions; operator behavior stays native."""
+
+OPERATOR_ICONS = {
+ 'object.bake_textures': 'grid',
+ 'object.switch_material': 'material',
+ 'object.export_game_engine': 'download',
+ 'object.stablegen_preview_quantization': 'eye',
+ 'object.stablegen_preview_sliced': 'layers',
+ 'object.stablegen_clear_quantization_preview': 'x',
+ 'object.stablegen_preview_sliced_cancel': 'stop',
+ 'object.export_3mf_cancel': 'stop',
+ 'stablegen.prepare_mask_paint': 'settings',
+ 'stablegen.paint_edit_mask': 'settings',
+ 'stablegen.finish_edit_mask': 'check',
+ 'stablegen.clear_edit_mask': 'x',
+ 'stablegen.check_server_status': 'reset',
+ 'stablegen.refresh_checkpoint_list': 'reset',
+ 'stablegen.refresh_lora_list': 'reset',
+ 'stablegen.reset_qwen_prompt': 'reset',
+ 'stablegen.reset_texturing_experiments': 'reset',
+ 'stablegen.apply_animation_to_rig': 'play',
+ 'stablegen.apply_rig_pose_preset': 'rig',
+ 'stablegen.characterize_rig': 'rig',
+ 'stablegen.edit_rig_mapping': 'rig',
+ 'stablegen.match_source_reference_pose': 'rig',
+ 'stablegen.set_retarget_reference_pose': 'rig',
+ 'stablegen.apply_autorig_bone_display': 'rig',
+ 'stablegen.toggle_rig_mapping_overlay': 'eye',
+ 'stablegen.toggle_collision_proxy_overlay': 'eye',
+ 'stablegen.toggle_retarget_source_preview': 'eye',
+ 'stablegen.sync_camera_order': 'reset',
+ 'stablegen.queue_move_up': 'up',
+ 'stablegen.queue_move_down': 'down',
+ 'stablegen.queue_open_result': 'folder',
+ 'stablegen.queue_invalidate': 'reset',
+ 'stablegen.queue_process': 'play',
+ 'stablegen.queue_clear': 'x',
+}
+NATIVE_ICONS = {
+ 'ADD': 'plus', 'REMOVE': 'minus', 'X': 'x', 'CANCEL': 'stop',
+ 'FILE_REFRESH': 'reset', 'EXPORT': 'download', 'IMPORT': 'folder',
+ 'FILE_FOLDER': 'folder', 'FILEBROWSER': 'folder', 'PLAY': 'play',
+ 'TRIA_UP': 'up', 'TRIA_DOWN': 'down', 'COLOR': 'material',
+ 'MATERIAL': 'material', 'TEXTURE': 'layers', 'IMAGE_DATA': 'eye',
+ 'CAMERA_DATA': 'camera', 'ARMATURE_DATA': 'rig', 'OUTLINER_OB_ARMATURE': 'rig',
+ 'BONE_DATA': 'rig', 'MODIFIER': 'modifier', 'MOD_DECIM': 'layers',
+ 'MOD_REMESH': 'modifier', 'SETTINGS': 'settings', 'PRESET': 'settings',
+ 'CHECKMARK': 'check', 'HIDE_OFF': 'eye', 'LIGHT': 'light',
+}
+SELECTION_PATHS = {
+ 'scene.stablegen_print_palette_index': 'Filament',
+ 'scene.lora_units_index': 'Adapter',
+}
+PRINT_PREVIEW = {
+ 'object.stablegen_preview_quantization': 'Colors',
+ 'object.stablegen_preview_sliced': 'Slices',
+ 'object.stablegen_clear_quantization_preview': 'Clear',
+}
+PRINT_EXPORT = {'object.export_stl': 'STL', 'object.export_3mf': '3MF'}
+
+
+def icon(control):
+ """Use a relevant native/semantic icon, or text alone for unknown commands."""
+ return OPERATOR_ICONS.get(control.args[0], NATIVE_ICONS.get(control.kwargs.get('icon')))
+
+
+def selection(control):
+ if control.method == 'operator' and control.args[0] == 'wm.context_set_int':
+ path = control.properties.get('data_path', '')
+ if path in SELECTION_PATHS:
+ return path.removeprefix('scene.'), control.properties.get('value', 0), SELECTION_PATHS[path]
+ return None
+
+
+def print_group(controls, section):
+ if section == 'print' and controls:
+ names = {c.args[0] for c in controls}
+ if names <= PRINT_PREVIEW.keys():
+ return 'Preview', PRINT_PREVIEW
+ if names <= PRINT_EXPORT.keys():
+ return 'Export', PRINT_EXPORT
+ return '', {}
diff --git a/stablegen/ui/studio_cards.py b/stablegen/ui/studio_cards.py
index 80e175f..deceac3 100644
--- a/stablegen/ui/studio_cards.py
+++ b/stablegen/ui/studio_cards.py
@@ -16,6 +16,8 @@ from .studio_widgets import FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP
GAP = 8
PAD = 12
+# Content width at which cards and action rows sit side by side.
+SIDE_BY_SIDE_WIDTH = 440
RESOLUTION_KEYS = {'auto_rescale', 'auto_rescale_target_mp', 'qwen_rescale_alignment'}
@@ -561,7 +563,7 @@ def draw(s, p, cards, section, x, y, width):
index += 1
continue
row = [card]
- if (width >= 440 and card.spec.beside and index + 1 < len(roots)
+ if (width >= SIDE_BY_SIDE_WIDTH and card.spec.beside and index + 1 < len(roots)
and roots[index + 1].spec.beside == card.spec.beside
and roots[index + 1].spec.key not in children):
row.append(roots[index + 1])
@@ -644,8 +646,8 @@ ACTION_DESCRIPTIONS = {
}
-def actions(s, p, rows, x, y, width):
- columns = 2 if width >= 440 else 1
+def actions(s, p, rows, x, y, width, *, max_columns=2):
+ columns = min(max_columns, 2 if width >= SIDE_BY_SIDE_WIDTH else 1)
cw = (width - GAP * (columns - 1)) / columns
for first in range(0, len(rows), columns):
p.begin_group()
diff --git a/stablegen/ui/studio_help.py b/stablegen/ui/studio_help.py
new file mode 100644
index 0000000..d2a080d
--- /dev/null
+++ b/stablegen/ui/studio_help.py
@@ -0,0 +1,90 @@
+"""Context-aware presentation help; never changes parameter values or commands."""
+import bpy
+
+from . import studio_model as model
+
+
+def property_hint(binding, context):
+ prop, scene = binding.rna(context), context.scene
+ key = binding.property
+ if binding.path == 'sg_studio_diagnostics' and key == 'mode':
+ from .studio_diagnostics import MODES
+ description = next((description for identifier, _label, description in MODES
+ if identifier == binding.value(context)), '')
+ return prop.description + '\n' + description
+ if key == 'comfyui_prompt':
+ if scene.architecture_mode != 'trellis2':
+ return 'Describe the desired texture appearance. View-specific wording belongs in each camera’s view prompt.'
+ if scene.trellis2_generate_from == 'image':
+ return ('Mesh shape follows the selected input image. This prompt applies to diffusion textures '
+ 'unless Separate texture prompt is enabled; native textures follow the image.')
+ shared = not scene.use_separate_texture_prompt
+ return ('Describe the image that will guide mesh generation. ' +
+ ('This also drives per-camera diffusion textures.' if shared else
+ 'Diffusion textures use the separate prompt on the Texture tab.'))
+ if key == 'sequential_ipadapter':
+ if scene.model_architecture in {'qwen_image_edit', 'qwen_image_21', 'flux2_klein'}:
+ return ('Use the first or most recent generated view as an image reference for style continuity. '
+ 'An enabled external style reference can take precedence.')
+ return ('Use IPAdapter with the first or most recent generated view for style continuity. '
+ 'An external IPAdapter image takes precedence when enabled.')
+ if key == 'pbr_emission_threshold':
+ return ('Cutoff on the blurred HSV detection mask (0–1). Higher values remove more weak '
+ 'detections after the saturation/brightness tests.' if scene.pbr_emission_method == 'hsv'
+ else 'Soft cutoff for lighting-residual intensity (0–1), after metallic suppression '
+ 'when available. Higher values remove more weak emission candidates.')
+ return prop.description
+
+
+class _PollMessage:
+ """Read a Python poll explanation without changing Blender's poll message."""
+ def __init__(self, owner):
+ self.owner, self.message = owner, ''
+
+ def __getattr__(self, name):
+ return getattr(self.owner, name)
+
+ def poll_message_set(self, message, *args):
+ self.message = str(message(*args) if callable(message) else message)
+
+
+def operator_hint(name, context, available=True, *, busy=False):
+ op = model.operator(name)
+ hint = op.get_rna_type().description
+ if available:
+ return hint
+ if busy:
+ return hint + '\nUnavailable while StableGen is running.'
+ cls = bpy.types.Operator.bl_rna_get_subclass_py(op.get_rna_type().identifier)
+ poll = getattr(getattr(cls, 'poll', None), '__func__', None)
+ if poll:
+ probe = _PollMessage(cls)
+ try:
+ poll(probe, context)
+ except Exception:
+ # Some third-party polls need a real class (e.g. super()). The
+ # original operator poll remains authoritative for enablement.
+ return hint
+ if probe.message:
+ return hint + '\nUnavailable: ' + probe.message
+ return hint
+
+
+def native_help(control, label=None):
+ """Identify native editors instead of asking users to open them to find out."""
+ if control.method == 'template_list':
+ name = control.args[3] if len(control.args) >= 6 else ''
+ title = {'sg_camera_order': 'Edit camera order', 'sg_scene_queue': 'Edit scene queue',
+ 'stablegen_print_palette': 'Edit filament palette'}.get(name, 'Edit list')
+ return title, 'Open Blender’s native editor for ' + title.removeprefix('Edit ').lower() + '.'
+ if control.method == 'operator_menu_enum':
+ op = model.operator(control.args[0])
+ title = label or control.kwargs.get('text') or op.get_rna_type().name
+ return title, op.get_rna_type().description
+ if control.method in {'prop', 'template_curve_mapping'} and len(control.args) >= 2:
+ data, key = control.args[:2]
+ prop = data.bl_rna.properties.get(key)
+ if prop:
+ title = label or control.kwargs.get('text') or prop.name
+ return title, prop.description or 'Open Blender’s native editor for ' + title.lower() + '.'
+ return label or 'Open editor', 'Open Blender’s native editor for these settings.'
diff --git a/stablegen/ui/studio_lora.py b/stablegen/ui/studio_lora.py
new file mode 100644
index 0000000..18aea7d
--- /dev/null
+++ b/stablegen/ui/studio_lora.py
@@ -0,0 +1,343 @@
+"""Direct LoRA cards and a shared model picker for the Studio sidebar."""
+from pathlib import PurePosixPath
+
+import bpy
+
+from . import studio_model as model
+from .model_units import get_lora_models
+from .studio_text import TextBuffer, wrap
+from .studio_widgets import CONTROL_HEIGHT, FONT_SIZE
+from ..utils import sg_modal_active
+
+PLACEHOLDERS = {'NONE_AVAILABLE', 'NO_COMFYUI_DIR_LORA', 'NO_LORAS_SUBDIR',
+ 'PERM_ERROR', 'SCAN_ERROR', 'NONE_FOUND', 'NO_SERVER', 'NO_PREFS'}
+
+
+def models(context):
+ return [tuple(item[:3]) for item in get_lora_models(context.scene, context)
+ if item and item[0] and item[0] not in PLACEHOLDERS]
+
+
+def path_name(value):
+ return str(value).replace('\\', '/')
+
+
+def title(value):
+ return PurePosixPath(path_name(value)).stem or 'Choose a model'
+
+
+def snapshot(scene):
+ return tuple((str(unit.as_pointer()), unit.model_name) for unit in scene.lora_units)
+
+
+class SG_OT_StudioLoRA(bpy.types.Operator):
+ bl_idname = 'stablegen.studio_lora'
+ bl_label = 'Edit LoRA Adapter'
+ bl_description = 'Add, replace or remove the adapter on this card'
+ bl_options = {'UNDO', 'INTERNAL'}
+ operation: bpy.props.EnumProperty(items=[('ADD', 'Add', ''), ('REPLACE', 'Replace', ''), ('REMOVE', 'Remove', '')])
+ model_name: bpy.props.StringProperty()
+ index: bpy.props.IntProperty(default=-1)
+ token: bpy.props.StringProperty()
+ scene_name: bpy.props.StringProperty()
+
+ @classmethod
+ def poll(cls, context):
+ return not sg_modal_active(context)
+
+ def execute(self, context):
+ scene = context.scene
+ if scene.name != self.scene_name:
+ return {'CANCELLED'}
+ if self.operation != 'ADD':
+ if not (0 <= self.index < len(scene.lora_units)
+ and str(scene.lora_units[self.index].as_pointer()) == self.token):
+ self.report({'WARNING'}, 'The adapter list changed. Choose the card again.')
+ return {'CANCELLED'}
+ if self.operation == 'REMOVE':
+ scene.lora_units_index = self.index
+ return bpy.ops.stablegen.remove_lora_unit('EXEC_DEFAULT')
+ if self.model_name not in {item[0] for item in models(context)}:
+ self.report({'WARNING'}, 'This model is no longer available. Refresh the model list.')
+ return {'CANCELLED'}
+ if self.operation == 'REPLACE':
+ unit = scene.lora_units[self.index]
+ if unit.model_name == self.model_name:
+ return {'CANCELLED'}
+ unit.model_name = self.model_name
+ return {'FINISHED'}
+ if any(unit.model_name == self.model_name for unit in scene.lora_units):
+ return {'CANCELLED'}
+ if not bpy.ops.stablegen.add_lora_unit.poll():
+ return {'CANCELLED'}
+ result = bpy.ops.stablegen.add_lora_unit('EXEC_DEFAULT')
+ if 'FINISHED' in result:
+ scene.lora_units[-1].model_name = self.model_name
+ return result
+
+
+def open_picker(s, rect, index=None):
+ s.commit()
+ if s.busy:
+ return
+ scene = bpy.context.scene
+ current = scene.lora_units[index].model_name if index is not None else ''
+ items = models(bpy.context)
+ if not items:
+ s.tell('Refresh the LoRA model list to choose an adapter.')
+ return
+ token = str(scene.lora_units[index].as_pointer()) if index is not None else ''
+ operation = 'REPLACE' if index is not None else 'ADD'
+ used = {unit.model_name for unit in scene.lora_units}
+ menu = {'kind': 'lora', 'anchor': rect, 'items': items, 'query': '',
+ 'buffer': TextBuffer(''), 'binding': None, 'index': 0, 'scroll': 0,
+ 'folder': None, 'scene': scene.name, 'architecture': scene.architecture_mode,
+ 'snapshot': snapshot(scene), 'current': current,
+ 'catalog': tuple(item[0] for item in items),
+ 'disabled': used if operation == 'ADD' else set(), 'operation': operation}
+
+ def choose(identifier):
+ if not valid_menu(s, menu) or identifier in menu['disabled']:
+ return
+ s.call('stablegen.studio_lora', {'operation': operation, 'model_name': identifier,
+ 'index': index if index is not None else -1, 'token': token,
+ 'scene_name': menu['scene']}, mode='EXEC_DEFAULT')
+
+ menu['callback'] = choose
+ menu['index'] = next((i for i, item in enumerate(items) if item[0] == current),
+ next((i for i, item in enumerate(items) if item[0] not in menu['disabled']), 0))
+ s.menu = menu
+ s.clear_hover()
+ s.area.tag_redraw()
+
+
+def valid_menu(s, menu):
+ scene = bpy.context.scene
+ return (not s.busy and not sg_modal_active(bpy.context)
+ and scene.name == menu['scene'] and scene.architecture_mode == menu['architecture']
+ and snapshot(scene) == menu['snapshot']
+ and tuple(item[0] for item in models(bpy.context)) == menu['catalog'])
+
+
+def menu_items(menu):
+ terms = path_name(menu['query']).casefold().split()
+ folder = menu['folder']
+ return [item for item in menu['items']
+ if all(term in path_name(item[0]).casefold() for term in terms)
+ and (folder is None or str(PurePosixPath(path_name(item[0])).parent) == folder)]
+
+
+def folders(s):
+ parent = s.menu
+ values = sorted({str(PurePosixPath(path_name(item[0])).parent) for item in parent['items']}, key=str.casefold)
+
+ def choose(value):
+ if not valid_menu(s, parent):
+ return
+ parent.update(folder=None if value == '__all__' else value, index=0, scroll=0)
+ parent['index'] = next((i for i, item in enumerate(menu_items(parent)) if item[0] not in parent['disabled']), 0)
+ s.menu = parent
+
+ s.menu = {'anchor': parent['folder_rect'], 'items': [('__all__', 'All folders', '')]
+ + [(value, 'Root folder' if value == '.' else value, value) for value in values],
+ 'query': '', 'binding': None, 'index': 0, 'scroll': 0, 'callback': choose}
+
+
+def keyboard(s, event):
+ """Edit the picker query without turning it into a scene property edit."""
+ if event.value != 'PRESS':
+ return False
+ menu, key = s.menu, event.type
+ buffer = menu['buffer']
+ ctrl = event.ctrl or event.oskey
+ if ctrl and key == 'A':
+ buffer.anchor, buffer.caret = 0, len(buffer.text)
+ elif ctrl and key in {'C', 'X'}:
+ a, b = buffer.selection
+ if a != b:
+ s.window_manager.clipboard = buffer.text[a:b]
+ if key == 'X':
+ buffer.replace('')
+ elif ctrl and key == 'V':
+ buffer.replace(s.window_manager.clipboard.replace('\n', ' ').replace('\r', ''))
+ elif ctrl and key in {'Z', 'Y'}:
+ buffer.undo(redo=key == 'Y' or event.shift)
+ elif key in {'LEFT_ARROW', 'RIGHT_ARROW', 'HOME', 'END'}:
+ direction = -1 if key == 'LEFT_ARROW' else 1
+ a, b = buffer.selection
+ destination = (0 if key == 'HOME' else len(buffer.text) if key == 'END'
+ else (a if direction < 0 else b) if a != b and not event.shift
+ else buffer.word(direction) if ctrl else buffer.caret + direction)
+ buffer.move(destination, event.shift)
+ elif key in {'BACK_SPACE', 'DEL'}:
+ buffer.delete(backward=key == 'BACK_SPACE', word=ctrl)
+ elif getattr(event, 'unicode', '') and not ctrl and not event.alt:
+ buffer.replace(event.unicode)
+ else:
+ return False
+ if menu['query'] != buffer.text:
+ menu.update(query=buffer.text, index=0, scroll=0)
+ menu['index'] = next((i for i, item in enumerate(menu_items(menu)) if item[0] not in menu['disabled']), 0)
+ s.clear_hover()
+ s.area.tag_redraw()
+ return True
+
+
+def select_search(s):
+ """Use Studio's caret hit testing without committing the query to RNA."""
+ previous = s.edit
+ if not s.menu.get('editor'):
+ return
+ try:
+ s.edit = s.menu['editor']
+ s.select_caret(*s.pointer)
+ finally:
+ s.edit = previous
+
+
+def number(s, p, binding, label, x, y, width, enabled):
+ from .studio import _binding_key
+ prop = binding.rna(bpy.context)
+ enabled = enabled and not prop.is_readonly and not s.busy
+ key = _binding_key(binding)
+ editing = s.edit if s.edit and s.edit['key'] == key else None
+ value = binding.value(bpy.context)
+ display = editing['buffer'].text if editing else f'{value:.{prop.precision}f}'.rstrip('0').rstrip('.') or '0'
+ inline = width >= p.measure(label) + 72
+ p.text(label, x, y + (5 if inline else 0), FONT_SIZE, 'text' if enabled else 'disabled')
+ rect = (x + width - 62, y, 62, CONTROL_HEIGHT) if inline else (x, y + 17, width, CONTROL_HEIGHT)
+ hint = prop.description
+ lines, scroll = p.text_field(key, rect, display, ('edit', binding, False), enabled=enabled,
+ hint=hint, kind='number', editing=editing['buffer'] if editing else None)
+ if editing:
+ editing.update(rect=rect, lines=lines, scroll=scroll)
+ return rect[1] + rect[3]
+
+
+def draw_section(s, p, section, x, y, width):
+ """Use only the per-unit properties present in the native panel capture."""
+ scene, start = bpy.context.scene, y
+ fields = {(c.control.args[0].as_pointer(), c.control.args[1]): c for c in model.controls(section.content)
+ if c.control.method == 'prop'}
+ add = next((c for c in model.controls(section.content)
+ if c.control.method == 'operator' and c.control.args[0] == 'stablegen.add_lora_unit'), None)
+ can_add = bool(add and add.enabled and not s.busy and models(bpy.context)
+ and bpy.ops.stablegen.add_lora_unit.poll())
+ p.begin_group()
+ cx, cw = x + 12, width - 24
+ p.icon('down', cx, y + 16, 10, 'text')
+ p.text('LoRA', cx + 18, y + 12, FONT_SIZE)
+ if cw >= 270:
+ p.text(f'{len(scene.lora_units)} adapters', cx + 57, y + 13, 10, 'secondary')
+ p.target('section:' + section.key, (cx, y + 5, cw - 104, 26), ('section', section.key), hint=section.title)
+ refresh = bpy.ops.stablegen.refresh_lora_list.poll() and not s.busy
+ p.button('lora:refresh', (cx + cw - 96, y + 8, 22, 22), '',
+ ('operator', 'stablegen.refresh_lora_list', {}), icon='reset', enabled=refresh,
+ hover=s.hovered('lora:refresh'), hint='Refresh the available LoRA models from ComfyUI')
+ rect = (cx + cw - 70, y + 8, 70, 22)
+ anchor = (cx, y + 8, cw, 22)
+ p.button('lora:add', rect, 'Add', lambda r=anchor: open_picker(s, r), icon='plus', style='outlined',
+ enabled=can_add, hint='Choose a LoRA model to add' if can_add else
+ 'Unavailable while StableGen is running' if s.busy else
+ 'All available models are already added' if models(bpy.context) else 'Refresh to fetch the available LoRA models')
+ p.rect(cx, y + 40, cw, 1, 'divider')
+ y += 52
+ for index, unit in enumerate(scene.lora_units):
+ top, token = y, str(unit.as_pointer())
+ live = fields.get((unit.as_pointer(), 'model_name'))
+ enabled = bool(live and live.enabled and not s.busy)
+ name = unit.model_name
+ key = 'lora:model:' + token
+ rect = (cx + 10, y + 8, cw - 43, 26)
+ p.begin_group()
+ if s.hovered(key) and enabled:
+ p.rect(*rect, 'hover_soft', 2)
+ p.icon('document', cx + 17, y + 15, 12, 'secondary' if enabled else 'disabled')
+ p.text(title(name), cx + 35, y + 15, FONT_SIZE, 'text' if enabled else 'disabled', cw - 97)
+ p.icon('down', cx + cw - 52, y + 17, 11, 'secondary' if enabled else 'disabled')
+ anchor = (cx, y + 8, cw, 26)
+ p.target(key, rect, lambda r=anchor, i=index: open_picker(s, r, i), enabled,
+ 'Change this adapter\n' + path_name(name))
+ p.button('lora:remove:' + token, (cx + cw - 29, y + 10, 22, 22), '',
+ ('operator', 'stablegen.studio_lora', {'operation': 'REMOVE', 'index': index,
+ 'token': token, 'scene_name': scene.name}), icon='x', enabled=not s.busy,
+ hover=s.hovered('lora:remove:' + token), hint='Remove ' + title(name))
+ p.text(path_name(name), cx + 11, y + 41, 10, 'secondary', cw - 22)
+ props = [(key, label) for key, label in [('model_strength', 'Model'), ('clip_strength', 'CLIP')]
+ if (unit.as_pointer(), key) in fields]
+ nw = (cw - 22 - 14 * (len(props) - 1)) / max(1, len(props))
+ ends = [number(s, p, model.Binding.from_data(unit, prop), label,
+ cx + 11 + i * (nw + 14), y + 59, nw, fields[(unit.as_pointer(), prop)].enabled)
+ for i, (prop, label) in enumerate(props)]
+ y = max(ends, default=y + 59) + 11
+ s.card_bounds[section.key + ':unit:' + str(index)] = (cx, top, cw, y - top)
+ p.end_group((cx, top, cw, y - top), 'subbox', 'section_border', 3)
+ y += 8
+ if not scene.lora_units:
+ message = 'Add an adapter to adjust its model strength.' if models(bpy.context) else 'Refresh to fetch LoRA models from ComfyUI.'
+ for _, _, line in wrap(message, cw, lambda value: p.measure(value, 10)):
+ p.text(line, cx, y, 10, 'secondary')
+ y += 15
+ y += 8
+ y += 4
+ s.card_bounds[section.key + ':adapters'] = (x, start, width, y - start)
+ p.end_group((x, start, width, y - start), 'card', 'section_border', 3)
+ return y + 8
+
+
+def draw_menu(s, p):
+ menu, items = s.menu, s.menu_items()
+ ax, ay, aw, ah = menu['anchor']
+ width = min(p.width - 30, max(280, aw))
+ rows = min(8, len(items), max(1, int((p.height - 150) / 45)))
+ menu['rows'] = rows
+ height = 109 + max(1, rows) * 45 + 29
+ x = min(max(15, ax), p.width - width - 15)
+ y = ay + ah + 5
+ if y + height > p.height - 10:
+ y = max(10, ay - height - 5)
+ menu['rect'] = (x, y, width, height)
+ p.rect(x - 1, y + 2, width + 2, height + 2, 'panel_shadow', 4)
+ p.outline(x, y, width, height, 'tooltip', 'section_border', 4)
+ p.text('Add adapter' if menu['operation'] == 'ADD' else 'Change adapter', x + 12, y + 12, FONT_SIZE)
+ p.button('choice:lora:close', (x + width - 31, y + 6, 22, 22), '', ('menu-lora-close',), icon='x')
+ rect = (x + 12, y + 38, width - 24, 27)
+ lines, scroll = p.text_field('choice:lora:search', rect, menu['query'], ('menu-lora-search',),
+ editing=menu['buffer'], hint='Search model filenames and folder paths')
+ menu['editor'] = {'buffer': menu['buffer'], 'rect': rect, 'lines': lines, 'scroll': scroll,
+ 'multiline': False, 'follow_caret': False}
+ if not menu['query']:
+ p.text('Search adapters…', x + 22, y + 45, FONT_SIZE, 'secondary', width - 45)
+ menu['folder_rect'] = (x + 12, y + 74, min(160, width - 100), 22)
+ label = 'All folders' if menu['folder'] is None else 'Root folder' if menu['folder'] == '.' else menu['folder']
+ fx, fy, fw, fh = menu['folder_rect']
+ p.outline(fx, fy, fw, fh, 'menu', 'hover_border' if s.hovered('choice:lora:folder') else 'menu_border', 3)
+ p.text(label, fx + 8, fy + 5, FONT_SIZE, 'menu_text', fw - 30)
+ p.icon('down', fx + fw - 16, fy + 6, 10, 'menu_text')
+ p.target('choice:lora:folder', menu['folder_rect'], ('menu-lora-folder',), hint='Filter models by folder')
+ p.text(f'{len(items)} results', x + width - 66, y + 79, 10, 'secondary', 57)
+ start = min(menu['scroll'], max(0, len(items) - rows))
+ for i, (identifier, label, description) in enumerate(items[start:start + rows], start):
+ rect = (x + 4, y + 109 + (i - start) * 45, width - 8, 45)
+ key, disabled = 'choice:' + identifier, identifier in menu['disabled']
+ if not disabled and (i == menu['index'] or s.hovered(key)):
+ p.rect(*rect, 'hover_soft')
+ tint = 'muted' if disabled else 'text'
+ p.icon('document', rect[0] + 10, rect[1] + 8, 12, tint)
+ p.text(title(identifier), rect[0] + 31, rect[1] + 6, FONT_SIZE, tint, width - 92)
+ p.text(path_name(identifier), rect[0] + 31, rect[1] + 24, 10, 'secondary', width - 48)
+ if disabled:
+ p.text('Added', x + width - 48, rect[1] + 8, 10, 'muted')
+ else:
+ p.icon('check' if identifier == menu['current'] else 'plus' if menu['operation'] == 'ADD' else 'right',
+ x + width - 24, rect[1] + 10, 12, 'secondary')
+ p.target(key, rect, ('menu-item', identifier), not disabled, path_name(identifier) + '\n' + description)
+ if not items:
+ p.text('No matching models', x + 12, y + 120, FONT_SIZE, 'secondary', width - 24)
+ if len(items) > rows:
+ track = rows * 45
+ p.rect(x + width - 5, y + 109 + start / len(items) * track, 2,
+ max(12, rows / len(items) * track), 'muted', 1)
+ p.rect(x + 12, y + height - 26, width - 24, 1, 'divider')
+ p.text('Enter to add · Esc to close' if menu['operation'] == 'ADD' else 'Enter to replace · Esc to close',
+ x + 12, y + height - 18, 10, 'secondary', width - 24)
diff --git a/stablegen/ui/studio_tips.py b/stablegen/ui/studio_tips.py
new file mode 100644
index 0000000..1cbb691
--- /dev/null
+++ b/stablegen/ui/studio_tips.py
@@ -0,0 +1,80 @@
+"""Studio tips whose dismissal lasts across files, sessions and add-on updates.
+
+Dismissals live in a small file in StableGen's user folder instead of the
+add-on preferences, so they persist even when preference auto-save is off.
+"""
+import json
+import logging
+from pathlib import Path
+
+import bpy
+
+from ..core import ADDON_PKG
+
+WIDEN_CALLOUT = 'widen_callout'
+WIDEN_HINT = 'widen_hint'
+
+_log = logging.getLogger(__name__)
+_dismissed = None
+
+
+def _path():
+ try:
+ folder = bpy.utils.extension_path_user(ADDON_PKG, create=True)
+ except ValueError:
+ # Legacy add-on installs have no extension user folder.
+ folder = bpy.utils.user_resource('CONFIG', path=ADDON_PKG, create=True)
+ return Path(folder) / 'tips.json'
+
+
+def _load():
+ global _dismissed
+ if _dismissed is None:
+ try:
+ _dismissed = set(json.loads(_path().read_text(encoding='utf-8')).get('dismissed', ()))
+ except FileNotFoundError:
+ _dismissed = set()
+ except (OSError, ValueError, AttributeError):
+ _log.warning('Could not read StableGen tips; showing them again', exc_info=True)
+ _dismissed = set()
+ return _dismissed
+
+
+def dismissed(name):
+ return name in _load()
+
+
+def dismiss(name):
+ tips = _load()
+ if name in tips:
+ return
+ tips.add(name)
+ try:
+ _path().write_text(json.dumps({'dismissed': sorted(tips)}), encoding='utf-8')
+ except OSError:
+ # The tip stays hidden for this session even if the file is unwritable.
+ _log.warning('Could not save dismissed StableGen tip', exc_info=True)
+
+
+def reset():
+ global _dismissed
+ _dismissed = set()
+ try:
+ _path().unlink(missing_ok=True)
+ except OSError:
+ _log.warning('Could not reset StableGen tips', exc_info=True)
+
+
+class SG_OT_ResetTips(bpy.types.Operator):
+ bl_idname = 'stablegen.reset_tips'
+ bl_label = 'Reset Tips'
+ bl_description = 'Show dismissed StableGen tips again, such as the hint to widen the sidebar'
+
+ def execute(self, context):
+ reset()
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ self.report({'INFO'}, 'StableGen tips will show again')
+ return {'FINISHED'}
diff --git a/stablegen/ui/studio_widgets.py b/stablegen/ui/studio_widgets.py
index a7bc10d..0f8e3ff 100644
--- a/stablegen/ui/studio_widgets.py
+++ b/stablegen/ui/studio_widgets.py
@@ -6,7 +6,9 @@ import bpy
import blf
import gpu
from gpu_extras.batch import batch_for_shader
+import numpy as np
+from . import brand
from .studio_text import wrap
FONT_SIZE = 11
@@ -15,6 +17,160 @@ CONTROL_GAP = 5
TEXT_LINE_HEIGHT = 17
TEXT_PADDING = 8
+def _arc_arrow(cx, cy, radius, start, end, length=4.5, width=5.5):
+ """Arc from start to end degrees (clockwise on screen when end > start) and its filled head.
+
+ The arc stops at the head's base so a thin stroke never runs into the arrowhead.
+ """
+ steps = max(10, int(abs(end - start) / 8))
+ arc = [(cx + radius * math.cos(math.radians(start + (end - start) * i / steps)),
+ cy + radius * math.sin(math.radians(start + (end - start) * i / steps))) for i in range(steps + 1)]
+ a, sign = math.radians(end), 1 if end > start else -1
+ bx, by = cx + radius * math.cos(a), cy + radius * math.sin(a)
+ tx, ty, nx, ny = -math.sin(a) * sign, math.cos(a) * sign, math.cos(a), math.sin(a)
+ head = [(bx + tx * length, by + ty * length),
+ (bx + nx * width / 2, by + ny * width / 2), (bx - nx * width / 2, by - ny * width / 2)]
+ return arc, head
+
+
+_SYNC = (_arc_arrow(10.5, 10.5, 7, 200, 320), _arc_arrow(10.5, 10.5, 7, 20, 140))
+
+# Line icons on a 21-unit grid. Like Blender's SVG icons, they are rasterized
+# once per pixel size into anti-aliased coverage bitmaps and drawn as textures.
+ICON_PATHS = {
+ 'camera': [[(2, 5), (6, 5), (8, 2), (13, 2), (15, 5), (19, 5), (19, 17), (2, 17), (2, 5)]],
+ 'document': [[(13, 2), (4, 2), (4, 19), (17, 19), (17, 6), (13, 2), (13, 6), (17, 6)], [(7, 10), (14, 10)], [(7, 14), (12, 14)]],
+ 'clone': [[(8, 7), (19, 7), (19, 18), (8, 18), (8, 7)], [(14, 4), (3, 4), (3, 14), (5, 14)]],
+ 'mirror': [[(10, 2), (10, 19)], [(2, 6), (6, 6), (6, 15), (2, 15), (2, 6)], [(14, 6), (18, 6), (18, 15), (14, 15), (14, 6)]],
+ 'expand': [[(12, 2), (19, 2), (19, 9)], [(19, 2), (12, 9)], [(8, 19), (2, 19), (2, 12)], [(2, 19), (9, 12)]],
+ 'labels': [[(3, 3), (18, 3)], [(10, 3), (10, 18)], [(6, 18), (14, 18)]],
+ 'down': [[(5, 8), (10, 13), (15, 8)]],
+ 'up': [[(5, 13), (10, 8), (15, 13)]],
+ 'right': [[(7, 5), (12, 10), (7, 15)]],
+ 'reset': [arc for arc, _ in _SYNC],
+ 'search': [[(14, 14), (19, 19)]],
+ 'settings': [[(2, 5), (19, 5)], [(2, 10), (19, 10)], [(2, 15), (19, 15)], [(7, 3), (7, 7)], [(14, 8), (14, 12)], [(9, 13), (9, 17)]],
+ 'play': [[(6, 3), (18, 10), (6, 18), (6, 3)]],
+ 'stop': [[(5, 5), (16, 5), (16, 16), (5, 16), (5, 5)]],
+ 'layers': [[(10, 2), (19, 7), (10, 12), (1, 7), (10, 2)], [(1, 11), (10, 16), (19, 11)], [(1, 15), (10, 20), (19, 15)]],
+ 'grid': [[(3, 3), (18, 3), (18, 18), (3, 18), (3, 3)], [(3, 8), (18, 8)], [(3, 13), (18, 13)], [(8, 3), (8, 18)], [(13, 3), (13, 18)]],
+ 'download': [[(10, 2), (10, 13)], [(5, 8), (10, 13), (15, 8)], [(2, 14), (2, 19), (18, 19), (18, 14)]],
+ 'eye': [[(1, 10), (6, 5), (14, 5), (19, 10), (14, 15), (6, 15), (1, 10)]],
+ 'x': [[(5, 5), (16, 16)], [(5, 16), (16, 5)]],
+ 'plus': [[(10, 3), (10, 18)], [(3, 10), (18, 10)]],
+ 'minus': [[(3, 10), (18, 10)]],
+ 'check': [[(3, 10), (8, 15), (18, 5)]],
+ 'arrow': [[(3, 10), (18, 10)], [(12, 4), (18, 10), (12, 16)]],
+ 'widen': [[(3, 3), (3, 18)], [(18, 10.5), (7, 10.5)], [(11, 6.5), (7, 10.5), (11, 14.5)]],
+ 'folder': [[(2, 6), (2, 18), (19, 18), (19, 6), (10, 6), (8, 3), (2, 3), (2, 6)]],
+ 'light': [[(7, 15), (7, 18), (14, 18), (14, 15), (17, 11), (17, 6), (13, 2), (8, 2), (4, 6), (4, 11), (7, 15)], [(7, 15), (14, 15)]],
+ 'modifier': [[(3, 3), (8, 3), (8, 8), (13, 8), (13, 13), (18, 13), (18, 18), (3, 18), (3, 3)]],
+ 'curve': [[(2, 17), (5, 17), (8, 14), (10, 6), (13, 3), (19, 3)], [(2, 15), (2, 19)], [(19, 1), (19, 5)]],
+ 'material': [[(10, 2), (18, 6), (18, 15), (10, 19), (2, 15), (2, 6), (10, 2)], [(2, 6), (10, 10), (18, 6)], [(10, 10), (10, 19)]],
+ 'rig': [[(10, 2), (10, 9), (4, 6)], [(10, 9), (17, 5)], [(10, 9), (6, 19)], [(10, 9), (16, 18)]],
+ 'graph': [[(2, 2), (2, 18), (19, 18)], [(4, 14), (8, 8), (12, 11), (18, 3)]],
+ 'shield': [[(10, 2), (18, 5), (17, 13), (10, 19), (3, 13), (2, 5), (10, 2)]],
+}
+ICON_CIRCLES = {'camera': (10.5, 11, 4), 'eye': (10, 10, 2.5), 'search': (9, 9, 6)}
+# Filled convex shapes, such as arrowheads that would blur into a thin stroke.
+ICON_FILLS = {'reset': [head for _, head in _SYNC]}
+ICON_PAD = 2
+_icon_textures = {}
+
+
+def _hint(path, stroke):
+ """Put axis-aligned strokes on whole pixels, as Blender's pixel-grid icon designs are."""
+ odd = round(stroke) % 2 == 1
+ snap = (lambda v: math.floor(v) + .5) if odd else round
+ hinted = [list(point) for point in path]
+ for i, ((x1, y1), (x2, y2)) in enumerate(zip(path, path[1:])):
+ if abs(x1 - x2) < 1e-4:
+ hinted[i][0] = hinted[i + 1][0] = snap(x1)
+ if abs(y1 - y2) < 1e-4:
+ hinted[i][1] = hinted[i + 1][1] = snap(y1)
+ return hinted
+
+
+def _rasterize(paths, extent, half_width):
+ """Analytic per-pixel stroke coverage, the anti-aliasing nanosvg gives Blender's icons."""
+ ys, xs = np.mgrid[0:extent, 0:extent].astype(np.float32) + .5
+ coverage = np.zeros((extent, extent), np.float32)
+ for path in paths:
+ for (x1, y1), (x2, y2) in zip(path, path[1:]):
+ dx, dy = x2 - x1, y2 - y1
+ length = dx * dx + dy * dy
+ t = np.clip(((xs - x1) * dx + (ys - y1) * dy) / length, 0, 1) if length else 0
+ distance = np.hypot(xs - (x1 + t * dx), ys - (y1 + t * dy))
+ np.maximum(coverage, np.clip(half_width + .5 - distance, 0, 1), out=coverage)
+ return coverage
+
+
+def _fill(coverage, polygons):
+ """Add convex polygons, anti-aliased by their signed distance to the nearest edge."""
+ extent = coverage.shape[0]
+ ys, xs = np.mgrid[0:extent, 0:extent].astype(np.float32) + .5
+ for polygon in polygons:
+ # Wind counter-clockwise on screen so every edge normal points outward.
+ if sum(x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(polygon, polygon[1:] + polygon[:1])) > 0:
+ polygon = polygon[::-1]
+ distance = np.full((extent, extent), -np.inf, np.float32)
+ for (x1, y1), (x2, y2) in zip(polygon, polygon[1:] + polygon[:1]):
+ length = math.hypot(x2 - x1, y2 - y1)
+ np.maximum(distance, ((xs - x1) * -(y2 - y1) + (ys - y1) * (x2 - x1)) / length, out=distance)
+ np.maximum(coverage, np.clip(.5 - distance, 0, 1), out=coverage)
+ return coverage
+
+
+def _icon_coverage(name, size, scale):
+ """Anti-aliased coverage of an icon at this device pixel size, top row first."""
+ stroke = scale # one UI pixel, the stroke weight of Blender's own icon set
+ unit = size * scale / 21
+ to_pixels = lambda points: [(px * unit + ICON_PAD, py * unit + ICON_PAD) for px, py in points]
+ paths = [_hint(to_pixels(path), stroke) for path in ICON_PATHS.get(name, ICON_PATHS['settings'])]
+ if name in ICON_CIRCLES:
+ cx, cy, radius = ICON_CIRCLES[name]
+ paths.append(to_pixels([(cx + math.cos(i * math.pi / 12) * radius,
+ cy + math.sin(i * math.pi / 12) * radius) for i in range(25)]))
+ extent = math.ceil(size * scale) + ICON_PAD * 2
+ coverage = _rasterize(paths, extent, stroke / 2)
+ return _fill(coverage, [to_pixels(polygon) for polygon in ICON_FILLS.get(name, ())])
+
+
+def _icon_texture(name, size, scale):
+ """Return a cached (texture, extent) for an icon at this device pixel size."""
+ key = (name, round(size * scale, 3))
+ if key not in _icon_textures:
+ coverage = _icon_coverage(name, size, scale)
+ extent = coverage.shape[0]
+ rgba = np.ones((extent, extent, 4), np.float32)
+ rgba[..., 3] = coverage[::-1] # GPU rows start at the bottom
+ data = gpu.types.Buffer('FLOAT', rgba.size, rgba.ravel().tolist())
+ _icon_textures[key] = gpu.types.GPUTexture((extent, extent), format='RGBA16F', data=data), extent
+ return _icon_textures[key]
+
+
+def _logo_texture(size, scale):
+ """Return a cached (texture, extent) for the full-colour logo at this device pixel size."""
+ extent = round(size * scale)
+ key = ('logo', extent)
+ if key not in _icon_textures:
+ rgba = brand.rasterize(brand.LOGO, extent, brand.LOGO_BOX)[::-1] # GPU rows start at the bottom
+ data = gpu.types.Buffer('FLOAT', rgba.size, np.ascontiguousarray(rgba).ravel().tolist())
+ _icon_textures[key] = gpu.types.GPUTexture((extent, extent), format='RGBA16F', data=data), extent
+ return _icon_textures[key]
+
+
+def _text_shadow(scale):
+ """Blender's widget font-style shadow as (blf level, value, alpha, x, y), or None."""
+ styles = bpy.context.preferences.ui_styles
+ if not styles or styles[0].widget.shadow <= 0:
+ return None
+ style = styles[0].widget
+ # The text shader blurs types 1-4 with 3x3, 5 and 7+ with 5x5; 6 is an outline.
+ level = 3 if style.shadow <= 4 else 6 if style.shadow == 6 else 5
+ return (level, style.shadow_value, style.shadow_alpha,
+ int(style.shadow_offset_x * scale), int(style.shadow_offset_y * scale))
+
def font_size(size=FONT_SIZE):
"""Use Blender's widget font size; coordinates already follow its UI scale."""
@@ -120,7 +276,7 @@ class Target:
if not self.enabled:
return 'DEFAULT'
kind = self.action[0] if isinstance(self.action, tuple) else ''
- return 'TEXT' if kind == 'edit' else 'MOVE_X' if kind == 'slider' else 'DEFAULT'
+ return 'TEXT' if kind in {'edit', 'menu-lora-search'} else 'MOVE_X' if kind == 'slider' else 'MOVE_Y' if kind == 'camera-drag' else 'DEFAULT'
def contains(self, x, y):
rx, ry, width, height = self.rect
@@ -135,6 +291,7 @@ class Painter:
def __init__(self, region, scale=1, font=0):
self.region, self.scale, self.font = region, scale, font
self.colors = theme_colors(bpy.context)
+ self.text_shadow = _text_shadow(scale)
self.width = region.width / scale - 28
self.height = region.height / scale
self.shader = gpu.shader.from_builtin('UNIFORM_COLOR')
@@ -291,7 +448,16 @@ class Painter:
blf.size(self.font, size * self.scale)
blf.color(self.font, *self.colors.get(tint, tint))
blf.position(self.font, x * self.scale, (self.height - y - size) * self.scale, 0)
+ if self.text_shadow:
+ level, value, alpha, offset_x, offset_y = self.text_shadow
+ blf.enable(self.font, blf.SHADOW)
+ blf.shadow(self.font, level, value, value, value, alpha)
+ blf.shadow_offset(self.font, offset_x, offset_y)
blf.draw(self.font, text)
+ if self.text_shadow:
+ blf.disable(self.font, blf.SHADOW)
+ # blf.draw leaves blending off; translucent shapes and icon edges need it.
+ gpu.state.blend_set('ALPHA')
def image(self, image, rect):
self.emit(self.draw_image, image, rect)
@@ -314,6 +480,15 @@ class Painter:
'texCoord': [(0,0), (1,0), (1,1), (0,1)]}).draw(shader)
def icon(self, name, x, y, size=15, tint='secondary'):
+ if name == 'grip':
+ diameter = max(2, round(size * self.scale / 7)) / self.scale
+ gap = 2 * diameter
+ for row in range(3):
+ for column in range(2):
+ self.rect(x + size / 2 + (column - .5) * gap - diameter / 2,
+ y + size / 2 + (row - 1) * gap - diameter / 2,
+ diameter, diameter, tint, diameter / 2)
+ return
if name == 'more':
diameter = max(2, round(size * self.scale / 4))
gap = max(1, round(size * self.scale / 8))
@@ -323,43 +498,38 @@ class Painter:
self.rect((left + i * (diameter + gap)) / self.scale, top / self.scale,
diameter / self.scale, diameter / self.scale, tint, diameter / (2 * self.scale))
return
- paths = {
- 'camera': [[(2, 5), (6, 5), (8, 2), (13, 2), (15, 5), (19, 5), (19, 17), (2, 17), (2, 5)]],
- 'document': [[(13, 2), (4, 2), (4, 19), (17, 19), (17, 6), (13, 2), (13, 6), (17, 6)], [(7, 10), (14, 10)], [(7, 14), (12, 14)]],
- 'clone': [[(8, 7), (19, 7), (19, 18), (8, 18), (8, 7)], [(14, 4), (3, 4), (3, 14), (5, 14)]],
- 'mirror': [[(10, 2), (10, 19)], [(2, 6), (6, 6), (6, 15), (2, 15), (2, 6)], [(14, 6), (18, 6), (18, 15), (14, 15), (14, 6)]],
- 'expand': [[(12, 2), (19, 2), (19, 9)], [(19, 2), (12, 9)], [(8, 19), (2, 19), (2, 12)], [(2, 19), (9, 12)]],
- 'labels': [[(3, 3), (18, 3)], [(10, 3), (10, 18)], [(6, 18), (14, 18)]],
- 'down': [[(5, 8), (10, 13), (15, 8)]],
- 'right': [[(7, 5), (12, 10), (7, 15)]],
- 'reset': [[(4, 4), (4, 10), (10, 10)], [(4, 10), (7, 4), (14, 4), (18, 8), (18, 14), (14, 18), (7, 18), (4, 15)]],
- 'search': [[(14, 14), (19, 19)]],
- 'settings': [[(2, 5), (19, 5)], [(2, 10), (19, 10)], [(2, 15), (19, 15)], [(7, 3), (7, 7)], [(14, 8), (14, 12)], [(9, 13), (9, 17)]],
- 'play': [[(6, 3), (18, 10), (6, 18), (6, 3)]],
- 'stop': [[(5, 5), (16, 5), (16, 16), (5, 16), (5, 5)]],
- 'layers': [[(10, 2), (19, 7), (10, 12), (1, 7), (10, 2)], [(1, 11), (10, 16), (19, 11)], [(1, 15), (10, 20), (19, 15)]],
- 'grid': [[(3, 3), (18, 3), (18, 18), (3, 18), (3, 3)], [(3, 8), (18, 8)], [(3, 13), (18, 13)], [(8, 3), (8, 18)], [(13, 3), (13, 18)]],
- 'download': [[(10, 2), (10, 13)], [(5, 8), (10, 13), (15, 8)], [(2, 14), (2, 19), (18, 19), (18, 14)]],
- 'eye': [[(1, 10), (6, 5), (14, 5), (19, 10), (14, 15), (6, 15), (1, 10)]],
- 'x': [[(5, 5), (16, 16)], [(5, 16), (16, 5)]],
- 'plus': [[(10, 3), (10, 18)], [(3, 10), (18, 10)]],
- 'arrow': [[(3, 10), (18, 10)], [(12, 4), (18, 10), (12, 16)]],
- 'folder': [[(2, 6), (2, 18), (19, 18), (19, 6), (10, 6), (8, 3), (2, 3), (2, 6)]],
- 'light': [[(7, 15), (7, 18), (14, 18), (14, 15), (17, 11), (17, 6), (13, 2), (8, 2), (4, 6), (4, 11), (7, 15)], [(7, 15), (14, 15)]],
- 'modifier': [[(3, 3), (8, 3), (8, 8), (13, 8), (13, 13), (18, 13), (18, 18), (3, 18), (3, 3)]],
- 'curve': [[(2, 17), (5, 17), (8, 14), (10, 6), (13, 3), (19, 3)], [(2, 15), (2, 19)], [(19, 1), (19, 5)]],
- 'material': [[(10, 2), (18, 6), (18, 15), (10, 19), (2, 15), (2, 6), (10, 2)], [(2, 6), (10, 10), (18, 6)], [(10, 10), (10, 19)]],
- 'rig': [[(10, 2), (10, 9), (4, 6)], [(10, 9), (17, 5)], [(10, 9), (6, 19)], [(10, 9), (16, 18)]],
- 'graph': [[(2, 2), (2, 18), (19, 18)], [(4, 14), (8, 8), (12, 11), (18, 3)]],
- 'shield': [[(10, 2), (18, 5), (17, 13), (10, 19), (3, 13), (2, 5), (10, 2)]],
- }
- if name in {'camera', 'eye', 'search'}:
- cx, cy, radius = {'camera': (10.5, 11, 4), 'eye': (10, 10, 2.5), 'search': (9, 9, 6)}[name]
- self.line([(x + (cx + math.cos(i * math.pi / 12) * radius) * size / 21,
- y + (cy + math.sin(i * math.pi / 12) * radius) * size / 21)
- for i in range(25)], tint, 1)
- for path in paths.get(name, paths['settings']):
- self.line([(x + px * size / 21, y + py * size / 21) for px, py in path], tint, 1)
+ self.emit(self.draw_icon, name, x, y, size, tint)
+
+ def draw_icon(self, name, x, y, size, tint):
+ texture, extent = _icon_texture(name, size, self.scale)
+ r, g, b, a = self.colors.get(tint, tint)
+ a *= bpy.context.preferences.themes[0].user_interface.icon_alpha
+ # Whole device pixels, like Blender's widget icons at 1:1 zoom.
+ left = round(x * self.scale) - ICON_PAD
+ top = self.region.height - round(y * self.scale) + ICON_PAD
+ shader = gpu.shader.from_builtin('IMAGE_COLOR')
+ shader.bind()
+ shader.uniform_sampler('image', texture)
+ shader.uniform_float('color', (r, g, b, a))
+ batch_for_shader(shader, 'TRI_FAN', {
+ 'pos': [(left, top - extent), (left + extent, top - extent), (left + extent, top), (left, top)],
+ 'texCoord': [(0, 0), (1, 0), (1, 1), (0, 1)]}).draw(shader)
+
+ def logo(self, x, y, size):
+ self.emit(self.draw_logo, x, y, size)
+
+ def draw_logo(self, x, y, size):
+ texture, extent = _logo_texture(size, self.scale)
+ alpha = bpy.context.preferences.themes[0].user_interface.icon_alpha
+ left = round(x * self.scale)
+ top = self.region.height - round(y * self.scale)
+ shader = gpu.shader.from_builtin('IMAGE_COLOR')
+ shader.bind()
+ shader.uniform_sampler('image', texture)
+ shader.uniform_float('color', (1, 1, 1, alpha))
+ batch_for_shader(shader, 'TRI_FAN', {
+ 'pos': [(left, top - extent), (left + extent, top - extent), (left + extent, top), (left, top)],
+ 'texCoord': [(0, 0), (1, 0), (1, 1), (0, 1)]}).draw(shader)
def target(self, key, rect, action, enabled=True, hint=''):
target = Target(key, rect, action, enabled, hint, self.clip_rect)
@@ -401,6 +571,22 @@ class Painter:
'accent' if hover else 'muted' if enabled else 'disabled')
self.target(key, rect, action, enabled, hint)
+ def selection(self, key, rect, label, action, selected, *, enabled=True, hint='', accessory_width=0):
+ """A selected item is a row with a radio marker, separate from actions."""
+ x, y, width, height = rect
+ hover = enabled and key == self.hover_key
+ self.outline(x, y, width, height, 'selected' if selected else 'hover_soft' if hover else 'menu',
+ 'accent' if selected else 'hover_border' if hover else 'menu_border', 3)
+ tint = 'accent' if selected and enabled else 'secondary' if enabled else 'disabled'
+ self.rect(x + 10, y + (height - 12) / 2, 12, 12, tint, 6)
+ self.rect(x + 11, y + (height - 10) / 2, 10, 10,
+ 'selected' if selected else 'hover_soft' if hover else 'menu', 5)
+ if selected:
+ self.rect(x + 13, y + (height - 6) / 2, 6, 6, tint, 3)
+ self.text(label, x + 30, y + (height - font_size()) / 2 - 1,
+ FONT_SIZE, 'text' if enabled else 'disabled', width - accessory_width - 38)
+ self.target(key, (x, y, width - accessory_width, height), action, enabled, hint)
+
def switch(self, key, rect, label, checked, action, *, enabled=True, hint='', hover=False):
hover = enabled and (hover or key == self.hover_key)
x, y, w, h = rect