# from solid2 import cube, cylinder, set_global_fn

# set_global_fn(100)

# c = cylinder(r=13, h=40).rotate([0,90,0])


# k = cube(0.5,0.2,0.5)
# a = 0
# b = 0
# for i in range(5):
#     for i in range(50):
#         c -= k.translate([0+a,12.8,-0.25])
#         a += 1
#     k.rotate([90,0,0])
# c.save_as_stl('knurl.stl')




from solid2 import *

SEGMENTS = 64 # Increase for smoother cylinder and texture
set_global_fn(SEGMENTS)

def cylinder_knurl(
    radius,
    height,
    bump_radius=0.5,
    bump_height=0.3,
    num_bumps=60 # Number of bumps around the circumference
):
    """
    Creates a knurled texture that wraps around a cylinder.
    """
    bumps = []
    angle_step = 360 / num_bumps

    for i in range(num_bumps):
        angle = i * angle_step
        # Calculate position on the cylinder's surface
        # Start by placing a bump directly on the X axis at the radius
        # Then rotate it around the Z axis
        bump_position_x = radius + (bump_height / 2) # Place bump slightly outside the radius for positive texture
        bump = translate([bump_position_x, 0, 0])(
            rotate(a=angle, v=[0,0,1])( # Rotate around Z axis
                cylinder(r=bump_radius, h=bump_height, center=True) # Center the bump itself
            )
        )
        bumps.append(bump)

    # Union all the individual bumps
    return union()(bumps)

def create_knurled_handle():
    handle_radius = 15
    handle_height = 80

    # Base cylinder for the handle
    handle_body = cylinder(r=handle_radius, h=handle_height, center=True)

    # Create the knurl texture
    knurl_texture_obj = cylinder_knurl(
        radius=handle_radius,
        height=handle_height, # This doesn't directly use the height parameter for cylinder_knurl, but useful for context
        bump_radius=0.4,
        bump_height=0.5,
        num_bumps=80 # More bumps for finer texture
    )

    # Position the texture along the Z-axis of the handle body
    # The `cylinder_knurl` creates bumps at Z=0. We want them along the handle's height.
    # We can also stack layers of knurling if desired.
    knurl_layers = []
    knurl_spacing = 1.0 # Vertical spacing between rows of knurls

    # Make multiple rows of knurling
    num_rows = int(handle_height / knurl_spacing)
    for row in range(num_rows):
        z_offset = (row * knurl_spacing) - (handle_height / 2) + (knurl_spacing / 2)
        knurl_layers.append(translate([0,0,z_offset])(knurl_texture_obj))


    # Union the main body with all the knurl layers
    return union()(handle_body, union()(knurl_layers))

if __name__ == '__main__':
    scad_code = scad_render(create_knurled_handle())
    with open("knurled_handle.scad", "w") as f:
        f.write(scad_code)
    print("Generated knurled_handle.scad")