Credibility pass over the Green Man generator

Turn audit.py into a run() function and drop audit_run.py, which only
existed to import it quietly. Remove unused parameters, keys, helpers
and imports from draw.py, manifest.py and stl_build.py, and the source
file names in stl_build.FILES that pointed at nothing. Keep the brow
strip's taper and knob positions in geom.py only. Correct comments and
docstrings that disagreed with the code, and the README's claim about
counts.

The page changes only in markup: no stray spaces in class attributes,
and three CSS declarations that did nothing are gone. Guide HTML,
templates and print files are byte-identical apart from that.

Credibility pass over a7c04e5..HEAD; the next one can scope from here.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Eric WagonerandClaude Fable 5.2 committed 2026-11-10 19:14:03 -05:00
1 parent b86153a9fd
commit f2bb87caeb
15 files changed
+148 -151

No files matched your search

+3 -2
View File
@@ -20,7 +20,7 @@ After a build, review `git diff` in `../greenman`, then run `../deploy` from the
## What a build does, in order
1. `stl_build.py` writes the eight print files into `out/stl` and tests each one: watertight, flat on the bed, no layer starting in mid-air. The three files in `stl_src` that failed on the printer are run through the same test as a control and must fail it.
2. `audit.py` walks the assembly in step order and checks each step's text against where the parts actually sit.
2. `audit.py` runs the manifest's own layout checks (`manifest.validate()`), then walks the assembly in step order and checks each step's text against where the parts actually sit.
3. `build_templates.py` makes the 1:1 cutting templates (4 pages).
4. `build_guides.py` makes the build guide and the painting guide as PDFs.
5. `build_web.py` makes the web page, with its head, share tags and the links back to the site index.
@@ -37,10 +37,11 @@ After a build, review `git diff` in `../greenman`, then run `../deploy` from the
| Template page layout | `build_templates.py` |
| Web page styling, title, description, share tags | `build_web.py` |
| PDF styling | `build_guides.py` |
| How HTML is rendered to PDF | `shot.py` |
| Generated print files (brow strip, acorns) | `stl_build.py` |
| README inside the kit zip | `assets/kit_README.txt` |
`manifest.py` is the single source for parts and steps. The templates, both guides, the web page and the print set all read from it, so a count changed there changes everywhere.
`manifest.py` is the single source for parts and steps. The templates, both guides, the web page and the print set all take their tables, counts and step order from it. Some sentences spell a number out by hand (in `content.py`, the template notes in `build_templates.py`, the download blurbs in `build_web.py` and `assets/kit_README.txt`), so reread those after changing a count.
## Inputs kept here
+52 -45
View File
@@ -1,48 +1,55 @@
"""Audit: walk the assembly in order and report, for every part, which face it is on, what it is glued to,
what it lies over, and what later covers it. Then check each step's written instructions against those facts."""
import re, manifest as M, content as C, geom as G
base = G.base_glasses()['outline']
P = M.PLACEMENTS; order = list(M.STEPS); problems = []
def name(p): return p['id']
for k in order:
st = M.STEPS[k]; ps = M.step_placements(k)
print(f"\n== {order.index(k)}. {st['title']} (drawing: {st['view']} view)")
for p in ps:
if p['shape'] is None: continue
same = [q for q in P if q is not p and q['shape'] is not None and q['face'] == p['face']]
fp = p['footprint']
under = [name(q) for q in same if q['seq'] < p['seq'] and fp is not None and q['shape'].intersection(fp).area > 1]
over_earlier = [name(q) for q in same if q['seq'] < p['seq'] and q['shape'].intersection(p['shape']).area > 15 and name(q) not in under]
covered_later = [name(q) for q in same if q['seq'] > p['seq'] and fp is not None and q['shape'].intersection(fp).area > 1]
on_base = fp.intersection(base).area / fp.area if fp is not None and fp.area else 0
print(f" {name(p):16s} face={p['face']:6s} glue={p['glue']:7s} on-foam={on_base:4.0%} glued over: {under or '-'} lies across: {over_earlier or '-'} glue spot later covered by: {covered_later or '-'}")
# --- text checks
t = C.STEP[k]; text = re.sub(r'<[^>]+>', '', ' '.join(t['do']) + ' ' + t['check'])
faces = {p['face'] for p in ps if p['face'] in ('front', 'back') and p['part'] not in ('STRAP',)}
for f in faces:
if not re.search(rf'\b{f}\b', text): problems.append(f"step '{k}': parts go on the {f} but the text never says '{f}'")
wrong = {'front': 'back', 'back': 'front'}
for f in faces:
if len(faces) == 1 and re.search(rf'(to|on|onto) the (<b>)?{wrong[f]}(</b>)? of the band', ' '.join(t['do'])): problems.append(f"step '{k}': text says {wrong[f]} of the band, parts are on the {f}")
view = 'back' if st['view'] in ('back', 'both') else 'front'
if faces and view not in faces: problems.append(f"step '{k}': drawing is a {view} view but its parts are on the {faces}")
glues = {p['glue'] for p in ps} - {'none', 'wire'}
gl = t['glue'].lower()
if 'contact' in glues and 'cement' not in gl: problems.append(f"step '{k}': uses contact cement but the header says '{t['glue']}'")
if 'hot' in glues and 'hot' not in gl: problems.append(f"step '{k}': uses hot glue but the header says '{t['glue']}'")
# numbers in the text vs geometry
for p in ps:
if p['part'] in 'LMS' and p['x'] and k in ('back', 'centre', 'front'):
if not re.search(rf"\b{abs(round(p['x']))} mm", text): problems.append(f"step '{k}': {name(p)} sits {abs(round(p['x']))} mm from centre; text does not give that distance")
a = abs(round(p['ang']))
if a and not re.search(rf"\b{a}°", text): problems.append(f"step '{k}': {name(p)} leans {a} deg; text does not give that angle")
# chips = manifest counts
for part, n in C.step_counts(k).items():
if part in C.SHORT and C.qty(part, n) not in C.step_parts(k): problems.append(f"step '{k}': chip for {part} missing")
# cross-document mentions of twigs / faces
allsrc = open(C.__file__).read()
for m in re.finditer(r"[^.'\n]{0,80}twig[^.'\n]{0,80}", allsrc):
if re.search(r'behind|backs? of', m.group(0)): problems.append('twig text still says behind/back: ' + m.group(0).strip()[:140])
print('\n== text vs layout problems:', len(problems))
for p in problems: print(' -', p)
print('manifest problems:', len(M.validate(verbose=False)))
def run(verbose=True):
"""Return every problem found, including manifest.validate()'s. With verbose, print the walk-through too."""
say = print if verbose else (lambda *a: None)
base = G.base_glasses()['outline']
P = M.PLACEMENTS; order = list(M.STEPS); problems = []
for k in order:
st = M.STEPS[k]; ps = M.step_placements(k)
say(f"\n== {order.index(k)}. {st['title']} (drawing: {st['view']} view)")
for p in ps:
if p['shape'] is None: continue
same = [q for q in P if q is not p and q['shape'] is not None and q['face'] == p['face']]
fp = p['footprint']
under = [q['id'] for q in same if q['seq'] < p['seq'] and fp is not None and q['shape'].intersection(fp).area > 1]
over_earlier = [q['id'] for q in same if q['seq'] < p['seq'] and q['shape'].intersection(p['shape']).area > 15 and q['id'] not in under]
covered_later = [q['id'] for q in same if q['seq'] > p['seq'] and fp is not None and q['shape'].intersection(fp).area > 1]
on_base = fp.intersection(base).area / fp.area if fp is not None and fp.area else 0
say(f" {p['id']:16s} face={p['face']:6s} glue={p['glue']:7s} on-foam={on_base:4.0%} glued over: {under or '-'} lies across: {over_earlier or '-'} glue spot later covered by: {covered_later or '-'}")
# --- text checks
t = C.STEP[k]; text = re.sub(r'<[^>]+>', '', ' '.join(t['do']) + ' ' + t['check'])
faces = {p['face'] for p in ps if p['face'] in ('front', 'back') and p['part'] != 'STRAP'}
for f in faces:
if not re.search(rf'\b{f}\b', text): problems.append(f"step '{k}': parts go on the {f} but the text never says '{f}'")
wrong = {'front': 'back', 'back': 'front'}
for f in faces:
if len(faces) == 1 and re.search(rf'(to|on|onto) the (<b>)?{wrong[f]}(</b>)? of the band', ' '.join(t['do'])): problems.append(f"step '{k}': text says {wrong[f]} of the band, parts are on the {f}")
view = 'back' if st['view'] in ('back', 'both') else 'front'
if faces and view not in faces: problems.append(f"step '{k}': drawing is a {view} view but its parts are on the {faces}")
glues = {p['glue'] for p in ps} - {'none', 'wire'}
gl = t['glue'].lower()
if 'contact' in glues and 'cement' not in gl: problems.append(f"step '{k}': uses contact cement but the header says '{t['glue']}'")
if 'hot' in glues and 'hot' not in gl: problems.append(f"step '{k}': uses hot glue but the header says '{t['glue']}'")
# numbers in the text vs geometry
for p in ps:
if p['part'] in 'LMS' and p['x'] and k in ('back', 'centre', 'front'):
if not re.search(rf"\b{abs(round(p['x']))} mm", text): problems.append(f"step '{k}': {p['id']} sits {abs(round(p['x']))} mm from centre; text does not give that distance")
a = abs(round(p['ang']))
if a and not re.search(rf"\b{a}°", text): problems.append(f"step '{k}': {p['id']} leans {a} deg; text does not give that angle")
# chips = manifest counts
for part, n in C.step_counts(k).items():
if part in C.SHORT and C.qty(part, n) not in C.step_parts(k): problems.append(f"step '{k}': chip for {part} missing")
# twigs are glued to the front; no sentence anywhere in the guides may put them behind the leaves
for m in re.finditer(r"[^.'\n]{0,80}twig[^.'\n]{0,80}", open(C.__file__).read()):
if re.search(r'behind|backs? of', m.group(0)): problems.append('twigs go on the front, but the text says behind/back: ' + m.group(0).strip()[:140])
layout = M.validate(verbose=False)
say('\n== text vs layout problems:', len(problems))
for p in problems: say(' -', p)
say('manifest problems:', len(layout))
return problems + layout
if __name__ == '__main__':
import sys; sys.exit(1 if run() else 0)
-11
View File
@@ -1,11 +0,0 @@
"""Run audit.py quietly and return its problems, for build.py. Run audit.py itself to read the full walk-through."""
import contextlib, io, importlib
def run():
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
import audit, manifest
importlib.reload(audit)
probs = list(audit.problems) + list(manifest.validate(verbose=False))
print(f'audit: {len(probs)} problems')
return probs
+5 -4
View File
@@ -11,9 +11,9 @@
Order matters: the print files are checked first because the guides quote the results."""
import shutil, sys, zipfile
from pathlib import Path
from paths import ROOT, OUT, ASSETS, SITE
from paths import OUT, ASSETS, SITE
STAMP = (2026, 1, 1, 0, 0, 0) # fixed date inside the zips, so an unchanged kit gives an unchanged zip
STAMP = (2026, 1, 1, 0, 0, 0) # fixed date inside the zips, so a zip changes only when its contents do
def zip_write(path, entries):
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as z:
@@ -27,8 +27,9 @@ def main(publish=True):
bad = {n: r['verdict'] for n, r in report.items() if r['verdict'].startswith('FAIL')}
assert not bad, f'print files failed the printability check: {bad}'
import audit_run
problems = audit_run.run()
import audit
problems = audit.run(verbose=False)
print(f'audit: {len(problems)} problems')
assert not problems, f'audit found problems: {problems}'
import build_templates, build_guides, build_web
pdfs = [build_templates.build(), build_guides.build('build'), build_guides.build('paint')]
+4 -4
View File
@@ -1,5 +1,5 @@
"""Build the two guide PDFs (US Letter portrait) from content.py."""
import asyncio, os, shutil
import asyncio, shutil
import content as C, shot, fonts
from paths import OUT, ASSETS
@@ -48,8 +48,8 @@ table.dense { font-size: 7.3pt; } table.dense td, table.dense th { padding-right
.leafstrip { display: grid; grid-template-columns: repeat(5, 1fr); gap: 1.5mm; } .leafstrip figcaption { text-align: center; }
'''
def link_images():
"""The guides load photos from img/ beside the HTML, so mirror the assets there."""
def copy_images():
"""The guides load photos from img/ beside the HTML, so copy the assets there."""
dst = OUT / 'img'
if dst.exists(): shutil.rmtree(dst)
shutil.copytree(ASSETS / 'img', dst)
@@ -58,7 +58,7 @@ def build(kind):
body = C.construction() if kind == 'build' else C.painting()
title = 'Green Man mask · build guide' if kind == 'build' else 'Green Man mask · painting guide'
html = f'<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{title}</title><style>{fonts.CSS}{CSS}</style></head><body>{body}</body></html>'
link_images(); src = str(OUT / f'_{kind}.html'); open(src, 'w').write(html)
copy_images(); src = str(OUT / f'_{kind}.html'); open(src, 'w').write(html)
out = str(OUT / f'GreenMan_{"build" if kind == "build" else "painting"}_guide.pdf')
asyncio.run(shot.go(src, out, footer=title)); return out
+9 -9
View File
@@ -1,7 +1,7 @@
"""1:1 cutting templates, US Letter landscape (content also fits A4). Counts come from the manifest."""
import os, asyncio
"""1:1 cutting templates, US Letter landscape (content also fits A4). Leaf counts come from the manifest."""
import asyncio
from collections import Counter
import geom as G, manifest as M, draw as D
import geom as G, manifest as M
from draw import f, path, line
from geom import TOP
import shot, fonts
@@ -68,23 +68,23 @@ def base_page(base, n, total):
return page(body, title, sub, n, total)
def leaf_counts():
"""(size, variant) -> [as drawn, flipped], from the manifest; spares are added to variant 0 as drawn."""
"""(size, variant) -> how many to cut, from the manifest; spares are counted under variant B."""
c = Counter()
for p in M.PLACEMENTS:
if p['part'] in 'LMST': c[(p['part'], p['variant'], bool(p['flip']))] += 1
for k, n in M.SPARES.items(): c[(k, 1, False)] += n
if p['part'] in 'LMST': c[(p['part'], p['variant'])] += 1
for k, n in M.SPARES.items(): c[(k, 1)] += n
return c
def leaf_cell(size, variant, cx, base_y, c):
name = {'L': 'Large', 'M': 'Medium', 'S': 'Small', 'T': 'Tip'}[size] + ' ' + 'AB'[variant]
leaf = G.oak(size, variant); n0, n1 = c[(size, variant, False)], c[(size, variant, True)]
leaf = G.oak(size, variant); n = c[(size, variant)]
g = f'<g transform="translate({f(cx)} {f(base_y)})"><path d="{path(leaf)}" fill="none" stroke="{CUT}" stroke-width="0.5" stroke-linejoin="round" class="cut"/>'
g += f'<path d="{" ".join(line(l) for l in G.vein_lines(size, variant))}" fill="none" stroke="{GUIDE}" stroke-width="0.25" stroke-dasharray="1.5 1.2"/></g>'
y = base_y + G.STEM_L + 6
g += T(cx, y, name, 3.3, 700, anchor='middle')
box = lambda k: ''.join(f'<rect x="{f(cx - k*2.6 + i*5.2 + 0.6)}" y="{f(y+7.2)}" width="4" height="4" fill="none" stroke="#111" stroke-width="0.3"/>' for i in range(k))
g += T(cx, y+4.8, f'cut {n0 + n1}', 2.9, 600, anchor='middle') + box(n0 + n1)
return g, n0 + n1
g += T(cx, y+4.8, f'cut {n}', 2.9, 600, anchor='middle') + box(n)
return g, n
def leaf_pages(n0, total):
c = leaf_counts(); ml = M.make_list(); pages = []
+4 -6
View File
@@ -1,6 +1,6 @@
"""Web page version of both guides, plus downloads, as it is published on the builds site.
Photos, PDFs and the zips sit beside the page in img/ and dl/."""
import re, importlib
import re
import content as C
from paths import OUT
@@ -62,24 +62,22 @@ table.dense { font-size: 0.8rem; min-width: 760px; }
.stl-grid figure { background: var(--paper); border-radius: 6px; padding: 4px 4px 8px; } .stl-grid figcaption { text-align: center; color: var(--paper-fg); margin: 0; font-size: 0.72rem; }
.leafstrip { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; } .leafstrip figcaption { text-align: center; }
.dl { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; margin-bottom: 10px; }
.dl .dlbtn { text-decoration: none; text-align: left; font: inherit; color: var(--fg); background: var(--surface); border: 1px solid var(--line); border-radius: 6px; padding: 14px 16px; cursor: pointer; display: grid; gap: 4px; }
.dl .dlbtn { text-decoration: none; color: var(--fg); background: var(--surface); border: 1px solid var(--line); border-radius: 6px; padding: 14px 16px; display: grid; gap: 4px; }
.dl .dlbtn:hover, .dl .dlbtn:focus-visible { border-color: var(--accent); outline: none; text-decoration: none; } .dl .dlbtn:hover b, .dl .dlbtn:focus-visible b { color: var(--accent); }
.dl .dlbtn b { font-family: var(--display); font-size: 1.2rem; font-weight: 500; } .dl .dlbtn span { font-size: 0.82rem; color: var(--muted); }
.home { margin: 0 0 24px; font-size: 0.95rem; } .home a { text-decoration: none; } .home a:hover, .home a:focus-visible { text-decoration: underline; }
.home.foot { margin: 48px 0 0; padding-top: 18px; border-top: 1px solid var(--line); }
@media (max-width: 760px) { .cover, .cols, .step, .stage { grid-template-columns: minmax(0, 1fr); } .cover-photo { max-width: 360px; } .leafstrip { grid-template-columns: repeat(5, minmax(0, 1fr)); } }
@media (max-width: 760px) { .cover, .cols, .step, .stage { grid-template-columns: minmax(0, 1fr); } .cover-photo { max-width: 360px; } }
'''
def wrap_tables(h): return h.replace('<table', '<div class="tw"><table').replace('</table>', '</table></div>')
def build(out=str(OUT / 'index.html')):
importlib.reload(C)
build_html = C.construction(); paint_html = C.painting().replace('<header class="cover">', '<header class="cover guide-start" id="painting">').replace('<h1>Green Man mask</h1>', '<h1>Painting the mask</h1>')
body = C.construction(); paint_html = C.painting().replace('<header class="cover">', '<header class="cover guide-start" id="painting">').replace('<h1>Green Man mask</h1>', '<h1>Painting the mask</h1>')
dls = [('GreenMan_mask_kit.zip', 'Whole kit', 'Templates, both guides, and the 8 print files in one zip'), ('GreenMan_templates.pdf', 'Templates', '4 pages, 1:1, US Letter or A4'),
('GreenMan_build_guide.pdf', 'Build guide', 'Printable, for the workbench'), ('GreenMan_painting_guide.pdf', 'Painting guide', 'Printable'), ('GreenMan_print_files.zip', 'Print files', '8 STL files, no supports needed')]
downloads = ('<section id="downloads"><h2>Downloads</h2><div class="dl">' + ''.join(f'<a class="dlbtn" href="dl/{f}" download><b>{t}</b><span>{d}</span></a>' for f, t, d in dls) + '</div></section>')
nav = '<nav class="top" aria-label="Sections"><a href="#downloads">Downloads</a><a href="#build">Build guide</a><a href="#step-strip">Assembly steps</a><a href="#painting">Painting guide</a></nav>'
body = build_html
i = body.index('</header>') + len('</header>')
body = body[:i] + nav + downloads + '<div id="build"></div>' + body[i:]
home = '<p class="home"><a href="../">\u2190 Kestrel\u2019s Builds</a></p>'
+7 -7
View File
@@ -3,24 +3,24 @@ import json
from collections import Counter, OrderedDict
import geom as G, manifest as M, draw as D
from geom import TOP
from paths import WORK
IMG = 'img/'
from paths import WORK
REPORT = json.load(open(WORK / 'stl_report.json'))
ML = M.make_list()
STEPKEYS = list(M.STEPS)
ASSEMBLY = [k for k in STEPKEYS if not M.STEPS[k].get('prep')]
def photo(name, cap, cls=''): return f'<figure class="photo {cls}"><img src="{IMG}{name}.jpg" alt="{cap}"><figcaption>{cap}</figcaption></figure>'
def fig(svg, cap='', cls=''): return f'<figure class="fig {cls}">{svg}' + (f'<figcaption>{cap}</figcaption>' if cap else '') + '</figure>'
def ul(items, cls=''): return f'<ul class="{cls}">' + ''.join(f'<li>{i}</li>' for i in items) + '</ul>'
def photo(name, cap, cls=''): return f'<figure class="{("photo " + cls).strip()}"><img src="{IMG}{name}.jpg" alt="{cap}"><figcaption>{cap}</figcaption></figure>'
def fig(svg, cap='', cls=''): return f'<figure class="{("fig " + cls).strip()}">{svg}' + (f'<figcaption>{cap}</figcaption>' if cap else '') + '</figure>'
def ul(items): return '<ul>' + ''.join(f'<li>{i}</li>' for i in items) + '</ul>'
def ol(items): return '<ol>' + ''.join(f'<li>{i}</li>' for i in items) + '</ol>'
def table(head, rows, cls='data'): return f'<table class="{cls}"><thead><tr>' + ''.join(f'<th>{h}</th>' for h in head) + '</tr></thead><tbody>' + ''.join('<tr>' + ''.join(f'<td>{c}</td>' for c in r) + '</tr>' for r in rows) + '</tbody></table>'
PLACE = {'strap': 'strap', 'back': 'crown, outer (on the back)', 'centre': 'crown, centre (on the front)', 'front': 'crown, front row', 'cheeks': 'cheeks', 'nose': 'nose', 'tendrils': 'tendril ends',
'clusters': 'temple clusters', 'hang': 'hanging beside the cheeks', 'twigs': 'in the crown, between the leaf rows', 'strip': 'front of the band', 'knot': 'centre of the band'}
def where(pid):
c = Counter(p['step'] for p in M.PLACEMENTS if p['part'] == pid for _ in range(p.get('count', 1)))
c = Counter(p['step'] for p in M.PLACEMENTS if p['part'] == pid for _ in range(p['count']))
if pid == 'BASE': return 'everything is glued to it'
if pid == 'PATCH': return 'back of the band, one behind each strap slit'
if pid == 'SPIRAL': return f'{c["tendrils"]} on the lower cheek tabs, 2 per side'
@@ -203,7 +203,7 @@ SHORT = {'L': ('large leaf', 'large leaves'), 'M': ('medium leaf', 'medium leave
def qty(k, n): return f'{n} {SHORT[k][0 if n == 1 else 1]}'
def step_counts(key):
c = Counter()
for p in M.step_placements(key): c[p['part']] += p.get('count', 1)
for p in M.step_placements(key): c[p['part']] += p['count']
return OrderedDict((k, n) for k, n in c.items() if n)
def step_parts(key): return ''.join(f'<span class="chip">{qty(k, n)}</span>' for k, n in step_counts(key).items())
def piles():
@@ -281,7 +281,7 @@ def construction():
'Snap off the brims. Sand every flat back with 120 grit until it is dull, then wipe with alcohol. Contact cement will not hold on glossy PLA.',
'<b>Form the brow strip.</b> Warm it from the back on the gun’s low setting, moving constantly, until it starts to sag (10 to 15 seconds). Lay it on the curved band, press from the centre outward with a gloved hand, and hold for 30 seconds. Bend in stages; forcing the ends cold will crack it. Do not glue it yet.',
'<b>Dry-fit everything</b> against the front-view drawing in “How it goes together”: strip, knot, acorns over the strap, a few leaves held in place. A part that does not fit your base is much cheaper to notice now.'])}</section>''')
H.append('<section><h2>Stage F · Assembly</h2><p>' + f'{len(ASSEMBLY)} steps' + ', about two hours. Hot glue goes on leaf stems, so every blade can still be lifted to reach behind it. The brow strip and acorns are pressed on first, while the mask can still lie flat. The crown is built up after that, starting with the large leaves. Work with glasses within reach; several checks need them.</p>'
H.append(f'<section><h2>Stage F · Assembly</h2><p>{len(ASSEMBLY)} steps, about two hours. Hot glue goes on leaf stems, so every blade can still be lifted to reach behind it. The brow strip and acorns are pressed on first, while the mask can still lie flat. The crown is built up after that, starting with the large leaves. Work with glasses within reach; several checks need them.</p>'
+ ''.join(step_block(k, i+1) for i, k in enumerate(ASSEMBLY)) + '</section>')
H.append(f'''<section class="keep"><h2>Final fit</h2><div class="cols"><div>{ul([
'Put it on, then your glasses. Walk around, look down, shake your head.',
+17 -18
View File
@@ -1,9 +1,10 @@
"""SVG drawings generated from the manifest. Units are mm (viewBox in mm); y is flipped for SVG."""
import numpy as np
from shapely.geometry import Polygon, MultiPolygon, LineString, Point, box
from shapely.geometry import LineString, Point, box
from shapely import affinity
import geom as G, manifest as M
from geom import TOP
from paths import WORK
VB = (-130.0, -(TOP+156), 260.0, TOP+156+104) # x, y, w, h for the full mask, front or back view
@@ -37,22 +38,22 @@ def line(ls, mirror=False):
def _leaf(p, pal, mirror, hl):
size = p['part']; tone = p.get('tone')
fill = (pal.get(tone) if tone else None) or pal[size]
edge = (pal.get('edge_' + tone) if tone else None) or pal.get('edge')
edge = pal.get('edge_' + tone) if tone else None
vein = (pal.get('vein_' + tone) if tone else None) or pal['vein']
s = f'<path d="{path(p["shape"], mirror)}" fill="{fill}" stroke="{HL if hl else edge or pal["leaf_s"]}" stroke-width="{0.9 if hl else (pal.get("edge_w", 1.0) if edge else 0.45)}" stroke-linejoin="round"/>'
s = f'<path d="{path(p["shape"], mirror)}" fill="{fill}" stroke="{HL if hl else edge or pal["leaf_s"]}" stroke-width="{0.9 if hl else (1.0 if edge else 0.45)}" stroke-linejoin="round"/>'
v = ' '.join(line(G.place(l, p['x'], p['y'], p['ang'], p['flip']), mirror) for l in G.vein_lines(size, p.get('variant', 0)))
return s + f'<path d="{v}" fill="none" stroke="{vein}" stroke-width="{pal.get("vein_w", 0.35)}" stroke-linecap="round"/>'
return s + f'<path d="{v}" fill="none" stroke="{vein}" stroke-width="0.35" stroke-linecap="round"/>'
def _strip(p, pal, mirror, hl):
s = f'<path d="{path(p["shape"], mirror)}" fill="{pal["bark"]}" stroke="{HL if hl else pal["bark_s"]}" stroke-width="{0.9 if hl else 0.5}"/>'
x = np.linspace(-G.STRIP_L/2+4, G.STRIP_L/2-4, 60); grooves = []
for k in range(5):
y = -7 + k*3.5 + 1.6*np.sin(x*0.09+k) + 0.7*np.sin(x*0.31+2*k)
keep = np.abs(y) < (11 - 5*(np.abs(x)/(G.STRIP_L/2))**1.6) - 1.5
keep = np.abs(y) < G.strip_half(x) - 1.5
seg = [(a, b + G.STRIP_Y) for a, b, kk in zip(x, y, keep) if kk]
if len(seg) > 2: grooves.append(line(LineString(seg), mirror))
s += f'<path d="{" ".join(grooves)}" fill="none" stroke="{pal["ridge"]}" stroke-width="0.7" stroke-linecap="round"/>'
for kx in (-52, -26, -5, 16, 40, 58):
for kx in G.STRIP_KNOB_X:
s += f'<ellipse cx="{f((-1 if mirror else 1)*kx)}" cy="{f(-G.STRIP_Y)}" rx="4.2" ry="2.6" fill="{pal["bark"]}" stroke="{pal["ridge"]}" stroke-width="0.6"/>'
return s
@@ -95,9 +96,8 @@ def _part(p, pal, mirror, hl):
if k == 'WIRE': return f'<circle cx="{f((-1 if mirror else 1)*p["x"])}" cy="{f(-p["y"])}" r="1.4" fill="{HL if hl else pal["wire"]}"/>'
return ''
def _base(base, pal, mirror, slits=True):
s = f'<path d="{path(base["outline"], mirror)}" fill="{pal["base"]}" stroke="{pal["base_s"]}" stroke-width="0.6" fill-rule="evenodd" stroke-linejoin="round"/>'
return s
def _base(base, pal, mirror):
return f'<path d="{path(base["outline"], mirror)}" fill="{pal["base"]}" stroke="{pal["base_s"]}" stroke-width="0.6" fill-rule="evenodd" stroke-linejoin="round"/>'
def _glasses(pal):
s = ''.join(f'<path d="{path(G.lens(sg))}" fill="none" stroke="{pal["glasses"]}" stroke-width="1.1"/>' for sg in (-1, 1))
@@ -106,10 +106,10 @@ def _glasses(pal):
s += f'<path d="M{f(sg*(G.FRAME_W/2-3))} {f(-(TOP-4))} L{f(sg*(G.FRAME_W/2+30))} {f(-(TOP-3))}" stroke="{pal["glasses"]}" stroke-width="1.6" stroke-linecap="round" fill="none"/>'
return s
def scene(view='front', done=(), hl=None, palette=None, numbers=False, glasses=True, base=None, hang_wire=True, vb=None, tones=None, extra=''):
def scene(view='front', done=(), hl=None, palette=None, numbers=False, glasses=True, tones=None):
"""One picture of the mask. done = steps already on (ghosted unless palette given); hl = step being added now."""
base = base or G.base_glasses(); mirror = view == 'back'
order = list(M.STEPS); show = set(done) | ({hl} if hl else set())
base = G.base_glasses(); mirror = view == 'back'
show = set(done) | ({hl} if hl else set())
parts = [p for p in M.PLACEMENTS if p['step'] in show]
def pal_for(p):
if palette: return palette
@@ -123,11 +123,11 @@ def scene(view='front', done=(), hl=None, palette=None, numbers=False, glasses=T
body += [_part(p, pal_for(p), False, p['step'] == hl and not palette) for p in backs if p['part'] != 'PATCH']
body.append(_base(base, bpal, False))
for p in fronts:
if p['part'] == 'AF' and hang_wire:
if p['part'] == 'AF':
w = next(q for q in M.PLACEMENTS if q['id'] == p['onto'][0])
body.append(f'<path d="M{f(w["x"])} {f(-w["y"])} Q{f(p["x"])} {f(-w["y"]+2)} {f(p["x"])} {f(-(p["y"]+G.ACORN["AF"][1]/2))}" fill="none" stroke="{pal_for(p)["wire"]}" stroke-width="0.5"/>')
body.append(_part(p, pal_for(p), False, p['step'] == hl and not palette))
if glasses and base['kind'] == 'glasses': body.append(_glasses(bpal))
if glasses: body.append(_glasses(bpal))
else:
body.append(_base(base, bpal, True))
for p in sorted(backs, key=lambda p: p['z']): body.append(_part(p, pal_for(p), True, p['step'] == hl and not palette))
@@ -138,12 +138,11 @@ def scene(view='front', done=(), hl=None, palette=None, numbers=False, glasses=T
body.append(f'<rect x="{f(min(x0, out+(-sg)*30))}" y="{f(-G.SLIT_Y1)}" width="{f(abs(out-x0)+30)}" height="{f(G.SLIT_Y1-G.SLIT_Y0)}" fill="{sp["strap"]}" opacity="0.9"/>')
body.append(f'<rect x="{f(min(x0, out))}" y="{f(-G.SLIT_Y1+2)}" width="{f(abs(out-x0))}" height="{f(G.SLIT_Y1-G.SLIT_Y0-4)}" fill="#6a6a6a" stroke="#fff" stroke-width="0.3" stroke-dasharray="1 1"/>')
if numbers and hl:
seq = [p for p in M.step_placements(hl) if p['footprint'] is not None and p['part'] not in ('STRAP',) and (p['face'] == 'back') == mirror]
seq = [p for p in M.step_placements(hl) if p['footprint'] is not None and p['part'] != 'STRAP' and (p['face'] == 'back') == mirror]
for i, p in enumerate(seq):
c = p['footprint'].centroid; x = (-1 if mirror else 1)*c.x
body.append(f'<circle cx="{f(x)}" cy="{f(-c.y)}" r="3.3" fill="#fff" stroke="{HL}" stroke-width="0.6"/><text x="{f(x)}" y="{f(-c.y+1.25)}" font-size="3.6" font-weight="700" text-anchor="middle" fill="{HL}" font-family="Inter, Helvetica, Arial, sans-serif">{i+1}</text>')
v = vb or VB
return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{f(v[0])} {f(v[1])} {f(v[2])} {f(v[3])}" role="img">{"".join(body)}{extra}</svg>'
return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{" ".join(f(v) for v in VB)}" role="img">{"".join(body)}</svg>'
if __name__ == '__main__':
steps = list(M.STEPS)
@@ -154,4 +153,4 @@ if __name__ == '__main__':
html += f'<div>{scene("back", done=["strap","strip"], hl="back", numbers=True)}</div>'
html += f'<div>{scene("front", done=steps[:8], hl="tendrils", numbers=True)}</div>'
html += f'<div>{scene("front", done=steps[:9], hl="cheeks", numbers=True)}</div>'
open(G.__file__.replace('geom.py', 'work/preview.html'), 'w').write(html + '</body></html>')
open(WORK / 'preview.html', 'w').write(html + '</body></html>')
+11 -4
View File
@@ -62,6 +62,7 @@ def arm_zones(): return [box(min(s*(FRAME_W/2-2), s*(FRAME_W/2+40)), TOP-6, max
# ---- oak leaves ----
LEAF = {'L': (95, 65), 'M': (70, 48), 'S': (48, 33), 'T': (30, 21)} # blade length, width
STEM_L, STEM_W = 12.0, 5.0
def _stem_w(size): return 4.0 if size == 'T' else STEM_W # the tip leaf has a narrower stem
# Two deliberately different leaf shapes per size, so a crown of them does not look stamped out.
# A: broad white-oak leaf, four shallow rounded lobes a side, nearly symmetric.
# B: slimmer leaf with three long lobes a side cut almost to the midrib, the lobes alternating left and right,
@@ -91,7 +92,7 @@ def oak(size, variant=0):
cr, cl = _CTRL[variant]
xr, yr = _half(L, W, cr, rng, 0.04); xl, yl = _half(L, W, cl, rng, 0.04)
blade = Polygon(list(zip(xr, yr)) + [(-a, b) for a, b in reversed(list(zip(xl, yl)))][1:]).buffer(0)
sw = STEM_W if size != 'T' else 4.0
sw = _stem_w(size)
stem = box(-sw/2, -STEM_L, sw/2, L*0.06)
leaf = unary_union([blade, stem]).buffer(0.6, join_style=1).buffer(-0.6, join_style=1)
assert leaf.geom_type == 'Polygon' and leaf.is_valid, f'leaf {size}{variant} is not one piece'
@@ -108,7 +109,7 @@ def vein_lines(size, variant=0):
return out
def stem_tab(size):
sw = STEM_W if size != 'T' else 4.0
sw = _stem_w(size)
return box(-sw/2, -STEM_L, sw/2, 0)
def place(geom, x, y, angle=0.0, flip=False):
@@ -118,15 +119,21 @@ def place(geom, x, y, angle=0.0, flip=False):
# ---- printed parts, front-view outlines ----
STRIP_L = 136.0
STRIP_KNOB_X = (-52, -26, -5, 16, 40, 58) # knobs along the strip's centre line
def strip_half(x, L=STRIP_L):
"""Half the strip's height at x: 11 mm at the centre, tapering to 6 mm at the ends."""
return 11 - 5*(np.abs(x)/(L/2))**1.6
def strip_poly(L=STRIP_L):
"""Brow strip as printed: straight, 22 mm tall at the centre tapering to 12 mm. Centre at (0,0)."""
x = np.linspace(-L/2, L/2, 120); half = 11 - 5*(np.abs(x)/(L/2))**1.6
x = np.linspace(-L/2, L/2, 120); half = strip_half(x, L)
top = half + 1.2*np.sin(x*0.22) + 0.6*np.sin(x*0.53+1); bot = -half + 1.0*np.sin(x*0.19+2)
return Polygon(list(zip(x, top)) + list(zip(x[::-1], bot[::-1]))).buffer(1.5, join_style=1).buffer(-1.5, join_style=1)
STRIP_Y = TOP + 16 # strip centre line on the band
KNOT_R = 21.0
KNOT_C = (0.0, TOP + 16 + 11 + 1 + KNOT_R) # sits on the band just above the strip, touching its top edge
KNOT_C = (0.0, STRIP_Y + 11 + 1 + KNOT_R) # sits on the band just above the strip, touching its top edge
ACORN = {'AL': (30.0, 37.0), 'AS': (22.0, 29.0), 'AF': (27.0, 31.0)} # width, length as printed
def acorn_poly(kind):
+12 -17
View File
@@ -22,12 +22,11 @@ PARTS = OrderedDict([
('TWIG', ('Forked twig', 'twig_forked.stl', 'print')),
('AL', ('Acorn, large half', 'acorn_large_half.stl', 'print')),
('AS', ('Acorn, small half', 'acorn_small_half.stl', 'print')),
('AF', ('Acorn, full (hangs on a line)', 'acorn_full.stl', 'print')),
('AF', ('Acorn, full (hangs on a line)', 'acorn_full.stl', 'print')),
('SPIRAL',('Tendril spiral', 'tendril_spiral.stl', 'print')),
('STRAP', ('Elastic strap, 19-25 mm wide', 'flat elastic, about 45 cm', 'other')),
('WIRE', ('Hanging line, 8 cm', 'fishing line or thin wire', 'other')),
('WIRE', ('Hanging line, 8 cm', 'fishing line or thin wire', 'other')),
])
TOOLS = OrderedDict([('STAMP', ('Leaf vein stamp', 'leaf_vein_stamp.stl'))])
SPARES = {'M': 1, 'S': 2} # cut and keep UNSEALED as repair stock; the only parts not placed
# Assembly steps in order. 'after' lists (step, reason): the reason is printed in the guide.
@@ -46,23 +45,19 @@ STEPS = OrderedDict([
('nose', dict(title='Nose leaf', view='front', after=[('strip', 'its stem sits just under the brow strip')])),
])
def _pair(fn):
out = []
for s in (-1, 1): out += fn(s)
return out
def build_placements():
P = []
def add(pid, part, step, face, glue, shape, footprint, z, x=None, y=None, note='', onto=(), ang=0.0, flip=False, variant=0, count=1):
P.append(dict(id=pid, part=part, step=step, face=face, glue=glue, shape=shape, footprint=footprint, z=z, x=x, y=y, note=note,
def add(pid, part, step, face, glue, shape, footprint, z, x=None, y=None, onto=(), ang=0.0, flip=False, variant=0, count=1):
P.append(dict(id=pid, part=part, step=step, face=face, glue=glue, shape=shape, footprint=footprint, z=z, x=x, y=y,
onto=tuple(onto), ang=ang, flip=flip, variant=variant, count=count))
side = {-1: 'R', 1: 'L'} # wearer's right is at -x in the front view
# --- strap: around the outer edge onto the front, through the slit front-to-back, tail glued to the underside of the strap
patches = G.base_glasses()['patches']
for s in (-1, 1):
run = box(min(s*G.SLIT_X, s*(G.FRAME_W/2+23)), G.SLIT_Y0, max(s*G.SLIT_X, s*(G.FRAME_W/2+23)), G.SLIT_Y1)
add(f'STRAP-front-{side[s]}', 'STRAP', 'strap', 'front', 'none', run, run, 12, s*G.SLIT_X, (G.SLIT_Y0+G.SLIT_Y1)/2, count=1 if s < 0 else 0) # one strap, two ends
add(f'PATCH-{side[s]}', 'PATCH', 'strap', 'back', 'contact', G._common()['patches'][(s+1)//2], G._common()['patches'][(s+1)//2], 1, s*G.SLIT_X, (G.SLIT_Y0+G.SLIT_Y1)/2)
add(f'PATCH-{side[s]}', 'PATCH', 'strap', 'back', 'contact', patches[(s+1)//2], patches[(s+1)//2], 1, s*G.SLIT_X, (G.SLIT_Y0+G.SLIT_Y1)/2)
# --- brow strip and knot
sp = G.place(G.strip_poly(), 0, G.STRIP_Y)
add('STRIP', 'STRIP', 'strip', 'front', 'contact', sp, sp, 20, 0, G.STRIP_Y)
@@ -97,7 +92,7 @@ def build_placements():
for k, (x0, y0, ang) in enumerate([(24, TOP+41, 12), (42, TOP+39, 27), (58, TOP+37, 42)]):
for s in (-1, 1):
add(f'M-front-{side[s]}{k+1}', 'M', 'front', 'front', 'hot', G.place(G.oak('M', k % 2), s*x0, y0, s*ang, flip=s < 0),
G.place(G.stem_tab('M'), s*x0, y0, s*ang), 30+k, s*x0, y0, note=f'{ang} deg out', ang=s*ang, flip=s < 0, variant=k % 2)
G.place(G.stem_tab('M'), s*x0, y0, s*ang), 30+k, s*x0, y0, ang=s*ang, flip=s < 0, variant=k % 2)
# --- hanging acorns: wire glued to the top of the cheek tab, later covered by the medium cheek leaf stem
for s in (-1, 1):
anchor = Point(s*88, 13).buffer(3)
@@ -118,7 +113,7 @@ def build_placements():
# --- nose leaf
add('S-nose', 'S', 'nose', 'front', 'hot', G.place(G.oak('S', 1), 0, TOP-8, 180), G.place(G.stem_tab('S'), 0, TOP-8, 180), 46, 0, TOP-8, ang=180, variant=1)
order = list(STEPS)
P.sort(key=lambda p: (order.index(p['step']),)) # stable: keeps authoring order inside a step
P.sort(key=lambda p: order.index(p['step'])) # stable: keeps authoring order inside a step
for i, p in enumerate(P): p['seq'] = i
return P
@@ -127,7 +122,7 @@ PLACEMENTS = build_placements()
def counts():
"""Number of each part actually placed."""
c = Counter()
for p in PLACEMENTS: c[p['part']] += p.get('count', 1)
for p in PLACEMENTS: c[p['part']] += p['count']
return c
def make_list():
@@ -166,9 +161,9 @@ def validate(verbose=True):
if b is a or b['face'] != a['face'] or b['shape'] is None: continue
if b['seq'] < a['seq'] and b['shape'].intersection(a['footprint']).area > 1.0 and b['id'] not in a['onto']:
errs.append(f"{a['id']} is glued after {b['id']}, which already covers its glue area")
# 5. glue areas sit on foam: leaf stems fully, rigid printed parts at least 55%
# 5. glue areas sit on foam: fully, except the knot and the acorn halves, which need at least 55%
for p in glued:
if p['part'] in ('STRAP',): continue
if p['part'] == 'STRAP': continue
ground = unary_union([outline] + [q['shape'] for q in PLACEMENTS if q['id'] in p['onto']])
frac = p['footprint'].intersection(ground).area / max(p['footprint'].area, 1e-6)
need = 0.97 if p['part'] in ('L', 'M', 'S', 'PATCH', 'WIRE', 'SPIRAL', 'TWIG', 'STRIP') else 0.55
@@ -208,7 +203,7 @@ def validate(verbose=True):
if sl.distance(o.exterior) < 8: errs.append(f"{b['kind']} base: strap slit is {sl.distance(o.exterior):.0f} mm from an edge")
if not pt.buffer(-4).contains(sl): errs.append(f"{b['kind']} base: patch does not cover its slit with 4 mm to spare")
for h in b['holes']:
d = h.distance(o.exterior) if not o.interiors else min(h.exterior.distance(o.exterior), 99)
d = h.exterior.distance(o.exterior)
if d < 10: errs.append(f"{b['kind']} base: eye hole is {d:.0f} mm from the outer edge")
notes.append(f"{b['kind']} base: {o.bounds[2]-o.bounds[0]:.0f} x {o.bounds[3]-o.bounds[1]:.0f} mm, one piece, min neck >= 8 mm")
ml = make_list()
+3 -3
View File
@@ -1,12 +1,12 @@
"""Render an HTML file to PNG (for checking) or PDF (for the kit) with the pre-installed Chromium."""
"""Render an HTML file to PNG (for checking) or PDF (for the kit) with Playwright's Chromium, or Google Chrome if Playwright has no browser of its own."""
import sys, asyncio
from playwright.async_api import async_playwright
async def go(src, out, width=1260, scale=1, footer=None):
async def go(src, out, width=1260, footer=None):
async with async_playwright() as p:
try: b = await p.chromium.launch()
except Exception: b = await p.chromium.launch(channel='chrome') # no Playwright browser installed: use Google Chrome
pg = await b.new_page(viewport={'width': width, 'height': 800}, device_scale_factor=scale)
pg = await b.new_page(viewport={'width': width, 'height': 800})
await pg.goto('file://' + src); await pg.evaluate('document.fonts.ready'); await pg.wait_for_timeout(300)
if out.endswith('.pdf'):
kw = dict(display_header_footer=True, header_template='<span></span>', footer_template=
+12 -12
View File
@@ -1,13 +1,13 @@
"""Assemble the print set (only parts the manifest places, plus the stamp) and test each file for printability:
watertight, sitting on the bed, no layer that starts in mid-air, and how much steep overhang it has."""
import os, shutil, json, numpy as np, trimesh
import shutil, json, numpy as np, trimesh
from trimesh import creation
from shapely.geometry import Polygon, LineString
from shapely.geometry import LineString
from shapely.ops import unary_union
import geom as G, manifest as M
from paths import STL_SRC, OUT, WORK
from paths import STL_SRC, OUT as _OUT, WORK
SRC = str(STL_SRC); OUT = str(_OUT / 'stl')
STL_OUT = OUT / 'stl'
def brow_strip(L=G.STRIP_L):
"""Thin heat-formable brow strip: 2.4 mm plate, bark ridges 1.2 mm proud, low knobs. Same outline the guide draws."""
@@ -20,7 +20,7 @@ def brow_strip(L=G.STRIP_L):
rp = unary_union(ridges).intersection(outline.buffer(-1.0))
for g in (rp.geoms if rp.geom_type == 'MultiPolygon' else [rp]):
if g.area > 2: parts.append(creation.extrude_polygon(g, 3.6))
for kx, s in [(-52, 4.2), (-26, 5.0), (-5, 3.8), (16, 5.0), (40, 4.2), (58, 3.4)]:
for kx, s in zip(G.STRIP_KNOB_X, (4.2, 5.0, 3.8, 5.0, 4.2, 3.4)):
k = creation.icosphere(2, s); k.apply_scale([1.5, 1, 0.5]); k.apply_translation([kx, 0, 2.4]); parts.append(k)
m = trimesh.boolean.union(parts, engine='manifold')
cut = creation.box([L+40, 80, 10]); cut.apply_translation([0, 0, -5]); m = m.difference(cut)
@@ -56,10 +56,10 @@ def acorn_full(h=28, r=10, cut=4.0):
GEN = {'brow_strip.stl': brow_strip, 'acorn_large_half.stl': lambda: acorn_half(30, 11), 'acorn_small_half.stl': lambda: acorn_half(22, 8), 'acorn_full.stl': acorn_full}
FILES = { # kit file name -> (source, part id)
FILES = { # kit file name -> (file in stl_src, or None if generated here; part id)
'brow_strip.stl': (None, 'STRIP'), 'bark_knot.stl': ('bark_knot.stl', 'KNOT'), 'twig_forked.stl': ('twig_forked_flat.stl', 'TWIG'),
'acorn_large_half.stl': ('acorn_large_halfback.stl', 'AL'), 'acorn_small_half.stl': ('acorn_small_halfback.stl', 'AS'),
'acorn_full.stl': ('acorn_full_upright.stl', 'AF'), 'tendril_spiral.stl': ('tendril_spiral_small_flat.stl', 'SPIRAL'),
'acorn_large_half.stl': (None, 'AL'), 'acorn_small_half.stl': (None, 'AS'),
'acorn_full.stl': (None, 'AF'), 'tendril_spiral.stl': ('tendril_spiral_small_flat.stl', 'SPIRAL'),
'leaf_vein_stamp.stl': ('leaf_vein_stamp.stl', 'STAMP'),
}
@@ -99,16 +99,16 @@ def check(m, layer=0.2):
def build():
ml = M.make_list(); report = {}
for name, (src, pid) in FILES.items():
if name in GEN: m = GEN[name](); m.export(f'{OUT}/{name}')
else: shutil.copy(f'{SRC}/{src}', f'{OUT}/{name}'); m = trimesh.load(f'{OUT}/{name}')
if name in GEN: m = GEN[name](); m.export(STL_OUT / name)
else: shutil.copy(STL_SRC / src, STL_OUT / name); m = trimesh.load(STL_OUT / name)
r = check(m); r['qty'] = 1 if pid == 'STAMP' else ml[pid]['total']; r['part'] = pid; report[name] = r
print(f"{name:24s} x{r['qty']} {str(r['extents']):22s} bed {r['bed_contact_mm2']:6.0f} mm2 mid-air {r['midair_mm2']:5.1f} steep overhang {r['overhang_mm2']:5.0f} {r['verdict']}")
# every printed part in the manifest has a file, and no file is for an unplaced part
need = {k for k, v in ml.items() if v['kind'] == 'print'}; have = {pid for _, pid in FILES.values()} - {'STAMP'}
assert need == have, (need ^ have)
# control: the two files that failed on the printer must fail this test
# control: the three files that failed on the printer must fail this test
for bad in ('tendril_spiral_small.stl', 'tendril_spiral.stl', 'twig_forked.stl'):
rb = check(trimesh.load(f'{SRC}/{bad}')); print(f"control {bad:28s} mid-air {rb['midair_mm2']:6.1f} {rb['verdict']}"); assert rb['verdict'].startswith('FAIL'), 'the test must reject the files that failed on the printer'
rb = check(trimesh.load(STL_SRC / bad)); print(f"control {bad:28s} mid-air {rb['midair_mm2']:6.1f} {rb['verdict']}"); assert rb['verdict'].startswith('FAIL'), 'the test must reject the files that failed on the printer'
json.dump(report, open(WORK / 'stl_report.json', 'w'), indent=1)
return report