@babylonjs-toolkit/agent 1.2.18 → 1.2.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/skills/bt-blender/SKILL.md +81 -19
- package/skills/bt-blender/references/hard-surface.md +9 -5
- package/skills/bt-blender/references/vehicles.md +14 -9
- package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
- package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
- package/skills/bt-blender/scripts/blender/construction_kit.py +61 -1
- package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
- package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
- package/skills/bt-blender/scripts/blender/image_measure.py +354 -5
- package/skills/bt-blender/scripts/blender/measure_stations.py +11 -1
- package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
- package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
- package/skills/bt-blender/scripts/blender/trace.py +283 -0
- package/skills/bt-blender/scripts/blender/world_gate.py +17 -5
- package/skills/bt-blender/scripts/bt-blender.mjs +4 -0
- package/skills/bt-execute/SKILL.md +2 -1
- package/skills/bt-gauntlet/SKILL.md +24 -14
- package/skills/bt-gauntlet/references/critic-rubrics.md +37 -5
- package/skills/bt-gauntlet/references/loop-templates.md +23 -3
- package/skills/bt-gauntlet/references/spec-composition.md +7 -1
- package/skills/bt-gauntlet/references/target-images.md +27 -0
- package/skills/bt-gauntlet/references/unity-pipeline.md +24 -3
- package/skills/bt-gauntlet/references/workspace.md +90 -6
|
@@ -20,7 +20,10 @@ What is in it, by form language:
|
|
|
20
20
|
- shared part operations the domain modules build on: boolean_cut (every cutter in one volume-checked
|
|
21
21
|
cut, rim edges returned), radial_array (copies round an axis), lod_chain (decimated LODs that keep
|
|
22
22
|
LOD0's custom normals);
|
|
23
|
-
- measuring: world_vertices, section_points, section_extent, evaluated_volume, edges_between
|
|
23
|
+
- measuring: world_vertices, section_points, section_extent, evaluated_volume, edges_between;
|
|
24
|
+
- blueprint and traces: load_blueprint (the reference views as image planes, from the `blueprint` tool),
|
|
25
|
+
load_traces (traced outlines and design curves, from the `trace` tool) and stamp_traces (marks the parts
|
|
26
|
+
built on them; a spec's "require_traces" gates on the stamp).
|
|
24
27
|
|
|
25
28
|
Everything works on data (bmesh, mesh attributes, modifiers) except smart_unwrap, which needs the UV
|
|
26
29
|
operator. Lengths are metres; Blender is Z-up and the model faces -Y (glTF / BabylonJS forward).
|
|
@@ -31,6 +34,7 @@ section with keystone follows NASA OpenVSP's cross-section definitions. sdf_infl
|
|
|
31
34
|
superellipse inflate field of colinurbs/claude-modeling-skills -- see sdf_inflate for its notice.
|
|
32
35
|
"""
|
|
33
36
|
import math
|
|
37
|
+
import os
|
|
34
38
|
import warnings
|
|
35
39
|
|
|
36
40
|
import bmesh
|
|
@@ -40,6 +44,7 @@ from mathutils import Matrix, Vector
|
|
|
40
44
|
from mathutils.kdtree import KDTree
|
|
41
45
|
|
|
42
46
|
import geometry_nodes_builders as gn
|
|
47
|
+
import reference_traces
|
|
43
48
|
|
|
44
49
|
# A corner radius of 0 becomes a fillet this share of the section size, so every section keeps the same
|
|
45
50
|
# point count for lofting. Mark that edge sharp if it must read crisp.
|
|
@@ -116,6 +121,9 @@ CENTRIPETAL_EXPONENT = 0.5
|
|
|
116
121
|
|
|
117
122
|
AXIS_INDEX = {"X": 0, "Y": 1, "Z": 2}
|
|
118
123
|
|
|
124
|
+
# Collection the `blueprint` tool puts the reference image planes, view cameras and reference box in.
|
|
125
|
+
BLUEPRINT_COLLECTION = "_Blueprint"
|
|
126
|
+
|
|
119
127
|
|
|
120
128
|
# --- scene -------------------------------------------------------------------------------------------------
|
|
121
129
|
|
|
@@ -1708,3 +1716,55 @@ def _close_pinches(obj: bpy.types.Object, step: float) -> None:
|
|
|
1708
1716
|
remesh.voxel_size = step
|
|
1709
1717
|
remesh.use_smooth_shade = True
|
|
1710
1718
|
apply_modifiers(obj)
|
|
1719
|
+
|
|
1720
|
+
|
|
1721
|
+
# --- blueprint and traces ----------------------------------------------------------------------------------
|
|
1722
|
+
|
|
1723
|
+
def load_blueprint(path: str) -> bpy.types.Collection:
|
|
1724
|
+
"""
|
|
1725
|
+
Appends the blueprint made by the `blueprint` tool (the reference images as planes at world scale in their
|
|
1726
|
+
view planes, an orthographic camera per view and the wire box at the known dimensions) into the current
|
|
1727
|
+
scene, so a build script models over the references. Every blueprint object's name starts with "_", so no
|
|
1728
|
+
tool measures or exports it.
|
|
1729
|
+
|
|
1730
|
+
:param path: The blueprint .blend.
|
|
1731
|
+
:returns: The linked-in blueprint collection.
|
|
1732
|
+
:raises FileNotFoundError: when the file does not exist.
|
|
1733
|
+
:raises ValueError: when the file holds no blueprint collection.
|
|
1734
|
+
"""
|
|
1735
|
+
absolute = os.path.abspath(path)
|
|
1736
|
+
if not os.path.isfile(absolute):
|
|
1737
|
+
raise FileNotFoundError(f"blueprint not found: {absolute} (run the blueprint tool first)")
|
|
1738
|
+
with bpy.data.libraries.load(absolute, link=False) as (source, target):
|
|
1739
|
+
if BLUEPRINT_COLLECTION not in source.collections:
|
|
1740
|
+
raise ValueError(f"{absolute} has no '{BLUEPRINT_COLLECTION}' collection")
|
|
1741
|
+
target.collections = [BLUEPRINT_COLLECTION]
|
|
1742
|
+
collection = target.collections[0]
|
|
1743
|
+
bpy.context.scene.collection.children.link(collection)
|
|
1744
|
+
return collection
|
|
1745
|
+
|
|
1746
|
+
|
|
1747
|
+
def load_traces(path: str) -> reference_traces.TraceSet:
|
|
1748
|
+
"""
|
|
1749
|
+
Reads the `trace` tool's traces.json: named design curves as (N, 3) world points (`.curve(name)`,
|
|
1750
|
+
`.curves`), each view's outline on its plane (`.outline(view)`, `.outline_points(view, depth)`), and
|
|
1751
|
+
station lookups (`.outline_boundary(view, axis, value, side)`, `.outline_extent(view, axis, value)`).
|
|
1752
|
+
Lay blockout sections, cage lines and loft rails on these, then `stamp_traces` the parts.
|
|
1753
|
+
|
|
1754
|
+
:param path: traces.json.
|
|
1755
|
+
:returns: The TraceSet.
|
|
1756
|
+
"""
|
|
1757
|
+
return reference_traces.load_traces(path)
|
|
1758
|
+
|
|
1759
|
+
|
|
1760
|
+
def stamp_traces(objects, path: str) -> str:
|
|
1761
|
+
"""
|
|
1762
|
+
Marks parts as built on a traces file: writes its SHA-256 to each object's `bt_traces` custom property.
|
|
1763
|
+
When a spec carries "require_traces", `world-gate` and `measure-stations` fail any measured part whose
|
|
1764
|
+
stamp is missing or belongs to an older traces file. Stamp only what was really built on the curves.
|
|
1765
|
+
|
|
1766
|
+
:param objects: The parts.
|
|
1767
|
+
:param path: traces.json.
|
|
1768
|
+
:returns: The SHA-256 written.
|
|
1769
|
+
"""
|
|
1770
|
+
return reference_traces.stamp_objects(objects, path)
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""
|
|
2
|
+
coverage_check -- prove that every region of the reference silhouette belongs to a part before building.
|
|
3
|
+
|
|
4
|
+
When an asset is split into parts (a body, a nose, flanks, pods), each part's region is drawn on the whole-
|
|
5
|
+
asset reference images in coverage.json. The union of the part regions must cover the subject's silhouette
|
|
6
|
+
(--min-coverage, 99 % of its pixels by default). Every UNCLAIMED region (a connected piece of silhouette no
|
|
7
|
+
part owns, above --min-region-percent of the silhouette) is listed with its bounding box and area, and so
|
|
8
|
+
is every overlap between two parts, so a region that belongs to no part (an unassigned flank) is found
|
|
9
|
+
before anyone builds, not after.
|
|
10
|
+
|
|
11
|
+
coverage.json (pixel coordinates of each reference image, row 0 at the top):
|
|
12
|
+
{"views": {"<reference name, file name or stem>": {"parts": {
|
|
13
|
+
"<part name>": [x0, y0, x1, y1] a box (right / bottom exclusive)
|
|
14
|
+
| [[x, y], [x, y], [x, y], ...] a polygon
|
|
15
|
+
| [<box or polygon>, ...] several regions
|
|
16
|
+
}}}}
|
|
17
|
+
|
|
18
|
+
node bt-blender.mjs coverage-check --reference refs/left.png [--reference top=refs/top.png ...]
|
|
19
|
+
--parts coverage.json --out coverage.png [--crop left=x0,y0,x1,y1] [--min-coverage 99]
|
|
20
|
+
[--background-tolerance 0.08] [--min-region-percent 0.1] [--tile 480]
|
|
21
|
+
|
|
22
|
+
The picture shows each part's region in its own colour, overlaps in white and unclaimed silhouette in solid
|
|
23
|
+
red; <out>.json has the numbers. Exits 1 while any view's coverage is below --min-coverage.
|
|
24
|
+
"""
|
|
25
|
+
import itertools
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
|
|
29
|
+
sys.dont_write_bytecode = True
|
|
30
|
+
SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
|
|
31
|
+
if SCRIPT_DIRECTORY not in sys.path:
|
|
32
|
+
sys.path.insert(0, SCRIPT_DIRECTORY)
|
|
33
|
+
|
|
34
|
+
import numpy as np # noqa: E402
|
|
35
|
+
|
|
36
|
+
import evidence_sheet # noqa: E402
|
|
37
|
+
import image_measure # noqa: E402
|
|
38
|
+
import overlay_sheet # noqa: E402
|
|
39
|
+
import tool_common # noqa: E402
|
|
40
|
+
|
|
41
|
+
TOOL_NAME = "coverage-check"
|
|
42
|
+
|
|
43
|
+
DEFAULT_MINIMUM_COVERAGE_PERCENT = 99.0
|
|
44
|
+
DEFAULT_MINIMUM_REGION_PERCENT = 0.1
|
|
45
|
+
DEFAULT_TILE_PIXELS = 480
|
|
46
|
+
|
|
47
|
+
# Values in a box region, and per polygon point.
|
|
48
|
+
BOX_VALUES = 4
|
|
49
|
+
POINT_VALUES = 2
|
|
50
|
+
MINIMUM_POLYGON_POINTS = 3
|
|
51
|
+
|
|
52
|
+
# Drawing: part colours in order (red is kept for unclaimed silhouette), and how strongly each is laid on.
|
|
53
|
+
PART_COLORS = ((0.3, 0.7, 1.0), (0.4, 0.9, 0.4), (1.0, 0.8, 0.2), (0.8, 0.5, 1.0), (0.2, 0.9, 0.85),
|
|
54
|
+
(1.0, 0.55, 0.2), (0.6, 0.8, 0.3), (0.95, 0.5, 0.8), (0.5, 0.6, 1.0), (0.85, 0.85, 0.5))
|
|
55
|
+
UNCLAIMED_COLOR = (1.0, 0.1, 0.1)
|
|
56
|
+
OVERLAP_COLOR = (1.0, 1.0, 1.0)
|
|
57
|
+
PART_STRENGTH = 0.45
|
|
58
|
+
UNCLAIMED_STRENGTH = 0.9
|
|
59
|
+
OVERLAP_STRENGTH = 0.5
|
|
60
|
+
OUTLINE_PIXELS = 2
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def build_parser() -> tool_common.ToolArgumentParser:
|
|
64
|
+
"""The tool's command-line options."""
|
|
65
|
+
parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
|
|
66
|
+
parser.add_argument("--reference", action="append", required=True, metavar="[NAME=]IMAGE",
|
|
67
|
+
help="a whole-asset reference image (repeatable)")
|
|
68
|
+
parser.add_argument("--parts", required=True, help="coverage.json: each part's region per reference")
|
|
69
|
+
parser.add_argument("--out", required=True, help="picture to write (PNG); the JSON goes beside it")
|
|
70
|
+
parser.add_argument("--crop", action="append", default=[], metavar="NAME=X0,Y0,X1,Y1",
|
|
71
|
+
help="crop box (pixels) for a named reference")
|
|
72
|
+
parser.add_argument("--min-coverage", type=float, default=DEFAULT_MINIMUM_COVERAGE_PERCENT,
|
|
73
|
+
help="percent of the silhouette the parts must cover")
|
|
74
|
+
parser.add_argument("--min-region-percent", type=float, default=DEFAULT_MINIMUM_REGION_PERCENT,
|
|
75
|
+
help="smallest unclaimed region listed, percent of the silhouette")
|
|
76
|
+
parser.add_argument("--background-tolerance", type=float, default=image_measure.DEFAULT_BACKGROUND_TOLERANCE)
|
|
77
|
+
parser.add_argument("--tile", type=int, default=DEFAULT_TILE_PIXELS, help="longest side of each tile, pixels")
|
|
78
|
+
return parser
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def region_polygons(region) -> list:
|
|
82
|
+
"""
|
|
83
|
+
A part's region as polygons.
|
|
84
|
+
|
|
85
|
+
:param region: A box [x0, y0, x1, y1], a polygon [[x, y], ...], or a list of those.
|
|
86
|
+
:returns: [(N, 2) arrays].
|
|
87
|
+
:raises ValueError: for anything else.
|
|
88
|
+
"""
|
|
89
|
+
if isinstance(region, list) and len(region) == BOX_VALUES and all(isinstance(value, (int, float)) for value in region):
|
|
90
|
+
left, top, right, bottom = (float(value) for value in region)
|
|
91
|
+
return [np.array([[left, top], [right, top], [right, bottom], [left, bottom]])]
|
|
92
|
+
if (isinstance(region, list) and len(region) >= MINIMUM_POLYGON_POINTS
|
|
93
|
+
and all(isinstance(point, list) and len(point) == POINT_VALUES
|
|
94
|
+
and all(isinstance(value, (int, float)) for value in point) for point in region)):
|
|
95
|
+
return [np.array(region, dtype=np.float64)]
|
|
96
|
+
if isinstance(region, list) and region and all(isinstance(item, list) for item in region):
|
|
97
|
+
return [polygon for item in region for polygon in region_polygons(item)]
|
|
98
|
+
raise ValueError(f"a part region must be a box [x0, y0, x1, y1], a polygon [[x, y], ...] or a list of them: {region}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _references(entries: list) -> list:
|
|
102
|
+
"""--reference entries as (name, path, the keys a coverage.json view may use for it)."""
|
|
103
|
+
references = []
|
|
104
|
+
for entry in entries:
|
|
105
|
+
name, separator, path = entry.partition("=")
|
|
106
|
+
if not separator:
|
|
107
|
+
name, path = os.path.splitext(os.path.basename(entry))[0], entry
|
|
108
|
+
keys = {name, path, os.path.basename(path), os.path.splitext(os.path.basename(path))[0]}
|
|
109
|
+
references.append((name, os.path.abspath(path), keys))
|
|
110
|
+
return references
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def check_view(name: str, rgba: np.ndarray, parts: dict, crop, options) -> tuple:
|
|
114
|
+
"""
|
|
115
|
+
Checks one reference: coverage, unclaimed regions, overlaps, and its picture.
|
|
116
|
+
|
|
117
|
+
:returns: (the view's result, its tile picture).
|
|
118
|
+
"""
|
|
119
|
+
height, width = rgba.shape[:2]
|
|
120
|
+
silhouette = overlay_sheet.subject(rgba, options.background_tolerance, crop)
|
|
121
|
+
area = float(silhouette.sum())
|
|
122
|
+
if area == 0:
|
|
123
|
+
raise ValueError(f"reference '{name}' holds no subject")
|
|
124
|
+
masks = {}
|
|
125
|
+
for part, region in parts.items():
|
|
126
|
+
mask = np.zeros((height, width), dtype=bool)
|
|
127
|
+
for polygon in region_polygons(region):
|
|
128
|
+
mask |= image_measure.fill_polygon(height, width, polygon)
|
|
129
|
+
masks[part] = mask
|
|
130
|
+
claimed = np.zeros((height, width), dtype=bool)
|
|
131
|
+
for mask in masks.values():
|
|
132
|
+
claimed |= mask
|
|
133
|
+
unclaimed = silhouette & ~claimed
|
|
134
|
+
minimum_pixels = max(1, int(np.ceil(options.min_region_percent / 100.0 * area)))
|
|
135
|
+
unclaimed_regions = [{"bbox": region["bbox"], "centroid": region["centroid"], "area_px": region["area_px"],
|
|
136
|
+
"area_percent": round(100.0 * region["area_px"] / area, 2)}
|
|
137
|
+
for region in image_measure.component_regions(unclaimed, minimum_pixels)]
|
|
138
|
+
overlaps = []
|
|
139
|
+
for first, second in itertools.combinations(masks, 2):
|
|
140
|
+
shared = int((masks[first] & masks[second] & silhouette).sum())
|
|
141
|
+
if shared:
|
|
142
|
+
overlaps.append({"parts": [first, second], "area_px": shared, "area_percent": round(100.0 * shared / area, 2)})
|
|
143
|
+
part_reports = {part: {"silhouette_percent": round(100.0 * float((mask & silhouette).sum()) / area, 2),
|
|
144
|
+
"outside_silhouette_percent": round(100.0 * float((mask & ~silhouette).sum()) / max(1.0, float(mask.sum())), 2)}
|
|
145
|
+
for part, mask in masks.items()}
|
|
146
|
+
coverage = round(100.0 * float((silhouette & claimed).sum()) / area, 2)
|
|
147
|
+
passed = coverage >= options.min_coverage
|
|
148
|
+
result = {"name": name, "coverage_percent": coverage, "unclaimed_percent": round(100.0 - coverage, 2),
|
|
149
|
+
"pass": passed, "unclaimed_regions": unclaimed_regions, "overlaps": overlaps, "parts": part_reports}
|
|
150
|
+
return result, draw_tile(rgba, silhouette, masks, unclaimed, parts, options.tile)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def draw_tile(rgba: np.ndarray, silhouette: np.ndarray, masks: dict, unclaimed: np.ndarray, parts: dict,
|
|
154
|
+
tile_pixels: int) -> np.ndarray:
|
|
155
|
+
"""Each part's region in its colour, overlaps in white, unclaimed silhouette in red, part names on top."""
|
|
156
|
+
height, width = silhouette.shape
|
|
157
|
+
scale = evidence_sheet.fit_scale(height, width, tile_pixels)
|
|
158
|
+
tile_height, tile_width = max(1, round(height * scale)), max(1, round(width * scale))
|
|
159
|
+
picture = evidence_sheet.dimmed(evidence_sheet.resize(rgba, tile_height, tile_width))
|
|
160
|
+
small_silhouette = evidence_sheet.resize_mask(silhouette, tile_height, tile_width)
|
|
161
|
+
coverage_count = np.zeros((tile_height, tile_width), dtype=np.int32)
|
|
162
|
+
for index, (part, mask) in enumerate(masks.items()):
|
|
163
|
+
small = evidence_sheet.resize_mask(mask, tile_height, tile_width)
|
|
164
|
+
coverage_count += small
|
|
165
|
+
color = PART_COLORS[index % len(PART_COLORS)]
|
|
166
|
+
evidence_sheet.tint(picture, small & small_silhouette, color, PART_STRENGTH)
|
|
167
|
+
for polygon in region_polygons(parts[part]):
|
|
168
|
+
image_measure.draw_polyline(picture, polygon * scale, color, OUTLINE_PIXELS)
|
|
169
|
+
evidence_sheet.tint(picture, (coverage_count > 1) & small_silhouette, OVERLAP_COLOR, OVERLAP_STRENGTH)
|
|
170
|
+
evidence_sheet.tint(picture, evidence_sheet.resize_mask(unclaimed, tile_height, tile_width), UNCLAIMED_COLOR,
|
|
171
|
+
UNCLAIMED_STRENGTH)
|
|
172
|
+
for index, part in enumerate(masks):
|
|
173
|
+
polygons = region_polygons(parts[part])
|
|
174
|
+
center = np.concatenate(polygons).mean(axis=0) * scale
|
|
175
|
+
text_width, text_height = evidence_sheet.text_size(part)
|
|
176
|
+
evidence_sheet.draw_text(picture, part, int(center[0] - text_width / 2), int(center[1] - text_height / 2),
|
|
177
|
+
PART_COLORS[index % len(PART_COLORS)])
|
|
178
|
+
return picture
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def run(options) -> dict:
|
|
182
|
+
"""
|
|
183
|
+
Checks every reference against its parts and writes the picture and the JSON.
|
|
184
|
+
|
|
185
|
+
:param options: Parsed options.
|
|
186
|
+
:returns: The tool result.
|
|
187
|
+
"""
|
|
188
|
+
crops = overlay_sheet.parse_crops(options.crop)
|
|
189
|
+
views = (tool_common.load_json(options.parts).get("views") or {})
|
|
190
|
+
if not views:
|
|
191
|
+
raise ValueError(f"{options.parts} has no views")
|
|
192
|
+
results, tiles, matched = [], [], set()
|
|
193
|
+
for name, path, keys in _references(options.reference):
|
|
194
|
+
key = next((candidate for candidate in views if candidate in keys), None)
|
|
195
|
+
if key is None:
|
|
196
|
+
raise ValueError(f"coverage.json has no parts for reference '{name}' (use one of {sorted(keys)} as its key)")
|
|
197
|
+
matched.add(key)
|
|
198
|
+
parts = views[key].get("parts") or {}
|
|
199
|
+
if not parts:
|
|
200
|
+
raise ValueError(f"coverage.json view '{key}' has no parts")
|
|
201
|
+
result, tile = check_view(name, tool_common.load_image(path), parts, crops.get(name), options)
|
|
202
|
+
result["reference"] = path
|
|
203
|
+
results.append(result)
|
|
204
|
+
unclaimed = result["unclaimed_regions"]
|
|
205
|
+
lines = [name, f"COVERAGE {result['coverage_percent']:.1f}% UNCLAIMED {result['unclaimed_percent']:.1f}% "
|
|
206
|
+
f"OVERLAPS {len(result['overlaps'])}", evidence_sheet.verdict(result["pass"])]
|
|
207
|
+
if unclaimed:
|
|
208
|
+
lines.append((f"LARGEST UNCLAIMED {unclaimed[0]['area_percent']:.1f}% AT {unclaimed[0]['bbox']}", UNCLAIMED_COLOR))
|
|
209
|
+
tiles.append((lines, tile))
|
|
210
|
+
unused = sorted(set(views) - matched)
|
|
211
|
+
out_path = os.path.abspath(options.out)
|
|
212
|
+
report = {"pass": all(result["pass"] for result in results), "min_coverage_percent": options.min_coverage,
|
|
213
|
+
"views": results, "unused_coverage_views": unused,
|
|
214
|
+
"picture": tool_common.save_image(out_path, evidence_sheet.compose_sheet(
|
|
215
|
+
tiles, title_lines=["EACH PART IN ITS COLOUR WHITE OVERLAP RED UNCLAIMED"]))}
|
|
216
|
+
report["report_json"] = tool_common.write_json(os.path.splitext(out_path)[0] + ".json", report)
|
|
217
|
+
return report
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
if __name__ == "__main__":
|
|
221
|
+
tool_common.run_tool(TOOL_NAME, build_parser(), run)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Evidence sheets for bt-blender: labelled tiles of several views on one image, region shading and outline
|
|
3
|
+
drawing, area-averaged resizing and a small built-in bitmap font, so a tool can label its pictures without
|
|
4
|
+
Pillow or a GPU.
|
|
5
|
+
|
|
6
|
+
Pure numpy: no bpy import. Image arrays are float RGB(A) in 0..1, row 0 at the top.
|
|
7
|
+
"""
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
import image_measure
|
|
11
|
+
|
|
12
|
+
# A 5 x 7 bitmap font: '#' is ink. Lower-case text is drawn in capitals; unknown characters as a box.
|
|
13
|
+
GLYPH_WIDTH = 5
|
|
14
|
+
GLYPH_HEIGHT = 7
|
|
15
|
+
GLYPHS = {
|
|
16
|
+
"A": ".###.|#...#|#...#|#####|#...#|#...#|#...#", "B": "####.|#...#|#...#|####.|#...#|#...#|####.",
|
|
17
|
+
"C": ".###.|#...#|#....|#....|#....|#...#|.###.", "D": "####.|#...#|#...#|#...#|#...#|#...#|####.",
|
|
18
|
+
"E": "#####|#....|#....|####.|#....|#....|#####", "F": "#####|#....|#....|####.|#....|#....|#....",
|
|
19
|
+
"G": ".###.|#...#|#....|#.###|#...#|#...#|.####", "H": "#...#|#...#|#...#|#####|#...#|#...#|#...#",
|
|
20
|
+
"I": ".###.|..#..|..#..|..#..|..#..|..#..|.###.", "J": "..###|...#.|...#.|...#.|...#.|#..#.|.##..",
|
|
21
|
+
"K": "#...#|#..#.|#.#..|##...|#.#..|#..#.|#...#", "L": "#....|#....|#....|#....|#....|#....|#####",
|
|
22
|
+
"M": "#...#|##.##|#.#.#|#.#.#|#...#|#...#|#...#", "N": "#...#|##..#|#.#.#|#..##|#...#|#...#|#...#",
|
|
23
|
+
"O": ".###.|#...#|#...#|#...#|#...#|#...#|.###.", "P": "####.|#...#|#...#|####.|#....|#....|#....",
|
|
24
|
+
"Q": ".###.|#...#|#...#|#...#|#.#.#|#..#.|.##.#", "R": "####.|#...#|#...#|####.|#.#..|#..#.|#...#",
|
|
25
|
+
"S": ".####|#....|#....|.###.|....#|....#|####.", "T": "#####|..#..|..#..|..#..|..#..|..#..|..#..",
|
|
26
|
+
"U": "#...#|#...#|#...#|#...#|#...#|#...#|.###.", "V": "#...#|#...#|#...#|#...#|#...#|.#.#.|..#..",
|
|
27
|
+
"W": "#...#|#...#|#...#|#.#.#|#.#.#|#.#.#|.#.#.", "X": "#...#|#...#|.#.#.|..#..|.#.#.|#...#|#...#",
|
|
28
|
+
"Y": "#...#|#...#|.#.#.|..#..|..#..|..#..|..#..", "Z": "#####|....#|...#.|..#..|.#...|#....|#####",
|
|
29
|
+
"0": ".###.|#...#|#..##|#.#.#|##..#|#...#|.###.", "1": "..#..|.##..|..#..|..#..|..#..|..#..|.###.",
|
|
30
|
+
"2": ".###.|#...#|....#|...#.|..#..|.#...|#####", "3": "####.|....#|....#|.###.|....#|....#|####.",
|
|
31
|
+
"4": "...#.|..##.|.#.#.|#..#.|#####|...#.|...#.", "5": "#####|#....|####.|....#|....#|#...#|.###.",
|
|
32
|
+
"6": "..##.|.#...|#....|####.|#...#|#...#|.###.", "7": "#####|....#|...#.|..#..|.#...|.#...|.#...",
|
|
33
|
+
"8": ".###.|#...#|#...#|.###.|#...#|#...#|.###.", "9": ".###.|#...#|#...#|.####|....#|...#.|.##..",
|
|
34
|
+
" ": ".....|.....|.....|.....|.....|.....|.....", ".": ".....|.....|.....|.....|.....|.##..|.##..",
|
|
35
|
+
",": ".....|.....|.....|.....|.##..|..#..|.#...", ":": ".....|.##..|.##..|.....|.##..|.##..|.....",
|
|
36
|
+
"%": "##..#|##..#|...#.|..#..|.#...|#..##|#..##", "-": ".....|.....|.....|#####|.....|.....|.....",
|
|
37
|
+
"_": ".....|.....|.....|.....|.....|.....|#####", "/": "....#|....#|...#.|..#..|.#...|#....|#....",
|
|
38
|
+
"=": ".....|.....|#####|.....|#####|.....|.....", "(": "...#.|..#..|.#...|.#...|.#...|..#..|...#.",
|
|
39
|
+
")": ".#...|..#..|...#.|...#.|...#.|..#..|.#...", "+": ".....|..#..|..#..|#####|..#..|..#..|.....",
|
|
40
|
+
"<": "...#.|..#..|.#...|#....|.#...|..#..|...#.", ">": ".#...|..#..|...#.|....#|...#.|..#..|.#...",
|
|
41
|
+
"[": ".###.|.#...|.#...|.#...|.#...|.#...|.###.", "]": ".###.|...#.|...#.|...#.|...#.|...#.|.###.",
|
|
42
|
+
"#": ".#.#.|.#.#.|#####|.#.#.|#####|.#.#.|.#.#.", "*": ".....|#.#.#|.###.|#####|.###.|#.#.#|.....",
|
|
43
|
+
"?": ".###.|#...#|....#|...#.|..#..|.....|..#..", "'": "..#..|..#..|.#...|.....|.....|.....|.....",
|
|
44
|
+
}
|
|
45
|
+
UNKNOWN_GLYPH = "#####|#...#|#...#|#...#|#...#|#...#|#####"
|
|
46
|
+
|
|
47
|
+
# Ink pixels per font pixel, the gap between characters and between lines (font pixels).
|
|
48
|
+
DEFAULT_TEXT_SCALE = 2
|
|
49
|
+
CHARACTER_GAP = 1
|
|
50
|
+
LINE_GAP = 3
|
|
51
|
+
|
|
52
|
+
# Label strip padding (pixels) and colours.
|
|
53
|
+
LABEL_PADDING = 6
|
|
54
|
+
LABEL_BACKGROUND = (0.1, 0.1, 0.12)
|
|
55
|
+
LABEL_TEXT = (0.95, 0.95, 0.95)
|
|
56
|
+
SHEET_BACKGROUND = (0.06, 0.06, 0.07)
|
|
57
|
+
TILE_GAP = 8
|
|
58
|
+
|
|
59
|
+
# Pass / fail label colours.
|
|
60
|
+
PASS_COLOR = (0.35, 0.85, 0.45)
|
|
61
|
+
FAIL_COLOR = (0.95, 0.35, 0.3)
|
|
62
|
+
|
|
63
|
+
# Share of the reference image kept when it is dimmed under evidence drawing.
|
|
64
|
+
DIM_SHARE = 0.55
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _glyph(character: str) -> np.ndarray:
|
|
68
|
+
"""A character's ink as a boolean (7, 5) array."""
|
|
69
|
+
rows = GLYPHS.get(character.upper(), UNKNOWN_GLYPH).split("|")
|
|
70
|
+
return np.array([[cell == "#" for cell in row] for row in rows], dtype=bool)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def text_size(text: str, scale: int = DEFAULT_TEXT_SCALE) -> tuple:
|
|
74
|
+
"""
|
|
75
|
+
The pixel size a single line of text takes.
|
|
76
|
+
|
|
77
|
+
:param text: The text.
|
|
78
|
+
:param scale: Ink pixels per font pixel.
|
|
79
|
+
:returns: (width, height) in pixels.
|
|
80
|
+
"""
|
|
81
|
+
return max(0, len(text) * (GLYPH_WIDTH + CHARACTER_GAP) - CHARACTER_GAP) * scale, GLYPH_HEIGHT * scale
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def draw_text(image: np.ndarray, text: str, column: int, row: int, color, scale: int = DEFAULT_TEXT_SCALE) -> None:
|
|
85
|
+
"""
|
|
86
|
+
Draws one line of text into an RGB(A) float image in place, clipped to the image.
|
|
87
|
+
|
|
88
|
+
:param image: (height, width, 3 or 4) float array.
|
|
89
|
+
:param text: The text.
|
|
90
|
+
:param column: Left edge of the text, pixels.
|
|
91
|
+
:param row: Top edge of the text, pixels.
|
|
92
|
+
:param color: RGB tuple 0..1.
|
|
93
|
+
:param scale: Ink pixels per font pixel.
|
|
94
|
+
"""
|
|
95
|
+
height, width = image.shape[:2]
|
|
96
|
+
for index, character in enumerate(text):
|
|
97
|
+
ink = np.repeat(np.repeat(_glyph(character), scale, axis=0), scale, axis=1)
|
|
98
|
+
left = column + index * (GLYPH_WIDTH + CHARACTER_GAP) * scale
|
|
99
|
+
rows, columns = np.nonzero(ink)
|
|
100
|
+
rows, columns = rows + row, columns + left
|
|
101
|
+
keep = (rows >= 0) & (rows < height) & (columns >= 0) & (columns < width)
|
|
102
|
+
image[rows[keep], columns[keep], :3] = color
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _area_weights(source_size: int, target_size: int) -> np.ndarray:
|
|
106
|
+
"""(target, source) matrix that averages the source cells covering each target cell."""
|
|
107
|
+
edges = np.linspace(0.0, source_size, target_size + 1)
|
|
108
|
+
cells = np.arange(source_size)
|
|
109
|
+
overlap = np.clip(np.minimum(edges[1:, None], cells[None, :] + 1.0) - np.maximum(edges[:-1, None], cells[None, :]), 0.0, None)
|
|
110
|
+
return overlap / overlap.sum(axis=1, keepdims=True)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def resize(image: np.ndarray, height: int, width: int) -> np.ndarray:
|
|
114
|
+
"""
|
|
115
|
+
Resizes an image or mask by area averaging (no aliasing when shrinking).
|
|
116
|
+
|
|
117
|
+
:param image: (height, width) or (height, width, channels) array.
|
|
118
|
+
:param height: Target height.
|
|
119
|
+
:param width: Target width.
|
|
120
|
+
:returns: float32 array of the target size (same channel count).
|
|
121
|
+
"""
|
|
122
|
+
rows = _area_weights(image.shape[0], height)
|
|
123
|
+
columns = _area_weights(image.shape[1], width)
|
|
124
|
+
values = image.astype(np.float32)
|
|
125
|
+
if values.ndim == 2:
|
|
126
|
+
return (rows @ values @ columns.T).astype(np.float32)
|
|
127
|
+
return np.stack([rows @ values[:, :, channel] @ columns.T for channel in range(values.shape[2])], axis=2).astype(np.float32)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def resize_mask(mask: np.ndarray, height: int, width: int) -> np.ndarray:
|
|
131
|
+
"""A boolean mask resized by area: a target pixel is set when at least half of what it covers is."""
|
|
132
|
+
return resize(mask, height, width) >= 0.5
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def dimmed(rgba: np.ndarray, share: float = DIM_SHARE) -> np.ndarray:
|
|
136
|
+
"""The image as grey RGB, pulled towards black, so coloured evidence drawn over it stands out."""
|
|
137
|
+
gray = image_measure.luminance(rgba)[:, :, None]
|
|
138
|
+
return np.repeat(gray * share, 3, axis=2).astype(np.float32)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def tint(image: np.ndarray, mask: np.ndarray, color, strength: float) -> None:
|
|
142
|
+
"""
|
|
143
|
+
Blends a colour over the masked pixels in place.
|
|
144
|
+
|
|
145
|
+
:param image: (height, width, 3+) float array.
|
|
146
|
+
:param mask: Boolean (height, width).
|
|
147
|
+
:param color: RGB tuple 0..1.
|
|
148
|
+
:param strength: 0 keeps the image, 1 paints the colour solid.
|
|
149
|
+
"""
|
|
150
|
+
image[mask, :3] = image[mask, :3] * (1.0 - strength) + np.array(color, dtype=np.float32) * strength
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def draw_mask_outline(image: np.ndarray, mask: np.ndarray, color, thickness: int = 1) -> None:
|
|
154
|
+
"""
|
|
155
|
+
Paints the inner edge of a mask (pixels with a neighbour outside it) in place.
|
|
156
|
+
|
|
157
|
+
:param image: (height, width, 3+) float array.
|
|
158
|
+
:param mask: Boolean (height, width).
|
|
159
|
+
:param color: RGB tuple 0..1.
|
|
160
|
+
:param thickness: Edge width in pixels.
|
|
161
|
+
"""
|
|
162
|
+
edge = mask & ~image_measure.erode(mask, thickness)
|
|
163
|
+
image[edge, :3] = color
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def draw_box(image: np.ndarray, box, color, thickness: int = 1) -> None:
|
|
167
|
+
"""
|
|
168
|
+
Draws a rectangle outline in place.
|
|
169
|
+
|
|
170
|
+
:param image: (height, width, 3+) float array.
|
|
171
|
+
:param box: [left, top, right, bottom] in pixels (right / bottom exclusive).
|
|
172
|
+
:param color: RGB tuple 0..1.
|
|
173
|
+
:param thickness: Line thickness in pixels.
|
|
174
|
+
"""
|
|
175
|
+
left, top, right, bottom = (float(value) for value in box)
|
|
176
|
+
corners = np.array([[left, top], [right - 1, top], [right - 1, bottom - 1], [left, bottom - 1]])
|
|
177
|
+
image_measure.draw_polyline(image, corners, color, thickness)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def fit_scale(height: int, width: int, tile_size: int) -> float:
|
|
181
|
+
"""The factor that makes an image's longer side `tile_size` pixels (never above 1)."""
|
|
182
|
+
return min(1.0, tile_size / float(max(height, width)))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _label_strip(lines: list, width: int, scale: int) -> np.ndarray:
|
|
186
|
+
"""A dark strip holding the label lines; each line is text, or (text, colour)."""
|
|
187
|
+
line_height = (GLYPH_HEIGHT + LINE_GAP) * scale
|
|
188
|
+
strip = np.empty((LABEL_PADDING * 2 + line_height * len(lines), width, 3), dtype=np.float32)
|
|
189
|
+
strip[:] = LABEL_BACKGROUND
|
|
190
|
+
for index, line in enumerate(lines):
|
|
191
|
+
text, color = (line, LABEL_TEXT) if isinstance(line, str) else line
|
|
192
|
+
draw_text(strip, text, LABEL_PADDING, LABEL_PADDING + index * line_height, color, scale)
|
|
193
|
+
return strip
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def compose_sheet(tiles: list, columns: int = 0, scale: int = DEFAULT_TEXT_SCALE, title_lines=None) -> np.ndarray:
|
|
197
|
+
"""
|
|
198
|
+
Lays labelled tiles out on one sheet, row by row.
|
|
199
|
+
|
|
200
|
+
:param tiles: [(label lines, RGB image)]; a label line is text or (text, RGB colour).
|
|
201
|
+
:param columns: Tiles per row; 0 picks a near-square grid.
|
|
202
|
+
:param scale: Label text scale.
|
|
203
|
+
:param title_lines: Optional lines (a legend) in a strip across the top of the sheet.
|
|
204
|
+
:returns: The sheet, float32 RGB.
|
|
205
|
+
"""
|
|
206
|
+
if not tiles:
|
|
207
|
+
raise ValueError("no tiles to lay out")
|
|
208
|
+
columns = columns or int(np.ceil(np.sqrt(len(tiles))))
|
|
209
|
+
labelled = []
|
|
210
|
+
for lines, image in tiles:
|
|
211
|
+
widest = max(text_size(line if isinstance(line, str) else line[0], scale)[0] for line in lines) if lines else 0
|
|
212
|
+
width = max(image.shape[1], widest + 2 * LABEL_PADDING)
|
|
213
|
+
body = np.empty((image.shape[0], width, 3), dtype=np.float32)
|
|
214
|
+
body[:] = SHEET_BACKGROUND
|
|
215
|
+
body[:, :image.shape[1]] = image[:, :, :3]
|
|
216
|
+
labelled.append(np.vstack((_label_strip(lines, width, scale), body)))
|
|
217
|
+
grid = [labelled[start:start + columns] for start in range(0, len(labelled), columns)]
|
|
218
|
+
column_widths = [max(row[index].shape[1] for row in grid if index < len(row)) for index in range(columns)]
|
|
219
|
+
row_heights = [max(tile.shape[0] for tile in row) for row in grid]
|
|
220
|
+
sheet = np.empty((sum(row_heights) + TILE_GAP * (len(grid) + 1),
|
|
221
|
+
sum(column_widths) + TILE_GAP * (columns + 1), 3), dtype=np.float32)
|
|
222
|
+
sheet[:] = SHEET_BACKGROUND
|
|
223
|
+
top = TILE_GAP
|
|
224
|
+
for row, row_height in zip(grid, row_heights):
|
|
225
|
+
left = TILE_GAP
|
|
226
|
+
for index, tile in enumerate(row):
|
|
227
|
+
sheet[top:top + tile.shape[0], left:left + tile.shape[1]] = tile
|
|
228
|
+
left += column_widths[index] + TILE_GAP
|
|
229
|
+
top += row_height + TILE_GAP
|
|
230
|
+
if not title_lines:
|
|
231
|
+
return sheet
|
|
232
|
+
widest = max(text_size(line if isinstance(line, str) else line[0], scale)[0] for line in title_lines)
|
|
233
|
+
if widest + 2 * LABEL_PADDING > sheet.shape[1]:
|
|
234
|
+
widened = np.empty((sheet.shape[0], widest + 2 * LABEL_PADDING, 3), dtype=np.float32)
|
|
235
|
+
widened[:] = SHEET_BACKGROUND
|
|
236
|
+
widened[:, :sheet.shape[1]] = sheet
|
|
237
|
+
sheet = widened
|
|
238
|
+
return np.vstack((_label_strip(title_lines, sheet.shape[1], scale), sheet))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def verdict(passed: bool) -> tuple:
|
|
242
|
+
"""A PASS / FAIL label line in its colour."""
|
|
243
|
+
return ("PASS", PASS_COLOR) if passed else ("FAIL", FAIL_COLOR)
|