#!/usr/bin/env python3
"""SG-01 tabletop gear pair. Run with Python 3.11 and cadquery==2.7.0."""
import argparse
import json
import math
import os
import shutil
import struct
from collections import Counter
from pathlib import Path
from xml.sax.saxutils import escape
from zipfile import ZIP_DEFLATED, ZipFile

import cadquery as cq
import numpy as np

VERSION = "1.0.0"
MODEL = "SG-01"
MODULE, TEETH, PRESSURE = 2.0, (20, 40), 20.0
CENTER = MODULE * sum(TEETH) / 2
THINNING = 0.15  # Pitch-circle tooth thickness removed from EACH gear, in mm.
FACE, BASE_T, PAD_H, END_PLAY = 8.0, 6.0, 1.0, 0.4
GEAR_Z = BASE_T + PAD_H
POST_D, BORE, PAD_D = 8.0, 8.4, 15.0
BOLT_D, HEAD_D, HEAD_DEPTH = 4.4, 7.6, 4.2
SCREW_LENGTH, WASHER_D, WASHER_T, NUT_H = 20.0, 12.0, 1.0, 5.0
HANDLE_RADIUS, HANDLE_D, HANDLE_H = 13.0, 9.5, 20.0
BASE_RADII = (30.0, 49.0)
WINDOW_R, WINDOW_D = 22.0, 16.0
ARROW = [(-2, 11), (2, 11), (2, 24), (6, 24), (0, 33), (-6, 24), (-2, 24)]
ORIGIN, Z = (0, 0, 0), (0, 0, 1)
OUT = Path(os.environ.get("ATLAS_BUILD_OUTPUT", Path.cwd() / "sg-01-output")).resolve()
ASSETS = OUT / "assets/model"
DOWNLOAD = OUT / "downloads"
DRAW = ASSETS / "drawings"
STL, STEP = DOWNLOAD / "stl", DOWNLOAD / "step"
# id, Chinese name, motion role, color, assembly origin, exploded displacement, explanation.
PARTS = [
    ("base", "双轴底座", "fixed", "#c8c3b2", (0, 0, 0), (0, 0, 0),
     "两个固定轴保持中心距。底座上的三角孔标出起点和半圈的位置。"),
    ("pinion", "20 齿小轮与手柄", "driver", "#de8840", (0, 0, GEAR_Z), (-10, 0, 34),
     "竖起的手柄与齿轮一起打印。手柄绕小轮中心转一圈，送过 20 个齿。"),
    ("wheel", "40 齿大轮", "driven", "#367c80", (CENTER, 0, GEAR_Z), (13, 0, 48),
     "箭头形通孔指示转角。小轮转一圈时，箭头从一端转到底座另一端的三角标记。"),
]
COUPONS = {"gauge-base": "校准短底座", "gauge-pinion": "主动轮试啮扇段", "gauge-wheel": "从动轮试啮扇段"}
SHEETS = [("assembly", "装配图与轴向剖视"), ("base", "双轴底座零件图"),
          ("pinion", "20 齿小轮与手柄零件图"), ("wheel", "40 齿大轮零件图"),
          ("calibration", "轴孔与啮合校准件装配图")]
FILES = [("print-package", "完整打印与装配包", "sg-01-print-package.zip"),
         ("step", "STEP 装配模型", "sg-01-assembly.step"), ("readme", "中文打印与装配说明", "README-zh.txt"),
         ("drawings", "全套二维图纸", "sg-01-drawings.zip"), ("source", "可独立运行的 CAD 源码", "build.py"),
         ("calibration", "轴孔与啮合校准件", "sg-01-calibration.zip")]
BOM = [{"name": "M4×20 圆柱头内六角螺钉（头部 Ø7 × 4 mm）", "qty": 2},
       {"name": "M4 加大平垫圈（外径 12 mm，厚 1 mm）", "qty": 2},
       {"name": "M4 尼龙防松螺母（约高 5 mm）", "qty": 2}]
REFERENCE = "https://www.maxwelltools.com/spur-gear-calculator/"


def polar(radius, angle):
    return (radius * math.cos(angle), radius * math.sin(angle), 0)


def circle(diameter, x=0, y=0):
    return cq.Wire.makeCircle(diameter / 2, (x, y, 0), Z)


def polygon(points):
    return cq.Wire.makePolygon([(x, y, 0) for x, y in points], close=True)


def plate(outline, holes, height):
    return cq.Solid.extrudeLinear(outline, holes, (0, 0, height))


def cylinder(diameter, height, x=0, y=0, z=0):
    return cq.Solid.makeCylinder(diameter / 2, height, (x, y, z))


def arc(radius, first, last):
    return cq.Edge.makeThreePointArc(polar(radius, first), polar(radius, (first + last) / 2), polar(radius, last))


def gear_outline(count, phase, tooth_numbers=None):
    """One outline for the CAD solid, including circular lands and involute flanks."""
    pitch = 2 * math.pi / count
    rp = MODULE * count / 2
    rf, ra = rp - 1.25 * MODULE, rp + MODULE
    alpha = math.radians(PRESSURE)
    rb = rp * math.cos(alpha)
    start = max(rb, rf)
    t0, t1 = (math.sqrt(max(0, (r / rb) ** 2 - 1)) for r in (start, ra))
    half_base = pitch / 4 - THINNING / (2 * rp) + math.tan(alpha) - alpha
    flank = []
    for i in range(10):
        t = t0 + (t1 - t0) * i / 9
        flank.append((rb * math.sqrt(1 + t * t), half_base - (t - math.atan(t))))
    half_root, half_tip = flank[0][1], flank[-1][1]
    teeth = list(range(count) if tooth_numbers is None else tooth_numbers)
    edges = []
    for k in teeth:
        angle = phase + k * pitch
        edges.append(arc(rf, angle - pitch / 2, angle - half_root))
        if rf < start:
            edges.append(cq.Edge.makeLine(polar(rf, angle - half_root), polar(start, angle - half_root)))
        edges.append(cq.Edge.makeSpline([cq.Vector(*polar(r, angle - h)) for r, h in flank]))
        edges.append(arc(ra, angle - half_tip, angle + half_tip))
        edges.append(cq.Edge.makeSpline([cq.Vector(*polar(r, angle + h)) for r, h in reversed(flank)]))
        if rf < start:
            edges.append(cq.Edge.makeLine(polar(start, angle + half_root), polar(rf, angle + half_root)))
        edges.append(arc(rf, angle + half_root, angle + pitch / 2))
    if tooth_numbers is not None:
        # The sector closes around a complete hub, so it fits the production axle.
        low = phase + (teeth[0] - 0.5) * pitch
        high = phase + (teeth[-1] + 0.5) * pitch
        rh = PAD_D / 2
        edges.extend([cq.Edge.makeLine(polar(rf, high), polar(rh, high)), arc(rh, high, low + 2 * math.pi),
                      cq.Edge.makeLine(polar(rh, low), polar(rf, low))])
    return cq.Wire.assembleEdges(edges)


