Skip to content

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

show generated images and numbered labels on viewport cameras

sakalondd299338616db
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index c17ef19..3d0aefc 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -53,6 +53,7 @@ from .cameras import (
MoveCameraOrder, ApplyCameraOrderPreset,
)
from .debug_tools import debug_classes as _debug_classes
+from .cameras import display as camera_display
from .core import server_monitor
from .texturing.regression import REGRESSION_CLASSES
from .texturing import masked_edit
@@ -204,6 +205,7 @@ 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)
def register():
@@ -223,11 +225,13 @@ def register():
)
register_variant_properties()
register_studio_ui()
+ camera_display.register()
server_monitor.register()
def unregister():
server_monitor.unregister()
+ camera_display.unregister()
unregister_studio_ui()
unregister_variant_properties()
masked_edit.unregister_properties()
diff --git a/stablegen/cameras/display.py b/stablegen/cameras/display.py
new file mode 100644
index 0000000..c923373
--- /dev/null
+++ b/stablegen/cameras/display.py
@@ -0,0 +1,116 @@
+"""Viewport-only camera display options and reversible surface diagnostics."""
+import bpy
+
+from ..utils import sg_modal_active
+from . import prompt_overlay
+
+
+def _redraw(self, context):
+ from . import overlays
+ overlays.display_settings_changed(context.scene)
+
+
+SCOPE = [('ALL', 'All', 'Display all visible cameras'),
+ ('SELECTED', 'Selected', 'Display only selected cameras'),
+ ('NONE', 'None', 'Hide this overlay')]
+
+
+class SGCameraDisplay(bpy.types.PropertyGroup):
+ labels: bpy.props.EnumProperty(name='Labels', items=SCOPE, default='ALL', update=_redraw,
+ description='Camera labels numbered in generation order. Click a saved-prompt icon to show or hide its editable view prompt')
+ images: bpy.props.EnumProperty(name='Generated images', items=SCOPE, default='ALL', update=_redraw,
+ description='Show existing projection images inside camera frames, preserving aspect ratio and alignment with the camera’s projection from either side. This viewport overlay does not change renders')
+ crops: bpy.props.BoolProperty(name='Actual image frames', default=True, update=_redraw,
+ description='Outline each camera’s actual rectangular projection frame inside Blender’s camera display')
+ states: bpy.props.BoolProperty(name='Camera state indicators', default=True, update=_redraw,
+ description='Orange marks selection; a camera icon marks the scene camera; a play icon marks the view currently generating')
+
+
+class SG_OT_CameraDisplay(bpy.types.Operator):
+ bl_idname = 'stablegen.camera_display'
+ bl_label = 'Camera Display'
+ bl_description = 'Configure numbered camera labels, generated image previews and rectangular image frames'
+
+ def invoke(self, context, event):
+ return context.window_manager.invoke_popup(self, width=320)
+
+ def execute(self, context):
+ return {'FINISHED'}
+
+ def draw(self, context):
+ layout = self.layout
+ settings = context.scene.sg_camera_display
+ layout.use_property_split = True
+ layout.use_property_decorate = False
+ layout.prop(settings, 'labels')
+ layout.prop(settings, 'images')
+ layout.prop(settings, 'crops')
+ layout.prop(settings, 'states')
+ layout.separator()
+ row = layout.row(align=True)
+ row.operator('stablegen.camera_surface_display', text='Visibility', icon='HIDE_OFF').mode = 'VISIBILITY'
+ row.operator('stablegen.camera_surface_display', text='View weight', icon='SHADING_RENDERED').mode = 'WEIGHT'
+ if context.scene.sg_studio_diagnostics.token:
+ layout.operator('stablegen.camera_surface_display', text='Restore textures', icon='LOOP_BACK').mode = 'TEXTURES'
+
+
+class SG_OT_CameraSurfaceDisplay(bpy.types.Operator):
+ bl_idname = 'stablegen.camera_surface_display'
+ bl_label = 'Camera Surface Diagnostic'
+ bl_description = 'Inspect the selected camera using reversible diagnostic materials; requires Debug enabled in add-on preferences'
+ bl_options = {'REGISTER', 'UNDO'}
+ mode: bpy.props.EnumProperty(items=[('VISIBILITY', 'Visibility', 'Surfaces visible to this camera'),
+ ('WEIGHT', 'View weight', 'Unnormalized projection visibility weight'),
+ ('TEXTURES', 'Restore textures', 'Restore original meshes and materials')])
+
+ @classmethod
+ def poll(cls, context):
+ if context.mode != 'OBJECT' or sg_modal_active(context):
+ return False
+ from ..core import ADDON_PKG
+ prefs = context.preferences.addons.get(ADDON_PKG)
+ if (not prefs or not prefs.preferences.enable_debug) and not context.scene.sg_studio_diagnostics.token:
+ cls.poll_message_set('Enable Debug in StableGen add-on preferences to use surface diagnostics')
+ return False
+ return any(o.type == 'CAMERA' for o in context.scene.objects)
+
+ def execute(self, context):
+ from ..ui import studio_diagnostics as diagnostics
+ state = context.scene.sg_studio_diagnostics
+ if self.mode == 'TEXTURES':
+ diagnostics.restore(context.scene)
+ else:
+ camera = context.active_object
+ if camera is None or camera.type != 'CAMERA':
+ camera = next((o for o in context.selected_objects if o.type == 'CAMERA'), context.scene.camera)
+ if camera is None:
+ self.report({'WARNING'}, 'Select a camera to inspect')
+ return {'CANCELLED'}
+ state.camera, state.mode = camera, self.mode
+ try:
+ diagnostics.apply(context)
+ except Exception as exc:
+ diagnostics.restore(context.scene)
+ self.report({'WARNING'}, str(exc).split('\n')[0])
+ return {'FINISHED'} # Restoration must remain undoable.
+ _redraw(None, context)
+ return {'FINISHED'}
+
+
+CLASSES = [SGCameraDisplay, SG_OT_CameraDisplay, SG_OT_CameraSurfaceDisplay,
+ prompt_overlay.SG_GT_CameraPrompt, prompt_overlay.SG_GGT_CameraPrompts,
+ prompt_overlay.SG_OT_CameraPromptInput]
+
+
+def register():
+ bpy.types.Scene.sg_camera_display = bpy.props.PointerProperty(type=SGCameraDisplay)
+ prompt_overlay.register()
+ from . import overlays
+ overlays.register_overlays()
+
+
+def unregister():
+ from . import overlays
+ overlays.unregister_overlays()
+ prompt_overlay.unregister()
+ del bpy.types.Scene.sg_camera_display
diff --git a/stablegen/cameras/images.py b/stablegen/cameras/images.py
new file mode 100644
index 0000000..4657001
--- /dev/null
+++ b/stablegen/cameras/images.py
@@ -0,0 +1,86 @@
+"""Read existing projection images without loading files or changing materials."""
+import json
+from pathlib import Path
+
+import bpy
+
+from ..texturing.view_plan import generation_cameras, order_cameras
+
+
+def images_from_manifest(cameras, textures, manifest):
+ """Keep persisted source indices even when cameras are renamed or removed."""
+ by_id = {}
+ for camera in cameras:
+ if camera.get('sg_view_uuid'):
+ by_id.setdefault(str(camera['sg_view_uuid']), []).append(camera)
+ by_name = {c.name: c for c in cameras}
+ result = {}
+ for fallback_index, record in enumerate(manifest.get('views', [])):
+ if not isinstance(record, dict):
+ continue
+ identity = str(record.get('view_id') or '')
+ matches = by_id.get(identity, [])
+ camera = (matches[0] if len(matches) == 1 else
+ next((c for c in matches if c.name == record.get('name')), None)) if identity else by_name.get(record.get('name'))
+ index = record.get('index', fallback_index)
+ if isinstance(index, str) and index.isdigit():
+ index = int(index)
+ if not isinstance(index, int):
+ continue
+ if camera is not None and index in textures:
+ result[camera.name] = textures[index]
+ return result
+
+
+def projected_images(context, *, objects=None, materials=None, manifests=None):
+ """Resolve actual texture nodes and saved camera identities, with no recovery.
+
+ Optional object/material inputs let viewport overlays use the original
+ projection while reversible diagnostic materials are being displayed.
+ Manifest reads can be cached outside the draw callback.
+ """
+ scene = context.scene
+ if objects is None:
+ objects = context.selected_objects if scene.texture_objects == 'selected' else context.view_layer.objects
+ if materials is None:
+ materials = {slot.material for obj in objects if obj.type == 'MESH' and not obj.hide_get()
+ for slot in obj.material_slots if slot.material}
+ textures, latest = {}, -1
+ for material in materials:
+ if not material.use_nodes or not material.node_tree:
+ continue
+ for node in material.node_tree.nodes:
+ if node.type != 'TEX_IMAGE' or node.image is None:
+ continue
+ parts = node.label.split('-')
+ if len(parts) != 2 or not all(part.isdigit() for part in parts):
+ continue
+ index, version = map(int, parts)
+ if version > latest:
+ latest, textures = version, {}
+ if version == latest:
+ textures.setdefault(index, node.image)
+ if not textures:
+ return {}
+ custom = [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ()
+ cameras = order_cameras(generation_cameras(scene), custom)
+ attempted = set()
+ for image in textures.values():
+ folder = Path(bpy.path.abspath(image.filepath, library=image.library)).parent
+ if folder.name.lower() != 'generated' or folder in attempted:
+ continue
+ attempted.add(folder)
+ path = folder.parent / 'view_plan.json'
+ try:
+ if manifests is not None and path in manifests:
+ manifest = manifests[path]
+ else:
+ manifest = json.loads(path.read_text(encoding='utf8'))
+ if manifests is not None:
+ manifests[path] = manifest
+ if isinstance(manifest, dict) and isinstance(manifest.get('views'), list) and manifest['views']:
+ return images_from_manifest(cameras, textures, manifest)
+ except (OSError, ValueError, TypeError):
+ continue
+ # Older generations without a view plan retain the existing order fallback.
+ return {camera.name: textures[i] for i, camera in enumerate(cameras) if i in textures}
diff --git a/stablegen/cameras/operators.py b/stablegen/cameras/operators.py
index 49c4ccf..6242dbf 100644
--- a/stablegen/cameras/operators.py
+++ b/stablegen/cameras/operators.py
@@ -275,10 +275,10 @@ class MirrorCamera(bpy.types.Operator):
class ToggleCameraLabels(bpy.types.Operator):
- """Toggle floating camera prompt labels in the 3D viewport.
+ """Toggle numbered camera labels in the 3D viewport.
- Shows or hides the per-camera prompt text (from Collect Camera Prompts
- or auto-generated view labels) next to each camera in the viewport."""
+ Draws short camera names and their generation-order numbers.
+ Full prompts remain in the camera prompt editor."""
bl_idname = "object.toggle_camera_labels"
bl_label = "Toggle Camera Labels"
bl_options = {'REGISTER'}
@@ -288,12 +288,12 @@ class ToggleCameraLabels(bpy.types.Operator):
return any(o.type == 'CAMERA' for o in context.scene.objects) and not sg_modal_active(context)
def execute(self, context):
- if _overlays._sg_label_draw_handle is not None:
+ if context.scene.sg_camera_display.labels != 'NONE':
+ context.scene.sg_camera_display.labels = 'NONE'
_sg_remove_label_overlay()
self.report({'INFO'}, "Camera labels hidden")
else:
+ context.scene.sg_camera_display.labels = 'ALL'
_sg_ensure_label_overlay()
self.report({'INFO'}, "Camera labels visible")
return {'FINISHED'}
-
-
\ No newline at end of file
diff --git a/stablegen/cameras/overlays.py b/stablegen/cameras/overlays.py
index 3e94c76..5e41a97 100644
--- a/stablegen/cameras/overlays.py
+++ b/stablegen/cameras/overlays.py
@@ -1,24 +1,31 @@
-"""GPU draw handlers for camera crop overlays and view labels."""
+"""Cached viewport-only camera image planes, crop frames and numbered labels."""
+import logging
-import math
-import bpy # pylint: disable=import-error
-import mathutils # pylint: disable=import-error
-import numpy as np
-import blf
+import bpy
import gpu
+import mathutils
+from bpy.app.handlers import persistent
+from bpy_extras.view3d_utils import location_3d_to_region_2d
from gpu_extras.batch import batch_for_shader
+
+from ..texturing.view_plan import generation_cameras, order_cameras
from .geometry import _get_camera_resolution
+from . import prompt_overlay
_ADDON_PKG = __package__.rsplit('.', 1)[0]
-
-
-# ---- Per-camera crop overlay (GPU draw handler) -------------------------
-
_sg_crop_draw_handle = None
+_sg_label_draw_handle = None
+_sg_labels_user_visible = True
+_registered = False
+_snapshots = {}
+_geometry = {}
+_textures = {}
+_shaders = {}
+_log = logging.getLogger(__name__)
+_last_error = None
def _sg_camera_overlay_color(camera):
- """Use the solid-projection diagnostic color when assigned to this camera."""
color = camera.get('_sg_debug_projection_color')
if color is not None:
return color
@@ -26,129 +33,460 @@ def _sg_camera_overlay_color(camera):
return prefs.preferences.overlay_color if prefs else (0.3, 0.5, 1.0)
-def _sg_draw_crop_overlays():
- """SpaceView3D draw callback: renders a coloured rectangle inside each
- camera's pyramid to visualise the actual (non-square) crop region."""
- context = bpy.context
+def _snapshot(context):
scene = context.scene
-
- # Respect Blender's overlay toggle
- space = context.space_data
- if space and hasattr(space, 'overlay') and not space.overlay.show_overlays:
+ key = (scene.as_pointer(), context.view_layer.name)
+ if key not in _snapshots:
+ _snapshots[key] = dict(scene=scene, layer=context.view_layer, cameras=(), images={},
+ dirty=True, manifests={})
+ return _snapshots[key]
+
+
+def _source_materials(context):
+ state = getattr(context.scene, 'sg_studio_diagnostics', None)
+ if state and state.token:
+ return {slot.object_material if slot.link == 'OBJECT' else slot.material
+ for record in state.meshes for slot in record.slots
+ if (slot.object_material if slot.link == 'OBJECT' else slot.material)}
+ # Camera selection must not hide the source images of selected-target runs.
+ return {slot.material for obj in context.view_layer.objects
+ if obj.type == 'MESH' and not obj.hide_get()
+ for slot in obj.material_slots if slot.material}
+
+
+def _generating_camera(context):
+ if getattr(context.scene, 'generation_status', '') != 'running':
+ return None
+ for window in context.window_manager.windows:
+ for op in window.modal_operators:
+ if getattr(op, 'bl_idname', '') != 'OBJECT_OT_test_stable':
+ continue
+ cameras = getattr(op, '_cameras', ()) or ()
+ if getattr(op, '_pbr_active', False):
+ return None # PBR's subset ordinal is not a camera source index.
+ if getattr(context.scene, 'generation_method', '') not in {'separate','sequential','refine','local_edit'}:
+ return None
+ index = getattr(op, '_current_image', -1)
+ if 0 <= index < len(cameras) and cameras[index].name in context.scene.objects:
+ return cameras[index]
+ return None
+
+
+def _refresh_snapshot(context):
+ """Main-thread timer work only: no filesystem/material scans during drawing."""
+ snapshot = _snapshot(context)
+ scene = context.scene
+ custom = [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ()
+ cameras = tuple(order_cameras(generation_cameras(scene), custom))
+ # Automatic sequencing and reproject may use a saved order for this run.
+ # Read the existing runtime plan; do not recompute coverage or change it.
+ if getattr(scene, 'generation_status', '') == 'running':
+ for window in context.window_manager.windows:
+ op = next((op for op in window.modal_operators
+ if getattr(op, 'bl_idname', '') == 'OBJECT_OT_test_stable'), None)
+ plan = getattr(op, '_cameras', None)
+ if plan and all(c.name in scene.objects for c in plan):
+ cameras = tuple(plan)
+ break
+ identity = tuple((c.as_pointer(), c.name, c.get('sg_view_uuid')) for c in cameras)
+ if identity != snapshot.get('identity'):
+ snapshot['dirty'] = True
+ snapshot['identity'] = identity
+ snapshot['cameras'] = cameras
+ snapshot['generating'] = _generating_camera(context)
+ if snapshot['dirty'] and scene.sg_camera_display.images != 'NONE':
+ from .images import projected_images
+ snapshot['images'] = projected_images(context, materials=_source_materials(context),
+ manifests=snapshot['manifests'])
+ snapshot['dirty'] = False
+ return snapshot
+
+
+@persistent
+def _invalidate(scene, depsgraph):
+ updates = list(depsgraph.updates)
+ if any(update.is_updated_shading or isinstance(update.id, (bpy.types.Material, bpy.types.NodeTree, bpy.types.Image,
+ bpy.types.Collection, bpy.types.Mesh))
+ for update in updates):
+ for snapshot in _snapshots.values():
+ snapshot['dirty'] = True
+ snapshot['manifests'].clear()
+ # Display settings, selection and material edits do not invalidate textures.
+ for update in updates:
+ if isinstance(update.id, bpy.types.Image):
+ _textures.pop(update.id.original.as_pointer(), None)
+
+
+def _tick():
+ if not _registered:
+ return None
+ seen = set()
+ live_keys = set()
+ try:
+ prompt_overlay.prune()
+ for window in bpy.context.window_manager.windows:
+ area = next((a for a in window.screen.areas if a.type == 'VIEW_3D'), None)
+ if area is None:
+ continue
+ key = (window.scene.as_pointer(), window.view_layer.name)
+ live_keys.add(key)
+ if key in seen:
+ continue
+ seen.add(key)
+ with bpy.context.temp_override(window=window, area=area):
+ previous = _snapshots.get(key)
+ cameras = previous['cameras'] if previous else ()
+ generating = previous.get('generating') if previous else None
+ dirty = previous is None or previous['dirty'] and window.scene.sg_camera_display.images != 'NONE'
+ current = _refresh_snapshot(bpy.context)
+ if dirty or cameras != current['cameras'] or generating != current['generating']:
+ for a in window.screen.areas:
+ if a.type == 'VIEW_3D':
+ a.tag_redraw()
+ for key in set(_snapshots)-live_keys:
+ del _snapshots[key]
+ camera_ids = {c.as_pointer() for snapshot in _snapshots.values() for c in snapshot['cameras']}
+ for key in set(_geometry)-camera_ids:
+ del _geometry[key]
+ image_ids = {image.as_pointer() for snapshot in _snapshots.values() for image in snapshot['images'].values()}
+ for key in set(_textures)-image_ids:
+ del _textures[key]
+ except (ReferenceError, RuntimeError):
+ _clear_cache()
+ return .6
+
+
+def _clear_cache():
+ _snapshots.clear()
+ _geometry.clear()
+ _textures.clear()
+ _shaders.clear()
+
+
+@persistent
+def _load_pre(_dummy):
+ _clear_cache()
+ prompt_overlay.clear()
+
+
+@persistent
+def _load_post(_dummy):
+ display_settings_changed(bpy.context.scene)
+
+
+def display_settings_changed(scene):
+ global _sg_labels_user_visible
+ if bpy.app.background or scene is None:
+ return
+ settings = getattr(scene, 'sg_camera_display', None)
+ if settings:
+ _sg_labels_user_visible = settings.labels != 'NONE'
+ from ..utils import sg_modal_active
+ # Generation deliberately suspends these handlers while preparing renders.
+ if sg_modal_active(bpy.context):
return
+ _sg_ensure_crop_overlay()
+ if _sg_labels_user_visible:
+ _sg_ensure_label_overlay()
+ else:
+ _sg_hide_label_overlay()
+ for screen in bpy.data.screens:
+ for area in screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
- shader = gpu.shader.from_builtin('UNIFORM_COLOR')
- for obj in scene.objects:
- if obj.type != 'CAMERA' or 'sg_display_crop' not in obj:
- continue
- res_x = obj.get('sg_res_x', 0)
- res_y = obj.get('sg_res_y', 0)
- if res_x <= 0 or res_y <= 0:
- continue
+def register_overlays():
+ global _registered
+ if bpy.app.background:
+ return
+ _registered = True
+ for handlers, callback in [(bpy.app.handlers.depsgraph_update_post, _invalidate),
+ (bpy.app.handlers.load_pre, _load_pre),
+ (bpy.app.handlers.load_post, _load_post)]:
+ if callback not in handlers:
+ handlers.append(callback)
+ if not bpy.app.timers.is_registered(_tick):
+ bpy.app.timers.register(_tick, first_interval=.1, persistent=True)
+ display_settings_changed(bpy.context.scene)
+
+
+def unregister_overlays():
+ global _registered
+ _registered = False
+ _sg_remove_crop_overlay()
+ _sg_hide_label_overlay()
+ if bpy.app.timers.is_registered(_tick):
+ bpy.app.timers.unregister(_tick)
+ for handlers, callback in [(bpy.app.handlers.depsgraph_update_post, _invalidate),
+ (bpy.app.handlers.load_pre, _load_pre),
+ (bpy.app.handlers.load_post, _load_post)]:
+ if callback in handlers:
+ handlers.remove(callback)
+ _clear_cache()
+
+
+def _draw_context():
+ context = bpy.context
+ if (context.area is None or context.area.type != 'VIEW_3D' or context.region_data is None
+ or not context.space_data.overlay.show_overlays):
+ return None
+ return context
+
+
+def _visible(camera, context):
+ return camera.visible_get(view_layer=context.view_layer, viewport=context.space_data)
+
+
+def _in_scope(scope, camera):
+ return scope == 'ALL' or scope == 'SELECTED' and camera.select_get()
+
+
+def _crop_points(camera, scene, depsgraph):
+ """Actual render intrinsics, including shift, forced sensor fit and ortho."""
+ rx, ry = _get_camera_resolution(camera, scene)
+ frame = camera.data.view_frame(scene=scene)
+ depth = abs(frame[0].z)
+ if camera.data.type != 'ORTHO':
+ depth *= camera.data.display_size
+ projection = camera.calc_matrix_camera(depsgraph, x=rx, y=ry,
+ scale_x=scene.render.pixel_aspect_x, scale_y=scene.render.pixel_aspect_y)
+ inverse = projection.inverted_safe()
+ points = []
+ for x, y in [(-1,-1), (1,-1), (1,1), (-1,1)]:
+ v = inverse @ mathutils.Vector((x,y,0,1))
+ v = v.xyz / v.w
+ if camera.data.type != 'ORTHO':
+ v *= depth / abs(v.z)
+ else:
+ v.z = -depth
+ points.append(v)
+ return points
+
+
+def _shader(name):
+ if name not in _shaders:
+ try:
+ _shaders[name] = gpu.shader.from_builtin(name)
+ except ValueError:
+ if name != 'IMAGE_COLOR_SCENE_LINEAR_TO_REC709_SRGB':
+ raise
+ _shaders[name] = gpu.shader.from_builtin('IMAGE_COLOR')
+ return _shaders[name]
+
+
+def _camera_geometry(camera, context, image):
+ data, render = camera.data, context.scene.render
+ signature = (tuple(v for row in camera.matrix_world for v in row),
+ data.type, data.lens, data.sensor_fit, data.sensor_width, data.sensor_height,
+ data.shift_x, data.shift_y, data.ortho_scale, data.display_size, data.clip_start, data.clip_end,
+ _get_camera_resolution(camera, context.scene), render.resolution_x, render.resolution_y,
+ render.pixel_aspect_x, render.pixel_aspect_y,
+ image.as_pointer() if image else 0, tuple(image.size) if image else ())
+ key = camera.as_pointer()
+ cached = _geometry.get(key)
+ if cached and cached['signature'] == signature:
+ return cached
+ local = _crop_points(camera, context.scene, context.evaluated_depsgraph_get())
+ points = [camera.matrix_world @ v for v in local]
+ center = sum(points, mathutils.Vector())/4
+ line = _shader('POLYLINE_UNIFORM_COLOR')
+ fill = _shader('UNIFORM_COLOR')
+ cached = dict(signature=signature, points=points, center=center,
+ border=batch_for_shader(line, 'LINES', {'pos':points}, indices=[(0,1),(1,2),(2,3),(3,0)]),
+ backing=batch_for_shader(fill, 'TRI_FAN', {'pos':points}))
+ if image and all(image.size):
+ cx = sum(v.x for v in local)/4
+ cy = sum(v.y for v in local)/4
+ half_x = abs(local[1].x-local[0].x)/2
+ half_y = abs(local[3].y-local[0].y)/2
+ aspect = image.size[0]/image.size[1]
+ if aspect > half_x/half_y:
+ half_y = half_x/aspect
+ else:
+ half_x = half_y*aspect
+ image_points = [camera.matrix_world @ mathutils.Vector((cx+x*half_x, cy+y*half_y, local[0].z))
+ for x,y in [(-1,-1),(1,-1),(1,1),(-1,1)]]
+ shader = _shader('IMAGE_COLOR_SCENE_LINEAR_TO_REC709_SRGB')
+ # Keep pixels anchored to the camera's axes, just like its projection.
+ # A reverse-side view naturally reverses the plane on screen; changing
+ # UVs to compensate would instead turn the subject away from the model.
+ cached['image'] = batch_for_shader(shader, 'TRI_FAN',
+ {'pos':image_points, 'texCoord':((0,0),(1,0),(1,1),(0,1))})
+ _geometry[key] = cached
+ return cached
+
+
+def _record_error():
+ global _last_error
+ import sys
+ error = repr(sys.exc_info()[1])
+ if error != _last_error:
+ _last_error = error
+ _log.exception('Camera viewport display could not draw')
- cam = obj.data
- # Use whichever side of THIS camera is longer as the reference.
- # The scene is set to a square of max_side, so the frustum is square
- # and each side = half_w = half_h. The crop rectangle occupies
- # res_x/cam_max × res_y/cam_max of that square.
- cam_max = max(res_x, res_y)
-
- frame = cam.view_frame(scene=scene)
- corner = frame[0]
- half_w = abs(corner[0])
- half_h = abs(corner[1])
- z_depth = corner[2]
- if half_w < 1e-8 or half_h < 1e-8:
- continue
- sx = res_x / cam_max
- sy = res_y / cam_max
-
- new_hw = half_w * sx
- new_hh = half_h * sy
-
- crop_local = [
- mathutils.Vector((+new_hw, +new_hh, z_depth)),
- mathutils.Vector((-new_hw, +new_hh, z_depth)),
- mathutils.Vector((-new_hw, -new_hh, z_depth)),
- mathutils.Vector((+new_hw, -new_hh, z_depth)),
- ]
-
- wm = obj.matrix_world
- world_pts = [wm @ v for v in crop_local]
- coords = [(v.x, v.y, v.z) for v in world_pts]
- indices = [(0, 1), (1, 2), (2, 3), (3, 0)]
- batch = batch_for_shader(shader, 'LINES', {"pos": coords}, indices=indices)
- shader.bind()
- _oc = _sg_camera_overlay_color(obj)
- shader.uniform_float("color", (_oc[0], _oc[1], _oc[2], 0.9))
- gpu.state.line_width_set(2.0)
+def _sg_draw_crop_overlays():
+ context = _draw_context()
+ if context is None:
+ return
+ settings = context.scene.sg_camera_display
+ if not settings.crops and settings.images == 'NONE':
+ return
+ snapshot = _snapshot(context)
+ blend, depth, depth_mask = gpu.state.blend_get(), gpu.state.depth_test_get(), gpu.state.depth_mask_get()
+ try:
gpu.state.blend_set('ALPHA')
gpu.state.depth_test_set('LESS_EQUAL')
gpu.state.depth_mask_set(False)
- batch.draw(shader)
-
- gpu.state.depth_test_set('NONE')
- gpu.state.depth_mask_set(True)
- gpu.state.blend_set('NONE')
- gpu.state.line_width_set(1.0)
-
-
-# ---- Per-camera view-label overlay (GPU text handler) --------------------
-
-_sg_label_draw_handle = None
-_sg_labels_user_visible = True
+ rv3d = context.region_data
+ eye = rv3d.view_matrix.inverted().translation
+ cameras = sorted(snapshot['cameras'], key=lambda c:(c.matrix_world.translation-eye).length_squared, reverse=True)
+ theme = context.preferences.themes[0].view_3d
+ for camera in cameras:
+ if not _visible(camera, context) or camera.data.type == 'PANO':
+ continue
+ image = snapshot['images'].get(camera.name)
+ geometry = _camera_geometry(camera, context, image)
+ # Previews should not cover the scene when looking through a camera.
+ if image and rv3d.view_perspective != 'CAMERA' and _in_scope(settings.images, camera) and 'image' in geometry:
+ fill = _shader('UNIFORM_COLOR')
+ fill.bind()
+ fill.uniform_float('color', (.065,.065,.065,1))
+ geometry['backing'].draw(fill)
+ pointer = image.as_pointer()
+ if pointer not in _textures:
+ _textures[pointer] = gpu.texture.from_image(image)
+ shader = _shader('IMAGE_COLOR_SCENE_LINEAR_TO_REC709_SRGB')
+ shader.bind()
+ shader.uniform_sampler('image', _textures[pointer])
+ shader.uniform_float('color', (1,1,1,1))
+ geometry['image'].draw(shader)
+ if settings.crops:
+ shader = _shader('POLYLINE_UNIFORM_COLOR')
+ shader.bind()
+ diagnostic = camera.get('_sg_debug_projection_color')
+ color = diagnostic or (theme.object_active if camera.select_get() else theme.space.text)
+ shader.uniform_float('color', tuple(color[:3])+(.95 if camera.select_get() or diagnostic else .5,))
+ shader.uniform_float('viewportSize', (context.region.width, context.region.height))
+ shader.uniform_float('lineWidth', 1.6 if camera.select_get() else 1.0)
+ geometry['border'].draw(shader)
+ except (ReferenceError, RuntimeError, ValueError, KeyError):
+ _record_error()
+ finally:
+ gpu.state.blend_set(blend)
+ gpu.state.depth_test_set(depth)
+ gpu.state.depth_mask_set(depth_mask)
+
+
+def _label_rect(x, y, width, height, occupied, bounds):
+ """Avoid intersecting badges; never pile multiple labels on a viewport edge."""
+ region_width, region_height = bounds
+ if x+width < 0 or x > region_width or y+height < 0 or y > region_height:
+ return None
+ x = max(8, min(x, region_width-width-8))
+ y = max(8, min(y, region_height-height-8))
+ for delta in [0, *[sign*i*(height+5) for i in range(1,9) for sign in (1,-1)]]:
+ candidate = (x,y+delta,width,height)
+ if candidate[1] < 8 or candidate[1]+height > region_height-8:
+ continue
+ if not any(x<px+pw+5 and x+width>px-5 and candidate[1]<py+ph+5
+ and candidate[1]+height>py-5 for px,py,pw,ph in occupied):
+ return candidate
+ return None
def _sg_draw_view_labels():
- """SpaceView3D POST_PIXEL callback: draws full camera prompt text
- (from ``scene.camera_prompts``) near each camera in the viewport."""
- context = bpy.context
- scene = context.scene
- region = context.region
- rv3d = context.region_data
- if region is None or rv3d is None:
+ context = _draw_context()
+ if context is None or context.region_data.view_perspective == 'CAMERA':
return
-
- # Respect Blender's overlay toggle
- space = context.space_data
- if space and hasattr(space, 'overlay') and not space.overlay.show_overlays:
+ settings = context.scene.sg_camera_display
+ if settings.labels == 'NONE':
return
-
- from bpy_extras.view3d_utils import location_3d_to_region_2d
-
- font_id = 0
- blf.size(font_id, 13)
-
- # Build a lookup of camera name -> prompt text
- prompt_lookup = {item.name: item.prompt for item in scene.camera_prompts
- if item.prompt}
-
- for obj in scene.objects:
- if obj.type != 'CAMERA':
- continue
- label = prompt_lookup.get(obj.name, '')
- if not label:
- continue
- co_2d = location_3d_to_region_2d(region, rv3d, obj.location)
- if co_2d is None:
- continue
- _oc = _sg_camera_overlay_color(obj)
- blf.color(font_id, _oc[0], _oc[1], _oc[2], 0.95)
- # Offset slightly below the camera marker
- blf.position(font_id, co_2d.x - blf.dimensions(font_id, label)[0] * 0.5,
- co_2d.y - 20, 0)
- gpu.state.blend_set('ALPHA')
- blf.draw(font_id, label)
-
- gpu.state.blend_set('NONE')
+ from ..ui.studio_widgets import Painter
+ scale = context.preferences.system.ui_scale
+ p = Painter(context.region, scale, 0)
+ p.width = context.region.width/scale
+ snapshot = _snapshot(context)
+ view = prompt_overlay.begin_draw(context, snapshot['cameras'])
+ prompts = {item.name: item for item in context.scene.camera_prompts}
+ theme = context.preferences.themes[0].view_3d
+ p.colors['camera_selected'] = tuple(theme.object_active)+(1,)
+ p.colors['camera_ink'] = (.08,.08,.08,1)
+ occupied = []
+ try:
+ # Prioritize the selected camera if labels need to be omitted in a crowd.
+ ordered = sorted(enumerate(snapshot['cameras']), key=lambda item:(
+ not (view.edit and view.edit['camera'] == item[1]),
+ item[1].as_pointer() not in view.expanded, not item[1].select_get()))
+ for index, camera in ordered:
+ if not _visible(camera, context) or not _in_scope(settings.labels, camera):
+ continue
+ center = camera.matrix_world.translation
+ clip = context.region_data.perspective_matrix @ center.to_4d()
+ if clip.w <= 0 or abs(clip.z) > clip.w:
+ continue
+ anchor = location_3d_to_region_2d(context.region, context.region_data, center)
+ if anchor is None:
+ continue
+ if not (0<=anchor.x<=context.region.width and 0<=anchor.y<=context.region.height):
+ continue
+ geometry = (_geometry.get(camera.as_pointer())
+ if camera.data.type != 'PANO' and (settings.crops or _in_scope(settings.images, camera)) else None)
+ if geometry and geometry['signature'][0] != tuple(v for row in camera.matrix_world for v in row):
+ geometry = None
+ if geometry:
+ projected = [location_3d_to_region_2d(context.region, context.region_data, v) for v in geometry['points']]
+ if all(v is not None for v in projected):
+ anchor = mathutils.Vector((sum(v.x for v in projected)/4, min(v.y for v in projected)))
+ x, y = anchor.x/scale, (context.region.height-anchor.y)/scale+6
+ title = str(camera.get('sg_view_label') or camera.name)
+ if title.endswith(' view'):
+ title = title[:-5].capitalize()
+ title = p.fit(title, 160)
+ number = f'{index+1:02}'
+ number_width = max(26,p.measure(number)+12)
+ scene_camera = settings.states and camera == context.scene.camera
+ generating = settings.states and camera == snapshot.get('generating')
+ prompt = prompts.get(camera.name)
+ expanded = camera.as_pointer() in view.expanded
+ width = number_width+p.measure(title)+16+(23 if scene_camera else 0)+(16 if generating else 0)+25
+ value = view.edit['buffer'].text if view.edit and view.edit['camera'] == camera else prompt.prompt if prompt else ''
+ field_width, field_height = prompt_overlay.prompt_height(p, value) if expanded else (0,0)
+ block_width, block_height = max(width, field_width), 25 + (field_height + 6 if expanded else 0)
+ block = _label_rect(x-block_width/2, y, block_width, block_height, occupied, (p.width, context.region.height/scale))
+ rect = (block[0]+(block_width-width)/2, block[1], width, 25) if block else None
+ if rect is None:
+ continue
+ occupied.append(block)
+ selected = camera.select_get()
+ bx,by,bw,bh = rect
+ if abs(by-y)>1:
+ p.line([(x,y-3),(max(bx+6,min(bx+bw-6,x)),by if by>y else by+bh)], 'muted', .7)
+ p.outline(*rect, 'selected' if selected else 'tooltip', 'camera_selected' if selected else 'section_border', 3)
+ p.rect(bx+1,by+1,number_width,bh-2,'camera_selected' if selected else 'raised',2,corners='LEFT')
+ p.text(number,bx+6,by+6,11,'camera_ink' if selected else 'text')
+ p.text(title,bx+number_width+8,by+6,11,'text')
+ icon_x = bx+number_width+8+p.measure(title)+5
+ if scene_camera:
+ p.icon('camera',icon_x,by+5,15,'secondary')
+ icon_x += 23
+ if generating:
+ p.icon('play',icon_x,by+6,12,'warning')
+ prompt_overlay.draw_icon(p, view, camera, (bx+bw-25,by,25,bh), bool(value.strip()),
+ 'camera_selected' if selected else 'section_border')
+ if expanded:
+ prompt_overlay.draw_field(p, view, camera, prompt, (block[0],by+bh+6,block_width,field_height))
+ except (ReferenceError, RuntimeError, ValueError, KeyError):
+ _record_error()
+ finally:
+ p.finish()
def _sg_ensure_crop_overlay():
"""Register the crop overlay draw handler if not already active."""
global _sg_crop_draw_handle
- if _sg_crop_draw_handle is None:
+ if _sg_crop_draw_handle is None and not bpy.app.background:
_sg_crop_draw_handle = bpy.types.SpaceView3D.draw_handler_add(
_sg_draw_crop_overlays, (), 'WINDOW', 'POST_VIEW')
@@ -165,7 +503,7 @@ def _sg_ensure_label_overlay():
"""Register the floating prompt-text label overlay if not already active."""
global _sg_label_draw_handle, _sg_labels_user_visible
_sg_labels_user_visible = True
- if _sg_label_draw_handle is None:
+ if _sg_label_draw_handle is None and not bpy.app.background:
_sg_label_draw_handle = bpy.types.SpaceView3D.draw_handler_add(
_sg_draw_view_labels, (), 'WINDOW', 'POST_PIXEL')
# Redraw all viewports so labels appear immediately
@@ -201,7 +539,7 @@ def _sg_restore_label_overlay():
"""Restore the label overlay only if the user had it enabled."""
if _sg_labels_user_visible:
global _sg_label_draw_handle
- if _sg_label_draw_handle is None:
+ if _sg_label_draw_handle is None and not bpy.app.background:
_sg_label_draw_handle = bpy.types.SpaceView3D.draw_handler_add(
_sg_draw_view_labels, (), 'WINDOW', 'POST_PIXEL')
for area in (bpy.context.screen.areas if bpy.context.screen else []):
diff --git a/stablegen/cameras/prompt_overlay.py b/stablegen/cameras/prompt_overlay.py
new file mode 100644
index 0000000..908b63c
--- /dev/null
+++ b/stablegen/cameras/prompt_overlay.py
@@ -0,0 +1,465 @@
+"""Viewport label prompt expansion and focused editing of saved view prompts."""
+from dataclasses import dataclass, field
+import logging
+import time
+
+import bpy
+import blf
+
+from ..ui.studio_text import TextBuffer
+from ..utils import sg_modal_active
+
+_views = {}
+_keymaps = []
+_registered = False
+_log = logging.getLogger(__name__)
+
+
+@dataclass
+class PromptView:
+ window: object
+ area: object
+ region: object
+ scene: object
+ expanded: set = field(default_factory=set)
+ targets: list = field(default_factory=list)
+ fields: dict = field(default_factory=dict)
+ scrolls: dict = field(default_factory=dict)
+ edit: dict | None = None
+ hover: int | None = None
+
+
+def view_key(context):
+ return (context.window.as_pointer(), context.area.as_pointer(),
+ context.region.as_pointer(), context.scene.as_pointer())
+
+
+def begin_draw(context, cameras):
+ key = view_key(context)
+ view = _views.get(key)
+ if view is None:
+ view = _views[key] = PromptView(context.window, context.area, context.region, context.scene)
+ view.targets.clear()
+ view.fields.clear()
+ view.expanded.intersection_update(c.as_pointer() for c in cameras)
+ if not context.space_data.show_gizmo:
+ view.hover = None
+ return view
+
+
+def clear():
+ _views.clear()
+
+
+def prune():
+ live = {(w.as_pointer(), a.as_pointer(), r.as_pointer(), w.scene.as_pointer())
+ for w in bpy.context.window_manager.windows for a in w.screen.areas if a.type == 'VIEW_3D'
+ for r in a.regions if r.type == 'WINDOW'}
+ for key in set(_views) - live:
+ del _views[key]
+
+
+def available(context):
+ return (context.area is not None and context.area.type == 'VIEW_3D'
+ and context.region is not None and context.region.type == 'WINDOW'
+ and context.region_data is not None and context.region_data.view_perspective != 'CAMERA'
+ and context.space_data.overlay.show_overlays
+ and context.scene.sg_camera_display.labels != 'NONE')
+
+
+def pointer(view, event):
+ scale = bpy.context.preferences.system.ui_scale
+ return ((event.mouse_x - view.region.x) / scale,
+ (view.region.height - (event.mouse_y - view.region.y)) / scale)
+
+
+def hit(view, point):
+ x, y = point
+ return next((t for t in reversed(view.targets)
+ if t['rect'][0] <= x <= t['rect'][0] + t['rect'][2]
+ and t['rect'][1] <= y <= t['rect'][1] + t['rect'][3]), None)
+
+
+def prompt_height(painter, value):
+ from ..ui.studio_text import wrap
+ from ..ui.studio_widgets import TEXT_LINE_HEIGHT, TEXT_PADDING
+ width = min(320, painter.width - 16)
+ rows = len(wrap(value, width - TEXT_PADDING * 2, painter.measure))
+ return width, min(118, max(67, rows * TEXT_LINE_HEIGHT + TEXT_PADDING * 2))
+
+
+class SG_GT_CameraPrompt(bpy.types.Gizmo):
+ """Native hover target; the existing overlay paints its visible control."""
+ bl_idname = 'SG_GT_camera_prompt'
+ __slots__ = ('rect', 'camera_key')
+
+ def setup(self):
+ self.rect = (0, 0, 0, 0)
+ self.camera_key = 0
+
+ def draw(self, context):
+ pass
+
+ def test_select(self, context, location):
+ scale = context.preferences.system.ui_scale
+ x, y = location[0] / scale, (context.region.height - location[1]) / scale
+ rx, ry, width, height = self.rect
+ return 0 if rx <= x <= rx + width and ry <= y <= ry + height else -1
+
+
+class SG_GGT_CameraPrompts(bpy.types.GizmoGroup):
+ bl_idname = 'SG_GGT_camera_prompts'
+ bl_label = 'Camera view prompts'
+ bl_space_type = 'VIEW_3D'
+ bl_region_type = 'WINDOW'
+ bl_options = {'PERSISTENT', 'SHOW_MODAL_ALL'}
+
+ @classmethod
+ def poll(cls, context):
+ return _registered and available(context) and not sg_modal_active(context)
+
+ def setup(self, context):
+ self.widgets = {}
+
+ def draw_prepare(self, context):
+ view = _views.get(view_key(context))
+ targets = {t['camera'].as_pointer(): t for t in view.targets if t['kind'] == 'toggle'} if view else {}
+ for key in set(self.widgets) - targets.keys():
+ self.gizmos.remove(self.widgets.pop(key))
+ for key, target in targets.items():
+ if key not in self.widgets:
+ widget = self.gizmos.new(SG_GT_CameraPrompt.bl_idname)
+ widget.target_set_operator('stablegen.camera_prompt_input')
+ widget.use_draw_modal = True
+ self.widgets[key] = widget
+ self.widgets[key].rect = target['rect']
+ self.widgets[key].camera_key = key
+ hovered = next((key for key, widget in self.widgets.items() if widget.is_highlight), None)
+ if view and view.hover != hovered:
+ view.hover = hovered
+ context.area.tag_redraw()
+
+
+def draw_icon(painter, view, camera, rect, has_prompt, border='section_border'):
+ x, y, width, height = rect
+ expanded = camera.as_pointer() in view.expanded
+ hovered = view.hover == camera.as_pointer()
+ fill = 'selected' if expanded else 'hover' if hovered else 'raised'
+ edge = 'accent' if expanded else 'hover_border' if hovered else border
+ painter.outline(x, y, width, height, fill, edge, 3, corners='RIGHT')
+ painter.rect(x, y, 1, height, edge)
+ # The filled page denotes saved wording; an empty page remains actionable.
+ tint = 'accent' if expanded else 'text'
+ u = 15 / 24
+ px, py = x + (width - 15) / 2, y + (height - 15) / 2
+ points = [(5, 3), (14, 3), (19, 8), (19, 21), (5, 21)]
+ fold = [(14, 3), (14, 8), (19, 8)]
+ if has_prompt:
+ painter.polygon([(px + a*u, py + b*u) for a, b in points], tint)
+ painter.polygon([(px + a*u, py + b*u) for a, b in fold], fill)
+ for top, line_width in ((11, 8), (15, 6)):
+ painter.rect(px + 8*u, py + top*u, line_width*u, 1.7*u, fill)
+ else:
+ painter.line([(px + a*u, py + b*u) for a, b in [*points, points[0]]], tint, 1.2)
+ painter.line([(px + a*u, py + b*u) for a, b in fold], tint, 1.2)
+ view.targets.append(dict(kind='toggle', camera=camera, rect=rect))
+
+
+def draw_field(painter, view, camera, prompt, rect):
+ key = camera.as_pointer()
+ edit = view.edit if view.edit and view.edit['camera'] == camera else None
+ value = edit['buffer'].text if edit else prompt.prompt if prompt else ''
+ lines, scroll = painter.text_field(str(key), rect, value, ('edit', None),
+ enabled=not sg_modal_active(bpy.context), multiline=True,
+ editing=edit['buffer'] if edit else None, scroll=view.scrolls.get(key, 0),
+ follow_caret=edit is not None and edit['follow_caret'])
+ view.scrolls[key] = scroll
+ view.fields[key] = dict(rect=rect, lines=lines, scroll=scroll)
+ view.targets.append(dict(kind='edit', camera=camera, rect=rect))
+ if not value and not edit:
+ painter.text('View prompt', rect[0] + 8, rect[1] + 8, 11, 'muted')
+
+
+def commit(view, cancel=False):
+ edit, view.edit = view.edit, None
+ if not edit or cancel:
+ return False
+ try:
+ camera, prompt = edit['camera'], edit['prompt']
+ # Cancel safely if a camera or its prompt was removed/replaced externally.
+ if view.scene.objects.get(camera.name) != camera:
+ return False
+ value = edit['buffer'].text
+ if prompt is None:
+ if (camera.name != edit['camera_name'] or view.scene.camera_prompts.get(camera.name) is not None
+ or not value.strip()):
+ return False
+ prompt = view.scene.camera_prompts.add()
+ prompt.name = camera.name
+ elif (camera.name != prompt.name or view.scene.camera_prompts.get(camera.name) != prompt
+ or prompt.prompt != edit['original']):
+ return False
+ if prompt.prompt == value:
+ return False
+ prompt.prompt = value
+ try:
+ with bpy.context.temp_override(window=view.window, area=view.area, region=view.region):
+ bpy.ops.ed.undo_push(message='Edit camera view prompt')
+ except RuntimeError:
+ _log.debug('Undo push unavailable for camera prompt edit', exc_info=True)
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ return True
+ except (ReferenceError, RuntimeError):
+ _log.debug('Camera prompt editor lost its scene context', exc_info=True)
+ return False
+
+
+class SG_OT_CameraPromptInput(bpy.types.Operator):
+ bl_idname = 'stablegen.camera_prompt_input'
+ bl_label = 'Edit Camera View Prompt'
+ bl_description = 'Show or hide the camera view prompt below its label; click the field to add or edit wording'
+ bl_options = {'INTERNAL'}
+
+ @classmethod
+ def poll(cls, context):
+ return _registered and available(context) and not sg_modal_active(context)
+
+ def invoke(self, context, event):
+ view = _views.get(view_key(context))
+ target = hit(view, pointer(view, event)) if view else None
+ if not target:
+ return {'PASS_THROUGH'}
+ self.view, self.key = view, view_key(context)
+ self.cursor_active = False
+ self.selecting = False
+ self.exit_timer = None
+ self.exit_deadline = 0
+ self.activate(context, target, event)
+ context.window_manager.modal_handler_add(self)
+ return {'RUNNING_MODAL'}
+
+ def activate(self, context, target, event):
+ view, camera = self.view, target['camera']
+ key = camera.as_pointer()
+ if target['kind'] == 'toggle':
+ commit(view)
+ if key in view.expanded:
+ view.expanded.remove(key)
+ else:
+ view.expanded.add(key)
+ elif not sg_modal_active(context):
+ if not view.edit or view.edit['camera'] != camera:
+ commit(view)
+ prompt = view.scene.camera_prompts.get(camera.name)
+ value = prompt.prompt if prompt else ''
+ view.edit = dict(camera=camera, camera_name=camera.name, prompt=prompt, original=value,
+ buffer=TextBuffer(value), follow_caret=False)
+ self.place_caret(pointer(view, event), extend=event.shift)
+ self.selecting = True
+ self.update_cursor(pointer(view, event))
+ view.area.tag_redraw()
+
+ def update_hover(self, point=None):
+ target = hit(self.view, point) if point is not None else None
+ hovered = target['camera'].as_pointer() if target and target['kind'] == 'toggle' else None
+ if self.view.hover != hovered:
+ self.view.hover = hovered
+ try:
+ self.view.area.tag_redraw()
+ except ReferenceError:
+ pass
+
+ def place_caret(self, point, extend=False):
+ from ..ui.studio_widgets import TEXT_PADDING, TEXT_LINE_HEIGHT, font_size
+ edit = self.view.edit
+ field = self.view.fields.get(edit['camera'].as_pointer()) if edit else None
+ if not field or not field['lines']:
+ return
+ x, y = point
+ rx, ry, width, height = field['rect']
+ row = max(0, min(len(field['lines']) - 1,
+ int((y - ry - TEXT_PADDING) / TEXT_LINE_HEIGHT) + field['scroll']))
+ start, end, line = field['lines'][row]
+ scale = bpy.context.preferences.system.ui_scale
+ blf.size(0, font_size() * scale)
+ distances = [blf.dimensions(0, line[:i])[0] / scale for i in range(len(line) + 1)]
+ caret = start + min(range(len(distances)), key=lambda i: abs(distances[i] - (x - rx - TEXT_PADDING)))
+ edit['buffer'].move(caret, extend)
+ edit['follow_caret'] = True
+
+ def update_cursor(self, point=None):
+ target = hit(self.view, point) if point is not None else None
+ active = bool(self.view.edit and target and target['kind'] == 'edit')
+ try:
+ if active and not self.cursor_active:
+ self.view.window.cursor_modal_set('TEXT')
+ elif self.cursor_active and not active:
+ self.view.window.cursor_modal_restore()
+ except ReferenceError:
+ active = False
+ self.cursor_active = active
+
+ def finish(self, cancel=False):
+ commit(self.view, cancel)
+ self.update_hover()
+ self.update_cursor()
+ try:
+ self.view.area.tag_redraw()
+ except ReferenceError:
+ pass
+
+ def defer_finish(self, context):
+ self.finish()
+ # Finishing on an outside mouse press can suppress Blender's derived
+ # CLICK event even with PASS_THROUGH. Release input ownership first and
+ # finish on our own timer, leaving native selection/navigation intact.
+ self.exit_timer = context.window_manager.event_timer_add(.05, window=self.view.window)
+ self.exit_deadline = time.monotonic() + .05
+ return {'PASS_THROUGH'}
+
+ def remove_timer(self, context):
+ if self.exit_timer is not None:
+ context.window_manager.event_timer_remove(self.exit_timer)
+ self.exit_timer = None
+
+ def modal(self, context, event):
+ view = self.view
+ try:
+ if self.exit_timer is not None:
+ if event.type == 'TIMER' and time.monotonic() >= self.exit_deadline:
+ self.remove_timer(context)
+ return {'FINISHED'}
+ return {'PASS_THROUGH'}
+ stale = _views.get(self.key) is not view or not _registered
+ if (stale or not available(context) or view_key(context) != self.key or sg_modal_active(context)):
+ self.finish(cancel=stale or context.scene != view.scene or sg_modal_active(context))
+ return {'FINISHED', 'PASS_THROUGH'}
+ point = pointer(view, event)
+ target = hit(view, point)
+ key, pressed = event.type, event.value == 'PRESS'
+ if key == 'WINDOW_DEACTIVATE':
+ self.finish()
+ return {'FINISHED', 'PASS_THROUGH'}
+ if key in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE'}:
+ self.update_hover(point)
+ if self.selecting and view.edit:
+ self.place_caret(point, extend=True)
+ view.area.tag_redraw()
+ self.update_cursor(point)
+ return {'RUNNING_MODAL'}
+ self.update_cursor(point)
+ return {'RUNNING_MODAL', 'PASS_THROUGH'}
+ if key == 'LEFTMOUSE' and event.value == 'RELEASE':
+ self.selecting = False
+ if view.edit:
+ return {'RUNNING_MODAL'}
+ self.finish()
+ return {'FINISHED'}
+ if key == 'LEFTMOUSE' and event.value in {'PRESS', 'DOUBLE_CLICK'}:
+ if target:
+ self.activate(context, target, event)
+ return {'RUNNING_MODAL'}
+ return self.defer_finish(context)
+ if key in {'MIDDLEMOUSE', 'RIGHTMOUSE'} and pressed:
+ return self.defer_finish(context)
+ if key in {'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'WHEELINMOUSE', 'WHEELOUTMOUSE', 'TRACKPADPAN'}:
+ if view.edit and target and target['kind'] == 'edit' and target['camera'] == view.edit['camera']:
+ camera_key = view.edit['camera'].as_pointer()
+ change = (-2 if key in {'WHEELUPMOUSE', 'WHEELINMOUSE'} else 2)
+ if key == 'TRACKPADPAN':
+ change = round((event.mouse_prev_y - event.mouse_y) / 17)
+ view.scrolls[camera_key] = max(0, view.scrolls.get(camera_key, 0) + change)
+ view.edit['follow_caret'] = False
+ view.area.tag_redraw()
+ return {'RUNNING_MODAL'}
+ return {'PASS_THROUGH'}
+ if not view.edit or not pressed:
+ return {'PASS_THROUGH'}
+ buffer, ctrl = view.edit['buffer'], event.ctrl or event.oskey
+ if key == 'ESC':
+ self.finish(cancel=True)
+ return {'FINISHED'}
+ if key in {'RET', 'NUMPAD_ENTER'}:
+ if ctrl:
+ self.finish()
+ return {'FINISHED'}
+ buffer.replace('\n')
+ elif ctrl and key == 'A':
+ buffer.anchor, buffer.caret = 0, len(buffer.text)
+ elif ctrl and key in {'C', 'X'}:
+ start, end = buffer.selection
+ if start != end:
+ context.window_manager.clipboard = buffer.text[start:end]
+ if key == 'X':
+ buffer.replace('')
+ elif ctrl and key == 'V':
+ buffer.replace(context.window_manager.clipboard.replace('\r\n', '\n').replace('\r', '\n'))
+ elif ctrl and key in {'Z', 'Y'}:
+ buffer.undo(redo=key == 'Y' or event.shift)
+ elif key in {'LEFT_ARROW', 'RIGHT_ARROW'}:
+ direction = -1 if key == 'LEFT_ARROW' else 1
+ start, end = buffer.selection
+ destination = ((start if direction < 0 else end) if start != end and not event.shift
+ else buffer.word(direction) if ctrl else buffer.caret + direction)
+ buffer.move(destination, event.shift)
+ elif key in {'HOME', 'END'}:
+ if ctrl:
+ destination = 0 if key == 'HOME' else len(buffer.text)
+ else:
+ destination = (buffer.text.rfind('\n', 0, buffer.caret) + 1 if key == 'HOME'
+ else buffer.text.find('\n', buffer.caret))
+ if destination < 0:
+ destination = len(buffer.text)
+ buffer.move(destination, event.shift)
+ elif key in {'UP_ARROW', 'DOWN_ARROW'}:
+ lines = view.fields[view.edit['camera'].as_pointer()]['lines']
+ row = next((i for i, (a, b, _) in enumerate(lines) if a <= buffer.caret <= b), len(lines) - 1)
+ column = buffer.caret - lines[row][0]
+ row = max(0, min(len(lines) - 1, row + (-1 if key == 'UP_ARROW' else 1)))
+ buffer.move(min(lines[row][1], lines[row][0] + column), event.shift)
+ elif key in {'BACK_SPACE', 'DEL'}:
+ buffer.delete(backward=key == 'BACK_SPACE', word=ctrl)
+ elif key == 'TAB':
+ self.finish()
+ return {'FINISHED'}
+ elif ctrl and key == 'S':
+ return self.defer_finish(context)
+ elif getattr(event, 'unicode', '') and not ctrl and not event.alt:
+ buffer.replace(event.unicode)
+ else:
+ # Keyboard shortcuts must not mutate the scene behind a focused field.
+ return {'RUNNING_MODAL'}
+ view.edit['follow_caret'] = True
+ view.area.tag_redraw()
+ return {'RUNNING_MODAL'}
+ except (ReferenceError, RuntimeError, KeyError):
+ self.finish(cancel=True)
+ return {'FINISHED', 'PASS_THROUGH'}
+
+ def cancel(self, context):
+ if hasattr(self, 'view'):
+ self.remove_timer(context)
+ self.finish(cancel=True)
+
+
+def register():
+ global _registered
+ _registered = True
+ if not bpy.app.background:
+ config = bpy.context.window_manager.keyconfigs.addon
+ if config:
+ keymap = config.keymaps.new(name='3D View', space_type='VIEW_3D', region_type='WINDOW')
+ item = keymap.keymap_items.new(SG_OT_CameraPromptInput.bl_idname, 'LEFTMOUSE', 'PRESS', any=True, head=True)
+ _keymaps.append((keymap, item))
+
+
+def unregister():
+ global _registered
+ _registered = False
+ for keymap, item in _keymaps:
+ keymap.keymap_items.remove(item)
+ _keymaps.clear()
+ clear()
diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.py
index fd22aae..68165bd 100644
--- a/stablegen/core/preferences.py
+++ b/stablegen/core/preferences.py
@@ -118,7 +118,7 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
overlay_color: bpy.props.FloatVectorProperty(
name="Overlay Color",
- description="Color used for the camera aspect-ratio crop rectangle and floating view labels in the viewport",
+ description="Color of the scene-camera indicator. Camera selection follows Blender’s theme; diagnostic camera colors take precedence",
subtype='COLOR',
size=3,
min=0.0, max=1.0,
diff --git a/stablegen/ui/studio_model.py b/stablegen/ui/studio_model.py
index dd2b0af..85856a8 100644
--- a/stablegen/ui/studio_model.py
+++ b/stablegen/ui/studio_model.py
@@ -139,44 +139,6 @@ def action(document, *names):
def projected_images(context):
- """Read actual projection textures, honoring the saved view plan if present.
-
- No render, file recovery, image loading or material change is performed here.
- """
- from ..texturing.view_plan import generation_cameras, order_cameras, order_cameras_from_manifest
- scene = context.scene
- objects = context.selected_objects if scene.texture_objects == 'selected' else context.view_layer.objects
- textures = {}
- latest = -1
- for obj in objects:
- if obj.type != 'MESH' or obj.hide_get():
- continue
- for slot in obj.material_slots:
- if not slot.material or not slot.material.use_nodes:
- continue
- for node in slot.material.node_tree.nodes:
- if node.type != 'TEX_IMAGE' or node.image is None:
- continue
- parts = node.label.split('-')
- if len(parts) != 2 or not all(part.isdigit() for part in parts):
- continue
- index, material = map(int, parts)
- if material > latest:
- latest, textures = material, {}
- if material == latest:
- textures.setdefault(index, node.image)
- if not textures:
- return {}
- custom = [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ()
- cameras = order_cameras(generation_cameras(scene), custom)
- for image in textures.values():
- folder = Path(bpy.path.abspath(image.filepath, library=image.library)).parent
- if folder.name.lower() != 'generated':
- continue
- try:
- manifest = json.loads((folder.parent / 'view_plan.json').read_text(encoding='utf8'))
- cameras = order_cameras_from_manifest(cameras, manifest)
- break
- except (OSError, ValueError, TypeError):
- continue
- return {camera.name: textures[i] for i, camera in enumerate(cameras) if i in textures}
+ """Read existing projection textures using their saved camera identities."""
+ from ..cameras.images import projected_images as resolve
+ return resolve(context)