Mike0021's picture
PBR option: pbr=true / POST /api/jobs/{id}/pbr (per-view albedo/roughness/metallic from the projtex-pbr ZeroGPU Space, baked into a metallicRoughness GLB)
605a39e verified
Raw History Blame Contribute Delete
129 kB
"""Project state and the end-to-end workflow: import -> plan -> generate & project -> bake & export -> retouch. A project is a directory with ``project.json`` plus images. Every step is non-destructive: views (generated images + cameras) and retouch layers are kept, and the texture is always re-fused from them, so a single view can be regenerated/replaced/disabled without touching the others. """ from __future__ import annotations import copy import hashlib import json import logging import re import shutil import time from dataclasses import dataclass from pathlib import Path from typing import Any import cv2 import numpy as np from PIL import Image from . import planning from .backends import GenRequest, PendingGeneration, get_backend from .camera import Camera from .gl import GL from .mesh import TexMesh, export_glb, export_obj, load_mesh, normalize_tile, orient_up, prepare_uvs from .projection import Accumulator, FusionParams, fill_by_part, overlay, project_view, push_pull_fill, smoothstep from .prompts import PRESETS, view_prompt log = logging.getLogger(__name__) MODES = ("object", "character", "environment") DEFAULT_SETTINGS: dict[str, Any] = { "mode": "object", "prompt": "", "subject": "", "negative_prompt": "", "lighting": "flat", # flat | soft | natural (see prompts.LIGHTING) "raw_prompt": False, # {material or object name: description}; each view prompt lists the parts it shows and where (and which # are out of view). Without descriptions, meaningful names from the file are used ("auto"); False: off "part_prompts": "auto", "export_single_mesh": False, # show each material's base colour (from the file) in the conditioning render instead of white clay, so parts # that differ only by material (painted stripes, a door panel) are visible to the image model. # auto: when at least two materials have clearly different colours "color_guide": "auto", # GLB with one object and one material (game-ready) instead of the source scene "style_reference": None, "backend": {"name": "qwen-turbo"}, "view_size": 1024, "texture_size": 2048, "preview_texture_size": 1024, "seed": 42, "background": [0.5, 0.5, 0.5], "sky_color": [0.78, 0.82, 0.88], "skymap": None, "harmonize": True, "align": "none", "consistency_refs": 0, "focus_prompt": "", # optional prompt for close-up (focus) views, e.g. only the face/hair part of the prompt "sequential": True, "validate": True, # reject generated views that do not line up with the render (re-framed, zoomed out ...) "max_retries": 2, "min_edge_agreement": 0.2, "min_silhouette_iou": 0.55, "min_silhouette_iou_below": 0.85, # views looking up from below: hard for the model, little painted to check "min_painted_corr": 0.45, # agreement with texture already painted by earlier views (see painted_agreement): "low_corr_painted_diff": 0.085, # low correlation counts only with a visible colour difference (flat dark "max_painted_diff": 0.13, # surfaces give meaningless correlations), and any large difference rejects "min_painted_frac": 0.12, # other parts' colours painted on a part (validate.foreign_content); off by default: on clapboard, trim and # window frames it flags good views too. Stripping out-of-view parts from the prompt fixes the cause. "max_foreign_frac": None, # a view that only disagrees with texture already painted, while matching the geometry well, paints just the # surface not painted yet (see _partial_ok) instead of being rejected "partial_views": True, "inside_seen_frac": 0.15, # surface seen by fewer cameras is "inside" (see Project.inside); 0 disables "inside": "plain", # plain: the inside of vessels gets its material's main colour | paint: views may paint it "metal": "keep", # keep the painted reflections | flat: mirror-like metal (metallic >= 0.9, roughness <= 0.3) # gets an even base colour, for renderers with environment lighting (they add the reflections) "min_painted_chroma_overlap": 0.45, # hue/saturation overlap with the painted pixels (good views 0.59-0.95) "partial_retries": 1, # extra tries for a view kept as partial, in case one continues the painted pattern "lower_steep_gaps": True, # a gap view rejected from high above gets one more try from 40 degrees "hide_grazed_paint": True, # conditioning renders leave out faint paint a view sees far more head-on (_condition) # objects: ring views that see less than this share of what the broadest one sees, mostly from an angle another # view sees much better, are generated after the others (Project._narrow_views_last); 0 disables "narrow_view_share": 0.5, # gap views from more than 50 degrees above that drew more than this share of the render's edges elsewhere # (validate.edges_moved: the subject redrawn from its usual angle) are rejected; None disables "max_edges_moved": 0.2, # with the colour guide on: a view that painted parts making up more than this share of the object in the # colour of a touching part with a clearly different guide (validate.merged_parts: a fretboard painted like # the neck) is retried; if every try does it, the one merging least is kept. None disables "max_merged_frac": 0.03, # pixels where a view painted a touching part's colour onto an evenly coloured part (validate.spilled_paint: a # xylophone's pink bar spilled onto its maple frame by a view drawn slightly larger) are not projected "mask_spills": True, # the low frequencies of evenly painted parts blended softly across views at bake (Project._blend_seams) "seam_blend": True, "swatch_refs": "auto", # a close-up of the part a view must paint most of, as already painted # (_swatch_reference); auto: not for parts described as a scene (a landscape wrapping round a vase) "mask_contradictions": True, # leave out the parts of an accepted gap view that repaint, in other colours, # what earlier views painted (validate.contradiction_mask) "min_edge_agreement_env": 0.1, "max_outside_change": 0.06, "max_lowpass_change": 0.035, # retouch upscale: the blurred content must stay the same # retouch: reject outputs that repaint the picture outside the mask "rescue": True, "view_masks": False, # native-mask backends: only repaint still-clay pixels of later views (keeps texture) # try to undo a global zoom/shift of a rejected view (SIFT + RANSAC similarity) before retrying # condition each view on what is already projected (False = independent views) "front_azimuth": 0.0, "fusion": FusionParams().to_dict(), } def _img_to_np(path: str | Path) -> np.ndarray: return np.asarray(Image.open(path).convert("RGB"), np.float32) / 255.0 def _np_to_img(a: np.ndarray) -> Image.Image: a = np.clip(a, 0, 1) return Image.fromarray((a * 255 + 0.5).astype(np.uint8)) def _save(a: np.ndarray, path: Path) -> Path: path.parent.mkdir(parents=True, exist_ok=True) _np_to_img(a).save(path) return path def _elevation(cam: Camera) -> float: """Degrees the camera looks down at its target (negative: from below).""" d = cam.eye_np - np.asarray(cam.target, np.float64) return float(np.degrees(np.arcsin(np.clip(d[1] / max(float(np.linalg.norm(d)), 1e-12), -1, 1)))) _COLORED_METAL = re.compile(r"gold|gilt|gilded|brass|bronze|copper|rose|anodi[sz]ed|tinted|blued|patina", re.I) def _main_color(cols: np.ndarray) -> np.ndarray: """Dominant colour of a set of texels: the fullest cell of a coarse colour grid, then its median (the white ground of a patterned glaze, not the average of ground and pattern).""" from scipy.ndimage import uniform_filter cols = np.nan_to_num(cols.reshape(-1, 3)) q = np.clip((cols * 8).astype(np.int64), 0, 7) hist = np.bincount(q[:, 0] * 64 + q[:, 1] * 8 + q[:, 2], minlength=512).reshape(8, 8, 8).astype(np.float64) top = np.array(np.unravel_index(uniform_filter(hist, 3, mode="constant").argmax(), hist.shape)) near = (np.abs(q - top) <= 1).all(1) # one colour family can straddle a cell border return np.median(cols[near], axis=0).astype(np.float32) @dataclass class View: name: str camera: Camera kind: str = "base" priority: float = 1.0 group: str = "" enabled: bool = True prompt_hint: str = "" prompt_extra: str = "" reference: str | None = None seed: int | None = None status: str = "planned" # planned | generated | imported | pending | failed image: str | None = None meta: dict | None = None def to_dict(self) -> dict: d = {k: getattr(self, k) for k in self.__dataclass_fields__} d["camera"] = self.camera.to_dict() return d @classmethod def from_dict(cls, d: dict) -> "View": d = dict(d) d["camera"] = Camera.from_dict(d["camera"]) return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__}) class Project: """Programmatic interface. All public methods return JSON-serialisable dicts.""" def __init__(self, root: str | Path): self.root = Path(root).resolve() self.data = json.loads((self.root / "project.json").read_text()) # projects created by older versions: fill in settings added since, with their defaults st = self.data.setdefault("settings", {}) for k, v in DEFAULT_SETTINGS.items(): if k not in st: st[k] = copy.deepcopy(v) st["fusion"] = {**FusionParams().to_dict(), **st.get("fusion", {})} self.views = [View.from_dict(v) for v in self.data.get("views", [])] self._mesh: TexMesh | None = None self._source: TexMesh | None = None self._source_tex: np.ndarray | None = None self._gl: GL | None = None self._tex_cache: dict = {} # ================================================================ lifecycle @classmethod def create(cls, root: str | Path, mesh_path: str | Path, mode: str = "object", uv: str = "auto", up: str | None = None, overwrite: bool = False, progress=None, **settings) -> "Project": """Import a mesh: flatten the scene, validate/repair UVs and initialise the project directory. ``progress(n_faces)`` is called before a UV unwrap (minutes on large meshes).""" if mode not in MODES: raise ValueError(f"mode must be one of {MODES}") root = Path(root).resolve() if (root / "project.json").exists() and not overwrite: raise FileExistsError(f"{root} already contains a project (use overwrite=True)") if overwrite and root.exists(): shutil.rmtree(root) (root / "mesh").mkdir(parents=True, exist_ok=True) t = time.time() gl = GL() src = load_mesh(mesh_path) up = up or ("auto" if mode == "character" else "y") if up == "auto" and mode != "character" and Path(mesh_path).suffix.lower() in (".glb", ".gltf"): up = "y" # glTF is +Y up; for objects the extent heuristic would stand a long bed on its end # (figures keep it: some GLB characters, e.g. Mixamo exports, really lie along Z) up_used = orient_up(src, up) normalize_tile(src) work = copy.deepcopy(src) # interiors are fused double-sided; objects need outward normals or inside-out parts stay unpainted orientation = planning.orient_faces(gl, work) if mode != "environment" else None tex_size = settings.get("texture_size") or (4096 if mode == "environment" else 2048) uv_rep = prepare_uvs(work, mode=uv, gl=gl, resolution=int(tex_size), progress=progress) work.save_npz(root / "mesh" / "work.npz") src.save_npz(root / "mesh" / "source.npz") tex_mats = [i for i, m in enumerate(src.materials) if m.get("image") is not None] for i, m in enumerate(src.materials): if m.get("image") is not None: m["image"].save(root / "mesh" / f"source_albedo_{i}.png") s = copy.deepcopy(DEFAULT_SETTINGS) if mode == "environment": s["fusion"]["double_sided"] = True s["texture_size"] = 4096 s["view_size"] = 1024 if mode == "character": s["front_azimuth"] = "auto" s.update({k: v for k, v in settings.items() if v is not None}) data = { "version": 1, "created": time.strftime("%Y-%m-%dT%H:%M:%S"), "mesh": { "source": str(Path(mesh_path).resolve()), "faces": int(len(work.faces)), "vertices": int(len(work.vertices)), "materials": len(src.materials), "textured_materials": tex_mats, "bounds": work.bounds.round(5).tolist(), "uv": uv_rep, "up_axis": up_used, "orientation": orientation, }, "settings": {**s, "mode": mode}, "views": [], "layers": [], "history": [], } (root / "project.json").write_text(json.dumps(data, indent=2)) p = cls(root) p._gl = gl p._mesh = work p._log("create", {"mesh": str(mesh_path), "mode": mode, "uv": uv_rep.get("decision"), "seconds": round(time.time() - t, 2)}) p.save() return p @classmethod def open(cls, root: str | Path) -> "Project": return cls(root) def save(self) -> None: self.data["views"] = [v.to_dict() for v in self.views] tmp = self.root / "project.json.tmp" tmp.write_text(json.dumps(self.data, indent=2, default=_json_default)) tmp.replace(self.root / "project.json") def _log(self, action: str, info: dict) -> None: self.data.setdefault("history", []).append({"t": time.strftime("%Y-%m-%dT%H:%M:%S"), "action": action, **info}) # ================================================================ accessors @property def settings(self) -> dict: return self.data["settings"] @property def mode(self) -> str: return self.settings["mode"] @property def gl(self) -> GL: if self._gl is None: self._gl = GL() return self._gl @property def mesh(self) -> TexMesh: if self._mesh is None: self._mesh = TexMesh.load_npz(self.root / "mesh" / "work.npz") return self._mesh def source_mesh(self) -> tuple[TexMesh, np.ndarray | None]: """Original mesh with its authored UVs and first base-color texture (for oracle/comparisons).""" if self._source is None: self._source = TexMesh.load_npz(self.root / "mesh" / "source.npz") mats = self.data["mesh"].get("textured_materials", []) if mats: self._source_tex = np.asarray( Image.open(self.root / "mesh" / f"source_albedo_{mats[0]}.png").convert("RGB")) return self._source, self._source_tex def _usable(self, v: "View") -> bool: return bool(v.enabled and v.image and v.status != "rejected" and (self.root / v.image).exists()) def source_textures(self) -> list: """Per-material base colour of the source asset: image array, flat colour, or None.""" src, _ = self.source_mesh() out = [] for i, m in enumerate(src.materials): f = self.root / "mesh" / f"source_albedo_{i}.png" if f.exists(): out.append(np.asarray(Image.open(f).convert("RGB"))) elif m.get("base_color") is not None: out.append(np.asarray(m["base_color"], np.float32)) else: out.append(None) return out def fusion(self) -> FusionParams: return FusionParams.from_dict(self.settings.get("fusion")) def view(self, name: str) -> View: for v in self.views: if v.name == name: return v raise KeyError(f"no view named {name!r}; views: {[v.name for v in self.views]}") def configure(self, **kw) -> dict: """Update settings (prompt, backend, lighting, texture_size, fusion={...}, style_reference=path, ...).""" s = self.settings for k, v in kw.items(): if v is None: continue if k == "fusion": s["fusion"] = {**s["fusion"], **v} elif k == "backend" and isinstance(v, str): s["backend"] = {"name": v} elif k == "style_reference": s[k] = self._import_file(v, "refs") if v else None elif k == "preset": s["prompt"] = (s.get("prompt", "") + ", " if s.get("prompt") else "") + PRESETS[v] elif k in DEFAULT_SETTINGS or k in ("mode",): s[k] = v else: raise KeyError(f"unknown setting {k!r}") self._log("configure", {k: v for k, v in kw.items() if v is not None and k != "backend"}) self.save() return {"settings": s} def _import_file(self, path: str | Path, sub: str) -> str: src = Path(path) if not src.is_absolute() and (self.root / src).exists(): return str(src) dst = self.root / sub / src.name dst.parent.mkdir(parents=True, exist_ok=True) if src.resolve() != dst.resolve(): shutil.copy(src, dst) return str(dst.relative_to(self.root)) def backend(self, override: Any = None): """Backend from the project settings, a name/options override, or a ready Backend instance (used by the hosted service to attach the caller's identity without writing it to project.json).""" from .backends import Backend if isinstance(override, Backend): return override cfg = dict(self.settings["backend"]) if isinstance(override, str): cfg = {"name": override} elif isinstance(override, dict): cfg = {**cfg, **override} if override.get("name") in (None, cfg["name"]) else dict(override) name = cfg.pop("name") if name == "files": cfg.setdefault("dir", str(self.root / "exchange")) return get_backend(name, **cfg) # ================================================================= planning def plan(self, preset: str | None = None, n_views: int | None = None, focus: Any = "default", gaps: bool = True, max_gap_views: int | None = None, fov: float | None = None, probes: int | None = None, eye_height: float | None = None, replace: bool = True, levels: str | float = "lowest", region: str = "auto") -> dict: """Place cameras. object: preset (minimal|balanced|dense|greedy); character: balanced + head close-ups; environment: regular 360-degree probes (6 cube views each). Optional gap views cover what is left.""" size = int(self.settings["view_size"]) mesh, gl = self.mesh, self.gl info: dict = {"mode": self.mode} if self.settings.get("front_azimuth") == "auto": gltf = Path(self.data["mesh"]["source"]).suffix.lower() in (".glb", ".gltf") # glTF puts the front at +Z; a figure that had to be stood up (up != y) loses that convention prior = 0.0 if gltf and self.data["mesh"].get("up_axis", "y") == "y" else None det = planning.detect_front_azimuth(gl, mesh, prior=prior) self.settings["front_azimuth"] = det["azimuth"] info["front"] = det fa = float(self.settings.get("front_azimuth") or 0.0) params = self.fusion() specs: list[planning.ViewSpec] = [] if self.mode in ("object", "character"): preset = preset or "balanced" fov = fov or 35.0 if preset == "greedy": specs = planning.plan_greedy(gl, mesh, n_views=n_views or 8, fov=fov, size=size, front_azimuth=fa, params=params) else: grounded = self.mode == "object" and planning.is_grounded(mesh) info["grounded"] = grounded specs = planning.plan_object(mesh, preset, fov=fov, size=size, front_azimuth=fa, grounded=grounded) if focus == "default": focus = "auto" if self.mode == "character" else None if focus: fi = self._resolve_focus(focus) info["focus"] = fi specs += planning.plan_focus(mesh, fi["center"], fi["radius"], label=fi["label"], size=size, front_azimuth=fa) else: preset = preset or "probes" if preset not in ("probes", "probes-greedy"): raise ValueError("environment presets: probes (regular spacing) | probes-greedy (coverage-driven)") env_probe = planning.CoverageProbe(gl, mesh, res=1024, params=params) views, pinfo = planning.plan_probes(mesh, n_probes=probes or 6, eye_height=eye_height, fov=fov or 100.0, size=size, levels=levels, probe=env_probe, region=region, placement="greedy" if preset == "probes-greedy" else "regular") specs = views info["probes"] = pinfo self._set_dens_ref(specs) params = self.fusion() env = self.mode == "environment" probe = planning.CoverageProbe(gl, mesh, res=1024 if env else 512, params=params) relevant = None walk = None weights = None if env: walk = info["probes"].pop("_walkable") np.save(self.root / "mesh" / "walkable.npy", walk) relevant = info["probes"].pop("_pvs", None) imp = info["probes"].pop("_importance", None) if relevant is None or imp is None: imp, relevant = planning.screen_importance(probe, walk) np.save(self.root / "mesh" / "pvs_1024.npy", relevant) np.save(self.root / "mesh" / "importance_1024.npy", imp) weights = planning.pvs_weights(imp) if not env: # estimate what the QA reports: the surface seen from the side or above, weighted by how much relevant = self.relevance(probe.res, above=True) weights = self.seen_weights(probe.res) ins = self.inside(probe.res) if ins is not None and self.settings.get("inside", "plain") == "plain": # filled, not painted relevant = np.where(ins, 0.0, relevant) if self.mode == "object" and preset != "greedy": specs, narrow = self._narrow_views_last(specs, probe, relevant, weights) if narrow: info["narrow_views_last"] = narrow best = np.zeros((probe.res, probe.res), np.float32) for s in specs: q = probe.quality(s.camera) s.meta["coverage_gain"] = round(self._cov(probe, np.maximum(q, best), relevant, weights=weights) - self._cov(probe, best, relevant, weights=weights), 4) best = np.maximum(best, q) info["coverage"] = round(self._cov(probe, best, relevant, weights=weights), 4) if env: info["coverage_definition"] = ("screen-weighted: share of what a viewer sees from walkable eye " "positions that is covered") info["visible_area_coverage"] = round(self._cov(probe, best, relevant), 4) info["surface_coverage_total"] = round(probe.coverage(best), 4) if gaps: gap_specs = planning.plan_gaps(gl, mesh, best, probe, max_views=max_gap_views or (6 if env else 3), size=size, environment=env, walkable=walk, relevant=relevant, fov=90.0 if env else 45.0, weights=weights) for g in gap_specs: best = np.maximum(best, probe.quality(g.camera)) specs += gap_specs info["gap_views"] = [g.name for g in gap_specs] info["coverage_with_gaps"] = round(self._cov(probe, best, relevant, weights=weights), 4) new = [View(s.name, s.camera, kind=s.kind, priority=s.priority, group=s.group, prompt_hint=s.prompt_hint, meta=s.meta) for s in specs] if replace: self.views = new else: names = {v.name for v in self.views} self.views += [v for v in new if v.name not in names] info["views"] = [{"name": v.name, "kind": v.kind, "priority": v.priority, "coverage_gain": (v.meta or {}).get("coverage_gain")} for v in self.views] self._log("plan", {"preset": preset, "views": len(self.views), "coverage": info["coverage"]}) self.save() return info def _narrow_views_last(self, specs: list, probe, relevant: np.ndarray | None, weights: np.ndarray | None) -> tuple[list, dict | None]: """Generate the ring views that see a small part of the model, from an angle others see much better, last. Each view continues what the views before it painted. Seen end-on (a skateboard deck uploaded on its side, looked at from its nose), a view shows the kicktail up close but at a grazing angle and paints a whole composition on it; the side views, which see that surface head-on, then copy it as a miniature (a second sun on the kicktail) instead of painting one graphic across the deck. Ring views (base views from 0 to 15 degrees above the horizon) that see less than ``narrow_view_share`` of what the broadest one sees, and most of whose surface another ring view sees far more head-on (cosine + 0.3), move after the other ring views. A gable front or a bus's windscreen, the best view of its own face, keeps its place; names, cameras and the rest of the order stay as planned.""" share = float(self.settings.get("narrow_view_share") or 0.0) ring = [s for s in specs if s.kind == "base" and 0.0 <= _elevation(s.camera) <= 15.0] if share <= 0 or len(ring) < 3: return specs, None w = weights * probe.uvg["valid"] if weights is not None else \ probe.area * (relevant > 0.05 if relevant is not None else 1.0) pos, nrm = probe.uvg["position"][..., :3], probe.uvg["normal"][..., :3] q, cos = {}, {} for s in ring: q[s.name] = w * probe.quality(s.camera) d = s.camera.eye_np[None, None] - pos d /= np.maximum(np.linalg.norm(d, axis=-1, keepdims=True), 1e-9) cos[s.name] = np.where(q[s.name] > 0, np.abs((d * nrm).sum(-1)), -1.0) seen = {n: float(x.sum()) for n, x in q.items()} top = max(seen.values()) narrow = {} for s in ring: if seen[s.name] >= share * top: continue better = np.max([c for n, c in cos.items() if n != s.name], axis=0) >= cos[s.name] + 0.3 elsewhere = float(q[s.name][better].sum() / max(seen[s.name], 1e-30)) if elsewhere > 0.5: narrow[s.name] = {"seen": round(seen[s.name] / top, 2), "seen_better_elsewhere": round(elsewhere, 2)} if not narrow: return specs, None last = specs.index(ring[-1]) moved = [s for s in ring if s.name in narrow] return [s for s in specs[:last + 1] if s not in moved] + moved + specs[last + 1:], narrow @staticmethod def _cov(probe, alpha: np.ndarray, relevant: np.ndarray | None, thresh: float = 0.3, weights: np.ndarray | None = None) -> float: if weights is not None: w = weights * probe.uvg["valid"] return float(w[alpha >= thresh].sum() / max(float(w.sum()), 1e-30)) if relevant is None: return probe.coverage(alpha, thresh) rel = probe.area * (relevant > 0.05) return float(rel[alpha >= thresh].sum() / max(rel.sum(), 1e-30)) def importance(self, res: int = 1024) -> np.ndarray | None: """Screen-weighted texel importance for environments (None for objects).""" if self.mode != "environment" or self.walkable() is None: return None f = self.root / "mesh" / f"importance_{res}.npy" if f.exists(): return np.load(f) probe = planning.CoverageProbe(self.gl, self.mesh, res=res, params=self.fusion()) imp, vis = planning.screen_importance(probe, self.walkable()) np.save(f, imp) np.save(self.root / "mesh" / f"pvs_{res}.npy", vis) return imp def walkable(self) -> np.ndarray | None: f = self.root / "mesh" / "walkable.npy" return np.load(f) if f.exists() else None def relevance(self, res: int = 1024, above: bool = False) -> np.ndarray: """Texels that can be seen at all: from outside orbits (objects) or from walkable eye positions (environments). Cached in mesh/pvs_<res>.npy. ``above``: objects only, seen from the side or above (the underside excluded; mesh/pvs_above_<res>.npy). QA statistics are computed over that surface.""" f = self.root / "mesh" / (f"pvs_above_{res}.npy" if above else f"pvs_{res}.npy") if f.exists(): return np.load(f) probe = planning.CoverageProbe(self.gl, self.mesh, res=res, params=self.fusion()) walk = self.walkable() if self.mode == "environment" and walk is not None: rel = planning.pvs_alpha(probe, walk) elif above: rel, seen, frac = planning.outside_visibility(probe, self.mesh, min_elevation=0.0, with_mean=True, with_frac=True) np.save(self.root / "mesh" / f"seen_above_{res}.npy", seen) np.save(self.root / "mesh" / f"seenfrac_above_{res}.npy", frac) else: rel = planning.outside_visibility(probe, self.mesh) np.save(f, rel) return rel def seen_weights(self, res: int = 1024) -> np.ndarray: """Objects: how much each texel is seen from the side and above (mean projection quality over a sphere of cameras), times its area. QA and planning weight coverage by it, so deep crevices and the inside of a well glimpsed at a grazing angle count little, and broad visible faces count fully.""" f = self.root / "mesh" / f"seen_above_{res}.npy" if not f.exists(): (self.root / "mesh" / f"pvs_above_{res}.npy").unlink(missing_ok=True) self.relevance(res, above=True) from .projection import texel_world_size tws = texel_world_size(self.gl.uv_gbuffer(self.mesh, res)) return np.nan_to_num(np.load(f) * tws * tws).astype(np.float32) def inside(self, res: int = 1024) -> np.ndarray | None: """Objects: surface seen only from above through an opening (the inside of a vase, a mug or a chimney): by fewer than ``inside_seen_frac`` of the cameras around and above the object, and mostly by steep ones (a recessed window or a porch floor is seen from the side). Views down such openings fail or paint the motif there (three gap views into a vase's mouth were rejected; a mug got its mountain landscape painted on the inner wall), so with ``inside: plain`` gap views do not aim at it and fuse() gives it the main colour of its material. None for environments.""" thr = float(self.settings.get("inside_seen_frac") or 0.0) if self.mode == "environment" or thr <= 0: return None f = self.root / "mesh" / f"seenfrac_above_{res}.npy" if not f.exists(): (self.root / "mesh" / f"pvs_above_{res}.npy").unlink(missing_ok=True) self.relevance(res, above=True) frac = np.load(f) if frac.ndim != 3: # written before the low-camera share was kept f.unlink() (self.root / "mesh" / f"pvs_above_{res}.npy").unlink(missing_ok=True) self.relevance(res, above=True) frac = np.load(f) seen, low = frac[..., 0], frac[..., 1] return (seen > 0) & (seen < thr) & (low <= 0.25 * seen) def _fill_inside(self, color: np.ndarray, alpha: np.ndarray, covered: np.ndarray, res: int) -> int: """Give the inside surface (see inside()) the dominant painted colour of its material (the white glaze of a blue-and-white vase), in place: all of it with ``inside: plain``, only what no view painted with ``inside: paint``. Returns the number of texels filled.""" ins = self.inside(min(res, 1024)) if ins is None or not ins.any(): return 0 idx = np.arange(res) * ins.shape[0] // res ins = ins[idx][:, idx] plain = self.settings.get("inside", "plain") == "plain" todo = ins if plain else ins & (alpha < 0.3) if not todo.any(): return 0 fid = self.gl.uv_gbuffer(self.mesh, res)["face"] mat = np.where(fid >= 0, self.mesh.face_material[np.maximum(fid, 0)], -1) good = (alpha >= 0.6) & (fid >= 0) & ~ins if good.sum() < 64: return 0 filled = np.zeros_like(todo) for m in np.unique(mat[todo]): src = good & (mat == m) tgt = todo & (mat == m) main = _main_color(color[src] if src.sum() >= 64 else color[good]) # paint mode keeps what a view painted there, blended in a = 0.0 if plain else np.clip(alpha[tgt] / 0.3, 0, 1)[:, None] color[tgt] = a * color[tgt] + (1 - a) * main filled |= tgt covered |= filled return int(filled.sum()) def _flatten_metal(self, color: np.ndarray, alpha: np.ndarray, res: int) -> int: """Mirror-like metal (metallic >= 0.9 and roughness <= 0.3 in the source file): the image model paints chrome with the reflections of the surroundings it imagines, which the metallic material then reflects a second time (wavy streaks across a chrome toaster's top) in a renderer with environment lighting. With ``metal: flat`` its painted texels get the material's main colour, with a fifth of the large-scale variation kept; for neutral metals in the file (chrome, steel: grey, and not named gold, brass, copper ...) the file's colour. Not the default: without an environment (the previews here, many three.js scenes) even chrome then looks like grey plastic, while the painted reflections read as chrome anywhere. Returns the texels changed.""" if self.settings.get("metal", "keep") != "flat" or not self.mesh.materials: return 0 shiny = [i for i, m in enumerate(self.mesh.materials) if float(m.get("metallic") or 0.0) >= 0.9 and float(m.get("roughness", 1.0)) <= 0.3] if not shiny: return 0 fid = self.gl.uv_gbuffer(self.mesh, res)["face"] mat = np.where(fid >= 0, self.mesh.face_material[np.maximum(fid, 0)], -1) sig = res / 64 pp = {str(k).lower(): str(v) for k, v in (self.settings.get("part_prompts") or {}).items()} \ if isinstance(self.settings.get("part_prompts"), dict) else {} lum_w = np.array([0.2126, 0.7152, 0.0722], np.float32) n = 0 for m in shiny: sel = (mat == m) & (alpha > 0) good = sel & (alpha >= 0.6) if good.sum() < 64: continue main = _main_color(color[good]) w = sel.astype(np.float32) wb = np.maximum(cv2.GaussianBlur(w, (0, 0), sig), 1e-6)[..., None] broad = cv2.GaussianBlur(color * w[..., None], (0, 0), sig) / wb out = main + 0.2 * (broad[sel] - main) mm = self.mesh.materials[m] base = np.clip(np.asarray(mm.get("base_color") or (0.8, 0.8, 0.8), np.float64)[:3], 0, 1) ** (1 / 2.2) words = f"{mm.get('name') or ''} {pp.get(str(mm.get('name') or '').lower(), '')}" if base.max() - base.min() < 0.12 and not _COLORED_METAL.search(words): # chrome or steel in the file: the painted reflections tinted it (a fire engine's chrome bumper came # out pink from its red body) and darkened it (an imagined dark studio): the file's colour, which a # renderer takes as the metal's reflectance, with the painted variation around its main colour out = (out @ lum_w / max(float(main @ lum_w), 1e-6))[:, None] * base.astype(np.float32)[None] color[sel] = np.clip(out, 0, 1) n += int(sel.sum()) return n def _set_dens_ref(self, specs) -> None: vals = [] for s in specs[:12]: d = self.gl.render_view(self.mesh, s.camera.resized(128), mode="clay")["depth"] if (d > 0).any(): vals.append(s.camera.focal_px / float(np.median(d[d > 0]))) if vals: self.settings["fusion"]["dens_ref"] = float(np.median(vals)) def _resolve_focus(self, focus) -> dict: mesh = self.mesh if isinstance(focus, dict): return {"center": list(map(float, focus["point"])), "radius": float(focus["radius"]), "label": focus.get("label", "detail"), "method": "explicit"} if focus in ("auto", "head", "face"): c, r = planning.head_region(mesh) out = {"center": c.tolist(), "radius": r, "label": "face", "method": "head-heuristic"} det = planning.detect_face(self.gl, mesh, c, r, front_azimuth=float(self.settings.get("front_azimuth") or 0)) if det is None: # busts: the top slice is only the skull cap, look at the upper body instead lo, hi = mesh.bounds h = hi[1] - lo[1] det = planning.detect_face(self.gl, mesh, (lo + hi) / 2 + np.array([0, 0.2 * h, 0]), 0.35 * h, front_azimuth=float(self.settings.get("front_azimuth") or 0)) lo, hi = mesh.bounds h = float(hi[1] - lo[1]) fa = float(self.settings.get("front_azimuth") or 0) for _ in range(2): # a box covering the whole beard/body: look again, zoomed in on it if det is None or det["world_width"] <= 0.25 * h: break finer = planning.detect_face(self.gl, mesh, np.array(det["point"]), 0.6 * det["world_width"], front_azimuth=fa) if finer is None or finer["world_width"] >= det["world_width"]: break det = finer if det is not None: p = np.array(det["point"]) # a head is ~1.8x as wide as the detected face box; its centre sits behind the face surface. # Even stylised figures (gnomes, chibi) keep the head radius within ~6-20 % of the height. r_face = 0.9 * det["world_width"] radius = float(np.clip(max(r * 0.8, r_face), 0.06 * h, 0.2 * h)) out["center"] = (p + np.array(det["forward"]) * 0.45 * radius).tolist() out["radius"] = float(radius) out["method"] = "face-detected" out["face_box_px"] = det["box_px"] return out raise ValueError(f"focus must be 'auto'/'head' or {{'point': [x,y,z], 'radius': r}}, got {focus!r}") def add_view(self, name: str, eye=None, target=None, fov: float = 40.0, kind: str = "custom", priority: float = 1.0, camera: dict | None = None, focus: dict | None = None, prompt_hint: str = "", index: int | None = None) -> dict: """Add a camera: explicit eye/target, a camera dict, or focus={'point','radius'[, 'direction']}.""" if any(v.name == name for v in self.views): raise ValueError(f"view {name!r} exists") size = int(self.settings["view_size"]) if camera: cam = Camera.from_dict({**camera, "width": camera.get("width", size), "height": camera.get("height", size)}) elif focus: cam = self.focus_camera(focus, size) else: cam = Camera.look_at(eye, target, fov=fov, width=size, height=size) v = View(name, cam, kind=kind, priority=priority, prompt_hint=prompt_hint) if index is None: self.views.append(v) else: self.views.insert(index, v) self.save() return v.to_dict() def set_view(self, name: str, **kw) -> dict: """Change enabled / priority / prompt_extra / reference(path) / seed / prompt_hint of a view.""" v = self.view(name) for k, val in kw.items(): if val is None: continue if k == "reference": val = self._import_file(val, "refs") if not hasattr(v, k) or k in ("name", "camera", "image", "status"): raise KeyError(f"cannot set {k!r}") setattr(v, k, val) self.save() return v.to_dict() def remove_view(self, name: str) -> dict: v = self.view(name) self.views.remove(v) self.save() return {"removed": name} def focus_camera(self, focus: dict, size: int | None = None) -> Camera: """Camera framing a sphere (point, radius) from the average surface normal (or a given direction).""" size = size or int(self.settings["view_size"]) c = np.asarray(focus["point"], np.float64) r = float(focus.get("radius", 0.1 * self.mesh.radius)) fov = float(focus.get("fov", 40.0)) if focus.get("direction") is not None: d = np.asarray(focus["direction"], np.float64) elif focus.get("eye") is not None: d = np.asarray(focus["eye"], np.float64) - c else: mesh = self.mesh near = np.linalg.norm(mesh.vertices - c, axis=1) < r if near.sum() < 3: near = np.argsort(np.linalg.norm(mesh.vertices - c, axis=1))[:16] d = mesh.normals[near].mean(0) if np.linalg.norm(d) < 1e-6: d = c - mesh.center d = d / max(np.linalg.norm(d), 1e-12) dist = r / np.tan(np.radians(fov) / 2) * 1.1 # avoid putting the camera behind other geometry (important inside environments) try: import trimesh tm = trimesh.Trimesh(self.mesh.vertices, self.mesh.faces, process=False) o = c + d * r * 0.05 hits, _, _ = tm.ray.intersects_location([o], [d], multiple_hits=False) if len(hits): t = float(np.linalg.norm(hits[0] - o)) if t < dist: dist = max(t * 0.85, r * 0.5) fov = float(min(100.0, 2 * np.degrees(np.arctan(r * 1.1 / dist)))) except Exception: # pragma: no cover - rays are best effort pass up = (0, 1, 0) if abs(d[1]) < 0.95 else (0, 0, -1) return Camera.look_at(c + d * dist, c, up=up, fov=fov, width=size, height=size, near=max(1e-4, 0.02 * dist)) # ================================================================== fusion def _state_key(self, res: int, upto: int | None = None, layers: bool = True) -> str: h = hashlib.sha1() h.update(json.dumps([res, upto, layers, self.settings["fusion"]]).encode()) for v in self.views[:upto]: if self._usable(v): p = self.root / v.image h.update(f"{v.name}{v.priority}{p.stat().st_mtime_ns if p.exists() else 0}".encode()) h.update(json.dumps(v.camera.to_dict()).encode()) if layers: for L in self.data.get("layers", []): if L.get("enabled", True): h.update(json.dumps(L, sort_keys=True, default=str).encode()) return h.hexdigest() def _valid_mask(self, v: View, img: np.ndarray, depth: np.ndarray) -> np.ndarray | None: """Pixels of a generated object view that may be projected: the image's own foreground (cached in views/<name>/valid.png). Keeps background-coloured pixels of a re-framed/cropped output off the mesh.""" inside = None for name in ("rescue_inside.png", "new_only.png", "contradicts.png", "spill.png"): # warp filler of a # rescued view; partial views; parts that repaint what earlier views painted and paint spilled onto a # neighbouring part (both stored inverted) ri = self.root / "views" / v.name / name if ri.exists(): mk = np.asarray(Image.open(ri).convert("L"), np.float32) / 255 if name in ("contradicts.png", "spill.png"): mk = 1.0 - mk if mk.shape != depth.shape: mk = cv2.resize(mk, depth.shape[::-1], interpolation=cv2.INTER_LINEAR) inside = mk if inside is None else inside * mk if self.mode == "environment": return inside f = self.root / "views" / v.name / "valid.png" if f.exists() and f.stat().st_mtime >= (self.root / v.image).stat().st_mtime: m = np.asarray(Image.open(f).convert("L"), np.float32) / 255 m = m if m.shape == depth.shape else cv2.resize(m, depth.shape[::-1], interpolation=cv2.INTER_NEAREST) return m if inside is None else m * inside from .validate import foreground_mask fg = foreground_mask(img, depth) if fg is None: return inside m = cv2.erode(fg.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(np.float32) f.parent.mkdir(parents=True, exist_ok=True) Image.fromarray((m * 255).astype(np.uint8)).save(f) return m if inside is None else m * inside def _project_view(self, v: View, res: int, acc: Accumulator, idx: int) -> dict: img = _img_to_np(self.root / v.image) cam = v.camera.resized(img.shape[1], img.shape[0]) depth = self.gl.render_view(self.mesh, cam, mode="clay")["depth"] mask = self._valid_mask(v, img, depth) tiles = project_view(self.gl, self.mesh, cam, img, res, self.fusion(), depth=depth, priority=v.priority, mask=mask) return acc.add(tiles, idx) def _apply_layers(self, color: np.ndarray, alpha: np.ndarray, res: int) -> int: changed = 0 for L in self.data.get("layers", []): if not L.get("enabled", True): continue img = _img_to_np(self.root / L["image"]) mask = np.asarray(Image.open(self.root / L["mask"]).convert("L"), np.float32) / 255 cam = Camera.from_dict(L["camera"]).resized(img.shape[1], img.shape[0]) depth = self.gl.render_view(self.mesh, cam, mode="clay")["depth"] tiles = project_view(self.gl, self.mesh, cam, img, res, self.fusion(), depth=depth, mask=mask, overlay_mode=True) changed += overlay(color, alpha, tiles, strength=float(L.get("strength", 1.0))) return changed def fuse(self, res: int | None = None, layers: bool = True, stats: bool = True, use_cache: bool = True) -> dict: """Blend all enabled, generated views (then retouch layers) into a texel-space texture.""" res = int(res or self.settings["texture_size"]) key = self._state_key(res, None, layers) if use_cache and self._tex_cache.get("key") == key: return self._tex_cache["value"] acc = Accumulator(res, self.fusion().sharpness) used = [] for i, v in enumerate(self.views): if self._usable(v): self._project_view(v, res, acc, i) used.append(v.name) color = acc.color() alpha = acc.alpha.copy() seams = self._blend_seams(color, alpha, res) if used and self.settings.get("seam_blend", True) \ and self.mode != "environment" else 0 metal = self._flatten_metal(color, alpha, res) if used else 0 changed = self._apply_layers(color, alpha, res) if layers else 0 covered = (acc.den > 0) | (alpha > 0.01) inside = self._fill_inside(color, alpha, covered, res) if used else 0 out = {"color": color, "alpha": alpha, "covered": covered, "acc": acc, "views": used, "layer_texels": changed, "inside_filled": inside, "metal_flattened": metal, "seam_texels": seams, "res": res} self._tex_cache = {"key": key, "value": out} return out def _blend_seams(self, color: np.ndarray, alpha: np.ndarray, res: int, max_res: int = 1024, sigma: float = 0.02) -> int: """Two-band fusion for evenly painted parts: their low frequencies blended softly across the views. Each view paints its own shading into the albedo; where the sharp blend hands a surface from one view to the next, a teddy bear's fur shows a seam down its back (two views 5 CIELAB lightness apart). The views, blurred (``sigma`` of the image), are fused twice at up to ``max_res``: with the usual sharp weights and with soft ones (exponent 1); the texture is multiplied by their ratio (0.7-1.4), which leaves the detail of the best view and removes the step. Patterned parts (_plain_part_colors) are left alone: there the ratio carries the other views' motifs and washes out a vase's landscape. Returns the texels changed.""" plain = np.isfinite(self._plain_part_colors(color, alpha)).all(1) if not plain.any(): return 0 lr = min(res, max_res) fp = self.fusion() sharp, soft = Accumulator(lr, fp.sharpness), Accumulator(lr, 1.0) for i, v in enumerate(self.views): if not self._usable(v): continue img = _img_to_np(self.root / v.image) cam = v.camera.resized(img.shape[1], img.shape[0]) depth = self.gl.render_view(self.mesh, cam, mode="clay")["depth"] mask = self._valid_mask(v, img, depth) fg = (depth > 0).astype(np.float32) sig = sigma * max(img.shape[:2]) wb = np.maximum(cv2.GaussianBlur(fg, (0, 0), sig), 1e-6)[..., None] blur = (cv2.GaussianBlur(img * fg[..., None], (0, 0), sig) / wb).astype(np.float32) tiles = list(project_view(self.gl, self.mesh, cam, blur, lr, fp, depth=depth, priority=v.priority, mask=mask)) sharp.add(tiles, i) soft.add(tiles, i) valid = sharp.den > 0 ratio = np.where(valid[..., None], np.clip(soft.color() / np.maximum(sharp.color(), 1e-3), 0.7, 1.4), 1.0) ratio = push_pull_fill(ratio.astype(np.float32), valid.astype(np.float32)) if lr != res: ratio = cv2.resize(ratio, (res, res), interpolation=cv2.INTER_LINEAR) tm = self._texel_materials(res) sel = (tm >= 0) & plain[np.clip(tm, 0, len(plain) - 1)] & (alpha > 0) color[sel] = np.clip(color[sel] * ratio[sel], 0, 1) return int(sel.sum()) def texture(self, res: int | None = None, fill: bool = True) -> np.ndarray: st = self.fuse(res) if not fill: return st["color"] return self.filled(st) # ============================================================== generation def _condition(self, cam: Camera, color: np.ndarray, alpha: np.ndarray, covered: np.ndarray, best_cos: np.ndarray | None = None) -> dict: """Render what the generator sees: projected texture where it exists, white clay elsewhere.""" tex = push_pull_fill(color, covered.astype(np.float32)) cover = smoothstep(0.02, 0.35, alpha) * covered env = self.mode == "environment" if best_cos is not None and not env and self.settings.get("hide_grazed_paint", True): # faint paint from views that only grazed the surface (a starburst drawn on a skateboard's grip tape # from 10 degrees, smeared along the deck) is not shown to a view that sees it far more head-on: shown # half transparent, it was kept as established paint by the views from above g = self.gl.uv_gbuffer(self.mesh, alpha.shape[0]) d = cam.eye_np.astype(np.float32)[None, None] - g["position"][..., :3] cos = np.abs((d * g["normal"][..., :3]).sum(-1)) / np.maximum(np.linalg.norm(d, axis=-1), 1e-9) cover = np.where((alpha < 0.5) & (cos > best_cos + 0.3), 0.0, cover) del g, d, cos bg = self.settings["sky_color"] if env else self.settings["background"] guide = self._color_guide_tex(color.shape[0]) out = self.gl.render_view(self.mesh, cam, mode="condition", albedo=tex, cover=cover.astype(np.float32), background=tuple(bg), ssaa=2, base=guide) cov = self.gl.render_view(self.mesh, cam, mode="coverage", cover=cover.astype(np.float32), gbuffer=True) # well painted (QA's "well covered" level): what a partially accepted view must not paint over strong = self.gl.render_view(self.mesh, cam, mode="coverage", gbuffer=False, cover=(smoothstep(0.5, 0.7, alpha) * covered).astype(np.float32))["color"][..., 0] clay = self.gl.render_view(self.mesh, cam, mode="clay", gbuffer=False)["color"][..., 0] fgm = cov["depth"] > 0 border = np.concatenate([fgm[0], fgm[-1], fgm[:, 0], fgm[:, -1]]) fg = cov["depth"] > 0 cover_px = np.where(fg, cov["color"][..., 0], 0.0).astype(np.float32) frac = float(cover_px[fg].mean()) if fg.any() else 0.0 img = out["color"] if env and self.settings.get("skymap"): img = self._sky_background(cam, img, out["depth"]) caption = scene_caption(cov["depth"], cov["normal"]) if env else "" if not env and self.settings.get("fill_islands", True): from .validate import fill_unpainted_islands # without guide colours the unpainted surface is plain white clay, which the model may keep as a white # sheet even over a third of a board seen from above: larger enclosed regions are shown in their paint share = self.settings.get("fill_islands_max_share") or (0.03 if guide is not None else 0.6) img = fill_unpainted_islands(img, cover_px, cov["face"], self.mesh.face_material, max_share=float(share)) out_d = {"image": img, "depth": out["depth"], "coverage": frac, "cover_px": cover_px, "clay": clay, "normal": cov["normal"], "cropped": bool(not env and border.mean() > 0.03), "caption": caption, "face": cov["face"], "color_guide": guide is not None, "strong_px": np.where(cov["depth"] > 0, strong, 0.0).astype(np.float32)} if best_cos is not None: # how head-on the surface was painted so far vs. how this camera sees it bc = self.gl.render_view(self.mesh, cam, mode="coverage", gbuffer=False, cover=best_cos.astype(np.float32))["color"][..., 0] vdir = cam.eye_np[None, None] - cov["position"] vdir /= np.maximum(np.linalg.norm(vdir, axis=-1, keepdims=True), 1e-9) out_d["bestcos_px"] = np.where(fg, bc, 0.0).astype(np.float32) out_d["cos_px"] = np.where(fg, np.abs((vdir * cov["normal"]).sum(-1)), 0.0).astype(np.float32) return out_d def _texel_materials(self, res: int) -> np.ndarray: """Material of each texel of a ``res`` atlas (-1 outside the charts).""" cache = getattr(self, "_texel_mat_cache", None) if cache is None or cache[0] != res: fid = self.gl.uv_gbuffer(self.mesh, res)["face"] cache = self._texel_mat_cache = (res, np.where(fid >= 0, self.mesh.face_material[np.clip(fid, 0, None)], -1)) return cache[1] def filled(self, st: dict) -> np.ndarray: """The fused texture with its unpainted texels filled, each part from its own paint (fill_by_part).""" color, covered = st["color"], st["covered"].astype(np.float32) if len(self.mesh.materials) < 2: return push_pull_fill(color, covered) return fill_by_part(color, covered, self._texel_materials(color.shape[0])) def _painted_part_colors(self, color: np.ndarray, alpha: np.ndarray) -> np.ndarray: """Median colour of each material as painted so far (NaN where too little is painted).""" tm = self._texel_materials(color.shape[0]) out = np.full((max(len(self.mesh.materials), 1), 3), np.nan, np.float32) good = alpha >= 0.5 for m in range(len(out)): sel = good & (tm == m) if sel.sum() >= 200: out[m] = np.median(color[sel], axis=0) return out def _plain_part_colors(self, color: np.ndarray, alpha: np.ndarray, max_far: float = 0.15) -> np.ndarray: """_painted_part_colors, NaN for parts already painted with a pattern (more than ``max_far`` of their painted texels 25 CIELAB units from the median: a teapot's flowers 23 %, a vase's landscape 47 %, a matryoshka 32-72 %; a shaded, dappled white horse 10 %), where new motifs are that pattern, not a design invented on a plain part.""" out = self._painted_part_colors(color, alpha) tm = self._texel_materials(color.shape[0]) good = alpha >= 0.5 for m in np.nonzero(np.isfinite(out).all(1))[0]: sel = good & (tm == m) idx = np.nonzero(sel.ravel())[0] if len(idx) > 20000: idx = idx[:: len(idx) // 20000] px = color.reshape(-1, 3)[idx].astype(np.float32) labs = cv2.cvtColor(np.clip(np.vstack([px, out[m][None]]), 0, 1).reshape(-1, 1, 3), cv2.COLOR_RGB2LAB) labs = labs.reshape(-1, 3) if float((np.linalg.norm(labs[:-1] - labs[-1], axis=1) > 25).mean()) > max_far: out[m] = np.nan return out def _material_colors(self) -> np.ndarray | None: """sRGB colour per material for the colour guide (None when off or not informative).""" mode = self.settings.get("color_guide", "auto") if not mode or not self.mesh.materials: return None cols = [] for m in self.mesh.materials: c = m.get("base_color") img = self.root / "mesh" / f"source_albedo_{self.mesh.materials.index(m)}.png" if img.exists(): # textured material: its mean colour c = (np.asarray(Image.open(img).convert("RGB").resize((32, 32)), np.float32) / 255).reshape(-1, 3).mean(0) c = np.clip(c, 0, 1) ** 2.2 # stored sRGB -> linear, converted back below cols.append(np.clip(np.asarray(c if c is not None else (0.8, 0.8, 0.8), np.float64)[:3], 0, 1)) srgb = np.array(cols) ** (1 / 2.2) # glTF base colours are linear used = np.unique(self.mesh.face_material) u = srgb[used] spread = float(np.max(np.linalg.norm(u[:, None] - u[None], axis=-1))) if len(u) > 1 else 0.0 if mode == "auto" and spread < 0.15: return None return 0.22 + 0.78 * srgb # lift dark colours so the shading still shows the shape def _shiny_materials(self) -> set[int]: """Polished metal and glass: the image model paints their reflections or what shows through, not their colour.""" out = set() for i, m in enumerate(self.mesh.materials): ext = (m.get("extensions") or {}).get("KHR_materials_transmission") or {} polished = float(m.get("metallic") or 0.0) >= 0.5 and float(m.get("roughness", 1.0)) <= 0.5 if polished or float(ext.get("transmissionFactor") or 0.0) > 0: out.add(i) return out def _color_guide_tex(self, res: int) -> np.ndarray | None: cache = getattr(self, "_guide_cache", None) if cache is not None and cache[0] == res: return cache[1] cols = self._material_colors() tex = None if cols is not None: uvg = self.gl.uv_gbuffer(self.mesh, res) fid = uvg["face"] tex = np.ones((res, res, 3), np.float32) valid = fid >= 0 tex[valid] = cols[self.mesh.face_material[fid[valid]]] tex = push_pull_fill(tex, valid.astype(np.float32)) # bleed into gutters for bilinear lookups self._guide_cache = (res, tex) return tex def _part_labels(self) -> tuple[np.ndarray, list[str], list[str]] | None: """Per-face part index for prompt layout hints: user-described material/object names, else the file's meaningful material names (or object names) when there are at least two.""" from .prompts import humanize, meaningful cfg = self.settings.get("part_prompts", "auto") if not cfg: return None m = self.mesh mats = [x.get("name") or "" for x in m.materials] objs = [x.get("name") or "" for x in m.parts] if m.face_part is not None else [] if isinstance(cfg, dict) and cfg: keys = [k for k in cfg] kidx = {k.lower(): j for j, k in enumerate(keys)} lab = np.full(len(m.faces), -1, np.int64) for names, per_face in ((mats, m.face_material), (objs, m.face_part)): # objects override materials if per_face is None or not names: continue table = np.array([kidx.get(n.lower(), -1) for n in names]) hit = table[per_face] lab = np.where(hit >= 0, hit, lab) used = sorted(set(lab[lab >= 0].tolist())) # unknown names are warned about by the service, not used if not used: return None remap = np.full(len(keys) + 1, -1, np.int64) remap[used] = np.arange(len(used)) return remap[lab], [keys[j] for j in used], [cfg[keys[j]] for j in used], True for names, per_face in ((mats, m.face_material), (objs, m.face_part)): keep = [i for i, n in enumerate(names) if meaningful(n)] if len({humanize(names[i]) for i in keep}) >= 2: idx = {i: j for j, i in enumerate(keep)} lab = np.array([idx.get(int(i), -1) for i in range(len(names))])[per_face] return lab, [names[i] for i in keep], [humanize(names[i]) for i in keep], False return None def _layout(self, face: np.ndarray, cam: Camera | None = None) -> tuple[str, str]: """(layout sentence for the view prompt, negative prompt with the named parts out of view).""" from .prompts import listed_parts, part_layout pl = getattr(self, "_pl_cache", False) if pl is False: pl = self._pl_cache = self._part_labels() self._part_area_cache = None # each part's share of the surface, for listed_parts self._part_fronts_cache = None neg = self.settings.get("negative_prompt", "") or "" if pl is None: return "", neg lab, names, desc, explicit = pl labels = np.where(face >= 0, lab[np.clip(face, 0, len(lab) - 1)], -1) # full res: tiny parts count # with descriptions per part the prompt names only what this view shows; with names alone (auto) the # user's free-text prompt already describes everything, so only out-of-view parts are used (negative) area = getattr(self, "_part_area_cache", None) if area is None: v, f = self.mesh.vertices, self.mesh.faces fa = 0.5 * np.linalg.norm(np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]]), axis=1) area = self._part_area_cache = np.bincount(lab[lab >= 0], weights=fa[lab >= 0], minlength=len(names)) \ / max(float(fa.sum()), 1e-30) behind = set() if explicit and cam is not None and self.mode == "object": fronts = getattr(self, "_part_fronts_cache", None) if fronts is None: fronts = self._part_fronts_cache = planning.part_fronts(self.mesh, lab, desc) for i, (c, f) in fronts.items(): d = (cam.eye_np - c)[[0, 2]] n = float(np.linalg.norm(cam.eye_np - c)) if np.linalg.norm(d) > 0.25 * n and float(d @ f) / np.linalg.norm(d) < -0.34: # > 110 degrees behind.add(i) text, unseen = part_layout(labels, names, desc if explicit else None, area_share=area, behind=behind) # the free text keeps only what this view shows enough of to be listed: a part seen as a sliver at the # silhouette (a van's side signs from above) is otherwise painted where the model likes, e.g. its # lettering across the roof listed = listed_parts(labels, len(names), area_share=area) self._view_parts = ([names[i] for i in listed], [n for i, n in enumerate(names) if i not in listed]) \ if explicit else None return text, ", ".join([x for x in [neg] + [desc[i] for i in unseen[:8]] if x]) def _sky_background(self, cam: Camera, img: np.ndarray, depth: np.ndarray) -> np.ndarray: sky = getattr(self, "_sky", None) if sky is None: sky = self._sky = _img_to_np(self.root / self.settings["skymap"]) d = cam.ray_dirs() lon = np.arctan2(d[..., 0], -d[..., 2]) lat = np.arcsin(np.clip(d[..., 1], -1, 1)) u = ((lon / (2 * np.pi) + 0.5) * (sky.shape[1] - 1)).astype(np.float32) vv = ((0.5 - lat / np.pi) * (sky.shape[0] - 1)).astype(np.float32) bg = cv2.remap(sky, u, vv, cv2.INTER_LINEAR) if bg.shape[:2] != img.shape[:2]: bg = cv2.resize(bg, img.shape[1::-1]) dd = depth if depth.shape == img.shape[:2] else cv2.resize(depth, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) return np.where((dd > 0)[..., None], img, bg) def _references(self, v: View, done: list[View]) -> list[tuple[Image.Image, str]]: refs = [] if self.settings.get("style_reference"): refs.append((Image.open(self.root / self.settings["style_reference"]).convert("RGB"), "global style reference: materials, colors and look")) if v.reference: refs.append((Image.open(self.root / v.reference).convert("RGB"), "reference seen from about the same angle as this view")) n = int(self.settings.get("consistency_refs", 0)) # the first view sets the design; then the latest ones (neighbours in plan order) picks = ([done[0]] + [d for d in done[1:]][-(n - 1):] if n > 1 else done[:1]) if n and done else [] for d in picks: refs.append((Image.open(self.root / d.image).convert("RGB"), f"already generated {d.name} view")) return refs def _swatch_reference(self, v: View, cond: dict, done: list[View]) -> tuple[Image.Image, str] | None: """A close-up of the part this view has to paint most of, as an earlier view painted it: the largest square inside that part's region, cut from the earlier view that shows the part largest. It carries the part's pattern and its density without the object's layout: a whole earlier view as reference made a teapot's handle side floral instead of plain, but also made a jukebox's plain back copy the front's arch and lit panels. None when the view has little new surface, no earlier view shows the part, or it is too small.""" if self.mode == "environment" or not done or cond.get("face") is None or cond.get("cover_px") is None: return None pl = self._part_labels() lab_face = pl[0] if pl else self.mesh.face_material descs = pl[2] if pl else [m.get("name") or "the material" for m in self.mesh.materials] face = cond["face"] cover = cond["cover_px"] if cover.shape != face.shape: cover = cv2.resize(cover, face.shape[::-1], interpolation=cv2.INTER_NEAREST) lab = np.where(face >= 0, lab_face[np.clip(face, 0, None)], -1) new = (lab >= 0) & (cover < 0.5) if new.sum() < 0.15 * max(int((face >= 0).sum()), 1): return None part = int(np.bincount(lab[new]).argmax()) best = None for d in done: if not d.image: continue cam = d.camera.resized(256, 256) f = self.gl.render_view(self.mesh, cam, mode="clay")["face"] m = (f >= 0) & (lab_face[np.clip(f, 0, None)] == part) if m.sum() < 400: continue dist = cv2.distanceTransform(m.astype(np.uint8), cv2.DIST_L2, 5) if best is None or dist.max() > best[0]: y, x = np.unravel_index(int(dist.argmax()), dist.shape) best = (float(dist.max()), y, x, d) if best is None or best[0] < 0.06 * 256: return None if self.settings.get("swatch_refs", "auto") == "auto": from .prompts import describes_scene if describes_scene(f"{descs[part]} {self.settings.get('prompt') or ''}"): return None # each view would repeat the close-up's pagodas instead of continuing the scene r, y, x, d = best img = _img_to_np(self.root / d.image) h, w = img.shape[:2] half = 0.7 * r # the square inscribed in the largest inside circle x0, x1 = int(max(0, (x - half) * w / 256)), int(min(w, (x + half) * w / 256)) y0, y1 = int(max(0, (y - half) * h / 256)), int(min(h, (y + half) * h / 256)) sw = _np_to_img(img[y0:y1, x0:x1]).resize((512, 512), Image.LANCZOS) return sw, str(descs[part]) def condition_image(self, name: str) -> dict: """Write the conditioning render (+ prompt) of a view, e.g. to generate it with an external tool.""" v = self.view(name) st = self._sequential_state(exclude=name) cond = self._condition(v.camera, st["color"], st["alpha"], st["covered"]) p = _save(cond["image"], self.root / "views" / v.name / "condition.png") prompt = self._view_prompt(v, cond["coverage"], 0) (self.root / "views" / v.name / "prompt.txt").write_text(prompt) return {"condition": str(p), "prompt": prompt, "coverage": cond["coverage"]} def _sequential_state(self, exclude: str | None = None) -> dict: res = int(self.settings["preview_texture_size"]) acc = Accumulator(res, self.fusion().sharpness) for i, v in enumerate(self.views): if self._usable(v) and v.name != exclude: self._project_view(v, res, acc, i) color, alpha = acc.color(), acc.alpha.copy() self._apply_layers(color, alpha, res) return {"color": color, "alpha": alpha, "covered": (acc.den > 0) | (alpha > 0.01), "acc": acc} def _view_prompt(self, v: View, coverage: float, n_refs: int, cropped: bool = False, retry: int = 0, caption: str = "", layout: str = "", color_guide: bool = False, retry_painted: bool = False, ref_note: str = "", retry_parts: list[tuple[str, str]] | None = None) -> str: s = self.settings hint = v.prompt_hint base = s.get("focus_prompt") if v.kind == "focus" and s.get("focus_prompt") else s["prompt"] subject = s.get("subject", "") vp = getattr(self, "_view_parts", None) if layout else None if vp: # described parts: the free text must not name parts this view does not show from .prompts import strip_unseen base = strip_unseen(base, vp[1], vp[0]) subject = strip_unseen(subject.split(" with ")[0], vp[1], vp[0]) if not base and layout: base = "the materials of the parts listed below" prompt = base + (f", {v.prompt_extra}" if v.prompt_extra else "") if v.kind in ("focus", "gap"): # "(full body, T-pose)"-style qualifiers contradict a close-up subject = re.sub(r"\s*\([^)]*\)", "", subject) label = v.name.rsplit("-", 1)[0] if v.kind == "focus" else "head" label = "face and head" if label == "face" else label ph = "" # objects with described parts: the list of parts each view shows beats a front/back guess that assumes # the file's +Z front (a shield modelled facing -Z was told "the front is not visible" on its crest view) if self.mode != "environment" and v.kind != "focus" and not (self.mode == "object" and layout): d = v.camera.eye_np - np.asarray(v.camera.target, np.float64) d /= max(np.linalg.norm(d), 1e-12) az = float(np.degrees(np.arctan2(d[0], d[2]))) - float(s.get("front_azimuth") or 0.0) el = float(np.degrees(np.arcsin(np.clip(d[1], -1, 1)))) from .prompts import pose_hint ph = pose_hint(az, el, character=self.mode == "character") return view_prompt(prompt, coverage=coverage, kind=v.kind, hint=hint, lighting=s["lighting"], subject=subject, environment=self.mode == "environment", n_refs=n_refs, raw_prompt=bool(s.get("raw_prompt")), cropped=cropped, retry=retry, focus_label=label, caption=caption, pose_hint=ph, layout=layout, color_guide=color_guide, retry_painted=retry_painted, ref_note=ref_note, retry_parts=retry_parts) def _merged_names(self, merged: list) -> list[tuple[str, str]]: """Readable names of the material pairs a view painted as one (left out when the file's names are generic).""" from .prompts import humanize, meaningful out = [] for p, q in merged: a, b = (self.mesh.materials[i].get("name") or "" for i in (p, q)) if meaningful(a) and meaningful(b) and humanize(a) != humanize(b): out.append((humanize(a), humanize(b))) return out def generate(self, views: list[str] | None = None, force: bool = False, backend: Any = None, bake: bool = True, progress: Any = None) -> dict: """Generate & project views in plan order. Each view is conditioned on everything projected so far (earlier views, retouches) so neighbouring views stay consistent. Already generated views are kept unless ``force`` (or they are named in ``views`` with force).""" if not (self.settings.get("prompt") or self.settings.get("raw_prompt") or isinstance(self.settings.get("part_prompts"), dict) and self.settings["part_prompts"]): raise ValueError("set a prompt first (configure(prompt=...) or part_prompts={...})") be = self.backend(backend) res = int(self.settings["preview_texture_size"]) params = self.fusion() targets = [v for v in self.views if v.enabled and (views is None or v.name in views) and (force or v.status not in ("generated", "imported"))] tnames = {v.name for v in targets} acc = Accumulator(res, params.sharpness) for i, v in enumerate(self.views): # everything that stays as is is visible from the start if self._usable(v) and v.name not in tnames: self._project_view(v, res, acc, i) results, done = [], [v for v in self.views if self._usable(v) and v.name not in tnames] sequential = bool(self.settings.get("sequential", True)) stopped = None def _emit(r: dict) -> None: # every outcome is reported as it happens (hosted service progress) results.append(r) if progress: progress("view_done", r) for v in targets: t0 = time.time() if progress: progress("view_start", {"view": v.name, "index": targets.index(v), "total": len(targets)}) color, alpha = acc.color(), acc.alpha.copy() self._apply_layers(color, alpha, res) covered = (acc.den > 0) | (alpha > 0.01) if not sequential: # every view starts from plain clay alpha, covered = np.zeros_like(alpha), np.zeros_like(covered) cond = self._condition(v.camera, color, alpha, covered, best_cos=acc.best_cos) if self.settings.get("max_foreign_frac") is not None: cond["part_colors"] = self._painted_part_colors(color, alpha) vdir = self.root / "views" / v.name _save(cond["image"], vdir / "condition.png") refs = self._references(v, done) ref_note = "" if self.settings.get("swatch_refs", "auto") and getattr(be, "max_references", 0) > len(refs): sw = self._swatch_reference(v, cond, done) if sw is not None: sw[0].save(vdir / "swatch.png") refs.append((sw[0], f"close-up of {sw[1]} as already painted")) ref_note = (f"The last additional image is a close-up of {sw[1]} as already painted elsewhere on " "the model. It shows the style, scale and density of its decoration only: continue " "what this render already shows painted, and decorate its untextured surfaces as " "densely as the close-up, without repeating the close-up's motifs or composition.") seed = v.seed if v.seed is not None else int(self.settings["seed"]) + self.views.index(v) src_mesh, src_tex = self.source_mesh() if be.name == "oracle" else (None, None) validate = bool(self.settings.get("validate", True)) tries = 1 + (int(self.settings.get("max_retries", 2)) if validate else 0) # the mock painter's colour field ignores the parts: touching parts always look alike there self._judge_parts = type(be).__name__ != "MockBackend" attempts, best, failed = [], None, None rescue_inside = None partial_best = None # an attempt good enough to paint only the unpainted surface (see _partial_ok) retry_painted = False retry_parts = None # parts the last try painted as one (names), see max_merged_frac parts_best = None # a try failing only on that: kept, merging least, if no try passes view_mask = None if self.settings.get("view_masks") and be.native_mask and cond["coverage"] > 0.02: clay = (cond["cover_px"] < 0.5) & (cond["depth"] > 0) grow = max(3, int(0.012 * max(clay.shape))) clay = cv2.dilate(clay.astype(np.uint8), np.ones((2 * grow + 1,) * 2, np.uint8)) > 0 if clay.mean() > 0.002: view_mask = Image.fromarray((clay * 255).astype(np.uint8)).resize( (v.camera.width, v.camera.height), Image.NEAREST) view_mask.save(vdir / "paint_mask.png") for k in range(tries): layout, negative = self._layout(cond["face"], v.camera) prompt = self._view_prompt(v, cond["coverage"], len(refs), cropped=cond["cropped"], retry=k, caption=cond.get("caption", ""), layout=layout, color_guide=cond.get("color_guide", False), retry_painted=retry_painted, ref_note=ref_note, retry_parts=retry_parts) (vdir / "prompt.txt").write_text(prompt + (f"\n\nNEGATIVE: {negative}" if negative else "")) req = GenRequest(image=_np_to_img(cond["image"]), prompt=prompt, width=v.camera.width, mask=view_mask, height=v.camera.height, seed=seed + 7919 * k, task="view", references=refs, negative_prompt=negative, name=v.name, context={"camera": v.camera, "gl": self.gl, "mesh": self.mesh, "source_mesh": src_mesh, "source_texture": src_tex}) try: out = be.generate(req) except PendingGeneration as exc: failed = ("pending", str(exc)) break except Exception as exc: failed = ("fatal" if getattr(exc, "fatal", False) else "failed", str(exc)[:500]) log.error("view %s failed: %s", v.name, exc) break out.save(vdir / ("raw.png" if k == 0 else f"raw_retry{k}.png")) if getattr(be, "last_meta", None): (vdir / ("backend_meta.json" if k == 0 else f"backend_meta_retry{k}.json")).write_text( json.dumps(be.last_meta, indent=1, default=str)) img, post = self._postprocess(np.asarray(out, np.float32) / 255, cond) post.update(self._validate(img, cond, v)) if not post["accepted"] and self.settings.get("rescue", True) and post.get("reject_reasons") != ["parts"]: from .validate import rescue_alignment ref = cv2.resize(cond["image"], img.shape[1::-1], interpolation=cv2.INTER_AREA) r = rescue_alignment(img, ref) if r is not None: inside = r[1].pop("inside") chk = self._validate(r[0], cond, v) post["rescue"] = {**r[1], **{kk: chk.get(kk) for kk in ("edge_agreement", "silhouette_iou")}, "accepted": chk["accepted"]} if chk["accepted"]: img = r[0] post.update(chk) post.pop("reject_reasons", None) rescue_inside = inside partial = None if not post["accepted"] and self._partial_ok(post): partial = self._unpainted_mask(cond, img.shape[:2]) if partial is not None and self.mode != "environment": partial = self._without_design_continuation(img, cond, partial, color, alpha, post) cost = (getattr(be, "last_usage", None) or {}).get("cost") attempts.append({"seed": seed + 7919 * k, "cost_usd": cost, **{kk: post.get(kk) for kk in ("edge_agreement", "silhouette_iou", "painted_corr", "painted_diff", "painted_chroma_overlap", "painted_contradiction", "merged_frac", "accepted")}, **({"partial": True} if partial is not None else {})}) if partial is not None and (partial_best is None or (post.get("painted_corr") or -1.0) > (partial_best[1].get("painted_corr") or -1.0)): # usable where nothing is painted yet; a retry may still continue the painted pattern partial_best = (img, {**post, "accepted": True, "partial": True}, seed + 7919 * k, rescue_inside, partial) if best is None or (post.get("edge_agreement") or 0) > (best[1].get("edge_agreement") or 0): best = (img, post, seed + 7919 * k, rescue_inside, None) if post["accepted"]: best = (img, post, seed + 7919 * k, rescue_inside, None) break retry_painted = post.get("reject_reasons") == ["painted"] retry_parts = self._merged_names(post.get("merged", [])) if "parts" in post.get("reject_reasons", []) \ else None if post.get("reject_reasons") == ["parts"] and ( parts_best is None or post["merged_frac"] < parts_best[1]["merged_frac"]): kept = {kk: vv for kk, vv in post.items() if kk != "reject_reasons"} parts_best = (img, {**kept, "accepted": True, "parts_kept": True}, seed + 7919 * k, rescue_inside, None) rescue_inside = None log.warning("view %s attempt %d rejected (%s)", v.name, k + 1, {kk: post.get(kk) for kk in ("edge_agreement", "silhouette_iou", "painted_corr", "painted_diff")}) if partial_best is not None and k >= int(self.settings.get("partial_retries", 1)): break if parts_best is not None and not (best is not None and best[1]["accepted"]): if not (v.status in ("generated", "imported") and v.image): # a regeneration keeps its old image best, failed = parts_best, None # every try painted two parts as one: keep the one merging least elif partial_best is not None and not (best is not None and best[1]["accepted"]): best, failed = partial_best, None # no retry continued the painted texture: keep the closest one if failed and failed[0] == "fatal": # e.g. GPU quota exhausted: stop, keep the view planned _emit({"view": v.name, "status": "stopped", "detail": failed[1]}) stopped = (failed[1], [t.name for t in targets[targets.index(v):]]) break if best is None: v.status = failed[0] if failed else "failed" v.meta = {**(v.meta or {}), "error": failed[1] if failed else "no output"} _emit({"view": v.name, "status": v.status, "detail": v.meta["error"]}) self.save() if v.status == "pending" and sequential: break # later views must see this one projected first: resume with the next generate() call continue img, post, used_seed, rescue_inside, partial_mask = best if not post["accepted"] and v.status in ("generated", "imported") and v.image \ and (self.root / v.image).exists(): # a forced regeneration that fails validation must not throw away an accepted image _save(img, vdir / "rejected_latest.png") v.meta = {**(v.meta or {}), "last_regeneration": {"rejected": True, "attempts": attempts}} _emit({"view": v.name, "status": "kept_previous", "attempts": attempts}) log.warning("view %s: regeneration rejected after %d attempts; keeping the previous image", v.name, len(attempts)) self._project_view(v, res, acc, self.views.index(v)) done.append(v) self.save() continue _save(img, vdir / "generated.png") for stale in ("valid.png", "rescue_inside.png", "new_only.png", "contradicts.png", "spill.png"): (vdir / stale).unlink(missing_ok=True) if post["accepted"] and self.settings.get("mask_spills", True) and self.mode != "environment" \ and len(self.mesh.materials) > 1: from .validate import spilled_paint sp = spilled_paint(img, cond["face"], self.mesh.face_material, self._shiny_materials()) if sp is not None and sp.any(): # a touching part's paint, from a view drawn slightly off Image.fromarray((sp * 255).astype(np.uint8)).save(vdir / "spill.png") fgv = cv2.resize(cond["depth"], img.shape[1::-1], interpolation=cv2.INTER_NEAREST) > 0 post["spill_pct"] = round(100 * float(sp[fgv].mean()), 1) if rescue_inside is not None: Image.fromarray((rescue_inside * 255).astype(np.uint8)).save(vdir / "rescue_inside.png") if partial_mask is not None: Image.fromarray((partial_mask * 255).astype(np.uint8)).save(vdir / "new_only.png") elif post["accepted"] and v.kind == "gap" and self.settings.get("mask_contradictions", True) \ and self.mode != "environment": # base views' differences are mostly a pattern's variations: # cutting them out leaves notches in a landscape band from .validate import contradiction_mask cm = contradiction_mask(img, cond) if cm is not None and cm[0].max() > 0: Image.fromarray((cm[0] * 255).astype(np.uint8)).save(vdir / "contradicts.png") fgv = cv2.resize(cond["depth"], img.shape[1::-1], interpolation=cv2.INTER_NEAREST) > 0 post["masked_pct"] = round(100 * float(cm[0][fgv].mean()), 1) v.image = str((vdir / "generated.png").relative_to(self.root)) v.status = "generated" if post["accepted"] else "rejected" v.meta = {**(v.meta or {}), "seed": used_seed, "backend": be.describe(), "coverage_before": cond["coverage"], "seconds": round(time.time() - t0, 1), "attempts": attempts, **post} v.meta.pop("last_regeneration", None) for k in ("reject_reasons", "parts_kept", "merged", "merged_names"): # from an earlier try or run if k not in post: v.meta.pop(k, None) if v.status == "rejected": _emit({"view": v.name, "status": "rejected", "attempts": attempts}) log.warning("view %s rejected after %d attempts; it is excluded from the bake", v.name, len(attempts)) self.save() continue self._project_view(v, res, acc, self.views.index(v)) done.append(v) _emit({"view": v.name, "status": "generated", "image": str(self.root / v.image), "seconds": v.meta["seconds"], "attempts": len(attempts), **post}) self.save() log.info("view %s done (%.1fs)", v.name, time.time() - t0) lowered = self._lower_steep_gaps(targets) if not stopped else [] if lowered: # one more pass for steep gap views the model would not draw from above, aimed lower again = self.generate(lowered, force=True, backend=backend, bake=False, progress=progress) results = [r for r in results if r["view"] not in lowered] + again["results"] self._log("generate", {"views": [r["view"] for r in results], "backend": be.name}) if be.name != self.settings["backend"].get("name") and not isinstance(backend, (dict, str)): self.settings["backend"] = {"name": be.name} # remember which backend produced the views self.save() out = {"results": results, "pending": [r["view"] for r in results if r["status"] == "pending"], "failed": [r["view"] for r in results if r["status"] == "failed"], "rejected": [r["view"] for r in results if r["status"] == "rejected"]} if stopped: out["stopped"] = {"reason": stopped[0], "remaining": stopped[1], "resume": "run `generate --views " + ",".join(stopped[1]) + "` later " "(add --force for views that already had an image); finished views are kept"} if bake and not out["pending"]: out["bake"] = self.bake() return out def _lower_steep_gaps(self, views: list[View], above: float = 50.0, to: float = 40.0) -> list[str]: """Rejected gap views that look down more steeply than ``above`` degrees, re-aimed at ``to`` degrees (same azimuth, target and distance) for one more try. From high above, image models tend to ignore the render and draw the subject from their usual angle (a camper van at 62 degrees came back as a three-quarter photo of a van on all its attempts, at 45 or 35 degrees it followed the geometry every time). Returns the names re-aimed; views already lowered once are left alone.""" if self.mode == "environment" or not self.settings.get("lower_steep_gaps", True): return [] import dataclasses out = [] for v in views: if v.kind != "gap" or v.status != "rejected" or (v.meta or {}).get("lowered_from") is not None: continue tgt = np.asarray(v.camera.target, np.float64) d = v.camera.eye_np - tgt dist = float(np.linalg.norm(d)) el = _elevation(v.camera) if el <= above: continue az, e = np.arctan2(d[0], d[2]), np.radians(to) nd = np.array([np.cos(e) * np.sin(az), np.sin(e), np.cos(e) * np.cos(az)]) v.camera = dataclasses.replace(v.camera, eye=(tgt + nd * dist).tolist()) v.meta = {**(v.meta or {}), "lowered_from": round(el, 1)} v.status = "planned" out.append(v.name) if out: log.info("re-aiming steep rejected gap views lower: %s", out) self.save() return out def _postprocess(self, img: np.ndarray, cond: dict) -> tuple[np.ndarray, dict]: """Optional alignment to the render and color harmonisation with already-projected texture.""" info: dict = {} ref = cv2.resize(cond["image"], img.shape[1::-1], interpolation=cv2.INTER_AREA) depth = cond["depth"] if depth.shape != img.shape[:2]: depth = cv2.resize(depth, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) if self.settings.get("align") == "ecc": img, info["align"] = align_to_render(img, ref, depth) info["edge_alignment_px"] = edge_misalignment(img, depth) info["shading_corr"] = shading_correlation(img, cond) if self.settings.get("harmonize") and cond["coverage"] > 0.05: img, info["harmonize_gain"] = harmonize(img, ref, cond, depth) return img, info def fill_gaps(self, max_views: int = 3, generate: bool = True, backend: Any = None, rounds: int = 1) -> dict: """Smart gap filling after generation: cluster still-uncovered visible surface, add cameras aimed at the largest clusters (walkable eye positions for environments) and generate only those views.""" out = {"rounds": []} for r in range(rounds): res = 1024 st = self.fuse(res) probe = planning.CoverageProbe(self.gl, self.mesh, res=res, params=self.fusion()) rel = self.relevance(res) env = self.mode == "environment" ins = self.inside(res) if ins is not None and self.settings.get("inside", "plain") == "plain": rel = np.where(ins, 0.0, rel) imp = self.importance(res) if env else None weights = planning.pvs_weights(imp) if imp is not None else None before = self._cov(probe, st["alpha"], rel, weights=weights) specs = planning.plan_gaps(self.gl, self.mesh, st["alpha"], probe, max_views=max_views, size=int(self.settings["view_size"]), environment=env, walkable=self.walkable(), relevant=rel, fov=90.0 if env else 45.0, min_area=0.002, weights=weights) existing = {v.name for v in self.views} new = [] k = 1 for sp in specs: while f"fill{k}" in existing: k += 1 name = f"fill{k}" existing.add(name) new.append(View(name, sp.camera, kind="gap", priority=sp.priority, prompt_hint=sp.prompt_hint, meta=sp.meta)) self.views += new self.save() info = {"coverage_before": round(before, 4), "added": [v.name for v in new]} if generate and new: info["generate"] = self.generate(views=[v.name for v in new], backend=backend, bake=False) st = self.fuse(res) info["coverage_after"] = round(self._cov(probe, st["alpha"], rel, weights=weights), 4) out["rounds"].append(info) if not new: break self._log("fill_gaps", {"rounds": len(out["rounds"])}) self.save() return out def _validate(self, img: np.ndarray, cond: dict, v: View) -> dict: from .validate import score_view depth, normal = cond["depth"], cond["normal"] if depth.shape != img.shape[:2]: depth = cv2.resize(depth, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) normal = cv2.resize(normal, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) sc = score_view(img, depth, normal, self.mode == "environment") from .validate import foreign_content, painted_agreement # a view from below is not held to what the views from the side only grazed (see painted_agreement) pa = painted_agreement(img, cond, spare_grazed=self.mode != "environment" and _elevation(v.camera) < -30.0) sc.update({k: v for k, v in pa.items() if k != "painted_frac" or len(pa) > 1}) fc = {} if self.settings.get("max_foreign_frac") is not None and cond.get("part_colors") is not None \ and cond.get("face") is not None and len(self.mesh.materials) > 1: fc = foreign_content(img, cond["face"], self.mesh.face_material, cond["part_colors"]) sc.update(fc) mp = {} if self.settings.get("max_merged_frac") is not None and cond.get("color_guide") and self.mode != "environment" \ and cond.get("face") is not None and getattr(self, "_judge_parts", True): from .validate import merged_parts mp = merged_parts(img, cond, self.mesh.face_material, self._material_colors(), self._shiny_materials()) sc.update(mp) if mp.get("merged"): # the file's own names, for reports sc["merged_names"] = [[self.mesh.materials[i].get("name") or f"material {i}" for i in pq] for pq in mp["merged"]] if not self.settings.get("validate", True): return {**sc, "accepted": True} ok = True reasons: list[str] = [] s = self.settings if fc and fc.get("foreign_frac", 0) > float(s["max_foreign_frac"]): ok = False # another part's content painted where that part is not modelled (a dial on a plain back) reasons.append("foreign") if mp.get("merged_frac", 0) > float(s["max_merged_frac"] or 0): ok = False # two touching parts painted as one: soft, the try merging least is kept (generate) reasons.append("parts") judged = pa.get("painted_frac", 0) >= float(s.get("min_painted_frac", 0.12)) and "painted_diff" in pa if judged: diff, corr = pa["painted_diff"], pa.get("painted_corr") if diff > float(s.get("max_painted_diff", 0.13)) or ( corr is not None and corr < float(s.get("min_painted_corr", 0.45)) and diff > float(s.get("low_corr_painted_diff", 0.085))): ok = False # contradicts what earlier views painted: likely another viewpoint re-imagined reasons.append("painted") if self.mode != "environment" and corr is not None and corr < float(s.get("contradiction_corr", 0.2)): from .validate import contradiction_mask cm = contradiction_mask(img, cond) if cm is not None: sc["painted_contradiction"] = cm[1] if cm[1] >= float(s.get("max_painted_contradiction", 0.1)) and "painted" not in reasons: ok = False # a tenth of what is painted repainted in other colours, nothing correlating: the # view re-imagined part of the model (a roof slope seen from above drawn as a wall) reasons.append("painted") over = pa.get("painted_chroma_overlap") if over is not None and pa["painted_frac"] >= 0.2 and over < float(s.get("min_painted_chroma_overlap", 0.45)): # other colours where the view should show what is painted (a slate roof slope seen face-on came back # as green siding: brightness gains hid it from painted_diff); never kept as a partial view ok = False reasons.append("colors") if v.kind == "gap" and self.mode != "environment" and s.get("max_edges_moved") is not None \ and cond.get("image") is not None and _elevation(v.camera) > 50.0: from .validate import edges_moved em = edges_moved(img, cond["image"], depth, normal) if em is not None: sc["edges_moved"] = round(em, 3) if em > float(s["max_edges_moved"]): ok = False # redrawn from the model's usual angle: windows where the render shows a roof reasons.append("moved") if self.mode != "environment" and sc.get("silhouette_iou") is not None and not judged: d = v.camera.eye_np - np.asarray(v.camera.target, np.float64) if d[1] / max(np.linalg.norm(d), 1e-12) < -0.17 and sc["silhouette_iou"] < float( s.get("min_silhouette_iou_below", 0.85)): ok = False # looking up from below (> 10 degrees) with nothing painted to compare against reasons.append("below") min_ea = float(self.settings["min_edge_agreement"]) if self.mode == "environment": # interiors: texture edges everywhere, geometry edges sparse -> lower bar min_ea = float(self.settings.get("min_edge_agreement_env", 0.1)) if sc.get("edge_agreement") is not None and sc["edge_agreement"] < min_ea: ok = False reasons.append("edges") if sc.get("silhouette_iou") is not None and sc["silhouette_iou"] < float(self.settings["min_silhouette_iou"]): ok = False reasons.append("silhouette") return {**sc, "accepted": ok, **({"reject_reasons": reasons} if reasons else {})} def _partial_ok(self, post: dict) -> bool: """A view that only disagrees with what is already painted, while matching the geometry very well (each view of a teapot invents its own flowers), may still paint the surface nobody painted yet.""" if post.get("reject_reasons") != ["painted"] or not self.settings.get("partial_views", True): return False if post.get("silhouette_iou") is not None and post["silhouette_iou"] < 0.9: return False min_ea = 0.25 if self.mode == "environment" else 0.4 return (post.get("edge_agreement") or 0) >= min_ea and post.get("painted_diff", 1) <= 0.2 def _without_design_continuation(self, img: np.ndarray, cond: dict, partial: np.ndarray, color: np.ndarray, alpha: np.ndarray, post: dict) -> np.ndarray: """A partial view's new-paint mask minus the continuation of a design it drew over established paint (validate.design_continuation: half a breastplate on a horse's chest).""" from .validate import contradiction_mask, design_continuation cm = contradiction_mask(img, cond) if cm is None or not (cm[0] > 0.5).any(): return partial cont = design_continuation(img, cond, cm[0] > 0.5, partial > 0.5, self.mesh.face_material, self._plain_part_colors(color, alpha)) if not cont.any(): return partial fg = cond["depth"] if cond["depth"].shape == img.shape[:2] else \ cv2.resize(cond["depth"], img.shape[1::-1], interpolation=cv2.INTER_NEAREST) post["continuation_pct"] = round(100 * float(cont.sum() / max(int((fg > 0).sum()), 1)), 1) k = max(3, int(0.012 * max(img.shape[:2]))) | 1 drop = np.clip(cv2.GaussianBlur(cv2.dilate(cont.astype(np.uint8), np.ones((k, k), np.uint8)).astype(np.float32), (0, 0), k / 3) * 1.5, 0, 1) return (partial * (1 - drop)).astype(np.float32) @staticmethod def _unpainted_mask(cond: dict, shape: tuple[int, int]) -> np.ndarray | None: """Feathered mask of the pixels of a view not yet painted well (grazing, thin projections may be replaced), with a thin blending band.""" cover, depth = cond.get("strong_px", cond.get("cover_px")), cond["depth"] if cover is None: return None h, w = shape rs = (lambda a: a if a.shape == (h, w) else cv2.resize(a, (w, h), interpolation=cv2.INTER_NEAREST)) cover, depth = rs(cover), rs(depth) free = cover < 0.5 if cond.get("cos_px") is not None: # also where this camera sees the surface much more head-on free |= rs(cond["cos_px"]) > rs(cond["bestcos_px"]) + 0.15 m = (free & (depth > 0)).astype(np.uint8) if m.sum() < 0.02 * max(int((depth > 0).sum()), 1): return None # nothing new to add k = max(3, int(0.012 * max(h, w))) | 1 m = cv2.dilate(m, np.ones((k, k), np.uint8)).astype(np.float32) return np.clip(cv2.GaussianBlur(m, (0, 0), k / 3), 0, 1) def import_view(self, name: str, image: str | Path, project_now: bool = True) -> dict: """Use an external image for a view (must match the view's conditioning render framing).""" v = self.view(name) vdir = self.root / "views" / v.name vdir.mkdir(parents=True, exist_ok=True) img = Image.open(image).convert("RGB") if img.size != (v.camera.width, v.camera.height): from .backends.base import fit_output img = fit_output(img, v.camera.width, v.camera.height) img.save(vdir / "generated.png") v.image = str((vdir / "generated.png").relative_to(self.root)) v.status = "imported" scores = self.rescore([name])[name] self._log("import_view", {"view": name, "image": str(image)}) self.save() out = {"view": name, "image": str(self.root / v.image), **scores} if not scores.get("accepted", True): out["warning"] = "the image does not line up with the view's geometry; check condition.png framing" return out def rescore(self, views: list[str] | None = None) -> dict: """(Re)compute alignment scores of existing view images (stored in each view's meta).""" from .validate import score_view out = {} for v in self.views: if (views and v.name not in views) or not v.image or not (self.root / v.image).exists(): continue img = _img_to_np(self.root / v.image) g = self.gl.render_view(self.mesh, v.camera.resized(img.shape[1], img.shape[0]), mode="clay") sc = score_view(img, g["depth"], g["normal"], self.mode == "environment") ok = self._validate(img, {"depth": g["depth"], "normal": g["normal"]}, v)["accepted"] v.meta = {**(v.meta or {}), **sc, "accepted": ok} out[v.name] = {**sc, "accepted": ok} self.save() return out # ===================================================================== bake def bake(self, resolution: int | None = None, out_dir: str = "bake", export: bool = True) -> dict: """Fuse everything at ``resolution`` (2048/4096/8192), fill gaps, write maps and export the GLB.""" t = time.time() res = int(resolution or self.settings["texture_size"]) st = self.fuse(res) filled = self.filled(st) od = self.root / out_dir od.mkdir(parents=True, exist_ok=True) paths = {"albedo": str(_save(filled, od / "albedo.png"))} _save(np.repeat(st["alpha"][..., None], 3, -1), od / "coverage.png") paths["coverage"] = str(od / "coverage.png") paths["view_ids"] = str(_save(_id_colors(st["acc"].best_id), od / "view_ids.png")) step = max(1, res // 1024) # which view painted each texel, for pick(): "painted_by" np.save(od / "view_ids.npy", st["acc"].best_id[::step, ::step]) (od / "view_ids.json").write_text(json.dumps([v.name for v in self.views])) dis = st["acc"].disagreement() paths["disagreement"] = str(_save(np.repeat(np.clip(dis * 4, 0, 1)[..., None], 3, -1), od / "disagreement.png")) stats = self.inspect(qa_res=min(res, 1024), write=False)["stats"] if export: paths["glb"] = str(export_glb(self.mesh, _np_to_img(filled), od / "textured.glb", up_axis=self.data["mesh"].get("up_axis", "y"), single=bool(self.settings.get("export_single_mesh")))) info = {"resolution": res, "views_used": st["views"], "layer_texels": st["layer_texels"], "paths": paths, "stats": stats, "seconds": round(time.time() - t, 2)} (od / "bake.json").write_text(json.dumps(info, indent=2)) self._log("bake", {"resolution": res, "coverage": stats.get("coverage")}) self.save() return info # ======================================================================= PBR def pbr_views(self, decomposer, views: list[str] | None = None, force: bool = False, progress=None) -> dict: """Split each usable view into albedo / roughness / metallic maps (views/<name>/pbr_<map>.png), once per view image.""" from .pbr import MAPS done = [] todo = [v for v in self.views if self._usable(v) and (not views or v.name in views)] for k, v in enumerate(todo): src = self.root / v.image outs = [self.root / "views" / v.name / f"pbr_{m}.png" for m in MAPS] if not force and all(o.exists() and o.stat().st_mtime >= src.stat().st_mtime for o in outs): continue maps = decomposer.decompose(Image.open(src).convert("RGB")) for m, o in zip(MAPS, outs): o.parent.mkdir(parents=True, exist_ok=True) maps[m].save(o) done.append(v.name) if progress: progress(k + 1, len(todo), v.name) return {"decomposed": done, "views": [v.name for v in todo]} def fuse_map(self, name: str, res: int) -> tuple[np.ndarray, np.ndarray]: """One PBR map in texel space: each view's pbr_<name>.png projected with the colour's cameras, masks and per-view weights, gaps filled. Returns (map, covered).""" acc = Accumulator(res, self.fusion().sharpness) for i, v in enumerate(self.views): f = self.root / "views" / v.name / f"pbr_{name}.png" if not self._usable(v) or not f.exists(): continue src = _img_to_np(self.root / v.image) img = _img_to_np(f) if img.shape[:2] != src.shape[:2]: img = cv2.resize(img, src.shape[1::-1], interpolation=cv2.INTER_LINEAR) cam = v.camera.resized(src.shape[1], src.shape[0]) depth = self.gl.render_view(self.mesh, cam, mode="clay")["depth"] mask = self._valid_mask(v, src, depth) acc.add(project_view(self.gl, self.mesh, cam, img, res, self.fusion(), depth=depth, priority=v.priority, mask=mask), i) covered = acc.den > 0 return self.filled({"color": acc.color(), "covered": covered}), covered def _metal_priors(self, metal: np.ndarray, res: int) -> dict: """What the materials' names and part prompts say, applied in place: parts described only as metal become metallic, parts described only as something else (wood, paint, bakelite...) not. The decomposer reads glossy paint as metal; the words settle it where they can. Returns {material: prior}.""" from .pbr import metal_prior parts = self.settings.get("part_prompts") if isinstance(self.settings.get("part_prompts"), dict) else {} tm = self._texel_materials(res) out = {} for i, m in enumerate(self.mesh.materials): name = m.get("name") or "" prior = metal_prior(f"{name} {parts.get(name, '')}") if prior is None: continue metal[tm == i] = prior out[name] = prior return out def bake_pbr(self, resolution: int | None = None, out_dir: str = "bake", keep_hue: bool = True) -> dict: """The PBR bake: a de-lit base colour (the decomposed albedo, with the views' hues when ``keep_hue``), roughness, metallic and their glTF metallicRoughness texture (G roughness, B metallic), and textured_pbr.glb. Run pbr_views first.""" from .pbr import keep_view_hue res = int(resolution or self.settings["texture_size"]) od = self.root / out_dir od.mkdir(parents=True, exist_ok=True) colour = self.filled(self.fuse(res)) albedo, cov = self.fuse_map("albedo", res) if not cov.any(): raise RuntimeError("no decomposed views: run pbr_views first") if keep_hue: albedo = keep_view_hue(colour, albedo) rough = self.fuse_map("roughness", res)[0].mean(-1) metal = self.fuse_map("metallic", res)[0].mean(-1) priors = self._metal_priors(metal, res) mr = np.stack([np.ones_like(rough), rough, metal], -1) paths = {"albedo_pbr": str(_save(albedo, od / "albedo_pbr.png")), "roughness": str(_save(np.repeat(rough[..., None], 3, -1), od / "roughness.png")), "metallic": str(_save(np.repeat(metal[..., None], 3, -1), od / "metallic.png")), "metallic_roughness": str(_save(mr, od / "metallic_roughness.png"))} paths["glb_pbr"] = str(export_glb(self.mesh, _np_to_img(albedo), od / "textured_pbr.glb", up_axis=self.data["mesh"].get("up_axis", "y"), single=bool(self.settings.get("export_single_mesh")), metallic_roughness=_np_to_img(mr))) info = {"resolution": res, "paths": paths, "covered": round(float(cov.mean()), 4), "metallic_fraction": round(float((metal[cov] > 0.5).mean()), 4) if cov.any() else 0.0, "roughness_mean": round(float(rough[cov].mean()), 3) if cov.any() else None, "metal_priors": priors} (od / "pbr.json").write_text(json.dumps(info, indent=2)) self._log("bake_pbr", {"resolution": res}) self.save() return info def export(self, path: str | Path | None = None, fmt: str = "glb", resolution: int | None = None, unlit: bool = False) -> dict: tex = _np_to_img(self.texture(resolution)) path = Path(path) if path else self.root / "export" / f"model.{fmt}" path.parent.mkdir(parents=True, exist_ok=True) if fmt == "glb": export_glb(self.mesh, tex, path, unlit=unlit, up_axis=self.data["mesh"].get("up_axis", "y")) elif fmt == "obj": export_obj(self.mesh, tex, path) else: raise ValueError("fmt must be glb or obj") tex.save(path.with_name(path.stem + "_albedo.png")) return {"path": str(path), "texture": str(path.with_name(path.stem + "_albedo.png"))} # ======================================================================= QA def inspect(self, qa_res: int = 1024, write: bool = True, max_suggestions: int = 6) -> dict: """Coverage / quality statistics and suggested retouch regions (holes, stretched, inconsistent).""" from .qa import analyse st = self.fuse(qa_res, use_cache=True) rep = analyse(self, st, max_suggestions=max_suggestions) if write: od = self.root / "inspect" od.mkdir(exist_ok=True) for k, img in rep.pop("maps").items(): _save(img, od / f"{k}.png") (od / "inspect.json").write_text(json.dumps(rep, indent=2, default=_json_default)) rep["dir"] = str(od) else: rep.pop("maps") return rep # ================================================================= retouch def retouch(self, prompt: str = "", mode: str = "repair", view: str | None = None, camera: dict | None = None, focus: dict | None = None, mask: Any = None, capture_size: int | None = None, output_size: int | None = None, softness: float = 0.75, mark: str | None = None, backend: Any = None, seed: int | None = None, color_match: bool = True, name: str | None = None, strength: float = 1.0, grow_px: int = 0, dry_run: bool = False) -> dict: """Local inpainting retouch projected only inside a feathered mask (the rest of the texture is kept). mode: repair (fix artifacts, keep content) | replace (new content from prompt) | upscale (re-imagine a low-res capture at higher resolution, e.g. capture_size=256 -> output_size=1024). camera: view=<name> | camera={eye,target,fov} | focus={point, radius[, direction]}. mask: None/'all' | 'uncovered' | 'low_quality' | path.png | {'sphere': [x,y,z,r]} | {'box': [[..],[..]]} | {'rect': [x0,y0,x1,y1]} | {'circle': [cx,cy,r]} (pixels of the output image). """ from .retouch import run_retouch info = run_retouch(self, prompt=prompt, mode=mode, view=view, camera=camera, focus=focus, mask=mask, capture_size=capture_size, output_size=output_size, softness=softness, mark=mark, backend=backend, seed=seed, color_match=color_match, name=name, strength=strength, grow_px=grow_px, dry_run=dry_run) if dry_run: # dry_run: nothing generated, only aim/aim.png (the capture with the mask outlined) return info self._log("retouch", {"layer": info.get("layer"), "mode": mode, "status": info.get("status")}) self.save() return info def set_layer(self, name: str, enabled: bool | None = None, strength: float | None = None) -> dict: for L in self.data.get("layers", []): if L["name"] == name: if enabled is not None: L["enabled"] = bool(enabled) if strength is not None: L["strength"] = float(strength) self.save() return L raise KeyError(name) def undo_retouch(self) -> dict: """Disable the most recent enabled retouch layer (the 'cancel last modification' action).""" for L in reversed(self.data.get("layers", [])): if L.get("enabled", True): L["enabled"] = False self.save() return {"disabled": L["name"]} return {"disabled": None} # ================================================================== renders def render(self, out_dir: str = "renders", turntable: int = 8, size: int = 768, mode: str = "albedo", elevation: float = 15.0, views: list[str] | None = None, compare_source: bool = False, resolution: int | None = None, video: bool = False) -> dict: from .report import render_project return render_project(self, out_dir=out_dir, turntable=turntable, size=size, mode=mode, elevation=elevation, views=views, compare_source=compare_source, resolution=resolution, video=video) def pick(self, pixels: list, view: str | None = None, camera: dict | None = None, size: int | None = None) -> dict: """Map image pixels (x, y; or 0-1 fractions) of a view/camera to 3D points, normals and texel UVs.""" if view: cam = self.view(view).camera elif camera: cam = Camera.from_dict({"width": 1024, "height": 1024, **camera}) else: raise ValueError("give view=<name> or camera={...}") if size: cam = cam.resized(size, int(round(size / cam.aspect))) g = self.gl.render_view(self.mesh, cam, mode="clay") ids_f, names_f = self.root / "bake" / "view_ids.npy", self.root / "bake" / "view_ids.json" ids = np.load(ids_f) if ids_f.exists() and names_f.exists() else None names = json.loads(names_f.read_text()) if ids is not None else [] out = [] for x, y in pixels: if max(x, y) <= 1.0: x, y = x * cam.width, y * cam.height xi, yi = int(np.clip(x, 0, cam.width - 1)), int(np.clip(y, 0, cam.height - 1)) if g["depth"][yi, xi] <= 0: out.append({"pixel": [xi, yi], "hit": False}) continue hit = {"pixel": [xi, yi], "hit": True, "point": g["position"][yi, xi].round(6).tolist(), "normal": g["normal"][yi, xi].round(4).tolist(), "uv": g["uv"][yi, xi].round(6).tolist(), "depth": round(float(g["depth"][yi, xi]), 6)} if ids is not None: # the view whose image won this texel in the last bake u, vv = g["uv"][yi, xi] n = ids.shape[0] k = int(ids[int(np.clip((1.0 - vv) * n, 0, n - 1)), int(np.clip(u * n, 0, n - 1))]) hit["painted_by"] = names[k] if 0 <= k < len(names) else None out.append(hit) return {"camera": cam.to_dict(), "picks": out} # ================================================================== status def status(self) -> dict: s = self.settings return { "root": str(self.root), "mode": self.mode, "mesh": self.data["mesh"], "prompt": s.get("prompt"), "backend": s.get("backend"), "texture_size": s.get("texture_size"), "views": [{"name": v.name, "kind": v.kind, "enabled": v.enabled, "status": v.status, "priority": v.priority, "image": v.image} for v in self.views], "layers": [{k: L.get(k) for k in ("name", "mode", "enabled", "strength", "prompt")} for L in self.data.get("layers", [])], } # ---------------------------------------------------------------- utilities def _json_default(o): if isinstance(o, (np.floating, np.integer)): return o.item() if isinstance(o, np.ndarray): return o.tolist() if isinstance(o, Path): return str(o) raise TypeError(type(o)) def _id_colors(ids: np.ndarray) -> np.ndarray: rng = np.random.default_rng(3) pal = rng.uniform(0.15, 1.0, (max(int(ids.max()) + 2, 2), 3)).astype(np.float32) pal[0] = 0.0 return pal[ids.astype(np.int64) + 1] def edge_misalignment(img: np.ndarray, depth: np.ndarray) -> float | None: """Median distance (px) from silhouette pixels of the render to the nearest strong edge in the image.""" fg = (depth > 0).astype(np.uint8) if fg.mean() > 0.97 or fg.mean() < 0.01: return None # environments: no silhouette to compare against sil = cv2.morphologyEx(fg, cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8)) > 0 gray = (np.clip(img.mean(-1), 0, 1) * 255).astype(np.uint8) edges = cv2.Canny(cv2.GaussianBlur(gray, (0, 0), 1.2), 30, 90) > 0 if not edges.any() or not sil.any(): return None dist = cv2.distanceTransform((~edges).astype(np.uint8), cv2.DIST_L2, 5) return round(float(np.median(dist[sil])), 2) def scene_caption(depth: np.ndarray, normal: np.ndarray) -> str: """Describe what an interior view shows (from the G-buffer), so the model paints rather than invents.""" fg = depth > 0 total = depth.size up = normal[..., 1] parts = [("open sky", (~fg).sum()), ("floor", (fg & (up > 0.8)).sum()), ("ceiling", (fg & (up < -0.8)).sum()), ("walls", (fg & (np.abs(up) < 0.3)).sum())] parts.append(("other objects", total - sum(n for _, n in parts))) desc = ", ".join(f"{name} ({100 * n / total:.0f}%)" for name, n in sorted(parts, key=lambda x: -x[1]) if n / total >= 0.05) inv = np.where(fg, 1.0 / np.maximum(depth, 1e-9), 0.0) d2 = np.abs(np.diff(inv, 2, axis=0))[:, 1:-1] + np.abs(np.diff(inv, 2, axis=1))[1:-1] planar = float(((d2 / np.maximum(inv[1:-1, 1:-1], 1e-9)) < 0.01)[fg[1:-1, 1:-1]].mean()) if fg.any() else 1.0 out = f"This view shows: {desc}." if planar > 0.97: out += (" The visible surfaces are flat: paint them as flat masonry, plaster or tiles; do not paint fake " "niches, windows, doors, curtains or objects onto them.") if (~fg).mean() > 0.02: out += " The open-sky areas stay sky." return out def shading_correlation(img: np.ndarray, cond: dict) -> float | None: """Pearson correlation between the generated luminance and the clay render's shading on surfaces that were still clay. High values mean the model kept the render's lighting (it will be baked into the albedo).""" clay, depth = cond.get("clay"), cond["depth"] if clay is None: return None if clay.shape != img.shape[:2]: clay = cv2.resize(clay, img.shape[1::-1], interpolation=cv2.INTER_AREA) depth = cv2.resize(depth, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) m = depth > 0 cover = cond.get("cover_px") if cover is not None: cv = cover if cover.shape == m.shape else cv2.resize(cover, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) m &= cv < 0.1 if m.sum() < 1000: return None lum = img[m] @ np.array([0.299, 0.587, 0.114]) sh = clay[m] if lum.std() < 1e-6 or sh.std() < 1e-6: return None return round(float(np.corrcoef(lum, sh)[0, 1]), 4) def align_to_render(img: np.ndarray, ref: np.ndarray, depth: np.ndarray, max_shift: float = 0.04) -> tuple: """Correct small global drift of the generated image (ECC affine on gradient magnitudes).""" def grad(a): g = cv2.GaussianBlur(a.mean(-1).astype(np.float32), (0, 0), 2.0) return cv2.magnitude(cv2.Sobel(g, cv2.CV_32F, 1, 0), cv2.Sobel(g, cv2.CV_32F, 0, 1)) h, w = depth.shape s = 512 / max(h, w) small = lambda a: cv2.resize(a, (int(w * s), int(h * s)), interpolation=cv2.INTER_AREA) gi, gr = grad(small(img)), grad(small(ref)) warp = np.eye(2, 3, dtype=np.float32) try: cc, warp = cv2.findTransformECC(gr, gi, warp, cv2.MOTION_AFFINE, (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 100, 1e-5), None, 5) except cv2.error: return img, {"applied": False, "reason": "ecc failed"} shift = np.abs(warp[:, 2]).max() / (512) lin = warp[:, :2] if shift > max_shift or np.abs(lin - np.eye(2)).max() > max_shift: return img, {"applied": False, "reason": "transform too large", "cc": float(cc)} warp[:, 2] /= s out = cv2.warpAffine(img, warp, (w, h), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_REPLICATE) return out, {"applied": True, "cc": round(float(cc), 4), "shift_px": [round(float(x), 2) for x in warp[:, 2]]} def harmonize(img: np.ndarray, ref: np.ndarray, cond: dict, depth: np.ndarray) -> tuple[np.ndarray, list]: """Per-channel gain so the new view matches already-projected texture where both overlap. Only pixels that the conditioning render showed as fully textured are used; the gain is clamped and applied at half strength because the model may legitimately re-shade surfaces. """ cover = cond.get("cover_px") if cover is None or cond["coverage"] < 0.05: return img, [1.0, 1.0, 1.0] if cover.shape != img.shape[:2]: cover = cv2.resize(cover, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) mask = (cover > 0.9) & (depth > 0) & np.isfinite(ref).all(-1) & np.isfinite(img).all(-1) mask = cv2.erode(mask.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0 if mask.sum() < 500: return img, [1.0, 1.0, 1.0] a = img[mask].astype(np.float64) b = ref[mask].astype(np.float64) gain = np.clip((a * b).sum(0) / np.maximum((a * a).sum(0), 1e-9), 0.8, 1.25) gain = 1 + 0.5 * (gain - 1) return np.clip(img * gain[None, None], 0, 1).astype(np.float32), [round(float(g), 4) for g in gain]
"""Project state and the end-to-end workflow: import -> plan -> generate & project -> bake & export -> retouch.
A project is a directory with ``project.json`` plus images. Every step is
non-destructive: views (generated images + cameras) and retouch layers are kept,
and the texture is always re-fused from them, so a single view can be
regenerated/replaced/disabled without touching the others.
"""
from __future__ import annotations
import copy
import hashlib
import json
import logging
import re
import shutil
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import cv2
import numpy as np
from PIL import Image
from . import planning
from .backends import GenRequest, PendingGeneration, get_backend
from .camera import Camera
from .gl import GL
from .mesh import TexMesh, export_glb, export_obj, load_mesh, normalize_tile, orient_up, prepare_uvs
from .projection import Accumulator, FusionParams, fill_by_part, overlay, project_view, push_pull_fill, smoothstep
from .prompts import PRESETS, view_prompt
log = logging.getLogger(__name__)
MODES = ("object", "character", "environment")
DEFAULT_SETTINGS: dict[str, Any] = {
"mode": "object",
"prompt": "",
"subject": "",
"negative_prompt": "",
"lighting": "flat", # flat | soft | natural (see prompts.LIGHTING)
"raw_prompt": False,
# {material or object name: description}; each view prompt lists the parts it shows and where (and which
# are out of view). Without descriptions, meaningful names from the file are used ("auto"); False: off
"part_prompts": "auto",
"export_single_mesh": False,
# show each material's base colour (from the file) in the conditioning render instead of white clay, so parts
# that differ only by material (painted stripes, a door panel) are visible to the image model.
# auto: when at least two materials have clearly different colours
"color_guide": "auto", # GLB with one object and one material (game-ready) instead of the source scene
"style_reference": None,
"backend": {"name": "qwen-turbo"},
"view_size": 1024,
"texture_size": 2048,
"preview_texture_size": 1024,
"seed": 42,
"background": [0.5, 0.5, 0.5],
"sky_color": [0.78, 0.82, 0.88],
"skymap": None,
"harmonize": True,
"align": "none",
"consistency_refs": 0,
"focus_prompt": "", # optional prompt for close-up (focus) views, e.g. only the face/hair part of the prompt
"sequential": True,
"validate": True, # reject generated views that do not line up with the render (re-framed, zoomed out ...)
"max_retries": 2,
"min_edge_agreement": 0.2,
"min_silhouette_iou": 0.55,
"min_silhouette_iou_below": 0.85, # views looking up from below: hard for the model, little painted to check
"min_painted_corr": 0.45, # agreement with texture already painted by earlier views (see painted_agreement):
"low_corr_painted_diff": 0.085, # low correlation counts only with a visible colour difference (flat dark
"max_painted_diff": 0.13, # surfaces give meaningless correlations), and any large difference rejects
"min_painted_frac": 0.12,
# other parts' colours painted on a part (validate.foreign_content); off by default: on clapboard, trim and
# window frames it flags good views too. Stripping out-of-view parts from the prompt fixes the cause.
"max_foreign_frac": None,
# a view that only disagrees with texture already painted, while matching the geometry well, paints just the
# surface not painted yet (see _partial_ok) instead of being rejected
"partial_views": True,
"inside_seen_frac": 0.15, # surface seen by fewer cameras is "inside" (see Project.inside); 0 disables
"inside": "plain", # plain: the inside of vessels gets its material's main colour | paint: views may paint it
"metal": "keep", # keep the painted reflections | flat: mirror-like metal (metallic >= 0.9, roughness <= 0.3)
# gets an even base colour, for renderers with environment lighting (they add the reflections)
"min_painted_chroma_overlap": 0.45, # hue/saturation overlap with the painted pixels (good views 0.59-0.95)
"partial_retries": 1, # extra tries for a view kept as partial, in case one continues the painted pattern
"lower_steep_gaps": True, # a gap view rejected from high above gets one more try from 40 degrees
"hide_grazed_paint": True, # conditioning renders leave out faint paint a view sees far more head-on (_condition)
# objects: ring views that see less than this share of what the broadest one sees, mostly from an angle another
# view sees much better, are generated after the others (Project._narrow_views_last); 0 disables
"narrow_view_share": 0.5,
# gap views from more than 50 degrees above that drew more than this share of the render's edges elsewhere
# (validate.edges_moved: the subject redrawn from its usual angle) are rejected; None disables
"max_edges_moved": 0.2,
# with the colour guide on: a view that painted parts making up more than this share of the object in the
# colour of a touching part with a clearly different guide (validate.merged_parts: a fretboard painted like
# the neck) is retried; if every try does it, the one merging least is kept. None disables
"max_merged_frac": 0.03,
# pixels where a view painted a touching part's colour onto an evenly coloured part (validate.spilled_paint: a