def base_outline():
    small, large = BASE_RADII
    nx = (small - large) / CENTER
    ny = math.sqrt(1 - nx * nx)
    a, b = (small * nx, small * ny), (CENTER + large * nx, large * ny)
    return (cq.Workplane("XY").moveTo(*a).lineTo(*b).threePointArc((CENTER + large, 0), (b[0], -b[1]))
            .lineTo(a[0], -a[1]).threePointArc((-small, 0), a).close().val())


def base_plate(calibration=False):
    if calibration:
        outline = cq.Workplane("XY").center(CENTER / 2, 0).slot2D(CENTER + 20, 20).val()
        marks = []
    else:
        outline = base_outline()
        marks = []
        for x, count, sign in [(0, TEETH[0], 1), (CENTER, TEETH[1], 1), (CENTER, TEETH[1], -1)]:
            radius = MODULE * (count + 2) / 2
            marks.append(polygon([(x, sign * (radius + 1)), (x + 2, sign * (radius + 5)),
                                  (x - 2, sign * (radius + 5))]))
    obj = plate(outline, marks, BASE_T)
    for x in (0, CENTER):
        obj = obj.fuse(cylinder(PAD_D, PAD_H, x, 0, BASE_T),
                       cylinder(POST_D, FACE + END_PLAY, x, 0, GEAR_Z))
        obj = obj.cut(cylinder(BOLT_D, 25, x), cylinder(HEAD_D, HEAD_DEPTH, x))
    return obj.clean().Solids()[0]


def make_geometry():
    z1, z2 = TEETH
    pinion = plate(gear_outline(z1, 0), [circle(BORE), circle(5, 0, -HANDLE_RADIUS)], FACE)
    grip = (cq.Workplane("XY").center(0, HANDLE_RADIUS).circle(HANDLE_D / 2).extrude(HANDLE_H)
            .edges(">Z").fillet(1.2).val().translate((0, 0, FACE)))
    pinion = pinion.fuse(grip).clean().Solids()[0]
    phase = math.pi / z2 if z2 % 2 == 0 else 0.0  # A tooth at +X faces a gap at -X.
    holes = [circle(BORE), polygon(ARROW)] + [circle(WINDOW_D, x, y)
              for x, y in ((-WINDOW_R, 0), (WINDOW_R, 0), (0, -WINDOW_R))]
    wheel = plate(gear_outline(z2, phase), holes, FACE)
    middle = z2 // 2
    return {"base": base_plate(), "pinion": pinion, "wheel": wheel, "gauge-base": base_plate(True),
            "gauge-pinion": plate(gear_outline(z1, 0, range(-2, 3)), [circle(BORE)], FACE),
            "gauge-wheel": plate(gear_outline(z2, phase, range(middle - 3, middle + 3)), [circle(BORE)], FACE)}


def location(part_id, degrees):
    if part_id == "base":
        return cq.Location(ORIGIN)
    if part_id == "pinion":
        return cq.Location((0, 0, GEAR_Z), Z, degrees)
    return cq.Location((CENTER, 0, GEAR_Z), Z, -degrees * TEETH[0] / TEETH[1])


def hardware_shapes():
    """Simplified purchased hardware envelopes; lengths measured from under the head."""
    journal_top = GEAR_Z + FACE + END_PLAY
    bolt = cylinder(7, 4, z=HEAD_DEPTH - 4).fuse(cylinder(4, SCREW_LENGTH, z=HEAD_DEPTH))
    washer = plate(circle(WASHER_D), [circle(4.3)], WASHER_T).translate((0, 0, journal_top))
    nut_radius = 7 / math.sqrt(3)
    corners = [polar(nut_radius, i * math.pi / 3)[:2] for i in range(6)]
    nut = plate(polygon(corners), [circle(4)], NUT_H).translate((0, 0, journal_top + WASHER_T))
    return {"screw": bolt, "washer": washer, "nut": nut}


