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 <noreply@anthropic.com>
This commit is contained in:
parent
72258d9288
commit
6eb3725254
6 changed files with 2309 additions and 0 deletions
698
surfaces/blender/brokkr_mesh_polish/__init__.py
Normal file
698
surfaces/blender/brokkr_mesh_polish/__init__.py
Normal file
|
|
@ -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)
|
||||
102
surfaces/blender/brokkr_mesh_polish/brokkr_actions.json
Normal file
102
surfaces/blender/brokkr_mesh_polish/brokkr_actions.json
Normal file
|
|
@ -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"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
414
surfaces/blender/brokkr_mesh_polish/core.py
Normal file
414
surfaces/blender/brokkr_mesh_polish/core.py
Normal file
|
|
@ -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
|
||||
234
surfaces/blender/tests/live/mesh_polish.py
Normal file
234
surfaces/blender/tests/live/mesh_polish.py
Normal file
|
|
@ -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 -- <out>
|
||||
|
||||
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 <out>.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)
|
||||
471
surfaces/blender/tests/live/mesh_polish.result.json
Normal file
471
surfaces/blender/tests/live/mesh_polish.result.json
Normal file
|
|
@ -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
|
||||
}
|
||||
390
surfaces/blender/tests/test_mesh_polish.py
Normal file
390
surfaces/blender/tests/test_mesh_polish.py
Normal file
|
|
@ -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()
|
||||
Loading…
Reference in a new issue