Official Codebase of 3DCodeVerse
Python
cleanup: A6+A7 — texturing: drop unshipped material_pass/cookbook
gaoypengb22ad908c694
diff --git a/harness/codeverse/texturing/materials.py b/harness/codeverse/texturing/materials.pyindex 3bacd493..f90e331e 100644--- a/harness/codeverse/texturing/materials.py+++ b/harness/codeverse/texturing/materials.py@@ -15,15 +15,13 @@ almost always one of two sentences:The numbers below are the ones a materials artist would type — measureddielectric IORs, the metallic/roughness pairs the glTF and Disney/Substanceguides publish, and the clear-coat that separates lacquered wood from raw-timber. They are used three ways:+timber. They are used two ways:-1. as **cookbook text** for the agent (:func:`cookbook_block`) — concrete beats- abstract (design law 2), so the agent gets a copyable table, not an adjective;-2. as the target of the **post-build normaliser**+1. as the target of the **post-build normaliser**(:mod:`codeverse.texturing.normalise`), which fixes a material whose numbersare an untouched framework default or are impossible for the finish its ownname claims;-3. as the PBR factors the **texture pass** writes next to a generated albedo+2. as the PBR factors the **texture pass** writes next to a generated albedo(:mod:`codeverse.texturing.apply`).Everything here is data + pure functions; nothing imports a model or touches a file.@@ -333,69 +331,6 @@ def out_of_band(pbr: Pbr, metallic: float | None, roughness: float | None) -> lireturn bad-# --------------------------------------------------------------------------- cookbook-_HEAD = (- "### Material families — copy these numbers\n\n"- "A Principled BSDF / MeshPhysicalMaterial left on its defaults renders as grey mud, and\n"- "the judge says so (`materials` is the weakest object criterion: mean 0.70). Pick the row\n"- "your part is made of and copy the numbers. Two rules that carry most of the realism:\n\n"- "* **Paint, glaze and varnish are DIELECTRIC.** A painted machine body is `metallic 0.0`\n"- " with a clear coat — not `metallic 0.8`. Only bare metal is metallic.\n"- "* **Nothing in the real world has one uniform roughness.** Vary it across a part\n"- " (grain, wear on edges, casting pebble) even when the colour stays flat.\n"-)---def cookbook_row(p: Pbr) -> str:- extras = []- if p.clearcoat:- extras.append(f"coat {p.clearcoat:.2f}/{p.clearcoat_roughness:.2f}")- if p.sheen:- extras.append(f"sheen {p.sheen:.2f}")- if p.transmission:- extras.append(f"transmission {p.transmission:.2f}")- base = ", ".join(f"{c:.2f}" for c in p.base_hint)- return (f"| {p.family} | {p.metallic:.2f} | {p.roughness:.2f} | {p.ior:.2f} | "- f"{', '.join(extras) or '—'} | {base} | {p.note} |")---def cookbook_block() -> str:- """The whole table as cookbook markdown (see ``not_done`` for the cookbook patch)."""- rows = [- _HEAD,- "| family | metallic | roughness | IOR | extras | base colour (linear sRGB) | notes |",- "|---|---|---|---|---|---|---|",- *[cookbook_row(p) for p in MATERIALS.values()],- "",- "**Blender (bpy)**",- "```python",- "bsdf = mat.node_tree.nodes['Principled BSDF']",- "bsdf.inputs['Base Color'].default_value = (0.11, 0.11, 0.12, 1.0) # cast_iron",- "bsdf.inputs['Metallic'].default_value = 1.0",- "bsdf.inputs['Roughness'].default_value = 0.62",- "bsdf.inputs['IOR'].default_value = 1.5",- "bsdf.inputs['Coat Weight'].default_value = 0.0 # 0.35 for painted_metal",- "bsdf.inputs['Coat Roughness'].default_value = 0.10",- "```",- "",- "**three.js**",- "```js",- "new THREE.MeshPhysicalMaterial({",- " color: 0x1c1c1e, metalness: 1.0, roughness: 0.62, ior: 1.5,",- " clearcoat: 0.0, clearcoatRoughness: 0.10, // 0.35 / 0.10 for painted_metal",- "});",- "```",- "",- "**Roughness variation without a texture file.** GLB export keeps only base colour,",- "metallic, roughness, emission, alpha and normal *textures* — a Blender noise node tree",- "does NOT survive it. What does survive: give one part 2-3 materials that differ only in",- "roughness and assign them per face group (a worn edge strip at -0.15, a recessed panel at",- "+0.12, the underside at +0.20). Two materials on one part is the cheapest thing that",- "stops a surface reading as plastic.",- ]- return "\n".join(rows) + "\n"--#: families that describe BARE metal. A strongly chromatic base colour contradicts#: them — real cast iron, steel and chrome are neutral (or warm, for brass/copper);#: "DarkGreenCastIron" is cast iron with PAINT on it, and paint is a dielectric.@@ -430,7 +365,7 @@ def looks_painted(family: str, rgb: tuple[float, float, float] | None) -> bool:__all__ = ["COARSE_TO_FINE", "FINISH_KEYWORDS", "FRAMEWORK_DEFAULTS", "MATERIALS", "SUBSTRATE_KEYWORDS","FamilyMatch", "Pbr",- "BARE_METAL_FAMILIES", "cookbook_block", "cookbook_row", "family_for", "is_framework_default",+ "BARE_METAL_FAMILIES", "family_for", "is_framework_default","is_warm_metal_hue","looks_painted", "out_of_band", "pbr_for", "saturation",]diff --git a/harness/codeverse/texturing/normalise.py b/harness/codeverse/texturing/normalise.pyindex 409d111f..03f7f0c4 100644--- a/harness/codeverse/texturing/normalise.py+++ b/harness/codeverse/texturing/normalise.py@@ -20,8 +20,9 @@ Everything else is left alone. Base colour is **never** changed — that is theagent'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; the result is ``artifacts/object_materials.glb``, shipped-only if the same do-no-harm judge gate the texture pass uses says it helped.+``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@@ -29,14 +30,14 @@ from __future__ import annotationsimport loggingimport timefrom pathlib import Path-from typing import Any, NamedTuple+from typing import NamedTuple-import trimeshfrom pydantic import BaseModel, Fieldfrom codeverse.contracts.plan import StaticPlanfrom codeverse.conventions import to_snakefrom codeverse.spatial.measure import load_scene+from codeverse.texturing.apply import verify_textured_glbfrom codeverse.texturing.materials import (FamilyMatch,family_for,@@ -226,103 +227,7 @@ def normalise_materials(def _verify(glb_in: Path, glb_out: Path) -> list[str]:"""Same nodes, same triangles — this pass may only move two floats per material."""- warnings: list[str] = []- a, b = load_scene(glb_in), load_scene(glb_out)- na, nb = set(a.graph.nodes_geometry), set(b.graph.nodes_geometry)- if na != nb:- warnings.append(f"node set changed: missing={sorted(na - nb)[:5]} extra={sorted(nb - na)[:5]}")- fa = sum(len(g.faces) for g in a.geometry.values() if isinstance(g, trimesh.Trimesh))- fb = sum(len(g.faces) for g in b.geometry.values() if isinstance(g, trimesh.Trimesh))- if fa != fb:- warnings.append(f"face count changed {fa} → {fb}")- return warnings+ return verify_textured_glb(glb_in, glb_out, expected_textured=0)-MATERIALS_GLB = "object_materials.glb"---class MaterialPassReport(BaseModel):- """What :func:`material_pass` did, and whether it shipped."""-- normalise: NormaliseReport- gate: Any | None = None- glb_out: str = ""- shipped: bool = False- delta: float | None = None- materials_delta: float | None = None- reason: str = ""- duration_s: float = 0.0-- def summary(self) -> dict[str, Any]:- return {- "shipped": self.shipped, "delta": self.delta, "materials_delta": self.materials_delta,- "changed": len(self.normalise.changes), "materials": self.normalise.n_materials,- "families": sorted({c.family for c in self.normalise.changes}),- "glb_out": self.glb_out, "reason": self.reason, "duration_s": self.duration_s,- }---def material_pass(- ws: Any,- spec: Any,- plan: StaticPlan | None,- *,- glb_in: Path | None = None,- judge: bool = True,- judge_obj: Any | None = None,- judge_model_id: str | None = None,- rubric: str | None = None,- render: Any | None = None,- events: Any | None = None,-) -> MaterialPassReport:- """Normalise ``artifacts/object.glb``'s materials into ``artifacts/object_materials.glb``- and keep it only if the same do-no-harm gate the texture pass uses agrees.-- Standalone sibling of :func:`codeverse.texturing.run.texture_pass`: no model- call except the two gate verdicts, and nothing is written when no material- needed changing.- """- from codeverse.events import EventLog- from codeverse.texturing.gate import judge_gate-- t0 = time.time()- events = events or EventLog(ws.events_path)- glb_in = Path(glb_in) if glb_in else ws.artifacts / "object.glb"- if not glb_in.is_file():- raise FileNotFoundError(f"no GLB to normalise: {glb_in}")- out = ws.artifacts / MATERIALS_GLB- norm = normalise_materials(glb_in, out, plan=plan)- rep = MaterialPassReport(normalise=norm, glb_out=norm.glb_out)- events.emit("material.normalised", changed=len(norm.changes), materials=norm.n_materials,- families=sorted({c.family for c in norm.changes}))- if not norm.changes:- rep.reason = "no material needed normalising"- rep.duration_s = round(time.time() - t0, 2)- return rep- if not judge:- rep.shipped = True- rep.reason = "judge gate skipped: shipped on the deterministic rules alone"- rep.duration_s = round(time.time() - t0, 2)- return rep- gate = judge_gate(spec, plan, glb_in, out, ws.artifacts / "materials_gate",- judge=judge_obj if judge_obj is not None else _gate_judge(spec, rubric, judge_model_id),- render=render)- rep.gate, rep.shipped, rep.delta = gate, gate.shipped, gate.delta- rep.materials_delta, rep.reason = gate.materials_delta, gate.reason- rep.duration_s = round(time.time() - t0, 2)- events.emit("material.gate", **rep.summary())- return rep---def _gate_judge(spec: Any, rubric: str | None, judge_model_id: str | None) -> Any:- from codeverse.contracts.common import TRACK_INFO- from codeverse.judges.vlm_judge import VlmJudge-- info = TRACK_INFO.get(spec.track)- name = rubric or (info.rubric if info is not None else "static_object_v1")- return VlmJudge(rubric=name, model_id=judge_model_id or spec.backends.judge, n_samples=1,- label="material_gate")---__all__ = ["MaterialChange", "MaterialPassReport", "NormaliseReport", "Verdict", "classify",- "material_pass", "normalise_materials"]+__all__ = ["MaterialChange", "NormaliseReport", "Verdict", "classify", "normalise_materials"]diff --git a/harness/tests/texturing/test_materials.py b/harness/tests/texturing/test_materials.pyindex d4a7d582..617b5078 100644--- a/harness/tests/texturing/test_materials.py+++ b/harness/tests/texturing/test_materials.py@@ -8,7 +8,6 @@ from codeverse.texturing.materials import (BARE_METAL_FAMILIES,COARSE_TO_FINE,MATERIALS,- cookbook_block,family_for,is_framework_default,is_warm_metal_hue,@@ -94,12 +93,3 @@ def test_saturated_colour_means_paint_but_gold_still_means_metal():assert not looks_painted("hardwood", (0.10, 0.35, 0.18)) # rule only applies to bare metalsassert is_warm_metal_hue((0.72, 0.40, 0.25)) and not is_warm_metal_hue((0.8, 0.1, 0.1))assert set(MATERIALS) >= BARE_METAL_FAMILIES---def test_cookbook_block_is_copyable_text():- text = cookbook_block()- for name in MATERIALS:- assert f"| {name} |" in text- assert "Principled BSDF" in text and "MeshPhysicalMaterial" in text- assert "metallic 0.0" in text # the paint-is-dielectric rule is spelled out- assert text.count("\n|---|") == 1 # exactly one table header separator