def manifest():
    z1, z2 = TEETH
    parameters = dict(driver_teeth=z1, driven_teeth=z2, module=MODULE, pressure_angle_deg=PRESSURE,
                      center_distance=CENTER, face_width=FACE, driver_pitch_diameter=MODULE*z1,
                      driven_pitch_diameter=MODULE*z2, backlash_mm=2*THINNING, shaft_diameter=POST_D,
                      bore_diameter=BORE, axial_clearance=END_PLAY, default_angle_deg=0)
    parts = [dict(id=i, name=n, role=role, color=c, position=p, explosionOffset=e, description=d,
                  printable=True, qty=1, stl=f"downloads/stl/{i}.stl", step=f"downloads/step/{i}.step")
             for i, n, role, c, p, e, d in PARTS]
    screws = [dict(id=f"axis_{side}", name="M4 轴心螺钉", parentPartId="base", frame="partLocal", kind="bolt",
                   position=[x, 0, HEAD_DEPTH], diameter=4, length=SCREW_LENGTH, headDiameter=7, headHeight=4)
              for x, side in [(0, "input"), (CENTER, "output")]]
    return dict(id="sg-01", name="手摇直齿轮", version=VERSION, units="mm", status="pending-physical-test",
                statusLabel="待实物试装", original=True, parameters=parameters, parts=parts,
                hardwareBOM=BOM, visualHardware=screws, kinematics=dict(outputUnit="°",
                output="-inputDegrees * driver_teeth / driven_teeth", zero="手柄和箭头孔均朝 +Y"),
                drawings=[dict(id=i, title=n, path=f"assets/model/drawings/{i}.svg", format="SVG",
                               units="mm", paper="A4", static=True) for i, n in SHEETS],
                downloads=[dict(id=i, label=n, path="downloads/" + f) for i, n, f in FILES],
                calibration=dict(name="轴孔与啮合校准件", path="downloads/sg-01-calibration.zip",
                                 parts=[dict(id=i, name=n, path=f"downloads/stl/{i}.stl") for i,n in COUPONS.items()]),
                printZip="downloads/sg-01-print-package.zip", readme="downloads/README-zh.txt",
                references=[{"title": "Maxwell Tools Company · Spur gear formula reference", "url": REFERENCE}],
                validation=dict(physicalTested=False, path="downloads/validation.json",
                                note="已检查 CAD 实体、STL 闭合、齿面间隙和两圈输入的运动。尚未打印或试装。"))


def stl_record(shape, path):
    data = path.read_bytes()
    count = struct.unpack_from("<I", data, 80)[0]
    assert len(data) == 84 + count * 50
    facets = np.frombuffer(data, dtype=[("normal", "<f4", 3), ("points", "<f4", (3, 3)), ("attr", "<u2")],
                           count=count, offset=84)["points"].astype(float)
    vertices, ids = np.unique(facets.reshape(-1, 3), axis=0, return_inverse=True)
    faces = ids.reshape(-1, 3)
    edges, directions = Counter(), Counter()
    for a, b in np.vstack([faces[:, (0, 1)], faces[:, (1, 2)], faces[:, (2, 0)]]):
        key = (min(a, b), max(a, b))
        edges[key] += 1
        directions[key] += 1 if a < b else -1
    a, b, c = facets.transpose(1, 0, 2)
    areas = np.linalg.norm(np.cross(b - a, c - a), axis=1)
    volume = float(np.einsum("ij,ij->", a, np.cross(b, c)) / 6)
    record = dict(valid=shape.isValid(), solids=len(shape.Solids()), volume_mm3=round(shape.Volume(), 3),
                  meshVolume_mm3=round(volume, 3), meshWatertight=all(v == 2 for v in edges.values()),
                  meshConsistentWinding=all(v == 0 for v in directions.values()),
                  meshDegenerateTriangles=int((areas < 1e-10).sum()), triangles=count,
                  meshLocalZ_mm=[float(vertices[:, 2].min()), float(vertices[:, 2].max())])
    assert record["valid"] and record["solids"] == 1 and volume > 0, (path.name, record)
    assert record["meshWatertight"] and record["meshConsistentWinding"] and record["meshDegenerateTriangles"] == 0, (path.name, record)
    assert abs(volume / shape.Volume() - 1) < 0.01 and record["meshLocalZ_mm"][0] == 0, (path.name, record)
    return record


def bottom_face(shape):
    return next(f for f in shape.Faces() if f.geomType() == "PLANE" and f.normalAt().z < -0.99
                and abs(f.Center().z) < 1e-6)


def profile_points(wire, tolerance):
    return np.array([(p.x, p.y) for p in wire.sample(tolerance)[0]])


def rotate_xy(points, deg, offset):
    angle = math.radians(deg)
    c, s = math.cos(angle), math.sin(angle)
    return points @ np.array([[c, s], [-s, c]]) + [offset, 0]


def gear_gap(loops, input_deg, extra_output=0):
    left = rotate_xy(loops[0], input_deg, 0)
    right = rotate_xy(loops[1], -input_deg * TEETH[0] / TEETH[1] + extra_output, CENTER)
    left_end = np.roll(left, -1, axis=0)
    right_end = np.roll(right, -1, axis=0)
    # All segments that could meet or come within 1 mm are in this tip-circle overlap strip.
    left_near = np.maximum(left[:, 0], left_end[:, 0]) > CENTER - MODULE * (TEETH[1] + 2) / 2 - 1
    right_near = np.minimum(right[:, 0], right_end[:, 0]) < MODULE * (TEETH[0] + 2) / 2 + 1
    a, b = left[left_near, None], left_end[left_near, None]
    c, d = right[None, right_near], right_end[None, right_near]
    u, v = b - a, d - c

    def cross2(s, t):
        return s[:, :, 0] * t[:, :, 1] - s[:, :, 1] * t[:, :, 0]

    crossing = ((cross2(u, c - a) * cross2(u, d - a) < 0) &
                (cross2(v, a - c) * cross2(v, b - c) < 0))
    if crossing.any():
        return 0.0

    def point_to_segments(p, start, line):
        delta = p - start
        fraction = np.clip(np.sum(delta * line, axis=2) / np.sum(line * line, axis=2), 0, 1)
        nearest = delta - fraction[:, :, None] * line
        return np.min(np.sum(nearest * nearest, axis=2))

    return math.sqrt(min(point_to_segments(a, c, v), point_to_segments(b, c, v),
                         point_to_segments(c, a, u), point_to_segments(d, a, u)))


