# gear.py: an involute spur gear from its equations. The lesson's create_involute_gear(), with two additions:
# it checks its inputs (the Validation tab), and it can cut a bore so the part can sit on a shaft (bore=0 leaves it solid).
# Run it in the FreeCAD Python console:  exec(open('/your/folder/gear.py').read())
# or with no window (FreeCAD 1.1):        freecad.cmd -c "exec(open('/your/folder/gear.py').read())"
# Tested in FreeCAD 1.1.4. The test at the end checks the gear it makes against the numbers on the lesson page.
import math
import FreeCAD as App
import Part


def create_involute_gear(module, num_teeth, pressure_angle=20, thickness=10, bore=0.0):
    """An involute spur gear as a Part solid. Sizes in mm, angle in degrees."""
    if module <= 0:
        raise ValueError("module must be more than 0 mm")
    if num_teeth < 4:
        raise ValueError("need at least 4 teeth")   # a guard against nonsense; a real 20 deg gear under 17 teeth is undercut
    if not 10 <= pressure_angle <= 30:
        raise ValueError("pressure_angle is usually 14.5, 20 or 25 degrees")
    if thickness <= 0:
        raise ValueError("thickness must be more than 0 mm")

    pitch_radius = module * num_teeth / 2.0
    a = math.radians(pressure_angle)
    base_radius = pitch_radius * math.cos(a)
    outer_radius = pitch_radius + module          # addendum: 1 module above the pitch circle
    root_radius = pitch_radius - 1.25 * module    # dedendum: 1.25 modules below it
    if bore and bore / 2.0 > root_radius - 2 * module:
        raise ValueError("bore too large: keep at least 2 modules of metal under the teeth")

    tooth_angle = 2 * math.pi / num_teeth
    half_tooth_angle = math.pi / (2 * num_teeth) + (math.tan(a) - a)   # half a tooth, seen from the centre, at the base circle

    def involute_point(theta):
        return (base_radius * (math.cos(theta) + theta * math.sin(theta)),
                base_radius * (math.sin(theta) - theta * math.cos(theta)))

    def rotate(x, y, angle):
        return (x * math.cos(angle) - y * math.sin(angle), x * math.sin(angle) + y * math.cos(angle))

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

    start_radius = max(base_radius, root_radius)          # the involute exists only outside the base circle
    theta_start = math.sqrt((start_radius / base_radius) ** 2 - 1)
    theta_end = math.sqrt((outer_radius / base_radius) ** 2 - 1)

    edges = []
    for tooth_num in range(num_teeth):
        angle_offset = tooth_num * tooth_angle
        flank1, flank2 = [], []
        for i in range(20):                                   # 20 points on each flank
            theta = theta_start + (theta_end - theta_start) * i / 19.0
            x, y = involute_point(theta)
            flank1.append(App.Vector(*rotate(x, y, angle_offset - half_tooth_angle), 0))
            flank2.append(App.Vector(*rotate(x, -y, angle_offset + half_tooth_angle), 0))
        flank2.reverse()

        flank_start = theta_start - math.atan(theta_start)
        start_angle = angle_offset - half_tooth_angle + flank_start
        end_angle = angle_offset + half_tooth_angle - flank_start
        next_start_angle = start_angle + tooth_angle

        if root_radius < start_radius:                        # a short radial line from the root circle to the base circle
            edges.append(Part.LineSegment(polar(root_radius, start_angle), flank1[0]).toShape())
        curve = Part.BSplineCurve(); curve.interpolate(flank1); edges.append(curve.toShape())
        edges.append(Part.Arc(flank1[-1], polar(outer_radius, angle_offset), flank2[0]).toShape())
        curve = Part.BSplineCurve(); curve.interpolate(flank2); edges.append(curve.toShape())
        if root_radius < start_radius:
            edges.append(Part.LineSegment(flank2[-1], polar(root_radius, end_angle)).toShape())
        edges.append(Part.Arc(polar(root_radius, end_angle),
                              polar(root_radius, (end_angle + next_start_angle) / 2),
                              polar(root_radius, next_start_angle)).toShape())

    solid = Part.Face(Part.Wire(edges)).extrude(App.Vector(0, 0, thickness))
    if bore:
        solid = solid.cut(Part.makeCylinder(bore / 2.0, thickness + 2, App.Vector(0, 0, -1)))
    return solid


def gear_numbers(shape, module, num_teeth, pressure_angle=20):
    """Measure a gear the script made: the numbers a reader checks with Tools > Measure."""
    rp = module * num_teeth / 2.0
    radii = [math.hypot(v.X, v.Y) for v in shape.Vertexes]
    cut = shape.section(Part.makeCircle(rp, App.Vector(0, 0, shape.BoundBox.ZMin + shape.BoundBox.ZLength / 2)))
    angles = sorted((math.atan2(v.Y, v.X) for v in cut.Vertexes), key=abs)[:2]   # the two sides of tooth 0, which sits at 0 deg
    return {
        'valid': shape.isValid(), 'solids': len(shape.Solids),
        'outer_d': 2 * max(radii), 'root_d': 2 * min(r for r in radii if r > rp / 2),
        'pitch_d': 2 * rp, 'base_d': 2 * rp * math.cos(math.radians(pressure_angle)),
        'tooth_at_pitch': rp * abs(angles[0] - angles[1]),
        'volume_cm3': shape.Volume / 1000.0,
    }


if __name__ == '__main__':
    gear = create_involute_gear(module=2.5, num_teeth=24, thickness=10)
    Part.show(gear, "InvoluteGear")
    n = gear_numbers(gear, 2.5, 24)
    print("Involute gear: module 2.5, 24 teeth, 20 deg, 10 mm thick")
    for k in ('pitch_d', 'base_d', 'outer_d', 'root_d', 'tooth_at_pitch'):
        print("  %-15s %8.3f mm" % (k, n[k]))
    print("  %-15s %8.2f cm3" % ('volume', n['volume_cm3']))

    # ---- test: the numbers on the lesson page
    assert n['valid'] and n['solids'] == 1, "not one valid solid"
    assert abs(n['outer_d'] - 65.0) < 1e-6, n['outer_d']          # tip radius 32.5
    assert abs(n['root_d'] - 53.75) < 1e-6, n['root_d']           # root radius 26.875
    assert abs(n['tooth_at_pitch'] - math.pi * 2.5 / 2) < 1e-3, n['tooth_at_pitch']   # 3.93 mm
    assert abs(n['volume_cm3'] - 27.740) < 0.01, n['volume_cm3']
    bored = create_involute_gear(module=2.5, num_teeth=24, thickness=10, bore=8)
    assert bored.isValid() and abs(bored.Volume - (gear.Volume - math.pi * 16 * 10)) < 0.01
    for bad in ({'module': 0, 'num_teeth': 24}, {'module': 2.5, 'num_teeth': 3}, {'module': 2.5, 'num_teeth': 24, 'bore': 50}):
        try:
            create_involute_gear(**bad); raise AssertionError("bad input was accepted: %s" % bad)
        except ValueError:
            pass
    print("TEST gear.py: PASS")
