From 72258d9288475e15072bd4cd25622006d4ea6c9e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:04 +0100 Subject: [PATCH 1/6] Blender tools: run an intent recipe in a background Blender; write a turntable recipe run_intents.py sends a JSON list of intents through BrokkrBlenderTarget.run_intent in a background Blender (the action table admits or denies each, host rows included) and writes the receipts to a file. It refuses to start without private Blender user directories. turntable_recipe.py writes such a recipe from Brokkr's own scene actions, so a before and an after of one subject are framed identically. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tools/run_intents.py | 106 +++++++++++++++++++++ surfaces/blender/tools/turntable_recipe.py | 75 +++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 surfaces/blender/tools/run_intents.py create mode 100644 surfaces/blender/tools/turntable_recipe.py diff --git a/surfaces/blender/tools/run_intents.py b/surfaces/blender/tools/run_intents.py new file mode 100644 index 0000000..9c06c01 --- /dev/null +++ b/surfaces/blender/tools/run_intents.py @@ -0,0 +1,106 @@ +"""Run a list of Brokkr intents in a background Blender, through the add-on's own agent turn. + + blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- [] + +For batch work on files (polishing a generated mesh, rendering a turntable) where no person has a Blender open. +Every intent goes through BrokkrBlenderTarget.run_intent: the action table admits or denies it, host add-on +rows are checked as in a live session, and each gets a receipt. No CultMesh node is opened: the receipts are +written to (default: the recipe's name with .receipts.json) and nowhere else, so nothing here +shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the +recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless +BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a +person's own Blender folders (docs/install.md). + +The recipe: + + {"requestedBy": "/", + "importDir": "", "outputDir": "", + "hostAddons": ["brokkr_mesh_polish"], optional; modules found beside brokkr_bridge or in hostAddonDirs + "hostAddonDirs": [""], optional; extra directories holding host add-on packages + "openBlend": "", "saveBlend": "", optional; without openBlend the scene starts empty; saveBlend + is written after the last intent + "keepGoing": false, optional; true runs the rest after a refusal + "intents": [{"action": "importGltf", "filepath": "ship.glb"}, ...]} + +commandId defaults to -; requestedBy to the recipe's. Exit status: 0 when every intent was +accepted, 3 when one was not (the receipts file says which), 2 when the recipe could not be run at all. +""" +import importlib +import json +import os +import sys +import types +from pathlib import Path + +import bpy + + +def fail(message: str) -> None: + print(f"run_intents: {message}", file=sys.stderr, flush=True) + sys.exit(2) + + +def main() -> int: + for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(name): + fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] + if not arguments: + fail("usage: blender --background --factory-startup --python run_intents.py -- []") + recipe_path = Path(arguments[0]).resolve() + receipts_path = Path(arguments[1]).resolve() if len(arguments) > 1 else recipe_path.with_suffix(".receipts.json") + try: + recipe = json.loads(recipe_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + fail(f"cannot read {recipe_path}: {error}") + unknown = set(recipe) - {"requestedBy", "importDir", "outputDir", "hostAddons", "hostAddonDirs", "openBlend", + "saveBlend", "keepGoing", "intents"} + if unknown or not isinstance(recipe.get("intents"), list): + fail(f"recipe has unknown keys {sorted(unknown)} or no intents array") + + surface = Path(__file__).resolve().parents[1] + package = types.ModuleType("brokkr_bridge") # the add-on's modules without registering its panel or timers + package.__path__ = [str(surface / "brokkr_bridge")] + sys.modules["brokkr_bridge"] = package + target_module = importlib.import_module("brokkr_bridge.blender_target") + + if recipe.get("openBlend"): + bpy.ops.wm.open_mainfile(filepath=str(Path(recipe["openBlend"]).resolve())) + else: + bpy.ops.wm.read_factory_settings(use_empty=True) # no default cube, camera or light + import addon_utils + for directory in [str(surface)] + [str(Path(d).resolve()) for d in recipe.get("hostAddonDirs", [])]: + if directory not in sys.path: + sys.path.append(directory) + for module in recipe.get("hostAddons", []): + if addon_utils.enable(module, default_set=True) is None: + fail(f"host add-on {module!r} could not be enabled") + + target = target_module.BrokkrBlenderTarget(bpy) + target.configure_action_dirs(recipe.get("importDir", ""), recipe.get("outputDir", "")) + target.reload_host_actions() + _, errors = target.host_actions() + if errors: + fail(f"host actions refused: {errors}") + + receipts, status = [], 0 + for index, intent in enumerate(recipe["intents"]): + command = dict(intent) + command.setdefault("commandId", f"{recipe_path.stem}-{index}") + command.setdefault("requestedBy", recipe.get("requestedBy", "")) + receipt = target.run_intent(bpy.context, command) + receipts.append(receipt) + print("RECEIPT", command["commandId"], command.get("action"), receipt["status"], + str(receipt.get("message", "")).replace("\n", " | ")[:300], flush=True) + if receipt["status"] != "accepted": + status = 3 + if not recipe.get("keepGoing"): + break + receipts_path.write_text(json.dumps(receipts, indent=1, default=str), encoding="utf-8") + if recipe.get("saveBlend") and (status == 0 or recipe.get("keepGoing")): + bpy.ops.wm.save_as_mainfile(filepath=str(Path(recipe["saveBlend"]).resolve())) + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/surfaces/blender/tools/turntable_recipe.py b/surfaces/blender/tools/turntable_recipe.py new file mode 100644 index 0000000..ccb2a59 --- /dev/null +++ b/surfaces/blender/tools/turntable_recipe.py @@ -0,0 +1,75 @@ +"""Write a run_intents recipe that renders a turntable of a .blend with Brokkr's own scene actions. + + python surfaces/blender/tools/turntable_recipe.py --blend ship.blend --output-dir renders --prefix ship_before \ + --radius 0.75 --requested-by nibu/hands > turntable.json + +The subject is assumed centred on the origin (brokkr_mesh_polish.orient leaves it there); --radius is half the +length the frame must hold. Each view is an orthographic still from a camera on a circle at --elevation degrees, +so two recipes with the same numbers frame two files identically: a before and an after can be compared view +by view. --look lit adds a sun over a dim grey world; --look flat lights with a uniform white world alone, which +shows a base colour texture as it is stored, baked shadows included. renderStill never overwrites, so a +recipe runs once per prefix. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys + + +def camera_pose(azimuth_deg: float, elevation_deg: float, distance: float) -> tuple[list[float], list[float]]: + """(location, XYZ Euler radians) of a camera on the circle that looks at the origin with +Z up. Azimuth 0 + looks along +Y from behind the subject's -Y end; it grows counter-clockwise seen from above.""" + azimuth, elevation = math.radians(azimuth_deg), math.radians(elevation_deg) + x = distance * math.cos(elevation) * math.sin(azimuth) + y = -distance * math.cos(elevation) * math.cos(azimuth) + z = distance * math.sin(elevation) + return [x, y, z], [math.pi / 2 - elevation, 0.0, azimuth] + + +def recipe(blend: str, output_dir: str, prefix: str, radius: float, views: int, elevation: float, size: int, + engine: str, look: str, requested_by: str) -> dict: + distance = radius * 6 + intents: list[dict] = [ + {"action": "setWorld", "color": [1, 1, 1] if look == "flat" else [0.5, 0.5, 0.5], "strength": 1.0 if look == "flat" else 0.4}, + {"action": "createObject", "objectType": "CAMERA", "name": "TurntableCamera"}, + {"action": "setCamera", "targetObjectName": "TurntableCamera", "cameraType": "ORTHO", "orthoScale": radius * 2.1, + "clipStart": radius * 0.01, "clipEnd": radius * 20, "active": True}, + ] + if look == "lit": + intents += [ + {"action": "createObject", "objectType": "LIGHT", "lightType": "SUN", "name": "TurntableSun"}, + {"action": "setLight", "targetObjectName": "TurntableSun", "energy": 3.0, "color": [1, 1, 1]}, + {"action": "setObjectTransform", "targetObjectName": "TurntableSun", "rotationEuler": [math.radians(40), 0.0, math.radians(35)]}, + ] + poses = [(360.0 * i / views, elevation) for i in range(views)] + [(0.0, 90.0), (0.0, -90.0)] + names = [f"{round(a):03d}" for a, _ in poses[:views]] + ["top", "bottom"] + for name, (azimuth, tilt) in zip(names, poses): + location, rotation = camera_pose(azimuth, tilt, distance) + intents.append({"action": "setObjectTransform", "targetObjectName": "TurntableCamera", "location": location, "rotationEuler": rotation}) + intents.append({"action": "renderStill", "outputPath": f"{prefix}_{look}_{name}.png", "engine": engine, + "resolutionX": size, "resolutionY": size, "cameraName": "TurntableCamera"}) + return {"requestedBy": requested_by, "outputDir": output_dir, "openBlend": blend, "intents": intents} + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--blend", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--radius", type=float, required=True) + parser.add_argument("--views", type=int, default=8) + parser.add_argument("--elevation", type=float, default=25.0) + parser.add_argument("--size", type=int, default=1024) + parser.add_argument("--engine", default="BLENDER_EEVEE") + parser.add_argument("--look", choices=("lit", "flat"), default="lit") + parser.add_argument("--requested-by", required=True) + a = parser.parse_args(argv) + json.dump(recipe(a.blend, a.output_dir, a.prefix, a.radius, a.views, a.elevation, a.size, a.engine, a.look, + a.requested_by), sys.stdout, indent=1) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) -- 2.47.3 From 6eb372525454d3de20ce02dfd7409d73bd110786 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:04 +0100 Subject: [PATCH 2/6] brokkr_mesh_polish: a host add-on that measures and polishes generated meshes Seven agent-callable operators for image-to-3D output (Tripo and its kin): audit (welded topology, UV overlap, texel density), repair, orient, delight (undo baked lighting that normals and occlusion explain), pick, scrub_markings (paint out baked lettering) and cut_parts (cut a fused skin into capped, rooted, parented parts from seeds). The arithmetic is core.py, numpy only, tested without Blender; the host file is tested against Brokkr's own checker; tests/live/mesh_polish.py proves every row through run_intent in Blender 5.3.0. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 698 ++++++++++++++++++ .../brokkr_mesh_polish/brokkr_actions.json | 102 +++ surfaces/blender/brokkr_mesh_polish/core.py | 414 +++++++++++ surfaces/blender/tests/live/mesh_polish.py | 234 ++++++ .../tests/live/mesh_polish.result.json | 471 ++++++++++++ surfaces/blender/tests/test_mesh_polish.py | 390 ++++++++++ 6 files changed, 2309 insertions(+) create mode 100644 surfaces/blender/brokkr_mesh_polish/__init__.py create mode 100644 surfaces/blender/brokkr_mesh_polish/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_mesh_polish/core.py create mode 100644 surfaces/blender/tests/live/mesh_polish.py create mode 100644 surfaces/blender/tests/live/mesh_polish.result.json create mode 100644 surfaces/blender/tests/test_mesh_polish.py diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py new file mode 100644 index 0000000..af1916c --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -0,0 +1,698 @@ +"""Mesh polish for generated meshes (Tripo and other image-to-3D output): measure, repair, orient, undo baked +lighting, scrub baked markings, cut a fused skin into articulated parts. + +A host add-on for Brokkr: it imports nothing from Brokkr, and brokkr_actions.json beside this file lists the +operators agents may run (docs/mesh-polish.md). The arithmetic is core.py (numpy, tested without Blender); +this file is the bpy around it. Every operator writes a JSON report to WindowManager.brokkr_mesh_polish_result. +""" +bl_info = {"name": "Brokkr Mesh Polish", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Mesh", "description": "Measure and polish generated meshes; agent-callable through Brokkr."} + +import json +import math + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +from . import core + +RESULT = "brokkr_mesh_polish_result" +CAP_MATERIAL = "Polish Cap" +CAP_COLOUR = (0.02, 0.02, 0.025, 1.0) + + +class Refused(Exception): + """The request cannot run on this scene; the message is the receipt.""" + + +def mesh_object(name: str): + obj = bpy.data.objects.get(name) + if obj is None or obj.type != "MESH": + raise Refused(f"No mesh object named {name!r}.") + return obj + + +def mesh_objects(name: str) -> list: + if name: + return [mesh_object(name)] + found = [o for o in bpy.context.scene.objects if o.type == "MESH"] + if not found: + raise Refused("The scene has no mesh objects.") + return found + + +def arrays(obj) -> dict: + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), + polygon (the polygon each triangle came from).""" + mesh = obj.data + mesh.calc_loop_triangles() + count = len(mesh.loop_triangles) + V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) + mesh.vertices.foreach_get("co", V) + N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) + mesh.vertex_normals.foreach_get("vector", N) + T = np.empty(count * 3, dtype=np.int32) + mesh.loop_triangles.foreach_get("vertices", T) + L = np.empty(count * 3, dtype=np.int32) + mesh.loop_triangles.foreach_get("loops", L) + P = np.empty(count, dtype=np.int32) + mesh.loop_triangles.foreach_get("polygon_index", P) + world = np.array(obj.matrix_world, dtype=np.float64) + V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] + N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) + UV = None + if mesh.uv_layers.active is not None: + flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) + mesh.uv_layers.active.uv.foreach_get("vector", flat) + UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + + +def merged(objects: list) -> dict: + """The arrays of several objects as one mesh (vertex indices offset).""" + parts = [arrays(o) for o in objects] + offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) + uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) + return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} + + +def base_color_nodes(obj) -> list: + """Image Texture nodes feeding a Principled BSDF Base Color in the object's materials, nearest first.""" + found = [] + for slot in obj.material_slots: + material = slot.material + if material is None or material.node_tree is None: + continue + for node in material.node_tree.nodes: + if node.type != "BSDF_PRINCIPLED": + continue + queue = [link.from_node for link in node.inputs["Base Color"].links] + seen = set() + while queue: + upstream = queue.pop(0) + if upstream.name in seen: + continue + seen.add(upstream.name) + if upstream.type == "TEX_IMAGE" and upstream.image is not None: + found.append(upstream) + break + queue.extend(link.from_node for socket in upstream.inputs for link in socket.links) + return found + + +def base_color_image(obj): + nodes = base_color_nodes(obj) + if not nodes: + raise Refused(f"Object {obj.name!r} has no image texture on a Principled Base Color.") + return nodes[0].image + + +def image_users(image) -> list: + return [o for o in bpy.context.scene.objects + if o.type == "MESH" and any(n.image == image for n in base_color_nodes(o))] + + +def read_pixels(image) -> np.ndarray: + """(h, w, 4) float32, row 0 at v = 0, in the image's stored values (sRGB-encoded for an sRGB image).""" + width, height = image.size + if width == 0 or height == 0: + raise Refused(f"Image {image.name!r} has no pixels.") + flat = np.empty(width * height * 4, dtype=np.float32) + image.pixels.foreach_get(flat) + return flat.reshape(height, width, 4) + + +def replace_image(old, pixels: np.ndarray, suffix: str): + """A new packed image holding pixels, swapped in for old on every image texture node that used it. Nothing + is written to disk: the image lives in the .blend and in any glTF exported from it.""" + height, width = pixels.shape[:2] + stem = old.name.rsplit(".", 1)[0] if old.name.lower().endswith((".jpg", ".jpeg", ".png")) else old.name + ours = old.get("brokkr_mesh_polish", False) + name = old.name if ours and old.name.endswith("." + suffix) else f"{stem}.{suffix}" + image = bpy.data.images.new(name, width, height, alpha=False) + image["brokkr_mesh_polish"] = True + image.colorspace_settings.name = old.colorspace_settings.name + image.pixels.foreach_set(np.ascontiguousarray(pixels, dtype=np.float32).reshape(-1)) + image.pack() + for material in bpy.data.materials: + if material.node_tree is not None: + for node in material.node_tree.nodes: + if node.type == "TEX_IMAGE" and node.image == old: + node.image = image + if ours and old.users == 0: # an intermediate this add-on made: a chain of edits keeps one image, not one per step + bpy.data.images.remove(old) + image.name = name + return image + + +def ambient_occlusion(V: np.ndarray, T: np.ndarray, N: np.ndarray, rays: int, reach: float, seed: int = 0) -> np.ndarray: + """Open-sky share (0..1) at each vertex: cosine-weighted rays from just above it, against the mesh itself.""" + tree = BVHTree.FromPolygons([tuple(v) for v in V], [tuple(int(i) for i in t) for t in T]) + rng = np.random.default_rng(seed) + u, phi = rng.random(rays), rng.random(rays) * 2 * math.pi + local = np.stack([np.sqrt(u) * np.cos(phi), np.sqrt(u) * np.sin(phi), np.sqrt(1 - u)], axis=1) + helper = np.where(np.abs(N[:, [0]]) < 0.9, [[1.0, 0.0, 0.0]], [[0.0, 1.0, 0.0]]) + tangent = np.cross(N, helper) + tangent /= np.maximum(np.linalg.norm(tangent, axis=1, keepdims=True), 1e-30) + bitangent = np.cross(N, tangent) + open_sky = np.empty(len(V)) + offset = reach * 1e-3 + for i in range(len(V)): + directions = local[:, [0]] * tangent[i] + local[:, [1]] * bitangent[i] + local[:, [2]] * N[i] + origin = Vector(V[i] + N[i] * offset) + hits = sum(1 for d in directions if tree.ray_cast(origin, Vector(d), reach)[0] is not None) + open_sky[i] = 1.0 - hits / rays + return open_sky + + +def resample(pixels: np.ndarray, size: int) -> np.ndarray: + """pixels (h,w,c) at size x size: block mean when the sides divide evenly, nearest texel otherwise.""" + h, w = pixels.shape[:2] + if h == size and w == size: + return pixels + if h % size == 0 and w % size == 0: + return pixels.reshape(size, h // size, size, w // size, -1).mean(axis=(1, 3)) + rows = np.minimum(((np.arange(size) + 0.5) * h / size).astype(int), h - 1) + cols = np.minimum(((np.arange(size) + 0.5) * w / size).astype(int), w - 1) + return pixels[rows][:, cols] + + +def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: + """A (s,s) field bilinearly resampled to (height, width), texel centres aligned.""" + s = field.shape[0] + y = np.clip((np.arange(height) + 0.5) * s / height - 0.5, 0, s - 1) + x = np.clip((np.arange(width) + 0.5) * s / width - 0.5, 0, s - 1) + y0, x0 = np.floor(y).astype(int), np.floor(x).astype(int) + y1, x1 = np.minimum(y0 + 1, s - 1), np.minimum(x0 + 1, s - 1) + fy, fx = (y - y0)[:, None].astype(np.float32), (x - x0)[None, :].astype(np.float32) + top = field[y0][:, x0] * (1 - fx) + field[y0][:, x1] * fx + bottom = field[y1][:, x0] * (1 - fx) + field[y1][:, x1] * fx + return top * (1 - fy) + bottom * fy + + +def pin_uvs(bm, faces) -> None: + """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows + that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, + and corners copied from several islands would smear the atlas across it and overlap everything.""" + layer = bm.loops.layers.uv.active + if layer is None: + return + fresh = set(faces) + for face in faces: + anchor = None + for loop in face.loops: + for other in loop.vert.link_loops: + if other.face not in fresh: + anchor = other[layer].uv.copy() + break + if anchor is not None: + break + if anchor is None: + anchor = face.loops[0][layer].uv.copy() + for loop in face.loops: + loop[layer].uv = anchor + + +def cap_surface(): + """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" + material = bpy.data.materials.get(CAP_MATERIAL) + if material is None: + material = bpy.data.materials.new(CAP_MATERIAL) + material.use_nodes = True + material.diffuse_color = CAP_COLOUR + shader = next((n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) + if shader is not None: + shader.inputs["Base Color"].default_value = CAP_COLOUR + shader.inputs["Roughness"].default_value = 0.7 + return material + + +class PolishOperator(bpy.types.Operator): + """Runs work(context) and stores its report; a Refused is an ERROR report (a failed receipt through Brokkr).""" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + try: + report = self.work(context) + except Refused as refusal: + self.report({"ERROR"}, str(refusal)) + return {"CANCELLED"} + setattr(context.window_manager, RESULT, json.dumps(report, separators=(",", ":"))) + return {"FINISHED"} + + +class BROKKR_MESH_POLISH_OT_audit(PolishOperator): + """Measure the meshes: triangles, welded topology (open and non-manifold edges, shells), UV overlap, UV + islands, texel density, and the size of the base colour texture""" + bl_idname = "brokkr_mesh_polish.audit" + bl_label = "Audit Mesh" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="A mesh object; every mesh in the scene when empty") + raster: bpy.props.IntProperty(name="UV Raster", default=1024, min=64, max=4096) + + def work(self, context): + report = {} + for obj in mesh_objects(self.object_name): + data = arrays(obj) + nodes = base_color_nodes(obj) + size = max(nodes[0].image.size) if nodes else 0 + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry["baseColorImage"] = nodes[0].image.name if nodes else "" + entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] + entry["customNormals"] = "custom_normal" in obj.data.attributes + report[obj.name] = entry + return report + + +class BROKKR_MESH_POLISH_OT_repair(PolishOperator): + """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells + below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + bl_idname = "brokkr_mesh_polish.repair" + bl_label = "Repair Mesh" + object_name: bpy.props.StringProperty(name="Object") + weld_fraction: bpy.props.FloatProperty(name="Weld", default=1e-4, min=0.0, max=0.02, precision=6, + description="Weld distance as a share of the bounding diagonal") + min_shell_area: bpy.props.FloatProperty(name="Min Shell Area", default=0.0, min=0.0, max=0.5, precision=5, + description="Delete shells holding less than this share of the surface; 0 keeps all") + fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, + description="Close holes of up to this many edges; 0 leaves holes") + sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, + description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") + + def work(self, context): + obj = mesh_object(self.object_name) + mesh = obj.data + before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + bm = bmesh.new() + bm.from_mesh(mesh) + diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length + counts = {"vertices": len(bm.verts)} + if self.weld_fraction > 0: + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) + counts["welded"] = counts.pop("vertices") - len(bm.verts) + faces = len(bm.faces) + bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) + counts["degenerateFacesRemoved"] = faces - len(bm.faces) + loose_edges = [e for e in bm.edges if not e.link_faces] + bmesh.ops.delete(bm, geom=loose_edges, context="EDGES") + loose_verts = [v for v in bm.verts if not v.link_edges] + bmesh.ops.delete(bm, geom=loose_verts, context="VERTS") + counts["looseEdgesRemoved"], counts["looseVertsRemoved"] = len(loose_edges), len(loose_verts) + counts["shellsRemoved"] = 0 + if self.min_shell_area > 0: + bm.verts.index_update() + pairs = np.array([[e.verts[0].index, e.verts[1].index] for e in bm.edges], dtype=np.int64).reshape(-1, 2) + labels = core.components(len(bm.verts), pairs) + face_label = np.array([f.verts[0].index for f in bm.faces], dtype=np.int64) + face_label = labels[face_label] if len(face_label) else face_label + area = np.array([f.calc_area() for f in bm.faces]) + shells, inverse = np.unique(face_label, return_inverse=True) + share = np.bincount(inverse, weights=area, minlength=len(shells)) / max(area.sum(), 1e-30) + small = share < self.min_shell_area + doomed = [f for f, s in zip(bm.faces[:], small[inverse]) if s] + bmesh.ops.delete(bm, geom=doomed, context="FACES") + counts["shellsRemoved"] = int(small.sum()) + counts["holesFilled"] = 0 + if self.fill_holes_sides > 0: + filled = bmesh.ops.holes_fill(bm, edges=[e for e in bm.edges if e.is_boundary], sides=self.fill_holes_sides) + counts["holesFilled"] = len(filled["faces"]) + pin_uvs(bm, filled["faces"]) + bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.to_mesh(mesh) + bm.free() + if self.sharp_angle > 0: + if "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) + mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) + mesh.update() + after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + return {"object": obj.name, "changes": counts, + "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, + "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + + +class BROKKR_MESH_POLISH_OT_orient(PolishOperator): + """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), + centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + bl_idname = "brokkr_mesh_polish.orient" + bl_label = "Orient Meshes" + length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, + description="Longest side after scaling, in scene units; 0 keeps the size") + flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") + roll_quarter_turns: bpy.props.IntProperty(name="Roll", default=0, min=0, max=3, + description="Quarter turns about the long axis, to choose which side is up") + principal: bpy.props.BoolProperty(name="Principal Axes", default=True, + description="Off keeps the current axes and only applies the turns, centre and scale") + + def work(self, context): + objects = mesh_objects("") + data = merged(objects) + centre, rotation = core.principal_frame(data["V"], data["T"]) + if self.principal: + rotation = np.array([rotation[1], rotation[0], -rotation[2]]) # long on Y, middle on X, right-handed + if np.linalg.det(rotation) < 0: + rotation[2] *= -1 + else: + rotation = np.eye(3) + turn = Matrix.Rotation(math.radians(90 * self.roll_quarter_turns), 3, "Y") + if self.flip_forward: + turn = Matrix.Rotation(math.pi, 3, "Z") @ turn + rotation = np.array(turn) @ rotation + local = (data["V"] - centre) @ rotation.T + low, high = local.min(axis=0), local.max(axis=0) + scale = self.length / float((high - low).max()) if self.length > 0 else 1.0 + middle = (low + high) / 2.0 + frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ + @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) + originals = {o.name: frame @ o.matrix_world for o in objects} + for obj in objects: + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(originals[obj.name]) + obj.data.update() + for obj in objects: + obj.parent = None + obj.matrix_world = Matrix.Identity(4) + final = (local - middle) * scale + return {"objects": [o.name for o in objects], "scale": scale, + "extent": [round(float(x), 6) for x in (high - low) * scale], + "mirrorError": {axis: core.mirror_error(final, index) for index, axis in enumerate("XYZ")}} + + +class BROKKR_MESH_POLISH_OT_delight(PolishOperator): + """Undo lighting baked into a base colour texture: fit the light that the surface's own normals and ambient + occlusion explain, then raise shaded texels to the level of the lit ones. The result is a new packed image""" + bl_idname = "brokkr_mesh_polish.delight" + bl_label = "Delight Base Colour" + object_name: bpy.props.StringProperty(name="Object", description="Any object using the texture; all its users are treated together") + strength: bpy.props.FloatProperty(name="Strength", default=1.0, min=0.0, max=1.0) + max_gain: bpy.props.FloatProperty(name="Max Gain", default=3.0, min=1.0, max=8.0, + description="No texel is brightened or darkened by more than this factor") + clusters: bpy.props.IntProperty(name="Colour Clusters", default=3, min=1, max=8, + description="How many distinct paints the texture is assumed to hold") + fit_size: bpy.props.IntProperty(name="Fit Size", default=1024, min=128, max=2048) + occlusion_rays: bpy.props.IntProperty(name="Occlusion Rays", default=48, min=8, max=256) + + def work(self, context): + image = base_color_image(mesh_object(self.object_name)) + users = image_users(image) + data = merged(users) + if data["UV"] is None: + raise Refused("An object using the texture has no UV map.") + V, T, N = data["V"], data["T"], data["N"] + diagonal = float(np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + occlusion = ambient_occlusion(V, T, N, self.occlusion_rays, 0.35 * diagonal) + owner, bary, _ = core.rasterize(data["UV"], self.fit_size) + covered = owner >= 0 + if covered.sum() < 64: + raise Refused("The UV map covers too little of the texture to fit lighting.") + normals = core.interpolate(owner, bary, N[T])[covered] + normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) + sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] + pixels = read_pixels(image) + encoded = image.colorspace_settings.name == "sRGB" + linear = core.srgb_to_linear(pixels[..., :3]) if encoded else pixels[..., :3] + small = resample(linear, self.fit_size)[covered].astype(np.float64) + log_l = np.log(core.luminance(small) + 1e-4) + basis = core.shading_basis(normals, sky) + # Texels below 4% of the white point are unpainted fill (what the generator never saw): no paint to judge. + judged = np.flatnonzero(core.luminance(small) > 0.04 * np.percentile(core.luminance(small), 95)) + if len(judged) < 64: + raise Refused("The texture is too dark to fit lighting.") + fit = np.random.default_rng(0).choice(judged, size=min(len(judged), 200000), replace=False) + labels = core.chroma_clusters(small[fit], min(self.clusters, len(fit))) + weights, explained = core.fit_shading(log_l[fit], basis[fit], labels) + gain = core.delight_gain(basis, weights, self.strength, self.max_gain) + after_log = np.log(core.luminance(small * gain[:, None]) + 1e-4) + _, explained_after = core.fit_shading(after_log[fit], basis[fit], labels) + field = np.ones((self.fit_size, self.fit_size, 1), dtype=np.float32) + field[covered] = gain[:, None] + field = core.push_pull(field, covered)[..., 0] + full = upsample(field, pixels.shape[0], pixels.shape[1]) + out = pixels.copy() + lit = linear * full[..., None] + out[..., :3] = core.linear_to_srgb(lit) if encoded else np.clip(lit, 0.0, None) + source = image.name + new = replace_image(image, out, "delit") # may remove image, when it was this add-on's own + return {"image": source, "newImage": new.name, "objects": [o.name for o in users], + "explainedByLight": {"before": explained, "after": explained_after}, + "before": core.lighting_signature(log_l[judged], normals[judged], sky[judged]), + "after": core.lighting_signature(after_log[judged], normals[judged], sky[judged]), + "gain": {"min": float(gain.min()), "median": float(np.median(gain)), "max": float(gain.max()), + "clamped": float(((gain >= self.max_gain * 0.999) | (gain <= 1.001 / self.max_gain)).mean())}} + + +class BROKKR_MESH_POLISH_OT_scrub_markings(PolishOperator): + """Paint out markings (garbled text, stray decals) on the base colour texture inside a sphere: texels far + from the sphere's median colour are replaced by a blend of their surroundings, with the surroundings' grain""" + bl_idname = "brokkr_mesh_polish.scrub_markings" + bl_label = "Scrub Markings" + object_name: bpy.props.StringProperty(name="Object") + x: bpy.props.FloatProperty(name="X", min=-1e6, max=1e6) + y: bpy.props.FloatProperty(name="Y", min=-1e6, max=1e6) + z: bpy.props.FloatProperty(name="Z", min=-1e6, max=1e6) + radius: bpy.props.FloatProperty(name="Radius", default=0.1, min=1e-4, max=1e6) + tolerance: bpy.props.FloatProperty(name="Tolerance", default=0.12, min=0.0, max=2.0, + description="Colour distance (0..1 texture values) from the region's median that counts as a marking") + grow: bpy.props.IntProperty(name="Grow", default=2, min=0, max=32, description="Texels to widen the marking mask by") + + def work(self, context): + obj = mesh_object(self.object_name) + image = base_color_image(obj) + data = arrays(obj) + if data["UV"] is None: + raise Refused(f"Object {obj.name!r} has no UV map.") + centre = np.array([self.x, self.y, self.z]) + corners = data["V"][data["T"]] + middle = corners.mean(axis=1) + reach = np.linalg.norm(corners - middle[:, None, :], axis=2).max(axis=1) + near = np.linalg.norm(middle - centre, axis=1) <= self.radius + reach + if not near.any(): + raise Refused("No surface lies inside the sphere.") + pixels = read_pixels(image) + height, width = pixels.shape[:2] + if height != width: + raise Refused("The base colour texture is not square.") + owner, bary, _ = core.rasterize(data["UV"][near], height) + position = core.interpolate(owner, bary, corners[near]) + region = (owner >= 0) & (np.linalg.norm(position - centre, axis=2) <= self.radius) + mask = core.marking_mask(pixels[..., :3], region, self.tolerance, self.grow) + if not mask.any(): + return {"object": obj.name, "image": image.name, "regionTexels": int(region.sum()), "scrubbedTexels": 0} + rows, cols = np.nonzero(mask) + pad = 24 + y0, y1 = max(rows.min() - pad, 0), min(rows.max() + pad + 1, height) + x0, x1 = max(cols.min() - pad, 0), min(cols.max() + pad + 1, width) + crop = pixels[y0:y1, x0:x1, :3].copy() + hole = mask[y0:y1, x0:x1] + source = region[y0:y1, x0:x1] & ~hole # fill from the same panel only, never from another UV island + if not source.any(): + raise Refused("The whole region counts as marking: raise the tolerance or the radius.") + filled = core.push_pull(crop, source) + grain = crop - core.box_blur(filled, 3) + donors = np.flatnonzero(source) + picks = np.random.default_rng(0).choice(donors, size=int(hole.sum())) + filled[hole] = np.clip(filled[hole] + grain.reshape(-1, 3)[picks], 0.0, 1.0) + out = pixels.copy() + out[y0:y1, x0:x1, :3][hole] = filled[hole] + source = image.name + new = replace_image(image, out, "scrubbed") # may remove image, when it was this add-on's own + return {"object": obj.name, "image": source, "newImage": new.name, + "regionTexels": int(region.sum()), "scrubbedTexels": int(mask.sum())} + + +class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): + """Cut one fused skin into named parts grown from seed points along its concave creases, cap both sides of + every cut, and give each part an origin at the centre of its cut, parented to the first-named part""" + bl_idname = "brokkr_mesh_polish.cut_parts" + bl_label = "Cut Parts" + object_name: bpy.props.StringProperty(name="Object") + seeds: bpy.props.StringProperty(name="Seeds", maxlen=4000, + description="name=x,y,z; name=x,y,z ... world-space points on the surface; the first name is the body") + crease_cost: bpy.props.FloatProperty(name="Crease Cost", default=40.0, min=0.0, max=1000.0, + description="How strongly parts stop at concave creases; 0 splits by distance alone") + through: bpy.props.FloatProperty(name="Through", default=0.0, min=0.0, max=1.0, + description="Above 0, each seed off the body also seeds the far face of its part, found by a ray inward no longer than this share of the bounding diagonal: for thin shells") + joint_scale: bpy.props.FloatProperty(name="Joint Scale", default=0.0, min=0.0, max=10.0, + description="Above 0, a ball joint is added at each cut: radius = this x the cut's mean radius") + + def work(self, context): + obj = mesh_object(self.object_name) + try: + seeds = core.parse_seeds(self.seeds) + except ValueError as error: + raise Refused(str(error)) from None + names = list(dict.fromkeys(name for name, _ in seeds)) + if len(names) < 2: + raise Refused("Cutting needs seeds for at least two parts.") + mesh = obj.data + world = obj.matrix_world.copy() + bm = bmesh.new() + bm.from_mesh(mesh) + diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) + bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) + bm.verts.index_update() + bm.faces.index_update() + matrix = np.array(world) + V = np.array([v.co[:] for v in bm.verts]) @ matrix[:3, :3].T + matrix[:3, 3] + T = np.array([[v.index for v in f.verts] for f in bm.faces], dtype=np.int64) + pairs = core.face_adjacency(T) + costs = core.crease_costs(V, T, pairs, self.crease_cost) + centroid = V[T].mean(axis=1) + placed = [(int(np.argmin(((centroid - np.array(point)) ** 2).sum(axis=1))), names.index(name)) for name, point in seeds] + if self.through > 0: # a thin part's far face: where a ray from the seed, going inward, comes out again + tree = BVHTree.FromPolygons([tuple(v) for v in V], [tuple(int(i) for i in t) for t in T]) + for triangle, index in list(placed): + if index == 0: + continue + a, b, c = V[T[triangle]] + inward = -np.cross(b - a, c - a) + inward /= max(np.linalg.norm(inward), 1e-30) + hit = tree.ray_cast(Vector(centroid[triangle] + inward * diagonal * 1e-4), Vector(inward), self.through * diagonal) + if hit[0] is not None and hit[2] != triangle: + placed.append((int(hit[2]), index)) + part, _ = core.grow_parts(len(T), pairs, costs, placed) + part[part < 0] = 0 # shells no seed reaches stay with the body + label = bm.faces.layers.int.new("polish_part") + was_open = bm.edges.layers.int.new("polish_was_open") + for face, value in zip(bm.faces, part): + face[label] = int(value) + for edge in bm.edges: + edge[was_open] = int(edge.is_boundary) + cap_material = cap_surface() + cap_slot = len(mesh.materials) + materials = list(mesh.materials) + [cap_material] + collection = obj.users_collection[0] if obj.users_collection else context.scene.collection + made, report = [], [] + for index, name in enumerate(names): + piece = bm.copy() + piece_label = piece.faces.layers.int["polish_part"] + piece_open = piece.edges.layers.int["polish_was_open"] + bmesh.ops.delete(piece, geom=[f for f in piece.faces if f[piece_label] != index], context="FACES") + cut = [e for e in piece.edges if e.is_boundary and not e[piece_open]] + if not piece.faces: + piece.free() + raise Refused(f"Part {name!r} came out empty: move its seed onto the surface.") + lengths = np.array([e.calc_length() for e in cut]) + mids = np.array([((e.verts[0].co + e.verts[1].co) / 2)[:] for e in cut]).reshape(-1, 3) + root_local = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut) else np.zeros(3) + spread = mids - root_local + normal_local = np.linalg.eigh((spread * lengths[:, None]).T @ spread)[1][:, 0] if len(cut) >= 3 else np.array([0.0, 0.0, 1.0]) + mean_radius = float((np.linalg.norm(spread, axis=1) * lengths).sum() / lengths.sum()) if len(cut) else 0.0 + caps = bmesh.ops.holes_fill(piece, edges=cut, sides=0)["faces"] if cut else [] + pin_uvs(piece, caps) + caps = bmesh.ops.triangulate(piece, faces=caps)["faces"] if caps else [] + for face in caps: + face.material_index = cap_slot + face.smooth = False + bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) + new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") + root_world = world @ Vector(root_local) if index else world.translation.copy() + piece.to_mesh(new_mesh) + piece.free() + for material in materials: + new_mesh.materials.append(material) + new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) + collection.objects.link(new_obj) + new_obj.matrix_world = world + if index: # move the origin to the cut centre without moving the surface + new_mesh.transform(Matrix.Translation(-Vector(root_local))) + new_obj.matrix_world = world @ Matrix.Translation(Vector(root_local)) + normal_world = (world.to_3x3() @ Vector(normal_local)).normalized() + new_obj["polish_cut_normal"] = [round(c, 6) for c in normal_world] + new_obj["polish_cut_radius"] = mean_radius + made.append(new_obj) + report.append({"name": new_obj.name, "triangles": len(new_mesh.polygons), "capTriangles": len(caps), + "cutEdges": len(cut), "root": [round(c, 6) for c in root_world], + "cutNormal": [round(c, 6) for c in normal_world], "cutRadius": mean_radius}) + bm.free() + body = made[0] + for child, entry in zip(made[1:], report[1:]): + child.parent = body + child.matrix_parent_inverse = body.matrix_world.inverted() + if self.joint_scale > 0 and entry["cutRadius"] > 0: + ball = bmesh.new() + bmesh.ops.create_uvsphere(ball, u_segments=16, v_segments=8, radius=entry["cutRadius"] * self.joint_scale) + joint_mesh = bpy.data.meshes.new(f"{child.name}.joint") + ball.to_mesh(joint_mesh) + ball.free() + joint_mesh.materials.append(cap_material) + joint_mesh.polygons.foreach_set("use_smooth", [True] * len(joint_mesh.polygons)) + joint = bpy.data.objects.new(f"{child.name}.joint", joint_mesh) + collection.objects.link(joint) + joint.matrix_world = Matrix.Translation(Vector(entry["root"])) + joint.parent = body + joint.matrix_parent_inverse = body.matrix_world.inverted() + entry["joint"] = joint.name + bpy.data.objects.remove(obj) + if mesh.users == 0: + bpy.data.meshes.remove(mesh) + return {"body": body.name, "parts": report} + + +class BROKKR_MESH_POLISH_OT_pick(PolishOperator): + """Name the surface point seen at a place in a camera's frame: where a render shows something, this says + where it is, so a region can be given to another action""" + bl_idname = "brokkr_mesh_polish.pick" + bl_label = "Pick Surface Point" + bl_options = {"REGISTER"} + camera_name: bpy.props.StringProperty(name="Camera") + u: bpy.props.FloatProperty(name="U", default=0.5, min=0.0, max=1.0, description="Across the frame, 0 left to 1 right") + v: bpy.props.FloatProperty(name="V", default=0.5, min=0.0, max=1.0, description="Up the frame, 0 bottom to 1 top") + resolution_x: bpy.props.IntProperty(name="Resolution X", default=0, min=0, max=16384, + description="Width of the picture (u, v) was read from; 0 is the scene's render width") + resolution_y: bpy.props.IntProperty(name="Resolution Y", default=0, min=0, max=16384, + description="Height of the picture (u, v) was read from; 0 is the scene's render height") + + def work(self, context): + camera = bpy.data.objects.get(self.camera_name) + if camera is None or camera.type != "CAMERA": + raise Refused(f"No camera named {self.camera_name!r}.") + scene = context.scene + context.view_layer.update() + render = scene.render + kept = (render.resolution_x, render.resolution_y) + try: # the frame's shape is the picture's: the same numbers the still was rendered with + render.resolution_x = self.resolution_x or kept[0] + render.resolution_y = self.resolution_y or kept[1] + top_right, bottom_right, bottom_left, top_left = camera.data.view_frame(scene=scene) + finally: + render.resolution_x, render.resolution_y = kept + on_frame = bottom_left + (bottom_right - bottom_left) * self.u + (top_left - bottom_left) * self.v + world = camera.matrix_world + if camera.data.type == "ORTHO": + origin = world @ Vector((on_frame.x, on_frame.y, 0.0)) + direction = (world.to_3x3() @ Vector((0.0, 0.0, -1.0))).normalized() + else: + origin = world.translation.copy() + direction = (world.to_3x3() @ on_frame).normalized() + hit, location, normal, _, obj, _ = scene.ray_cast(context.evaluated_depsgraph_get(), origin, direction) + if not hit: + return {"hit": False} + return {"hit": True, "object": obj.name, "point": [round(c, 6) for c in location], + "normal": [round(c, 6) for c in normal]} + + +classes = (BROKKR_MESH_POLISH_OT_audit, BROKKR_MESH_POLISH_OT_repair, BROKKR_MESH_POLISH_OT_orient, + BROKKR_MESH_POLISH_OT_delight, BROKKR_MESH_POLISH_OT_scrub_markings, BROKKR_MESH_POLISH_OT_cut_parts, + BROKKR_MESH_POLISH_OT_pick) + + +def register(): + setattr(bpy.types.WindowManager, RESULT, bpy.props.StringProperty()) + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + delattr(bpy.types.WindowManager, RESULT) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json new file mode 100644 index 0000000..d2950b7 --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -0,0 +1,102 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_mesh_polish.audit", + "doc": "Measure meshes: triangles, welded topology, shells, UV overlap and islands, texel density. Changes nothing.", + "changesScene": false, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "a mesh object; every mesh in the scene when absent"}, + {"name": "raster", "type": "integer", "minimum": 64, "maximum": 4096, "default": 1024, "doc": "grid the UV overlap is counted on"} + ] + }, + { + "name": "brokkr_mesh_polish.repair", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, + {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, + {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} + ] + }, + { + "name": "brokkr_mesh_polish.orient", + "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, + {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, + {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, + {"name": "principal", "type": "boolean", "default": true, "doc": "false keeps the current axes and only turns, centres and scales"} + ] + }, + { + "name": "brokkr_mesh_polish.delight", + "doc": "Undo lighting baked into the base colour texture, as far as normals and ambient occlusion explain it.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "any object using the texture"}, + {"name": "strength", "type": "number", "minimum": 0, "maximum": 1, "default": 1}, + {"name": "max_gain", "type": "number", "minimum": 1, "maximum": 8, "default": 3, "doc": "largest brightening or darkening factor"}, + {"name": "clusters", "type": "integer", "minimum": 1, "maximum": 8, "default": 3, "doc": "distinct paints assumed"}, + {"name": "fit_size", "type": "integer", "minimum": 128, "maximum": 2048, "default": 1024}, + {"name": "occlusion_rays", "type": "integer", "minimum": 8, "maximum": 256, "default": 48} + ] + }, + { + "name": "brokkr_mesh_polish.scrub_markings", + "doc": "Paint out markings (garbled text, decals) on the base colour texture inside a world-space sphere.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "x", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "y", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "z", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "radius", "type": "number", "minimum": 0.0001, "maximum": 1000000, "required": true}, + {"name": "tolerance", "type": "number", "minimum": 0, "maximum": 2, "default": 0.12, "doc": "colour distance from the region's median that counts as a marking"}, + {"name": "grow", "type": "integer", "minimum": 0, "maximum": 32, "default": 2, "doc": "texels to widen the mask by"} + ] + }, + { + "name": "brokkr_mesh_polish.cut_parts", + "doc": "Cut one fused skin into named parts grown from seeds along concave creases; cap the cuts; root each part at its cut.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "seeds", "type": "string", "required": true, "minLength": 3, "maxLength": 4000, "doc": "name=x,y,z; name=x,y,z ... world-space; the first name is the body"}, + {"name": "crease_cost", "type": "number", "minimum": 0, "maximum": 1000, "default": 40, "doc": "how strongly parts stop at sharp concave creases; 0 splits by distance alone"}, + {"name": "through", "type": "number", "minimum": 0, "maximum": 1, "default": 0, "doc": "above 0, each seed off the body also seeds the far face of its part, by a ray inward no longer than this share of the bounding diagonal (thin shells)"}, + {"name": "joint_scale", "type": "number", "minimum": 0, "maximum": 10, "default": 0, "doc": "above 0 adds a ball joint at each cut, radius = this x the cut's mean radius"} + ] + }, + { + "name": "brokkr_mesh_polish.pick", + "doc": "The surface point seen at (u, v) of a camera's frame, so a place found in a render can be named to another action. Changes nothing.", + "changesScene": false, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "camera_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "u", "type": "number", "minimum": 0, "maximum": 1, "required": true, "doc": "across the frame, 0 left to 1 right"}, + {"name": "v", "type": "number", "minimum": 0, "maximum": 1, "required": true, "doc": "up the frame, 0 bottom to 1 top"}, + {"name": "resolution_x", "type": "integer", "minimum": 0, "maximum": 16384, "default": 0, "doc": "width of the picture (u, v) was read from; 0 is the scene's render width"}, + {"name": "resolution_y", "type": "integer", "minimum": 0, "maximum": 16384, "default": 0, "doc": "height of the picture; 0 is the scene's render height"} + ] + } + ] +} diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py new file mode 100644 index 0000000..0ae197a --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -0,0 +1,414 @@ +"""The arithmetic of mesh polish: numpy only, no bpy, so every rule here is tested without Blender. + +A mesh is three arrays: V (n,3) positions, T (m,3) vertex indices of triangles, UV (m,3,2) per-corner texture +coordinates. Generated meshes (Tripo and its kin) and glTF imports split vertices at every UV seam, so topology +is always judged on welded positions (weld), never on the raw indices. +""" +from __future__ import annotations + +import numpy as np + + +def weld(V: np.ndarray, T: np.ndarray, tolerance: float) -> tuple[np.ndarray, np.ndarray]: + """(welded vertex id per vertex, T rewritten to welded ids): vertices in the same tolerance cell are one.""" + cells = np.round(np.asarray(V, dtype=np.float64) / max(tolerance, 1e-12)).astype(np.int64) + _, ids = np.unique(cells, axis=0, return_inverse=True) + ids = ids.reshape(-1) + return ids, ids[T] + + +def components(count: int, pairs: np.ndarray) -> np.ndarray: + """Connected-component label (the smallest member id) for each of count nodes joined by pairs (k,2).""" + parent = np.arange(count, dtype=np.int64) + if len(pairs) == 0: + return parent + a, b = pairs[:, 0], pairs[:, 1] + while True: + pa, pb = parent[a], parent[b] + if np.array_equal(pa, pb): + return parent + np.minimum.at(parent, np.maximum(pa, pb), np.minimum(pa, pb)) + while True: + hop = parent[parent] + if np.array_equal(hop, parent): + break + parent = hop + + +def triangle_areas(V: np.ndarray, T: np.ndarray) -> np.ndarray: + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return 0.5 * np.linalg.norm(np.cross(b - a, c - a), axis=1) + + +def edge_census(TW: np.ndarray) -> dict[str, int]: + """Edges of the welded triangles by how many triangles use them: 1 is an open boundary, 3 or more is + non-manifold. Triangles that collapsed in the weld (two corners equal) are left out.""" + live = (TW[:, 0] != TW[:, 1]) & (TW[:, 1] != TW[:, 2]) & (TW[:, 0] != TW[:, 2]) + tw = TW[live] + edges = np.sort(np.concatenate([tw[:, [0, 1]], tw[:, [1, 2]], tw[:, [2, 0]]]), axis=1) + _, counts = np.unique(edges, axis=0, return_counts=True) + return {"edges": int(len(counts)), "boundaryEdges": int((counts == 1).sum()), + "nonManifoldEdges": int((counts > 2).sum()), "collapsedTriangles": int((~live).sum())} + + +def triangle_components(TW: np.ndarray) -> np.ndarray: + """Component label per triangle: triangles sharing a welded vertex are one shell.""" + count = int(TW.max()) + 1 if len(TW) else 0 + labels = components(count, np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]]])) + return labels[TW[:, 0]] + + +def rasterize(UV: np.ndarray, size: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Texel centres covered by the UV triangles, on a size x size grid with v up (row 0 is v = 0). + + Returns (owner, bary, cover): owner[y, x] is the last triangle covering the texel centre or -1, bary[y, x] + its barycentric weights there, cover[y, x] how many triangles cover it (2 or more is UV overlap).""" + owner = np.full((size, size), -1, dtype=np.int32) + bary = np.zeros((size, size, 3), dtype=np.float32) + cover = np.zeros((size, size), dtype=np.uint16) + P = np.asarray(UV, dtype=np.float64) * size - 0.5 # texel index space: centre of texel i is i + lo = np.clip(np.ceil(P.min(axis=1)).astype(np.int64), 0, size) + hi = np.clip(np.floor(P.max(axis=1)).astype(np.int64) + 1, 0, size) + det = ((P[:, 1, 0] - P[:, 0, 0]) * (P[:, 2, 1] - P[:, 0, 1]) - (P[:, 2, 0] - P[:, 0, 0]) * (P[:, 1, 1] - P[:, 0, 1])) + for t in np.nonzero((np.abs(det) > 1e-12) & (hi[:, 0] > lo[:, 0]) & (hi[:, 1] > lo[:, 1]))[0]: + x0, y0, x1, y1 = lo[t, 0], lo[t, 1], hi[t, 0], hi[t, 1] + xs = np.arange(x0, x1, dtype=np.float64)[None, :] + ys = np.arange(y0, y1, dtype=np.float64)[:, None] + a, b, c = P[t] + w1 = ((xs - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (ys - a[1])) / det[t] + w2 = ((b[0] - a[0]) * (ys - a[1]) - (xs - a[0]) * (b[1] - a[1])) / det[t] + w0 = 1.0 - w1 - w2 + inside = (w0 >= 0) & (w1 >= 0) & (w2 >= 0) + if not inside.any(): + continue + block = (slice(y0, y1), slice(x0, x1)) + cover[block] += inside + owner[block][inside] = t + bary[block][inside] = np.stack([w0, w1, w2], axis=-1)[inside] + return owner, bary, cover + + +def interpolate(owner: np.ndarray, bary: np.ndarray, corners: np.ndarray) -> np.ndarray: + """Per-texel value of a per-corner attribute corners (m,3,k); zero where no triangle covers.""" + out = np.zeros(owner.shape + (corners.shape[-1],), dtype=np.float32) + hit = owner >= 0 + out[hit] = np.einsum("pc,pck->pk", bary[hit], corners[owner[hit]]) + return out + + +def uv_islands(TW: np.ndarray, UV: np.ndarray) -> int: + """UV islands: triangles joined where they share a welded vertex at the same UV coordinate.""" + keys = np.concatenate([TW.reshape(-1, 1).astype(np.float64), np.round(UV.reshape(-1, 2) * 65536.0)], axis=1) + _, ids = np.unique(keys, axis=0, return_inverse=True) + ids = ids.reshape(-1, 3) + labels = components(int(ids.max()) + 1, np.concatenate([ids[:, [0, 1]], ids[:, [1, 2]]])) + return int(len(np.unique(labels[ids[:, 0]]))) + + +def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> float: + order = np.argsort(values) + cumulative = np.cumsum(weights[order]) + return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) + + +def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, + weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + """The measurements a polish pass is judged by. Lengths are in the mesh's own units. + + Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is + the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + V = np.asarray(V, dtype=np.float64) + T = np.asarray(T, dtype=np.int64) + extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) + diagonal = float(np.linalg.norm(extent)) + areas = triangle_areas(V, T) + ids, TW = weld(V, T, diagonal * weld_fraction) + report = {"triangles": int(len(T)), "vertices": int(len(V)), "weldedVertices": int(ids.max()) + 1 if len(V) else 0, + "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), + "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} + report.update(edge_census(TW)) + shells = triangle_components(TW) + _, shell_sizes = np.unique(shells, return_counts=True) + report["shells"] = int(len(shell_sizes)) + report["shellTriangles"] = sorted((int(s) for s in shell_sizes), reverse=True)[:12] + if UV is None: + return report + UV = np.asarray(UV, dtype=np.float64) + signed = 0.5 * ((UV[:, 1, 0] - UV[:, 0, 0]) * (UV[:, 2, 1] - UV[:, 0, 1]) + - (UV[:, 2, 0] - UV[:, 0, 0]) * (UV[:, 1, 1] - UV[:, 0, 1])) + _, _, cover = rasterize(UV, raster) + covered = int((cover > 0).sum()) + report.update({ + "uvIslands": uv_islands(TW, UV), + "uvFlippedTriangles": int((signed < 0).sum()), + "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), + "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), + "uvCoverage": covered / float(raster * raster), + "uvOverlap": float((cover > 1).sum()) / covered if covered else 0.0, + }) + usable = (areas > 0) & (np.abs(signed) > 0) + if texture_size and usable.any(): + density = np.sqrt(np.abs(signed[usable]) * texture_size * texture_size / areas[usable]) + p5, p50, p95 = (weighted_quantile(density, areas[usable], q) for q in (0.05, 0.5, 0.95)) + report.update({"texelDensityMedian": p50, "texelDensityP5": p5, "texelDensityP95": p95, + "texelDensitySpread": p95 / p5 if p5 > 0 else float("inf")}) + return report + + +# --- orientation ----------------------------------------------------------------------------------------- + +def principal_frame(V: np.ndarray, T: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """(centre, R): the area-weighted centroid and a right-handed rotation whose rows are the principal axes, + longest first. R @ (p - centre) puts the longest axis on x, the shortest on z.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + areas = triangle_areas(V, T) + mids = (a + b + c) / 3.0 + centre = (mids * areas[:, None]).sum(axis=0) / areas.sum() + d = mids - centre + _, vectors = np.linalg.eigh((d * areas[:, None]).T @ d) + R = vectors[:, ::-1].T.copy() + if np.linalg.det(R) < 0: + R[2] *= -1 + return centre, R + + +def mirror_error(V: np.ndarray, axis: int, samples: int = 800, seed: int = 0) -> float: + """How far the point set is from mirror-symmetric across the plane axis = 0: the mean distance from a + mirrored sample to its nearest original, as a fraction of the bounding diagonal. 0 is a perfect mirror.""" + rng = np.random.default_rng(seed) + pick = V[rng.choice(len(V), size=min(samples, len(V)), replace=False)] + mirrored = pick.copy() + mirrored[:, axis] *= -1 + base = V[rng.choice(len(V), size=min(4 * samples, len(V)), replace=False)] + nearest = np.sqrt(((mirrored[:, None, :] - base[None, :, :]) ** 2).sum(axis=2).min(axis=1)) + return float(nearest.mean() / np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + + +# --- parts ----------------------------------------------------------------------------------------------- + +def face_adjacency(TW: np.ndarray) -> np.ndarray: + """Pairs (k,2) of triangles that share a welded edge (each manifold edge once; an edge of three or more + triangles joins them in a chain).""" + count = len(TW) + edges = np.sort(np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]], TW[:, [2, 0]]]), axis=1) + face = np.tile(np.arange(count), 3) + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges, face = edges[order], face[order] + same = (edges[1:] == edges[:-1]).all(axis=1) + return np.stack([face[:-1][same], face[1:][same]], axis=1) + + +def crease_costs(V: np.ndarray, T: np.ndarray, pairs: np.ndarray, crease_cost: float) -> np.ndarray: + """Cost of stepping between two adjacent triangles: the distance between their centroids as a fraction of + the bounding diagonal, plus crease_cost times the square of how concave the fold between them is (0 flat + or convex, 1 a fold back on itself). A sharp concave crease is where one part of a fused skin meets another; + the square keeps the gentle concavity of a bowl, many small folds, far cheaper than one such crease.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + normal = np.cross(b - a, c - a) + normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-30) + centre = (a + b + c) / 3.0 + diagonal = np.linalg.norm(V.max(axis=0) - V.min(axis=0)) + i, j = pairs[:, 0], pairs[:, 1] + step = centre[j] - centre[i] + angle = np.arccos(np.clip((normal[i] * normal[j]).sum(axis=1), -1.0, 1.0)) / np.pi + concave = ((step * normal[i]).sum(axis=1) - (step * normal[j]).sum(axis=1)) > 0 + return np.linalg.norm(step, axis=1) / diagonal + crease_cost * np.where(concave, angle * angle, 0.0) + + +def grow_parts(count: int, pairs: np.ndarray, costs: np.ndarray, seeds: list[tuple[int, int]]) -> tuple[np.ndarray, np.ndarray]: + """(part, cost) per triangle: each triangle joins the seed it is cheapest to walk to, at that cost; part is + -1 and cost infinite where no seed reaches. seeds are (triangle, part) and several seeds may name one part.""" + import heapq + + order = np.argsort(np.concatenate([pairs[:, 0], pairs[:, 1]]), kind="stable") + source = np.concatenate([pairs[:, 0], pairs[:, 1]])[order] + target = np.concatenate([pairs[:, 1], pairs[:, 0]])[order].tolist() + weight = np.concatenate([costs, costs])[order].tolist() + start = np.searchsorted(source, np.arange(count + 1)).tolist() + best = [float("inf")] * count + part = [-1] * count + heap = [] + for triangle, label in seeds: + best[triangle], part[triangle] = 0.0, label + heap.append((0.0, triangle, label)) + heapq.heapify(heap) + while heap: + cost, triangle, label = heapq.heappop(heap) + if cost > best[triangle] or part[triangle] != label: + continue + for k in range(start[triangle], start[triangle + 1]): + other, reach = target[k], cost + weight[k] + if reach < best[other]: + best[other], part[other] = reach, label + heapq.heappush(heap, (reach, other, label)) + return np.asarray(part, dtype=np.int64), np.asarray(best) + + +def parse_seeds(text: str) -> list[tuple[str, tuple[float, float, float]]]: + """'hull=0,0,0; pod1=1,0,0.5; pod1=1.2,0,0.4' as [(name, (x, y, z))]; ValueError names the bad entry.""" + seeds = [] + for entry in (piece.strip() for piece in text.split(";")): + if not entry: + continue + name, _, numbers = entry.partition("=") + values = numbers.split(",") + try: + point = tuple(float(v) for v in values) + except ValueError: + point = () + if not name.strip() or len(point) != 3: + raise ValueError(f"seed {entry!r} is not name=x,y,z") + seeds.append((name.strip(), point)) + if not seeds: + raise ValueError("no seeds given") + return seeds + + +# --- baked lighting -------------------------------------------------------------------------------------- + +def srgb_to_linear(c: np.ndarray) -> np.ndarray: + return np.where(c <= 0.04045, c / 12.92, ((np.maximum(c, 0.0) + 0.055) / 1.055) ** 2.4) + + +def linear_to_srgb(c: np.ndarray) -> np.ndarray: + c = np.clip(c, 0.0, 1.0) + return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1.0 / 2.4) - 0.055) + + +def luminance(rgb: np.ndarray) -> np.ndarray: + return rgb[..., 0] * 0.2126 + rgb[..., 1] * 0.7152 + rgb[..., 2] * 0.0722 + + +def shading_basis(normals: np.ndarray, occlusion: np.ndarray) -> np.ndarray: + """What baked light can depend on at a surface point: the eight non-constant order-2 spherical harmonics of + the unit normal (a smooth distant light) and the log of ambient occlusion (0..1, 1 is open sky).""" + x, y, z = normals[:, 0], normals[:, 1], normals[:, 2] + return np.stack([x, y, z, x * y, y * z, x * z, x * x - y * y, 3 * z * z - 1, + np.log(np.clip(occlusion, 0.02, 1.0))], axis=1) + + +def chroma_clusters(rgb: np.ndarray, count: int) -> np.ndarray: + """A cluster per sample by chromaticity alone (r and g as shares of the sum): paint of one hue stays one + cluster whether lit or shaded, so each cluster can stand for one family of paint.""" + return kmeans((rgb / (rgb.sum(axis=1, keepdims=True) + 1e-4))[:, :2], count) + + +def fit_shading(log_l: np.ndarray, basis: np.ndarray, clusters: np.ndarray, expectile: float = 0.85, + rounds: int = 12) -> tuple[np.ndarray, float]: + """(weights, explained): log luminance = an intercept per cluster + basis @ weights (the light). + + The fit follows the upper envelope of luminance (an expectile regression: samples above the fit weigh + expectile, samples below weigh 1 - expectile). Within one hue the brightest paint at a given normal and + occlusion shows how much light the bake put there; darker paint in the same place, such as machinery in a + crevice of a pale hull, is paint and must not be read as shadow. explained is the share of the + within-cluster variance of log luminance that the light accounts for: near 0, no baked light was found.""" + count = int(clusters.max()) + 1 + weight = np.ones(len(log_l)) + + def demean(values: np.ndarray) -> np.ndarray: + scaled = values * (weight[:, None] if values.ndim == 2 else weight) + sums = np.stack([np.bincount(clusters, weights=column, minlength=count) for column in scaled.reshape(len(values), -1).T], axis=1) + means = sums / np.maximum(np.bincount(clusters, weights=weight, minlength=count), 1e-12)[:, None] + return values - means[clusters].reshape(values.shape) + + w = np.zeros(basis.shape[1]) + for _ in range(rounds): + x, y = demean(basis), demean(log_l) + root = np.sqrt(weight) + w, *_ = np.linalg.lstsq(x * root[:, None], y * root, rcond=None) + weight = np.where(y - x @ w > 0, expectile, 1.0 - expectile) + weight = np.ones(len(log_l)) + x, y = demean(basis), demean(log_l) + total = float((y * y).sum()) + residual = demean(log_l - basis @ w) + return w, max(1.0 - float((residual * residual).sum()) / total, 0.0) if total > 0 else 0.0 + + +def lighting_signature(log_l: np.ndarray, normals: np.ndarray, occlusion: np.ndarray, up: int = 2) -> dict: + """Model-free signs of baked light: how much brighter up-facing surface is than down-facing (a ratio of + geometric-mean luminance, 1 is none) and how log luminance correlates with ambient occlusion (0 is none).""" + top, bottom = normals[:, up] > 0.5, normals[:, up] < -0.5 + ratio = float(np.exp(log_l[top].mean() - log_l[bottom].mean())) if top.any() and bottom.any() else 1.0 + spread = float(np.std(occlusion)) + correlation = float(np.corrcoef(log_l, occlusion)[0, 1]) if spread > 1e-6 and np.std(log_l) > 1e-9 else 0.0 + return {"upDownLuminanceRatio": ratio, "occlusionCorrelation": correlation} + + +def kmeans(features: np.ndarray, count: int, rounds: int = 12, seed: int = 0) -> np.ndarray: + rng = np.random.default_rng(seed) + centres = features[rng.choice(len(features), size=count, replace=False)].copy() + labels = np.zeros(len(features), dtype=np.int64) + for _ in range(rounds): + labels = np.argmin(((features[:, None, :] - centres[None, :, :]) ** 2).sum(axis=2), axis=1) + for k in range(count): + if (labels == k).any(): + centres[k] = features[labels == k].mean(axis=0) + return labels + + +def delight_gain(basis: np.ndarray, weights: np.ndarray, strength: float, max_gain: float) -> np.ndarray: + """The factor that undoes the fitted light at each sample. Surface the light favoured (the 90th percentile + of fitted light) is left as it is and shaded surface rises to meet it; nothing changes by more than + max_gain either way.""" + light = basis @ weights + return np.clip(np.exp(strength * (np.percentile(light, 90) - light)), 1.0 / max_gain, max_gain) + + +# --- texture filling ------------------------------------------------------------------------------------- + +def push_pull(image: np.ndarray, known: np.ndarray) -> np.ndarray: + """image (h,w,c) with the texels where known is False replaced by a smooth blend of the known texels around + them (push-pull: average down a pyramid, fill up from the coarser level). Known texels are returned as given.""" + h, w = known.shape + if known.all() or not known.any() or min(h, w) < 2: + return image.copy() + value = np.where(known[..., None], image, 0.0).astype(np.float32) + mass = known.astype(np.float32) + h2, w2 = (h + 1) // 2, (w + 1) // 2 + padded_v = np.zeros((h2 * 2, w2 * 2, image.shape[2]), dtype=np.float32) + padded_m = np.zeros((h2 * 2, w2 * 2), dtype=np.float32) + padded_v[:h, :w], padded_m[:h, :w] = value, mass + small_m = padded_m.reshape(h2, 2, w2, 2).sum(axis=(1, 3)) + small_v = padded_v.reshape(h2, 2, w2, 2, -1).sum(axis=(1, 3)) / np.maximum(small_m, 1e-9)[..., None] + filled = push_pull(small_v, small_m > 0) + up = np.repeat(np.repeat(filled, 2, axis=0), 2, axis=1)[:h, :w] + return np.where(known[..., None], image, up).astype(image.dtype) + + +def box_blur(image: np.ndarray, radius: int) -> np.ndarray: + """Mean over a (2 radius + 1) square, edges clamped; image is (h,w) or (h,w,c).""" + if radius <= 0: + return image.copy() + out = image.astype(np.float64) + for axis in (0, 1): + pad = [(0, 0)] * out.ndim + pad[axis] = (radius + 1, radius) + summed = np.cumsum(np.pad(out, pad, mode="edge"), axis=axis) + n = out.shape[axis] + upper = np.take(summed, np.arange(2 * radius + 1, 2 * radius + 1 + n), axis=axis) + lower = np.take(summed, np.arange(0, n), axis=axis) + out = (upper - lower) / (2 * radius + 1) + return out.astype(image.dtype) + + +def dilate(mask: np.ndarray, steps: int) -> np.ndarray: + out = mask.copy() + for _ in range(steps): + grown = out.copy() + grown[1:, :] |= out[:-1, :] + grown[:-1, :] |= out[1:, :] + grown[:, 1:] |= out[:, :-1] + grown[:, :-1] |= out[:, 1:] + out = grown + return out + + +def marking_mask(rgb: np.ndarray, region: np.ndarray, tolerance: float, grow: int) -> np.ndarray: + """Texels inside region whose colour is further than tolerance (Euclidean, in the image's own 0..1 values) + from the region's median colour, grown by grow texels within the region: the ink on a painted panel.""" + if not region.any(): + return np.zeros(region.shape, dtype=bool) + background = np.median(rgb[region], axis=0) + ink = region & (np.linalg.norm(rgb - background, axis=-1) > tolerance) + return dilate(ink, grow) & region diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py new file mode 100644 index 0000000..4284585 --- /dev/null +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -0,0 +1,234 @@ +"""Live proof, in a background Blender, that every brokkr_mesh_polish row is admitted by Brokkr as a host action +and does what its doc says to real bpy meshes and images. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/mesh_polish.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. +Writes .result.json and exits 1 when a check failed. +""" +import json +import math +import os +import sys +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + +SURFACE = Path(__file__).resolve().parents[2] +OUT = sys.argv[sys.argv.index("--") + 1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +addon_utils.enable("brokkr_mesh_polish", default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields}) + result = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + return receipt, result + + +def new_object(name, build, image=None): + mesh = bpy.data.meshes.new(name) + bm = bmesh.new() + bm.loops.layers.uv.new("UVMap") # calc_uvs fills a layer that exists + build(bm) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + bpy.context.scene.collection.objects.link(obj) + if image is not None: + material = bpy.data.materials.new(name) + material.use_nodes = True + node = material.node_tree.nodes.new("ShaderNodeTexImage") + node.image = image + shader = next(n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED") + material.node_tree.links.new(node.outputs["Color"], shader.inputs["Base Color"]) + mesh.materials.append(material) + return obj + + +def new_image(name, pixels): + height, width = pixels.shape[:2] + image = bpy.data.images.new(name, width, height, alpha=False) + image.colorspace_settings.name = "Non-Color" # stored values are the paint: the checks read them back as written + rgba = np.ones((height, width, 4), dtype=np.float32) + rgba[..., :3] = pixels + image.pixels.foreach_set(rgba.reshape(-1)) + return image + + +def pixels_of(obj): + image = obj.material_slots[0].material.node_tree.nodes["Image Texture"].image + flat = np.empty(image.size[0] * image.size[1] * 4, dtype=np.float32) + image.pixels.foreach_get(flat) + return flat.reshape(image.size[1], image.size[0], 4)[..., :3], image + + +check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) + +# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +size = 256 +rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) +sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), + new_image("ball_bake", baked.astype(np.float32))) +sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) +torn = bmesh.new() +torn.from_mesh(sphere.data) +bmesh.ops.split_edges(torn, edges=torn.edges[:]) +torn.to_mesh(sphere.data) +torn.free() +receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") +check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) +check("audit: welded topology sees one closed shell in the torn sphere", + before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) +check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 + and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) +torn_vertices = len(sphere.data.vertices) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) +check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) +check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) + and len(sphere.data.vertices) == 48 * 23 + 2, repaired) +edges = [e for e in sphere.data.edges] +check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) + +# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +after_pixels, after_image = pixels_of(sphere) +column = after_pixels[:, size // 2, 0] +# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 +ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) +ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} +check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" + and after_image.packed_file is not None, receipt["message"]) +check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) +# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 +check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) +slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) +sphere.hide_viewport = True +bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body +receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) +extent = corners.max(axis=0) - corners.min(axis=0) +check("orient: long on Y, thin on Z, scaled to the length, centred", + receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) + and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) +check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +bpy.data.objects.remove(slab) + +# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- +def knobbed(bm): + bmesh.ops.create_cube(bm, size=2.0) + top = next(f for f in bm.faces if f.normal.z > 0.9) + bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) + extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) + bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) + bmesh.ops.delete(bm, geom=[top], context="FACES") + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + + +block = new_object("Block", knobbed) +receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") +check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) +receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) +R["cut"] = cut +check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) + and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) +if receipt["status"] == "accepted": + knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] + part = {entry["name"]: entry for entry in cut["parts"]} + check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) + and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) + check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body + and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) + _, closed = send("brokkr_mesh_polish.audit") + check("cut_parts: both sides of the cut are capped (closed shells)", + all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), + {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) + check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) +receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") +check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- +panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) +panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) +for column_start in range(8, 120, 8): # yellow strokes over the whole texture + panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + + +def plate(bm): + bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + + +sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x +sign.location = (0, 0, 5) +bpy.context.view_layer.update() +camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) +bpy.context.scene.collection.objects.link(camera) +camera.data.type = "ORTHO" +camera.data.ortho_scale = 4.0 +camera.location = (0, 0, 9) +receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) +check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] + and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) +receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) +check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + + +def ink(pixels): + return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + + +receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) +after, image = pixels_of(sign) +inside = np.zeros((128, 128), dtype=bool) +inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 +far = np.zeros((128, 128), dtype=bool) +far[:, 72:] = True # the other half of the sign +R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} +check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" + and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) +check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) +receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) +check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) +receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) +check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json new file mode 100644 index 0000000..9f3bae1 --- /dev/null +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -0,0 +1,471 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host file admitted", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick" + ] + }, + { + "name": "audit: accepted, no undo step", + "ok": true, + "detail": "Operator brokkr_mesh_polish.audit finished." + }, + { + "name": "audit: welded topology sees one closed shell in the torn sphere", + "ok": true, + "detail": { + "triangles": 2208, + "vertices": 4512, + "weldedVertices": 1106, + "extent": [ + 2.000001, + 2.000002, + 2.0 + ], + "surfaceArea": 12.521572614010894, + "degenerateTriangles": 0, + "edges": 3312, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 2208 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 0, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.95831298828125, + "uvOverlap": 0.0, + "texelDensityMedian": 61.97425923665604, + "texelDensityP5": 57.66165269744736, + "texelDensityP95": 113.44982327717632, + "texelDensitySpread": 1.9675090457856172, + "baseColorImage": "ball_bake", + "baseColorSize": [ + 256, + 256 + ], + "customNormals": false + } + }, + { + "name": "audit: texture and UV facts", + "ok": true, + "detail": { + "triangles": 2208, + "vertices": 4512, + "weldedVertices": 1106, + "extent": [ + 2.000001, + 2.000002, + 2.0 + ], + "surfaceArea": 12.521572614010894, + "degenerateTriangles": 0, + "edges": 3312, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 2208 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 0, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.95831298828125, + "uvOverlap": 0.0, + "texelDensityMedian": 61.97425923665604, + "texelDensityP5": 57.66165269744736, + "texelDensityP95": 113.44982327717632, + "texelDensitySpread": 1.9675090457856172, + "baseColorImage": "ball_bake", + "baseColorSize": [ + 256, + 256 + ], + "customNormals": false + } + }, + { + "name": "repair: accepted as one undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-2", + "action": "brokkr_mesh_polish.repair", + "status": "accepted", + "message": "Operator brokkr_mesh_polish.repair finished.", + "objectName": "", + "requestedBy": "test/driver", + "note": "", + "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", + "lookPath": "", + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", + "observedAt": "2026-12-01T00:06:45.524772+00:00" + } + }, + { + "name": "repair: welds the torn vertices", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 3406, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0 + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1 + } + } + }, + { + "name": "repair: every edge has two faces again", + "ok": true, + "detail": 2256 + }, + { + "name": "delight: accepted, new packed image on the material", + "ok": true, + "detail": "Operator brokkr_mesh_polish.delight finished." + }, + { + "name": "delight: finds the baked light", + "ok": true, + "detail": { + "image": "ball_bake", + "newImage": "ball_bake.delit", + "objects": [ + "Ball" + ], + "explainedByLight": { + "before": 0.9722586649734903, + "after": 0.005096664890544278 + }, + "before": { + "upDownLuminanceRatio": 2.5686425388668988, + "occlusionCorrelation": 0.0 + }, + "after": { + "upDownLuminanceRatio": 1.0190418174045521, + "occlusionCorrelation": 0.0 + }, + "gain": { + "min": 0.9849698054726783, + "median": 1.454503966956526, + "max": 3.0, + "clamped": 0.05147808358817533 + } + } + }, + { + "name": "delight: levels top against bottom", + "ok": true, + "detail": [ + 3.2905027932960893, + 1.119760513305664 + ] + }, + { + "name": "orient: long on Y, thin on Z, scaled to the length, centred", + "ok": true, + "detail": [ + [ + 4.0, + 12.0, + 2.000000476837158 + ], + { + "objects": [ + "Slab" + ], + "scale": 4.000000308302869, + "extent": [ + 4.0, + 12.0, + 2.0 + ], + "mirrorError": { + "X": 7.4458642458520986e-09, + "Y": 7.225481440456122e-09, + "Z": 1.962464589014781e-09 + } + } + ] + }, + { + "name": "orient: reports the mirror error of a symmetric body as small", + "ok": true, + "detail": { + "X": 7.4458642458520986e-09, + "Y": 7.225481440456122e-09, + "Z": 1.962464589014781e-09 + } + }, + { + "name": "cut fixture is one closed skin", + "ok": true, + "detail": { + "triangles": 28, + "vertices": 16, + "weldedVertices": 16, + "extent": [ + 2.0, + 2.0, + 3.0 + ], + "surfaceArea": 28.605887413024902, + "degenerateTriangles": 0, + "edges": 42, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 28 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 28, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.0, + "uvOverlap": 0.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + }, + { + "name": "cut_parts: accepted, one undo step, the fused object is replaced", + "ok": true, + "detail": "Operator brokkr_mesh_polish.cut_parts finished." + }, + { + "name": "cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + "ok": true, + "detail": { + "name": "Block.knob", + "triangles": 12, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 1.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128, + "joint": "Block.knob.joint" + } + }, + { + "name": "cut_parts: the knob hangs from the body and has not moved", + "ok": true, + "detail": null + }, + { + "name": "cut_parts: both sides of the cut are capped (closed shells)", + "ok": true, + "detail": { + "Block.body": [ + 0, + 1 + ], + "Block.knob": [ + 0, + 1 + ] + } + }, + { + "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "ok": true, + "detail": "Block.knob.joint" + }, + { + "name": "cut_parts: one part is refused with nothing changed", + "ok": true, + "detail": "Error: Cutting needs seeds for at least two parts." + }, + { + "name": "pick: names the surface point under (u, v) of a picture of that shape", + "ok": true, + "detail": { + "hit": true, + "object": "Sign", + "point": [ + -1.0, + 0.0, + 5.0 + ], + "normal": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "name": "pick: off the surface is a miss, not an error", + "ok": true, + "detail": { + "hit": false + } + }, + { + "name": "scrub_markings: accepted, the lettering inside the sphere is gone", + "ok": true, + "detail": { + "report": { + "object": "Sign", + "image": "sign_paint", + "newImage": "sign_paint.scrubbed", + "regionTexels": 1612, + "scrubbedTexels": 1130 + }, + "inkInsideBefore": 192, + "inkInsideAfter": 0 + } + }, + { + "name": "scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", + "ok": true, + "detail": "sign_paint.scrubbed" + }, + { + "name": "scrub_markings: a sphere off the surface is refused", + "ok": true, + "detail": "Error: No surface lies inside the sphere." + }, + { + "name": "a bound miss is denied by Brokkr's table before the operator runs", + "ok": true, + "detail": "max_gain must be between 1 and 8." + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick" + ], + "delight": { + "report": { + "image": "ball_bake", + "newImage": "ball_bake.delit", + "objects": [ + "Ball" + ], + "explainedByLight": { + "before": 0.9722586649734903, + "after": 0.005096664890544278 + }, + "before": { + "upDownLuminanceRatio": 2.5686425388668988, + "occlusionCorrelation": 0.0 + }, + "after": { + "upDownLuminanceRatio": 1.0190418174045521, + "occlusionCorrelation": 0.0 + }, + "gain": { + "min": 0.9849698054726783, + "median": 1.454503966956526, + "max": 3.0, + "clamped": 0.05147808358817533 + } + }, + "ratioBefore": 3.2905027932960893, + "ratioAfter": 1.119760513305664 + }, + "cut": { + "body": "Block.body", + "parts": [ + { + "name": "Block.body", + "triangles": 20, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 0.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128 + }, + { + "name": "Block.knob", + "triangles": 12, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 1.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128, + "joint": "Block.knob.joint" + } + ] + }, + "scrub": { + "report": { + "object": "Sign", + "image": "sign_paint", + "newImage": "sign_paint.scrubbed", + "regionTexels": 1612, + "scrubbedTexels": 1130 + }, + "inkInsideBefore": 192, + "inkInsideAfter": 0 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py new file mode 100644 index 0000000..7205f81 --- /dev/null +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -0,0 +1,390 @@ +"""Mesh polish tests. No Blender: the arithmetic in brokkr_mesh_polish/core.py on small hand-built meshes and +textures, the host action file against Brokkr's own checker, and the turntable recipe against the action table. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators around this arithmetic are exercised in a real Blender by tests/live/mesh_polish.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped reading +and the reading of the nearest mutant named beside it, and both are at least 1.2 away. +""" +from __future__ import annotations + +import importlib.util +import json +import math +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + + +def load(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None + + +def quad_strip(count: int, fold_after: int | None = None): + """count unit quads along x as 2 * count triangles, every triangle with its own three vertices (as a glTF + import leaves a seamed mesh). After fold_after quads the strip turns straight up: a 90 degree concave fold + seen from above.""" + V, T = [], [] + for i in range(count): + def at_station(s): + if fold_after is None or s <= fold_after: + return (float(s), 0.0) + return (float(fold_after), float(s - fold_after)) + (x0, z0), (x1, z1) = at_station(i), at_station(i + 1) + corners = [(x0, 0.0, z0), (x1, 0.0, z1), (x1, 1.0, z1), (x0, 1.0, z0)] + for tri in ((0, 1, 2), (0, 2, 3)): + T.append([len(V), len(V) + 1, len(V) + 2]) + V.extend(corners[k] for k in tri) + return np.array(V, dtype=float), np.array(T, dtype=np.int64) + + +@unittest.skipIf(np is None, "numpy is not installed") +class TopologyTests(unittest.TestCase): + def test_weld_joins_split_vertices_so_only_the_rim_is_open(self): + V, T = quad_strip(3) + _, TW = core.weld(V, T, 1e-6) + census = core.edge_census(TW) + self.assertEqual(census["boundaryEdges"], 8) # the rim of a 3 x 1 strip; unwelded, all 18 edges are open + self.assertEqual(census["nonManifoldEdges"], 0) + self.assertEqual(len(np.unique(core.triangle_components(TW))), 1) + + def test_three_triangles_on_one_edge_are_non_manifold(self): + V = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1]], dtype=float) + T = np.array([[0, 1, 2], [0, 1, 3], [0, 1, 4]]) + self.assertEqual(core.edge_census(T)["nonManifoldEdges"], 1) + report = core.audit(V, T, None) + self.assertEqual((report["nonManifoldEdges"], report["shells"], report["triangles"]), (1, 1, 3)) + + def test_separate_pieces_are_separate_shells(self): + V, T = quad_strip(2) + V2 = np.concatenate([V, V + [0, 5, 0]]) + T2 = np.concatenate([T, T + len(V)]) + report = core.audit(V2, T2, None) + self.assertEqual(report["shells"], 2) + self.assertEqual(report["shellTriangles"], [4, 4]) + + def test_components_follow_long_chains(self): + pairs = np.array([[i, i + 1] for i in range(999)]) + self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) + self.assertEqual(len(np.unique(core.components(1000, pairs[:500]))), 500) + + +@unittest.skipIf(np is None, "numpy is not installed") +class UvTests(unittest.TestCase): + SQUARE_V = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], dtype=float) + SQUARE_T = np.array([[0, 1, 2], [0, 2, 3]]) + SQUARE_UV = np.array([[[0, 0], [1, 0], [1, 1]], [[0, 0], [1, 1], [0, 1]]], dtype=float) + + def test_a_square_filling_the_texture_has_full_coverage_no_overlap_and_density_of_the_texture_size(self): + report = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV, texture_size=1024, raster=128) + self.assertAlmostEqual(report["uvCoverage"], 1.0, places=2) + self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) + self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + + def test_two_triangles_on_the_same_texels_overlap(self): + stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) + report = core.audit(self.SQUARE_V, self.SQUARE_T, stacked, texture_size=1024, raster=128) + self.assertGreater(report["uvOverlap"], 0.98) + + def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) + self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) + self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) + + def test_rasterize_gives_each_texel_its_triangle_and_weights(self): + owner, bary, cover = core.rasterize(self.SQUARE_UV, 8) + self.assertEqual(owner[0, 7], 0) # low v, high u: the first triangle + self.assertEqual(owner[7, 0], 1) + self.assertTrue(np.allclose(bary.sum(axis=2)[owner >= 0], 1.0, atol=1e-5)) + position = core.interpolate(owner, bary, self.SQUARE_V[self.SQUARE_T]) + self.assertTrue(np.allclose(position[2, 5, :2], [(5 + 0.5) / 8, (2 + 0.5) / 8], atol=1e-5)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class OrientTests(unittest.TestCase): + def test_principal_frame_puts_the_long_side_on_x_and_the_thin_side_on_z(self): + V, T = quad_strip(6) # 6 x 1 x 0 + turn = np.array([[0.36, 0.48, -0.8], [-0.8, 0.6, 0.0], [0.48, 0.64, 0.6]]) # a rotation + centre, R = core.principal_frame(V @ turn.T + [3, -2, 5], T) + local = (V @ turn.T + [3, -2, 5] - centre) @ R.T + extent = local.max(axis=0) - local.min(axis=0) + # the diagonal split of each quad skews the area-weighted axes by under a degree + self.assertTrue(np.allclose(extent, [6, 1, 0], atol=0.08)) + self.assertLess(extent[2], 1e-9) + self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + symmetric = np.concatenate([half, half * [-1, 1, 1]]) + lopsided = np.concatenate([half, half * [-0.3, 1, 1] - [0.4, 0, 0]]) + shipped, mutant = core.mirror_error(symmetric, 0), core.mirror_error(lopsided, 0) + # shipped 0.0 exactly (every mirrored sample is itself a point); the lopsided cloud reads 0.0426 + self.assertEqual(shipped, 0.0) + self.assertGreater(mutant, 0.0426 / 1.2) + + +@unittest.skipIf(np is None, "numpy is not installed") +class PartTests(unittest.TestCase): + def grown(self, crease_cost: float): + V, T = quad_strip(10, fold_after=7) + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + costs = core.crease_costs(V, T, pairs, crease_cost) + part, cost = core.grow_parts(len(T), pairs, costs, [(0, 0), (len(T) - 1, 1)]) + return part, cost + + def test_parts_stop_at_a_sharp_concave_crease(self): + part, _ = self.grown(40.0) + self.assertEqual(part.tolist(), [0] * 14 + [1] * 6) # the fold is after quad 7: 14 triangles before it + + def test_without_crease_cost_parts_split_by_distance_alone(self): + part, _ = self.grown(0.0) + self.assertEqual(part.tolist(), [0] * 10 + [1] * 10) + + def test_a_convex_fold_costs_nothing(self): + V, T = quad_strip(10, fold_after=7) + V[:, 2] *= -1 # the same strip folded down, normals unchanged: convex seen from the side they face + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + part, _ = core.grow_parts(len(T), pairs, core.crease_costs(V, T, pairs, 40.0), [(0, 0), (len(T) - 1, 1)]) + self.assertEqual(int((part == 0).sum()), 10) + + def test_a_bowl_of_gentle_folds_costs_far_less_than_one_sharp_crease_of_the_same_turn(self): + def crease_total(turns): # a strip of quads that turns upward by these degrees after each quad + V, T, x, z, heading = [], [], 0.0, 0.0, 0.0 + for turn in [0.0] + turns: + heading += math.radians(turn) + x1, z1 = x + math.cos(heading), z + math.sin(heading) + corners = [(x, 0.0, z), (x1, 0.0, z1), (x1, 1.0, z1), (x, 1.0, z)] + for tri in ((0, 1, 2), (0, 2, 3)): + T.append([len(V), len(V) + 1, len(V) + 2]) + V.extend(corners[k] for k in tri) + x, z = x1, z1 + V, T = np.array(V), np.array(T, dtype=np.int64) + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + return float((core.crease_costs(V, T, pairs, 1.0) - core.crease_costs(V, T, pairs, 0.0)).sum()) + + sharp, gentle = crease_total([90.0]), crease_total([10.0] * 9) + # shipped ratio 9.0 (the square: 0.5 ** 2 against 9 * (1 / 18) ** 2); a cost linear in the fold reads 1.0. Bound 3. + self.assertGreater(sharp / gentle, 3.0 * 1.2) + self.assertAlmostEqual(sharp, 0.25, places=9) + + def test_unseeded_shells_are_unreached_and_several_seeds_may_name_one_part(self): + V, T = quad_strip(2) + V2, T2 = np.concatenate([V, V + [0, 5, 0]]), np.concatenate([T, T + len(V)]) + _, TW = core.weld(V2, T2, 1e-6) + pairs = core.face_adjacency(TW) + part, cost = core.grow_parts(len(T2), pairs, core.crease_costs(V2, T2, pairs, 1.0), [(0, 0), (3, 0)]) + self.assertEqual(part.tolist(), [0, 0, 0, 0, -1, -1, -1, -1]) + self.assertTrue(np.isinf(cost[4:]).all()) + + def test_seed_text(self): + self.assertEqual(core.parse_seeds("hull=0,0,0; pod 1=1,-2.5,3e-1;"), [("hull", (0.0, 0.0, 0.0)), ("pod 1", (1.0, -2.5, 0.3))]) + for bad in ("", "hull", "hull=1,2", "=1,2,3", "hull=a,b,c"): + with self.assertRaises(ValueError): + core.parse_seeds(bad) + + +@unittest.skipIf(np is None, "numpy is not installed") +class DelightTests(unittest.TestCase): + """A synthetic bake: 40000 surface samples, pale paint with a tenth of it dark machinery (same hue), lit by + a sky brighter above than below and dimmed by occlusion.""" + + def setUp(self): + rng = np.random.default_rng(7) + count = 40000 + normals = rng.normal(size=(count, 3)) + self.normals = normals / np.linalg.norm(normals, axis=1, keepdims=True) + self.occlusion = rng.uniform(0.1, 1.0, count) + self.light = (0.55 + 0.45 * self.normals[:, 2]) * self.occlusion ** 0.7 + 0.05 + self.paint = np.where(rng.random(count) < 0.1, 0.08, 0.8) + self.rgb = (self.paint * self.light)[:, None] * np.array([1.0, 0.97, 0.9]) + self.basis = core.shading_basis(self.normals, self.occlusion) + self.log_l = np.log(core.luminance(self.rgb) + 1e-4) + self.clusters = core.chroma_clusters(self.rgb, 1) + + def delit(self, weights): + gain = core.delight_gain(self.basis, weights, 1.0, 8.0) + return np.log(core.luminance(self.rgb * gain[:, None]) + 1e-4) + + def test_the_fit_finds_the_light_and_dividing_it_out_levels_up_and_down(self): + weights, explained = core.fit_shading(self.log_l, self.basis, self.clusters) + before = core.lighting_signature(self.log_l, self.normals, self.occlusion) + after = core.lighting_signature(self.delit(weights), self.normals, self.occlusion) + self.assertGreater(explained, 0.2) + # up/down ratio: shipped 1.029; with no correction (a gain of 1) 3.323. Bound sqrt(1.029 * 3.323) = 1.849. + self.assertGreater(before["upDownLuminanceRatio"], 1.849 * 1.2) + self.assertLess(after["upDownLuminanceRatio"], 1.849 / 1.2) + # occlusion correlation: shipped 0.0032; uncorrected 0.356. Bound sqrt(0.0032 * 0.356) = 0.0337. + self.assertGreater(before["occlusionCorrelation"], 0.0337 * 1.2) + self.assertLess(abs(after["occlusionCorrelation"]), 0.0337 / 1.2) + + def test_dark_paint_in_crevices_is_not_read_as_shadow(self): + # All the dark machinery sits in the occluded third. A mean fit (expectile 0.5) reads it as shadow and + # overstates the occlusion weight; the envelope fit follows the pale paint. + crevice = self.occlusion < 0.4 + paint = np.where(crevice & (np.random.default_rng(3).random(len(crevice)) < 0.6), 0.08, 0.8) + rgb = (paint * self.light)[:, None] * np.array([1.0, 0.97, 0.9]) + log_l = np.log(core.luminance(rgb) + 1e-4) + true_weight = 0.7 # light ~ occlusion ** 0.7, up to the small ambient floor + envelope, _ = core.fit_shading(log_l, self.basis, self.clusters) + mean, _ = core.fit_shading(log_l, self.basis, self.clusters, expectile=0.5) + # occlusion weight: shipped 0.921, mean-fit mutant 1.502. Bound sqrt(0.921 * 1.502) = 1.176. + self.assertLess(envelope[-1], 1.176 / 1.2) + self.assertGreater(mean[-1], 1.176 * 1.2) + self.assertGreater(envelope[-1], true_weight * 0.8) + + def test_gain_leaves_the_lit_side_alone_and_respects_the_limit(self): + weights, _ = core.fit_shading(self.log_l, self.basis, self.clusters) + gain = core.delight_gain(self.basis, weights, 1.0, 3.0) + self.assertLessEqual(float(gain.max()), 3.0) + self.assertGreaterEqual(float(gain.min()), 1 / 3.0 - 1e-12) + light = self.basis @ weights + reference = np.abs(light - np.percentile(light, 90)) < 0.01 # the surface the light favoured + self.assertTrue(np.allclose(gain[reference], 1.0, atol=0.011)) + self.assertGreater(float(np.median(gain[self.occlusion < 0.3])), 1.5) # shaded surface is raised + self.assertTrue(np.allclose(core.delight_gain(self.basis, weights, 0.0, 3.0), 1.0)) + + def test_flat_paint_shows_no_light(self): + flat = np.tile([0.5, 0.4, 0.3], (len(self.normals), 1)) * np.random.default_rng(5).uniform(0.9, 1.1, (len(self.normals), 1)) + _, explained = core.fit_shading(np.log(core.luminance(flat)), self.basis, core.chroma_clusters(flat, 1)) + self.assertLess(explained, 0.01) + + def test_chroma_clusters_ignore_brightness(self): + teal, yellow = np.array([0.1, 0.4, 0.45]), np.array([0.8, 0.7, 0.1]) + shade = np.random.default_rng(2).uniform(0.1, 1.0, (200, 1)) + labels = core.chroma_clusters(np.concatenate([teal * shade, yellow * shade]), 2) + self.assertEqual(len(set(labels[:200])), 1) + self.assertEqual(len(set(labels[200:])), 1) + self.assertNotEqual(labels[0], labels[200]) + + def test_srgb_round_trip(self): + values = np.linspace(0, 1, 101) + self.assertTrue(np.allclose(core.linear_to_srgb(core.srgb_to_linear(values)), values, atol=1e-6)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class TextureFillTests(unittest.TestCase): + def test_push_pull_fills_a_hole_from_its_surroundings_and_keeps_known_texels(self): + image = np.zeros((32, 32, 3), dtype=np.float32) + image[:, :16] = [0.2, 0.4, 0.6] + image[:, 16:] = [0.6, 0.4, 0.2] + known = np.ones((32, 32), dtype=bool) + known[10:20, 2:10] = False + holed = image.copy() + holed[~known] = 9.0 + filled = core.push_pull(holed, known) + self.assertTrue(np.array_equal(filled[known], image[known])) + self.assertTrue(np.allclose(filled[12:18, 3:8], [0.2, 0.4, 0.6], atol=0.05)) + + def test_push_pull_without_a_hole_or_without_anything_known_returns_the_image(self): + image = np.random.default_rng(0).random((8, 8, 3)).astype(np.float32) + self.assertTrue(np.array_equal(core.push_pull(image, np.ones((8, 8), dtype=bool)), image)) + self.assertTrue(np.array_equal(core.push_pull(image, np.zeros((8, 8), dtype=bool)), image)) + + def test_marking_mask_takes_the_ink_and_leaves_the_panel(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) + panel[18:22, 8:30] = [0.85, 0.75, 0.2] # a stroke of yellow lettering + region = np.zeros((40, 40), dtype=bool) + region[5:35, 5:35] = True + mask = core.marking_mask(panel, region, 0.25, 1) + self.assertTrue(mask[18:22, 8:30].all()) + self.assertEqual(int(mask.sum()), 4 * 22 + 2 * 22 + 2 * 4) # the stroke grown by one texel edgewise, nothing else + outside = np.zeros((40, 40), dtype=bool) + self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): + flat = np.full((9, 9), 0.5) + self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) + point = np.zeros((9, 9)) + point[4, 4] = 1.0 + blurred = core.box_blur(point, 1) + self.assertTrue(np.allclose(blurred[3:6, 3:6], 1 / 9)) + self.assertAlmostEqual(float(blurred.sum()), 1.0, places=9) + + +class HostFileTests(unittest.TestCase): + """brokkr_actions.json is the add-on's whole contract with Brokkr: it must pass Brokkr's own checker.""" + + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_mesh_polish" / "brokkr_actions.json").read_text(encoding="utf-8")) + + def test_brokkr_admits_the_file(self): + at.check_host(self.document, at.table()["charsets"]) + + def test_every_row_names_an_operator_and_property_the_add_on_defines(self): + source = (SURFACE / "brokkr_mesh_polish" / "__init__.py").read_text(encoding="utf-8") + for row in self.document["actions"]: + self.assertIn(f'bl_idname = "{row["name"]}"', source) + self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") + body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] + for field in row["fields"]: + self.assertIn(f" {field['name']}: bpy.props.", body, f"{row['name']}.{field['name']}") + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + host = [{**row, "host": "brokkr_mesh_polish"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + admitted = at.validate({**envelope, "action": "brokkr_mesh_polish.delight", "object_name": "Hull"}, host) + self.assertEqual(admitted["object_name"], "Hull") + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_mesh_polish.delight", "object_name": "Hull", "max_gain": 9}, host) + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required + + +class TurntableRecipeTests(unittest.TestCase): + def test_every_pose_looks_at_the_origin_with_z_up(self): + for azimuth in (0, 45, 90, 200, 315): + for elevation in (-90, -30, 0, 25, 90): + location, (rx, _, rz) = turntable.camera_pose(azimuth, elevation, 5.0) + forward = (-math.sin(rx) * math.sin(rz), math.sin(rx) * math.cos(rz), -math.cos(rx)) # camera -Z after XYZ Euler (rx, 0, rz) + for axis in range(3): + self.assertAlmostEqual(forward[axis], -location[axis] / 5.0, places=9) + + def test_every_intent_of_a_recipe_is_admitted_by_the_action_table(self): + for look in ("lit", "flat"): + recipe = turntable.recipe("ship.blend", "out", "ship", 0.7, 8, 25.0, 512, "BLENDER_EEVEE", look, "nibu/hands") + renders = [i for i in recipe["intents"] if i["action"] == "renderStill"] + self.assertEqual(len(renders), 10) # eight around, top, bottom + self.assertEqual(len({i["outputPath"] for i in renders}), 10) + for index, intent in enumerate(recipe["intents"]): + at.validate({"schema": "brokkr.blender.command_intent.v0", "commandId": f"t-{index}", + "requestedBy": recipe["requestedBy"], **intent}, []) + + def test_two_recipes_with_the_same_numbers_frame_identically(self): + a = turntable.recipe("a.blend", "out", "a", 0.7, 4, 25.0, 512, "CYCLES", "lit", "nibu/hands") + b = turntable.recipe("b.blend", "out", "b", 0.7, 4, 25.0, 512, "CYCLES", "lit", "nibu/hands") + moves = lambda r: [i for i in r["intents"] if i["action"] in ("setObjectTransform", "setCamera")] + self.assertEqual(moves(a), moves(b)) + + +if __name__ == "__main__": + unittest.main() -- 2.47.3 From 0921bec89babe7ebb75e10ebf3235130b890a05b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:05 +0100 Subject: [PATCH 3/6] docs: mesh polish actions, the headless intent runner and the turntable recipe Co-Authored-By: Claude Fable 5.2 --- README.md | 3 + surfaces/blender/docs/install.md | 3 + surfaces/blender/docs/mesh-polish.md | 172 +++++++++++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 surfaces/blender/docs/mesh-polish.md diff --git a/README.md b/README.md index e0be8d0..90f7c57 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,9 @@ broker. - `surfaces/blender/brokkr_bridge`: Blender add-on target backed by CultLib's Python CultMesh node/server, with an optional debug export probes. +- `surfaces/blender/brokkr_mesh_polish`: Blender host add-on that measures and polishes generated meshes + (audit, repair, orient, delight, scrub markings, cut parts), agent-callable through Brokkr's host actions; + `surfaces/blender/tools` runs intent recipes in a background Blender (`surfaces/blender/docs/mesh-polish.md`). - `brokkr-command`: .NET CLI that writes one Unity command intent through the project's directory store and reports the editor's receipt (`docs/provider-contract.md`). - `brokkr-daemon`: Rust CLI that emits Brokkr's provider advertisement and diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 9ef449e..2659f4d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -290,6 +290,9 @@ with nothing pushed; an argument Blender will not convert, or an `ERROR` report agent turn clears that WindowManager property before the call and copies it, up to 16000 characters and then `[truncated]`, into the receipt's `hostResult` (empty for every other action). +`surfaces/blender/brokkr_mesh_polish` is a host add-on that ships with Brokkr (`mesh-polish.md`), and +`surfaces/blender/tools/run_intents.py` runs a list of intents, host rows included, in a background Blender. + The admitted rows are published in the host snapshot as `hostActions` (each with its `host` module). `brokkr-ctl blender send --help --store ` lists them after the built-ins, `send` refuses an intent they refuse before writing anything, and the add-on still decides. Human-only is absence: an operator only a diff --git a/surfaces/blender/docs/mesh-polish.md b/surfaces/blender/docs/mesh-polish.md new file mode 100644 index 0000000..93b8fac --- /dev/null +++ b/surfaces/blender/docs/mesh-polish.md @@ -0,0 +1,172 @@ +# Mesh polish for generated meshes + +`surfaces/blender/brokkr_mesh_polish` is a Blender add-on that measures and polishes meshes made by image-to-3D +generators (Tripo and its kin): one fused or many-shelled skin, vertices split at every UV seam, an arbitrary +orientation, a unit-cube scale, and a base colour texture with the concept render's lighting and lettering baked in. + +It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"): it imports nothing from Brokkr, and +`brokkr_actions.json` beside its `__init__.py` lists the operators agents may run. Every field, type, bound and +default is in that file; `brokkr-ctl blender send --help --store ` prints it for a live session. The +arithmetic is `core.py` (numpy only) and is tested without Blender. + +Every action writes a JSON report, returned in the receipt's `hostResult`. Actions that change the scene are one +undo step each. Lengths are in scene units; points and directions are world-space. + +## Running it + +In a person's Blender: enable the add-on beside Brokkr and press `Reload Host Actions` in the Brokkr panel; the +actions then arrive as intents like any other. + +With no Blender open, `surfaces/blender/tools/run_intents.py` runs a recipe (a JSON list of intents) in a +background Blender through the same agent turn, and writes the receipts to a file: + +```text +blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- polish.json +``` + +```json +{"requestedBy": "nibu/hands", "importDir": "work", "outputDir": "work", "hostAddons": ["brokkr_mesh_polish"], + "saveBlend": "work/ship.blend", + "intents": [ + {"action": "importGltf", "filepath": "ship_tripo.glb"}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "brokkr_mesh_polish.orient", "roll_quarter_turns": 2}, + {"action": "brokkr_mesh_polish.repair", "object_name": "tripo_ab12"}, + {"action": "brokkr_mesh_polish.delight", "object_name": "tripo_ab12", "clusters": 2}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "exportGltf", "filepath": "ship_polished.glb"}]} +``` + +The runner opens no CultMesh node: receipts go to `.receipts.json` only. It is the human of its own +Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`), and it refuses to +start without private `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS`. Its exit status is +0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. + +`surfaces/blender/tools/turntable_recipe.py` writes a recipe of Brokkr's own scene actions (`setWorld`, +`createObject`, `setCamera`, `setObjectTransform`, `renderStill`) for an orthographic turntable of a `.blend` whose +subject is centred on the origin. Two recipes with the same numbers frame two files identically, so a before and +an after compare view by view. `--look flat` lights with a uniform white world alone and shows the texture as +stored, baked shadows included; `--look lit` adds a sun. + +A polish pass that works, in order: `audit`, `orient` (render a flat turntable and pick `roll_quarter_turns` and +`flip_forward` by eye), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then +`pick` and `cut_parts` when parts must move, `audit` again, `exportGltf`. + +## Actions + +### audit + +Measures one mesh object, or every mesh in the scene. Changes nothing. Topology is counted after welding positions +within 1e-5 of the bounding diagonal, because an imported mesh is split at every UV seam and would otherwise read +as all open edges. + +- `triangles`, `vertices`, `weldedVertices`, `extent`, `surfaceArea`, `degenerateTriangles`. +- `boundaryEdges` (one triangle on the edge: an open rim), `nonManifoldEdges` (three or more), `shells` and + the triangle count of the largest twelve. +- `uvIslands`, `uvFlippedTriangles` (mirrored in UV space), `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, + `uvCoverage` (share of the texture some triangle covers) and `uvOverlap` (share of covered texels that more + than one triangle covers), both counted at texel centres on a `raster` x `raster` grid. +- `texelDensityMedian`, `P5`, `P95` (texels per unit length for the base colour texture's size, area-weighted) and + `texelDensitySpread` (P95 / P5; 1 is uniform). +- `baseColorImage`, `baseColorSize`, `customNormals`. + +### repair + +Welds coincident vertices (UVs live on face corners, so seams keep their UVs), removes degenerate faces and loose +edges and vertices, optionally deletes shells below `min_shell_area` of the surface, optionally closes holes of up +to `fill_holes_sides` edges, and makes face normals consistent. With `sharp_angle` above 0 the generator's custom +normals are dropped and shading is recomputed: smooth, hard across edges sharper than the angle. + +A filled hole has no place in the UV map: each new face takes one UV point from the old face beside it, so it shows +that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`). Making normals consistent flips the +winding of shells that faced inward, which mirrors their UVs; `uvFlippedTriangles` can rise. + +Welding does not join shells that merely touch or intersect. A mesh assembled from open, interpenetrating shells +stays one: its open edges and non-manifold edges are reported, not repaired. Closing such a mesh means remeshing it +and rebaking its texture, which this add-on does not do. + +### orient + +Turns every mesh in the scene, as one rigid body, onto its area-weighted principal axes: longest on Y, shortest on +Z, centred on the origin, the longest side scaled to `length` when given. The transform is baked into the mesh data +and the objects are left unparented at identity. Principal axes do not know bow from stern or up from down: +`flip_forward` and `roll_quarter_turns` choose, and `mirrorError` in the report (per axis, 0 is a perfect mirror) +says which plane the body is symmetric across. `principal: false` keeps the current axes and applies only the +turns, the centring and the scale. + +### delight + +Undoes lighting baked into the base colour texture, as far as the surface's own shape explains it. + +For each texel the add-on knows the surface normal and the ambient occlusion there (cosine-weighted rays against +the mesh, per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints +the texture holds) plus a light term: the order-2 spherical harmonics of the normal and the log of occlusion. The +fit follows the upper envelope of luminance (an expectile regression at 0.85), because within one hue the +brightest paint at a given normal and occlusion shows how much light the bake put there, while darker paint in the +same place, machinery in a crevice of a pale hull, is paint. Texels darker than 4% of the texture's white point are +left out of the fit: they are fill the generator never saw. Each texel is then multiplied by the factor that undoes +the fitted light, relative to the surface the light favoured (the 90th percentile), limited to `max_gain` either +way. The result is a new packed image (`.delit`) swapped into the material; nothing is written to disk. + +The report: `explainedByLight` (share of within-hue luminance variance the light term explains, before and +after), and two model-free readings before and after, over the texels that were judged: +`upDownLuminanceRatio` (up-facing over down-facing surface, 1 is none) and `occlusionCorrelation`. `gain.clamped` +is the share of texels that hit `max_gain`. + +What it cannot do. It removes smooth, shape-following light: sky-over-ground gradients and occlusion darkening. +It does not remove cast shadows, specular highlights, or light the shape does not explain. It cannot tell dark +paint from shadow where a hue has no bright paint at all in some range of occlusion. Texels the generator filled +with black stay black: there is no colour there to recover. It raises shaded paint by gain, so 8-bit noise and +JPEG blocks in dark areas are raised with it. + +### pick + +The surface point seen at `(u, v)` of a camera's frame (`u` across, `v` up, both 0 to 1), with the object and +normal there. `resolution_x` and `resolution_y` are the size of the picture the place was read from, since the +frame's shape follows the picture's. Changes nothing. It turns "the lettering at this place in this render" into a +point that `scrub_markings` or `cut_parts` can take. + +### scrub_markings + +Paints out markings on the base colour texture inside a world-space sphere. Texels of the object's surface inside +the sphere whose colour is further than `tolerance` from the sphere's median colour are the marking; the mask is +widened by `grow` texels, filled with a smooth blend of the unmasked texels of the same region (push-pull), and +given the surrounding texture's grain. The result is a new packed image (`.scrubbed`); successive scrubs +keep one image, not a chain. + +The median colour must be the panel, not the marking: keep the sphere wide enough that lettering is the minority. +Panel lines, rivets and rust inside the sphere that differ from the panel by more than `tolerance` go with the +lettering. The fill is a blend, not a reconstruction: a faint ghost of the removed strokes can remain where the +unmasked source was thin. + +### cut_parts + +Cuts one fused skin into named parts and makes each a separate object that can move. + +`seeds` is `name=x,y,z; name=x,y,z; ...`: points on the surface, several per name allowed; the first name is the +body. Every triangle joins the seed it is cheapest to walk to, where a step costs its length (as a share of the +bounding diagonal) plus `crease_cost` times the square of how concave the fold it crosses is. Parts therefore stop +at sharp concave creases, where one part of a fused skin meets another, and split by distance where there is no +crease. `through` above 0 also seeds the far face of each part off the body, found by a ray inward from each seed +no longer than that share of the diagonal: a thin shell (a petal, a fin) is then held from both faces. + +The mesh is welded and triangulated first. Each part becomes an object `.`; both sides of every cut +are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); each part off +the body gets its origin at the centre of its cut and is parented to the body without moving; custom properties +`polish_cut_normal` and `polish_cut_radius` record the cut's plane and mean radius. `joint_scale` above 0 adds a +ball of that share of the cut radius at each root, parented to the body. The original object is removed. + +The report gives each part's `triangles`, `capTriangles`, `cutEdges`, `root`, `cutNormal` and `cutRadius`. + +What it cannot do. Seeds decide the parts; a seed on the wrong surface gives a wrong part. Place them from a +render with `pick`, then check where they landed before cutting (a small cube at each seed, rendered, is enough). +Cuts follow triangle edges, so on a coarse mesh they are ragged. Caps are fans across the cut and can fold over on a +cut that is far from planar; they are meant to be hidden by the neighbouring part, not shown. The root is the +centre of the cut, not a designed hinge: it is a sensible pivot to start from. + +## Tests + +- `tests/test_mesh_polish.py`: the arithmetic on hand-built meshes and textures, `brokkr_actions.json` against + Brokkr's own host-file checker, and the turntable recipe against the action table. No Blender; needs numpy. +- `tests/live/mesh_polish.py`: every action through `run_intent` in a background Blender against real bpy + (`mesh_polish.result.json` is the last run, Blender 5.3.0). -- 2.47.3 From 64ffc14e0abe72c039ba99e57738a1bc06a4e0f1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH 4/6] run_intents: refuse Blender user directories that are a person's own, or that Blender is not using The guard only checked that the three variables were non-empty. tools/private_dirs.py now refuses a variable set inside %APPDATA%/Blender Foundation, ~/.config/blender or the macOS folder, and a Blender whose own answer for CONFIG, EXTENSIONS or SCRIPTS is not under the variable. (Soul finding run-intents-guard-checks-non-empty, PR 22.) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tools/private_dirs.py | 44 ++++++++++++++++++++++++++ surfaces/blender/tools/run_intents.py | 12 ++++--- 2 files changed, 51 insertions(+), 5 deletions(-) create mode 100644 surfaces/blender/tools/private_dirs.py diff --git a/surfaces/blender/tools/private_dirs.py b/surfaces/blender/tools/private_dirs.py new file mode 100644 index 0000000..014ef78 --- /dev/null +++ b/surfaces/blender/tools/private_dirs.py @@ -0,0 +1,44 @@ +"""Whether a Blender about to be driven by a script has user directories of its own. Stdlib only. + +A script that enables add-ons or saves preferences in a person's own Blender folders changes her Blender. The +three variables below point Blender at other folders; BLENDER_USER_RESOURCE_PATH does not (Blender 5.3 ignores it). +""" +from __future__ import annotations + +import os +from pathlib import Path +from typing import Callable, Mapping + +VARIABLES = {"BLENDER_USER_CONFIG": "CONFIG", "BLENDER_USER_EXTENSIONS": "EXTENSIONS", "BLENDER_USER_SCRIPTS": "SCRIPTS"} + + +def own_blender_roots(environ: Mapping[str, str], home: str) -> list[Path]: + """Where a person's own Blender keeps its folders on Windows, Linux and macOS, for this environment.""" + roots = [Path(home) / ".config" / "blender", Path(home) / "Library" / "Application Support" / "Blender"] + for variable in ("APPDATA", "XDG_CONFIG_HOME"): + if environ.get(variable): + roots.append(Path(environ[variable]) / ("Blender Foundation" if variable == "APPDATA" else "blender")) + return roots + + +def _inside(path: Path, root: Path) -> bool: + a, b = os.path.normcase(os.path.abspath(path)), os.path.normcase(os.path.abspath(root)) + return a == b or a.startswith(b + os.sep) + + +def refusal(environ: Mapping[str, str], home: str, resource: Callable[[str], str] | None = None) -> str | None: + """None when the three variables are set to folders outside every own-Blender root, and, given Blender's + own answer (resource('CONFIG') and so on, bpy.utils.user_resource), Blender is really using them; otherwise + the sentence to refuse with.""" + for variable, kind in VARIABLES.items(): + value = environ.get(variable) + if not value: + return f"{variable} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories" + for root in own_blender_roots(environ, home): + if _inside(Path(value), root): + return f"{variable} is {value}, inside a person's own Blender folder ({root}): point it at a scratch directory" + if resource is not None: + used = resource(kind) + if not used or not _inside(Path(used), Path(value)): + return f"Blender uses {used or 'no folder'} for {kind}, not {variable} ({value}): refusing to touch it" + return None diff --git a/surfaces/blender/tools/run_intents.py b/surfaces/blender/tools/run_intents.py index 9c06c01..eb09a64 100644 --- a/surfaces/blender/tools/run_intents.py +++ b/surfaces/blender/tools/run_intents.py @@ -8,8 +8,8 @@ rows are checked as in a live session, and each gets a receipt. No CultMesh node written to (default: the recipe's name with .receipts.json) and nowhere else, so nothing here shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless -BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a -person's own Blender folders (docs/install.md). +BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set to folders outside a person's own +Blender folders and Blender is really using them (tools/private_dirs.py), so it never reads or writes hers. The recipe: @@ -41,9 +41,11 @@ def fail(message: str) -> None: def main() -> int: - for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(name): - fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import private_dirs + refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) + if refused: + fail(refused) arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] if not arguments: fail("usage: blender --background --factory-startup --python run_intents.py -- []") -- 2.47.3 From 7de1e25e609f2ad41fae577cae33cdb7f229c93b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH 5/6] brokkr_mesh_polish: repair and cut_parts turn no face; orient keeps the hierarchy; the tests pin the operators Soul falsified PR 22: repair's unconditional recalc_face_normals reversed 4,565 of 23,341 and 15,735 of 28,426 triangles on two further Tripo hulls, which a single-sided material culls. repair now leaves every winding alone; recalc_normals is opt-in and reports windingFlipped. cut_parts no longer recalculates either. Custom shading normals are carried through weld, fill and cut as plain directions and set back, new faces are shaded by their own direction, and delight reads those shading normals instead of winding-derived ones. audit: windingAgainstNormals, and uvMirroredTriangles (texture parity against the shading normals) in place of uvFlippedTriangles, which changed whenever a winding did. orient: object_name scopes it to a root and its descendants; parents and pivots are kept. cut_parts: a mesh with no material keeps a bare first slot, so only caps take the cap material. Tests: 13 more unit tests and 18 more live checks (43 with BROKKR_POLISH_HULLS). The live sphere is now torn, half inside out under outward custom normals. Soul's 26 mutants and 11 of this batch's own all die. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 148 ++++- .../brokkr_mesh_polish/brokkr_actions.json | 6 +- surfaces/blender/brokkr_mesh_polish/core.py | 20 +- surfaces/blender/tests/live/mesh_polish.py | 259 +++++++- .../tests/live/mesh_polish.result.json | 585 ++++++++++++++++-- surfaces/blender/tests/test_mesh_polish.py | 115 +++- 6 files changed, 1017 insertions(+), 116 deletions(-) diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index af1916c..473550d 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -45,15 +45,17 @@ def mesh_objects(name: str) -> list: def arrays(obj) -> dict: - """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), - polygon (the polygon each triangle came from).""" + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), CN (per corner, the + normals the mesh is shaded with: its custom normals when it has them), N (per vertex, the mean of its + corners' CN) and polygon (the polygon each triangle came from). The normals never come from the winding + alone when the mesh carries custom normals, so a shell wound inside out still reads as it is drawn.""" mesh = obj.data mesh.calc_loop_triangles() count = len(mesh.loop_triangles) V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) mesh.vertices.foreach_get("co", V) - N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) - mesh.vertex_normals.foreach_get("vector", N) + corner = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", corner) T = np.empty(count * 3, dtype=np.int32) mesh.loop_triangles.foreach_get("vertices", T) L = np.empty(count * 3, dtype=np.int32) @@ -62,14 +64,18 @@ def arrays(obj) -> dict: mesh.loop_triangles.foreach_get("polygon_index", P) world = np.array(obj.matrix_world, dtype=np.float64) V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] - N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner = corner.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner /= np.maximum(np.linalg.norm(corner, axis=1, keepdims=True), 1e-30) + CN = corner[L.reshape(-1, 3)] + N = np.zeros((len(V), 3)) + np.add.at(N, T.reshape(-1), CN.reshape(-1, 3)) N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) UV = None if mesh.uv_layers.active is not None: flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) mesh.uv_layers.active.uv.foreach_get("vector", flat) UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] - return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "CN": CN, "polygon": P} def merged(objects: list) -> dict: @@ -78,6 +84,7 @@ def merged(objects: list) -> dict: offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "CN": np.concatenate([p["CN"] for p in parts]), "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} @@ -198,7 +205,14 @@ def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: def pin_uvs(bm, faces) -> None: """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, - and corners copied from several islands would smear the atlas across it and overlap everything.""" + and corners copied from several islands would smear the atlas across it and overlap everything. The fill + also copies its neighbours' stashed shading normals onto the new corners; those are cleared, so the new + face is shaded by its own direction.""" + kept = bm.loops.layers.float_vector.get(KEPT_NORMAL) + if kept is not None: + for face in faces: + for loop in face.loops: + loop[kept] = (0.0, 0.0, 0.0) layer = bm.loops.layers.uv.active if layer is None: return @@ -218,6 +232,41 @@ def pin_uvs(bm, faces) -> None: loop[layer].uv = anchor +KEPT_NORMAL = "polish_kept_normal" + + +def stash_normals(mesh, bm) -> bool: + """Copy the mesh's custom shading normals onto the bmesh's face corners, as plain vectors, so they survive + edits. Blender stores a custom normal against the automatic normal of its corner; welding or cutting + changes the automatic normals, and the stored ones would then be read as different directions.""" + if "custom_normal" not in mesh.attributes: + return False + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + normals = flat.reshape(-1, 3) + layer = bm.loops.layers.float_vector.new(KEPT_NORMAL) + for face in bm.faces: + for loop in face.loops: + loop[layer] = normals[loop.index] + return True + + +def restore_normals(mesh, keep: bool = True) -> None: + """Set the stashed vectors back as the mesh's custom normals (a new face's zero vector means automatic), + or with keep False only drop the stash.""" + attribute = mesh.attributes.get(KEPT_NORMAL) + if attribute is None: + return + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + attribute.data.foreach_get("vector", flat) + mesh.attributes.remove(attribute) + if keep: + stale = mesh.attributes.get("custom_normal") + if stale is not None: # else a zero vector would keep the stale value instead of meaning automatic + mesh.attributes.remove(stale) + mesh.normals_split_custom_set(flat.reshape(-1, 3).tolist()) + + def cap_surface(): """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" material = bpy.data.materials.get(CAP_MATERIAL) @@ -261,7 +310,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): data = arrays(obj) nodes = base_color_nodes(obj) size = max(nodes[0].image.size) if nodes else 0 - entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster, CN=data["CN"]) entry["baseColorImage"] = nodes[0].image.name if nodes else "" entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] entry["customNormals"] = "custom_normal" in obj.data.attributes @@ -271,7 +320,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): class BROKKR_MESH_POLISH_OT_repair(PolishOperator): """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells - below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + below an area share, close small holes; on request rewind faces outward or recompute shading from a sharp angle""" bl_idname = "brokkr_mesh_polish.repair" bl_label = "Repair Mesh" object_name: bpy.props.StringProperty(name="Object") @@ -281,20 +330,26 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): description="Delete shells holding less than this share of the surface; 0 keeps all") fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, description="Close holes of up to this many edges; 0 leaves holes") + recalc_normals: bpy.props.BoolProperty(name="Recalculate Normals", default=False, + description="Rewind each shell so Blender judges it to face outward. Off leaves every face's winding as it is. On an open or intersecting shell the judgement can be wrong, and a face it turns is culled by a single-sided material: read windingFlipped in the report") sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") def work(self, context): obj = mesh_object(self.object_name) mesh = obj.data - before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + start = arrays(obj) + before = core.audit(start["V"], start["T"], None, CN=start["CN"]) bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length counts = {"vertices": len(bm.verts)} + faces = len(bm.faces) if self.weld_fraction > 0: bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) counts["welded"] = counts.pop("vertices") - len(bm.verts) + counts["facesCollapsedByWeld"] = faces - len(bm.faces) faces = len(bm.faces) bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) counts["degenerateFacesRemoved"] = faces - len(bm.faces) @@ -323,26 +378,39 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): counts["holesFilled"] = len(filled["faces"]) pin_uvs(bm, filled["faces"]) bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) - bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + counts["windingFlipped"] = 0 + if self.recalc_normals: + was = [face.normal.copy() for face in bm.faces] + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.normal_update() + counts["windingFlipped"] = sum(1 for face, normal in zip(bm.faces, was) if face.normal.dot(normal) < 0) bm.to_mesh(mesh) bm.free() + # Custom normals are stored against each face's own normal: a face that was turned would carry its + # custom normal turned with it, so they cannot outlive a rewind. + drop_custom = self.sharp_angle > 0 or counts["windingFlipped"] > 0 + counts["customNormalsDropped"] = bool(drop_custom and "custom_normal" in mesh.attributes) + if drop_custom and "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + restore_normals(mesh, keep=not drop_custom) if self.sharp_angle > 0: - if "custom_normal" in mesh.attributes: - mesh.attributes.remove(mesh.attributes["custom_normal"]) mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) mesh.update() - after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + end = arrays(obj) + after = core.audit(end["V"], end["T"], None, CN=end["CN"]) + keys = ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells", "windingAgainstNormals") return {"object": obj.name, "changes": counts, - "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, - "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + "before": {k: before[k] for k in keys}, "after": {k: after[k] for k in keys}} class BROKKR_MESH_POLISH_OT_orient(PolishOperator): - """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), - centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + """Turn an object and everything parented under it (or the whole scene), as one rigid body, onto its + principal axes (longest on Y, shortest on Z), centre it at the origin and scale its longest side to a length. + Rotation and scale are baked into the mesh data; every object keeps its parent and its pivot point""" bl_idname = "brokkr_mesh_polish.orient" bl_label = "Orient Meshes" + object_name: bpy.props.StringProperty(name="Object", description="The root of what to turn: it and its descendants; every object in the scene when empty") length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, description="Longest side after scaling, in scene units; 0 keeps the size") flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") @@ -352,7 +420,17 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): description="Off keeps the current axes and only applies the turns, centre and scale") def work(self, context): - objects = mesh_objects("") + if self.object_name: + top = bpy.data.objects.get(self.object_name) + if top is None: + raise Refused(f"No object named {self.object_name!r}.") + members = [top] + list(top.children_recursive) + else: + members = list(context.scene.objects) + objects = [o for o in members if o.type == "MESH"] + if not objects: + raise Refused("There is no mesh to orient.") + context.view_layer.update() data = merged(objects) centre, rotation = core.principal_frame(data["V"], data["T"]) if self.principal: @@ -371,15 +449,20 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): middle = (low + high) / 2.0 frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) - originals = {o.name: frame @ o.matrix_world for o in objects} - for obj in objects: - if obj.data.users > 1: - obj.data = obj.data.copy() - obj.data.transform(originals[obj.name]) - obj.data.update() - for obj in objects: - obj.parent = None - obj.matrix_world = Matrix.Identity(4) + def depth(obj): + return 0 if obj.parent is None else 1 + depth(obj.parent) + + world = {o.name: o.matrix_world.copy() for o in members} + for obj in sorted(members, key=depth): # parents first: a child's new place is set against its parent's + target = frame @ world[obj.name] + pivot = Matrix.Translation(target.translation) + if obj.type == "MESH": + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(pivot.inverted() @ target) + obj.data.update() + obj.matrix_world = pivot if obj.type in ("MESH", "EMPTY") else target + context.view_layer.update() final = (local - middle) * scale return {"objects": [o.name for o in objects], "scale": scale, "extent": [round(float(x), 6) for x in (high - low) * scale], @@ -413,7 +496,7 @@ class BROKKR_MESH_POLISH_OT_delight(PolishOperator): covered = owner >= 0 if covered.sum() < 64: raise Refused("The UV map covers too little of the texture to fit lighting.") - normals = core.interpolate(owner, bary, N[T])[covered] + normals = core.interpolate(owner, bary, data["CN"])[covered] normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] pixels = read_pixels(image) @@ -536,6 +619,7 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): world = obj.matrix_world.copy() bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) @@ -568,8 +652,8 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for edge in bm.edges: edge[was_open] = int(edge.is_boundary) cap_material = cap_surface() - cap_slot = len(mesh.materials) - materials = list(mesh.materials) + [cap_material] + materials = (list(mesh.materials) or [None]) + [cap_material] # a bare mesh keeps a bare first slot: only caps are dark + cap_slot = len(materials) - 1 collection = obj.users_collection[0] if obj.users_collection else context.scene.collection made, report = [], [] for index, name in enumerate(names): @@ -593,11 +677,11 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for face in caps: face.material_index = cap_slot face.smooth = False - bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") root_world = world @ Vector(root_local) if index else world.translation.copy() piece.to_mesh(new_mesh) piece.free() + restore_normals(new_mesh) for material in materials: new_mesh.materials.append(material) new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json index d2950b7..c161dcd 100644 --- a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -14,7 +14,7 @@ }, { "name": "brokkr_mesh_polish.repair", - "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes; windings are left alone unless recalc_normals.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -23,16 +23,18 @@ {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "recalc_normals", "type": "boolean", "default": false, "doc": "rewind each shell to face outward as Blender judges it; off leaves every winding as it is. Can turn faces wrongly on open shells: read windingFlipped"}, {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} ] }, { "name": "brokkr_mesh_polish.orient", - "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "doc": "Turn an object and its descendants (or the scene) as one body onto its principal axes (long on Y, short on Z), centre, scale; parents and pivots are kept.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "the root of what to turn, with its descendants; every object in the scene when absent"}, {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py index 0ae197a..9031425 100644 --- a/surfaces/blender/brokkr_mesh_polish/core.py +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -111,13 +111,24 @@ def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> floa return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) +def winding_against(V: np.ndarray, T: np.ndarray, CN: np.ndarray) -> np.ndarray: + """True for each triangle whose corner order faces away from its own shading normals CN (m,3,3): the + triangle is drawn from behind, and a single-sided material culls it.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return (np.cross(b - a, c - a) * CN.sum(axis=1)).sum(axis=1) < 0 + + def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, - weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + weld_fraction: float = 1e-5, raster: int = 1024, CN: np.ndarray | None = None) -> dict: """The measurements a polish pass is judged by. Lengths are in the mesh's own units. Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is - texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5. + With CN, the per-corner shading normals, windingAgainstNormals counts triangles wound away from them, and + uvMirroredTriangles counts triangles whose texture reads mirrored on the surface as shaded: negative UV + area on a triangle wound with its normals, or positive on one wound against them. Without CN the winding is + taken as right, so uvMirroredTriangles is the triangles of negative UV area.""" V = np.asarray(V, dtype=np.float64) T = np.asarray(T, dtype=np.int64) extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) @@ -128,6 +139,9 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} report.update(edge_census(TW)) + against = winding_against(V, T, np.asarray(CN, dtype=np.float64)) & (areas > 0) if CN is not None else np.zeros(len(T), dtype=bool) + if CN is not None: + report["windingAgainstNormals"] = int(against.sum()) shells = triangle_components(TW) _, shell_sizes = np.unique(shells, return_counts=True) report["shells"] = int(len(shell_sizes)) @@ -141,7 +155,7 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int covered = int((cover > 0).sum()) report.update({ "uvIslands": uv_islands(TW, UV), - "uvFlippedTriangles": int((signed < 0).sum()), + "uvMirroredTriangles": int(((signed < 0) ^ against)[np.abs(signed) >= 1e-12].sum()), "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), "uvCoverage": covered / float(raster * raster), diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index 4284585..5659698 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -5,7 +5,8 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. -Writes .result.json and exits 1 when a check failed. +With BROKKR_POLISH_HULLS= it also repairs each and checks that no face was +turned. Writes .result.json and exits 1 when a check failed. """ import json import math @@ -17,13 +18,15 @@ from pathlib import Path import bmesh import bpy import numpy as np -from mathutils import Matrix - -for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(_name): - raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +from mathutils import Matrix, Vector SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) OUT = sys.argv[sys.argv.index("--") + 1] package = types.ModuleType("brokkr_bridge") package.__path__ = [str(SURFACE / "brokkr_bridge")] @@ -40,6 +43,7 @@ target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "hostRows": [row["name"] for row in target.host_actions()[0]]} COUNT = [0] +RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived where it is used def check(name, ok, detail=None): @@ -92,58 +96,184 @@ def pixels_of(obj): check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) -# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward +# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ size = 256 -rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) -sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), - new_image("ball_bake", baked.astype(np.float32))) + + +def ball(bm): + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) + layer = bm.loops.layers.uv.active + for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does + for loop in face.loops: + loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) + + +sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) torn = bmesh.new() torn.from_mesh(sphere.data) bmesh.ops.split_edges(torn, edges=torn.edges[:]) +inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] +reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) +bmesh.ops.reverse_faces(torn, faces=inside_out) torn.to_mesh(sphere.data) torn.free() +sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) + + +def polygon_normals(mesh): + flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) + mesh.polygons.foreach_get("normal", flat) + return flat.reshape(-1, 3) + + +def shading_error(mesh): + """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) + return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) + + receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) check("audit: welded topology sees one closed shell in the torn sphere", before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 - and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) -torn_vertices = len(sphere.data.vertices) -receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) + and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps +check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles + and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) +torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) and len(sphere.data.vertices) == 48 * 23 + 2, repaired) -edges = [e for e in sphere.data.edges] -check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) +check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) +normals_after = polygon_normals(sphere.data) +turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 +R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} +check("repair: by default turns no face (a single-sided material would cull a turned one)", + turned == 0 and repaired["changes"]["windingFlipped"] == 0 + and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) +check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 + and not repaired["changes"]["customNormalsDropped"], R["winding"]) -# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ -receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) after_pixels, after_image = pixels_of(sphere) column = after_pixels[:, size // 2, 0] -# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 -ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) -ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) -R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} -check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" - and after_image.packed_file is not None, receipt["message"]) +north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 +ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) +ratio_after = float(column[north] / column[south]) +# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the +# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. +border = int(math.ceil(size * 0.1)) +deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} +check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" + and after_image.name == "ball_bake.delit" and after_image.packed_file is not None + and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) -# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 -check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) +# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half +# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 +check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) +# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 +check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) -# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) +check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces + and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes + and rewound["after"]["windingAgainstNormals"] == 0, rewound) + +# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- +def holey(bm): + bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 + at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) + small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole + large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole + bmesh.ops.delete(bm, geom=small + large, context="FACES") + bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 + + +sheet = new_object("Sheet", holey) +flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess +flipped_sheet.from_mesh(sheet.data) +bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) +flipped_sheet.to_mesh(sheet.data) +flipped_sheet.free() +TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them +sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) +receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) +R["mend"] = mended +check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 + and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) +facing = polygon_normals(sheet.data)[:, 2] +check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) +shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) +sheet.data.corner_normals.foreach_get("vector", shading) +shading = shading.reshape(-1, 3) +fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] +old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] +check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), + [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) +bpy.data.objects.remove(sheet) + +# --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- +def pair(bm): + layer = bm.loops.layers.uv.active + for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other + made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) + for face in {f for v in made["verts"] for f in v.link_faces}: + for loop in face.loops: + loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) + + +import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain + +twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) +twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) +twin = polish.arrays(twins) +twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) +owner, bary, _ = polish.core.rasterize(twin["UV"], size) +sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] +occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) +twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) +flat = np.ones((size, size, 4), dtype=np.float32) +flat[..., :3] = twin_bake +bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) +receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) +twin_after, _ = pixels_of(twins) +shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) +shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) +R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} +# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 +check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 + and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) +bpy.data.objects.remove(twins) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) -sphere.hide_viewport = True -bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body -receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +sphere.location = (20, 0, 0) +bpy.context.view_layer.update() +receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) extent = corners.max(axis=0) - corners.min(axis=0) check("orient: long on Y, thin on Z, scaled to the length, centred", receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] + and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) +receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") +check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) bpy.data.objects.remove(slab) # --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- @@ -177,11 +307,54 @@ if receipt["status"] == "accepted": check("cut_parts: both sides of the cut are capped (closed shells)", all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) - check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} + check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 + and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) + cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons + if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} + check("cut_parts: each cap faces out of its own part, and no old face was turned", + all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) + and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) + check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) + # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot + receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) + pivot = knob.matrix_world.translation + reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) + R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} + # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y + check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body + and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 + and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- +def plate_body(bm): + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 + bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + + +def underside(name): + """Triangles of the part that face down and are surface, not cap.""" + part_object = bpy.data.objects[name] + return sum(1 for polygon in part_object.data.polygons + if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") + + +R["through"] = {} +for label, through in (("without", 0.0), ("with", 0.1)): + new_object("Plate", plate_body) + # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, + # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) + R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None + for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: + bpy.data.objects.remove(leftover) +check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + # --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) @@ -194,16 +367,16 @@ def plate(bm): sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x -sign.location = (0, 0, 5) +sign.location = (40, 0, 5) # clear of the block bpy.context.view_layer.update() camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) bpy.context.scene.collection.objects.link(camera) camera.data.type = "ORTHO" camera.data.ortho_scale = 4.0 -camera.location = (0, 0, 9) +camera.location = (40, 0, 9) receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] - and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) + and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) @@ -227,6 +400,26 @@ check("scrub_markings: a sphere off the surface is refused", receipt["status"] = receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) +# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- +HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") +R["hulls"] = {} +for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: + known = set(bpy.data.objects.keys()) + bpy.ops.import_scene.gltf(filepath=str(path)) + for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: + was = polygon_normals(hull.data) + _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) + against = raw[hull.name]["windingAgainstNormals"] + receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) + now = polygon_normals(hull.data) + turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None + R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, + "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} + check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" + and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair + and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) + bpy.data.objects.remove(hull) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index 9f3bae1..afe1e82 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -37,26 +37,27 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, { @@ -77,28 +78,38 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, + { + "name": "audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + "ok": true, + "detail": [ + 1104, + 1104, + 0 + ] + }, { "name": "repair: accepted as one undo step", "ok": true, @@ -113,8 +124,8 @@ "note": "", "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", - "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", - "observedAt": "2026-12-01T00:06:45.524772+00:00" + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", + "observedAt": "2026-12-01T01:10:29.202522+00:00" } }, { @@ -124,25 +135,30 @@ "object": "Ball", "changes": { "welded": 3406, + "facesCollapsedByWeld": 0, "degenerateFacesRemoved": 0, "looseEdgesRemoved": 0, "looseVertsRemoved": 0, "shellsRemoved": 0, - "holesFilled": 0 + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false }, "before": { "triangles": 2208, "vertices": 4512, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 }, "after": { "triangles": 2208, "vertices": 1106, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 } } }, @@ -152,9 +168,58 @@ "detail": 2256 }, { - "name": "delight: accepted, new packed image on the material", + "name": "repair: by default turns no face (a single-sided material would cull a turned one)", "ok": true, - "detail": "Operator brokkr_mesh_polish.delight finished." + "detail": [ + 0, + { + "object": "Ball", + "changes": { + "welded": 3406, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + } + } + ] + }, + { + "name": "repair: the shading normals survive the weld", + "ok": true, + "detail": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + } + }, + { + "name": "delight: accepted, new packed image on the material, in the old image's colour space", + "ok": true, + "detail": [ + "Operator brokkr_mesh_polish.delight finished.", + "Non-Color" + ] }, { "name": "delight: finds the baked light", @@ -166,22 +231,22 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } } }, @@ -189,10 +254,149 @@ "name": "delight: levels top against bottom", "ok": true, "detail": [ - 3.2905027932960893, - 1.119760513305664 + 3.2607489597780868, + 1.1137723922729492 ] }, + { + "name": "delight: the gain reaches the island's border unweakened", + "ok": true, + "detail": 0.0 + }, + { + "name": "repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 576, + "customNormalsDropped": true + }, + "before": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + "ok": true, + "detail": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: a filled hole is wound as the faces around it", + "ok": true, + "detail": [ + 33, + -1.0 + ] + }, + { + "name": "repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + "ok": true, + "detail": [ + 6, + [ + [ + 0.0, + 0.0, + -1.0 + ], + [ + 0.0, + 0.0, + -1.0 + ] + ], + [ + 0.6000571846961975, + 7.155610326492479e-09, + -0.7999570965766907 + ] + ] + }, + { + "name": "delight: lifts occluded surface to the level of open surface", + "ok": true, + "detail": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 + } + }, { "name": "orient: long on Y, thin on Z, scaled to the length, centred", "ok": true, @@ -229,6 +433,18 @@ "Z": 1.962464589014781e-09 } }, + { + "name": "orient: an object outside the named root is not touched", + "ok": true, + "detail": [ + "Slab" + ] + }, + { + "name": "orient: an unknown root is refused", + "ok": true, + "detail": "Error: No object named 'Nobody'." + }, { "name": "cut fixture is one closed skin", "ok": true, @@ -247,12 +463,13 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 0, "shells": 1, "shellTriangles": [ 28 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 28, "uvOutsideUnitTriangles": 0, "uvCoverage": 0.0, @@ -312,15 +529,76 @@ } }, { - "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "name": "cut_parts: exactly the cap faces carry the cap material", + "ok": true, + "detail": { + "Block.body": 2, + "Block.knob": 2 + } + }, + { + "name": "cut_parts: each cap faces out of its own part, and no old face was turned", + "ok": true, + "detail": { + "Block.body": [ + 1.0, + 1.0 + ], + "Block.knob": [ + -1.0, + -1.0 + ] + } + }, + { + "name": "cut_parts: a joint sits at the root", "ok": true, "detail": "Block.knob.joint" }, + { + "name": "orient: after a cut the parts keep their parent and their pivot at the cut", + "ok": true, + "detail": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + } + }, { "name": "cut_parts: one part is refused with nothing changed", "ok": true, "detail": "Error: Cutting needs seeds for at least two parts." }, + { + "name": "cut_parts: through seeds the far face of a thin part", + "ok": true, + "detail": { + "without": 0, + "with": 93 + } + }, { "name": "pick: names the surface point under (u, v) of a picture of that shape", "ok": true, @@ -328,7 +606,7 @@ "hit": true, "object": "Sign", "point": [ - -1.0, + 39.0, 0.0, 5.0 ], @@ -375,6 +653,72 @@ "name": "a bound miss is denied by Brokkr's table before the operator runs", "ok": true, "detail": "max_gain must be between 1 and 8." + }, + { + "name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull sub.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull third.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } } ], "hostErrors": [], @@ -387,6 +731,11 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick" ], + "winding": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + }, "delight": { "report": { "image": "ball_bake", @@ -395,26 +744,87 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } }, - "ratioBefore": 3.2905027932960893, - "ratioAfter": 1.119760513305664 + "ratioBefore": 3.2607489597780868, + "ratioAfter": 1.1137723922729492, + "borderDeficit": 0.0 + }, + "mend": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + }, + "occlusion": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 }, "cut": { "body": "Block.body", @@ -456,6 +866,37 @@ } ] }, + "orientParts": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + }, + "through": { + "without": 0, + "with": 93 + }, "scrub": { "report": { "object": "Sign", @@ -467,5 +908,61 @@ "inkInsideBefore": 192, "inkInsideAfter": 0 }, + "hulls": { + "fourth.glb": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "sub.glb": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "third.glb": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py index 7205f81..9f0b4ef 100644 --- a/surfaces/blender/tests/test_mesh_polish.py +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -37,6 +37,7 @@ def load(name: str, path: Path): turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +private_dirs = load("private_dirs", SURFACE / "tools" / "private_dirs.py") core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None @@ -83,6 +84,23 @@ class TopologyTests(unittest.TestCase): self.assertEqual(report["shells"], 2) self.assertEqual(report["shellTriangles"], [4, 4]) + def test_a_triangle_the_weld_collapses_adds_no_edges(self): + V, T = quad_strip(3) + sliver = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]) # two corners weld into one + _, TW = core.weld(np.concatenate([V, sliver]), np.concatenate([T, [[len(V), len(V) + 1, len(V) + 2]]]), 1e-6) + census = core.edge_census(TW) + self.assertEqual((census["collapsedTriangles"], census["boundaryEdges"], census["nonManifoldEdges"]), (1, 8, 0)) + + def test_winding_against_shading_normals_is_counted_per_triangle(self): + V, T = quad_strip(3) # every triangle faces +z + up = np.tile([0.0, 0.0, 1.0], (len(T), 3, 1)) + self.assertEqual(int(core.winding_against(V, T, up).sum()), 0) + mixed = T.copy() + mixed[:2] = mixed[:2, ::-1] # two triangles wound the other way, their shading normals still up + self.assertEqual(core.winding_against(V, mixed, up).tolist(), [True, True, False, False, False, False]) + self.assertEqual(core.audit(V, mixed, None, CN=up)["windingAgainstNormals"], 2) + self.assertNotIn("windingAgainstNormals", core.audit(V, mixed, None)) + def test_components_follow_long_chains(self): pairs = np.array([[i, i + 1] for i in range(999)]) self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) @@ -101,7 +119,34 @@ class UvTests(unittest.TestCase): self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) - self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + self.assertEqual((report["uvIslands"], report["uvMirroredTriangles"]), (1, 0)) + + def test_a_seam_in_uv_space_makes_two_islands_of_one_surface(self): + apart = self.SQUARE_UV * 0.4 + apart[1] += 0.5 # the second triangle's UVs moved away: the 3D edge is shared, the UV edge is not + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, apart, 1024, raster=64)["uvIslands"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.4, 1024, raster=64)["uvIslands"], 1) + + def test_texel_density_is_weighted_by_surface_area(self): + # one large triangle at 1024 texels per unit and four tiny ones at 4096: by count the median is 4096, by area 1024 + tiny = np.array([[0, 0, 0], [0.01, 0, 0], [0, 0.01, 0]], dtype=float) + V = np.concatenate([self.SQUARE_V[[0, 1, 2]] * 0.5] + [tiny + [2 + i, 0, 0] for i in range(4)]) + T = np.arange(15).reshape(5, 3) + UV = np.concatenate([self.SQUARE_UV[:1] * 0.5] + [tiny[None, :, :2] * 4 + [0.6 + 0.05 * i, 0.6] for i in range(4)]) + report = core.audit(V, T, UV, texture_size=1024, raster=64) + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensityP95"], 1024.0, places=3) + + def test_mirrored_texture_is_judged_against_the_shading_normals_not_the_winding(self): + up = np.tile([0.0, 0.0, 1.0], (2, 3, 1)) + wound_back = self.SQUARE_T[:, ::-1] + uv_back = self.SQUARE_UV[:, ::-1] # the same texel at each vertex, listed in the reversed corner order + report = core.audit(self.SQUARE_V, wound_back, uv_back, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (2, 0)) # culled, but not mirrored + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + report = core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (0, 2)) # drawn, and mirrored def test_two_triangles_on_the_same_texels_overlap(self): stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) @@ -111,7 +156,7 @@ class UvTests(unittest.TestCase): def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): mirrored = self.SQUARE_UV.copy() mirrored[..., 0] = 1 - mirrored[..., 0] - self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvMirroredTriangles"], 2) half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) @@ -138,6 +183,22 @@ class OrientTests(unittest.TestCase): self.assertLess(extent[2], 1e-9) self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + def test_principal_frame_is_a_rotation_for_a_shape_and_for_its_mirror_image(self): + rng = np.random.default_rng(4) + V = rng.random((60, 3)) * [5.0, 2.0, 1.0] + T = rng.integers(0, 60, size=(40, 3)) + T = T[(T[:, 0] != T[:, 1]) & (T[:, 1] != T[:, 2]) & (T[:, 0] != T[:, 2])] + determinants = [float(np.linalg.det(core.principal_frame(V * flip, T)[1])) for flip in ([1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1])] + self.assertTrue(np.allclose(determinants, 1.0), determinants) # never a reflection: it would turn the mesh inside out + + def test_mirror_error_is_about_the_axis_asked(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + about_y = np.concatenate([half, half * [1, -1, 1]]) + [0.7, 0.0, 0.3] # a mirror across y = 0 only + self.assertEqual(core.mirror_error(about_y, 1), 0.0) + self.assertGreater(core.mirror_error(about_y, 0), 0.05) + self.assertGreater(core.mirror_error(about_y, 2), 0.05) + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): rng = np.random.default_rng(1) half = rng.random((400, 3)) @@ -321,6 +382,16 @@ class TextureFillTests(unittest.TestCase): outside = np.zeros((40, 40), dtype=bool) self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + def test_marking_mask_judges_against_the_median_so_heavy_lettering_does_not_move_the_panel_colour(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel[:, ::3] = [0.95, 0.9, 0.3] # a third of the region is lettering: the mean colour is 0.3 from the panel + region = np.ones((40, 40), dtype=bool) + mask = core.marking_mask(panel, region, 0.25, 0) + self.assertTrue(np.array_equal(mask, np.repeat((np.arange(40) % 3 == 0)[None, :], 40, axis=0))) + + def test_srgb_known_values(self): + self.assertTrue(np.allclose(core.srgb_to_linear(np.array([0.0, 0.04045, 0.5, 1.0])), [0.0, 0.0031308, 0.21404, 1.0], atol=2e-5)) + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): flat = np.full((9, 9), 0.5) self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) @@ -360,6 +431,46 @@ class HostFileTests(unittest.TestCase): at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required +class PrivateDirsTests(unittest.TestCase): + """The guard a driver script runs before it touches Blender's user folders.""" + HOME = str(Path("/home/her")) + APPDATA = str(Path("/users/her/AppData/Roaming")) + + def environ(self, **changes): + base = {"BLENDER_USER_CONFIG": "/scratch/bl/cfg", "BLENDER_USER_EXTENSIONS": "/scratch/bl/ext", + "BLENDER_USER_SCRIPTS": "/scratch/bl/scripts", "APPDATA": self.APPDATA} + base.update(changes) + return {k: v for k, v in base.items() if v is not None} + + def test_scratch_directories_pass(self): + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME)) + used = {"CONFIG": "/scratch/bl/cfg", "EXTENSIONS": "/scratch/bl/ext", "SCRIPTS": "/scratch/bl/scripts"} + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME, lambda kind: used[kind])) + + def test_an_unset_or_empty_variable_is_refused(self): + for name in private_dirs.VARIABLES: + for value in (None, ""): + self.assertIn(name, private_dirs.refusal(self.environ(**{name: value}), self.HOME)) + + def test_a_variable_pointing_into_her_own_blender_folders_is_refused(self): + own = [str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3" / "extensions"), + str(Path(self.APPDATA) / "Blender Foundation"), + str(Path(self.HOME) / ".config" / "blender" / "5.3" / "scripts"), + str(Path(self.HOME) / "Library" / "Application Support" / "Blender" / "5.3" / "config")] + for folder in own: + for name in private_dirs.VARIABLES: + refused = private_dirs.refusal(self.environ(**{name: folder}), self.HOME) + self.assertIsNotNone(refused, folder) + self.assertIn("own Blender folder", refused) + beside = str(Path(self.APPDATA) / "Blender Foundation Scratch") # a sibling that only shares a prefix + self.assertIsNone(private_dirs.refusal(self.environ(BLENDER_USER_EXTENSIONS=beside), self.HOME)) + + def test_a_blender_that_is_not_using_the_variables_is_refused(self): + hers = str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3") + self.assertIn("refusing to touch it", private_dirs.refusal(self.environ(), self.HOME, lambda kind: hers)) + self.assertIn("refusing", private_dirs.refusal(self.environ(), self.HOME, lambda kind: "")) + + class TurntableRecipeTests(unittest.TestCase): def test_every_pose_looks_at_the_origin_with_z_up(self): for azimuth in (0, 45, 90, 200, 315): -- 2.47.3 From 2e3ac798eab717d30e6b245049970735cebf4930 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:46 +0100 Subject: [PATCH 6/6] docs: mesh polish after Soul's pass: windings, shading normals, orient scope, delight's gradient limit, the guard Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/mesh-polish.md | 68 ++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/docs/mesh-polish.md b/surfaces/blender/docs/mesh-polish.md index 93b8fac..914ed6a 100644 --- a/surfaces/blender/docs/mesh-polish.md +++ b/surfaces/blender/docs/mesh-polish.md @@ -38,9 +38,11 @@ blender --background --factory-startup --python surfaces/blender/tools/run_inten ``` The runner opens no CultMesh node: receipts go to `.receipts.json` only. It is the human of its own -Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`), and it refuses to -start without private `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS`. Its exit status is -0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. +Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`). It refuses to +start unless `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS` are each set to a folder +outside a person's own Blender folders (`%APPDATA%\Blender Foundation`, `~/.config/blender`, +`~/Library/Application Support/Blender`) and Blender reports that it is using them (`tools/private_dirs.py`). Its +exit status is 0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. `surfaces/blender/tools/turntable_recipe.py` writes a recipe of Brokkr's own scene actions (`setWorld`, `createObject`, `setCamera`, `setObjectTransform`, `renderStill`) for an orthographic turntable of a `.blend` whose @@ -49,7 +51,7 @@ an after compare view by view. `--look flat` lights with a uniform white world a stored, baked shadows included; `--look lit` adds a sun. A polish pass that works, in order: `audit`, `orient` (render a flat turntable and pick `roll_quarter_turns` and -`flip_forward` by eye), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then +`flip_forward` by eye; give `principal: false` on any later call, or the axes are found again), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then `pick` and `cut_parts` when parts must move, `audit` again, `exportGltf`. ## Actions @@ -63,7 +65,13 @@ as all open edges. - `triangles`, `vertices`, `weldedVertices`, `extent`, `surfaceArea`, `degenerateTriangles`. - `boundaryEdges` (one triangle on the edge: an open rim), `nonManifoldEdges` (three or more), `shells` and the triangle count of the largest twelve. -- `uvIslands`, `uvFlippedTriangles` (mirrored in UV space), `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, +- `windingAgainstNormals`: triangles whose corner order faces away from their own shading normals (the custom + normals a generated mesh carries). A single-sided material culls them. A mesh without custom normals is shaded + from its windings, so this reads 0 whatever its windings are. +- `uvMirroredTriangles`: triangles whose texture reads mirrored on the surface as shaded, that is negative UV area + on a triangle wound with its normals, or positive UV area on one wound against them. A triangle that is merely + wound backwards is not counted here. +- `uvIslands`, `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, `uvCoverage` (share of the texture some triangle covers) and `uvOverlap` (share of covered texels that more than one triangle covers), both counted at texel centres on a `raster` x `raster` grid. - `texelDensityMedian`, `P5`, `P95` (texels per unit length for the base colour texture's size, area-weighted) and @@ -73,13 +81,24 @@ as all open edges. ### repair Welds coincident vertices (UVs live on face corners, so seams keep their UVs), removes degenerate faces and loose -edges and vertices, optionally deletes shells below `min_shell_area` of the surface, optionally closes holes of up -to `fill_holes_sides` edges, and makes face normals consistent. With `sharp_angle` above 0 the generator's custom -normals are dropped and shading is recomputed: smooth, hard across edges sharper than the angle. +edges and vertices, optionally deletes shells below `min_shell_area` of the surface, and optionally closes holes of +up to `fill_holes_sides` edges. + +It turns no face. The winding of every face is left as the generator made it, and the mesh's custom shading normals +are carried through the weld as plain directions and set back afterwards (Blender stores a custom normal against +its corner's automatic normal, which welding changes). `windingFlipped` in the report is 0 and +`windingAgainstNormals` is the same before and after, less any triangle that was removed. + +`recalc_normals: true` asks Blender to rewind each shell to face outward. On a closed shell that is right. On the +open, intersecting shells generators make it is a guess: on three Tripo hulls it turned 83 of 10,406, 4,564 of +23,341 and 15,734 of 28,426 triangles, and a single-sided material then culls whatever was turned the wrong way. +The report says how many faces it turned (`windingFlipped`); the custom normals cannot outlive a rewind and are +dropped (`customNormalsDropped`). With `sharp_angle` above 0 the custom normals are also dropped and shading is +recomputed: smooth, hard across edges sharper than the angle. A filled hole has no place in the UV map: each new face takes one UV point from the old face beside it, so it shows -that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`). Making normals consistent flips the -winding of shells that faced inward, which mirrors their UVs; `uvFlippedTriangles` can rise. +that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`); it is shaded by its own direction, +not by its neighbours' custom normals. Welding does not join shells that merely touch or intersect. A mesh assembled from open, interpenetrating shells stays one: its open edges and non-manifold edges are reported, not repaired. Closing such a mesh means remeshing it @@ -87,9 +106,11 @@ and rebaking its texture, which this add-on does not do. ### orient -Turns every mesh in the scene, as one rigid body, onto its area-weighted principal axes: longest on Y, shortest on -Z, centred on the origin, the longest side scaled to `length` when given. The transform is baked into the mesh data -and the objects are left unparented at identity. Principal axes do not know bow from stern or up from down: +Turns `object_name` and everything parented under it (every object in the scene when absent), as one rigid body, +onto its area-weighted principal axes: longest on Y, shortest on Z, centred on the origin, the longest side scaled +to `length` when given. Objects outside that root are not touched. Rotation and scale are baked into the mesh data; +every object keeps its parent and its pivot point (a cut part's origin stays at the centre of its cut), and meshes +and empties end unrotated and unscaled. Principal axes do not know bow from stern or up from down: `flip_forward` and `roll_quarter_turns` choose, and `mirrorError` in the report (per axis, 0 is a perfect mirror) says which plane the body is symmetric across. `principal: false` keeps the current axes and applies only the turns, the centring and the scale. @@ -98,8 +119,9 @@ turns, the centring and the scale. Undoes lighting baked into the base colour texture, as far as the surface's own shape explains it. -For each texel the add-on knows the surface normal and the ambient occlusion there (cosine-weighted rays against -the mesh, per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints +For each texel the add-on knows the shading normal (the mesh's custom normals when it has them, so a shell wound +inside out is still read as it is drawn) and the ambient occlusion there (cosine-weighted rays against the mesh, +per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints the texture holds) plus a light term: the order-2 spherical harmonics of the normal and the log of occlusion. The fit follows the upper envelope of luminance (an expectile regression at 0.85), because within one hue the brightest paint at a given normal and occlusion shows how much light the bake put there, while darker paint in the @@ -115,7 +137,11 @@ is the share of texels that hit `max_gain`. What it cannot do. It removes smooth, shape-following light: sky-over-ground gradients and occlusion darkening. It does not remove cast shadows, specular highlights, or light the shape does not explain. It cannot tell dark -paint from shadow where a hue has no bright paint at all in some range of occlusion. Texels the generator filled +paint from shadow where a hue has no bright paint at all in some range of occlusion. It cannot tell paint from light +when the paint itself follows the shape: a smooth fade of one hue that runs with the normal (a hull painted lighter +above than below) is read as sky-over-ground light and flattened; in a probe such a fade kept 0.35 of its slope. +Paint in panels, bands or patches keeps its contrast (slope 1.00 in the same probe). On a mesh without custom +normals whose shells are wound inside out, the normals it reads are wrong; `audit` cannot see that case. Texels the generator filled with black stay black: there is no colour there to recover. It raises shaded paint by gain, so 8-bit noise and JPEG blocks in dark areas are raised with it. @@ -151,7 +177,8 @@ crease. `through` above 0 also seeds the far face of each part off the body, fou no longer than that share of the diagonal: a thin shell (a petal, a fin) is then held from both faces. The mesh is welded and triangulated first. Each part becomes an object `.`; both sides of every cut -are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); each part off +are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); no existing +face is turned and the custom shading normals are carried through, as in `repair`; each part off the body gets its origin at the centre of its cut and is parented to the body without moving; custom properties `polish_cut_normal` and `polish_cut_radius` record the cut's plane and mean radius. `joint_scale` above 0 adds a ball of that share of the cut radius at each root, parented to the body. The original object is removed. @@ -167,6 +194,9 @@ centre of the cut, not a designed hinge: it is a sensible pivot to start from. ## Tests - `tests/test_mesh_polish.py`: the arithmetic on hand-built meshes and textures, `brokkr_actions.json` against - Brokkr's own host-file checker, and the turntable recipe against the action table. No Blender; needs numpy. + Brokkr's own host-file checker, the private-directory guard, and the turntable recipe against the action table. + No Blender; needs numpy. - `tests/live/mesh_polish.py`: every action through `run_intent` in a background Blender against real bpy - (`mesh_polish.result.json` is the last run, Blender 5.3.0). + (`mesh_polish.result.json` is the last run, Blender 5.3.0). Its sphere is a generator's in miniature: torn at + every edge, half its faces wound inside out under outward custom normals. With `BROKKR_POLISH_HULLS` set to a + directory of generated `.glb` hulls it also repairs each and checks that no face was turned. -- 2.47.3