def measure_reference_poses(geometry):
    shapes = {k: geometry[k] for k in ("pinion", "wheel")}
    pinion_top = max(shapes["pinion"].Faces(), key=lambda face: face.Center().z).Center()
    arrow_tip = max(bottom_face(shapes["wheel"]).innerWires(), key=lambda w: w.BoundingBox().ymax)
    arrow_vertex = max(arrow_tip.Vertices(), key=lambda v: v.Center().y).Center()
    markers = {"pinion": pinion_top, "wheel": arrow_vertex}
    assert abs(pinion_top.y - HANDLE_RADIUS) < 1e-6 and abs(arrow_vertex.y - max(y for _, y in ARROW)) < 1e-6
    result = []
    for angle in (0, 17, 90, 180, 273, 360, 540, 719, 720):
        transforms = {}
        for key, marker in markers.items():
            loc = location(key, angle)
            hole = next(e for e in bottom_face(shapes[key]).Edges() if e.geomType() == "CIRCLE"
                        and math.isclose(e.radius(), BORE / 2))
            axis = hole.located(loc).arcCenter()
            pointer = cq.Vertex.makeVertex(*marker.toTuple()).located(loc).Center() - axis
            turns = angle if key == "pinion" else -angle * TEETH[0] / TEETH[1]
            measured = math.degrees(math.atan2(-pointer.x, pointer.y))
            measured += 360 * round((turns - measured) / 360)
            assert abs(turns - measured) < 1e-7, (key, angle, measured)
            transforms[key] = dict(position=[round(v, 9) for v in axis.toTuple()], rotationZ=math.radians(measured))
        result.append(dict(input=angle, output=round(math.degrees(transforms["wheel"]["rotationZ"]), 9),
                           transforms=transforms))
    return result


def validate(geometry):
    records = {i: stl_record(obj, STL / (i + ".stl")) for i, obj in geometry.items()}
    outlines = [bottom_face(geometry[k]).outerWire() for k in ("pinion", "wheel")]
    for wire, z in zip(outlines, TEETH):
        tips = [e for e in wire.Edges() if e.geomType() == "CIRCLE" and
                math.isclose(e.radius(), MODULE * (z + 2) / 2)]
        assert len(tips) == z, (len(tips), z)
    posts = [edge.arcCenter().x for edge in geometry["base"].Edges() if edge.geomType() == "CIRCLE"
             and math.isclose(edge.radius(), POST_D / 2)]
    assert math.isclose(max(posts) - min(posts), CENTER)
    tolerance = 0.003
    loops = [profile_points(w, tolerance) for w in outlines]
    step = 0.25
    tooth_pitch = 360 / TEETH[0]
    # Each subsequent pinion tooth and wheel gap has the same CAD profile.
    gaps = [gear_gap(loops, i * step) for i in range(round(tooth_pitch / step) + 1)]
    assert all(gear_gap(loops, 2.7, extra_output=delta) == 0 for delta in (-0.4, 0.4)), "检查放大齿隙后能否两向咬合"
    near_gap = min(gaps)
    # Lipschitz travel of both tip circles to the nearest sample, plus profile chord errors.
    max_radius = MODULE * (TEETH[0] + 2) / 2 + MODULE * (TEETH[1] + 2) / 2 * TEETH[0] / TEETH[1]
    margin = near_gap - 2 * tolerance - max_radius * math.radians(step / 2)
    assert margin > 0, (near_gap, margin)
    # Confirm faces on the actual solids, independently of the planar sweep.
    exact = []
    for deg in (0, 3.7, 8.9, 15.1):
        pinion, wheel = [geometry[i].located(location(i, deg)) for i in ("pinion", "wheel")]
        distance = pinion.distance(wheel)
        assert 0 < distance < 2 * THINNING and not pinion.intersect(wheel).Solids()
        assert abs(distance - gear_gap(loops, deg)) < 2 * tolerance
        exact.append(dict(input=deg, nearestFlanks_mm=round(distance, 6)))
    assembly = [geometry[i].located(location(i, 0)) for i in ("base", "pinion", "wheel")]
    nongap = []
    for x in (0, CENTER):
        assembly.extend(obj.translate((x, 0, 0)) for obj in hardware_shapes().values())
    for i, first in enumerate(assembly):
        for second in assembly[i + 1:]:
            overlap = sum(s.Volume() for s in first.intersect(second).Solids())
            if overlap > 1e-5:
                nongap.append((i, overlap))
    assert not nongap, nongap
    ra = [(z + 2) * MODULE / 2 for z in TEETH]
    rb = [z * MODULE / 2 * math.cos(math.radians(PRESSURE)) for z in TEETH]
    contact = (sum(math.sqrt(a*a - b*b) for a, b in zip(ra, rb)) - CENTER * math.sin(math.radians(PRESSURE)))
    contact /= math.pi * MODULE * math.cos(math.radians(PRESSURE))
    assert contact > 1
    return dict(version=VERSION, units="mm", cadquery=cq.__version__, physicalTested=False, parts=records,
                scope="教学样板的名义几何。检查包含简化螺钉、垫圈和螺母；实物尺寸、摩擦、磨损与承载待试验。",
                motion=dict(samples=len(gaps), sampleStep_deg=step, toothPeriod_deg=tooth_pitch,
                            assemblyPeriod_deg=360 * TEETH[1] / math.gcd(*TEETH),
                            method="对 CAD 齿廓以 0.003 mm 弦差离散，在一个齿距内检验各位置的边界相交与最短距。后续齿对按齿距重复。以齿顶的最大移动量核对相邻样本之间的剩余间隙，另用精确实体抽查。",
                            observedToothCounts=list(TEETH), minSampledGap_mm=round(near_gap, 6),
                            maxSampledGap_mm=round(max(gaps), 6), conservativeGap_mm=round(margin, 6),
                            referencePoses=measure_reference_poses(geometry), brepChecks=exact,
                            referenceMethod="按已装配 CAD 的轴孔中心与手柄顶面中心、箭头孔顶点测量。",
                            intersections=[], angularContactProbe_deg=[-0.4, 0.4],
                            pitchLineBacklash_mm=2 * THINNING, theoreticalContactRatio=round(contact, 5)),
                assembly=dict(zeroPoseSolidPairs=len(assembly) * (len(assembly) - 1) // 2, volumeIntersections=[],
                              shaftRadialClearance_mm=round((BORE - POST_D) / 2, 3), topWasherClearance_mm=END_PLAY,
                              washerRadialOverlap_mm=(WASHER_D - BORE) / 2,
                              screwProtrusionAboveNut_mm=round(HEAD_DEPTH + SCREW_LENGTH - GEAR_Z - FACE -
                                                              END_PLAY - WASHER_T - NUT_H, 3)))


