// Chair leg foot / cap with a rounded (half-sphere) bottom.
// All sizes in mm. Change the parameters below and re-export.
// Parametric: measure your own leg and change the values under "Leg measurements".
// Write-up: https://www.marius.digital/claude-code-3d-printing-openscad/

// --- Leg measurements ---
leg_d_bottom = 16.2;   // leg diameter at its flat end
leg_d_top    = 17.2;   // diameter of the opening at socket_depth above the end (measured 18.2;
                       // the first print was ~1 mm loose at the opening, so 17.2)
socket_depth = 20;     // how far the cap goes up the leg

// --- Variant ---
// 0 = standard shoe (legs that still have their original 4 mm pad)
// 4 = shoe for the leg whose pad broke: same outside, bottom 4 mm of the socket filled in
filler = 0;

// --- Fit and strength ---
clearance = 0.2;       // added to the hole diameter; lower = tighter
wall      = 2.5;       // side wall thickness
dome_h    = (leg_d_bottom + clearance) / 2 + wall;  // full half-sphere; set a smaller number for a flatter dome
lead_in   = 0.6;       // chamfer at the opening so it slides on easily

// --- Output ---
print_orientation = true;  // true = open end down, dome up (no supports needed)

$fn = 128;
arc_steps = 48;        // smoothness of the rounded bottom

hole_r1 = (leg_d_bottom + clearance) / 2;
hole_r2 = (leg_d_top + clearance) / 2;
out_r1  = hole_r1 + wall;
out_r2  = hole_r2 + wall;
total_h = dome_h + socket_depth;        // same for every variant
floor_z = dome_h + filler;              // height of the socket floor
floor_r = hole_r1 + (hole_r2 - hole_r1) * filler / socket_depth;  // same cone, just cut off higher

// Half cross-section (x = radius, y = height), spun around the vertical axis.
// The bottom is a quarter-ellipse: a quarter-circle when dome_h == out_r1.
function bottom_arc() = [
    for (i = [0 : arc_steps])
        let (a = 90 * i / arc_steps)
        [out_r1 * sin(a), dome_h * (1 - cos(a))]
];

module foot() {
    // The intersection with a big box changes nothing in the shape, but makes the mesh engine
    // rebuild the mesh and drop the zero-size triangles rotate_extrude leaves on the axis.
    intersection() {
        cube(200, center = true);
        rotate_extrude()
            polygon(concat(
                bottom_arc(),                                   // floor contact up to the side wall
                [
                    [out_r2,               total_h],            // outer wall, following the leg's taper
                    [hole_r2 + lead_in,    total_h],            // rim
                    [hole_r2,              total_h - lead_in],  // lead-in chamfer
                    [floor_r,              floor_z],            // socket wall
                    [0,                    floor_z]             // socket floor, back to the axis
                ]
            ));
    }
}

if (print_orientation)
    translate([0, 0, total_h]) rotate([180, 0, 0]) foot();
else
    foot();
