Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
show the generated views on a baked scene's camera cards
sakalond8a9bc7b9b1ee
diff --git a/stablegen/cameras/images.py b/stablegen/cameras/images.pyindex 4e33723..cdb823d 100644--- a/stablegen/cameras/images.py+++ b/stablegen/cameras/images.py@@ -1,5 +1,6 @@"""Read existing projection images without loading files or changing materials."""import json+import osimport refrom pathlib import Path@@ -9,6 +10,10 @@ from ..texturing.view_plan import generation_cameras, order_cameras# Masked Edit output folders: '<timestamp>-masked-<hex>' (see masked_edit.SG_OT_MaskedEdit)._MASKED_RUN = re.compile(r'-masked-[0-9a-f]+$', re.IGNORECASE)+# A run's generated views: generated_image<view>-<material>-0001.png (utils.get_file_path)+_GENERATED_FILE = re.compile(r'generated_image(\d+)-(\d+)(?:-\d+)?\.png$', re.IGNORECASE)+_run_folders = {} # (timestamp, .blend, image count, output folder) -> the run folder, or None+_run_views = {} # run folder -> (view_plan.json and generated/ mtimes, {view id or name: file})def is_masked_edit_layer(node):@@ -101,3 +106,79 @@ def projected_images(context, *, objects=None, materials=None, manifests=None):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}+++def _run_folder(context):+ """The folder of the scene's run (named after its output timestamp) holding its view plan: where StableGen+ writes it, or where an image the file uses (a bake, a projected view) came from after the .blend was renamed."""+ scene = context.scene+ stamp = scene.output_timestamp+ if not stamp:+ return None+ from ..core import get_addon_prefs+ prefs = get_addon_prefs(context)+ output = bpy.path.abspath(prefs.output_dir) if prefs is not None and prefs.output_dir else ''+ key = (stamp, bpy.data.filepath, len(bpy.data.images), output)+ if key not in _run_folders:+ candidates = []+ if output:+ stem = Path(bpy.data.filepath).stem or scene.name+ candidates.append(Path(output) / stem / stamp)+ for image in bpy.data.images:+ if image.source != 'FILE' or not image.filepath:+ continue+ path = Path(bpy.path.abspath(image.filepath, library=image.library))+ candidates.extend(parent for parent in path.parents if parent.name == stamp)+ folder = None+ for candidate in dict.fromkeys(candidates):+ try:+ if (candidate / 'view_plan.json').is_file():+ folder = candidate+ break+ except OSError:+ continue+ _run_folders[key] = folder+ return _run_folders[key]+++def generated_files(context):+ """Each scene camera's generated image file in the scene's own run ({camera name: path}). The cards show these+ when the camera's view is not in a visible material, as after Bake Textures, whose materials hold the bake."""+ folder = _run_folder(context)+ if folder is None:+ return {}+ plan, generated = folder / 'view_plan.json', folder / 'generated'+ try:+ stamp = (plan.stat().st_mtime, generated.stat().st_mtime)+ except OSError:+ return {}+ cached = _run_views.get(folder)+ if cached is None or cached[0] != stamp:+ files = {} # view index -> the file of its lowest material id+ try:+ names = [entry.name for entry in os.scandir(generated) if entry.is_file()]+ manifest = json.loads(plan.read_text(encoding='utf8'))+ except (OSError, ValueError):+ return {}+ for name in names:+ match = _GENERATED_FILE.fullmatch(name)+ if match:+ index, material = int(match.group(1)), int(match.group(2))+ if index not in files or material < files[index][0]:+ files[index] = (material, str(generated / name))+ views = {}+ for record in manifest.get('views', []) if isinstance(manifest, dict) else ():+ index = record.get('index') if isinstance(record, dict) else None+ index = int(index) if isinstance(index, str) and index.isdigit() else index+ if isinstance(index, int) and index in files:+ for key in (record.get('view_id'), record.get('name')):+ if key:+ views.setdefault(str(key), files[index][1])+ cached = _run_views[folder] = (stamp, views)+ views = cached[1]+ result = {}+ for camera in generation_cameras(context.scene):+ path = views.get(str(camera.get('sg_view_uuid') or '')) or views.get(camera.name)+ if path:+ result[camera.name] = path+ return resultdiff --git a/stablegen/ui/studio.py b/stablegen/ui/studio.pyindex 80b4de3..be72c00 100644--- a/stablegen/ui/studio.py+++ b/stablegen/ui/studio.py@@ -28,7 +28,7 @@ from . import studio_setup as setup_pagefrom .presentation import Layout, Control, Section, STRUCTURAL_PROPERTIES, TOOL_SECTIONSfrom .studio_text import TextBuffer, wrapfrom .studio_widgets import (Painter, FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP,- TEXT_LINE_HEIGHT, TEXT_PADDING, color, font_size)+ TEXT_LINE_HEIGHT, TEXT_PADDING, color, font_size, image_size)from .presets import (PRESETS, PRESET_MODEL_NAMES, PRESET_VARIANTS, PRESET_WORKFLOWS,preset_label as _preset_label, preset_model as _preset_model,preset_workflow as _preset_workflow, strip_word as _strip)@@ -151,9 +151,10 @@ def _undo(message):def _view_aspect(scene, camera, image):- """A camera's view shape: its generated image's, else its resolution's."""- if image is not None and image.size[0] > 0 and image.size[1] > 0:- return image.size[0] / image.size[1]+ """A camera's view shape: its generated image's (a Blender image or a file), else its resolution's."""+ width, height = image_size(image) if image is not None else (0, 0)+ if width > 0 and height > 0:+ return width / heightfrom ..cameras.geometry import _get_camera_resolutionwidth, height = _get_camera_resolution(camera, scene)return width / max(1, height)@@ -2565,7 +2566,8 @@ class StudioSession:index = next((i for i, c in enumerate(cameras) if c.name == camera.name), 0)margin = 24p.text(f'{index + 1:02} · {camera.name}', left + margin, top + 14, 13, 'text', right - left - 2 * margin)- note = f'{image.size[0]} × {image.size[1]} · click or Esc to close'+ image_width, image_height = image_size(image)+ note = f'{image_width} × {image_height} · click or Esc to close'p.text(note, right - margin - p.measure(note, 10), top + 17, 10, 'muted')p.image(image, (left + margin, top + 40, right - left - 2 * margin, bottom - top - 40 - margin), 12)finally:diff --git a/stablegen/ui/studio_model.py b/stablegen/ui/studio_model.pyindex 9c298b7..a62c276 100644--- a/stablegen/ui/studio_model.py+++ b/stablegen/ui/studio_model.py@@ -207,6 +207,10 @@ def action(document, *names):def projected_images(context):- """Read existing projection textures using their saved camera identities."""- from ..cameras.images import projected_images as resolve- return resolve(context)+ """Each camera's generated view: the image its projection material shows (by its saved camera identity), else+ the image file in the scene's own run folder, as for a baked scene (a file path; the cards draw either)."""+ from ..cameras.images import generated_files, projected_images as resolve+ images = resolve(context)+ for name, path in generated_files(context).items():+ images.setdefault(name, path)+ return imagesdiff --git a/stablegen/ui/studio_widgets.py b/stablegen/ui/studio_widgets.pyindex f48e15f..b5b62a7 100644--- a/stablegen/ui/studio_widgets.py+++ b/stablegen/ui/studio_widgets.py@@ -218,6 +218,34 @@ def _file_key(path):return os.path.normcase(os.path.abspath(path)), stat.st_mtime_ns, stat.st_size+_file_sizes = {} # file path -> (its _file_key, (width, height))+++def image_size(image):+ """(width, height) of a Blender image or an image file: a PNG's header, else the decoded file."""+ if not isinstance(image, str):+ return tuple(image.size)+ key = _file_key(image)+ if key is None:+ return 0, 0+ cached = _file_sizes.get(key[0])+ if cached is None or cached[0] != key:+ size = (0, 0)+ try:+ with open(image, 'rb') as handle:+ head = handle.read(24)+ if head[:8] == b'\x89PNG\r\n\x1a\n':+ size = int.from_bytes(head[16:20], 'big'), int.from_bytes(head[20:24], 'big')+ except OSError:+ pass+ if size == (0, 0):+ source = _file_source(image)+ if source is not None:+ size = source.shape[1], source.shape[0]+ cached = _file_sizes[key[0]] = (key, size)+ return cached[1]++def _file_source(path, cap=THUMBNAIL_SOURCE):"""An image file as _thumbnail_source gives a Blender image (premultiplied RGBA, bottom row first), readstraight from the file: drawing may not load image datablocks. None when it can't be read."""