class Drawing:
    """A4 drawing in page millimetres. All outlines and cuts are sampled from CAD."""
    def __init__(self, number, title):
        self.svg = ['<svg xmlns="http://www.w3.org/2000/svg" width="297mm" height="210mm" viewBox="0 0 297 210" role="img">',
                    f'<title>{MODEL} · {escape(title)}</title>', '''<defs>
<pattern id="base-hatch" patternUnits="userSpaceOnUse" width="2" height="2" patternTransform="rotate(45)"><path d="M0 0v2" stroke="#555" stroke-width=".3"/></pattern>
<pattern id="gear-hatch" patternUnits="userSpaceOnUse" width="2.2" height="2.2" patternTransform="rotate(-45)"><path d="M0 0v2.2" stroke="#555" stroke-width=".3"/></pattern>
<marker id="arrow" viewBox="0 0 6 4" markerWidth="2.8" markerHeight="1.8" refX="6" refY="2" orient="auto-start-reverse" markerUnits="userSpaceOnUse"><path d="M0 0L6 2L0 4Z" fill="#222"/></marker>
</defs><style>text{font-family:'PingFang SC','Noto Sans CJK SC','Microsoft YaHei',sans-serif;fill:#171717}.edge{stroke:#171717;stroke-width:.35;stroke-linejoin:round;fill-rule:evenodd}.thin,.center,.dim{fill:none;stroke:#444;stroke-width:.20}.center{stroke-dasharray:4 1 .6 1}.dim{marker-start:url(#arrow);marker-end:url(#arrow)}</style>
<rect width="297" height="210" fill="white"/><rect x="6" y="6" width="285" height="198" fill="none" stroke="#444" stroke-width=".3"/>''']
        self.text(12, 18, title, 6)
        self.text(285, 17, f"{MODEL}  /  {number:02d}     v{VERSION}", 3.5, "end")
        self.line(6, 23, 291, 23)
        self.line(6, 192, 291, 192)
        self.text(12, 200, "机巧   /   手摇直齿轮", 3.3)
        self.text(285, 200, f"名义尺寸 · mm     /     待实物试装     /     A4 · {number}/{len(SHEETS)}", 3.1, "end")

    def text(self, x, y, text, size=3.4, anchor="start"):
        self.svg.append(f'<text x="{x:g}" y="{y:g}" font-size="{size:g}" text-anchor="{anchor}">{escape(str(text))}</text>')

    def line(self, x1, y1, x2, y2, style="thin"):
        self.svg.append(f'<path class="{style}" d="M{x1:g},{y1:g}L{x2:g},{y2:g}"/>')

    def cross(self, x, y, r=6):
        self.line(x-r, y, x+r, y, "center")
        self.line(x, y-r, x, y+r, "center")

    def pitch(self, x, y, radius):
        self.svg.append(f'<circle class="center" cx="{x:g}" cy="{y:g}" r="{radius:g}"/>')

    def hdim(self, x1, x2, y, start1, start2, text):
        self.line(x1, start1, x1, y+2)
        self.line(x2, start2, x2, y+2)
        self.line(x1, y, x2, y, "dim")
        self.text((x1+x2)/2, y-1.3, text, 3.3, "middle")

    def vdim(self, top, bottom, x, origin, text):
        self.line(origin, top, x+2, top)
        self.line(origin, bottom, x+2, bottom)
        self.line(x, top, x, bottom, "dim")
        self.svg.append(f'<text transform="translate({x-1.2:g} {(top+bottom)/2:g}) rotate(-90)" font-size="3.3" text-anchor="middle">{escape(text)}</text>')

    def face(self, face, project, fill):
        path = []
        for wire in [face.outerWire(), *face.innerWires()]:
            points = [project(p) for p in wire.sample(0.04)[0]]
            path.append("M" + "L".join(f"{x:.3f},{y:.3f}" for x,y in points) + "Z")
        self.svg.append(f'<path class="edge" d="{" ".join(path)}" fill="{fill}"/>')

    def top(self, shape, x, y, scale, fill="white"):
        faces = sorted((f for f in shape.Faces() if f.geomType() == "PLANE" and f.normalAt().z > 0.99),
                       key=lambda f: f.Center().z)
        for face in faces:
            self.face(face, lambda p: (x + p.x * scale, y - p.y * scale), fill)

    def section(self, shape, plane, axis, x, y, scale, fill, origin=0):
        for face in shape.intersect(plane).Faces():
            self.face(face, lambda p: (x + (getattr(p, axis) - origin) * scale, y - p.z * scale), fill)

    def notes(self, x, y, title, lines):
        self.text(x, y, title, 4.1)
        for i, line in enumerate(lines, 1):
            self.text(x, y + 6.7*i, line, 3.25)

    def save(self, name):
        (DRAW / (name + ".svg")).write_text("\n".join([*self.svg, "</svg>"]), encoding="utf8")


def slice_plane(axis, middle, width, upper=45):
    lo, hi = middle - width / 2, middle + width / 2
    outline = [(lo, -1), (hi, -1), (hi, upper), (lo, upper)]
    points = [(u, 0, z) if axis == "x" else (0, u, z) for u, z in outline]
    return cq.Face.makeFromWires(cq.Wire.makePolygon(points, close=True))


def axle_section(sheet, geometry, assembly, x, y):
    scale = 2.2
    plane = slice_plane("x", CENTER, 27)
    sheet.section(geometry["base"], plane, "x", x, y, scale, "url(#base-hatch)", CENTER)
    if assembly:
        wheel = geometry["wheel"].located(location("wheel", 0))
        sheet.section(wheel, plane, "x", x, y, scale, "url(#gear-hatch)", CENTER)
        for shape in hardware_shapes().values():
            sheet.section(shape.translate((CENTER, 0, 0)), plane, "x", x, y, scale, "#dedede", CENTER)
    sheet.line(x, y+3, x, y-2.2*26, "center")


