Skip to content

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

add marigold v2 albedo and normal extraction

sakalond78578db87660
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 88ca5f7..3182b34 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -1832,9 +1832,23 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
('marigold', "Marigold IID (Flat Albedo)", "True albedo from Marigold IID-Appearance \u2014 removes all lighting but may lose texture detail"),
('delight', "StableDelight (Delighted)", "Specular-removed image via StableDelight \u2014 preserves diffuse shading and texture detail, only strips highlights"),
('lighting', "Marigold IID-Lighting (Vibrant)", "Albedo from Marigold IID-Lighting \u2014 tends to produce more vibrant, saturated colours than IID-Appearance"),
+ ('marigold_v2', "Marigold V2 (Sharp Albedo)", "Albedo from Marigold V2 at up to the Marigold V2 resolution \u2014 removes lighting while keeping fine texture detail and colour. Needs the Marigold V2 models (about 24 GB with normals) and a September 2026 or newer ComfyUI. Roughness and metallic still come from Marigold IID-Appearance"),
],
default='marigold', update=update_parameters,
)
+ bpy.types.Scene.pbr_normal_model = bpy.props.EnumProperty(
+ name="Normal Model", description="Model used to estimate the normal map",
+ items=[
+ ('marigold', "Marigold Normals", "Marigold normals (LCM), processed at the Inference resolution"),
+ ('marigold_v2', "Marigold V2", "Marigold V2 normals at up to the Marigold V2 resolution \u2014 sharper surface detail. Needs the Marigold V2 models and a September 2026 or newer ComfyUI"),
+ ],
+ default='marigold', update=update_parameters,
+ )
+ bpy.types.Scene.pbr_v2_max_resolution = bpy.props.IntProperty(
+ name="Marigold V2 resolution (px)",
+ description="Longest edge Marigold V2 processes at. Images are processed at their own size within 1024 px and this limit. Higher values keep more detail but need more memory and time",
+ default=2048, min=1024, max=4096, step=64, update=update_parameters
+ )
bpy.types.Scene.pbr_map_albedo = bpy.props.BoolProperty(
name="Albedo", description="Extract a lighting-reduced base-color map using the selected method. Enable Use as material base color separately to assign it to the projected material.",
default=True, update=update_parameters
@@ -2219,6 +2233,7 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'pbr_emission_value_min', 'pbr_emission_bloom',
'pbr_emission_strength',
'pbr_normal_strength', 'pbr_delight_strength',
+ 'pbr_normal_model', 'pbr_v2_max_resolution',
'pbr_use_native_resolution', 'pbr_tiling',
'pbr_tile_albedo', 'pbr_tile_material', 'pbr_tile_normal', 'pbr_tile_height',
'pbr_tile_emission', 'pbr_tile_grid', 'pbr_tile_inference', 'pbr_tile_superres',
diff --git a/stablegen/texturing/pbr.py b/stablegen/texturing/pbr.py
index 42c47b2..faa7e42 100644
--- a/stablegen/texturing/pbr.py
+++ b/stablegen/texturing/pbr.py
@@ -80,9 +80,12 @@ class _PBRMixin:
settings = {}
+ # Marigold V2 ignores the v1 inference, step and tiling settings and has its own resolution.
+ v2_settings = {'model': 'marigold_v2',
+ 'v2_resolution': getattr(scene, 'pbr_v2_max_resolution', 2048)}
+
settings['albedo'] = {
- **common,
- **tiling_dict(tile_albedo),
+ **(v2_settings if albedo_source == 'marigold_v2' else {**common, **tiling_dict(tile_albedo)}),
'source': albedo_source,
'delight_strength': getattr(scene, 'pbr_delight_strength', 1.0) if albedo_source == 'delight' else None,
'auto_saturation': getattr(scene, 'pbr_albedo_auto_saturation', False),
@@ -96,10 +99,13 @@ class _PBRMixin:
**common,
**tiling_dict(tile_material),
}
- settings['normal'] = {
- **common,
- **tiling_dict(tile_normal),
- }
+ if getattr(scene, 'pbr_normal_model', 'marigold') == 'marigold_v2':
+ settings['normal'] = dict(v2_settings)
+ else:
+ settings['normal'] = {
+ **common,
+ **tiling_dict(tile_normal),
+ }
settings['height'] = {
**common,
**tiling_dict(tile_height),
@@ -854,6 +860,9 @@ class _PBRMixin:
use_delight = (want_albedo and albedo_source == 'delight')
use_lighting_albedo = (want_albedo and albedo_source == 'lighting')
+ use_v2_albedo = (want_albedo and albedo_source == 'marigold_v2')
+ use_v2_normals = (want_normal
+ and getattr(scene, 'pbr_normal_model', 'marigold') == 'marigold_v2')
# ── Determine which Marigold models to run ────────────────────
# When all_missing is set (selective rerun), only models whose
@@ -863,7 +872,7 @@ class _PBRMixin:
or want_roughness
or want_metallic
)
- need_normals = want_normal
+ need_normals = want_normal and not use_v2_normals
need_height = want_height
# IID-Lighting is needed for 'residual' emission OR 'lighting' albedo
need_iid_lighting = (
@@ -880,6 +889,12 @@ class _PBRMixin:
need_iid_lighting = need_iid_lighting and bool(
all_missing & {'emission', 'albedo'})
use_delight = use_delight and 'albedo' in all_missing
+ use_v2_albedo = use_v2_albedo and 'albedo' in all_missing
+ use_v2_normals = use_v2_normals and 'normal' in all_missing
+
+ # Albedo produced by a separate pass: IID-Appearance then only supplies
+ # roughness and metallic, and its albedo output is discarded.
+ external_albedo = (want_albedo and albedo_source in ('delight', 'marigold_v2'))
models_to_run = []
if need_appearance:
@@ -910,6 +925,8 @@ class _PBRMixin:
total_model_steps = (len(models_to_run)
+ (1 if use_delight else 0)
+ + (1 if use_v2_albedo else 0)
+ + (1 if use_v2_normals else 0)
+ extra_emission_steps)
if total_model_steps == 0:
print("[StableGen] No PBR maps enabled, skipping decomposition")
@@ -939,7 +956,7 @@ class _PBRMixin:
custom_tile_height = False
custom_tile_emission = False
# Whether IID-Appearance is the albedo provider
- appearance_provides_albedo = (not use_delight
+ appearance_provides_albedo = (not external_albedo
and not use_lighting_albedo)
if tiling_mode == 'selective':
@@ -1055,6 +1072,56 @@ class _PBRMixin:
except Exception as err:
print(f"[StableGen] Failed to save delight albedo: {err}")
+ # ── Marigold V2 passes (all cameras per map) ──────────────────
+ v2_tasks = ([('albedo', 'albedo')] if use_v2_albedo else []) + \
+ ([('normals', 'normal')] if use_v2_normals else [])
+ for task, map_name in v2_tasks:
+ model_step += 1
+ self._pbr_step = model_step
+ print(f"[StableGen] Model {model_step}/{total_model_steps}: Marigold V2 {task}")
+ for ci, cam_idx in enumerate(cam_ids):
+ if per_camera_missing and cam_idx in per_camera_missing:
+ if map_name not in per_camera_missing[cam_idx]:
+ print(f"[StableGen] Camera {cam_idx}: {map_name} exists, skipping Marigold V2")
+ continue
+ self._pbr_cam = ci
+ self._stage = f"PBR: Marigold V2 {task} (cam {ci+1}/{num_cams})"
+ self._progress = 0
+ print(f"[StableGen] Camera {cam_idx} ({ci+1}/{num_cams})…")
+ result = self.workflow_manager.generate_marigold_v2_map(
+ context, camera_images[cam_idx], task)
+ if isinstance(result, dict) and "error" in result:
+ print(f"[StableGen] Marigold V2 error: {result['error']}")
+ self._error = f"Marigold V2 failed: {result['error']}"
+ return
+ if map_name == 'normal':
+ converted = self._convert_normals_cam_to_world(result, cam_idx)
+ if converted is not None:
+ result = converted
+ pbr_path = get_file_path(
+ context, "pbr", subtype=map_name,
+ camera_id=cam_idx, material_id=self._material_id)
+ try:
+ if map_name == 'albedo':
+ self._save_raw_copy(context, "albedo", cam_idx, result)
+ with open(pbr_path, 'wb') as f:
+ f.write(result)
+ self._pbr_maps[cam_idx][map_name] = pbr_path
+ print(f"[StableGen] Saved {map_name} (Marigold V2) → "
+ f"{os.path.basename(pbr_path)}")
+ except Exception as err:
+ print(f"[StableGen] Failed to save Marigold V2 {map_name}: {err}")
+ if v2_tasks and models_to_run:
+ # The Qwen-Image-Edit base stays cached in ComfyUI; the Marigold v1
+ # custom nodes load their own pipelines and need the memory back.
+ try:
+ server_address = context.preferences.addons[
+ _ADDON_PKG].preferences.server_address
+ self.workflow_manager._flush_comfyui_vram(
+ server_address, retries=1, label="after Marigold V2")
+ except Exception as e:
+ print(f"[StableGen] VRAM flush after Marigold V2 failed (non-fatal): {e}")
+
# ── Marigold model passes (all cameras per model) ─────────────
for model_name, map_names in models_to_run:
model_step += 1
@@ -1094,7 +1161,7 @@ class _PBRMixin:
if tiling_mode == 'selective':
dual_run_iid = (
- should_tile and is_iid and not use_delight
+ should_tile and is_iid and not external_albedo
)
dual_run_lighting = (
should_tile and is_iid_lighting
@@ -1215,7 +1282,7 @@ class _PBRMixin:
context, result, map_names, cam_idx,
want_roughness=want_roughness,
want_metallic=want_metallic,
- use_delight=use_delight,
+ use_delight=external_albedo,
use_lighting_albedo=use_lighting_albedo)
# ── Post-Marigold emission passes ─────────────────────────────
diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.py
index 2e8122d..1b4bc64 100644
--- a/stablegen/texturing/workflows.py
+++ b/stablegen/texturing/workflows.py
@@ -2062,6 +2062,165 @@ class _TexturingWorkflowMixin:
# StableDelight returns a single image
return delight_images[0] if delight_images else {"error": "StableDelight returned empty"}
+ # Marigold V2 (huawei-bayerlab, Apache-2.0): single-step LoRAs on Qwen-Image-Edit-2509, run by
+ # ComfyUI core. File names follow the Comfy-Org repack; they may sit in subfolders.
+ MARIGOLD_V2_REPO = "https://huggingface.co/Comfy-Org/marigold-v2-0"
+ MARIGOLD_V2_BASE = "qwen_image_edit_2509_int8_convrot.safetensors"
+
+ def _resolve_comfy_model(self, server_address, folder, basename=None, match=None):
+ """Return the server-side name of a model file in a ComfyUI model folder.
+
+ Looks for an exact *basename* (in any subfolder) or, failing that, the
+ first file whose lower-cased name passes *match*. Returns ``None``
+ when nothing fits or the folder cannot be listed.
+ """
+ try:
+ resp = urllib.request.urlopen(
+ f"http://{server_address}/models/{folder}", timeout=get_timeout('api'))
+ names = json.loads(resp.read())
+ except Exception:
+ return None
+ flat = lambda n: n.replace('\\', '/').rsplit('/', 1)[-1].lower()
+ if basename:
+ for name in names:
+ if flat(name) == basename.lower():
+ return name
+ if match:
+ for name in names:
+ if match(flat(name)):
+ return name
+ return None
+
+ def generate_marigold_v2_map(self, context, input_image_path, task):
+ """Run Marigold V2 on a generated image and return the map as PNG bytes.
+
+ *task* is ``'albedo'`` (sRGB albedo) or ``'normals'`` (camera-space
+ normals, X right / Y up / Z toward the camera, encoded as (N + 1) / 2,
+ the same convention as Marigold v1). The image is processed at its own
+ size, rounded to a multiple of 16 and kept between 1024 px and
+ ``pbr_v2_max_resolution`` on the longest edge; the result is resized
+ back to the input size.
+
+ Returns ``bytes`` on success or ``{"error": "..."}``.
+ """
+ server_address = context.preferences.addons[_ADDON_PKG].preferences.server_address
+ client_id = str(uuid.uuid4())
+ scene = context.scene
+ repo = self.MARIGOLD_V2_REPO
+
+ for node_class in ('MarigoldV2PostProcess', 'ConditioningLoader'):
+ try:
+ resp = urllib.request.urlopen(
+ f"http://{server_address}/object_info/{node_class}",
+ timeout=get_timeout('api'))
+ found = node_class in json.loads(resp.read())
+ except urllib.error.HTTPError as e:
+ if e.code != 404:
+ return {"error": f"Marigold V2: failed to query ComfyUI for node "
+ f"'{node_class}' (HTTP {e.code}). Is ComfyUI running?"}
+ found = False
+ except Exception as e:
+ return {"error": f"Marigold V2: could not reach ComfyUI at '{server_address}' "
+ f"({type(e).__name__}: {e})."}
+ if not found:
+ return {"error": f"Marigold V2 needs ComfyUI's core node '{node_class}' "
+ f"(added in September 2026). Update ComfyUI and restart it."}
+
+ base = self._resolve_comfy_model(
+ server_address, 'diffusion_models', self.MARIGOLD_V2_BASE,
+ match=lambda n: (('qwen_image_edit_2509' in n or 'qwen-image-edit-2509' in n)
+ and 'lightning' not in n and n.endswith('.safetensors')))
+ lora = self._resolve_comfy_model(server_address, 'loras', f"marigold_v2_{task}.safetensors")
+ vae = self._resolve_comfy_model(server_address, 'vae', f"marigold_v2_{task}_vae.safetensors")
+ cond = self._resolve_comfy_model(
+ server_address, 'embeddings', f"marigold_v2_{task}_conditioning.safetensors")
+ missing = [label for label, name in (
+ (f"diffusion_models/{self.MARIGOLD_V2_BASE}", base),
+ (f"loras/marigold_v2_{task}.safetensors", lora),
+ (f"vae/marigold_v2_{task}_vae.safetensors", vae),
+ (f"embeddings/marigold_v2_{task}_conditioning.safetensors", cond)) if name is None]
+ if missing:
+ return {"error": f"Marigold V2 model files not found on the ComfyUI server: "
+ f"{', '.join(missing)}. Download them from {repo} into the "
+ f"matching ComfyUI/models/ folders, then restart ComfyUI."}
+
+ from .._generator_utils import upload_image_to_comfyui
+ image_info = upload_image_to_comfyui(server_address, input_image_path, operator=self.operator)
+ if image_info is None:
+ return {"error": f"Failed to upload image for Marigold V2: {input_image_path}"}
+ uploaded_name = image_info.get("name", os.path.basename(input_image_path))
+
+ with Image.open(input_image_path) as _img:
+ src_w, src_h = _img.size
+ max_res = int(getattr(scene, 'pbr_v2_max_resolution', 2048))
+ longest = min(max(max(src_w, src_h), 1024), max_res)
+ scale = longest / max(src_w, src_h)
+ proc_w = max(16, int(round(src_w * scale / 16)) * 16)
+ proc_h = max(16, int(round(src_h * scale / 16)) * 16)
+ print(f"[StableGen] Marigold V2 {task}: processing at {proc_w}×{proc_h} "
+ f"(input {src_w}×{src_h})")
+
+ # One deterministic step, as in the ComfyUI reference workflow: the encoded image is the
+ # starting latent (img_to_img_velocity), no noise, sigma 0.5 -> 0.
+ prompt = {
+ "1": {"class_type": "LoadImage", "inputs": {"image": uploaded_name}},
+ "2": {"class_type": "ImageScale",
+ "inputs": {"image": ["1", 0], "upscale_method": "lanczos",
+ "width": proc_w, "height": proc_h, "crop": "disabled"}},
+ "3": {"class_type": "UNETLoader",
+ "inputs": {"unet_name": base, "weight_dtype": "default"}},
+ "4": {"class_type": "LoraLoaderModelOnly",
+ "inputs": {"model": ["3", 0], "lora_name": lora, "strength_model": 1.0}},
+ "5": {"class_type": "ModelSamplingAuraFlow",
+ "inputs": {"model": ["4", 0], "shift": 1.73, "sampling": "img_to_img_velocity"}},
+ "6": {"class_type": "ConditioningLoader", "inputs": {"conditioning_name": cond}},
+ "7": {"class_type": "VAELoader", "inputs": {"vae_name": vae}},
+ "8": {"class_type": "VAEEncode", "inputs": {"pixels": ["2", 0], "vae": ["7", 0]}},
+ "9": {"class_type": "DisableNoise", "inputs": {}},
+ "10": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "euler"}},
+ "11": {"class_type": "ManualSigmas", "inputs": {"sigmas": "0.5, 0"}},
+ "12": {"class_type": "BasicGuider",
+ "inputs": {"model": ["5", 0], "conditioning": ["6", 0]}},
+ "13": {"class_type": "SamplerCustomAdvanced",
+ "inputs": {"noise": ["9", 0], "guider": ["12", 0], "sampler": ["10", 0],
+ "sigmas": ["11", 0], "latent_image": ["8", 0]}},
+ "14": {"class_type": "VAEDecode", "inputs": {"samples": ["13", 0], "vae": ["7", 0]}},
+ "15": {"class_type": "MarigoldV2PostProcess",
+ "inputs": {"image": ["14", 0], "prediction": task}},
+ "16": {"class_type": "SaveImageWebsocket", "inputs": {"images": ["15", 0]}},
+ }
+ NODES = {"save_image": "16"}
+
+ ws = self._connect_to_websocket(server_address, client_id)
+ if ws is None:
+ return {"error": "WebSocket connection failed for Marigold V2"}
+ if hasattr(self.operator, '_active_ws'):
+ self.operator._active_ws = ws
+ type(self.operator)._active_ws = ws
+ try:
+ images = self._execute_prompt_and_get_images(
+ ws, prompt, client_id, server_address, NODES)
+ finally:
+ if hasattr(self.operator, '_active_ws'):
+ self.operator._active_ws = None
+ type(self.operator)._active_ws = None
+ try:
+ ws.close()
+ except Exception:
+ pass
+
+ if not isinstance(images, dict) or not images.get(NODES['save_image']):
+ return {"error": f"Marigold V2 {task} failed — no output received"}
+ data = images[NODES['save_image']][0]
+
+ out = Image.open(BytesIO(data)).convert('RGB')
+ if out.size != (src_w, src_h):
+ out = out.resize((src_w, src_h), Image.LANCZOS)
+ buf = BytesIO()
+ out.save(buf, format='PNG')
+ data = buf.getvalue()
+ return data
+
def _build_klein_txt2img(self, context):
"""Return (prompt_dict, save_node_id) for a minimal FLUX.2 Klein txt2img.
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 477af20..e006bbf 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -1533,6 +1533,8 @@ class StableGenPanel(bpy.types.Panel):
grid.prop(scene, "pbr_map_emission", toggle=True, icon="LIGHT_POINT")
# ── Per-map adjustment controls ──
if scene.pbr_map_normal:
+ adj_row = sub.row()
+ adj_row.prop(scene, "pbr_normal_model", text="Normal Model")
adj_row = sub.row()
adj_row.prop(scene, "pbr_normal_strength", text="Normal Strength", slider=True)
if scene.pbr_map_height:
@@ -1589,6 +1591,10 @@ class StableGenPanel(bpy.types.Panel):
scene.pbr_tiling != 'off' and scene.pbr_tile_inference == 'MODEL'):
row = sub.row()
row.prop(scene, "pbr_processing_resolution", text="Inference resolution (px)")
+ if ((scene.pbr_map_albedo and scene.pbr_albedo_source == 'marigold_v2')
+ or (scene.pbr_map_normal and scene.pbr_normal_model == 'marigold_v2')):
+ row = sub.row()
+ row.prop(scene, "pbr_v2_max_resolution", text="Marigold V2 resolution (px)")
row = sub.row(align=True)
row.prop(scene, "pbr_denoise_steps", text="Inference steps")
row.prop(scene, "pbr_ensemble_size", text="Predictions per map")
diff --git a/stablegen/ui/studio_cards.py b/stablegen/ui/studio_cards.py
index 2b719fd..53c1720 100644
--- a/stablegen/ui/studio_cards.py
+++ b/stablegen/ui/studio_cards.py
@@ -103,7 +103,7 @@ SCHEMAS = {
description='Reflection softness', beside='material', parent='pbr'),
Spec('metallic', 'Metallic', 'material', ('pbr_map_metallic',), feature='pbr_map_metallic',
description='Metal or dielectric', beside='material', parent='pbr'),
- Spec('normal', 'Normal', 'layers', ('pbr_map_normal', 'pbr_normal_strength'), feature='pbr_map_normal',
+ Spec('normal', 'Normal', 'layers', ('pbr_map_normal', 'pbr_normal_model', 'pbr_normal_strength'), feature='pbr_map_normal',
description='Surface detail', beside='detail', parent='pbr'),
Spec('height', 'Height', 'modifier', ('pbr_map_height', 'pbr_height_scale'), feature='pbr_map_height',
description='Displacement', beside='detail', parent='pbr'),
@@ -118,7 +118,7 @@ SCHEMAS = {
Spec('processing', 'Shared processing', 'settings', ('pbr_use_native_resolution',
'pbr_processing_resolution', 'pbr_tiling', 'pbr_tile_grid', 'pbr_tile_inference', 'pbr_tile_superres',
'pbr_tile_albedo', 'pbr_tile_material', 'pbr_tile_normal', 'pbr_tile_height',
- 'pbr_tile_emission', 'pbr_denoise_steps', 'pbr_ensemble_size'), parent='pbr',
+ 'pbr_tile_emission', 'pbr_denoise_steps', 'pbr_ensemble_size', 'pbr_v2_max_resolution'), parent='pbr',
rows=(('pbr_use_native_resolution',), ('pbr_tiling',), ('pbr_denoise_steps', 'pbr_ensemble_size'))),
Spec('material', 'Material & lighting', 'material', ('fallback_color', 'overwrite_material', 'pbr_auto_lighting')),
),
@@ -235,6 +235,7 @@ LABELS = {
'pbr_ao_samples': 'AO samples',
'pbr_ao_distance': 'Ray distance (BU)',
'pbr_normal_strength': 'Normal strength',
+ 'pbr_normal_model': 'Normal model',
'pbr_auto_lighting': 'Add studio lighting after projection',
'early_priority': 'Prioritize earlier views',
'sequential_factor': 'Full-visibility tolerance',
@@ -294,6 +295,7 @@ LABELS = {
'pbr_tile_grid': 'Tile grid',
'pbr_tile_inference': 'Tile inference',
'pbr_processing_resolution': 'Inference resolution (px)',
+ 'pbr_v2_max_resolution': 'Marigold V2 resolution (px)',
'pbr_denoise_steps': 'Inference steps',
'pbr_ensemble_size': 'Predictions per map',
'pbr_emission_bloom': 'Detection blur (px)',
diff --git a/stablegen/ui/studio_hierarchy.py b/stablegen/ui/studio_hierarchy.py
index 93820d4..3426140 100644
--- a/stablegen/ui/studio_hierarchy.py
+++ b/stablegen/ui/studio_hierarchy.py
@@ -60,8 +60,8 @@ FAMILIES = {
'pbr_decomposition': ('pbr_map_albedo', 'pbr_map_roughness', 'pbr_map_metallic',
'pbr_map_normal', 'pbr_map_height', 'pbr_map_ao', 'pbr_map_emission',
'pbr_use_native_resolution', 'pbr_tiling', 'pbr_denoise_steps',
- 'pbr_ensemble_size', 'pbr_replace_color_with_albedo', 'pbr_auto_lighting'),
- 'pbr_map_normal': ('pbr_normal_strength',),
+ 'pbr_ensemble_size', 'pbr_v2_max_resolution', 'pbr_replace_color_with_albedo', 'pbr_auto_lighting'),
+ 'pbr_map_normal': ('pbr_normal_model', 'pbr_normal_strength'),
'pbr_map_height': ('pbr_height_scale',),
'pbr_map_ao': ('pbr_ao_samples', 'pbr_ao_distance'),
'pbr_map_emission': ('pbr_emission_method', 'pbr_emission_threshold', 'pbr_emission_strength'),