Skip to content

Official Codebase of 3DCodeVerse

Python

texturing: twelve modules become five along the real seams

gaoypeng2e0d0b69eeee
diff --git a/harness/codeverse/cli/texture_cmd.py b/harness/codeverse/cli/texture_cmd.py
index a0f26276..d9e26f53 100644
--- a/harness/codeverse/cli/texture_cmd.py
+++ b/harness/codeverse/cli/texture_cmd.py
@@ -104,8 +104,8 @@ def scene_pack(
ScenePlan = C.lazy("codeverse.contracts.plan", "ScenePlan")
if not isinstance(plan, ScenePlan):
raise C.CliError("scene-pack needs a scene run (plan.json with zones)")
- scene_texture_pack = C.lazy("codeverse.texturing.scene_pack", "scene_texture_pack")
- texture_pack_prompt = C.lazy("codeverse.texturing.scene_pack", "texture_pack_prompt")
+ scene_texture_pack = C.lazy("codeverse.texturing.plan", "scene_texture_pack")
+ texture_pack_prompt = C.lazy("codeverse.texturing.plan", "texture_pack_prompt")
model_id = spec.backends.planner if model is None else model
with C.mutating(ws, what=f"3dcv texture scene-pack {ws.root.name}", action="texture"):
pack = scene_texture_pack(plan, out or ws.public / "textures", _image_model(image_model), model_id, size=size, n_max=n)
diff --git a/harness/codeverse/texturing/__init__.py b/harness/codeverse/texturing/__init__.py
index 22c50872..aad0e2a9 100644
--- a/harness/codeverse/texturing/__init__.py
+++ b/harness/codeverse/texturing/__init__.py
@@ -3,12 +3,28 @@
``scene_pack.scene_texture_pack``."""
from codeverse.texturing.apply import ApplyReport, apply_textures
-from codeverse.texturing.gate import GateResult, SeamGateResult, judge_gate, seam_gate
-from codeverse.texturing.generate import FakeImageModel, TextureAsset, TextureSet, generate_textures
-from codeverse.texturing.plan import TexturePart, TexturePlan, default_plan, material_plan
+from codeverse.texturing.generate import (
+ FakeImageModel,
+ GateResult,
+ SeamGateResult,
+ TextureAsset,
+ TextureSet,
+ generate_textures,
+ judge_gate,
+ make_tileable,
+ seam_gate,
+ seam_score,
+)
+from codeverse.texturing.plan import (
+ ScenePack,
+ TexturePart,
+ TexturePlan,
+ default_plan,
+ material_plan,
+ scene_texture_pack,
+ texture_pack_prompt,
+)
from codeverse.texturing.run import TextureReport, texture_pass
-from codeverse.texturing.scene_pack import ScenePack, scene_texture_pack, texture_pack_prompt
-from codeverse.texturing.tile import make_tileable, seam_score
__all__ = [
"ApplyReport", "apply_textures", "GateResult", "SeamGateResult", "judge_gate", "seam_gate",
diff --git a/harness/codeverse/texturing/apply.py b/harness/codeverse/texturing/apply.py
index 78f45b76..3bdbd950 100644
--- a/harness/codeverse/texturing/apply.py
+++ b/harness/codeverse/texturing/apply.py
@@ -1,42 +1,324 @@
-"""Apply a ``TexturePlan`` + generated images to the canonical GLB → a textured GLB.
-
-How textures are embedded (trimesh 4.x): every textured geometry gets
-``trimesh.visual.TextureVisuals(uv=<per-vertex UV>, material=PBRMaterial(
-baseColorTexture=<PIL image>, baseColorFactor=tint|white, metallicFactor,
-roughnessFactor))``; ``Scene.export(path)`` (glTF exporter) writes TEXCOORD_0,
-one glTF ``image``/``texture``/``material`` per distinct ``PBRMaterial`` object
-(materials are shared across parts with the same texture id + factors, so the
-GLB carries each PNG once) and keeps node names + transforms. Each material also
-carries a ``metallicRoughnessTexture`` and a ``normalTexture`` DERIVED from its
-albedo (:mod:`codeverse.texturing.maps`), so the grain modulates the specular
-lobe and the relief, not only the colour — ``derived_maps=False`` restores the
-albedo-only behaviour. Geometry
-positions are never altered (only seam-split vertices are duplicated); parts
-marked ``skip`` keep their original visuals (flat colours / vertex colours).
-
-Verification: the exported file is reloaded with trimesh and the node-name set
-and per-part textured state are checked before the function returns.
+"""Derived PBR maps: roughness and normal, computed from a generated albedo tile.
+
+The texture pass used to ship **albedo only** — one image per material, plus two
+scalar factors. A flat roughness is exactly what the judge keeps calling out:
+*"the blue material lacks roughness variation or bump mapping, making it look
+like smooth plastic rather than cast iron"* (`tool_hard_bench_vise` r1),
+*"materials are flat colors with no texture character (no wood grain, no leather
+bump)"* (`furn_hard_rolltop_desk` r2). A grain that only changes colour is a
+sticker; a grain that also changes how the light scatters is a material.
+
+Both maps are derived from the albedo, so they cost nothing (no extra image
+call), tile exactly like it does, and can never disagree with it:
+
+* **roughness** — dark, recessed-looking pixels of a surface are its pores, its
+ end grain, its casting pits: rougher. Bright ones are the polished high
+ points: smoother. So roughness is the family's base value modulated by
+ ``-(luminance - mean)``, with the amplitude set per family (wood grain and
+ cast iron vary a lot, glazed ceramic almost not at all).
+* **normal** — wrap-around central differences of that same detail signal, read
+ as a height field. Same reasoning: what is dark is low.
+
+Written into the GLB as a glTF ``metallicRoughnessTexture`` (roughness in G,
+metallic in B — the packing the spec mandates) and a ``normalTexture``.
"""
from __future__ import annotations
import logging
import time
+from dataclasses import dataclass
from pathlib import Path
-from typing import Any
+from typing import Any, NamedTuple
import numpy as np
import trimesh
-from PIL import Image
+from PIL import Image, ImageFilter
from pydantic import BaseModel, Field
+from codeverse.contracts.plan import StaticPlan
from codeverse.conventions import to_snake
from codeverse.spatial.measure import GlbLoadError, instance_groups, load_scene
-from codeverse.texturing.maps import is_flat, metallic_roughness_image, normal_image
-from codeverse.texturing.materials import COARSE_TO_FINE
+from codeverse.texturing.materials import (
+ COARSE_TO_FINE,
+ FamilyMatch,
+ family_for,
+ is_framework_default,
+ looks_painted,
+ out_of_band,
+ pbr_for,
+)
from codeverse.texturing.plan import TexturePart, TexturePlan
-from codeverse.texturing.uv import unwrap
+#: family → (roughness amplitude, normal-map strength). Amplitude is the peak
+#: deviation from the base roughness across the tile; strength scales the Sobel
+#: gradient before it becomes a slope.
+VARIATION: dict[str, tuple[float, float]] = {
+ "hardwood": (0.16, 0.55),
+ "softwood": (0.20, 0.85),
+ "painted_wood": (0.10, 0.35),
+ "cast_iron": (0.22, 0.90),
+ "brushed_metal": (0.12, 0.25),
+ "machined_steel": (0.10, 0.25),
+ "chrome": (0.05, 0.10),
+ "brass": (0.10, 0.25),
+ "copper_patina": (0.24, 0.90),
+ "painted_metal": (0.08, 0.25),
+ "rough_plastic": (0.12, 0.40),
+ "glossy_plastic": (0.07, 0.20),
+ "rubber": (0.10, 0.45),
+ "fabric": (0.14, 0.95),
+ "leather": (0.18, 0.90),
+ "ceramic": (0.06, 0.20),
+ "concrete": (0.20, 0.95),
+ "stone": (0.20, 0.90),
+ "paper": (0.10, 0.35),
+ "glass": (0.02, 0.05),
+}
+DEFAULT_VARIATION = (0.14, 0.55)
+
+#: blur radius (as a fraction of the tile) used to separate the tile's large-scale
+#: shading from the fine detail that actually is surface relief
+_DETAIL_BLUR_FRAC = 0.06
+
+
+def variation_for(family: str) -> tuple[float, float]:
+ return VARIATION.get(family, DEFAULT_VARIATION)
+
+
+def _luminance(img: Image.Image) -> np.ndarray:
+ a = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
+ return 0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]
+
+
+def _blur(a: np.ndarray, radius: float) -> np.ndarray:
+ """Gaussian blur of a 0..1 float array (through PIL, so no scipy dependency)."""
+ img = Image.fromarray(np.round(np.clip(a, 0.0, 1.0) * 255).astype(np.uint8), mode="L")
+ return np.asarray(img.filter(ImageFilter.GaussianBlur(radius)), dtype=np.float32) / 255.0
+
+
+def _detail(img: Image.Image) -> np.ndarray:
+ """Luminance with its low-frequency component removed, rescaled to ~[-1, 1].
+
+ Removing the low frequencies matters: a generated tile often has a broad
+ lighting ramp baked in, and using raw luminance would turn that ramp into a
+ roughness gradient across the whole part. The blurred reference is built from
+ the SAME luminance array (not PIL's ``convert("L")``, which uses the ITU-R 601
+ weights and would leave a constant offset behind on a solid colour).
+ """
+ lum = _luminance(img)
+ d = lum - _blur(lum, max(1.0, _DETAIL_BLUR_FRAC * max(img.size)))
+ scale = float(np.percentile(np.abs(d), 98))
+ return np.clip(d / scale, -1.0, 1.0) if scale > 1e-6 else np.zeros_like(d)
+
+
+def roughness_array(albedo: Image.Image, base_roughness: float, family: str) -> np.ndarray:
+ """Per-pixel roughness in 0..1: ``base - amplitude × detail`` (dark = rough)."""
+ amp = variation_for(family)[0]
+ return np.clip(float(base_roughness) - amp * _detail(albedo), 0.0, 1.0)
+
+
+def metallic_roughness_image(
+ albedo: Image.Image, base_roughness: float, metallic: float, family: str
+) -> Image.Image:
+ """glTF ``metallicRoughnessTexture``: R unused, **G = roughness**, **B = metallic**."""
+ rough = roughness_array(albedo, base_roughness, family)
+ h, w = rough.shape
+ out = np.zeros((h, w, 3), dtype=np.uint8)
+ out[..., 1] = np.round(rough * 255).astype(np.uint8)
+ out[..., 2] = np.uint8(round(float(np.clip(metallic, 0.0, 1.0)) * 255))
+ return Image.fromarray(out, mode="RGB")
+
+
+def normal_image(albedo: Image.Image, family: str, *, strength: float | None = None) -> Image.Image:
+ """Tangent-space normal map from the albedo's detail, read as a height field.
+
+ Gradients are taken with ``np.roll`` (wrap-around), so a tile that is seamless
+ in albedo stays seamless in its normals.
+ """
+ s = variation_for(family)[1] if strength is None else float(strength)
+ height = _detail(albedo)
+ # central differences, wrapping at the tile edges
+ dx = (np.roll(height, -1, axis=1) - np.roll(height, 1, axis=1)) * 0.5
+ dy = (np.roll(height, -1, axis=0) - np.roll(height, 1, axis=0)) * 0.5
+ nx, ny, nz = -dx * s * 4.0, dy * s * 4.0, np.ones_like(height)
+ norm = np.sqrt(nx * nx + ny * ny + nz * nz)
+ rgb = np.stack([nx / norm, ny / norm, nz / norm], axis=-1) * 0.5 + 0.5
+ return Image.fromarray(np.round(np.clip(rgb, 0.0, 1.0) * 255).astype(np.uint8), mode="RGB")
+
+
+def is_flat(img: Image.Image, *, tol: float = 0.01) -> bool:
+ """A tile with no detail at all (a solid colour): derived maps would be noise."""
+ lum = _luminance(img)
+ return bool(np.percentile(np.abs(lum - float(lum.mean())), 99) < tol)
+
+
+# ===================================================================== uv
+# (merged from codeverse/texturing/uv.py, 2026-08-28)
+#: long/mid extent ratio above which ``auto`` picks a cylinder projection ...
+CYLINDER_ASPECT = 2.5
+#: ... provided the cross-section is roughly round (mid/min below this); slabs → box
+CYLINDER_SECTION = 2.0
+#: |n · axis| above which a face is a cylinder cap (planar projected)
+CAP_COS = 0.75
+
+
+@dataclass
+class Unwrapped:
+ vertices: np.ndarray # (N', 3) LOCAL coordinates (possibly split)
+ faces: np.ndarray # (F, 3)
+ normals: np.ndarray | None # (N', 3) local normals or None
+ uv: np.ndarray # (N', 2)
+ projection: str # box | cylinder | planar_y | planar_z
+ axis: int # projection axis (cylinder axis / planar normal axis)
+ n_split: int # vertices added by seam splitting
+
+
+def choose_projection(extents_world: np.ndarray, requested: str) -> tuple[str, int]:
+ """Resolve ``auto`` → (projection, axis). Elongated with a round-ish section →
+ cylinder around the long axis; everything else (slabs, boxes, frames) → box. Explicit projections pass through (cylinder axis =
+ the longest world axis; planar axes are fixed: planar_y → 1, planar_z → 2)."""
+ e = np.asarray(extents_world, dtype=float)
+ order = np.argsort(e)[::-1]
+ long_axis = int(order[0])
+ if requested == "cylinder":
+ return "cylinder", long_axis
+ if requested == "planar_y":
+ return "planar_y", 1
+ if requested == "planar_z":
+ return "planar_z", 2
+ if requested == "box":
+ return "box", int(np.argmin(e))
+ mid = max(float(e[order[1]]), 1e-9)
+ small = max(float(e[order[2]]), 1e-9)
+ if float(e[order[0]]) / mid >= CYLINDER_ASPECT and mid / small <= CYLINDER_SECTION:
+ return "cylinder", long_axis
+ return "box", int(np.argmin(e))
+
+
+def _face_normals(P: np.ndarray, F: np.ndarray) -> np.ndarray:
+ a, b, c = P[F[:, 0]], P[F[:, 1]], P[F[:, 2]]
+ n = np.cross(b - a, c - a)
+ ln = np.linalg.norm(n, axis=1, keepdims=True)
+ return n / np.maximum(ln, 1e-12)
+
+
+def _box_uv(P: np.ndarray, F: np.ndarray, tile: float) -> tuple[np.ndarray, np.ndarray]:
+ """Per-face dominant axis of the face normal → planar projection on the other two."""
+ n = _face_normals(P, F)
+ axis = np.argmax(np.abs(n), axis=1) # (F,)
+ sign = np.sign(n[np.arange(len(F)), axis])
+ sign[sign == 0] = 1.0
+ other = np.array([[2, 1], [0, 2], [0, 1]]) # axis → (u axis, v axis)
+ corners = P[F] # (F,3,3)
+ ua, va = other[axis, 0], other[axis, 1]
+ u = np.take_along_axis(corners, ua[:, None, None].repeat(3, 1), axis=2)[:, :, 0]
+ v = np.take_along_axis(corners, va[:, None, None].repeat(3, 1), axis=2)[:, :, 0]
+ u = u * sign[:, None] # keep handedness consistent on opposite faces
+ uv = np.stack([u, v], axis=2) / tile
+ key = axis[:, None].repeat(3, 1) * 2 + (sign[:, None].repeat(3, 1) < 0).astype(int)
+ return uv, key
+
+
+def _planar_uv(P: np.ndarray, F: np.ndarray, axis: int, tile: float) -> tuple[np.ndarray, np.ndarray]:
+ other = {0: (2, 1), 1: (0, 2), 2: (0, 1)}[axis]
+ corners = P[F]
+ uv = np.stack([corners[:, :, other[0]], corners[:, :, other[1]]], axis=2) / tile
+ return uv, np.zeros((len(F), 3), dtype=int)
+
+
+def _cylinder_uv(P: np.ndarray, F: np.ndarray, axis: int, tile: float) -> tuple[np.ndarray, np.ndarray]:
+ a, b = [i for i in range(3) if i != axis]
+ center = 0.5 * (P.min(axis=0) + P.max(axis=0))
+ d = P - center
+ radius = float(np.mean(np.hypot(d[:, a], d[:, b])))
+ radius = max(radius, 1e-4)
+ circ = 2.0 * np.pi * radius
+ ang = np.arctan2(d[:, b], d[:, a]) # (-π, π]
+ u_v = (ang + np.pi) / (2.0 * np.pi) * circ / tile # 0..circ/tile
+ v_v = P[:, axis] / tile
+ u = u_v[F] # (F,3)
+ v = v_v[F]
+ key = np.zeros((len(F), 3), dtype=int)
+ # seam: faces straddling angle ±π have a u spread > half circumference → shift the low corners
+ span = u.max(axis=1) - u.min(axis=1)
+ wrap = span > 0.5 * circ / tile
+ if wrap.any():
+ low = u < (u.max(axis=1, keepdims=True) - 0.5 * circ / tile)
+ shift = wrap[:, None] & low
+ u = u + shift * (circ / tile)
+ key = key + shift.astype(int)
+ # caps: planar
+ n = _face_normals(P, F)
+ cap = np.abs(n[:, axis]) > CAP_COS
+ if cap.any():
+ corners = P[F]
+ u = np.where(cap[:, None], corners[:, :, a] / tile, u)
+ v = np.where(cap[:, None], corners[:, :, b] / tile, v)
+ key = np.where(cap[:, None], 2, key)
+ return np.stack([u, v], axis=2), key
+
+
+def split_by_key(
+ vertices: np.ndarray, faces: np.ndarray, normals: np.ndarray | None, uv_corner: np.ndarray, key_corner: np.ndarray
+) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray, int]:
+ """Duplicate a vertex once per distinct (vertex, key) pair; UV per new vertex =
+ mean of its corner UVs (they agree within a key by construction)."""
+ F = faces
+ flat_v = F.reshape(-1)
+ flat_k = key_corner.reshape(-1)
+ pair = flat_v.astype(np.int64) * (int(flat_k.max()) + 1 if flat_k.size else 1) + flat_k
+ uniq, inverse = np.unique(pair, return_inverse=True)
+ n_new = len(uniq)
+ src = np.zeros(n_new, dtype=np.int64)
+ src[inverse] = flat_v
+ new_vertices = vertices[src]
+ new_normals = normals[src] if normals is not None else None
+ new_uv = np.zeros((n_new, 2), dtype=np.float64)
+ counts = np.zeros(n_new, dtype=np.float64)
+ np.add.at(new_uv, inverse, uv_corner.reshape(-1, 2))
+ np.add.at(counts, inverse, 1.0)
+ new_uv /= np.maximum(counts, 1.0)[:, None]
+ new_faces = inverse.reshape(-1, 3)
+ return new_vertices, new_faces, new_normals, new_uv, int(n_new - len(vertices))
+
+
+def unwrap(
+ vertices_local: np.ndarray,
+ faces: np.ndarray,
+ transform: np.ndarray,
+ *,
+ projection: str = "auto",
+ tile_size_m: float = 0.3,
+ normals_local: np.ndarray | None = None,
+) -> Unwrapped:
+ """Compute UVs for one mesh given its 4×4 world ``transform``. Returns the
+ (possibly vertex-split) mesh in LOCAL coordinates plus per-vertex UVs."""
+ V = np.asarray(vertices_local, dtype=np.float64)
+ F = np.asarray(faces, dtype=np.int64)
+ if V.ndim != 2 or V.shape[1] != 3 or F.ndim != 2 or F.shape[1] != 3 or len(F) == 0:
+ raise ValueError("unwrap needs (N,3) vertices and (F,3) triangles")
+ tile = float(tile_size_m)
+ if not tile > 0:
+ raise ValueError("tile_size_m must be > 0")
+ T = np.asarray(transform, dtype=np.float64)
+ P = V @ T[:3, :3].T + T[:3, 3]
+ ext = P.max(axis=0) - P.min(axis=0)
+ proj, axis = choose_projection(ext, projection)
+ if proj == "box":
+ uv_c, key_c = _box_uv(P, F, tile)
+ elif proj == "cylinder":
+ uv_c, key_c = _cylinder_uv(P, F, axis, tile)
+ else:
+ uv_c, key_c = _planar_uv(P, F, axis, tile)
+ nv, nf, nn, uv, n_split = split_by_key(V, F, normals_local, uv_c, key_c)
+ # keep numbers small for float32 TEXCOORD precision (pattern is periodic anyway)
+ uv = uv - np.floor(uv.min(axis=0))
+ return Unwrapped(vertices=nv, faces=nf, normals=nn, uv=uv, projection=proj, axis=axis, n_split=n_split)
+
+
+# ===================================================================== apply
+# (merged from codeverse/texturing/apply.py, 2026-08-28)
log = logging.getLogger(__name__)
@@ -222,3 +504,188 @@ def textured_summary(glb: Path | str) -> dict[str, int]:
textured += 1
imgs.add(id(tex))
return {"geometries": len(s.geometry), "textured": textured, "images": len(imgs)}
+
+
+# ===================================================================== normalise
+# (merged from codeverse/texturing/normalise.py, 2026-08-28)
+log = logging.getLogger(__name__)
+
+
+class MaterialChange(BaseModel):
+ node: str
+ material: str = ""
+ family: str
+ keyword: str = ""
+ reason: str # untouched | impossible
+ metallic: tuple[float, float] # before, after
+ roughness: tuple[float, float]
+
+
+class NormaliseReport(BaseModel):
+ glb_out: str = ""
+ changes: list[MaterialChange] = Field(default_factory=list)
+ n_materials: int = 0
+ n_unchanged: int = 0
+ n_unresolved: int = 0
+ warnings: list[str] = Field(default_factory=list)
+ duration_ms: int = 0
+
+ def changed(self) -> bool:
+ return bool(self.changes)
+
+ def table(self) -> str:
+ if not self.changes:
+ return "no material needed normalising"
+ rows = [f"{'node':22} {'family':15} {'why':11} metallic roughness"]
+ for c in self.changes:
+ rows.append(f"{c.node[:22]:22} {c.family:15} {c.reason:11} "
+ f"{c.metallic[0]:.2f}→{c.metallic[1]:.2f} {c.roughness[0]:.2f}→{c.roughness[1]:.2f}")
+ return "\n".join(rows)
+
+
+def _plan_materials(plan: StaticPlan | None) -> dict[str, str]:
+ """snake(part name) → the plan's ``material`` string for that part."""
+ if plan is None:
+ return {}
+ return {to_snake(p.name): (p.material or p.description or "") for p in plan.parts}
+
+
+def _factors(mat: object) -> tuple[float | None, float | None]:
+ m = getattr(mat, "metallicFactor", None)
+ r = getattr(mat, "roughnessFactor", None)
+ return (None if m is None else float(m)), (None if r is None else float(r))
+
+
+def _base_rgb(mat: object) -> tuple[float, float, float] | None:
+ """``baseColorFactor`` as 0..1 RGB (trimesh stores it as 0-255 RGBA)."""
+ f = getattr(mat, "baseColorFactor", None)
+ if f is None or len(f) < 3:
+ return None
+ vals = [float(c) for c in f[:3]]
+ scale = 255.0 if max(vals) > 1.0 else 1.0
+ return (vals[0] / scale, vals[1] / scale, vals[2] / scale)
+
+
+def _has_texture(mat: object) -> bool:
+ return any(getattr(mat, k, None) is not None
+ for k in ("baseColorTexture", "metallicRoughnessTexture", "normalTexture"))
+
+
+class Verdict(NamedTuple):
+ family: str
+ reason: str # untouched | impossible
+ keyword: str
+ metallic: float
+ roughness: float
+
+
+def _clamp(v: float, lo: float, hi: float) -> float:
+ return round(min(hi, max(lo, v)), 3)
+
+
+def _evidence(material_name: str, node: str, plan_text: str) -> tuple[FamilyMatch | None, str]:
+ """Best family match and WHERE it came from (``material`` > ``node`` > ``plan``)."""
+ for tier, text in (("material", material_name), ("node", node), ("plan", plan_text)):
+ hit = family_for(text)
+ if hit is not None:
+ return hit, tier
+ return None, ""
+
+
+def classify(
+ node: str, material_name: str, plan_text: str, metallic: float | None, roughness: float | None,
+ base_rgb: tuple[float, float, float] | None = None,
+) -> Verdict | None:
+ """What (if anything) to do with one material.
+
+ ``untouched`` snaps to the family's canonical numbers; ``impossible`` only
+ *clamps* the offending factor to the nearest edge of the family's plausible
+ band, so an author's deliberate-but-extreme choice survives as far as physics
+ allows. ``None`` = leave it exactly as it is."""
+ hit, tier = _evidence(material_name, node, plan_text)
+ if hit is None:
+ return None
+ family = hit.family
+ if looks_painted(family, base_rgb):
+ # a saturated colour on a "cast iron" part means paint over the iron
+ family = "painted_wood" if family == "cast_iron" and (base_rgb or (0, 0, 0))[1] > 0.5 else "painted_metal"
+ target = pbr_for(family)
+ if target is None:
+ return None
+ if is_framework_default(metallic, roughness):
+ return Verdict(target.family, "untouched", hit.keyword, target.metallic, target.roughness)
+ if tier == "plan":
+ # the plan's prose covers a whole part, not one material: it is good enough to
+ # spot a never-configured default, never good enough to overrule real numbers
+ return None
+ bad = out_of_band(target, metallic, roughness)
+ if not bad:
+ return None
+ m = 1.0 if metallic is None else float(metallic)
+ r = 1.0 if roughness is None else float(roughness)
+ return Verdict(
+ target.family, "impossible", hit.keyword,
+ _clamp(m, *target.metallic_band) if "metallic" in bad else m,
+ _clamp(r, *target.roughness_band) if "roughness" in bad else r,
+ )
+
+
+def normalise_materials(
+ glb_in: Path | str, glb_out: Path | str, *, plan: StaticPlan | None = None, write: bool = True
+) -> NormaliseReport:
+ """Rewrite the flat-default / impossible materials of ``glb_in`` into ``glb_out``.
+
+ Geometry, node names, UVs and base colours are untouched; only
+ ``metallicFactor`` / ``roughnessFactor`` move. When nothing needs changing the
+ output is not written and ``report.glb_out`` stays empty.
+ """
+ t0 = time.time()
+ glb_in, glb_out = Path(glb_in), Path(glb_out)
+ scene = load_scene(glb_in)
+ rep = NormaliseReport()
+ plan_mats = _plan_materials(plan)
+ seen: dict[int, tuple[float, float] | None] = {}
+ for node in scene.graph.nodes_geometry:
+ _, geom_name = scene.graph.get(node)
+ geom = scene.geometry.get(geom_name) if geom_name else None
+ mat = getattr(getattr(geom, "visual", None), "material", None)
+ if mat is None:
+ rep.n_unresolved += 1
+ continue
+ if id(mat) in seen: # a material shared by several nodes is normalised once
+ continue
+ rep.n_materials += 1
+ if _has_texture(mat):
+ rep.n_unchanged += 1
+ seen[id(mat)] = None
+ continue
+ metallic, roughness = _factors(mat)
+ snake = to_snake(node)
+ plan_text = plan_mats.get(snake) or plan_mats.get(to_snake(node.split("__", 1)[0])) or ""
+ verdict = classify(node, str(getattr(mat, "name", "") or ""), plan_text, metallic, roughness,
+ _base_rgb(mat))
+ if verdict is None:
+ rep.n_unchanged += 1
+ seen[id(mat)] = None
+ continue
+ before = (1.0 if metallic is None else metallic, 1.0 if roughness is None else roughness)
+ mat.metallicFactor = float(verdict.metallic)
+ mat.roughnessFactor = float(verdict.roughness)
+ seen[id(mat)] = (verdict.metallic, verdict.roughness)
+ rep.changes.append(MaterialChange(
+ node=node, material=str(getattr(mat, "name", "") or ""), family=verdict.family,
+ keyword=verdict.keyword, reason=verdict.reason,
+ metallic=(round(before[0], 3), verdict.metallic), roughness=(round(before[1], 3), verdict.roughness),
+ ))
+ if rep.changes and write:
+ glb_out.parent.mkdir(parents=True, exist_ok=True)
+ scene.export(glb_out)
+ rep.glb_out = str(glb_out)
+ rep.warnings.extend(_verify(glb_in, glb_out))
+ rep.duration_ms = int((time.time() - t0) * 1000)
+ return rep
+
+
+def _verify(glb_in: Path, glb_out: Path) -> list[str]:
+ """Same nodes, same triangles — this pass may only move two floats per material."""
+ return verify_textured_glb(glb_in, glb_out, expected_textured=0)
diff --git a/harness/codeverse/texturing/gate.py b/harness/codeverse/texturing/gate.py
deleted file mode 100644
index 73af695a..00000000
--- a/harness/codeverse/texturing/gate.py
+++ /dev/null
@@ -1,164 +0,0 @@
-"""Do-no-harm ship gate for a texture pass.
-
-1. ``seam_gate``: per-texture seam score (``tile.seam_score`` after mirror-blend)
- must be ≤ ``SEAM_MAX``; failing textures are dropped (their parts keep flat
- materials) — deterministic, free.
-2. ``judge_gate``: render BEFORE and AFTER (``render_glb``, quick 4 views) and
- judge both with the same ``VlmJudge`` (rubric of the track, n_samples=1).
- Ship iff ``Δoverall ≥ min_overall_delta`` (default −0.01) AND the rubric's
- material criterion improved (``> min_materials_delta``, default 0). A degraded
- verdict on either side → not shipped (a glitch is never a score).
-
-Everything is injectable (``render`` / ``judge`` callables) so tests run offline.
-"""
-
-from __future__ import annotations
-
-import logging
-import time
-from collections.abc import Callable, Sequence
-from pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel, Field
-
-from codeverse.contracts.artifacts import Measurement, RenderSet
-from codeverse.contracts.common import Usage
-from codeverse.contracts.judgment import Judgment
-from codeverse.contracts.plan import AcceptanceItem, StaticPlan
-from codeverse.contracts.spec import Spec
-from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
-from codeverse.texturing.generate import TextureAsset
-from codeverse.texturing.tile import SEAM_MAX
-
-log = logging.getLogger(__name__)
-
-MIN_OVERALL_DELTA = -0.01
-MIN_MATERIALS_DELTA = 0.0
-
-
-class SeamGateResult(BaseModel):
- passed: dict[str, float] = Field(default_factory=dict, description="texture_id → seam score (kept)")
- failed: dict[str, float] = Field(default_factory=dict, description="texture_id → seam score (dropped)")
- threshold: float = SEAM_MAX
-
-
-def seam_gate(textures: dict[str, TextureAsset], *, max_seam: float = SEAM_MAX) -> SeamGateResult:
- res = SeamGateResult(threshold=max_seam)
- for tid, a in textures.items():
- if not a.ok:
- continue
- (res.passed if a.seam_score <= max_seam else res.failed)[tid] = round(float(a.seam_score), 4)
- return res
-
-
-class GateResult(BaseModel):
- shipped: bool
- reason: str = ""
- overall_before: float | None = None
- overall_after: float | None = None
- delta: float | None = None
- materials_criterion: str = ""
- materials_before: float | None = None
- materials_after: float | None = None
- materials_delta: float | None = None
- renders_before: RenderSet | None = None
- renders_after: RenderSet | None = None
- judgment_before: Judgment | None = None
- judgment_after: Judgment | None = None
- usage: Usage = Field(default_factory=Usage)
- duration_s: float = 0.0
-
-
-def material_criterion(scores: dict[str, float], rubric_hint: str = "") -> str:
- """The rubric criterion that tracks surface quality (``materials``,
- ``material_color``, ``materials_shaders_effects``, ``material_truth`` ...)."""
- for k in scores:
- if k.startswith("material"):
- return k
- for k in scores:
- if "material" in k or "texture" in k or "surface" in k:
- return k
- return ""
-
-
-def _plan_summary(plan: StaticPlan | None) -> str:
- if plan is None:
- return ""
- parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
- e = plan.overall_bbox.extents
- return f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m. Parts: {parts}."
-
-
-def _degraded(j: Judgment) -> bool:
- from codeverse.judges.rubrics import is_degraded
-
- return is_degraded(j)
-
-
-def judge_gate(
- spec: Spec,
- plan: StaticPlan | None,
- glb_before: Path,
- glb_after: Path,
- out_dir: Path,
- *,
- judge: Any,
- measurement: Measurement | None = None,
- views: Sequence[ViewPreset] = OBJECT_VIEWS_QUICK,
- render: Callable[..., RenderSet] | None = None,
- size: int = 512,
- min_overall_delta: float = MIN_OVERALL_DELTA,
- min_materials_delta: float = MIN_MATERIALS_DELTA,
-) -> GateResult:
- """Render + judge both GLBs; decide. ``judge`` is any object with
- ``.judge(JudgeInput) -> Judgment`` (``VlmJudge`` or a fake)."""
- from codeverse.judges.base import JudgeInput
-
- t0 = time.time()
- if render is None:
- from codeverse.spatial.render import render_glb
-
- render = render_glb
- out_dir = Path(out_dir)
- rs_before = render(glb_before, out_dir / "before", views=list(views), width=size, height=size)
- rs_after = render(glb_after, out_dir / "after", views=list(views), width=size, height=size)
- acceptance: list[AcceptanceItem] = list(getattr(plan, "acceptance", []) or [])
- summary = _plan_summary(plan)
- res = GateResult(shipped=False, renders_before=rs_before, renders_after=rs_after)
- jb = judge.judge(JudgeInput(spec=spec, renders=rs_before, measurement=measurement, acceptance=acceptance,
- plan_summary=summary, round_index=0,
- extra_context="Texture gate: BEFORE texturing (flat materials)."))
- ja = judge.judge(JudgeInput(spec=spec, renders=rs_after, measurement=measurement, acceptance=acceptance,
- plan_summary=summary, round_index=0,
- extra_context="Texture gate: AFTER texturing (image textures applied)."))
- res.judgment_before, res.judgment_after = jb, ja
- res.usage = jb.usage + ja.usage
- res.duration_s = round(time.time() - t0, 2)
- if _degraded(jb) or _degraded(ja):
- res.reason = "judge degraded on one side — not shipped"
- return res
- res.overall_before, res.overall_after = float(jb.overall), float(ja.overall)
- res.delta = round(res.overall_after - res.overall_before, 4)
- crit = material_criterion(ja.scores)
- res.materials_criterion = crit
- if crit:
- res.materials_before = float(jb.scores.get(crit, 0.0))
- res.materials_after = float(ja.scores.get(crit, 0.0))
- res.materials_delta = round(res.materials_after - res.materials_before, 4)
- ok_overall = res.delta >= min_overall_delta
- ok_mat = (res.materials_delta is None) or (res.materials_delta > min_materials_delta)
- if crit and res.materials_delta is None:
- ok_mat = False
- res.shipped = bool(ok_overall and ok_mat)
- if res.shipped:
- res.reason = f"Δoverall {res.delta:+.3f} ≥ {min_overall_delta:+.2f} and {crit or 'overall'} {res.materials_delta:+.3f}" if crit \
- else f"Δoverall {res.delta:+.3f} ≥ {min_overall_delta:+.2f}"
- else:
- why = []
- if not ok_overall:
- why.append(f"Δoverall {res.delta:+.3f} < {min_overall_delta:+.2f}")
- if not ok_mat:
- why.append(f"{crit} {res.materials_delta:+.3f} did not improve")
- res.reason = "; ".join(why)
- return res
diff --git a/harness/codeverse/texturing/generate.py b/harness/codeverse/texturing/generate.py
index a93b4425..2babfdbd 100644
--- a/harness/codeverse/texturing/generate.py
+++ b/harness/codeverse/texturing/generate.py
@@ -1,17 +1,14 @@
-"""Generate the texture images a ``TexturePlan`` (or a scene pack) needs.
-
-* one image per distinct prompt (parts sharing a ``texture_id`` share the image;
- identical prompts under different ids are generated once and copied),
-* content cache ``<cache_dir>/textures/<sha(prompt|model|size|tile_version)>.png``
- (the raw generation, BEFORE seam fixing, so a better ``make_tileable`` can be
- re-applied without paying again),
-* parallel fan-out (ThreadPool) on the shared key pool,
-* every call yields a ``Usage`` (per texture and total),
-* the delivered asset is ``out_dir/<texture_id>.png``: ``make_tileable`` →
- ``fit_size(size)`` → PNG, with its ``seam_score`` recorded.
-
-``FakeImageModel`` (procedural PIL images, deterministic per prompt) lets every
-test run offline with the exact same code path.
+"""Tileability: seam scoring, mirror-blend seam fixing, resizing and saving.
+
+* ``seam_score(img)``: mean absolute difference (0..1) between the left/right and
+ top/bottom wrap edges, normalised by the image's own local contrast so a noisy
+ texture is not penalised for being noisy. ≈0 = perfect wrap.
+* ``make_tileable(img, border_frac)``: cross-fades each edge band with the mirrored
+ opposite band (a smoothstep ramp over ``border_frac`` of the width) so the wrap
+ seam disappears; content in the middle is untouched.
+* ``offset_check(img)``: half-offset the image (seams move to the centre) — the
+ classic visual check; returns the offset image for inspection.
+* ``fit_size`` / ``save_texture``: power-of-two downscale + PNG or JPEG q90.
"""
from __future__ import annotations
@@ -21,7 +18,7 @@ import logging
import shutil
import threading
import time
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
@@ -31,9 +28,115 @@ from PIL import Image
from pydantic import BaseModel, Field
from codeverse.config import get_settings
+from codeverse.contracts.artifacts import Measurement, RenderSet
from codeverse.contracts.common import Usage
-from codeverse.texturing.tile import fit_size, make_tileable, save_texture, seam_score
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem, StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
+
+#: seam score above which a texture is considered NOT tileable (after make_tileable)
+SEAM_MAX = 0.08
+
+
+def _arr(img: Image.Image) -> np.ndarray:
+ return np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
+
+
+def seam_score(img: Image.Image | np.ndarray) -> float:
+ """Mean |Δ| across the wrap seams relative to the mean |Δ| between neighbouring
+ pixel columns/rows inside the image (so 1.0 ≈ 'the seam is as strong as the
+ texture's own detail'); clamped to [0, 1]."""
+ a = _arr(img) if isinstance(img, Image.Image) else np.asarray(img, dtype=np.float32)
+ if a.ndim == 2:
+ a = a[:, :, None]
+ h, w = a.shape[:2]
+ if h < 4 or w < 4:
+ return 0.0
+ seam_lr = np.abs(a[:, 0, :] - a[:, -1, :]).mean()
+ seam_tb = np.abs(a[0, :, :] - a[-1, :, :]).mean()
+ # typical one-step difference inside the image (excluding the seam)
+ inner_lr = np.abs(a[:, 1:, :] - a[:, :-1, :]).mean()
+ inner_tb = np.abs(a[1:, :, :] - a[:-1, :, :]).mean()
+ # a seam is bad when it exceeds the local detail noticeably; blend absolute + relative
+ rel = 0.5 * (seam_lr / max(inner_lr, 1e-3) + seam_tb / max(inner_tb, 1e-3))
+ absolute = 0.5 * (seam_lr + seam_tb)
+ score = 0.5 * absolute + 0.5 * min(1.0, max(0.0, (rel - 1.0) / 8.0))
+ return float(min(1.0, max(0.0, score)))
+
+
+def _ramp(n: int) -> np.ndarray:
+ t = (np.arange(n, dtype=np.float32) + 0.5) / n
+ return t * t * (3.0 - 2.0 * t) # smoothstep 0 → 1
+
+
+def make_tileable(img: Image.Image, border_frac: float = 0.12) -> Image.Image:
+ """Mirror-blend the wrap seams. Along X: the left band is cross-faded with the
+ mirrored right band and vice versa (weights symmetric so the wrap is exact);
+ then the same along Y. ``border_frac`` ∈ [0.05, 0.3] of the size."""
+ border_frac = float(min(0.3, max(0.05, border_frac)))
+ a = _arr(img)
+ h, w = a.shape[:2]
+ bw, bh = max(2, int(round(w * border_frac))), max(2, int(round(h * border_frac)))
+ out = a.copy()
+ # horizontal: blend left band with mirrored right band
+ r = _ramp(bw)[None, :, None] # 0 at the outer edge → 1 inside
+ left, right = a[:, :bw, :], a[:, w - bw:, :]
+ mir_right = right[:, ::-1, :] # right band mirrored so its outer edge meets the left edge
+ mir_left = left[:, ::-1, :]
+ out[:, :bw, :] = left * (0.5 + 0.5 * r) + mir_right * (0.5 - 0.5 * r)
+ out[:, w - bw:, :] = right * (0.5 + 0.5 * r[:, ::-1, :]) + mir_left * (0.5 - 0.5 * r[:, ::-1, :])
+ a = out.copy()
+ r = _ramp(bh)[:, None, None]
+ top, bottom = a[:bh, :, :], a[h - bh:, :, :]
+ mir_bottom, mir_top = bottom[::-1, :, :], top[::-1, :, :]
+ out[:bh, :, :] = top * (0.5 + 0.5 * r) + mir_bottom * (0.5 - 0.5 * r)
+ out[h - bh:, :, :] = bottom * (0.5 + 0.5 * r[::-1, :, :]) + mir_top * (0.5 - 0.5 * r[::-1, :, :])
+ return Image.fromarray((np.clip(out, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8), "RGB")
+
+
+def offset_check(img: Image.Image) -> Image.Image:
+ """Roll the image by half its size so the wrap seams sit in the centre."""
+ a = _arr(img)
+ h, w = a.shape[:2]
+ rolled = np.roll(np.roll(a, w // 2, axis=1), h // 2, axis=0)
+ return Image.fromarray((rolled * 255.0 + 0.5).astype(np.uint8), "RGB")
+
+
+def fit_size(img: Image.Image, size: int) -> Image.Image:
+ """Square, power-of-two-ish downscale to ``size`` (never upscales)."""
+ w, h = img.size
+ if w != h:
+ s = min(w, h)
+ img = img.crop(((w - s) // 2, (h - s) // 2, (w - s) // 2 + s, (h - s) // 2 + s))
+ if img.size[0] > size:
+ img = img.resize((size, size), Image.LANCZOS)
+ return img.convert("RGB")
+
+
+def save_texture(img: Image.Image, path: Path, *, fmt: str | None = None, quality: int = 90) -> Path:
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fmt = (fmt or ("JPEG" if path.suffix.lower() in (".jpg", ".jpeg") else "PNG")).upper()
+ if fmt == "JPEG":
+ img.convert("RGB").save(path, "JPEG", quality=quality, optimize=True)
+ else:
+ img.convert("RGB").save(path, "PNG", optimize=True)
+ return path
+
+
+def tile_preview(img: Image.Image, reps: int = 2, size: int = 512) -> Image.Image:
+ """``reps × reps`` repetition for eyeballing tileability."""
+ t = img.convert("RGB").resize((size // reps, size // reps), Image.LANCZOS)
+ out = Image.new("RGB", (t.size[0] * reps, t.size[1] * reps))
+ for i in range(reps):
+ for j in range(reps):
+ out.paste(t, (i * t.size[0], j * t.size[1]))
+ return out
+
+# ===================================================================== generate
+# (merged from codeverse/texturing/generate.py, 2026-08-28)
log = logging.getLogger(__name__)
#: bump when the cached raw image semantics change (prompt composition, model config)
@@ -230,3 +333,138 @@ def generate_textures(
result.textures[other] = dup
result.duration_s = round(time.time() - t0, 2)
return result
+
+
+# ===================================================================== gate
+# (merged from codeverse/texturing/gate.py, 2026-08-28)
+log = logging.getLogger(__name__)
+
+MIN_OVERALL_DELTA = -0.01
+MIN_MATERIALS_DELTA = 0.0
+
+
+class SeamGateResult(BaseModel):
+ passed: dict[str, float] = Field(default_factory=dict, description="texture_id → seam score (kept)")
+ failed: dict[str, float] = Field(default_factory=dict, description="texture_id → seam score (dropped)")
+ threshold: float = SEAM_MAX
+
+
+def seam_gate(textures: dict[str, TextureAsset], *, max_seam: float = SEAM_MAX) -> SeamGateResult:
+ res = SeamGateResult(threshold=max_seam)
+ for tid, a in textures.items():
+ if not a.ok:
+ continue
+ (res.passed if a.seam_score <= max_seam else res.failed)[tid] = round(float(a.seam_score), 4)
+ return res
+
+
+class GateResult(BaseModel):
+ shipped: bool
+ reason: str = ""
+ overall_before: float | None = None
+ overall_after: float | None = None
+ delta: float | None = None
+ materials_criterion: str = ""
+ materials_before: float | None = None
+ materials_after: float | None = None
+ materials_delta: float | None = None
+ renders_before: RenderSet | None = None
+ renders_after: RenderSet | None = None
+ judgment_before: Judgment | None = None
+ judgment_after: Judgment | None = None
+ usage: Usage = Field(default_factory=Usage)
+ duration_s: float = 0.0
+
+
+def material_criterion(scores: dict[str, float], rubric_hint: str = "") -> str:
+ """The rubric criterion that tracks surface quality (``materials``,
+ ``material_color``, ``materials_shaders_effects``, ``material_truth`` ...)."""
+ for k in scores:
+ if k.startswith("material"):
+ return k
+ for k in scores:
+ if "material" in k or "texture" in k or "surface" in k:
+ return k
+ return ""
+
+
+def _plan_summary(plan: StaticPlan | None) -> str:
+ if plan is None:
+ return ""
+ parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
+ e = plan.overall_bbox.extents
+ return f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m. Parts: {parts}."
+
+
+def _degraded(j: Judgment) -> bool:
+ from codeverse.judges.rubrics import is_degraded
+
+ return is_degraded(j)
+
+
+def judge_gate(
+ spec: Spec,
+ plan: StaticPlan | None,
+ glb_before: Path,
+ glb_after: Path,
+ out_dir: Path,
+ *,
+ judge: Any,
+ measurement: Measurement | None = None,
+ views: Sequence[ViewPreset] = OBJECT_VIEWS_QUICK,
+ render: Callable[..., RenderSet] | None = None,
+ size: int = 512,
+ min_overall_delta: float = MIN_OVERALL_DELTA,
+ min_materials_delta: float = MIN_MATERIALS_DELTA,
+) -> GateResult:
+ """Render + judge both GLBs; decide. ``judge`` is any object with
+ ``.judge(JudgeInput) -> Judgment`` (``VlmJudge`` or a fake)."""
+ from codeverse.judges.base import JudgeInput
+
+ t0 = time.time()
+ if render is None:
+ from codeverse.spatial.render import render_glb
+
+ render = render_glb
+ out_dir = Path(out_dir)
+ rs_before = render(glb_before, out_dir / "before", views=list(views), width=size, height=size)
+ rs_after = render(glb_after, out_dir / "after", views=list(views), width=size, height=size)
+ acceptance: list[AcceptanceItem] = list(getattr(plan, "acceptance", []) or [])
+ summary = _plan_summary(plan)
+ res = GateResult(shipped=False, renders_before=rs_before, renders_after=rs_after)
+ jb = judge.judge(JudgeInput(spec=spec, renders=rs_before, measurement=measurement, acceptance=acceptance,
+ plan_summary=summary, round_index=0,
+ extra_context="Texture gate: BEFORE texturing (flat materials)."))
+ ja = judge.judge(JudgeInput(spec=spec, renders=rs_after, measurement=measurement, acceptance=acceptance,
+ plan_summary=summary, round_index=0,
+ extra_context="Texture gate: AFTER texturing (image textures applied)."))
+ res.judgment_before, res.judgment_after = jb, ja
+ res.usage = jb.usage + ja.usage
+ res.duration_s = round(time.time() - t0, 2)
+ if _degraded(jb) or _degraded(ja):
+ res.reason = "judge degraded on one side — not shipped"
+ return res
+ res.overall_before, res.overall_after = float(jb.overall), float(ja.overall)
+ res.delta = round(res.overall_after - res.overall_before, 4)
+ crit = material_criterion(ja.scores)
+ res.materials_criterion = crit
+ if crit:
+ res.materials_before = float(jb.scores.get(crit, 0.0))
+ res.materials_after = float(ja.scores.get(crit, 0.0))
+ res.materials_delta = round(res.materials_after - res.materials_before, 4)
+ ok_overall = res.delta >= min_overall_delta
+ ok_mat = (res.materials_delta is None) or (res.materials_delta > min_materials_delta)
+ if crit and res.materials_delta is None:
+ ok_mat = False
+ res.shipped = bool(ok_overall and ok_mat)
+ if res.shipped:
+ res.reason = f"Δoverall {res.delta:+.3f} ≥ {min_overall_delta:+.2f} and {crit or 'overall'} {res.materials_delta:+.3f}" if crit \
+ else f"Δoverall {res.delta:+.3f} ≥ {min_overall_delta:+.2f}"
+ else:
+ why = []
+ if not ok_overall:
+ why.append(f"Δoverall {res.delta:+.3f} < {min_overall_delta:+.2f}")
+ if not ok_mat:
+ why.append(f"{crit} {res.materials_delta:+.3f} did not improve")
+ res.reason = "; ".join(why)
+ return res
diff --git a/harness/codeverse/texturing/maps.py b/harness/codeverse/texturing/maps.py
deleted file mode 100644
index 2921b400..00000000
--- a/harness/codeverse/texturing/maps.py
+++ /dev/null
@@ -1,137 +0,0 @@
-"""Derived PBR maps: roughness and normal, computed from a generated albedo tile.
-
-The texture pass used to ship **albedo only** — one image per material, plus two
-scalar factors. A flat roughness is exactly what the judge keeps calling out:
-*"the blue material lacks roughness variation or bump mapping, making it look
-like smooth plastic rather than cast iron"* (`tool_hard_bench_vise` r1),
-*"materials are flat colors with no texture character (no wood grain, no leather
-bump)"* (`furn_hard_rolltop_desk` r2). A grain that only changes colour is a
-sticker; a grain that also changes how the light scatters is a material.
-
-Both maps are derived from the albedo, so they cost nothing (no extra image
-call), tile exactly like it does, and can never disagree with it:
-
-* **roughness** — dark, recessed-looking pixels of a surface are its pores, its
- end grain, its casting pits: rougher. Bright ones are the polished high
- points: smoother. So roughness is the family's base value modulated by
- ``-(luminance - mean)``, with the amplitude set per family (wood grain and
- cast iron vary a lot, glazed ceramic almost not at all).
-* **normal** — wrap-around central differences of that same detail signal, read
- as a height field. Same reasoning: what is dark is low.
-
-Written into the GLB as a glTF ``metallicRoughnessTexture`` (roughness in G,
-metallic in B — the packing the spec mandates) and a ``normalTexture``.
-"""
-
-from __future__ import annotations
-
-import numpy as np
-from PIL import Image, ImageFilter
-
-#: family → (roughness amplitude, normal-map strength). Amplitude is the peak
-#: deviation from the base roughness across the tile; strength scales the Sobel
-#: gradient before it becomes a slope.
-VARIATION: dict[str, tuple[float, float]] = {
- "hardwood": (0.16, 0.55),
- "softwood": (0.20, 0.85),
- "painted_wood": (0.10, 0.35),
- "cast_iron": (0.22, 0.90),
- "brushed_metal": (0.12, 0.25),
- "machined_steel": (0.10, 0.25),
- "chrome": (0.05, 0.10),
- "brass": (0.10, 0.25),
- "copper_patina": (0.24, 0.90),
- "painted_metal": (0.08, 0.25),
- "rough_plastic": (0.12, 0.40),
- "glossy_plastic": (0.07, 0.20),
- "rubber": (0.10, 0.45),
- "fabric": (0.14, 0.95),
- "leather": (0.18, 0.90),
- "ceramic": (0.06, 0.20),
- "concrete": (0.20, 0.95),
- "stone": (0.20, 0.90),
- "paper": (0.10, 0.35),
- "glass": (0.02, 0.05),
-}
-DEFAULT_VARIATION = (0.14, 0.55)
-
-#: blur radius (as a fraction of the tile) used to separate the tile's large-scale
-#: shading from the fine detail that actually is surface relief
-_DETAIL_BLUR_FRAC = 0.06
-
-
-def variation_for(family: str) -> tuple[float, float]:
- return VARIATION.get(family, DEFAULT_VARIATION)
-
-
-def _luminance(img: Image.Image) -> np.ndarray:
- a = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
- return 0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]
-
-
-def _blur(a: np.ndarray, radius: float) -> np.ndarray:
- """Gaussian blur of a 0..1 float array (through PIL, so no scipy dependency)."""
- img = Image.fromarray(np.round(np.clip(a, 0.0, 1.0) * 255).astype(np.uint8), mode="L")
- return np.asarray(img.filter(ImageFilter.GaussianBlur(radius)), dtype=np.float32) / 255.0
-
-
-def _detail(img: Image.Image) -> np.ndarray:
- """Luminance with its low-frequency component removed, rescaled to ~[-1, 1].
-
- Removing the low frequencies matters: a generated tile often has a broad
- lighting ramp baked in, and using raw luminance would turn that ramp into a
- roughness gradient across the whole part. The blurred reference is built from
- the SAME luminance array (not PIL's ``convert("L")``, which uses the ITU-R 601
- weights and would leave a constant offset behind on a solid colour).
- """
- lum = _luminance(img)
- d = lum - _blur(lum, max(1.0, _DETAIL_BLUR_FRAC * max(img.size)))
- scale = float(np.percentile(np.abs(d), 98))
- return np.clip(d / scale, -1.0, 1.0) if scale > 1e-6 else np.zeros_like(d)
-
-
-def roughness_array(albedo: Image.Image, base_roughness: float, family: str) -> np.ndarray:
- """Per-pixel roughness in 0..1: ``base - amplitude × detail`` (dark = rough)."""
- amp = variation_for(family)[0]
- return np.clip(float(base_roughness) - amp * _detail(albedo), 0.0, 1.0)
-
-
-def metallic_roughness_image(
- albedo: Image.Image, base_roughness: float, metallic: float, family: str
-) -> Image.Image:
- """glTF ``metallicRoughnessTexture``: R unused, **G = roughness**, **B = metallic**."""
- rough = roughness_array(albedo, base_roughness, family)
- h, w = rough.shape
- out = np.zeros((h, w, 3), dtype=np.uint8)
- out[..., 1] = np.round(rough * 255).astype(np.uint8)
- out[..., 2] = np.uint8(round(float(np.clip(metallic, 0.0, 1.0)) * 255))
- return Image.fromarray(out, mode="RGB")
-
-
-def normal_image(albedo: Image.Image, family: str, *, strength: float | None = None) -> Image.Image:
- """Tangent-space normal map from the albedo's detail, read as a height field.
-
- Gradients are taken with ``np.roll`` (wrap-around), so a tile that is seamless
- in albedo stays seamless in its normals.
- """
- s = variation_for(family)[1] if strength is None else float(strength)
- height = _detail(albedo)
- # central differences, wrapping at the tile edges
- dx = (np.roll(height, -1, axis=1) - np.roll(height, 1, axis=1)) * 0.5
- dy = (np.roll(height, -1, axis=0) - np.roll(height, 1, axis=0)) * 0.5
- nx, ny, nz = -dx * s * 4.0, dy * s * 4.0, np.ones_like(height)
- norm = np.sqrt(nx * nx + ny * ny + nz * nz)
- rgb = np.stack([nx / norm, ny / norm, nz / norm], axis=-1) * 0.5 + 0.5
- return Image.fromarray(np.round(np.clip(rgb, 0.0, 1.0) * 255).astype(np.uint8), mode="RGB")
-
-
-def is_flat(img: Image.Image, *, tol: float = 0.01) -> bool:
- """A tile with no detail at all (a solid colour): derived maps would be noise."""
- lum = _luminance(img)
- return bool(np.percentile(np.abs(lum - float(lum.mean())), 99) < tol)
-
-
-__all__ = [
- "DEFAULT_VARIATION", "VARIATION", "is_flat", "metallic_roughness_image", "normal_image",
- "roughness_array", "variation_for",
-]
diff --git a/harness/codeverse/texturing/materials.py b/harness/codeverse/texturing/materials.py
index f90e331e..9f939574 100644
--- a/harness/codeverse/texturing/materials.py
+++ b/harness/codeverse/texturing/materials.py
@@ -18,7 +18,7 @@ guides publish, and the clear-coat that separates lacquered wood from raw
timber. They are used two ways:
1. as the target of the **post-build normaliser**
- (:mod:`codeverse.texturing.normalise`), which fixes a material whose numbers
+ (:mod:`codeverse.texturing.apply`), which fixes a material whose numbers
are an untouched framework default or are impossible for the finish its own
name claims;
2. as the PBR factors the **texture pass** writes next to a generated albedo
diff --git a/harness/codeverse/texturing/normalise.py b/harness/codeverse/texturing/normalise.py
deleted file mode 100644
index 03f7f0c4..00000000
--- a/harness/codeverse/texturing/normalise.py
+++ /dev/null
@@ -1,233 +0,0 @@
-"""Post-build material normaliser: give a GLB's flat-default materials real PBR numbers.
-
-The agent authors the object's *colours*; what it forgets are the two numbers that
-decide whether a surface reads as the thing it is named after. Two failure modes
-show up in the recorded verdicts, and this pass fixes exactly those two — nothing
-else, so it can never repaint a deliberate choice:
-
-``untouched``
- metallic/roughness sit exactly on a framework default pair
- (glTF 1.0/1.0, three 0.0/1.0, Blender Principled 0.0/0.5). Nobody types those:
- they are what you get when the material was never configured. The glTF default
- in particular is *fully metallic, fully rough* — grey mud under any light.
-
-``impossible``
- the numbers are outside the physical band of the family the material's own
- name claims: a node called ``PolishedChrome`` at ``metallic 0.2``, a
- ``VarnishedBeech`` at ``metallic 0.8``, a ``CastIron`` at ``roughness 0.05``.
-
-Everything else is left alone. Base colour is **never** changed — that is the
-agent's design decision and the judge grades intent on it.
-
-Like the texture pass this is a *derived asset*: ``artifacts/object.glb`` and
-``src/`` are untouched. It runs as the first step of
-:func:`codeverse.texturing.run.texture_pass`, which writes the result to
-``textures/object_normalised.glb`` and textures on top of it.
-"""
-
-from __future__ import annotations
-
-import logging
-import time
-from pathlib import Path
-from typing import NamedTuple
-
-from pydantic import BaseModel, Field
-
-from codeverse.contracts.plan import StaticPlan
-from codeverse.conventions import to_snake
-from codeverse.spatial.measure import load_scene
-from codeverse.texturing.apply import verify_textured_glb
-from codeverse.texturing.materials import (
- FamilyMatch,
- family_for,
- is_framework_default,
- looks_painted,
- out_of_band,
- pbr_for,
-)
-
-log = logging.getLogger(__name__)
-
-
-class MaterialChange(BaseModel):
- node: str
- material: str = ""
- family: str
- keyword: str = ""
- reason: str # untouched | impossible
- metallic: tuple[float, float] # before, after
- roughness: tuple[float, float]
-
-
-class NormaliseReport(BaseModel):
- glb_out: str = ""
- changes: list[MaterialChange] = Field(default_factory=list)
- n_materials: int = 0
- n_unchanged: int = 0
- n_unresolved: int = 0
- warnings: list[str] = Field(default_factory=list)
- duration_ms: int = 0
-
- def changed(self) -> bool:
- return bool(self.changes)
-
- def table(self) -> str:
- if not self.changes:
- return "no material needed normalising"
- rows = [f"{'node':22} {'family':15} {'why':11} metallic roughness"]
- for c in self.changes:
- rows.append(f"{c.node[:22]:22} {c.family:15} {c.reason:11} "
- f"{c.metallic[0]:.2f}→{c.metallic[1]:.2f} {c.roughness[0]:.2f}→{c.roughness[1]:.2f}")
- return "\n".join(rows)
-
-
-def _plan_materials(plan: StaticPlan | None) -> dict[str, str]:
- """snake(part name) → the plan's ``material`` string for that part."""
- if plan is None:
- return {}
- return {to_snake(p.name): (p.material or p.description or "") for p in plan.parts}
-
-
-def _factors(mat: object) -> tuple[float | None, float | None]:
- m = getattr(mat, "metallicFactor", None)
- r = getattr(mat, "roughnessFactor", None)
- return (None if m is None else float(m)), (None if r is None else float(r))
-
-
-def _base_rgb(mat: object) -> tuple[float, float, float] | None:
- """``baseColorFactor`` as 0..1 RGB (trimesh stores it as 0-255 RGBA)."""
- f = getattr(mat, "baseColorFactor", None)
- if f is None or len(f) < 3:
- return None
- vals = [float(c) for c in f[:3]]
- scale = 255.0 if max(vals) > 1.0 else 1.0
- return (vals[0] / scale, vals[1] / scale, vals[2] / scale)
-
-
-def _has_texture(mat: object) -> bool:
- return any(getattr(mat, k, None) is not None
- for k in ("baseColorTexture", "metallicRoughnessTexture", "normalTexture"))
-
-
-class Verdict(NamedTuple):
- family: str
- reason: str # untouched | impossible
- keyword: str
- metallic: float
- roughness: float
-
-
-def _clamp(v: float, lo: float, hi: float) -> float:
- return round(min(hi, max(lo, v)), 3)
-
-
-def _evidence(material_name: str, node: str, plan_text: str) -> tuple[FamilyMatch | None, str]:
- """Best family match and WHERE it came from (``material`` > ``node`` > ``plan``)."""
- for tier, text in (("material", material_name), ("node", node), ("plan", plan_text)):
- hit = family_for(text)
- if hit is not None:
- return hit, tier
- return None, ""
-
-
-def classify(
- node: str, material_name: str, plan_text: str, metallic: float | None, roughness: float | None,
- base_rgb: tuple[float, float, float] | None = None,
-) -> Verdict | None:
- """What (if anything) to do with one material.
-
- ``untouched`` snaps to the family's canonical numbers; ``impossible`` only
- *clamps* the offending factor to the nearest edge of the family's plausible
- band, so an author's deliberate-but-extreme choice survives as far as physics
- allows. ``None`` = leave it exactly as it is."""
- hit, tier = _evidence(material_name, node, plan_text)
- if hit is None:
- return None
- family = hit.family
- if looks_painted(family, base_rgb):
- # a saturated colour on a "cast iron" part means paint over the iron
- family = "painted_wood" if family == "cast_iron" and (base_rgb or (0, 0, 0))[1] > 0.5 else "painted_metal"
- target = pbr_for(family)
- if target is None:
- return None
- if is_framework_default(metallic, roughness):
- return Verdict(target.family, "untouched", hit.keyword, target.metallic, target.roughness)
- if tier == "plan":
- # the plan's prose covers a whole part, not one material: it is good enough to
- # spot a never-configured default, never good enough to overrule real numbers
- return None
- bad = out_of_band(target, metallic, roughness)
- if not bad:
- return None
- m = 1.0 if metallic is None else float(metallic)
- r = 1.0 if roughness is None else float(roughness)
- return Verdict(
- target.family, "impossible", hit.keyword,
- _clamp(m, *target.metallic_band) if "metallic" in bad else m,
- _clamp(r, *target.roughness_band) if "roughness" in bad else r,
- )
-
-
-def normalise_materials(
- glb_in: Path | str, glb_out: Path | str, *, plan: StaticPlan | None = None, write: bool = True
-) -> NormaliseReport:
- """Rewrite the flat-default / impossible materials of ``glb_in`` into ``glb_out``.
-
- Geometry, node names, UVs and base colours are untouched; only
- ``metallicFactor`` / ``roughnessFactor`` move. When nothing needs changing the
- output is not written and ``report.glb_out`` stays empty.
- """
- t0 = time.time()
- glb_in, glb_out = Path(glb_in), Path(glb_out)
- scene = load_scene(glb_in)
- rep = NormaliseReport()
- plan_mats = _plan_materials(plan)
- seen: dict[int, tuple[float, float] | None] = {}
- for node in scene.graph.nodes_geometry:
- _, geom_name = scene.graph.get(node)
- geom = scene.geometry.get(geom_name) if geom_name else None
- mat = getattr(getattr(geom, "visual", None), "material", None)
- if mat is None:
- rep.n_unresolved += 1
- continue
- if id(mat) in seen: # a material shared by several nodes is normalised once
- continue
- rep.n_materials += 1
- if _has_texture(mat):
- rep.n_unchanged += 1
- seen[id(mat)] = None
- continue
- metallic, roughness = _factors(mat)
- snake = to_snake(node)
- plan_text = plan_mats.get(snake) or plan_mats.get(to_snake(node.split("__", 1)[0])) or ""
- verdict = classify(node, str(getattr(mat, "name", "") or ""), plan_text, metallic, roughness,
- _base_rgb(mat))
- if verdict is None:
- rep.n_unchanged += 1
- seen[id(mat)] = None
- continue
- before = (1.0 if metallic is None else metallic, 1.0 if roughness is None else roughness)
- mat.metallicFactor = float(verdict.metallic)
- mat.roughnessFactor = float(verdict.roughness)
- seen[id(mat)] = (verdict.metallic, verdict.roughness)
- rep.changes.append(MaterialChange(
- node=node, material=str(getattr(mat, "name", "") or ""), family=verdict.family,
- keyword=verdict.keyword, reason=verdict.reason,
- metallic=(round(before[0], 3), verdict.metallic), roughness=(round(before[1], 3), verdict.roughness),
- ))
- if rep.changes and write:
- glb_out.parent.mkdir(parents=True, exist_ok=True)
- scene.export(glb_out)
- rep.glb_out = str(glb_out)
- rep.warnings.extend(_verify(glb_in, glb_out))
- rep.duration_ms = int((time.time() - t0) * 1000)
- return rep
-
-
-def _verify(glb_in: Path, glb_out: Path) -> list[str]:
- """Same nodes, same triangles — this pass may only move two floats per material."""
- return verify_textured_glb(glb_in, glb_out, expected_textured=0)
-
-
-__all__ = ["MaterialChange", "NormaliseReport", "Verdict", "classify", "normalise_materials"]
diff --git a/harness/codeverse/texturing/plan.py b/harness/codeverse/texturing/plan.py
index aa772b04..4c562e08 100644
--- a/harness/codeverse/texturing/plan.py
+++ b/harness/codeverse/texturing/plan.py
@@ -9,6 +9,7 @@ skip) validated in code with deterministic defaults, cached by content hash.
from __future__ import annotations
import hashlib
+import json
import logging
from collections.abc import Sequence
from pathlib import Path
@@ -20,11 +21,12 @@ from codeverse.config import get_settings
from codeverse.contracts.artifacts import RenderSet
from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
from codeverse.contracts.common import Usage
-from codeverse.contracts.plan import PartPlan, StaticPlan
+from codeverse.contracts.plan import PartPlan, ScenePlan, StaticPlan
from codeverse.contracts.spec import Spec
from codeverse.conventions import to_snake
from codeverse.models.schema_utils import parse_json_lenient
from codeverse.prompts import load_text, prompt_hash, render
+from codeverse.texturing.generate import TextureSet, generate_textures
log = logging.getLogger(__name__)
@@ -342,3 +344,211 @@ def plan_table(tp: TexturePlan) -> str:
f"{p.roughness:<5.2f} {p.metallic:<4.1f} {'yes' if p.skip else 'no'}{(' — ' + p.reason) if p.skip and p.reason else ''}")
return "\n".join(rows)
+
+# ===================================================================== scene_pack
+# (merged from codeverse/texturing/scene_pack.py, 2026-08-28)
+log = logging.getLogger(__name__)
+
+PACK_TEMPLATE = "texturing/scene_pack.md"
+DEFAULT_URL_PREFIX = "/public/textures"
+MANIFEST_NAME = "manifest.json"
+
+
+class PackEntry(BaseModel):
+ name: str
+ material_family: MaterialFamily = "other"
+ subject: str = ""
+ prompt: str = ""
+ tile_size_m: float = Field(default=1.0, gt=0.0, le=50.0)
+ role: str = "ground"
+ roughness: float = Field(default=0.8, ge=0.0, le=1.0)
+ metallic: float = Field(default=0.0, ge=0.0, le=1.0)
+ file: str = ""
+ seam_score: float = 0.0
+ error: str = ""
+
+
+class PackOutput(BaseModel):
+ textures: list[PackEntry]
+ notes: str = ""
+
+
+class ScenePack(BaseModel):
+ out_dir: str
+ entries: dict[str, PackEntry] = Field(default_factory=dict)
+ notes: str = ""
+ model_id: str = ""
+ source: str = "default"
+ usage: Usage = Field(default_factory=Usage)
+ manifest_path: str = ""
+
+ def manifest(self) -> dict[str, dict[str, Any]]:
+ return {n: {"file": e.file, "tile_size_m": e.tile_size_m, "family": e.material_family, "role": e.role,
+ "prompt": e.prompt, "seam_score": e.seam_score, "roughness": e.roughness, "metallic": e.metallic}
+ for n, e in self.entries.items() if e.file and not e.error}
+
+
+# --------------------------------------------------------------------------- planning
+_GROUND_RULES: list[tuple[tuple[str, ...], PackEntry]] = [
+ (("grass", "lawn", "meadow", "garden", "park"), PackEntry(name="grass_ground", subject="short green lawn grass seen from above, fine blades, slight colour variation", tile_size_m=1.5, role="ground")),
+ (("moss", "mossy", "forest", "woodland"), PackEntry(name="moss_ground", subject="dense green moss carpet, soft velvety clumps", tile_size_m=1.0, role="ground")),
+ (("gravel", "karesansui", "zen", "raked"), PackEntry(name="fine_gravel", material_family="stone", subject="fine pale grey granite gravel, small even pebbles", tile_size_m=0.8, role="ground")),
+ (("sand", "beach", "desert", "dune"), PackEntry(name="sand_ground", subject="fine pale beige sand with soft ripples", tile_size_m=1.0, role="ground")),
+ (("soil", "dirt", "earth", "mud", "path", "trail"), PackEntry(name="packed_soil", subject="dark brown packed earth with small pebbles", tile_size_m=1.0, role="path")),
+ (("cobble", "pavement", "plaza", "street", "square", "town"), PackEntry(name="cobblestone", material_family="stone", subject="grey granite cobblestones with dark mortar joints", tile_size_m=1.2, role="path")),
+ (("stone", "rock", "boulder", "granite", "cliff"), PackEntry(name="rough_granite", material_family="stone", subject="rough grey granite rock with lichen speckles", tile_size_m=1.0, role="prop")),
+ (("wood", "plank", "bridge", "deck", "dock", "pier", "timber", "cabin", "fence"), PackEntry(name="weathered_planks", material_family="wood", subject="weathered grey-brown wooden planks, straight grain, narrow gaps", tile_size_m=0.8, role="prop")),
+ (("roof", "tile", "shingle", "house", "temple", "hut"), PackEntry(name="clay_roof_tiles", material_family="ceramic", subject="terracotta clay roof tiles in overlapping rows", tile_size_m=1.0, role="roof")),
+ (("brick", "wall"), PackEntry(name="red_brick", material_family="stone", subject="red clay bricks with light grey mortar, running bond", tile_size_m=1.0, role="wall")),
+ (("bark", "tree", "trunk", "maple", "oak", "pine"), PackEntry(name="tree_bark", material_family="wood", subject="dark grey-brown tree bark with vertical furrows", tile_size_m=0.5, role="prop")),
+ (("water", "pond", "lake", "river", "sea", "harbour", "harbor"), PackEntry(name="pond_bed", material_family="stone", subject="dark silty pond bed with scattered small pebbles and algae", tile_size_m=1.0, role="water_bed")),
+ (("fabric", "tent", "cloth", "banner", "awning", "canvas"), PackEntry(name="canvas_fabric", material_family="fabric", subject="natural off-white woven canvas", tile_size_m=0.3, role="fabric")),
+ (("metal", "steel", "iron", "rust"), PackEntry(name="rusty_steel", material_family="metal", subject="rust-streaked painted steel plate, matte", tile_size_m=0.5, role="prop")),
+ (("concrete", "asphalt", "road", "industrial"), PackEntry(name="concrete", material_family="stone", subject="smooth grey concrete with fine pores", tile_size_m=1.0, role="ground")),
+ (("bamboo",), PackEntry(name="bamboo_poles", material_family="wood", subject="vertical cured yellow bamboo poles with dark nodes", tile_size_m=0.5, role="prop")),
+]
+
+
+def _plan_text(plan: ScenePlan) -> str:
+ bits = [plan.title, plan.summary, plan.setting, plan.mood, plan.environment]
+ bits += [f"{z.name} {z.description}" for z in plan.zones]
+ bits += [f"{a.name} {a.description}" for a in plan.assets]
+ return " ".join(bits)
+
+
+def _finalize_entry(e: PackEntry) -> PackEntry:
+ fam = e.material_family if e.material_family in FAMILY_DEFAULTS else "other"
+ d = FAMILY_DEFAULTS[fam]
+ name = to_snake(e.name) or f"{fam}_texture"
+ subject = e.subject.strip() or name.replace("_", " ")
+ return e.model_copy(update={
+ "name": name, "material_family": fam, "subject": subject, "prompt": compose_image_prompt(subject, fam),
+ "tile_size_m": float(e.tile_size_m) if e.tile_size_m > 0 else d.tile_size_m,
+ "roughness": float(e.roughness) if e.roughness is not None else d.roughness,
+ "metallic": float(e.metallic) if e.metallic is not None else d.metallic,
+ })
+
+
+def default_scene_pack_plan(plan: ScenePlan, *, n_min: int = 6, n_max: int = 12) -> list[PackEntry]:
+ """Keyword fallback: textures whose trigger words appear in the plan; always a
+ ground; padded with generic ground/stone/wood up to ``n_min``."""
+ words = set(to_snake(_plan_text(plan)).split("_"))
+ out: list[PackEntry] = []
+ for keys, entry in _GROUND_RULES:
+ if any(k in words for k in keys) and len(out) < n_max:
+ out.append(entry)
+ names = {e.name for e in out}
+ for _, entry in _GROUND_RULES:
+ if len(out) >= n_min:
+ break
+ if entry.name not in names:
+ out.append(entry)
+ names.add(entry.name)
+ return [_finalize_entry(e) for e in out[:n_max]]
+
+
+def scene_pack_plan(
+ plan: ScenePlan, model_id: str, *, model: Any | None = None, n_min: int = 6, n_max: int = 12, temperature: float = 0.4,
+) -> tuple[list[PackEntry], str, Usage]:
+ """Structured text call → entries. Empty ``model_id`` and no model → default plan."""
+ if not model_id and model is None:
+ return default_scene_pack_plan(plan, n_min=n_min, n_max=n_max), "default", Usage()
+ if model is None:
+ from codeverse.models import get_chat_model
+
+ model = get_chat_model(model_id)
+ zones = "\n".join(f"- {z.name}: {z.description}" for z in plan.zones)
+ assets = "\n".join(f"- {a.name} ({a.kind}): {a.description}" for a in plan.assets) or "- (none)"
+ text = render(PACK_TEMPLATE, n_min=n_min, n_max=n_max, title=plan.title, setting=plan.setting, mood=plan.mood,
+ environment=plan.environment, zones=zones, assets=assets)
+ req = ChatRequest(messages=[ChatMessage.user(text)], system="You plan texture packs for 3D scenes. JSON only.",
+ response_schema=PackOutput.model_json_schema(), temperature=temperature, thinking="low",
+ max_output_tokens=65_536, max_wait_s=900.0, label="scene_texture_pack")
+ resp = model.generate(req)
+ payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
+ try:
+ out = PackOutput.model_validate(payload)
+ except ValidationError as e:
+ raise ValueError(f"scene pack planner returned invalid JSON: {e}") from e
+ entries: list[PackEntry] = []
+ seen: set[str] = set()
+ for e in out.textures:
+ fe = _finalize_entry(e)
+ if fe.name in seen:
+ continue
+ seen.add(fe.name)
+ entries.append(fe)
+ if not entries:
+ raise ValueError("scene pack planner returned no textures")
+ return entries[:n_max], out.notes, resp.usage
+
+
+# --------------------------------------------------------------------------- generation
+def scene_texture_pack(
+ scene_plan: ScenePlan,
+ out_dir: Path,
+ image_model: Any,
+ model_id: str = "",
+ *,
+ model: Any | None = None,
+ size: int = 1024,
+ cache_dir: Path | None = None,
+ n_min: int = 6,
+ n_max: int = 12,
+ max_workers: int = 6,
+ use_cache: bool = True,
+) -> ScenePack:
+ """Plan + generate the pack into ``out_dir`` and write ``manifest.json``."""
+ out_dir = Path(out_dir)
+ entries, notes, usage = scene_pack_plan(scene_plan, model_id, model=model, n_min=n_min, n_max=n_max)
+ pack = ScenePack(out_dir=str(out_dir), notes=notes, model_id=model_id, source="vlm" if (model_id or model) else "default",
+ usage=usage)
+ ts: TextureSet = generate_textures({e.name: e.prompt for e in entries}, out_dir, image_model, size=size,
+ cache_dir=cache_dir, max_workers=max_workers, use_cache=use_cache)
+ pack.usage = pack.usage + ts.usage
+ for e in entries:
+ a = ts.textures.get(e.name)
+ if a is None:
+ continue
+ e = e.model_copy(update={"file": Path(a.path).name if a.ok else "", "seam_score": round(a.seam_score, 4), "error": a.error})
+ pack.entries[e.name] = e
+ pack.manifest_path = str(write_manifest(pack, out_dir))
+ return pack
+
+
+def write_manifest(pack: ScenePack, out_dir: Path) -> Path:
+ p = Path(out_dir) / MANIFEST_NAME
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps(pack.manifest(), indent=2))
+ return p
+
+
+def load_manifest(path: Path) -> dict[str, dict[str, Any]]:
+ p = Path(path)
+ if p.is_dir():
+ p = p / MANIFEST_NAME
+ return json.loads(p.read_text())
+
+
+def texture_pack_prompt(manifest: dict[str, dict[str, Any]], *, url_prefix: str = DEFAULT_URL_PREFIX) -> str:
+ """Prompt snippet for zone/env generation: what exists and the exact loading idiom."""
+ if not manifest:
+ return ""
+ lines = ["## Available textures (seamless tileable albedo PNGs, generated for this scene)"]
+ for name, e in manifest.items():
+ lines.append(f"- `{url_prefix}/{e['file']}` — {name} ({e.get('family', 'other')}, {e.get('role', '')}; "
+ f"one tile = {float(e['tile_size_m']):.2f} m; roughness {float(e.get('roughness', 0.8)):.2f})")
+ lines.append(
+ "Load with the provided loader ONLY (no TextureLoader of your own, no DataTexture):\n"
+ "```js\n"
+ f"const tex = loaders.texture.load('{url_prefix}/{next(iter(manifest.values()))['file']}');\n"
+ "tex.wrapS = tex.wrapT = THREE.RepeatWrapping;\n"
+ "tex.colorSpace = THREE.SRGBColorSpace;\n"
+ "tex.anisotropy = 8;\n"
+ "tex.repeat.set(sizeX / TILE_M, sizeZ / TILE_M); // TILE_M = the tile size listed above, sizeX/Z = the surface's world size in m\n"
+ "const mat = new THREE.MeshStandardMaterial({ map: tex, roughness: 0.8, metalness: 0.0 });\n"
+ "```\n"
+ "Use `texture.clone()` (+ `needsUpdate = true`) when the same image needs a different repeat. "
+ "Keep vertex-colour / procedural materials where no texture fits; never invent texture URLs."
+ )
+ return "\n".join(lines)
diff --git a/harness/codeverse/texturing/run.py b/harness/codeverse/texturing/run.py
index a1708baa..2c2f98b9 100644
--- a/harness/codeverse/texturing/run.py
+++ b/harness/codeverse/texturing/run.py
@@ -32,10 +32,20 @@ from codeverse.contracts.plan import StaticPlan
from codeverse.contracts.spec import Spec
from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
from codeverse.events import EventLog
-from codeverse.texturing.apply import ApplyReport, apply_textures
-from codeverse.texturing.gate import GateResult, SeamGateResult, judge_gate, seam_gate
-from codeverse.texturing.generate import TextureSet, generate_textures
-from codeverse.texturing.normalise import NormaliseReport, normalise_materials
+from codeverse.texturing.apply import (
+ ApplyReport,
+ NormaliseReport,
+ apply_textures,
+ normalise_materials,
+)
+from codeverse.texturing.generate import (
+ GateResult,
+ SeamGateResult,
+ TextureSet,
+ generate_textures,
+ judge_gate,
+ seam_gate,
+)
from codeverse.texturing.plan import TexturePlan, material_plan
from codeverse.workspace import Workspace
@@ -183,7 +193,7 @@ def texture_pass(
keyword arguments win over the bundle.
``normalise=True`` first runs the deterministic material normaliser
- (:func:`codeverse.texturing.normalise.normalise_materials`) over the input GLB,
+ (:func:`codeverse.texturing.apply.normalise_materials`) over the input GLB,
so the parts the texture pass *skips* — chrome, glass, tiny hardware — still get
plausible metallic/roughness numbers. It costs no model call, and the same
before/after judge gate (BEFORE is always the untouched ``glb_in``) decides
diff --git a/harness/codeverse/texturing/scene_pack.py b/harness/codeverse/texturing/scene_pack.py
deleted file mode 100644
index 3f881075..00000000
--- a/harness/codeverse/texturing/scene_pack.py
+++ /dev/null
@@ -1,239 +0,0 @@
-"""Scene texture pack: the 6-12 tileable albedo textures a ``ScenePlan`` implies,
-generated BEFORE zone generation so scene code can load them.
-
-* ``scene_pack_plan(plan, model_id)``: one text-only structured call → entries
- (name, family, subject, tile size, role, PBR factors); ``default_scene_pack_plan``
- is the keyword fallback (no model).
-* ``scene_texture_pack(plan, out_dir, image_model, model_id)``: generate + seam-fix
- → ``out_dir/<name>.png`` + ``out_dir/manifest.json``
- ``{name: {file, tile_size_m, family, role, prompt, seam_score}}``.
-* ``texture_pack_prompt(manifest)``: the snippet the scene track injects into zone /
- env prompts (URL, tile size, exact three.js loading lines).
-
-Served URL: the workspace root is served at ``/`` (``runtime_js/lib/host_coverage.mjs``),
-so ``public/textures/<name>.png`` is reachable as ``/public/textures/<name>.png``.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-from pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel, Field, ValidationError
-
-from codeverse.contracts.chat import ChatMessage, ChatRequest
-from codeverse.contracts.common import Usage
-from codeverse.contracts.plan import ScenePlan
-from codeverse.conventions import to_snake
-from codeverse.models.schema_utils import parse_json_lenient
-from codeverse.prompts import render
-from codeverse.texturing.generate import TextureSet, generate_textures
-from codeverse.texturing.plan import FAMILY_DEFAULTS, MaterialFamily, compose_image_prompt
-
-log = logging.getLogger(__name__)
-
-PACK_TEMPLATE = "texturing/scene_pack.md"
-DEFAULT_URL_PREFIX = "/public/textures"
-MANIFEST_NAME = "manifest.json"
-
-
-class PackEntry(BaseModel):
- name: str
- material_family: MaterialFamily = "other"
- subject: str = ""
- prompt: str = ""
- tile_size_m: float = Field(default=1.0, gt=0.0, le=50.0)
- role: str = "ground"
- roughness: float = Field(default=0.8, ge=0.0, le=1.0)
- metallic: float = Field(default=0.0, ge=0.0, le=1.0)
- file: str = ""
- seam_score: float = 0.0
- error: str = ""
-
-
-class PackOutput(BaseModel):
- textures: list[PackEntry]
- notes: str = ""
-
-
-class ScenePack(BaseModel):
- out_dir: str
- entries: dict[str, PackEntry] = Field(default_factory=dict)
- notes: str = ""
- model_id: str = ""
- source: str = "default"
- usage: Usage = Field(default_factory=Usage)
- manifest_path: str = ""
-
- def manifest(self) -> dict[str, dict[str, Any]]:
- return {n: {"file": e.file, "tile_size_m": e.tile_size_m, "family": e.material_family, "role": e.role,
- "prompt": e.prompt, "seam_score": e.seam_score, "roughness": e.roughness, "metallic": e.metallic}
- for n, e in self.entries.items() if e.file and not e.error}
-
-
-# --------------------------------------------------------------------------- planning
-_GROUND_RULES: list[tuple[tuple[str, ...], PackEntry]] = [
- (("grass", "lawn", "meadow", "garden", "park"), PackEntry(name="grass_ground", subject="short green lawn grass seen from above, fine blades, slight colour variation", tile_size_m=1.5, role="ground")),
- (("moss", "mossy", "forest", "woodland"), PackEntry(name="moss_ground", subject="dense green moss carpet, soft velvety clumps", tile_size_m=1.0, role="ground")),
- (("gravel", "karesansui", "zen", "raked"), PackEntry(name="fine_gravel", material_family="stone", subject="fine pale grey granite gravel, small even pebbles", tile_size_m=0.8, role="ground")),
- (("sand", "beach", "desert", "dune"), PackEntry(name="sand_ground", subject="fine pale beige sand with soft ripples", tile_size_m=1.0, role="ground")),
- (("soil", "dirt", "earth", "mud", "path", "trail"), PackEntry(name="packed_soil", subject="dark brown packed earth with small pebbles", tile_size_m=1.0, role="path")),
- (("cobble", "pavement", "plaza", "street", "square", "town"), PackEntry(name="cobblestone", material_family="stone", subject="grey granite cobblestones with dark mortar joints", tile_size_m=1.2, role="path")),
- (("stone", "rock", "boulder", "granite", "cliff"), PackEntry(name="rough_granite", material_family="stone", subject="rough grey granite rock with lichen speckles", tile_size_m=1.0, role="prop")),
- (("wood", "plank", "bridge", "deck", "dock", "pier", "timber", "cabin", "fence"), PackEntry(name="weathered_planks", material_family="wood", subject="weathered grey-brown wooden planks, straight grain, narrow gaps", tile_size_m=0.8, role="prop")),
- (("roof", "tile", "shingle", "house", "temple", "hut"), PackEntry(name="clay_roof_tiles", material_family="ceramic", subject="terracotta clay roof tiles in overlapping rows", tile_size_m=1.0, role="roof")),
- (("brick", "wall"), PackEntry(name="red_brick", material_family="stone", subject="red clay bricks with light grey mortar, running bond", tile_size_m=1.0, role="wall")),
- (("bark", "tree", "trunk", "maple", "oak", "pine"), PackEntry(name="tree_bark", material_family="wood", subject="dark grey-brown tree bark with vertical furrows", tile_size_m=0.5, role="prop")),
- (("water", "pond", "lake", "river", "sea", "harbour", "harbor"), PackEntry(name="pond_bed", material_family="stone", subject="dark silty pond bed with scattered small pebbles and algae", tile_size_m=1.0, role="water_bed")),
- (("fabric", "tent", "cloth", "banner", "awning", "canvas"), PackEntry(name="canvas_fabric", material_family="fabric", subject="natural off-white woven canvas", tile_size_m=0.3, role="fabric")),
- (("metal", "steel", "iron", "rust"), PackEntry(name="rusty_steel", material_family="metal", subject="rust-streaked painted steel plate, matte", tile_size_m=0.5, role="prop")),
- (("concrete", "asphalt", "road", "industrial"), PackEntry(name="concrete", material_family="stone", subject="smooth grey concrete with fine pores", tile_size_m=1.0, role="ground")),
- (("bamboo",), PackEntry(name="bamboo_poles", material_family="wood", subject="vertical cured yellow bamboo poles with dark nodes", tile_size_m=0.5, role="prop")),
-]
-
-
-def _plan_text(plan: ScenePlan) -> str:
- bits = [plan.title, plan.summary, plan.setting, plan.mood, plan.environment]
- bits += [f"{z.name} {z.description}" for z in plan.zones]
- bits += [f"{a.name} {a.description}" for a in plan.assets]
- return " ".join(bits)
-
-
-def _finalize_entry(e: PackEntry) -> PackEntry:
- fam = e.material_family if e.material_family in FAMILY_DEFAULTS else "other"
- d = FAMILY_DEFAULTS[fam]
- name = to_snake(e.name) or f"{fam}_texture"
- subject = e.subject.strip() or name.replace("_", " ")
- return e.model_copy(update={
- "name": name, "material_family": fam, "subject": subject, "prompt": compose_image_prompt(subject, fam),
- "tile_size_m": float(e.tile_size_m) if e.tile_size_m > 0 else d.tile_size_m,
- "roughness": float(e.roughness) if e.roughness is not None else d.roughness,
- "metallic": float(e.metallic) if e.metallic is not None else d.metallic,
- })
-
-
-def default_scene_pack_plan(plan: ScenePlan, *, n_min: int = 6, n_max: int = 12) -> list[PackEntry]:
- """Keyword fallback: textures whose trigger words appear in the plan; always a
- ground; padded with generic ground/stone/wood up to ``n_min``."""
- words = set(to_snake(_plan_text(plan)).split("_"))
- out: list[PackEntry] = []
- for keys, entry in _GROUND_RULES:
- if any(k in words for k in keys) and len(out) < n_max:
- out.append(entry)
- names = {e.name for e in out}
- for _, entry in _GROUND_RULES:
- if len(out) >= n_min:
- break
- if entry.name not in names:
- out.append(entry)
- names.add(entry.name)
- return [_finalize_entry(e) for e in out[:n_max]]
-
-
-def scene_pack_plan(
- plan: ScenePlan, model_id: str, *, model: Any | None = None, n_min: int = 6, n_max: int = 12, temperature: float = 0.4,
-) -> tuple[list[PackEntry], str, Usage]:
- """Structured text call → entries. Empty ``model_id`` and no model → default plan."""
- if not model_id and model is None:
- return default_scene_pack_plan(plan, n_min=n_min, n_max=n_max), "default", Usage()
- if model is None:
- from codeverse.models import get_chat_model
-
- model = get_chat_model(model_id)
- zones = "\n".join(f"- {z.name}: {z.description}" for z in plan.zones)
- assets = "\n".join(f"- {a.name} ({a.kind}): {a.description}" for a in plan.assets) or "- (none)"
- text = render(PACK_TEMPLATE, n_min=n_min, n_max=n_max, title=plan.title, setting=plan.setting, mood=plan.mood,
- environment=plan.environment, zones=zones, assets=assets)
- req = ChatRequest(messages=[ChatMessage.user(text)], system="You plan texture packs for 3D scenes. JSON only.",
- response_schema=PackOutput.model_json_schema(), temperature=temperature, thinking="low",
- max_output_tokens=65_536, max_wait_s=900.0, label="scene_texture_pack")
- resp = model.generate(req)
- payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
- try:
- out = PackOutput.model_validate(payload)
- except ValidationError as e:
- raise ValueError(f"scene pack planner returned invalid JSON: {e}") from e
- entries: list[PackEntry] = []
- seen: set[str] = set()
- for e in out.textures:
- fe = _finalize_entry(e)
- if fe.name in seen:
- continue
- seen.add(fe.name)
- entries.append(fe)
- if not entries:
- raise ValueError("scene pack planner returned no textures")
- return entries[:n_max], out.notes, resp.usage
-
-
-# --------------------------------------------------------------------------- generation
-def scene_texture_pack(
- scene_plan: ScenePlan,
- out_dir: Path,
- image_model: Any,
- model_id: str = "",
- *,
- model: Any | None = None,
- size: int = 1024,
- cache_dir: Path | None = None,
- n_min: int = 6,
- n_max: int = 12,
- max_workers: int = 6,
- use_cache: bool = True,
-) -> ScenePack:
- """Plan + generate the pack into ``out_dir`` and write ``manifest.json``."""
- out_dir = Path(out_dir)
- entries, notes, usage = scene_pack_plan(scene_plan, model_id, model=model, n_min=n_min, n_max=n_max)
- pack = ScenePack(out_dir=str(out_dir), notes=notes, model_id=model_id, source="vlm" if (model_id or model) else "default",
- usage=usage)
- ts: TextureSet = generate_textures({e.name: e.prompt for e in entries}, out_dir, image_model, size=size,
- cache_dir=cache_dir, max_workers=max_workers, use_cache=use_cache)
- pack.usage = pack.usage + ts.usage
- for e in entries:
- a = ts.textures.get(e.name)
- if a is None:
- continue
- e = e.model_copy(update={"file": Path(a.path).name if a.ok else "", "seam_score": round(a.seam_score, 4), "error": a.error})
- pack.entries[e.name] = e
- pack.manifest_path = str(write_manifest(pack, out_dir))
- return pack
-
-
-def write_manifest(pack: ScenePack, out_dir: Path) -> Path:
- p = Path(out_dir) / MANIFEST_NAME
- p.parent.mkdir(parents=True, exist_ok=True)
- p.write_text(json.dumps(pack.manifest(), indent=2))
- return p
-
-
-def load_manifest(path: Path) -> dict[str, dict[str, Any]]:
- p = Path(path)
- if p.is_dir():
- p = p / MANIFEST_NAME
- return json.loads(p.read_text())
-
-
-def texture_pack_prompt(manifest: dict[str, dict[str, Any]], *, url_prefix: str = DEFAULT_URL_PREFIX) -> str:
- """Prompt snippet for zone/env generation: what exists and the exact loading idiom."""
- if not manifest:
- return ""
- lines = ["## Available textures (seamless tileable albedo PNGs, generated for this scene)"]
- for name, e in manifest.items():
- lines.append(f"- `{url_prefix}/{e['file']}` — {name} ({e.get('family', 'other')}, {e.get('role', '')}; "
- f"one tile = {float(e['tile_size_m']):.2f} m; roughness {float(e.get('roughness', 0.8)):.2f})")
- lines.append(
- "Load with the provided loader ONLY (no TextureLoader of your own, no DataTexture):\n"
- "```js\n"
- f"const tex = loaders.texture.load('{url_prefix}/{next(iter(manifest.values()))['file']}');\n"
- "tex.wrapS = tex.wrapT = THREE.RepeatWrapping;\n"
- "tex.colorSpace = THREE.SRGBColorSpace;\n"
- "tex.anisotropy = 8;\n"
- "tex.repeat.set(sizeX / TILE_M, sizeZ / TILE_M); // TILE_M = the tile size listed above, sizeX/Z = the surface's world size in m\n"
- "const mat = new THREE.MeshStandardMaterial({ map: tex, roughness: 0.8, metalness: 0.0 });\n"
- "```\n"
- "Use `texture.clone()` (+ `needsUpdate = true`) when the same image needs a different repeat. "
- "Keep vertex-colour / procedural materials where no texture fits; never invent texture URLs."
- )
- return "\n".join(lines)
diff --git a/harness/codeverse/texturing/tile.py b/harness/codeverse/texturing/tile.py
deleted file mode 100644
index 7edbd501..00000000
--- a/harness/codeverse/texturing/tile.py
+++ /dev/null
@@ -1,118 +0,0 @@
-"""Tileability: seam scoring, mirror-blend seam fixing, resizing and saving.
-
-* ``seam_score(img)``: mean absolute difference (0..1) between the left/right and
- top/bottom wrap edges, normalised by the image's own local contrast so a noisy
- texture is not penalised for being noisy. ≈0 = perfect wrap.
-* ``make_tileable(img, border_frac)``: cross-fades each edge band with the mirrored
- opposite band (a smoothstep ramp over ``border_frac`` of the width) so the wrap
- seam disappears; content in the middle is untouched.
-* ``offset_check(img)``: half-offset the image (seams move to the centre) — the
- classic visual check; returns the offset image for inspection.
-* ``fit_size`` / ``save_texture``: power-of-two downscale + PNG or JPEG q90.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-import numpy as np
-from PIL import Image
-
-#: seam score above which a texture is considered NOT tileable (after make_tileable)
-SEAM_MAX = 0.08
-
-
-def _arr(img: Image.Image) -> np.ndarray:
- return np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
-
-
-def seam_score(img: Image.Image | np.ndarray) -> float:
- """Mean |Δ| across the wrap seams relative to the mean |Δ| between neighbouring
- pixel columns/rows inside the image (so 1.0 ≈ 'the seam is as strong as the
- texture's own detail'); clamped to [0, 1]."""
- a = _arr(img) if isinstance(img, Image.Image) else np.asarray(img, dtype=np.float32)
- if a.ndim == 2:
- a = a[:, :, None]
- h, w = a.shape[:2]
- if h < 4 or w < 4:
- return 0.0
- seam_lr = np.abs(a[:, 0, :] - a[:, -1, :]).mean()
- seam_tb = np.abs(a[0, :, :] - a[-1, :, :]).mean()
- # typical one-step difference inside the image (excluding the seam)
- inner_lr = np.abs(a[:, 1:, :] - a[:, :-1, :]).mean()
- inner_tb = np.abs(a[1:, :, :] - a[:-1, :, :]).mean()
- # a seam is bad when it exceeds the local detail noticeably; blend absolute + relative
- rel = 0.5 * (seam_lr / max(inner_lr, 1e-3) + seam_tb / max(inner_tb, 1e-3))
- absolute = 0.5 * (seam_lr + seam_tb)
- score = 0.5 * absolute + 0.5 * min(1.0, max(0.0, (rel - 1.0) / 8.0))
- return float(min(1.0, max(0.0, score)))
-
-
-def _ramp(n: int) -> np.ndarray:
- t = (np.arange(n, dtype=np.float32) + 0.5) / n
- return t * t * (3.0 - 2.0 * t) # smoothstep 0 → 1
-
-
-def make_tileable(img: Image.Image, border_frac: float = 0.12) -> Image.Image:
- """Mirror-blend the wrap seams. Along X: the left band is cross-faded with the
- mirrored right band and vice versa (weights symmetric so the wrap is exact);
- then the same along Y. ``border_frac`` ∈ [0.05, 0.3] of the size."""
- border_frac = float(min(0.3, max(0.05, border_frac)))
- a = _arr(img)
- h, w = a.shape[:2]
- bw, bh = max(2, int(round(w * border_frac))), max(2, int(round(h * border_frac)))
- out = a.copy()
- # horizontal: blend left band with mirrored right band
- r = _ramp(bw)[None, :, None] # 0 at the outer edge → 1 inside
- left, right = a[:, :bw, :], a[:, w - bw:, :]
- mir_right = right[:, ::-1, :] # right band mirrored so its outer edge meets the left edge
- mir_left = left[:, ::-1, :]
- out[:, :bw, :] = left * (0.5 + 0.5 * r) + mir_right * (0.5 - 0.5 * r)
- out[:, w - bw:, :] = right * (0.5 + 0.5 * r[:, ::-1, :]) + mir_left * (0.5 - 0.5 * r[:, ::-1, :])
- a = out.copy()
- r = _ramp(bh)[:, None, None]
- top, bottom = a[:bh, :, :], a[h - bh:, :, :]
- mir_bottom, mir_top = bottom[::-1, :, :], top[::-1, :, :]
- out[:bh, :, :] = top * (0.5 + 0.5 * r) + mir_bottom * (0.5 - 0.5 * r)
- out[h - bh:, :, :] = bottom * (0.5 + 0.5 * r[::-1, :, :]) + mir_top * (0.5 - 0.5 * r[::-1, :, :])
- return Image.fromarray((np.clip(out, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8), "RGB")
-
-
-def offset_check(img: Image.Image) -> Image.Image:
- """Roll the image by half its size so the wrap seams sit in the centre."""
- a = _arr(img)
- h, w = a.shape[:2]
- rolled = np.roll(np.roll(a, w // 2, axis=1), h // 2, axis=0)
- return Image.fromarray((rolled * 255.0 + 0.5).astype(np.uint8), "RGB")
-
-
-def fit_size(img: Image.Image, size: int) -> Image.Image:
- """Square, power-of-two-ish downscale to ``size`` (never upscales)."""
- w, h = img.size
- if w != h:
- s = min(w, h)
- img = img.crop(((w - s) // 2, (h - s) // 2, (w - s) // 2 + s, (h - s) // 2 + s))
- if img.size[0] > size:
- img = img.resize((size, size), Image.LANCZOS)
- return img.convert("RGB")
-
-
-def save_texture(img: Image.Image, path: Path, *, fmt: str | None = None, quality: int = 90) -> Path:
- path = Path(path)
- path.parent.mkdir(parents=True, exist_ok=True)
- fmt = (fmt or ("JPEG" if path.suffix.lower() in (".jpg", ".jpeg") else "PNG")).upper()
- if fmt == "JPEG":
- img.convert("RGB").save(path, "JPEG", quality=quality, optimize=True)
- else:
- img.convert("RGB").save(path, "PNG", optimize=True)
- return path
-
-
-def tile_preview(img: Image.Image, reps: int = 2, size: int = 512) -> Image.Image:
- """``reps × reps`` repetition for eyeballing tileability."""
- t = img.convert("RGB").resize((size // reps, size // reps), Image.LANCZOS)
- out = Image.new("RGB", (t.size[0] * reps, t.size[1] * reps))
- for i in range(reps):
- for j in range(reps):
- out.paste(t, (i * t.size[0], j * t.size[1]))
- return out
diff --git a/harness/codeverse/texturing/uv.py b/harness/codeverse/texturing/uv.py
deleted file mode 100644
index a263443e..00000000
--- a/harness/codeverse/texturing/uv.py
+++ /dev/null
@@ -1,176 +0,0 @@
-"""Analytic UVs per part: box (per-face dominant axis), cylinder (around the long
-axis, planar caps) or planar projections, all in WORLD metres divided by
-``tile_size_m`` so a pattern has the same physical size on every part.
-
-Vertices are split only where two incident faces disagree on the projection key
-(box axis, cylinder seam / cap) so smooth shading is preserved elsewhere; vertex
-normals are carried along. The mesh geometry (positions, node transforms) is
-never changed — only TEXCOORD_0 is added.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-import numpy as np
-
-#: long/mid extent ratio above which ``auto`` picks a cylinder projection ...
-CYLINDER_ASPECT = 2.5
-#: ... provided the cross-section is roughly round (mid/min below this); slabs → box
-CYLINDER_SECTION = 2.0
-#: |n · axis| above which a face is a cylinder cap (planar projected)
-CAP_COS = 0.75
-
-
-@dataclass
-class Unwrapped:
- vertices: np.ndarray # (N', 3) LOCAL coordinates (possibly split)
- faces: np.ndarray # (F, 3)
- normals: np.ndarray | None # (N', 3) local normals or None
- uv: np.ndarray # (N', 2)
- projection: str # box | cylinder | planar_y | planar_z
- axis: int # projection axis (cylinder axis / planar normal axis)
- n_split: int # vertices added by seam splitting
-
-
-def choose_projection(extents_world: np.ndarray, requested: str) -> tuple[str, int]:
- """Resolve ``auto`` → (projection, axis). Elongated with a round-ish section →
- cylinder around the long axis; everything else (slabs, boxes, frames) → box. Explicit projections pass through (cylinder axis =
- the longest world axis; planar axes are fixed: planar_y → 1, planar_z → 2)."""
- e = np.asarray(extents_world, dtype=float)
- order = np.argsort(e)[::-1]
- long_axis = int(order[0])
- if requested == "cylinder":
- return "cylinder", long_axis
- if requested == "planar_y":
- return "planar_y", 1
- if requested == "planar_z":
- return "planar_z", 2
- if requested == "box":
- return "box", int(np.argmin(e))
- mid = max(float(e[order[1]]), 1e-9)
- small = max(float(e[order[2]]), 1e-9)
- if float(e[order[0]]) / mid >= CYLINDER_ASPECT and mid / small <= CYLINDER_SECTION:
- return "cylinder", long_axis
- return "box", int(np.argmin(e))
-
-
-def _face_normals(P: np.ndarray, F: np.ndarray) -> np.ndarray:
- a, b, c = P[F[:, 0]], P[F[:, 1]], P[F[:, 2]]
- n = np.cross(b - a, c - a)
- ln = np.linalg.norm(n, axis=1, keepdims=True)
- return n / np.maximum(ln, 1e-12)
-
-
-def _box_uv(P: np.ndarray, F: np.ndarray, tile: float) -> tuple[np.ndarray, np.ndarray]:
- """Per-face dominant axis of the face normal → planar projection on the other two."""
- n = _face_normals(P, F)
- axis = np.argmax(np.abs(n), axis=1) # (F,)
- sign = np.sign(n[np.arange(len(F)), axis])
- sign[sign == 0] = 1.0
- other = np.array([[2, 1], [0, 2], [0, 1]]) # axis → (u axis, v axis)
- corners = P[F] # (F,3,3)
- ua, va = other[axis, 0], other[axis, 1]
- u = np.take_along_axis(corners, ua[:, None, None].repeat(3, 1), axis=2)[:, :, 0]
- v = np.take_along_axis(corners, va[:, None, None].repeat(3, 1), axis=2)[:, :, 0]
- u = u * sign[:, None] # keep handedness consistent on opposite faces
- uv = np.stack([u, v], axis=2) / tile
- key = axis[:, None].repeat(3, 1) * 2 + (sign[:, None].repeat(3, 1) < 0).astype(int)
- return uv, key
-
-
-def _planar_uv(P: np.ndarray, F: np.ndarray, axis: int, tile: float) -> tuple[np.ndarray, np.ndarray]:
- other = {0: (2, 1), 1: (0, 2), 2: (0, 1)}[axis]
- corners = P[F]
- uv = np.stack([corners[:, :, other[0]], corners[:, :, other[1]]], axis=2) / tile
- return uv, np.zeros((len(F), 3), dtype=int)
-
-
-def _cylinder_uv(P: np.ndarray, F: np.ndarray, axis: int, tile: float) -> tuple[np.ndarray, np.ndarray]:
- a, b = [i for i in range(3) if i != axis]
- center = 0.5 * (P.min(axis=0) + P.max(axis=0))
- d = P - center
- radius = float(np.mean(np.hypot(d[:, a], d[:, b])))
- radius = max(radius, 1e-4)
- circ = 2.0 * np.pi * radius
- ang = np.arctan2(d[:, b], d[:, a]) # (-π, π]
- u_v = (ang + np.pi) / (2.0 * np.pi) * circ / tile # 0..circ/tile
- v_v = P[:, axis] / tile
- u = u_v[F] # (F,3)
- v = v_v[F]
- key = np.zeros((len(F), 3), dtype=int)
- # seam: faces straddling angle ±π have a u spread > half circumference → shift the low corners
- span = u.max(axis=1) - u.min(axis=1)
- wrap = span > 0.5 * circ / tile
- if wrap.any():
- low = u < (u.max(axis=1, keepdims=True) - 0.5 * circ / tile)
- shift = wrap[:, None] & low
- u = u + shift * (circ / tile)
- key = key + shift.astype(int)
- # caps: planar
- n = _face_normals(P, F)
- cap = np.abs(n[:, axis]) > CAP_COS
- if cap.any():
- corners = P[F]
- u = np.where(cap[:, None], corners[:, :, a] / tile, u)
- v = np.where(cap[:, None], corners[:, :, b] / tile, v)
- key = np.where(cap[:, None], 2, key)
- return np.stack([u, v], axis=2), key
-
-
-def split_by_key(
- vertices: np.ndarray, faces: np.ndarray, normals: np.ndarray | None, uv_corner: np.ndarray, key_corner: np.ndarray
-) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray, int]:
- """Duplicate a vertex once per distinct (vertex, key) pair; UV per new vertex =
- mean of its corner UVs (they agree within a key by construction)."""
- F = faces
- flat_v = F.reshape(-1)
- flat_k = key_corner.reshape(-1)
- pair = flat_v.astype(np.int64) * (int(flat_k.max()) + 1 if flat_k.size else 1) + flat_k
- uniq, inverse = np.unique(pair, return_inverse=True)
- n_new = len(uniq)
- src = np.zeros(n_new, dtype=np.int64)
- src[inverse] = flat_v
- new_vertices = vertices[src]
- new_normals = normals[src] if normals is not None else None
- new_uv = np.zeros((n_new, 2), dtype=np.float64)
- counts = np.zeros(n_new, dtype=np.float64)
- np.add.at(new_uv, inverse, uv_corner.reshape(-1, 2))
- np.add.at(counts, inverse, 1.0)
- new_uv /= np.maximum(counts, 1.0)[:, None]
- new_faces = inverse.reshape(-1, 3)
- return new_vertices, new_faces, new_normals, new_uv, int(n_new - len(vertices))
-
-
-def unwrap(
- vertices_local: np.ndarray,
- faces: np.ndarray,
- transform: np.ndarray,
- *,
- projection: str = "auto",
- tile_size_m: float = 0.3,
- normals_local: np.ndarray | None = None,
-) -> Unwrapped:
- """Compute UVs for one mesh given its 4×4 world ``transform``. Returns the
- (possibly vertex-split) mesh in LOCAL coordinates plus per-vertex UVs."""
- V = np.asarray(vertices_local, dtype=np.float64)
- F = np.asarray(faces, dtype=np.int64)
- if V.ndim != 2 or V.shape[1] != 3 or F.ndim != 2 or F.shape[1] != 3 or len(F) == 0:
- raise ValueError("unwrap needs (N,3) vertices and (F,3) triangles")
- tile = float(tile_size_m)
- if not tile > 0:
- raise ValueError("tile_size_m must be > 0")
- T = np.asarray(transform, dtype=np.float64)
- P = V @ T[:3, :3].T + T[:3, 3]
- ext = P.max(axis=0) - P.min(axis=0)
- proj, axis = choose_projection(ext, projection)
- if proj == "box":
- uv_c, key_c = _box_uv(P, F, tile)
- elif proj == "cylinder":
- uv_c, key_c = _cylinder_uv(P, F, axis, tile)
- else:
- uv_c, key_c = _planar_uv(P, F, axis, tile)
- nv, nf, nn, uv, n_split = split_by_key(V, F, normals_local, uv_c, key_c)
- # keep numbers small for float32 TEXCOORD precision (pattern is periodic anyway)
- uv = uv - np.floor(uv.min(axis=0))
- return Unwrapped(vertices=nv, faces=nf, normals=nn, uv=uv, projection=proj, axis=axis, n_split=n_split)
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 8ec4fc88..0969150a 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -151,9 +151,10 @@ codeverse/
reference safe to use, Spec attachment + honesty guards, proportions
(does the picture agree with the brief?), render-vs-reference diff,
the content-addressed cache and ground_spec (the one call the CLI makes)
- texturing/ plan.py (VLM material plan), generate.py (+ tile.py seam fix), uv.py (world-metre
- unwrap), apply.py, gate.py (seam + before/after judge), scene_pack.py, run.py (texture_pass),
- maps.py (PBR map set), materials.py (named material library), normalise.py
+ texturing/ plan.py (VLM material plan + the scene texture pack), generate.py
+ (generation + the tileable seam fix + the seam/judge gate), apply.py
+ (world-metre unwrap, PBR map set, application + material normalisation),
+ materials.py (named material library), run.py (texture_pass)
orchestrator.py stage runner with resume, run state, round loop (RoundPolicy,
StopPolicy, BestSelector), refine-task compilation + grouping, budget
tracks/ __init__.py (get_track(track, **options) + the TrackPipeline protocol),
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index beb7a089..338ad9d8 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -413,7 +413,7 @@ texture_pass(ws, spec, plan, *, model_id, image_model=None, judge=True, judge_mo
# gate (ship iff Δoverall ≥ −0.01 AND materials criterion improved); record.extra["texturing"], events texture.*
from codeverse.texturing.plan import material_plan, default_plan, TexturePlan
from codeverse.texturing.generate import generate_textures, FakeImageModel
-from codeverse.texturing.scene_pack import scene_texture_pack, texture_pack_prompt # 6–12 named tiles + manifest.json
+from codeverse.texturing.plan import scene_texture_pack, texture_pack_prompt # 6–12 named tiles + manifest.json
# under public/textures/ for scene prompts (URL /public/textures/<name>.png)
```
diff --git a/harness/tests/texturing/test_gate.py b/harness/tests/texturing/test_gate.py
index 395b19ca..bd85f583 100644
--- a/harness/tests/texturing/test_gate.py
+++ b/harness/tests/texturing/test_gate.py
@@ -4,8 +4,7 @@ from __future__ import annotations
from pathlib import Path
-from codeverse.texturing.gate import judge_gate, material_criterion, seam_gate
-from codeverse.texturing.generate import TextureAsset
+from codeverse.texturing.generate import TextureAsset, judge_gate, material_criterion, seam_gate
from tests.texturing.conftest import FakeJudge, fake_render
diff --git a/harness/tests/texturing/test_generate.py b/harness/tests/texturing/test_generate.py
index bcb5ddfd..7671efd9 100644
--- a/harness/tests/texturing/test_generate.py
+++ b/harness/tests/texturing/test_generate.py
@@ -6,8 +6,7 @@ from pathlib import Path
from PIL import Image
-from codeverse.texturing.generate import FakeImageModel, generate_textures, prompt_key
-from codeverse.texturing.tile import SEAM_MAX
+from codeverse.texturing.generate import SEAM_MAX, FakeImageModel, generate_textures, prompt_key
def test_generate_dedupes_caches_and_accounts(tmp_path: Path):
diff --git a/harness/tests/texturing/test_live.py b/harness/tests/texturing/test_live.py
index be41bb6c..fdb06e8e 100644
--- a/harness/tests/texturing/test_live.py
+++ b/harness/tests/texturing/test_live.py
@@ -10,8 +10,8 @@ from codeverse.config import get_settings
from codeverse.contracts.plan import StaticPlan
from codeverse.contracts.spec import Spec
from codeverse.models.gemini_image import GeminiImageModel
+from codeverse.texturing.generate import seam_score
from codeverse.texturing.plan import compose_image_prompt, material_plan
-from codeverse.texturing.tile import seam_score
pytestmark = pytest.mark.live
RUN = Path(__file__).resolve().parents[2] / "runs" / "e2e_chair_blender"
diff --git a/harness/tests/texturing/test_maps.py b/harness/tests/texturing/test_maps.py
index 5b2398d6..69b3385a 100644
--- a/harness/tests/texturing/test_maps.py
+++ b/harness/tests/texturing/test_maps.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import numpy as np
from PIL import Image
-from codeverse.texturing.maps import (
+from codeverse.texturing.apply import (
DEFAULT_VARIATION,
VARIATION,
is_flat,
diff --git a/harness/tests/texturing/test_normalise.py b/harness/tests/texturing/test_normalise.py
index 280def4f..9eefd99e 100644
--- a/harness/tests/texturing/test_normalise.py
+++ b/harness/tests/texturing/test_normalise.py
@@ -9,7 +9,7 @@ from PIL import Image
from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
from codeverse.spatial.measure import load_scene, measure_glb
-from codeverse.texturing.normalise import classify, normalise_materials
+from codeverse.texturing.apply import classify, normalise_materials
def _pbr(name: str, metallic, roughness, colour=(120, 120, 120, 255), **kw):
diff --git a/harness/tests/texturing/test_scene_pack.py b/harness/tests/texturing/test_scene_pack.py
index f3c1c051..4d400e54 100644
--- a/harness/tests/texturing/test_scene_pack.py
+++ b/harness/tests/texturing/test_scene_pack.py
@@ -9,7 +9,7 @@ import pytest
from codeverse.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
from codeverse.texturing.generate import FakeImageModel
-from codeverse.texturing.scene_pack import (
+from codeverse.texturing.plan import (
default_scene_pack_plan,
load_manifest,
scene_pack_plan,
diff --git a/harness/tests/texturing/test_tile.py b/harness/tests/texturing/test_tile.py
index 9ea05e5c..9cbd591d 100644
--- a/harness/tests/texturing/test_tile.py
+++ b/harness/tests/texturing/test_tile.py
@@ -5,12 +5,12 @@ from __future__ import annotations
import numpy as np
from PIL import Image
-from codeverse.texturing.generate import procedural_texture
-from codeverse.texturing.tile import (
+from codeverse.texturing.generate import (
SEAM_MAX,
fit_size,
make_tileable,
offset_check,
+ procedural_texture,
save_texture,
seam_score,
tile_preview,
diff --git a/harness/tests/texturing/test_uv.py b/harness/tests/texturing/test_uv.py
index feaedb5a..1e356cb0 100644
--- a/harness/tests/texturing/test_uv.py
+++ b/harness/tests/texturing/test_uv.py
@@ -6,7 +6,7 @@ import numpy as np
import pytest
import trimesh
-from codeverse.texturing.uv import choose_projection, split_by_key, unwrap
+from codeverse.texturing.apply import choose_projection, split_by_key, unwrap
def test_choose_projection_rules():