def make_drawings(geometry):
    def new(k):
        ident, title = SHEETS[k]
        return Drawing(k + 1, title)
    x, y, sc = 47, 91, 1.14
    assembly = new(0)
    assembly.text(12, 32, "俯视 · 手柄与箭头孔均指向起点", 3.6)
    assembly.top(geometry["base"], x, y, sc)
    for i, offset in [("pinion", 0), ("wheel", CENTER)]:
        assembly.top(geometry[i], x+sc*offset, y, sc)
        for key in ("washer", "nut", "screw"):
            # Only the exposed end of the screw is visible from above.
            hw = hardware_shapes()[key] if key != "screw" else cylinder(4, 1)
            assembly.top(hw, x+sc*offset, y, sc, "#e2e2e2")
        assembly.cross(x+sc*offset, y, 5)
    assembly.hdim(x, x+sc*CENTER, 158, y+5, y+5, f"{CENTER:g}")
    assembly.text(182, 33, "从动轴局部剖视", 4.2)
    axle_section(assembly, geometry, True, 232, 99)
    assembly.notes(181, 111, "由下向上装配", ["底座托台 → 齿轮 → 加大垫圈 → 防松螺母。",
                      "螺钉从底面穿入。垫圈压在固定轴端。",
                      f"轴端比轮面高 {END_PLAY:g}，两轮齿宽均为 {FACE:g}。"])
    assembly.notes(181, 151, "自备五金 · 每种 2 件", ["M4×20 圆柱头内六角螺钉", "M4 加大平垫圈，外径 12、厚 1", "M4 尼龙防松螺母，约高 5"])
    assembly.notes(13, 172, "小轮转一圈，大轮反向半圈", ["20 个齿依次经过啮合处，占大轮全周 40 齿的一半。"])
    assembly.save("assembly")

    base = new(1)
    base.text(12, 32, "俯视 · 两轴连线为中心基准", 3.6)
    base.top(geometry["base"], x, y, sc)
    for offset in (0, CENTER):
        base.cross(x+sc*offset, y)
    base.hdim(x, x+sc*CENTER, 153, y+6, y+6, f"{CENTER:g}")
    base.hdim(x-sc*BASE_RADII[0], x+sc*(CENTER+BASE_RADII[1]), 167, y+1, y+1,
              f"{sum(BASE_RADII)+CENTER:g}")
    base.vdim(y-BASE_RADII[1]*sc, y+BASE_RADII[1]*sc, 177, x+sc*CENTER, f"{2*BASE_RADII[1]:g}")
    base.text(190, 33, "固定轴局部剖视 · 两处相同", 3.9)
    axle_section(base, geometry, False, 234, 86)
    base.notes(190, 98, "轴座尺寸", [f"底板厚 {BASE_T:g}，上方托台 Ø{PAD_D:g} × {PAD_H:g}。",
               f"托台上的轴 Ø{POST_D:g}，露出 {FACE+END_PLAY:g}。",
               f"通孔 Ø{BOLT_D:g}，底部沉孔 Ø{HEAD_D:g} 深 {HEAD_DEPTH:g}。",
               "圆柱头坐入底部沉孔后，底板可以平放。"])
    base.notes(190, 147, "轮缘与标记", [f"底板两端半径 R{BASE_RADII[0]:g} / R{BASE_RADII[1]:g}，两侧相切。",
               "三个三角形通孔朝向齿轮，标记起点与半圈。"])
    base.text(13, 183, "底面贴打印平台。两根空心轴与底座一次打印。")
    base.save("base")

    for index, (key, count) in enumerate(zip(("pinion", "wheel"), TEETH), 2):
        sheet = new(index)
        driven = key == "wheel"
        sx, sy, scale = (78, 101, 1.57) if driven else (70, 91, 2.22)
        sheet.text(12, 32, "俯视 · 点划线为分度圆", 3.6)
        sheet.top(geometry[key], sx, sy, scale)
        sheet.pitch(sx, sy, scale * MODULE * count / 2)
        sheet.cross(sx, sy)
        sheet.text(157, 33, "沿轴孔与指示标记剖切", 3.9)
        size = 1.17 if driven else 1.95
        ox, oy = 218, 97
        plane = slice_plane("y", 0, MODULE * (count + 2) + 4)
        sheet.section(geometry[key], plane, "y", ox, oy, size, "url(#gear-hatch)")
        sheet.line(ox, oy+2, ox, oy-(FACE+(0 if driven else HANDLE_H))*size-4, "center")
        sheet.vdim(oy-size*FACE, oy, 278, ox + size * MODULE * count/2, f"{FACE:g}")
        if not driven:
            sheet.hdim(ox, ox+size*HANDLE_RADIUS, 109, oy+1, oy+1, f"{HANDLE_RADIUS:g}")
            sheet.vdim(oy-size*(FACE+HANDLE_H), oy-size*FACE, 261, ox+size*HANDLE_RADIUS, f"{HANDLE_H:g}")
        sheet.notes(156, 124, "直齿渐开线齿形", [f"{count} 齿，模数 {MODULE:g}，压力角 {PRESSURE:g}°。",
               f"分度圆 Ø{MODULE*count:g}，齿顶圆 Ø{MODULE*(count+2):g}，",
               f"齿根圆 Ø{MODULE*(count-2.5):g}，轴孔 Ø{BORE:g}。",
               f"在分度圆上，每轮齿厚减薄 {THINNING:g}。"])
        if driven:
            sheet.text(12, 178, f"3 × Ø{WINDOW_D:g} 观察孔的圆心距轴心 {WINDOW_R:g}。第四处为箭头形通孔。")
            sheet.text(156, 170, "箭头顶点距轴心 33。转过半圈后，")
            sheet.text(156, 177, "箭头能与底座另一端的三角标记对齐。")
        else:
            sheet.text(12, 159, f"手柄 Ø{HANDLE_D:g}，根部距轴心 {HANDLE_RADIUS:g}。")
            sheet.text(12, 167, "对侧小通孔 Ø5，与手柄到轴心的距离相同。")
            sheet.text(156, 170, "手柄端缘圆角 R1.2。底面平放打印，")
            sheet.text(156, 177, "手柄与齿轮连成一体。")
        sheet.save(key)

    cal = new(4)
    cal.text(12, 33, "俯视 · 两个扇段朝向彼此", 3.7)
    ox, oy, s = 32, 91, 1.65
    cal.top(geometry["gauge-base"], ox, oy, s)
    for key, offset in [("gauge-pinion", 0), ("gauge-wheel", CENTER)]:
        cal.top(geometry[key], ox+offset*s, oy, s)
        cal.cross(ox+offset*s, oy)
    cal.hdim(ox, ox+CENTER*s, 135, oy+7, oy+7, f"{CENTER:g}")
    cal.notes(173, 52, "先试印这三件", ["短底座沿用正式底座的轴孔、轴端和沉孔。",
              "五齿小扇段与六齿大扇段用的是正式齿形。",
              "装上和正式机构相同的螺钉、垫圈和螺母。"])
    cal.notes(173, 106, "手动检查", ["在中间位置左右轻拨小扇段约 10°。",
              "检查齿是否顺着进入下一齿槽，有无顶齿。",
              "轻抬扇段，确认轴向可动但不会越过垫圈。"])
    cal.notes(13, 158, "与正式件使用相同的切片设置", ["三个校准件都以平底朝下。校准包内的中文说明列出了紧配合与毛边的处理顺序。"])
    cal.save("calibration")


def instructions():
    z1, z2 = TEETH
    return f"""机巧 · {MODEL} 手摇直齿轮    v{VERSION}
单位 mm；角度从上方观察，逆时针为正。实物状态：待打印、待试装。

观察运动
把小轮手柄、大轮箭头孔都对准底座上方的三角标记。小轮逆时针摇一圈，{z1} 个齿依次经过啮合处，大轮同步走过 {z1} 个齿。大轮一圈有 {z2} 个齿，所走过的正好是半圈，方向为顺时针。指向底座下方三角孔时，就是半圈。
小轮输入      0°       90°       180°       360°       720°
大轮输出      0°      −45°       −90°      −180°      −360°
动画显示相对于起点的理想转角。实物换向时须先贴上另一侧齿面，手柄会有少许空程。

桌面样板尺寸
主动 {z1} 齿，从动 {z2} 齿；模数 {MODULE:g}，压力角 {PRESSURE:g}°，齿宽 {FACE:g}。
分度圆直径 {MODULE*z1:g} / {MODULE*z2:g}，齿顶圆直径 {MODULE*(z1+2):g} / {MODULE*(z2+2):g}。
固定轴中心距为 ({MODULE*z1:g} + {MODULE*z2:g}) ÷ 2 = {CENTER:g}。每轮分度圆上的齿厚各减薄 {THINNING:g}，配对名义圆周侧隙合计 {2*THINNING:g}。
底座长 {sum(BASE_RADII)+CENTER:g}、宽 {2*BASE_RADII[1]:g}、板厚 {BASE_T:g}。轴径 Ø{POST_D:g}，轮孔 Ø{BORE:g}，单边名义间隙 {(BORE-POST_D)/2:.2f}。轮底坐在 Ø{PAD_D:g} 的托台上。轴端高出轮面 {END_PLAY:g}。
小轮手柄与轮体一次成形，手柄中心距轴 {HANDLE_RADIUS:g}、直径 {HANDLE_D:g}、从轮面伸出 {HANDLE_H:g}。大轮的箭头孔用来观察转角。

打印清单
正式件各 1 个：stl/base.stl 双轴底座、stl/pinion.stl 小轮与手柄、stl/wheel.stl 大轮。
校准件各 1 个：stl/gauge-base.stl 短底座、stl/gauge-pinion.stl 五齿扇段、stl/gauge-wheel.stl 六齿扇段。
以毫米导入切片器，保持 100% 同比。六件的平底均在 Z=0。底座轴朝上，小轮手柄朝上，两轮齿面平铺。示例起点为 PLA、0.4 mm 喷嘴、0.20 mm 层高、3 道外壁、20% 填充。按材料和打印机调整。底座沉孔顶有短跨桥，注意清理垂丝。可把三件分盘，用不同颜色打印两轮和底座，标记更易辨认。

自备五金与工具
{chr(10).join(str(h['qty'])+' × '+h['name'] for h in BOM)}
准备 3 mm 内六角扳手与 7 mm 扳手。螺钉标注长度从头下算起。校准时可先借用同一套五金。

先试印校准件
1. 用与正式件相同的材料和参数打印三件校准件，清除首层外翻与孔口毛刺。
2. 先空套两扇段。孔应能顺着固定轴滑到底，并用手轻拨转动。让两个扇段的齿朝向彼此，把小轮中央齿放入大轮中间的齿槽。装入下面所述五金，在中间位置往复拨小扇段约 10°。
3. 如果单个扇段就转不动，先看轮孔和轴的实际尺寸，清理孔口或调孔补偿后重打校准件。若只有啮合才发紧，检查齿间拉丝、首层外翻，再核对两轴的 {CENTER:g} 中心距。轴和轮孔均已合适时，再做齿面的水平尺寸补偿并复测。每次只改一个参数。
4. 捏住扇段轻轻上下移动，可感觉少量轴向间隙。若紧固后才卡住，确认垫圈平整、确实落在轴端，且轴端高出齿轮上表面。通过这三项再打正式件。

正式装配
1. 把两个 M4×20 螺钉从底面穿过轴孔，螺钉头进入 Ø{HEAD_D:g}、深 {HEAD_DEPTH:g} 的沉孔。
2. 手柄朝上，将小轮套在底座较小一端。手柄对准近旁三角孔。把大轮箭头孔对准同侧三角孔，将其沿另一根轴垂直放下，使一边的齿进入另一边的齿槽。
3. 每根轴顶放一片 M4 加大垫圈，再装防松螺母。内六角扳手扶住螺钉头，用 7 mm 扳手把螺母紧到垫圈刚贴实固定轴端。垫圈覆盖轮孔并保留 {END_PLAY:g} 名义轴向游隙。手拨确认齿轮绕固定轴转动。
4. 扶住底座，慢摇小轮两圈。每过半圈停一下，看大轮是否反向走过四分之一圈。小轮一圈时，大轮箭头应指向对侧三角孔；小轮两圈时，双方都回起点。若某处抬轮、跳齿或卡住，回到校准步骤检查。

文件与证据
drawings/ 有 5 张 A4 静态 SVG 图纸，可用浏览器查看或按标注读数。step/ 是三个打印件的独立实体。sg-01-assembly.step 含零位打印件以及简化的螺钉、垫圈和螺母，螺纹用名义圆柱表示。网页三维中五金简画为轴心螺钉。
validation.json 记录 CAD 实体、导出 STL 网格，以及齿面间隙、标记转角、零位装配干涉的数字检查。校准件和样板均待实物试装；打印误差、摩擦、磨损和承载能力需要实物检验。
用 Python 3.11 安装 cadquery==2.7.0，运行 python build.py 可在当前目录的 sg-01-output/ 重新生成。也可设置 ATLAS_BUILD_OUTPUT 指定输出目录。

尺寸依据
样板的轴、配合、减薄量和手柄尺寸来自本项目 CAD。标准直齿轮分度圆、齿顶、齿根及中心距的计算见 Maxwell Tools Company 的 Spur gear formula reference。
{REFERENCE}
"""


def file_digest(path):
    from hashlib import sha256
    return sha256(path.read_bytes()).hexdigest()


def model_input_digest():
    from hashlib import sha256
    # The portion above manifest contains the physical dimensions, gear geometry and placement.
    modeling_code = Path(__file__).read_bytes().split(b"\ndef manifest():", 1)[0]
    return sha256(cq.__version__.encode() + modeling_code).hexdigest()


def export_geometry(geometry):
    for ident, shape in geometry.items():
        cq.exporters.export(shape, str(STL / (ident + ".stl")), tolerance=0.025, angularTolerance=0.12)
    assembly = cq.Assembly(name="SG-01")
    for ident, _, _, color, *_ in PARTS:
        shape = geometry[ident]
        cq.exporters.export(shape, str(STEP / (ident + ".step")))
        rgb = [int(color[i:i+2], 16) / 255 for i in (1, 3, 5)]
        assembly.add(shape, loc=location(ident, 0), name=ident, color=cq.Color(*rgb))
    for side, x in [("input", 0), ("output", CENTER)]:
        for ident, shape in hardware_shapes().items():
            assembly.add(shape, name=side + "_" + ident, loc=cq.Location((x, 0, 0)), color=cq.Color(.48, .51, .52))
    assembly.export(str(DOWNLOAD / "sg-01-assembly.step"))


def write_json(path, data):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf8")


def archive(name, files):
    from zipfile import ZipInfo
    with ZipFile(DOWNLOAD / name, "w") as package:
        for member, path in sorted(files.items()):
            package.writestr(ZipInfo(member), path.read_bytes(), compress_type=ZIP_DEFLATED)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--drawings-only", action="store_true", help="更新已验证版本的图纸和说明")
    args = parser.parse_args()
    for folder in [ASSETS, STL, STEP, DRAW]:
        folder.mkdir(parents=True, exist_ok=True)
    geometry = make_geometry()
    print("6 个 CAD 实体已生成。", flush=True)
    report_path = DOWNLOAD / "validation.json"
    if args.drawings_only:
        report = json.loads(report_path.read_text(encoding="utf8"))
        if (report["geometryInputs"] != model_input_digest() or
                any(file_digest(OUT / p) != h for p,h in report["geometryFiles"].items())):
            raise SystemExit("建模输入或几何文件已变化，请重新生成全部资产。")
    else:
        export_geometry(geometry)
        print("STL 及 STEP 已导出，开始齿面与配合检查。", flush=True)
        report = validate(geometry)
        report["geometryInputs"] = model_input_digest()
        cad_files = [*(STL / (i + ".stl") for i in geometry), *(STEP / (p[0] + ".step") for p in PARTS),
                     DOWNLOAD / "sg-01-assembly.step"]
        report["geometryFiles"] = {p.relative_to(OUT).as_posix(): file_digest(p) for p in cad_files}
    model = manifest()
    write_json(ASSETS / "mechanism.json", model)
    write_json(report_path, report)
    make_drawings(geometry)
    readme = DOWNLOAD / "README-zh.txt"
    readme.write_text(instructions(), encoding="utf8")
    source = DOWNLOAD / "build.py"
    if Path(__file__).resolve() != source.resolve():
        shutil.copyfile(__file__, source)
    drawings = {i + ".svg": DRAW / (i + ".svg") for i, _ in SHEETS}
    archive("sg-01-drawings.zip", drawings)
    archive("sg-01-calibration.zip", {"README-zh.txt": readme, **{i + ".stl": STL / (i + ".stl") for i in COUPONS}})
    files = {"README-zh.txt": readme, "build.py": source, "mechanism.json": ASSETS / "mechanism.json",
             "validation.json": report_path, "sg-01-assembly.step": DOWNLOAD / "sg-01-assembly.step"}
    files.update({"drawings/" + name: p for name, p in drawings.items()})
    files.update({f"stl/{i}.stl": STL / (i + ".stl") for i in geometry})
    files.update({f"step/{p[0]}.step": STEP / (p[0] + ".step") for p in PARTS})
    archive("sg-01-print-package.zip", files)
    print(f"{MODEL} v{VERSION}：{len(files)} 个制作包成员，数字检查完成。", flush=True)


if __name__ == "__main__":
    main()
