1/////////////////////////////////////////////////////////////////////
   2// LibFile: rounding.scad
   3//   Routines to create rounded corners, with either circular rounding,
   4//   or continuous curvature rounding with no sudden curvature transitions.
   5//   Provides rounding of corners or rounding that preserves corner points and curves the edges.
   6//   Also provides some 3D rounding functions, and a powerful function for joining
   7//   two prisms together with a rounded fillet at the joint.  
   8// Includes:
   9//   include <BOSL2/std.scad>
  10//   include <BOSL2/rounding.scad>
  11// FileGroup: Advanced Modeling
  12// FileSummary: Round path corners, rounded prisms, rounded cutouts in tubes, filleted prism joints
  13//////////////////////////////////////////////////////////////////////
  14include <beziers.scad>
  15include <structs.scad>
  16
  17// Section: Types of Roundovers
  18//   The functions and modules in this file support two different types of roundovers and some different mechanisms for specifying
  19//   the size of the roundover.  The usual circular roundover can produce a tactile "bump" where the curvature changes from flat to
  20//   circular.  See https://hackernoon.com/apples-icons-have-that-shape-for-a-very-good-reason-720d4e7c8a14 for details.
  21//   We compute continuous curvature rounding using 4th order Bezier curves.  This type of rounding, which we call "smooth" rounding,
  22//   does not have a "radius" so we need different ways to specify the size of the roundover.  We introduce the `cut` and `joint`
  23//   parameters for this purpose.  They can specify dimensions of circular roundovers, continuous curvature "smooth" roundovers, and even chamfers.  
  24//   .
  25//   The `cut` parameter specifies the distance from the unrounded corner to the rounded tip, so how
  26//   much of the corner to "cut" off.  This can be easier to understand than setting a circular radius, which can be
  27//   unexpectedly extreme when the corner is very sharp.  It also allows a systematic specification of
  28//   corner treatments that are the same size for all corner treatments.
  29//   .
  30//   The `joint` parameter specifies the distance
  31//   away from the corner along the path where the roundover or chamfer should start.  This parameter is good for ensuring that
  32//   your roundover will fit on the polygon or polyhedron, since you can easily tell whether you have enough space, and whether
  33//   adjacent corner treatments will interfere.
  34//   .
  35//   For circular rounding you can use the `radius` or `r` parameter to set the rounding radius.
  36//   .
  37//   For chamfers you can use `width` to set the width of the chamfer.  
  38//   .
  39//   The "smooth" rounding method also has a parameter that specifies how smooth the curvature match is.  This parameter, `k`,
  40//   ranges from 0 to 1, with a default of 0.5.  Larger values gives a more 
  41//   abrupt transition and smaller ones a more gradual transition.  If you set the value much higher
  42//   than 0.8 the curvature changes abruptly enough that though it is theoretically continuous, it may
  43//   not be continuous in practice.  If you set it very small then the transition is so gradual that
  44//   the length of the roundover may be extremely long, and the actual rounded part of the curve may be very small.  
  45// Figure(2D,Med,NoAxes):  Parameters of a "circle" roundover
  46//   h = 18;
  47//   w = 12.6;
  48//   strokewidth = .3;
  49//   example = [[0,0],[w,h],[2*w,0]];
  50//   stroke(example, width=strokewidth*1.5);
  51//   textangle = 90-vector_angle(example)/2;
  52//   theta = vector_angle(example)/2;
  53//   color("green"){ stroke([[w,h], [w,h-18*(1-sin(theta))/cos(theta)]], width=strokewidth, endcaps="arrow2");
  54//                   translate([w-1.75,h-7])scale(.1)rotate(textangle)text("cut",size=14); }
  55//   ll=lerp([w,h], [0,0],18/norm([w,h]-[0,0]) );
  56//   color("blue"){ stroke(_shift_segment([[w,h], ll], -.7), width=strokewidth,endcaps="arrow2");
  57//                  translate([w/2-1.3,h/2+.6])  scale(.1)rotate(textangle)text("joint",size=14);}
  58//   color("red")stroke(
  59//         select(round_corners(example, joint=18, method="circle",$fn=64,closed=false),1,-2),
  60//         width=strokewidth);
  61//   r=18*tan(theta);
  62//   color("black"){
  63//     stroke([ll, [w,h-r-18*(1-sin(theta))/cos(theta)]], width=strokewidth, endcaps="arrow2");
  64//     translate([w/1.6,0])text("radius", size=1.4);
  65//   }
  66// Figure(2D,Med,NoAxes):  Parameters of a "smooth" roundover with the default of `k=0.5`.  Note the long, slow transition from flat to round.  
  67//   h = 18;
  68//   w = 12.6;
  69//   strokewidth = .3;
  70//   example = [[0,0],[w,h],[2*w,0]];
  71//   stroke(example, width=strokewidth*1.5);
  72//   textangle = 90-vector_angle(example)/2;
  73//   color("green"){ stroke([[w,h], [w,h-cos(vector_angle(example)/2) *3/8*h]], width=strokewidth, endcaps="arrow2");
  74//                   translate([w-1.75,h-5.5])scale(.1)rotate(textangle)text("cut",size=14); }
  75//   ll=lerp([w,h], [0,0],18/norm([w,h]-[0,0]) );
  76//   color("blue"){ stroke(_shift_segment([[w,h], ll], -.7), width=strokewidth,endcaps="arrow2");
  77//                  translate([w/2-1.3,h/2+.6])  scale(.1)rotate(textangle)text("joint",size=14);}
  78//   color("red")stroke(
  79//         select(round_corners(example, joint=18, method="smooth",closed=false),1,-2),
  80//         width=strokewidth);
  81// Figure(2D,Med,NoAxes):  Parameters of a "smooth" roundover, with `k=0.75`.  The transition into the roundover is shorter, and faster.  The cut length is bigger for the same joint length.
  82//   h = 18;
  83//   w = 12.6;
  84//   strokewidth = .3;
  85//   example = [[0,0],[w,h],[2*w,0]];
  86//   stroke(example, width=strokewidth*1.5);
  87//   textangle = 90-vector_angle(example)/2;
  88//   color("green"){ stroke([[w,h], [w,h-cos(vector_angle(example)/2) *4/8*h]], width=strokewidth, endcaps="arrow2");
  89//                   translate([w-1.75,h-5.5])scale(.1)rotate(textangle)text("cut",size=14); }
  90//   ll=lerp([w,h], [0,0],18/norm([w,h]-[0,0]) );
  91//   color("blue"){ stroke(_shift_segment([[w,h], ll], -.7), width=strokewidth,endcaps="arrow2");
  92//                  translate([w/2-1.3,h/2+.6])  scale(.1)rotate(textangle)text("joint",size=14);}
  93//   color("red")stroke(
  94//         select(round_corners(example, joint=18, method="smooth",closed=false,k=.75),1,-2),
  95//         width=strokewidth);
  96// Figure(2D,Med,NoAxes):  Parameters of a "smooth" roundover, with `k=0.15`.  The transition is so gradual that it appears that the roundover is much smaller than specified.  The cut length is much smaller for the same joint length.  
  97//   h = 18;
  98//   w = 12.6;
  99//   strokewidth = .3;
 100//   example = [[0,0],[w,h],[2*w,0]];
 101//   stroke(example, width=strokewidth*1.5);
 102//   textangle = 90-vector_angle(example)/2;
 103//   color("green"){ stroke([[w,h], [w,h-cos(vector_angle(example)/2) *1.6/8*h]], width=strokewidth, endcaps="arrow2");
 104//                   translate([w+.3,h])text("cut",size=1.4); }
 105//   ll=lerp([w,h], [0,0],18/norm([w,h]-[0,0]) );
 106//   color("blue"){ stroke(_shift_segment([[w,h], ll], -.7), width=strokewidth,endcaps="arrow2");
 107//                  translate([w/2-1.3,h/2+.6])  scale(.1)rotate(textangle)text("joint",size=14);}
 108//   color("red")stroke(
 109//         select(round_corners(example, joint=18, method="smooth",closed=false,k=.15),1,-2),
 110//         width=strokewidth);
 111// Figure(2D,Med,NoAxes):  Parameters of a symmetric "chamfer".
 112//   h = 18;
 113//   w = 12.6;
 114//   strokewidth = .3;
 115//   example = [[0,0],[w,h],[2*w,0]];
 116//   stroke(example, width=strokewidth*1.5);
 117//   textangle = 90-vector_angle(example)/2;
 118//   color("black"){
 119//        stroke(fwd(1,
 120//         select(round_corners(example, joint=18, method="chamfer",closed=false),1,-2)),
 121//         width=strokewidth,endcaps="arrow2");
 122//        translate([w,.3])text("width", size=1.4,halign="center");
 123//   }     
 124//   color("green"){ stroke([[w,h], [w,h-18*cos(vector_angle(example)/2)]], width=strokewidth, endcaps="arrow2");
 125//                   translate([w-1.75,h-5.5])scale(.1)rotate(textangle)text("cut",size=14); }
 126//   ll=lerp([w,h], [0,0],18/norm([w,h]-[0,0]) );
 127//   color("blue"){ stroke(_shift_segment([[w,h], ll], -.7), width=strokewidth,endcaps="arrow2");
 128//                  translate([w/2-1.3,h/2+.6]) rotate(textangle)text("joint",size=1.4);}
 129//   color("red")stroke(
 130//         select(round_corners(example, joint=18, method="chamfer",closed=false),1,-2),
 131//         width=strokewidth);
 132
 133
 134// Section: Rounding Paths
 135
 136// Function: round_corners()
 137// Synopsis: Round or chamfer the corners of a path (clipping them off).
 138// SynTags: Path
 139// Topics: Rounding, Paths
 140// See Also: round_corners(), smooth_path(), path_join(), offset_stroke()
 141// Usage:
 142//   rounded_path = round_corners(path, [method], [radius=], [cut=], [joint=], [closed=], [verbose=]);
 143// Description:
 144//   Takes a 2D or 3D path as input and rounds each corner
 145//   by a specified amount.  The rounding at each point can be different and some points can have zero
 146//   rounding.  The `round_corners()` function supports three types of corner treatment: chamfers, circular rounding,
 147//   and continuous curvature rounding using 4th order bezier curves.  See
 148//   [Types of Roundover](rounding.scad#subsection-types-of-roundover) for details on rounding types.  
 149//   .
 150//   You select the type of rounding using the `method` parameter, which should be `"smooth"` to
 151//   get continuous curvature rounding, `"circle"` to get circular rounding, or `"chamfer"` to get chamfers.  The default is circle
 152//   rounding.  Each method accepts multiple options to specify the amount of rounding.  See
 153//   [Types of Roundover](rounding.scad#subsection-types-of-roundover) for example diagrams.
 154//   .
 155//   * The `cut` parameter specifies the distance from the unrounded corner to the rounded tip, so how
 156//   much of the corner to "cut" off.  
 157//   * The `joint` parameter specifies the distance
 158//   away from the corner along the path where the roundover or chamfer should start.  This makes it easy to ensure your roundover will fit,
 159//   so use it if you want the largest possible roundover.  
 160//   * For circular rounding you can use the `radius` or `r` parameter to set the rounding radius.
 161//   * For chamfers you can use the `width` parameter, which sets the width of the chamfer edge.  
 162//   .
 163//   As explained in [Types of Roundover](rounding.scad#subsection-types-of-roundover), the continuous curvature "smooth"
 164//   type of rounding also accepts the `k` parameter, between 0 and 1, which specifies how fast the curvature changes at
 165//   the joint.  The default is `k=0.5`.  
 166//   .
 167//   If you select curves that are too large to fit the function will fail with an error.  You can set `verbose=true` to
 168//   get a message showing a list of scale factors you can apply to your rounding parameters so that the
 169//   roundovers will fit on the curve.  If the scale factors are larger than one
 170//   then they indicate how much you can increase the curve sizes before collisions will occur.
 171//   .
 172//   The parameters `radius`, `cut`, `joint` and `k` can be numbers, which round every corner using the same parameters, or you
 173//   can specify a list to round each corner with different parameters.  If the curve is not closed then the first and last points
 174//   of the curve are not rounded.  In this case you can specify a full list of points anyway, and the endpoint values are ignored,
 175//   or you can specify a list that has length len(path)-2, omitting the two dummy values.
 176//   .
 177//   If your input path includes collinear points you must use a cut or radius value of zero for those "corners".  You can
 178//   choose a nonzero joint parameter when the collinear points form a 180 degree angle.  This will cause extra points to be inserted. 
 179//   If the collinear points form a spike (0 degree angle) then round_corners will fail. 
 180//   .
 181//   Examples:
 182//   * `method="circle", radius=2`:
 183//       Rounds every point with circular, radius 2 roundover
 184//   * `method="smooth", cut=2`:
 185//       Rounds every point with continuous curvature rounding with a cut of 2, and a default 0.5 smoothing parameter
 186//   * `method="smooth", cut=2, k=0.3`:
 187//       Rounds every point with continuous curvature rounding with a cut of 2, and a very gentle 0.3 smoothness setting
 188//   .
 189//   The number of segments used for roundovers is determined by `$fa`, `$fs` and `$fn` as usual for
 190//   circular roundovers.  For continuous curvature roundovers `$fs` and `$fn` are used and `$fa` is
 191//   ignored.  Note that $fn is interpreted as the number of points on the roundover curve, which is
 192//   not equivalent to its meaning for rounding circles because roundovers are usually small fractions
 193//   of a circular arc.  As usual, $fn overrides $fs.  When doing continuous curvature rounding be sure to use lots of segments or the effect
 194//   will be hidden by the discretization.  Note that if you use $fn with "smooth" then $fn points are added at each corner.
 195//   This guarantees a specific output length.  It also means that if
 196//   you set `joint` nonzero on a flat "corner", with collinear points, you will get $fn points at that "corner."
 197//   If you have two roundovers that fully consume a segment then they share a point where they meet in the segment, which means the output
 198//   point count will be decreased by one.  
 199// Arguments:
 200//   path = list of 2d or 3d points defining the path to be rounded.
 201//   method = rounding method to use.  Set to "chamfer" for chamfers, "circle" for circular rounding and "smooth" for continuous curvature 4th order bezier rounding.  Default: "circle"
 202//   ---
 203//   radius/r = rounding radius, only compatible with `method="circle"`. Can be a number or vector.
 204//   cut = rounding cut distance, compatible with all methods.  Can be a number or vector.
 205//   joint = rounding joint distance, compatible with `method="chamfer"` and `method="smooth"`.  Can be a number or vector.
 206//   width = width of the flat edge created by chamfering, compatible with `method="chamfer"`.  Can be a number or vector. 
 207//   k = continuous curvature smoothness parameter for `method="smooth"`.  Can be a number or vector.  Default: 0.5
 208//   closed = if true treat the path as a closed polygon, otherwise treat it as open.  Default: true.
 209//   verbose = if true display rounding scale factors that show how close roundovers are to overlapping.  Default: false
 210//
 211// Example(2D,Med): Standard circular roundover with radius the same at every point. Compare results at the different corners.
 212//   $fn=36;
 213//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 214//   polygon(round_corners(shape, radius=1));
 215//   color("red") down(.1) polygon(shape);
 216// Example(2D,Med): Circular roundover using the "cut" specification, the same at every corner.
 217//   $fn=36;
 218//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 219//   polygon(round_corners(shape, cut=1));
 220//   color("red") down(.1) polygon(shape);
 221// Example(2D,Med): Continous curvature roundover using "cut", still the same at every corner.  The default smoothness parameter of 0.5 was too gradual for these roundovers to fit, but 0.7 works.
 222//   $fn=36;
 223//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 224//   polygon(round_corners(shape, method="smooth", cut=1, k=0.7));
 225//   color("red") down(.1) polygon(shape);
 226// Example(2D,Med): Continuous curvature roundover using "joint", for the last time the same at every corner.  Notice how small the roundovers are.
 227//   $fn=36;
 228//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 229//   polygon(round_corners(shape, method="smooth", joint=1, k=0.7));
 230//   color("red") down(.1) polygon(shape);
 231// Example(2D,Med): Circular rounding, different at every corner, some corners left unrounded
 232//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 233//   radii = [1.8, 0, 2, 0.3, 1.2, 0];
 234//   polygon(round_corners(shape, radius = radii,$fn=64));
 235//   color("red") down(.1) polygon(shape);
 236// Example(2D,Med): Continuous curvature rounding, different at every corner, with varying smoothness parameters as well, and `$fs` set very small.  Note that `$fa` is ignored here with method set to "smooth".
 237//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 238//   cuts = [1.5,0,2,0.3, 1.2, 0];
 239//   k = [0.6, 0.5, 0.5, 0.7, 0.3, 0.5];
 240//   polygon(round_corners(shape, method="smooth", cut=cuts, k=k, $fs=0.1));
 241//   color("red") down(.1) polygon(shape);
 242// Example(2D,Med): Chamfers
 243//   $fn=36;
 244//   shape = [[0,0], [10,0], [15,12], [6,6], [6, 12], [-3,7]];
 245//   polygon(round_corners(shape, method="chamfer", cut=1));
 246//   color("red") down(.1) polygon(shape);
 247// Example(Med3D): 3D printing test pieces to display different curvature shapes.  You can see the discontinuity in the curvature on the "C" piece in the rendered image.
 248//   ten = square(50);
 249//   cut = 5;
 250//   linear_extrude(height=14) {
 251//     translate([25,25,0])text("C",size=30, valign="center", halign="center");
 252//     translate([85,25,0])text("5",size=30, valign="center", halign="center");
 253//     translate([85,85,0])text("3",size=30, valign="center", halign="center");
 254//     translate([25,85,0])text("7",size=30, valign="center", halign="center");
 255//   }
 256//   linear_extrude(height=13) {
 257//     polygon(round_corners(ten, cut=cut, $fn=96*4));
 258//     translate([60,0,0])polygon(round_corners(ten,  method="smooth", cut=cut, $fn=96));
 259//     translate([60,60,0])polygon(round_corners(ten, method="smooth", cut=cut, k=0.32, $fn=96));
 260//     translate([0,60,0])polygon(round_corners(ten, method="smooth", cut=cut, k=0.7, $fn=96));
 261//   }
 262// Example(2D,Med): Rounding a path that is not closed in a three different ways.
 263//   $fs=.1;
 264//   $fa=1;
 265//   zigzagx = [-10, 0, 10, 20, 29, 38, 46, 52, 59, 66, 72, 78, 83, 88, 92, 96, 99, 102, 112];
 266//   zigzagy = concat([0], flatten(repeat([-10,10],8)), [-10,0]);
 267//   zig = hstack(zigzagx,zigzagy);
 268//   stroke(zig,width=1);   // Original shape
 269//   fwd(20)            // Smooth size corners with a cut of 4 and curvature parameter 0.6
 270//     stroke(round_corners(zig,cut=4, k=0.6, method="smooth", closed=false),width=1);
 271//   fwd(40)            // Smooth size corners with circular arcs and a cut of 4
 272//     stroke(round_corners(zig,cut=4,closed=false, method="circle"),width=1);
 273//                      // Smooth size corners with a circular arc and radius 1.5 (close to maximum possible)
 274//   fwd(60)            // Note how the different points are cut back by different amounts
 275//     stroke(round_corners(zig,radius=1.5,closed=false),width=1);
 276// Example(FlatSpin,VPD=42,VPT=[7.75,6.69,5.22]): Rounding some random 3D paths
 277//   $fn=36;
 278//   list1= [
 279//     [2.887360, 4.03497, 6.372090],
 280//     [5.682210, 9.37103, 0.783548],
 281//     [7.808460, 4.39414, 1.843770],
 282//     [0.941085, 5.30548, 4.467530],
 283//     [1.860540, 9.81574, 6.497530],
 284//     [6.938180, 7.21163, 5.794530]
 285//   ];
 286//   list2= [
 287//     [1.079070, 4.74091, 6.900390],
 288//     [8.775850, 4.42248, 6.651850],
 289//     [5.947140, 9.17137, 6.156420],
 290//     [0.662660, 6.95630, 5.884230],
 291//     [6.564540, 8.86334, 9.953110],
 292//     [5.420150, 4.91874, 3.866960]
 293//   ];
 294//   path_sweep(regular_ngon(n=36,or=.1),round_corners(list1,closed=false, method="smooth", cut = 0.65));
 295//   right(6)
 296//     path_sweep(regular_ngon(n=36,or=.1),round_corners(list2,closed=false, method="circle", cut = 0.75));
 297// Example(3D,Med):  Rounding a spiral with increased rounding along the length
 298//   // Construct a square spiral path in 3D
 299//   $fn=36;
 300//   square = [[0,0],[1,0],[1,1],[0,1]];
 301//   spiral = flatten(repeat(concat(square,reverse(square)),5));  // Squares repeat 10x, forward and backward
 302//   squareind = [for(i=[0:9]) each [i,i,i,i]];                   // Index of the square for each point
 303//   z = count(40)*.2+squareind;
 304//   path3d = hstack(spiral,z);                                   // 3D spiral
 305//   rounding = squareind/20;
 306//       // Setting k=1 means curvature won't be continuous, but curves are as round as possible
 307//       // Try changing the value to see the effect.
 308//   rpath = round_corners(path3d, joint=rounding, k=1, method="smooth", closed=false);
 309//   path_sweep( regular_ngon(n=36, or=.1), rpath);
 310// Example(2D): The rounding invocation that is commented out gives an error because the rounding parameters interfere with each other.  The error message gives a list of factors that can help you fix this: [0.852094, 0.852094, 1.85457, 10.1529]
 311//   $fn=64;
 312//   path = [[0, 0],[10, 0],[20, 20],[30, -10]];
 313//   debug_polygon(path);
 314//   //polygon(round_corners(path,cut = [1,3,1,1],
 315//   //        method="circle"));
 316// Example(2D): The list of factors shows that the problem is in the first two rounding values, because the factors are smaller than one.  If we multiply the first two parameters by 0.85 then the roundings fit.  The verbose option gives us the same fit factors.  
 317//   $fn=64;
 318//   path = [[0, 0],[10, 0],[20, 20],[30, -10]];
 319//   polygon(round_corners(path,cut = [0.85,3*0.85,1,1],
 320//                         method="circle", verbose=true));
 321// Example(2D): From the fit factors we can see that rounding at vertices 2 and 3 could be increased a lot.  Applying those factors we get this more rounded shape.  The new fit factors show that we can still further increase the rounding parameters if we wish.  
 322//   $fn=64;
 323//   path = [[0, 0],[10, 0],[20, 20],[30, -10]];
 324//   polygon(round_corners(path,cut = [0.85,3*0.85,2.13, 10.15],
 325//                         method="circle",verbose=true));
 326// Example(2D): Using the `joint` parameter it's easier to understand whether your roundvers will fit.  We can guarantee a fairly large roundover on any path by picking each one to use up half the segment distance along the shorter of its two segments:
 327//   $fn=64;
 328//   path = [[0, 0],[10, 0],[20, 20],[30, -10]];
 329//   path_len = path_segment_lengths(path,closed=true);
 330//   halflen = [for(i=idx(path)) min(select(path_len,i-1,i))/2];
 331//   polygon(round_corners(path,joint = halflen,
 332//                         method="circle",verbose=true));
 333// Example(2D): Chamfering, specifying the chamfer width
 334//   path = star(5, step=2, d=100);
 335//   path2 = round_corners(path, method="chamfer", width=5);
 336//   polygon(path2);
 337// Example(2D): Chamfering, specifying the cut
 338//   path = star(5, step=2, d=100);
 339//   path2 = round_corners(path, method="chamfer", cut=5);
 340//   polygon(path2);
 341// Example(2D): Chamfering, specifying joint length
 342//   path = star(5, step=2, d=100);
 343//   path2 = round_corners(path, method="chamfer", joint=5);
 344//   polygon(path2);
 345// Example(2D): Two passes to apply chamfers first, and then round the unchamfered corners.  Chamfers always add one point, so it's not hard to keep track of the vertices
 346//   $fn=32;
 347//   shape = square(10);
 348//   chamfered = round_corners(shape, method="chamfer",
 349//                             cut=[2,0,2,0]);
 350//   rounded = round_corners(chamfered, 
 351//              cut = [0, 0,  // 1st original vertex, chamfered
 352//                     1.5,   // 2nd original vertex
 353//                     0, 0,  // 3rd original vertex, chamfered
 354//                     2.5]); // 4th original vertex
 355//   polygon(rounded);
 356// Example(2D): Another example of mixing chamfers and roundings with two passes
 357//   path = star(5, step=2, d=100);
 358//   chamfcut = [for (i=[0:4]) each [7,0]];
 359//   radii = [for (i=[0:4]) each [0,0,10]];
 360//   path2=round_corners(
 361//           round_corners(path,
 362//                         method="chamfer",
 363//                         cut=chamfcut),
 364//           radius=radii);
 365//   stroke(path2, closed=true);
 366// Example(2D,Med,NoAxes): Specifying by corner index.  Use {{list_set()}} to construct the full chamfer cut list. 
 367//   path = star(47, ir=25, or=50);  // long path, lots of corners
 368//   chamfind = [8, 28, 60];         // But only want 3 chamfers
 369//   chamfcut = list_set([],chamfind,[10,13,15],minlen=len(path));
 370//   rpath = round_corners(path, cut=chamfcut, method="chamfer");   
 371//   polygon(rpath);
 372// Example(2D,Med,NoAxes): Two-pass to chamfer and round by index.  Use {{repeat_entries()}} to correct for first pass chamfers.
 373//   $fn=32;
 374//   path = star(47, ir=32, or=65);  // long path, lots of corners
 375//   chamfind = [8, 28, 60];         // But only want 3 chamfers
 376//   roundind = [7,9,27,29,59,61];   // And 6 roundovers
 377//   chamfcut = list_set([],chamfind,[10,13,15],minlen=len(path));
 378//   roundcut = list_set([],roundind,repeat(8,6),minlen=len(path));
 379//   dups = list_set([], chamfind, repeat(2,len(chamfind)), dflt=1, minlen=len(path));
 380//   rpath1 = round_corners(path, cut=chamfcut, method="chamfer");
 381//   rpath2 = round_corners(rpath1, cut=repeat_entries(roundcut,dups));
 382//   polygon(rpath2);
 383module round_corners(path, method="circle", radius, r, cut, joint, width, k, closed=true, verbose=false) {no_module();}
 384function round_corners(path, method="circle", radius, r, cut, joint, width, k, closed=true, verbose=false) =
 385    assert(in_list(method,["circle", "smooth", "chamfer"]), "method must be one of \"circle\", \"smooth\" or \"chamfer\"")
 386    let(
 387        default_k = 0.5,
 388        size=one_defined([radius, r, cut, joint, width], "radius,r,cut,joint,width"),
 389        path = force_path(path), 
 390        size_ok = is_num(size) || len(size)==len(path) || (!closed && len(size)==len(path)-2),
 391        k_ok = is_undef(k) || (method=="smooth" && (is_num(k) || len(k)==len(path) || (!closed && len(k)==len(path)-2))),
 392        measure = is_def(radius) ? "radius"
 393                : is_def(r) ? "radius"
 394                : is_def(cut) ? "cut" 
 395                : is_def(joint) ? "joint"
 396                : "width"
 397    )
 398    assert(is_path(path,[2,3]), "input path must be a 2d or 3d path")
 399    assert(len(path)>2,str("Path has length ",len(path),".  Length must be 3 or more."))
 400    assert(size_ok,str("Input ",measure," must be a number or list with length ",len(path), closed?"":str(" or ",len(path)-2)))
 401    assert(k_ok,method=="smooth" ? str("Input k must be a number or list with length ",len(path), closed?"":str(" or ",len(path)-2)) :
 402                                   "Input k is only allowed with method=\"smooth\"")
 403    assert(method=="circle" || measure!="radius", "radius parameter allowed only with method=\"circle\"")
 404    assert(method=="chamfer" || measure!="width", "width parameter  allowed only with method=\"chamfer\"")
 405    let(
 406        parm = is_num(size) ? repeat(size, len(path)) :
 407               len(size)<len(path) ? [0, each size, 0] :
 408                                     size,
 409        k = is_undef(k) ? repeat(default_k,len(path)) :
 410            is_num(k) ? repeat(k, len(path)) :
 411            len(k)<len(path) ? [0, each k, 0] :
 412                               k,
 413        badparm = [for(i=idx(parm)) if(parm[i]<0)i],
 414        badk = [for(i=idx(k)) if(k[i]<0 || k[i]>1)i]
 415     )
 416     assert(is_vector(parm) && badparm==[], str(measure," must be nonnegative"))
 417     assert(is_vector(k) && badk==[], "k parameter must be in the interval [0,1]")
 418     let(
 419        // dk is a list of parameters, where distance is the joint length to move away from the corner
 420        //     "smooth" method: [distance, curvature]
 421        //     "circle" method: [distance, radius]
 422        //     "chamfer" method: [distance]
 423        dk = [
 424              for(i=[0:1:len(path)-1])
 425                  let(
 426                      pathbit = select(path,i-1,i+1),
 427                      // This is the half-angle at the corner
 428                      angle = approx(pathbit[0],pathbit[1]) || approx(pathbit[1],pathbit[2]) ? undef
 429                            : vector_angle(select(path,i-1,i+1))/2
 430                  )
 431                  (!closed && (i==0 || i==len(path)-1))  ? [0] :          // Force zeros at ends for non-closed
 432                  parm[i]==0 ? [0]    : // If no rounding requested then don't try to compute parameters
 433                  assert(is_def(angle), str("Repeated point in path at index ",i," with nonzero rounding"))
 434                  assert(!approx(angle,0), closed && i==0 ? "Closing the path causes it to turn back on itself at the end" :
 435                                                            str("Path turns back on itself at index ",i," with nonzero rounding"))
 436                  (method=="chamfer" && measure=="joint")? [parm[i]] :
 437                  (method=="chamfer" && measure=="cut")  ? [parm[i]/cos(angle)] :
 438                  (method=="chamfer" && measure=="width") ? [parm[i]/sin(angle)/2] :
 439                  (method=="smooth" && measure=="joint") ? [parm[i],k[i]] :
 440                  (method=="smooth" && measure=="cut")   ? [8*parm[i]/cos(angle)/(1+4*k[i]),k[i]] :
 441                  (method=="circle" && measure=="radius")? [parm[i]/tan(angle), parm[i]] :
 442                  (method=="circle" && measure=="joint") ? [parm[i], parm[i]*tan(angle)] : 
 443                /*(method=="circle" && measure=="cut")*/   approx(angle,90) ? [INF] : 
 444                                                           let( circ_radius = parm[i] / (1/sin(angle) - 1))
 445                                                           [circ_radius/tan(angle), circ_radius],
 446        ],
 447        lengths = [for(i=[0:1:len(path)]) norm(select(path,i)-select(path,i-1))],
 448        scalefactors = [
 449            for(i=[0:1:len(path)-1])
 450                if (closed || (i!=0 && i!=len(path)-1))
 451                 min(
 452                    lengths[i]/(select(dk,i-1)[0]+dk[i][0]),
 453                    lengths[i+1]/(dk[i][0]+select(dk,i+1)[0])
 454                 )
 455        ],
 456        dummy = verbose ? echo("Roundover scale factors:",scalefactors) : 0
 457    )
 458    assert(min(scalefactors)>=1,str("Roundovers are too big for the path.  If you multitply them by this vector they should fit: ",scalefactors))
 459    // duplicates are introduced when roundings fully consume a segment, so remove them
 460    deduplicate([
 461        for(i=[0:1:len(path)-1]) each
 462            (dk[i][0] == 0)? [path[i]] :
 463            (method=="smooth")? _bezcorner(select(path,i-1,i+1), dk[i]) :
 464            (method=="chamfer") ? _chamfcorner(select(path,i-1,i+1), dk[i]) :
 465            _circlecorner(select(path,i-1,i+1), dk[i])
 466    ]);
 467
 468// Computes the continuous curvature control points for a corner when given as
 469// input three points in a list defining the corner.  The points must be
 470// equidistant from each other to produce the continuous curvature result.
 471// The output control points will include the 3 input points plus two
 472// interpolated points.
 473//
 474// k is the curvature parameter, ranging from 0 for very slow transition
 475// up to 1 for a sharp transition that doesn't have continuous curvature any more
 476function _smooth_bez_fill(points,k) = [
 477        points[0],
 478        lerp(points[1],points[0],k),
 479        points[1],
 480        lerp(points[1],points[2],k),
 481        points[2],
 482];
 483
 484// Computes the points of a continuous curvature roundover given as input
 485// the list of 3 points defining the corner and a parameter specification
 486//
 487// If parm is a scalar then it is treated as the curvature and the control
 488// points are calculated using _smooth_bez_fill.  Otherwise, parm is assumed
 489// to be a pair [d,k] where d is the length of the curve.  The length is
 490// calculated from the input point list and the control point list will not
 491// necessarily include points[0] or points[2] on its output.
 492//
 493// The number of points output is $fn if it is set.  Otherwise $fs is used
 494// to calculate the point count.
 495
 496function _bezcorner(points, parm) =
 497        let(
 498                P = is_list(parm)?
 499                        let(
 500                                d = parm[0],
 501                                k = parm[1],
 502                                prev = unit(points[0]-points[1]),
 503                                next = unit(points[2]-points[1])
 504                        ) [
 505                                points[1]+d*prev,
 506                                points[1]+k*d*prev,
 507                                points[1],
 508                                points[1]+k*d*next,
 509                                points[1]+d*next
 510                        ] : _smooth_bez_fill(points,parm),
 511                N = max(3,$fn>0 ?$fn : ceil(bezier_length(P)/$fs))
 512        )
 513        bezier_curve(P,N,endpoint=true);
 514
 515function _chamfcorner(points, parm) =
 516        let(
 517                d = parm[0],
 518                prev = unit(points[0]-points[1]),
 519                next = unit(points[2]-points[1])
 520          )
 521       [points[1]+prev*d, points[1]+next*d];
 522
 523function _circlecorner(points, parm) =
 524        let(
 525            angle = vector_angle(points)/2,
 526            d = parm[0],
 527            r = parm[1],
 528            prev = unit(points[0]-points[1]),
 529            next = unit(points[2]-points[1])
 530        )
 531        approx(angle,90) ? [points[1]+prev*d, points[1]+next*d] :
 532        let(
 533            center = r/sin(angle) * unit(prev+next)+points[1],
 534                    start = points[1]+prev*d,
 535                    end = points[1]+next*d
 536        )     // 90-angle is half the angle of the circular arc
 537        arc(max(3,ceil((90-angle)/180*segs(r))), cp=center, points=[start,end]);
 538
 539
 540// Used by offset_sweep and convex_offset_extrude.
 541// Produce edge profile curve from the edge specification
 542// z_dir is the direction multiplier (1 to build up, -1 to build down)
 543function _rounding_offsets(edgespec,z_dir=1) =
 544        let(
 545                edgetype = struct_val(edgespec, "type"),
 546                extra = struct_val(edgespec,"extra"),
 547                N = struct_val(edgespec, "steps"),
 548                r = struct_val(edgespec,"r"),
 549                cut = struct_val(edgespec,"cut"),
 550                k = struct_val(edgespec,"k"),
 551                radius = in_list(edgetype,["circle","teardrop"])
 552                            ? (is_def(cut) ? cut/(sqrt(2)-1) : r)
 553                         :edgetype=="chamfer"
 554                            ? (is_def(cut) ? sqrt(2)*cut : r)
 555                         : undef,
 556                chamf_angle = struct_val(edgespec, "angle"),
 557                cheight = struct_val(edgespec, "chamfer_height"),
 558                cwidth = struct_val(edgespec, "chamfer_width"),
 559                chamf_width = first_defined([!all_defined([cut,chamf_angle]) ? undef : cut/cos(chamf_angle),
 560                                             cwidth,
 561                                             !all_defined([cheight,chamf_angle]) ? undef : cheight*tan(chamf_angle)]),
 562                chamf_height = first_defined([
 563                                              !all_defined([cut,chamf_angle]) ? undef : cut/sin(chamf_angle),
 564                                              cheight,
 565                                              !all_defined([cwidth, chamf_angle]) ? undef : cwidth/tan(chamf_angle)]),
 566                joint = first_defined([
 567                        struct_val(edgespec,"joint"),
 568                        all_defined([cut,k]) ? 16*cut/sqrt(2)/(1+4*k) : undef
 569                ]),
 570                points = struct_val(edgespec, "points"),
 571                argsOK = in_list(edgetype,["circle","teardrop"])? is_def(radius) :
 572                        edgetype == "chamfer"? chamf_angle>0 && chamf_angle<90 && num_defined([chamf_height,chamf_width])==2 :
 573                        edgetype == "smooth"? num_defined([k,joint])==2 :
 574                        edgetype == "profile"? points[0]==[0,0] :
 575                        false
 576        )
 577        assert(argsOK,str("Invalid specification with type ",edgetype))
 578        let(
 579                offsets =
 580                        edgetype == "profile"? scale([-1,z_dir], p=list_tail(points)) :
 581                        edgetype == "chamfer"?  chamf_width==0 && chamf_height==0? [] : [[-chamf_width,z_dir*abs(chamf_height)]] :
 582                        edgetype == "teardrop"? (
 583                                radius==0? [] : concat(
 584                                        [for(i=[1:N]) [radius*(cos(i*45/N)-1),z_dir*abs(radius)* sin(i*45/N)]],
 585                                        [[-2*radius*(1-sqrt(2)/2), z_dir*abs(radius)]]
 586                                )
 587                        ) :
 588                        edgetype == "circle"? radius==0? [] : [for(i=[1:N]) [radius*(cos(i*90/N)-1), z_dir*abs(radius)*sin(i*90/N)]] :
 589                        /* smooth */ joint==0 ? [] :
 590                        list_tail(
 591                                _bezcorner([[0,0],[0,z_dir*abs(joint)],[-joint,z_dir*abs(joint)]], k, $fn=N+2)
 592                        )
 593        )
 594        quant(extra > 0 && len(offsets)>0 ? concat(offsets, [last(offsets)+[0,z_dir*extra]]) : offsets, 1/1024);
 595
 596
 597
 598// Function: smooth_path()
 599// Synopsis: Create smoothed path that passes through all the points of a given path.
 600// SynTags: Path
 601// Topics: Rounding, Paths
 602// See Also: round_corners(), smooth_path(), path_join(), offset_stroke()
 603// Usage:
 604//   smoothed = smooth_path(path, [tangents], [size=|relsize=], [splinesteps=], [closed=], [uniform=]);
 605// Description:
 606//   Smooths the input path using a cubic spline.  Every segment of the path will be replaced by a cubic curve
 607//   with `splinesteps` points.  The cubic interpolation will pass through every input point on the path
 608//   and will match the tangents at every point.  If you do not specify tangents they will be computed using
 609//   path_tangents with uniform=false by default.  Note that setting uniform to true with non-uniform
 610//   sampling may be desirable in some cases but tends to produces curves that overshoot the point on the path.  
 611//   .
 612//   The size or relsize parameter determines how far the curve can bend away from
 613//   the input path.  In the case where the curve has a single hump, the size specifies the exact distance
 614//   between the specified path and the curve.  If you give relsize then it is relative to the segment
 615//   length (e.g. 0.05 means 5% of the segment length).  In 2d when the spline may make an S-curve,
 616//   in which case the size parameter specifies the sum of the deviations of the two peaks of the curve.  In 3-space
 617//   the bezier curve may have three extrema: two maxima and one minimum.  In this case the size specifies
 618//   the sum of the maxima minus the minimum.  At a given segment there is a maximum size: if your size
 619//   value is too large it will be rounded down.  See also path_to_bezpath().
 620// Arguments:
 621//   path = path to smooth
 622//   tangents = tangents constraining curve direction at each point.  Default: computed automatically
 623//   ---
 624//   relsize = relative size specification for the curve, a number or vector.  Default: 0.1
 625//   size = absolute size specification for the curve, a number or vector
 626//   uniform = set to true to compute tangents with uniform=true.  Default: false
 627//   closed = true if the curve is closed.  Default: false. 
 628// Example(2D): Original path in green, smoothed path in yellow:
 629//   color("green")stroke(square(4), width=0.1);
 630//   stroke(smooth_path(square(4),size=0.4), width=0.1);
 631// Example(2D): Closing the path changes the end tangents
 632//   polygon(smooth_path(square(4),size=0.4,closed=true));
 633// Example(2D): Turning on uniform tangent calculation also changes the end derivatives:
 634//   color("green")stroke(square(4), width=0.1);
 635//   stroke(smooth_path(square(4),size=0.4,uniform=true),
 636//          width=0.1);
 637// Example(2D): Here's a wide rectangle.  Using size means all edges bulge the same amount, regardless of their length. 
 638//   color("green")
 639//     stroke(square([10,4]), closed=true, width=0.1);
 640//   stroke(smooth_path(square([10,4]),size=1,closed=true),
 641//          width=0.1);
 642// Example(2D): With relsize the bulge is proportional to the side length. 
 643//   color("green")stroke(square([10,4]), closed=true, width=0.1);
 644//   stroke(smooth_path(square([10,4]),relsize=0.1,closed=true),
 645//          width=0.1);
 646// Example(2D): Settting uniform to true biases the tangents to aline more with the line sides
 647//   color("green")
 648//     stroke(square([10,4]), closed=true, width=0.1);
 649//   stroke(smooth_path(square([10,4]),uniform=true,
 650//                      relsize=0.1,closed=true),
 651//          width=0.1);
 652// Example(2D): A more interesting shape:
 653//   path = [[0,0], [4,0], [7,14], [-3,12]];
 654//   polygon(smooth_path(path,size=1,closed=true));
 655// Example(2D): Here's the square again with less smoothing.
 656//   polygon(smooth_path(square(4), size=.25,closed=true));
 657// Example(2D): Here's the square with a size that's too big to achieve, so you get the maximum possible curve:
 658//   color("green")stroke(square(4), width=0.1,closed=true);
 659//   stroke(smooth_path(square(4), size=4, closed=true),
 660//          closed=true,width=.1);
 661// Example(2D): You can alter the shape of the curve by specifying your own arbitrary tangent values
 662//   polygon(smooth_path(square(4),
 663//           tangents=1.25*[[-2,-1], [-4,1], [1,2], [6,-1]],
 664//           size=0.4,closed=true));
 665// Example(2D): Or you can give a different size for each segment
 666//   polygon(smooth_path(square(4),size = [.4, .05, 1, .3],
 667//                       closed=true));
 668// Example(FlatSpin,VPD=35,VPT=[4.5,4.5,1]):  Works on 3d paths as well
 669//   path = [[0,0,0],[3,3,2],[6,0,1],[9,9,0]];
 670//   stroke(smooth_path(path,relsize=.1),width=.3);
 671// Example(2D): This shows the type of overshoot that can occur with uniform=true.  You can produce overshoots like this if you supply a tangent that is difficult to connect to the adjacent points  
 672//   pts = [[-3.3, 1.7], [-3.7, -2.2], [3.8, -4.8], [-0.9, -2.4]];
 673//   stroke(smooth_path(pts, uniform=true, relsize=0.1),width=.1);
 674//   color("red")move_copies(pts)circle(r=.15,$fn=12);
 675// Example(2D): With the default of uniform false no overshoot occurs.  Note that the shape of the curve is quite different.  
 676//   pts = [[-3.3, 1.7], [-3.7, -2.2], [3.8, -4.8], [-0.9, -2.4]];
 677//   stroke(smooth_path(pts, uniform=false, relsize=0.1),width=.1);
 678//   color("red")move_copies(pts)circle(r=.15,$fn=12);
 679module smooth_path(path, tangents, size, relsize, splinesteps=10, uniform=false, closed=false) {no_module();}
 680function smooth_path(path, tangents, size, relsize, splinesteps=10, uniform=false, closed) =
 681  is_1region(path) ? smooth_path(path[0], tangents, size, relsize, splinesteps, uniform, default(closed,true)) :
 682  let (
 683     bez = path_to_bezpath(path, tangents=tangents, size=size, relsize=relsize, uniform=uniform, closed=default(closed,false)),
 684     smoothed = bezpath_curve(bez,splinesteps=splinesteps)
 685  )
 686  closed ? list_unwrap(smoothed) : smoothed;
 687
 688
 689function _scalar_to_vector(value,length,varname) = 
 690  is_vector(value)
 691    ? assert(len(value)==length, str(varname," must be length ",length))
 692      value
 693    : assert(is_num(value), str(varname, " must be a numerical value"))
 694      repeat(value, length);
 695
 696
 697// Function: path_join()
 698// Synopsis: Join paths end to end with optional rounding.
 699// SynTags: Path
 700// Topics: Rounding, Paths
 701// See Also: round_corners(), smooth_path(), path_join(), offset_stroke()
 702// Usage:
 703//   joined_path = path_join(paths, [joint], [k=], [relocate=], [closed=]);
 704// Description:
 705//   Connect a sequence of paths together into a single path with optional continuous curvature rounding
 706//   applied at the joints.  By default the first path is taken as specified and subsequent paths are
 707//   translated into position so that each path starts where the previous path ended.
 708//   If you set relocate to false then this relocation is skipped.
 709//   You specify rounding using the `joint` parameter, which specifies the distance away from the corner
 710//   where the roundover should start.  The path_join function may remove many path points to cut the path 
 711//   back by the joint length.  Rounding is using continous curvature 4th order bezier splines and
 712//   the parameter `k` specifies how smooth the curvature match is.  This parameter ranges from 0 to 1 with
 713//   a default of 0.5.  Use a larger k value to get a curve that is bigger for the same joint value.  When
 714//   k=1 the curve may be similar to a circle if your curves are symmetric.  As the path is built up, the joint
 715//   parameter applies to the growing path, so if you pick a large joint parameter it may interact with the
 716//   previous path sections.  See [Types of Roundover](rounding.scad#subsection-types-of-roundover) for more details
 717//   on continuous curvature rounding. 
 718//   .
 719//   The rounding is created by extending the two clipped paths to define a corner point.  If the extensions of
 720//   the paths do not intersect, the function issues an error.  When closed=true the final path should actually close
 721//   the shape, repeating the starting point of the shape.  If it does not, then the rounding will fill the gap.
 722//   .
 723//   The number of segments in the roundovers is set based on $fn and $fs.  If you use $fn it specifies the number of
 724//   segments in the roundover, regardless of its angular extent.
 725// Arguments:
 726//   paths = list of paths to join
 727//   joint = joint distance, either a number, a pair (giving the previous and next joint distance) or a list of numbers and pairs.  Default: 0
 728//   ---
 729//   k = curvature parameter, either a number or vector.  Default: 0.5
 730//   relocate = set to false to prevent paths from being arranged tail to head.  Default: true
 731//   closed = set to true to round the junction between the last and first paths.  Default: false
 732// Example(2D): Connection of 3 simple paths.  
 733//   horiz = [[0,0],[10,0]];
 734//   vert = [[0,0],[0,10]];
 735//   stroke(path_join([horiz, vert, -horiz]));
 736// Example(2D): Adding curvature with joint of 3
 737//   horiz = [[0,0],[10,0]];
 738//   vert = [[0,0],[0,10]];
 739//   stroke(path_join([horiz, vert, -horiz],joint=3,$fn=16));
 740// Example(2D): Setting k=1 increases the amount of curvature
 741//   horiz = [[0,0],[10,0]];
 742//   vert = [[0,0],[0,10]];
 743//   stroke(path_join([horiz, vert, -horiz],joint=3,k=1,$fn=16));
 744// Example(2D): Specifying pairs of joint values at a path joint creates an asymmetric curve
 745//   horiz = [[0,0],[10,0]];
 746//   vert = [[0,0],[0,10]];
 747//   stroke(path_join([horiz, vert, -horiz],
 748//                    joint=[[4,1],[1,4]],$fn=16),width=.3);
 749// Example(2D): A closed square
 750//   horiz = [[0,0],[10,0]];
 751//   vert = [[0,0],[0,10]];
 752//   stroke(path_join([horiz, vert, -horiz, -vert],
 753//                    joint=3,k=1,closed=true,$fn=16),closed=true);
 754// Example(2D): Different curve at each corner by changing the joint size
 755//   horiz = [[0,0],[10,0]];
 756//   vert = [[0,0],[0,10]];
 757//   stroke(path_join([horiz, vert, -horiz, -vert],
 758//                    joint=[3,0,1,2],k=1,closed=true,$fn=16),
 759//          closed=true,width=0.4);
 760// Example(2D): Different curve at each corner by changing the curvature parameter.  Note that k=0 still gives a small curve, unlike joint=0 which gives a sharp corner.
 761//   horiz = [[0,0],[10,0]];
 762//   vert = [[0,0],[0,10]];
 763//   stroke(path_join([horiz, vert, -horiz, -vert],joint=3,
 764//                    k=[1,.5,0,.7],closed=true,$fn=16),
 765//          closed=true,width=0.4);
 766// Example(2D): Joint value of 7 is larger than half the square so curves interfere with each other, which breaks symmetry because they are computed sequentially
 767//   horiz = [[0,0],[10,0]];
 768//   vert = [[0,0],[0,10]];
 769//   stroke(path_join([horiz, vert, -horiz, -vert],joint=7,
 770//                     k=.4,closed=true,$fn=16),
 771//          closed=true);
 772// Example(2D): Unlike round_corners, we can add curves onto curves.
 773//   $fn=64;
 774//   myarc = arc(width=20, thickness=5 );
 775//   stroke(path_join(repeat(myarc,3), joint=4));
 776// Example(2D): Here we make a closed shape from two arcs and round the sharp tips
 777//   arc1 = arc(width=20, thickness=4,$fn=75);
 778//   arc2 = reverse(arc(width=20, thickness=2,$fn=75));
 779//   // Without rounding
 780//   stroke(path_join([arc1,arc2]),width=.3);
 781//   // With rounding
 782//   color("red")stroke(path_join([arc1,arc2], 3,k=1,closed=true),
 783//                      width=.3,closed=true,$fn=12); 
 784// Example(2D): Combining arcs with segments
 785//   arc1 = arc(width=20, thickness=4,$fn=75);
 786//   arc2 = reverse(arc(width=20, thickness=2,$fn=75));
 787//   vpath = [[0,0],[0,-5]];
 788//   stroke(path_join([arc1,vpath,arc2,reverse(vpath)]),width=.2);
 789//   color("red")stroke(path_join([arc1,vpath,arc2,reverse(vpath)],
 790//                                [1,2,2,1],k=1,closed=true),
 791//                      width=.2,closed=true,$fn=12);
 792// Example(2D): Here relocation is off.  We have three segments (in yellow) and add the curves to the segments.  Notice that joint zero still produces a curve because it refers to the endpoints of the supplied paths.  
 793//   p1 = [[0,0],[2,0]];
 794//   p2 = [[3,1],[1,3]];
 795//   p3 = [[0,3],[-1,1]];
 796//   color("red")stroke(
 797//     path_join([p1,p2,p3], joint=0, relocate=false,
 798//               closed=true),
 799//     width=.3,$fn=48);
 800//   for(x=[p1,p2,p3]) stroke(x,width=.3);
 801// Example(2D): If you specify closed=true when the last path doesn't meet the first one then it is similar to using relocate=false: the function tries to close the path using a curve.  In the example below, this results in a long curve to the left, when given the unclosed three segments as input.  Note that if the segments are parallel the function fails with an error.  The extension of the curves must intersect in a corner for the rounding to be well-defined.  To get a normal rounding of the closed shape, you must include a fourth path, the last segment that closes the shape.
 802//   horiz = [[0,0],[10,0]];
 803//   vert = [[0,0],[0,10]];
 804//   h2 = [[0,-3],[10,0]];
 805//   color("red")stroke(
 806//     path_join([horiz, vert, -h2],closed=true,
 807//               joint=3,$fn=25),
 808//     closed=true,width=.5);
 809//   stroke(path_join([horiz, vert, -h2]),width=.3);
 810// Example(2D): With a single path with closed=true the start and end junction is rounded.
 811//   tri = regular_ngon(n=3, r=7);
 812//   stroke(path_join([tri], joint=3,closed=true,$fn=12),
 813//          closed=true,width=.5);
 814module path_join(paths,joint=0,k=0.5,relocate=true,closed=false) { no_module();}
 815function path_join(paths,joint=0,k=0.5,relocate=true,closed=false)=
 816  assert(is_list(paths),"Input paths must be a list of paths")
 817  let(
 818      paths = [for(i=idx(paths)) force_path(paths[i],str("paths[",i,"]"))],
 819      badpath = [for(j=idx(paths)) if (!is_path(paths[j])) j]
 820  )
 821  assert(badpath==[], str("Entries in paths are not valid paths: ",badpath))
 822  len(paths)==0 ? [] :
 823  len(paths)==1 && !closed ? paths[0] :
 824  let(
 825      paths = !closed || len(paths)>1
 826            ? paths
 827            : [list_wrap(paths[0])],
 828      N = len(paths) + (closed?0:-1),
 829      k = _scalar_to_vector(k,N),
 830      repjoint = is_num(joint) || (is_vector(joint,2) && len(paths)!=3),
 831      joint = repjoint ? repeat(joint,N) : joint
 832  )
 833  assert(all_nonnegative(k), "k must be nonnegative")
 834  assert(len(joint)==N,str("Input joint must be scalar or length ",N))
 835  let(
 836      bad_j = [for(j=idx(joint)) if (!is_num(joint[j]) && !is_vector(joint[j],2)) j]
 837  )
 838  assert(bad_j==[], str("Invalid joint values at indices ",bad_j))
 839  let(result=_path_join(paths,joint,k, relocate=relocate, closed=closed))
 840  closed ? list_unwrap(result) : result;
 841
 842function _path_join(paths,joint,k=0.5,i=0,result=[],relocate=true,closed=false) =
 843  let( 
 844      result = result==[] ? paths[0] : result,
 845      loop = i==len(paths)-1,
 846      revresult = reverse(result),
 847      nextpath = loop     ? result
 848               : relocate ? move(revresult[0]-paths[i+1][0], p=paths[i+1])
 849               : paths[i+1],
 850      d_first = is_vector(joint[i]) ? joint[i][0] : joint[i],
 851      d_next = is_vector(joint[i]) ? joint[i][1] : joint[i]
 852  )
 853  assert(d_first>=0 && d_next>=0, str("Joint value negative when adding path ",i+1))
 854  assert(d_first<path_length(revresult),str("Path ",i," is too short for specified cut distance ",d_first))
 855  assert(d_next<path_length(nextpath), str("Path ",i+1," is too short for specified cut distance ",d_next))
 856  let(
 857      firstcut = path_cut_points(revresult, d_first, direction=true),
 858      nextcut = path_cut_points(nextpath, d_next, direction=true)
 859  )
 860  assert(!loop || nextcut[1] < len(revresult)-1-firstcut[1], "Path is too short to close the loop")
 861  let(
 862     first_dir=firstcut[2],
 863     next_dir=nextcut[2],
 864     corner = line_intersection([firstcut[0], firstcut[0]-first_dir], [nextcut[0], nextcut[0]-next_dir],RAY,RAY)
 865  )
 866  assert(is_def(corner), str("Curve directions at cut points don't intersect in a corner when ",
 867                             loop?"closing the path":str("adding path ",i+1)))
 868  let(
 869      bezpts = _smooth_bez_fill([firstcut[0], corner, nextcut[0]],k[i]),
 870      N = max(3,$fn>0 ?$fn : ceil(bezier_length(bezpts)/$fs)),
 871      bezpath = approx(firstcut[0],corner) && approx(corner,nextcut[0])
 872                  ? []
 873                  : bezier_curve(bezpts,N),
 874      new_result = [each select(result,loop?nextcut[1]:0,len(revresult)-1-firstcut[1]),
 875                    each bezpath,
 876                    nextcut[0],
 877                    if (!loop) each list_tail(nextpath,nextcut[1])
 878                   ]
 879  )
 880  i==len(paths)-(closed?1:2)
 881     ? new_result
 882     : _path_join(paths,joint,k,i+1,new_result, relocate,closed);
 883
 884
 885
 886// Function&Module: offset_stroke()
 887// Synopsis: Draws a line along a path with options to specify angles and roundings at the ends.
 888// SynTags: Path, Region
 889// Topics: Rounding, Paths
 890// See Also: round_corners(), smooth_path(), path_join(), offset_stroke()
 891// Usage: as module
 892//   offset_stroke(path, [width], [rounded=], [chamfer=], [start=], [end=], [check_valid=], [quality=], [closed=],...) [ATTACHMENTS];
 893// Usage: as function
 894//   path = offset_stroke(path, [width], closed=false, [rounded=], [chamfer=], [start=], [end=], [check_valid=], [quality=],...);
 895//   region = offset_stroke(path, [width], closed=true, [rounded=], [chamfer=], [start=], [end=], [check_valid=], [quality=],...);
 896// Description:
 897//   Uses `offset()` to compute a stroke for the input path.  Unlike `stroke`, the result does not need to be
 898//   centered on the input path.  The corners can be rounded, pointed, or chamfered, and you can make the ends
 899//   rounded, flat or pointed with the `start` and `end` parameters.
 900//   .
 901//   The `check_valid` and `quality`  parameters are passed through to `offset()`
 902//   .
 903//   If `width` is a scalar then the output will be a centered stroke of the specified width.  If width
 904//   is a list of two values then those two values will define the stroke side positions relative to the center line, where
 905//   as with offset(), the shift is to the left for open paths and outward for closed paths.  For example,
 906//   setting `width` to `[0,1]` will create a stroke of width 1 that extends entirely to the left of the input, and and [-4,-6]
 907//   will create a stroke of width 2 offset 4 units to the right of the input path.
 908//   .
 909//   If closed==false then the function form will return a path.  If closed==true then it will return a region.  The `start` and
 910//   `end` parameters are forbidden for closed paths.
 911//   .
 912//   Three simple end treatments are supported, "flat" (the default), "round" and "pointed".  The "flat" treatment
 913//   cuts off the ends perpendicular to the path and the "round" treatment applies a semicircle to the end.  The
 914//   "pointed" end treatment caps the stroke with a centered triangle that has 45 degree angles on each side.
 915//   .
 916//   More complex end treatments are available through parameter lists with helper functions to ease parameter passing.  The parameter list
 917//   keywords are
 918//      - "for" : must appear first in the list and have the value "offset_stroke"
 919//      - "type": the type of end treatment, one of "shifted_point", "roundover", or "flat"
 920//      - "angle": relative angle (relative to the path)
 921//      - "abs_angle": absolute angle (angle relative to x-axis)
 922//      - "cut": cut distance for roundovers, a single value to round both corners identically or a list of two values for the two corners.  Negative values round outward.
 923//      - "k": curvature smoothness parameter for roundovers, default 0.75
 924//   .
 925//   Function helpers for defining ends, prefixed by "os" for offset_stroke, are:
 926//      - os_flat(angle|absangle): specify a flat end either relative to the path or relative to the x-axis
 927//      - os_pointed(dist, [loc]): specify a pointed tip where the point is distance `loc` from the centerline (positive is the left direction as for offset), and `dist` is the distance from the path end to the point tip.  The default value for `loc` is zero (the center).  You must specify `dist` when using this option.
 928//      - os_round(cut, [angle|absangle], [k]).  Rounded ends with the specified cut distance, based on the specified angle or absolute angle.  The `k` parameter is the smoothness parameter for continuous curvature rounding.  See [Types of Roundover](rounding.scad#subsection-types-of-roundover) for more details on
 929//        continuous curvature rounding.  
 930//   .
 931//   Note that `offset_stroke()` will attempt to apply roundovers and angles at the ends even when it means deleting segments of the stroke, unlike round_corners which only works on a segment adjacent to a corner.  If you specify an overly extreme angle it will fail to find an intersection with the stroke and display an error.  When you specify an angle the end segment is rotated around the center of the stroke and the last segment of the stroke one one side is extended to the corner.
 932//   .
 933//   The `$fn` and `$fs` variables are used in the usual way to determine the number of segments for roundings produced by the offset
 934//   invocations and roundings produced by the semi-circular "round" end treatment.  The os_round() end treatment
 935//   uses a bezier curve, and will produce segments of approximate length `$fs` or it will produce `$fn` segments.
 936//   (This means that even a quarter circle will have `$fn` segments, unlike the usual case where it would have `$fn/4` segments.)
 937// Arguments:
 938//   path = 2d path that defines the stroke
 939//   width = width of the stroke, a scalar or a vector of 2 values giving the offset from the path.  Default: 1
 940//   ---
 941//   rounded = set to true to use rounded offsets, false to use sharp (delta) offsets.  Default: true
 942//   chamfer = set to true to use chamfers when `rounded=false`.  Default: false
 943//   start = end treatment for the start of the stroke when closed=false.  See above for details.  Default: "flat"
 944//   end = end treatment for the end of the stroke when closed=false.  See above for details.  Default: "flat"
 945//   check_valid = passed to offset().  Default: true
 946//   quality = passed to offset().  Default: 1
 947//   closed = true if the curve is closed, false otherwise.  Default: false
 948//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `"origin"`
 949//   spin = Rotate this many degrees after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 950//   cp = Centerpoint for determining intersection anchors or centering the shape.  Determintes the base of the anchor vector.  Can be "centroid", "mean", "box" or a 2D point.  Default: "centroid"
 951//   atype = Set to "hull" or "intersect" to select anchor type.  Default: "hull"
 952// Example(2D):  Basic examples illustrating flat, round, and pointed ends, on a finely sampled arc and a path made from 3 segments.
 953//   arc = arc(points=[[1,1],[3,4],[6,3]],n=50);
 954//   path = [[0,0],[6,2],[9,7],[8,10]];
 955//   xdistribute(spacing=10){
 956//     offset_stroke(path, width = 2);
 957//     offset_stroke(path, start="round", end="round", width = 2);
 958//     offset_stroke(path, start="pointed", end="pointed", width = 2);
 959//   }
 960//   fwd(10) xdistribute(spacing=10){
 961//     offset_stroke(arc, width = 2);
 962//     offset_stroke(arc, start="round", end="round", width = 2);
 963//     offset_stroke(arc, start="pointed", end="pointed", width = 2);
 964//   }
 965// Example(2D):  The effect of the `rounded` and `chamfer` options is most evident at sharp corners.  This only affects the middle of the path, not the ends.
 966//   sharppath = [[0,0], [1.5,5], [3,0]];
 967//   xdistribute(spacing=5){
 968//     offset_stroke(sharppath, $fn=16);
 969//     offset_stroke(sharppath, rounded=false);
 970//     offset_stroke(sharppath, rounded=false, chamfer=true);
 971//   }
 972// Example(2D):  When closed is enabled all the corners are affected by those options.
 973//   sharppath = [[0,0], [1.5,5], [3,0]];
 974//   xdistribute(spacing=5){
 975//     offset_stroke(sharppath,closed=true, $fn=16);
 976//     offset_stroke(sharppath, rounded=false, closed=true);
 977//     offset_stroke(sharppath, rounded=false, chamfer=true,
 978//                   closed=true);
 979//   }
 980// Example(2D):  The left stroke uses flat ends with a relative angle of zero.  The right hand one uses flat ends with an absolute angle of zero, so the ends are parallel to the x-axis.
 981//   path = [[0,0],[6,2],[9,7],[8,10]];
 982//   offset_stroke(path, start=os_flat(angle=0), end=os_flat(angle=0));
 983//   right(5)
 984//     offset_stroke(path, start=os_flat(abs_angle=0), end=os_flat(abs_angle=0));
 985// Example(2D):  With continuous sampling the end treatment can remove segments or extend the last segment linearly, as shown here.  Again the left side uses relative angle flat ends and the right hand example uses absolute angle.
 986//   arc = arc(points=[[4,0],[3,4],[6,3]],n=50);
 987//   offset_stroke(arc, start=os_flat(angle=45), end=os_flat(angle=45));
 988//   right(5)
 989//     offset_stroke(arc, start=os_flat(abs_angle=45), end=os_flat(abs_angle=45));
 990// Example(2D):  The os_pointed() end treatment allows adjustment of the point tip, as shown here.  The width is 2 so a location of 1 is at the edge.
 991//   arc = arc(points=[[1,1],[3,4],[6,3]],n=50);
 992//   offset_stroke(arc, width=2, start=os_pointed(loc=1,dist=3),end=os_pointed(loc=1,dist=3));
 993//   right(10)
 994//     offset_stroke(arc, width=2, start=os_pointed(dist=4),end=os_pointed(dist=-1));
 995//   fwd(7)
 996//     offset_stroke(arc, width=2, start=os_pointed(loc=2,dist=2),end=os_pointed(loc=.5,dist=-1));
 997// Example(2D):  The os_round() end treatment adds roundovers to the end corners by specifying the `cut` parameter.  In the first example, the cut parameter is the same at each corner.  The bezier smoothness parameter `k` is given to allow a larger cut.  In the second example, each corner is given a different roundover, including zero for no rounding at all.  The red shows the same strokes without the roundover.
 998//   $fn=36;
 999//   arc = arc(points=[[1,1],[3,4],[6,3]],n=50);
1000//   path = [[0,0],[6,2],[9,7],[8,10]];
1001//   offset_stroke(path, width=2, rounded=false,start=os_round(angle=-20, cut=0.4,k=.9),
1002//                                              end=os_round(angle=-35, cut=0.4,k=.9));
1003//   color("red")down(.1)offset_stroke(path, width=2, rounded=false,start=os_flat(-20),
1004//                                                                  end=os_flat(-35));
1005//   right(9){
1006//     offset_stroke(arc, width=2, rounded=false, start=os_round(cut=[.3,.6],angle=-45),
1007//                                                end=os_round(angle=20,cut=[.6,0]));
1008//     color("red")down(.1)offset_stroke(arc, width=2, rounded=false, start=os_flat(-45),
1009//                                                                    end=os_flat(20));
1010//   }
1011// Example(2D):  Negative cut values produce a flaring end.  Note how the absolute angle aligns the ends of the first example withi the axes.  In the second example positive and negative cut values are combined.  Note also that very different cuts are needed at the start end to produce a similar looking flare.
1012//   arc = arc(points=[[1,1],[3,4],[6,3]],n=50);
1013//   path = [[0,0],[6,2],[9,7],[8,10]];
1014//   offset_stroke(path, width=2, rounded=false,start=os_round(cut=-1, abs_angle=90),
1015//                                              end=os_round(cut=-0.5, abs_angle=0),$fn=36);
1016//   right(10)
1017//      offset_stroke(arc, width=2, rounded=false, start=os_round(cut=[-.75,-.2], angle=-45),
1018//                                                 end=os_round(cut=[-.2,.2], angle=20),$fn=36);
1019// Example(2D):  Setting the width to a vector allows you to offset the stroke.  Here with successive increasing offsets we create a set of parallel strokes
1020//   path = [[0,0],[4,4],[8,4],[2,9],[10,10]];
1021//   for(i=[0:.25:2])
1022//     offset_stroke(path, rounded=false,width = [i,i+.08]);
1023// Example(2D):  Setting rounded=true in the above example makes a very big difference in the result.  
1024//   path = [[0,0],[4,4],[8,4],[2,9],[10,10]];
1025//   for(i=[0:.25:2])
1026//     offset_stroke(path, rounded=true,width = [i,i+.08], $fn=36);
1027// Example(2D):  In this example a spurious triangle appears.  This results from overly enthusiastic validity checking.  Turning validity checking off fixes it in this case.
1028//   path = [[0,0],[4,4],[8,4],[2,9],[10,10]];
1029//   offset_stroke(path, check_valid=true,rounded=false,
1030//                 width = [1.4, 1.5]);
1031//   right(2)
1032//     offset_stroke(path, check_valid=false,rounded=false,
1033//                   width = [1.4, 1.5]);
1034// Example(2D):  But in this case, disabling the validity check produces an invalid result.
1035//   path = [[0,0],[4,4],[8,4],[2,9],[10,10]];
1036//   offset_stroke(path, check_valid=true,rounded=false,
1037//                 width = [1.9, 2]);
1038//   translate([1,-0.25])
1039//     offset_stroke(path, check_valid=false,rounded=false,
1040//                   width = [1.9, 2]);
1041// Example(2D): Self-intersecting paths are handled differently than with the `stroke()` module.
1042//   $fn=16;
1043//   path = turtle(["move",10,"left",144], repeat=4);
1044//   stroke(path, closed=true);
1045//   right(12)
1046//     offset_stroke(path, width=1, closed=true);
1047function offset_stroke(path, width=1, rounded=true, start, end, check_valid=true, quality=1, chamfer=false, closed=false,
1048                       atype="hull", anchor, spin, cp="centroid") =
1049        let(path = force_path(path))
1050        assert(is_path(path,2),"path is not a 2d path")
1051        let(
1052            closedok = !closed || (is_undef(start) && is_undef(end)),
1053            start = default(start,"flat"),
1054            end = default(end,"flat")
1055        )
1056        assert(closedok, "Parameters `start` and `end` not allowed with closed path")
1057        let(
1058            start = closed? [] : _parse_stroke_end(default(start,"flat"),"start"),
1059            end = closed? [] : _parse_stroke_end(default(end,"flat"),"end"),
1060            width = is_list(width)? reverse(sort(width)) : [1,-1]*width/2,
1061            left_r = !rounded? undef : width[0],
1062            left_delta = rounded? undef : width[0],
1063            right_r = !rounded? undef : width[1],
1064            right_delta = rounded? undef : width[1],
1065            left_path = offset(
1066                    path, delta=left_delta, r=left_r, closed=closed,
1067                    check_valid=check_valid, quality=quality,
1068                    chamfer=chamfer 
1069            ),
1070            right_path = offset(
1071                    path, delta=right_delta, r=right_r, closed=closed,
1072                    check_valid=check_valid, quality=quality,
1073                    chamfer=chamfer 
1074            )
1075         )
1076         closed? let(pts = [left_path, right_path])
1077                 reorient(anchor=anchor, spin=spin, two_d=true, region=pts, extent=atype=="hull", cp=cp, p=pts)
1078         :
1079         let(
1080             startpath = _stroke_end(width,left_path, right_path, start),
1081             endpath = _stroke_end(reverse(width),reverse(right_path), reverse(left_path),end),
1082             clipping_ok = startpath[1]+endpath[2]<=len(left_path) && startpath[2]+endpath[1]<=len(right_path)
1083         )
1084         assert(clipping_ok, "End treatment removed the whole stroke")
1085         let(
1086             pts = concat(
1087                          slice(left_path,startpath[1],-1-endpath[2]),
1088                          endpath[0],
1089                          reverse(slice(right_path,startpath[2],-1-endpath[1])),
1090                          startpath[0]
1091                  )
1092         )
1093         reorient(anchor=anchor, spin=spin, two_d=true, path=pts, extent=atype=="hull", cp=cp, p=pts);
1094
1095function os_pointed(dist,loc=0) =
1096        assert(is_def(dist), "Must specify `dist`")
1097        [
1098                "for", "offset_stroke",
1099                "type", "shifted_point",
1100                "loc",loc,
1101                "dist",dist
1102        ];
1103
1104function os_round(cut, angle, abs_angle, k, r) =
1105        assert(is_undef(r), "Radius not supported for os_round with offset_stroke.  (Did you mean os_circle for offset_sweep?)")
1106        let(
1107                acount = num_defined([angle,abs_angle]),
1108                use_angle = first_defined([angle,abs_angle,0])
1109        )
1110        assert(acount<2, "You must define only one of `angle` and `abs_angle`")
1111        assert(is_def(cut), "Parameter `cut` not defined.")
1112        [
1113                "for", "offset_stroke",
1114                "type", "roundover",
1115                "angle", use_angle,
1116                "absolute", is_def(abs_angle),
1117                "cut", is_vector(cut)? point2d(cut) : [cut,cut],
1118                "k", first_defined([k, 0.75])
1119        ];
1120
1121
1122function os_flat(angle, abs_angle) =
1123        let(
1124                acount = num_defined([angle,abs_angle]),
1125                use_angle = first_defined([angle,abs_angle,0])
1126        )
1127        assert(acount<2, "You must define only one of `angle` and `abs_angle`")
1128        [
1129                "for", "offset_stroke",
1130                "type", "flat",
1131                "angle", use_angle,
1132                "absolute", is_def(abs_angle)
1133        ];
1134
1135
1136
1137// Return angle in (-90,90] required to map line1 onto line2 (lines specified as lists of two points)
1138function angle_between_lines(line1,line2) =
1139        let(angle = atan2(det2([line1,line2]),line1*line2))
1140        angle > 90 ? angle-180 :
1141        angle <= -90 ? angle+180 :
1142        angle;
1143
1144
1145function _parse_stroke_end(spec,name) =
1146        is_string(spec)?
1147            assert(
1148                    in_list(spec,["flat","round","pointed"]),
1149                    str("Unknown \"",name,"\" string specification \"", spec,"\".  Must be \"flat\", \"round\", or \"pointed\"")
1150            )
1151            [["type", spec]]
1152        : let(
1153              dummy = _struct_valid(spec,"offset_stroke",name)
1154          )
1155          struct_set([], spec);
1156
1157
1158function _stroke_end(width,left, right, spec) =
1159        let(
1160                type = struct_val(spec, "type"),
1161                user_angle = default(struct_val(spec, "angle"), 0),
1162                normal_seg = _normal_segment(right[0], left[0]),
1163                normal_pt = normal_seg[1],
1164                center = normal_seg[0],
1165                parallel_dir = unit(left[0]-right[0]),
1166                normal_dir = unit(normal_seg[1]-normal_seg[0]),
1167                width_dir = sign(width[0]-width[1])
1168        )
1169        type == "round"? [arc(points=[right[0],normal_pt,left[0]],n=ceil(segs(width/2)/2)),1,1]  :
1170        type == "pointed"? [[normal_pt],0,0] :
1171        type == "shifted_point"? (
1172                let(shiftedcenter = center + width_dir * parallel_dir * struct_val(spec, "loc"))
1173                [[shiftedcenter+normal_dir*struct_val(spec, "dist")],0,0]
1174        ) :
1175        // Remaining types all support angled cutoff, so compute that
1176        assert(abs(user_angle)<=90, "End angle must be in [-90,90]")
1177        let(
1178                angle = struct_val(spec,"absolute")?
1179                        angle_between_lines(left[0]-right[0],[cos(user_angle),sin(user_angle)]) :
1180                        user_angle,
1181                endseg = [center, rot(p=[left[0]], angle, cp=center)[0]],
1182                intright = angle>0,
1183                pathclip = _path_line_intersection(intright? right : left, endseg),
1184                pathextend = line_intersection(endseg, select(intright? left:right,0,1))
1185        )
1186        type == "flat"? (
1187                intright?
1188                        [[pathclip[0], pathextend], 1, pathclip[1]] :
1189                        [[pathextend, pathclip[0]], pathclip[1],1]
1190        ) :
1191        type == "roundover"? (
1192                let(
1193                        bez_k = struct_val(spec,"k"),
1194                        cut = struct_val(spec,"cut"),
1195                        cutleft = cut[0],
1196                        cutright = cut[1],
1197                        // Create updated paths taking into account clipping for end rotation
1198                        newright = intright?
1199                                concat([pathclip[0]],list_tail(right,pathclip[1])) :
1200                                concat([pathextend],list_tail(right)),
1201                        newleft = !intright?
1202                                concat([pathclip[0]],list_tail(left,pathclip[1])) :
1203                                concat([pathextend],list_tail(left)),
1204                        // calculate corner angles, which are different when the cut is negative (outside corner)
1205                        leftangle = cutleft>=0?
1206                                vector_angle([newleft[1],newleft[0],newright[0]])/2 :
1207                                90-vector_angle([newleft[1],newleft[0],newright[0]])/2,
1208                        rightangle = cutright>=0?
1209                                vector_angle([newright[1],newright[0],newleft[0]])/2 :
1210                                90-vector_angle([newright[1],newright[0],newleft[0]])/2,
1211                        jointleft = 8*cutleft/cos(leftangle)/(1+4*bez_k),
1212                        jointright = 8*cutright/cos(rightangle)/(1+4*bez_k),
1213                        pathcutleft = path_cut_points(newleft,abs(jointleft)),
1214                        pathcutright = path_cut_points(newright,abs(jointright)),
1215                        leftdelete = intright? pathcutleft[1] : pathcutleft[1] + pathclip[1] -1,
1216                        rightdelete = intright? pathcutright[1] + pathclip[1] -1 : pathcutright[1],
1217                        leftcorner = line_intersection([pathcutleft[0], newleft[pathcutleft[1]]], [newright[0],newleft[0]]),
1218                        rightcorner = line_intersection([pathcutright[0], newright[pathcutright[1]]], [newright[0],newleft[0]]),
1219                        roundover_fits = is_def(rightcorner) && is_def(leftcorner) &&
1220                                         jointleft+jointright < norm(rightcorner-leftcorner)
1221                )
1222                assert(roundover_fits,"Roundover too large to fit")
1223                let(
1224                        angled_dir = unit(newleft[0]-newright[0]),
1225                        nPleft = [
1226                                leftcorner - jointleft*angled_dir,
1227                                leftcorner,
1228                                pathcutleft[0]
1229                        ],
1230                        nPright = [
1231                                pathcutright[0],
1232                                rightcorner,
1233                                rightcorner + jointright*angled_dir
1234                        ],
1235                        leftcurve = _bezcorner(nPleft, bez_k),
1236                        rightcurve = _bezcorner(nPright, bez_k)
1237                )
1238                [concat(rightcurve, leftcurve), leftdelete, rightdelete]
1239        ) : [[],0,0];  // This case shouldn't occur
1240
1241// returns [intersection_pt, index of first point in path after the intersection]
1242function _path_line_intersection(path, line, ind=0) =
1243        ind==len(path)-1 ? undef :
1244        let(intersect=line_intersection(line, select(path,ind,ind+1),LINE,SEGMENT))
1245        // If it intersects the segment excluding it's final point, then we're done
1246        // The final point is treated as part of the next segment
1247        is_def(intersect) && intersect != path[ind+1]?
1248                [intersect, ind+1] :
1249                _path_line_intersection(path, line, ind+1);
1250
1251module offset_stroke(path, width=1, rounded=true, start, end, check_valid=true, quality=1, chamfer=false, closed=false,
1252                     atype="hull", anchor, spin, cp="centroid")
1253{
1254        result = offset_stroke(
1255                path, width=width, rounded=rounded,
1256                start=start, end=end,
1257                check_valid=check_valid, quality=quality,
1258                chamfer=chamfer,
1259                closed=closed
1260        );
1261        region(result,atype=atype, anchor=anchor, spin=spin, cp=cp) children();
1262}
1263
1264
1265// Section: Three-Dimensional Rounding
1266
1267// Function&Module: offset_sweep()
1268// Synopsis: Make a solid from a polygon with offset that changes along its length.
1269// SynTags: Geom, VNF
1270// Topics: Rounding, Offsets
1271// See Also: convex_offset_extrude(), rounded_prism(), bent_cutout_mask(), join_prism(), linear_sweep()
1272// Usage: most common module arguments.  See Arguments list below for more.
1273//   offset_sweep(path, [height|length|h|l|], [bottom], [top], [offset=], [convexity=],...) [ATTACHMENTS];
1274// Usage: most common function arguments.  See Arguments list below for more.
1275//   vnf = offset_sweep(path, [height|h|l|length], [bottom], [top], [offset=], ...);
1276// Description:
1277//   Takes a 2d path as input and extrudes it upwards and/or downward.  Each layer in the extrusion is produced using `offset()` to expand or shrink the previous layer.  When invoked as a function returns a VNF; when invoked as a module produces geometry.  
1278//   Using the `top` and/or `bottom` arguments you can specify a sequence of offsets values, or you can use several built-in offset profiles that
1279//   provide end treatments such as roundovers.
1280//   The height of the resulting object can be specified using the `height` argument, in which case `height` must be larger than the combined height
1281//   of the end treatments.  If you omit `height` then the object height will be the height of just the top and bottom end treatments.  
1282//   .
1283//   The path is shifted by `offset()` multiple times in sequence
1284//   to produce the final shape (not multiple shifts from one parent), so coarse definition of the input path will degrade
1285//   from the successive shifts.  If the result seems rough or strange try increasing the number of points you use for
1286//   your input.  If you get unexpected corners in your result you may have forgotten to set `$fn` or `$fa` and `$fs`.  
1287//   Be aware that large numbers of points (especially when check_valid is true) can lead to lengthy run times.  If your
1288//   shape doesn't develop new corners from the offsetting you may be able to save a lot of time by setting `check_valid=false`.  Be aware that
1289//   disabling the validity check when it is needed can generate invalid polyhedra that will produce CGAL errors upon
1290//   rendering.  Such validity errors will also occur if you specify a self-intersecting shape.
1291//   The offset profile is quantized to 1/1024 steps to avoid failures in offset() that can occur with very tiny offsets.
1292//   .
1293//   The build-in profiles are: circular rounding, teardrop rounding, continuous curvature rounding, and chamfer.
1294//   Also note that when a rounding radius is negative the rounding will flare outwards.  The easiest way to specify
1295//   the profile is by using the profile helper functions.  These functions take profile parameters, as well as some
1296//   general settings and translate them into a profile specification, with error checking on your input.  The description below
1297//   describes the helper functions and the parameters specific to each function.  Below that is a description of the generic
1298//   settings that you can optionally use with all of the helper functions.  For more details on the "cut" and "joint" rounding parameters, and
1299//   on continuous curvature rounding, see [Types of Roundover](rounding.scad#subsection-types-of-roundover). 
1300//   .
1301//   - profile: os_profile(points)
1302//     Define the offset profile with a list of points.  The first point must be [0,0] and the roundover should rise in the positive y direction, with positive x values for inward motion (standard roundover) and negative x values for flaring outward.  If the y value ever decreases then you might create a self-intersecting polyhedron, which is invalid.  Such invalid polyhedra will create cryptic assertion errors when you render your model and it is your responsibility to avoid creating them.  Note that the starting point of the profile is the center of the extrusion.  If you use a profile as the top it will rise upwards.  If you use it as the bottom it will be inverted, and will go downward.
1303//   - circle: os_circle(r|cut).  Define circular rounding either by specifying the radius or cut distance.
1304//   - smooth: os_smooth(cut|joint, [k]).  Define continuous curvature rounding, with `cut` and `joint` as for round_corners. The k parameter controls how fast the curvature changes and should be between 0 and 1.  
1305//   - teardrop: os_teardrop(r|cut).  Rounding using a 1/8 circle that then changes to a 45 degree chamfer.  The chamfer is at the end, and enables the object to be 3d printed without support.  The radius gives the radius of the circular part.
1306//   - chamfer: os_chamfer([height], [width], [cut], [angle]).  Chamfer the edge at desired angle or with desired height and width.  You can specify height and width together and the angle will be ignored, or specify just one of height and width and the angle is used to determine the shape.  Alternatively, specify "cut" along with angle to specify the cut back distance of the chamfer.
1307//   - mask: os_mask(mask, [out]).  Create a profile from one of the [2d masking shapes](shapes2d.scad#5-2d-masking-shapes).  The `out` parameter specifies that the mask should flare outward (like crown molding or baseboard).  This is set false by default.  
1308//   .
1309//   The general settings that you can use with all of the helper functions are mostly used to control how offset_sweep() calls the offset() function.
1310//   - extra: Add an extra vertical step of the specified height, to be used for intersections or differences.  This extra step will extend the resulting object beyond the height you specify.  Default: 0
1311//   - check_valid: passed to offset().  Default: true
1312//   - quality: passed to offset().  Default: 1
1313//   - steps: Number of vertical steps to use for the profile.  (Not used by os_profile).  Default: 16
1314//   - offset: Select "round" (r=) or "delta" (delta=) offset types for offset. You can also choose "chamfer" but this leads to exponential growth in the number of vertices with the steps parameter.  Default: "round"
1315//   .
1316//   Many of the arguments are described as setting "default" values because they establish settings which may be overridden by
1317//   the top and bottom profile specifications.
1318//   .
1319//   You will generally want to use the above helper functions to generate the profiles.
1320//   The profile specification is a list of pairs of keywords and values, e.g. ["for","offset_sweep","r",12, type, "circle"]. The keywords are
1321//   - "for" - must appear first in the list and have the value "offset_sweep"
1322//   - "type" - type of rounding to apply, one of "circle", "teardrop", "chamfer", "smooth", or "profile" (Default: "circle")
1323//   - "r" - the radius of the roundover, which may be zero for no roundover, or negative to round or flare outward.  Default: 0
1324//   - "cut" - the cut distance for the roundover or chamfer, which may be negative for flares
1325//   - "chamfer_width" - the width of a chamfer
1326//   - "chamfer_height" - the height of a chamfer
1327//   - "angle" - the chamfer angle, measured from the vertical (so zero is vertical, 90 is horizontal).  Default: 45
1328//   - "joint" - the joint distance for a "smooth" roundover
1329//   - "k" - the curvature smoothness parameter for "smooth" roundovers, a value in [0,1].  Default: 0.75
1330//   - "points" - point list for use with the "profile" type
1331//   - "extra" - extra height added for unions/differences.  This makes the shape taller than the requested height.  (Default: 0)
1332//   - "check_valid" - passed to offset.  Default: true.
1333//   - "quality" - passed to offset.  Default: 1.
1334//   - "steps" - number of vertical steps to use for the roundover.  Default: 16.
1335//   - "offset" - select "round" (r=), "delta" (delta=), or "chamfer" offset type for offset.  Default: "round"
1336//   .
1337//   Note that if you set the "offset" parameter to "chamfer" then every exterior corner turns from one vertex into two vertices with
1338//   each offset operation.  Since the offsets are done one after another, each on the output of the previous one, this leads to
1339//   exponential growth in the number of vertices.  This can lead to long run times or yield models that
1340//   run out of recursion depth and give a cryptic error.  Furthermore, the generated vertices are distributed non-uniformly.  Generally you
1341//   will get a similar or better looking model with fewer vertices using "round" instead of
1342//   "chamfer".  Use the "chamfer" style offset only in cases where the number of steps is very small or just one (such as when using
1343//   the `os_chamfer` profile type).
1344//
1345// Arguments:
1346//   path = 2d path (list of points) to extrude
1347//   height / l / h = total height (including rounded portions, but not extra sections) of the output.  Default: combined height of top and bottom end treatments.
1348//   bottom = rounding spec for the bottom end
1349//   top = rounding spec for the top end.
1350//   ---
1351//   offset = default offset, `"round"` or `"delta"`.  Default: `"round"`
1352//   steps = default step count.  Default: 16
1353//   quality = default quality.  Default: 1
1354//   check_valid = default check_valid.  Default: true.
1355//   extra = default extra height.  Default: 0
1356//   cut = default cut value.
1357//   chamfer_width = default width value for chamfers.
1358//   chamfer_height = default height value for chamfers.
1359//   angle = default angle for chamfers.  Default: 45
1360//   joint = default joint value for smooth roundover.
1361//   k = default curvature parameter value for "smooth" roundover
1362//   convexity = convexity setting for use with polyhedron.  (module only) Default: 10
1363//   anchor = Translate so anchor point is at the origin.  (module only) Default: "origin"
1364//   spin = Rotate this many degrees around Z axis after anchor.  (module only) Default: 0
1365//   orient = Vector to rotate top towards after spin  (module only)
1366//   atype = Select "hull" or "intersect" anchor types.  Default: "hull"
1367//   cp = Centerpoint for determining "intersect" anchors or centering the shape.  Determintes the base of the anchor vector.  Can be "centroid", "mean", "box" or a 3D point.  Default: "centroid"
1368// Example: Rounding a star shaped prism with postive radius values
1369//   star = star(5, r=22, ir=13);
1370//   rounded_star = round_corners(star, cut=flatten(repeat([.5,0],5)), $fn=24);
1371//   offset_sweep(rounded_star, height=20, bottom=os_circle(r=4), top=os_circle(r=1), steps=15);
1372// Example: Rounding a star shaped prism with negative radius values.  The starting shape has no corners, so the value of `$fn` does not matter.
1373//   star = star(5, r=22, ir=13); 
1374//   rounded_star = round_corners(star, cut=flatten(repeat([.5,0],5)), $fn=36);
1375//   offset_sweep(rounded_star, height=20, bottom=os_circle(r=-4), top=os_circle(r=-1), steps=15);
1376// Example: If the shape has sharp corners, make sure to set `$fn/$fs/$fa`.  The corners of this triangle are not round, even though `offset="round"` (the default) because the number of segments is small.
1377//   triangle = [[0,0],[10,0],[5,10]];
1378//   offset_sweep(triangle, height=6, bottom = os_circle(r=-2),steps=4);
1379// Example: Can improve the result by increasing $fn
1380//   $fn=12;
1381//   triangle = [[0,0],[10,0],[5,10]];
1382//   offset_sweep(triangle, height=6, bottom = os_circle(r=-2),steps=4);
1383// Example: Using $fa and $fs works too; it produces a different looking triangulation of the rounded corner
1384//   $fa=1;$fs=0.3;
1385//   triangle = [[0,0],[10,0],[5,10]];
1386//   offset_sweep(triangle, height=6, bottom = os_circle(r=-2),steps=4);
1387// Example: Here is the star chamfered at the top with a teardrop rounding at the bottom. Check out the rounded corners on the chamfer.  The large $fn value ensures a smooth curve on the concave corners of the chamfer.  It has no effect anywhere else on the model.  Observe how the rounded star points vanish at the bottom in the teardrop: the number of vertices does not remain constant from layer to layer.
1388//    star = star(5, r=22, ir=13);
1389//    rounded_star = round_corners(star, cut=flatten(repeat([.5,0],5)), $fn=24);
1390//    offset_sweep(rounded_star, height=20, bottom=os_teardrop(r=4), top=os_chamfer(width=4),$fn=64);
1391// Example: We round a cube using the continous curvature rounding profile.  But note that the corners are not smooth because the curved square collapses into a square with corners.    When a collapse like this occurs, we cannot turn `check_valid` off.  For a better result use `rounded_prism()` instead.
1392//   square = square(1);
1393//   rsquare = round_corners(square, method="smooth", cut=0.1, k=0.7, $fn=36);
1394//   end_spec = os_smooth(cut=0.1, k=0.7, steps=22);
1395//   offset_sweep(rsquare, height=1, bottom=end_spec, top=end_spec);
1396// Example(3D,Med): A nice rounded box, with a teardrop base and circular rounded interior and top
1397//   box = square([255,50]);
1398//   rbox = round_corners(box, method="smooth", cut=4, $fn=12);
1399//   thickness = 2;
1400//   difference(){
1401//     offset_sweep(rbox, height=50, check_valid=false, steps=22,
1402//                  bottom=os_teardrop(r=2), top=os_circle(r=1));
1403//     up(thickness)
1404//       offset_sweep(offset(rbox, r=-thickness, closed=true,check_valid=false),
1405//                    height=48, steps=22, check_valid=false,
1406//                    bottom=os_circle(r=4), top=os_circle(r=-1,extra=1));
1407//   }
1408// Example: This box is much thicker, and cut in half to show the profiles.  Note also that we can turn `check_valid` off for the outside and for the top inside, but not for the bottom inside.  This example shows use of the direct keyword syntax without the helper functions.
1409//   smallbox = square([75,50]);
1410//   roundbox = round_corners(smallbox, method="smooth", cut=4, $fn=12);
1411//   thickness=4;
1412//   height=50;
1413//   back_half(y=25, s=200)
1414//     difference(){
1415//       offset_sweep(roundbox, height=height, bottom=["for","offset_sweep","r",10,"type","teardrop"],
1416//                                             top=["for","offset_sweep","r",2], steps = 22, check_valid=false);
1417//       up(thickness)
1418//         offset_sweep(offset(roundbox, r=-thickness, closed=true),
1419//                       height=height-thickness, steps=22,
1420//                       bottom=["for","offset_sweep","r",6],
1421//                       top=["for","offset_sweep","type","chamfer","angle",30,
1422//                            "chamfer_height",-3,"extra",1,"check_valid",false]);
1423//   }
1424// Example(3D,Med): A box with multiple sections and rounded dividers
1425//   thickness = 2;
1426//   box = square([255,50]);
1427//   cutpoints = [0, 125, 190, 255];
1428//   rbox = round_corners(box, method="smooth", cut=4, $fn=12);
1429//   back_half(y=25, s=700)
1430//     difference(){
1431//       offset_sweep(rbox, height=50, check_valid=false, steps=22,
1432//                    bottom=os_teardrop(r=2), top=os_circle(r=1));
1433//       up(thickness)
1434//         for(i=[0:2]){
1435//           ofs = i==1 ? 2 : 0;
1436//           hole = round_corners([[cutpoints[i]-ofs,0], [cutpoints[i]-ofs,50],
1437//                                 [cutpoints[i+1]+ofs, 50], [cutpoints[i+1]+ofs,0]],
1438//                                method="smooth", cut=4, $fn=36);
1439//           offset_sweep(offset(hole, r=-thickness, closed=true,check_valid=false),
1440//                         height=48, steps=22, check_valid=false,
1441//                         bottom=os_circle(r=4), top=os_circle(r=-1,extra=1));
1442//         }
1443//     }
1444// Example(3D,Med): Star shaped box
1445//   star = star(5, r=22, ir=13);
1446//   rounded_star = round_corners(star, cut=flatten(repeat([.5,0],5)), $fn=24);
1447//   thickness = 2;
1448//   ht=20;
1449//   difference(){
1450//     offset_sweep(rounded_star, height=ht, bottom=["for","offset_sweep","r",4],
1451//                                           top=["for","offset_sweep","r",1], steps=15);
1452//     up(thickness)
1453//         offset_sweep(offset(rounded_star,r=-thickness,closed=true),
1454//                       height=ht-thickness, check_valid=false,
1455//                       bottom=os_circle(r=7), top=os_circle(r=-1, extra=1),$fn=40);
1456//     }
1457// Example: A profile defined by an arbitrary sequence of points.
1458//   star = star(5, r=22, ir=13);
1459//   rounded_star = round_corners(star, cut=flatten(repeat([.5,0],5)), $fn=24);
1460//   profile = os_profile(points=[[0,0],[.3,.1],[.6,.3],[.9,.9], [1.2, 2.7],[.8,2.7],[.8,3]]);
1461//   offset_sweep(reverse(rounded_star), height=20, top=profile, bottom=profile, $fn=32);
1462// Example: Parabolic rounding
1463//   star = star(5, r=22, ir=13);
1464//   rounded_star = round_corners(star, cut=flatten(repeat([.5,0],5)), $fn=24);
1465//   offset_sweep(rounded_star, height=20, top=os_profile(points=[for(r=[0:.1:2])[sqr(r),r]]),
1466//                                          bottom=os_profile(points=[for(r=[0:.2:5])[-sqrt(r),r]]),$fn=32);
1467// Example: This example uses a sine wave offset profile.  Note that we give no specification for the bottom, so it is straight.
1468//   sq = [[0,0],[20,0],[20,20],[0,20]];
1469//   sinwave = os_profile(points=[for(theta=[0:5:720]) [4*sin(theta), theta/700*15]]);
1470//   offset_sweep(sq, height=20, top=sinwave, $fn=32);
1471// Example: The same as the previous example but `offset="delta"`
1472//   sq = [[0,0],[20,0],[20,20],[0,20]];
1473//   sinwave = os_profile(points=[for(theta=[0:5:720]) [4*sin(theta), theta/700*15]]);
1474//   offset_sweep(sq, height=20, top=sinwave, offset="delta");
1475// Example: a box with a flared top.  A nice roundover on the top requires a profile edge, but we can use "extra" to create a small chamfer.
1476//   rhex = round_corners(hexagon(side=10), method="smooth", joint=2, $fs=0.2);
1477//   back_half()
1478//     difference(){
1479//       offset_sweep(rhex, height=10, bottom=os_teardrop(r=2), top=os_teardrop(r=-4, extra=0.2));
1480//       up(1)
1481//         offset_sweep(offset(rhex,r=-1), height=9.5, bottom=os_circle(r=2), top=os_teardrop(r=-4));
1482//     }
1483// Example: Using os_mask to create ogee profiles:
1484//   ogee = mask2d_ogee([
1485//       "xstep",1,  "ystep",1,  // Starting shoulder.
1486//       "fillet",5, "round",5,  // S-curve.
1487//       "ystep",1,              // Ending shoulder.
1488//   ]);
1489//   star = star(5, r=220, ir=130);
1490//   rounded_star = round_corners(star, cut=flatten(repeat([5,0],5)), $fn=24);
1491//   offset_sweep(rounded_star, height=100, top=os_mask(ogee), bottom=os_mask(ogee,out=true));
1492
1493
1494// This function does the actual work of repeatedly calling offset() and concatenating the resulting face and vertex lists to produce
1495// the inputs for the polyhedron module.
1496function _make_offset_polyhedron(path,offsets, offset_type, flip_faces, quality, check_valid, offsetind=0,
1497                                 vertexcount=0, vertices=[], faces=[] )=
1498        offsetind==len(offsets)? (
1499                let(
1500                        bottom = count(len(path),vertexcount),
1501                        oriented_bottom = !flip_faces? bottom : reverse(bottom)
1502                ) [vertices, concat(faces,[oriented_bottom])]
1503        ) : (
1504                let(
1505                        this_offset = offsetind==0? offsets[0][0] : offsets[offsetind][0] - offsets[offsetind-1][0],
1506                        delta = offset_type=="delta" || offset_type=="chamfer" ? this_offset : undef,
1507                        r = offset_type=="round"? this_offset : undef,
1508                        do_chamfer = offset_type == "chamfer"
1509                )
1510                let(
1511                        vertices_faces = offset(
1512                                path, r=r, delta=delta, chamfer = do_chamfer, closed=true,
1513                                check_valid=check_valid, quality=quality,
1514                                return_faces=true,
1515                                firstface_index=vertexcount,
1516                                flip_faces=flip_faces
1517                        )
1518                )
1519                _make_offset_polyhedron(
1520                        vertices_faces[0], offsets, offset_type,
1521                        flip_faces, quality, check_valid, 
1522                        offsetind+1, vertexcount+len(path),
1523                        vertices=concat(
1524                                vertices,
1525                                path3d(vertices_faces[0],offsets[offsetind][1])
1526                        ),
1527                        faces=concat(faces, vertices_faces[1])
1528                )
1529        );
1530
1531
1532function _struct_valid(spec, func, name) =
1533        spec==[] ? true :
1534        assert(is_list(spec) && len(spec)>=2 && spec[0]=="for",str("Specification for \"", name, "\" is an invalid structure"))
1535        assert(spec[1]==func, str("Specification for \"",name,"\" is for a different function (",func,")"));
1536
1537function offset_sweep(
1538                       path, height, 
1539                       bottom=[], top=[], 
1540                       h, l, length, 
1541                       offset="round", r=0, steps=16,
1542                       quality=1, check_valid=true,
1543                       extra=0,
1544                       cut=undef, chamfer_width=undef, chamfer_height=undef,
1545                       joint=undef, k=0.75, angle=45
1546                      ) =
1547    let(
1548        argspec = [
1549                   ["for",""],
1550                   ["r",r],
1551                   ["extra",extra],
1552                   ["type","circle"],
1553                   ["check_valid",check_valid],
1554                   ["quality",quality],
1555                   ["steps",steps],
1556                   ["offset",offset],
1557                   ["chamfer_width",chamfer_width],
1558                   ["chamfer_height",chamfer_height],
1559                   ["angle",angle],
1560                   ["cut",cut],
1561                   ["joint",joint],
1562                   ["k", k],
1563                   ["points", []],
1564        ],
1565        path = force_path(path)
1566    )
1567    assert(is_path(path,2), "Input path must be a 2D path")
1568    let(
1569        clockwise = is_polygon_clockwise(path),
1570        dummy1 = _struct_valid(top,"offset_sweep","top"),
1571        dummy2 = _struct_valid(bottom,"offset_sweep","bottom"),
1572        top = struct_set(argspec, top, grow=false),
1573        bottom = struct_set(argspec, bottom, grow=false),
1574
1575        //  This code does not work.  It hits the error in _make_offset_polyhedron from offset being wrong
1576        //  before this code executes.  Had to move the test into _make_offset_polyhedron, which is ugly since it's in the loop
1577        offsetsok = in_list(struct_val(top, "offset"),["round","delta","chamfer"])
1578                    && in_list(struct_val(bottom, "offset"),["round","delta","chamfer"])
1579    )
1580    assert(offsetsok,"Offsets must be one of \"round\", \"delta\", or \"chamfer\"")
1581    let(
1582        offsets_bot = _rounding_offsets(bottom, -1),
1583        offsets_top = _rounding_offsets(top, 1),
1584        dummy = (struct_val(top,"offset")=="chamfer" && len(offsets_top)>5)
1585                        || (struct_val(bottom,"offset")=="chamfer" && len(offsets_bot)>5)
1586                ? echo("WARNING: You have selected offset=\"chamfer\", which leads to exponential growth in the vertex count and requested more than 5 layers.  This can be slow or run out of recursion depth.")
1587                : 0,
1588
1589        // "Extra" height enlarges the result beyond the requested height, so subtract it
1590        bottom_height = len(offsets_bot)==0 ? 0 : abs(last(offsets_bot)[1]) - struct_val(bottom,"extra"),
1591        top_height = len(offsets_top)==0 ? 0 : abs(last(offsets_top)[1]) - struct_val(top,"extra"),
1592
1593        height = one_defined([l,h,height,length], "l,h,height,length", dflt=u_add(bottom_height,top_height)),
1594        middle = height-bottom_height-top_height
1595    )
1596    assert(height>0, "Height must be positive") 
1597    assert(middle>=0, str("Specified end treatments (bottom height = ",bottom_height,
1598                          " top_height = ",top_height,") are too large for extrusion height (",height,")"
1599                         )
1600    )
1601    let(
1602        initial_vertices_bot = path3d(path),
1603
1604        vertices_faces_bot = _make_offset_polyhedron(
1605                path, offsets_bot, struct_val(bottom,"offset"), clockwise,
1606                struct_val(bottom,"quality"),
1607                struct_val(bottom,"check_valid"),
1608                vertices=initial_vertices_bot
1609        ),
1610
1611        top_start_ind = len(vertices_faces_bot[0]),
1612        initial_vertices_top = path3d(path, middle),
1613        vertices_faces_top = _make_offset_polyhedron(
1614                path, move(p=offsets_top,[0,middle]),
1615                struct_val(top,"offset"), !clockwise,
1616                struct_val(top,"quality"),
1617                struct_val(top,"check_valid"),
1618                vertexcount=top_start_ind,
1619                vertices=initial_vertices_top
1620        ),
1621        middle_faces = middle==0 ? [] : [
1622                for(i=[0:len(path)-1]) let(
1623                        oneface=[i, (i+1)%len(path), top_start_ind+(i+1)%len(path), top_start_ind+i]
1624                ) !clockwise ? reverse(oneface) : oneface
1625        ]
1626    )
1627    [up(bottom_height, concat(vertices_faces_bot[0],vertices_faces_top[0])),  // Vertices
1628     concat(vertices_faces_bot[1], vertices_faces_top[1], middle_faces)];     // Faces
1629
1630
1631module offset_sweep(path, height, 
1632                    bottom=[], top=[], 
1633                    h, l,
1634                    offset="round", r=0, steps=16,
1635                    quality=1, check_valid=true,
1636                    extra=0,
1637                    cut=undef, chamfer_width=undef, chamfer_height=undef,
1638                    joint=undef, k=0.75, angle=45,
1639                    convexity=10,anchor="origin",cp="centroid",
1640                    spin=0, orient=UP, atype="hull")
1641{
1642    assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"");
1643    vnf = offset_sweep(path=path, height=height, h=h, l=l, top=top, bottom=bottom, offset=offset, r=r, steps=steps,
1644                       quality=quality, check_valid=check_valid, extra=extra, cut=cut, chamfer_width=chamfer_width,
1645                       chamfer_height=chamfer_height, joint=joint, k=k, angle=angle);
1646    vnf_polyhedron(vnf,convexity=convexity,anchor=anchor, spin=spin, orient=orient, atype=atype, cp=cp)
1647        children();
1648}   
1649
1650
1651
1652function os_circle(r,cut,extra,check_valid, quality,steps, offset) =
1653        assert(num_defined([r,cut])==1, "Must define exactly one of `r` and `cut`")
1654        _remove_undefined_vals([
1655                "for", "offset_sweep",
1656                "type", "circle",
1657                "r",r,
1658                "cut",cut,
1659                "extra",extra,
1660                "check_valid",check_valid,
1661                "quality", quality,
1662                "steps", steps,
1663                "offset", offset
1664        ]);
1665
1666function os_teardrop(r,cut,extra,check_valid, quality,steps, offset) =
1667        assert(num_defined([r,cut])==1, "Must define exactly one of `r` and `cut`")
1668        _remove_undefined_vals([
1669                "for", "offset_sweep",
1670                "type", "teardrop",
1671                "r",r,
1672                "cut",cut,
1673                "extra",extra,
1674                "check_valid",check_valid,
1675                "quality", quality,
1676                "steps", steps,
1677                "offset", offset
1678        ]);
1679
1680function os_chamfer(height, width, cut, angle, extra,check_valid, quality,steps, offset) =
1681        let(ok = (is_def(cut) && num_defined([height,width])==0) || num_defined([height,width])>0)
1682        assert(ok, "Must define `cut`, or one or both of `width` and `height`")
1683        _remove_undefined_vals([
1684                "for", "offset_sweep",
1685                "type", "chamfer",
1686                "chamfer_width",width,
1687                "chamfer_height",height,
1688                "cut",cut,
1689                "angle",angle,
1690                "extra",extra,
1691                "check_valid",check_valid,
1692                "quality", quality,
1693                "steps", steps,
1694                "offset", offset
1695        ]);
1696
1697function os_smooth(cut, joint, k, extra,check_valid, quality,steps, offset) =
1698        assert(num_defined([joint,cut])==1, "Must define exactly one of `joint` and `cut`")
1699        _remove_undefined_vals([
1700                "for", "offset_sweep",
1701                "type", "smooth",
1702                "joint",joint,
1703                "k",k,
1704                "cut",cut,
1705                "extra",extra,
1706                "check_valid",check_valid,
1707                "quality", quality,
1708                "steps", steps,
1709                "offset", offset
1710        ]);
1711
1712function os_profile(points, extra,check_valid, quality, offset) =
1713        assert(is_path(points),"Profile point list is not valid")
1714        _remove_undefined_vals([
1715                "for", "offset_sweep",
1716                "type", "profile",
1717                "points", points,
1718                "extra",extra,
1719                "check_valid",check_valid,
1720                "quality", quality,
1721                "offset", offset
1722        ]);
1723
1724
1725function os_mask(mask, out=false, extra,check_valid, quality, offset) =
1726  let(
1727      origin_index = [for(i=idx(mask)) if (mask[i].x<0 && mask[i].y<0) i],
1728      xfactor = out ? -1 : 1
1729  )
1730  assert(len(origin_index)==1,"Cannot find origin in the mask")
1731  let(
1732      points = ([for(pt=list_rotate(mask,origin_index[0])) [xfactor*max(pt.x,0),-max(pt.y,0)]])
1733  )
1734  os_profile(deduplicate(move(-points[1],p=list_tail(points))), extra,check_valid,quality,offset);
1735
1736
1737// Module: convex_offset_extrude()
1738// Synopsis: Make a solid from geometry where offset changes along the object's length.
1739// SynTags: Geom
1740// Topics: Rounding, Offsets
1741// See Also: offset_sweep(), rounded_prism(), bent_cutout_mask(), join_prism(), linear_sweep()
1742// Usage: Basic usage.  See below for full options
1743//   convex_offset_extrude(height, [bottom], [top], ...) 2D-CHILDREN;
1744// Description:
1745//   Extrudes 2d children with layers formed from the convex hull of the offset of each child according to a sequence of offset values.
1746//   Like `offset_sweep` this module can use built-in offset profiles to provide treatments such as roundovers or chamfers but unlike `offset_sweep()` it
1747//   operates on 2d children rather than a point list.  Each offset is computed using
1748//   the native `offset()` module from the input geometry.
1749//   If your shape has corners that you want rounded by offset be sure to set `$fn` or `$fs` appropriately.
1750//   If your geometry has internal holes or is too small for the specified offset then you may get
1751//   unexpected results.
1752//   .
1753//   The build-in profiles are: circular rounding, teardrop rounding, continuous curvature rounding, and chamfer.
1754//   Also note that when a rounding radius is negative the rounding will flare outwards.  The easiest way to specify
1755//   the profile is by using the profile helper functions.  These functions take profile parameters, as well as some
1756//   general settings and translate them into a profile specification, with error checking on your input.  The description below
1757//   describes the helper functions and the parameters specific to each function.  Below that is a description of the generic
1758//   settings that you can optionally use with all of the helper functions.
1759//   For more details on the "cut" and "joint" rounding parameters, and
1760//   on continuous curvature rounding, see [Types of Roundover](rounding.scad#subsection-types-of-roundover). 
1761//   .
1762//   The final shape is created by combining convex hulls of small extrusions.  The thickness of these small extrusions may result
1763//   your model being slightly too long (if the curvature at the end is flaring outward), so if the exact length is very important
1764//   you may need to intersect with a bounding cube.  (Note that extra length can also be intentionally added with the `extra` argument.)
1765//   .
1766//   - profile: os_profile(points)
1767//     Define the offset profile with a list of points.  The first point must be [0,0] and the roundover should rise in the positive y direction, with positive x values for inward motion (standard roundover) and negative x values for flaring outward.  If the y value ever decreases then you might create a self-intersecting polyhedron, which is invalid.  Such invalid polyhedra will create cryptic assertion errors when you render your model and it is your responsibility to avoid creating them.  Note that the starting point of the profile is the center of the extrusion.  If you use a profile as the top it will rise upwards.  If you use it as the bottom it will be inverted, and will go downward.
1768//   - circle: os_circle(r|cut).  Define circular rounding either by specifying the radius or cut distance.
1769//   - smooth: os_smooth(cut|joint, [k]).  Define continuous curvature rounding, with `cut` and `joint` as for round_corners.  The k parameter controls how fast the curvature changes and should be between 0 and 1.
1770//   - teardrop: os_teardrop(r|cut).  Rounding using a 1/8 circle that then changes to a 45 degree chamfer.  The chamfer is at the end, and enables the object to be 3d printed without support.  The radius gives the radius of the circular part.
1771//   - chamfer: os_chamfer([height], [width], [cut], [angle]).  Chamfer the edge at desired angle or with desired height and width.  You can specify height and width together and the angle will be ignored, or specify just one of height and width and the angle is used to determine the shape.  Alternatively, specify "cut" along with angle to specify the cut back distance of the chamfer.
1772//   .
1773//   The general settings that you can use with all of the helper functions are mostly used to control how offset_sweep() calls the offset() function.
1774//   - extra: Add an extra vertical step of the specified height, to be used for intersections or differences.  This extra step will extend the resulting object beyond the height you specify.  Default: 0
1775//   - steps: Number of vertical steps to use for the profile.  (Not used by os_profile).  Default: 16
1776//   - offset: Select "round" (r=), "delta" (delta=), or "chamfer" offset types for offset.  Default: "round"
1777//   .
1778//   Many of the arguments are described as setting "default" values because they establish settings which may be overridden by
1779//   the top and bottom profile specifications.
1780//   .
1781//   You will generally want to use the above helper functions to generate the profiles.
1782//   The profile specification is a list of pairs of keywords and values, e.g. ["r",12, type, "circle"]. The keywords are
1783//   - "type" - type of rounding to apply, one of "circle", "teardrop", "chamfer", "smooth", or "profile" (Default: "circle")
1784//   - "r" - the radius of the roundover, which may be zero for no roundover, or negative to round or flare outward.  Default: 0
1785//   - "cut" - the cut distance for the roundover or chamfer, which may be negative for flares
1786//   - "chamfer_width" - the width of a chamfer
1787//   - "chamfer_height" - the height of a chamfer
1788//   - "angle" - the chamfer angle, measured from the vertical (so zero is vertical, 90 is horizontal).  Default: 45
1789//   - "joint" - the joint distance for a "smooth" roundover
1790//   - "k" - the curvature smoothness parameter for "smooth" roundovers, a value in [0,1].  Default: 0.75
1791//   - "points" - point list for use with the "profile" type
1792//   - "extra" - extra height added for unions/differences.  This makes the shape taller than the requested height.  (Default: 0)
1793//   - "steps" - number of vertical steps to use for the roundover.  Default: 16.
1794//   - "offset" - select "round" (r=) or "delta" (delta=) offset type for offset.  Default: "round"
1795//   .
1796//   Note that unlike `offset_sweep`, because the offset operation is always performed from the base shape, using chamfered offsets does not increase the
1797//   number of vertices or lead to any special complications.
1798//
1799// Arguments:
1800//   height / length / l / h = total height (including rounded portions, but not extra sections) of the output.  Default: combined height of top and bottom end treatments.
1801//   bottom = rounding spec for the bottom end
1802//   top = rounding spec for the top end.
1803//   ---
1804//   offset = default offset, `"round"`, `"delta"`, or `"chamfer"`.  Default: `"round"`
1805//   steps = default step count.  Default: 16
1806//   extra = default extra height.  Default: 0
1807//   cut = default cut value.
1808//   chamfer_width = default width value for chamfers.
1809//   chamfer_height = default height value for chamfers.
1810//   angle = default angle for chamfers.  Default: 45
1811//   joint = default joint value for smooth roundover.
1812//   k = default curvature parameter value for "smooth" roundover
1813//   convexity = convexity setting for use with polyhedron.  Default: 10
1814// Example: Chamfered elliptical prism.  If you stretch a chamfered cylinder the chamfer will be uneven.
1815//   convex_offset_extrude(bottom = os_chamfer(height=-2),
1816//                         top=os_chamfer(height=1), height=7)
1817//     xscale(4)circle(r=6,$fn=64);
1818// Example: Elliptical prism with circular roundovers.
1819//   convex_offset_extrude(bottom=os_circle(r=-2),
1820//                         top=os_circle(r=1), height=7,steps=10)
1821//     xscale(4)circle(r=6,$fn=64);
1822// Example: If you give a non-convex input you get a convex hull output
1823//   right(50) linear_extrude(height=7) star(5,r=22,ir=13);
1824//   convex_offset_extrude(bottom = os_chamfer(height=-2),
1825//                         top=os_chamfer(height=1), height=7, $fn=32)
1826//     star(5,r=22,ir=13);
1827function convex_offset_extrude(
1828        height, 
1829        bottom=[], top=[], 
1830        h, l, length,
1831        offset="round", r=0, steps=16,
1832        extra=0,
1833        cut=undef, chamfer_width=undef, chamfer_height=undef,
1834        joint=undef, k=0.75, angle=45,
1835        convexity=10, thickness = 1/1024
1836) = no_function("convex_offset_extrude");
1837module convex_offset_extrude(
1838        height,
1839        bottom=[],
1840        top=[], 
1841        h, l, length,
1842        offset="round", r=0, steps=16,
1843        extra=0,
1844        cut=undef, chamfer_width=undef, chamfer_height=undef,
1845        joint=undef, k=0.75, angle=45,
1846        convexity=10, thickness = 1/1024
1847) {
1848        req_children($children);  
1849        argspec = [
1850                ["for", ""],
1851                ["r",r],
1852                ["extra",extra],
1853                ["type","circle"],
1854                ["steps",steps],
1855                ["offset",offset],
1856                ["chamfer_width",chamfer_width],
1857                ["chamfer_height",chamfer_height],
1858                ["angle",angle],
1859                ["cut",cut],
1860                ["joint",joint],
1861                ["k", k],
1862                ["points", []],
1863        ];
1864        top = struct_set(argspec, top, grow=false);
1865        bottom = struct_set(argspec, bottom, grow=false);
1866
1867        offsets_bot = _rounding_offsets(bottom, -1);
1868        offsets_top = _rounding_offsets(top, 1);
1869
1870        // "Extra" height enlarges the result beyond the requested height, so subtract it
1871        bottom_height = len(offsets_bot)==0 ? 0 : abs(last(offsets_bot)[1]) - struct_val(bottom,"extra");
1872        top_height = len(offsets_top)==0 ? 0 : abs(last(offsets_top)[1]) - struct_val(top,"extra");
1873
1874        height = one_defined([l,h,height,length], "l,h,height,length", dflt=u_add(bottom_height,top_height));
1875        middle = height-bottom_height-top_height;
1876        check =
1877          assert(height>=0, "Height must be nonnegative")
1878          assert(middle>=0, str(
1879                                "Specified end treatments (bottom height = ",bottom_height,
1880                                " top_height = ",top_height,") are too large for extrusion height (",height,")"
1881                            )
1882          );
1883        // The entry r[i] is [radius,z] for a given layer
1884        r = move([0,bottom_height],p=concat(
1885                          reverse(offsets_bot), [[0,0], [0,middle]], move([0,middle], p=offsets_top)));
1886        delta = [for(val=deltas(column(r,0))) sign(val)];
1887        below=[-thickness,0];
1888        above=[0,thickness];
1889           // layers is a list of pairs of the relative positions for each layer, e.g. [0,thickness]
1890           // puts the layer above the polygon, and [-thickness,0] puts it below.
1891        layers = [for (i=[0:len(r)-1])
1892          i==0 ? (delta[0]<0 ? below : above) :
1893          i==len(r)-1 ? (delta[len(delta)-1] < 0 ? below : above) :
1894          delta[i]==0 ? above :
1895          delta[i+1]==0 ? below :
1896          delta[i]==delta[i-1] ? [-thickness/2, thickness/2] :
1897          delta[i] == 1 ? above :
1898          /* delta[i] == -1 ? */ below];
1899        dochamfer = offset=="chamfer";
1900        attachable(){
1901          for(i=[0:len(r)-2])
1902            for(j=[0:$children-1])
1903             hull(){
1904               up(r[i][1]+layers[i][0])
1905                 linear_extrude(convexity=convexity,height=layers[i][1]-layers[i][0])
1906                   if (offset=="round")
1907                     offset(r=r[i][0])
1908                       children(j);
1909                   else
1910                     offset(delta=r[i][0],chamfer = dochamfer)
1911                       children(j);
1912               up(r[i+1][1]+layers[i+1][0])
1913                 linear_extrude(convexity=convexity,height=layers[i+1][1]-layers[i+1][0])
1914                   if (offset=="round")
1915                     offset(r=r[i+1][0])
1916                       children(j);
1917                   else
1918                     offset(delta=r[i+1][0],chamfer=dochamfer)
1919                       children(j);
1920             }
1921          union();
1922        }
1923}
1924
1925
1926
1927function _remove_undefined_vals(list) =
1928        let(ind=search([undef],list,0)[0])
1929        list_remove(list, concat(ind, add_scalar(ind,-1)));
1930
1931
1932
1933function _rp_compute_patches(top, bot, rtop, rsides, ktop, ksides, concave) =
1934   let(
1935     N = len(top),
1936     plane = plane3pt_indexed(top,0,1,2),
1937     rtop_in = is_list(rtop) ? rtop[0] : rtop,
1938     rtop_down = is_list(rtop) ? rtop[1] : abs(rtop)
1939   )
1940  [for(i=[0:N-1])
1941           let(
1942               rside_prev = is_list(rsides[i])? rsides[i][0] : rsides[i],
1943               rside_next = is_list(rsides[i])? rsides[i][1] : rsides[i],
1944               concave_sign = (concave[i] ? -1 : 1) * (rtop_in>=0 ? 1 : -1),  // Negative if normals need to go "out"
1945               prev = select(top,i-1) - top[i],
1946               next = select(top,i+1) - top[i],
1947               prev_offset = top[i] + rside_prev * unit(prev) / sin(vector_angle(prev,bot[i]-top[i])),
1948               next_offset = top[i] + rside_next * unit(next) / sin(vector_angle(next,bot[i]-top[i])),
1949               down = rtop_down * unit(bot[i]-top[i]) / sin(abs(plane_line_angle(plane, [bot[i],top[i]]))),
1950               row2 = [prev_offset,     top[i],     next_offset     ],
1951               row4 = [prev_offset+down,top[i]+down,next_offset+down],
1952               in_prev = concave_sign * unit(next-(next*prev)*prev/(prev*prev)),
1953               in_next = concave_sign * unit(prev-(prev*next)*next/(next*next)),
1954               far_corner = top[i]+ concave_sign*unit(unit(prev)+unit(next))* abs(rtop_in) / sin(vector_angle(prev,next)/2),
1955               row0 =
1956                 concave_sign<0 ?
1957                    [prev_offset+abs(rtop_in)*in_prev, far_corner, next_offset+abs(rtop_in)*in_next]
1958                 :
1959                    let(
1960                       prev_corner = prev_offset + abs(rtop_in)*in_prev,
1961                       next_corner = next_offset + abs(rtop_in)*in_next,
1962                       line = project_plane(plane, [
1963                                                       [far_corner, far_corner+prev],
1964                                                       [prev_offset, prev_offset+in_prev],
1965                                                       [far_corner, far_corner+next],
1966                                                       [next_offset, next_offset+in_next]
1967                                                   ]),
1968                       prev_degenerate = is_undef(line_intersection(line[0],line[1],RAY,RAY)),
1969                       next_degenerate = is_undef(line_intersection(line[2],line[3],RAY,RAY))
1970                    )
1971                    [ prev_degenerate ? far_corner : prev_corner,
1972                      far_corner,
1973                      next_degenerate ? far_corner : next_corner]
1974            ) _smooth_bez_fill(
1975                      [for(row=[row0, row2, row4]) _smooth_bez_fill(row,ksides[i])],
1976                      ktop)];
1977
1978
1979// Function&Module: rounded_prism()
1980// Synopsis: Make a rounded 3d object by connecting two polygons with the same vertex count.
1981// SynTags: Geom, VNF
1982// Topics: Rounding, Offsets
1983// See Also: offset_sweep(), convex_offset_extrude(), rounded_prism(), bent_cutout_mask(), join_prism()
1984// Usage: as a module
1985//   rounded_prism(bottom, [top], [height=|h=|length=|l=], [joint_top=], [joint_bot=], [joint_sides=], [k=], [k_top=], [k_bot=], [k_sides=], [splinesteps=], [debug=], [convexity=],...) [ATTACHMENTS];
1986// Usage: as a function
1987//   vnf = rounded_prism(bottom, [top], [height=|h=|length=|l=], [joint_top=], [joint_bot=], [joint_sides=], [k=], [k_top=], [k_bot=], [k_sides=], [splinesteps=], [debug=]);
1988// Description:
1989//   Construct a generalized prism with continuous curvature rounding.  You supply the polygons for the top and bottom of the prism.  The only
1990//   limitation is that joining the edges must produce a valid polyhedron with coplanar side faces.  You specify the rounding by giving
1991//   the joint distance away from the corner for the rounding curve.  The k parameter ranges from 0 to 1 with a default of 0.5.  Larger
1992//   values give a more abrupt transition and smaller ones a more gradual transition.  If you set the value much higher
1993//   than 0.8 the curvature changes abruptly enough that though it is theoretically continuous, it may
1994//   not be continuous in practice.  A value of 0.92 is a good approximation to a circle.  If you set it very small then the transition
1995//   is so gradual that the roundover may be very small.  If you want a very smooth roundover, set the joint parameter as large as possible and
1996//   then adjust the k value down as low as gives a sufficiently large roundover.  See
1997//   [Types of Roundover](rounding.scad#subsection-types-of-roundover) for more information on continuous curvature rounding.  
1998//   .
1999//   You can specify the bottom and top polygons by giving two compatible 3d paths.  You can also give 2d paths and a height/length and the
2000//   two shapes will be offset in the z direction from each other.  The final option is to specify just the bottom along with a height/length;
2001//   in this case the top will be a copy of the bottom, offset in the z direction by the specified height.
2002//   .
2003//   You define rounding for all of the top edges, all of the bottom edges, and independently for each of the connecting side edges.
2004//   You specify rounding the rounding by giving the joint distance for where the curved section should start.  If the joint distance is 1 then
2005//   it means the curved section begins 1 unit away from the edge (in the perpendicular direction).  Typically each joint distance is a scalar
2006//   value and the rounding is symmetric around each edge.  However, you can specify a 2-vector for the joint distance to produce asymmetric
2007//   rounding which is different on the two sides of the edge.  This may be useful when one one edge in your polygon is much larger than another.
2008//   For the top and bottom you can specify negative joint distances.  If you give a scalar negative value then the roundover will flare
2009//   outward.  If you give a vector value then a negative value then if joint_top[0] is negative the shape will flare outward, but if
2010//   joint_top[1] is negative the shape will flare upward.  At least one value must be non-negative.  The same rules apply for joint_bot.
2011//   The joint_sides parameter must be entirely nonnegative.
2012//   .
2013//   If you set `debug` to true the module version will display the polyhedron even when it is invalid and it will show the bezier patches at the corners.
2014//   This can help troubleshoot problems with your parameters.  With the function form setting debug to true causes it to return [patches,vnf] where
2015//   patches is a list of the bezier control points for the corner patches.
2016//   .
2017//   Note that rounded_prism() is not well suited to rounding shapes that have already been rounded, or that have many points.
2018//   It works best when the top and bottom are polygons with well-defined corners.  When the polygons have been rounded already,
2019//   further rounding generates tiny bezier patches patches that can more easily
2020//   interfere, giving rise to an invalid polyhedron.  It's also slow because you get bezier patches for every corner in the model.  
2021//   .
2022// Arguments:
2023//   bottom = 2d or 3d path describing bottom polygon
2024//   top = 2d or 3d path describing top polygon (must be the same dimension as bottom)
2025//   ---
2026//   height/length/h/l = height of the shape when you give 2d bottom
2027//   joint_top = rounding length for top (number or 2-vector).  Default: 0
2028//   joint_bot = rounding length for bottom (number or 2-vector).  Default: 0
2029//   joint_sides = rounding length for side edges, a number/2-vector or list of them.  Default: 0
2030//   k = continuous curvature rounding parameter for all edges.  Default: 0.5
2031//   k_top = continuous curvature rounding parameter for top
2032//   k_bot = continuous curvature rounding parameter for bottom
2033//   k_bot = continuous curvature rounding parameter for bottom
2034//   splinesteps = number of segments to use for curved patches.  Default: 16
2035//   debug = turn on debug mode which displays illegal polyhedra and shows the bezier corner patches for troubleshooting purposes.  Default: False
2036//   convexity = convexity parameter for polyhedron(), only for module version.  Default: 10
2037//   anchor = Translate so anchor point is at the origin.  (module only) Default: "origin"
2038//   spin = Rotate this many degrees around Z axis after anchor.  (module only) Default: 0
2039//   orient = Vector to rotate top towards after spin  (module only)
2040//   atype = Select "hull" or "intersect" anchor types.  (module only) Default: "hull"
2041//   cp = Centerpoint for determining "intersect" anchors or centering the shape.  Determintes the base of the anchor vector.  Can be "centroid", "mean", "box" or a 3D point.  (module only) Default: "centroid"
2042// Example: Uniformly rounded pentagonal prism
2043//   rounded_prism(pentagon(3), height=3,
2044//                 joint_top=0.5, joint_bot=0.5, joint_sides=0.5);
2045// Example: Maximum possible rounding.
2046//   rounded_prism(pentagon(3), height=3,
2047//                 joint_top=1.5, joint_bot=1.5, joint_sides=1.5);
2048// Example: Decreasing k from the default of 0.5 to 0.3 gives a smoother round over which takes up more space, so it appears less rounded.
2049//   rounded_prism(pentagon(3), height=3, joint_top=1.5, joint_bot=1.5,
2050//                 joint_sides=1.5, k=0.3, splinesteps=32);
2051// Example: Increasing k from the default of 0.5 to 0.92 approximates a circular roundover, which does not have continuous curvature.  Notice the visible "edges" at the boundary of the corner and edge patches.  
2052//   rounded_prism(pentagon(3), height=3, joint_top=0.5,
2053//                 joint_bot=0.5, joint_sides=0.5, k=0.92);
2054// Example: rounding just one edge
2055//   rounded_prism(pentagon(side=3), height=3, joint_top=0.5, joint_bot=0.5,
2056//                 joint_sides=[0,0,0.5,0,0], splinesteps=16);
2057// Example: rounding all the edges differently
2058//   rounded_prism(pentagon(side=3), height=3, joint_top=0.25, joint_bot=0.5,
2059//                 joint_sides=[1.7,.5,.7,1.2,.4], splinesteps=32);
2060// Example: different k values for top, bottom and sides
2061//   rounded_prism(pentagon(side=3.0), height=3.0, joint_top=1.4, joint_bot=1.4,
2062//                 joint_sides=0.7, k_top=0.7, k_bot=0.3, k_sides=0.5, splinesteps=48);
2063// Example: flared bottom
2064//   rounded_prism(pentagon(3), height=3, joint_top=1.0,
2065//                 joint_bot=-0.5, joint_sides=0.5);
2066// Example: truncated pyramid
2067//   rounded_prism(pentagon(3), apply(scale(.7),pentagon(3)),
2068//                 height=3, joint_top=0.5, joint_bot=0.5, joint_sides=0.5);
2069// Example: top translated
2070//   rounded_prism(pentagon(3), apply(right(2),pentagon(3)),
2071//                 height=3, joint_top=0.5, joint_bot=0.5, joint_sides=0.5);
2072// Example(NORENDER): top rotated: fails due to non-coplanar side faces
2073//   rounded_prism(pentagon(3), apply(rot(45),pentagon(3)), height=3,
2074//                 joint_top=0.5, joint_bot=0.5, joint_sides=0.5);
2075// Example: skew top
2076//   rounded_prism(path3d(pentagon(3)), apply(affine3d_skew_yz(0,-20),path3d(pentagon(3),3)),
2077//                 joint_top=0.5, joint_bot=0.5, joint_sides=0.5);
2078// Example: this rotation gives coplanar sides
2079//   rounded_prism(path3d(square(4)), apply(yrot(-100)*right(2),path3d(square(4),3)),
2080//                 joint_top=0.5, joint_bot=0.5, joint_sides=0.5);
2081// Example: a shape with concave corners
2082//   M = path3d(turtle(["left", 180, "length",3,"move", "left", "move", 3, "right",
2083//                      "move", "right", "move", 4, "right", "move", 3, "right", "move", 2]));
2084//   rounded_prism(M, apply(up(3),M), joint_top=0.75, joint_bot=0.2,
2085//                 joint_sides=[.2,2.5,2,0.5,1.5,.5,2.5], splinesteps=32);
2086// Example: using debug mode to see the corner patch sizes, which may help figure out problems with interfering corners or invalid polyhedra.  The corner patches must not intersect each other.
2087//   M = path3d(turtle(["left", 180, "length",3,"move", "left", "move", 3, "right",
2088//                      "move", "right", "move", 4, "right", "move", 3, "right", "move", 2]));
2089//   rounded_prism(M, apply(up(3),M), joint_top=0.75, joint_bot=0.2,
2090//                 joint_sides=[.2,2.5,2,0.5,1.5,.5,2.5], splinesteps=16,debug=true);
2091// Example: applying transformation to the previous example
2092//   M = path3d(turtle(["left", 180, "length",3,"move", "left", "move", 3, "right",
2093//                      "move", "right", "move", 4, "right", "move", 3, "right", "move", 2]));
2094//   rounded_prism(M, apply(right(1)*scale(.75)*up(3),M), joint_top=0.5, joint_bot=0.2,
2095//                 joint_sides=[.2,1,1,0.5,1.5,.5,2], splinesteps=32);
2096// Example: this example shows most of the different types of patches that rounded_prism creates.  Note that some of the patches are close to interfering with each other across the top of the polyhedron, which would create an invalid result.
2097//   N = apply(rot(180)*yscale(.8),turtle(["length",3,"left", "move", 2, "right", 135,"move", sqrt(2), 
2098//                                         "left", "move", sqrt(2), "right", 135, "move", 2]));
2099//   rounded_prism(N, height=3, joint_bot=0.5, joint_top=1.25, joint_sides=[[1,1.75],0,.5,.5,2], debug=true);
2100// Example: This object has different scales on its different axies.  Here is the largest symmetric rounding that fits.  Note that the rounding is slightly smaller than the object dimensions because of roundoff error.
2101//   rounded_prism(square([100.1,30.1]), height=8.1, joint_top=4, joint_bot=4,
2102//                 joint_sides=15, k_sides=0.3, splinesteps=32);
2103// Example: Using asymetric rounding enables a much more rounded form:
2104//   rounded_prism(square([100.1,30.1]), height=8.1, joint_top=[15,4], joint_bot=[15,4],
2105//                 joint_sides=[[15,50],[50,15],[15,50],[50,15]], k_sides=0.3, splinesteps=32);
2106// Example: Flaring the top upward instead of outward.  The bottom has an asymmetric rounding with a small flare but a large rounding up the side.
2107//   rounded_prism(pentagon(3), height=3, joint_top=[1,-1],
2108//                 joint_bot=[-0.5,2], joint_sides=0.5);
2109// Example: Sideways polygons:
2110//   rounded_prism(apply(yrot(95),path3d(hexagon(3))), apply(yrot(95), path3d(hexagon(3),3)),
2111//                 joint_top=2, joint_bot=1, joint_sides=1);
2112// Example: Chamfer a polyhedron by setting splinesteps to 1
2113//   N = apply(rot(180)*yscale(.8),turtle(["length",3,"left", "move", 2, "right", 135,"move", sqrt(2), 
2114//                                         "left", "move", sqrt(2), "right", 135, "move", 2]));
2115//   rounded_prism(N, height=3, joint_bot=-0.3, joint_top=.4, joint_sides=[.75,0,.2,.2,.7], splinesteps=1);
2116
2117
2118module rounded_prism(bottom, top, joint_bot=0, joint_top=0, joint_sides=0, k_bot, k_top, k_sides,
2119                     k=0.5, splinesteps=16, h, length, l, height, convexity=10, debug=false,
2120                     anchor="origin",cp="centroid",spin=0, orient=UP, atype="hull")
2121{
2122  assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"");
2123  result = rounded_prism(bottom=bottom, top=top, joint_bot=joint_bot, joint_top=joint_top, joint_sides=joint_sides,
2124                         k_bot=k_bot, k_top=k_top, k_sides=k_sides, k=k, splinesteps=splinesteps, h=h, length=length, height=height, l=l,debug=debug);
2125  vnf = debug ? result[1] : result;
2126  attachable(anchor=anchor, spin=spin, orient=orient, vnf=vnf, extent=atype=="hull", cp=cp)
2127  {
2128    if (debug){
2129        vnf_polyhedron(vnf, convexity=convexity);
2130        debug_bezier_patches(result[0], showcps=true, splinesteps=splinesteps, $fn=16, showdots=false, showpatch=false);
2131    }
2132    else vnf_polyhedron(vnf,convexity=convexity);
2133    children();
2134  }
2135}
2136
2137
2138function rounded_prism(bottom, top, joint_bot=0, joint_top=0, joint_sides=0, k_bot, k_top, k_sides, k=0.5, splinesteps=16,
2139                       h, length, l, height, debug=false) =
2140   let(
2141       bottom = force_path(bottom,"bottom"),
2142       top = force_path(top,"top")
2143   )
2144   assert(is_path(bottom,[2,3]) && len(bottom)>=3, "bottom must be a 2D or 3D path")
2145   assert(is_num(k) && k>=0 && k<=1, "Curvature parameter k must be in interval [0,1]")
2146   let(
2147     N=len(bottom),
2148     k_top = default(k_top, k),
2149     k_bot = default(k_bot, k),
2150     k_sides = default(k_sides, k),
2151     height = one_defined([h,l,height,length],"height,length,l,h", dflt=undef),
2152     shapedimok = (len(bottom[0])==3 && is_path(top,3)) || (len(bottom[0])==2 && (is_undef(top) || is_path(top,2)))
2153   )
2154   assert(is_num(k_top) && k_top>=0 && k_top<=1, "Curvature parameter k_top must be in interval [0,1]")
2155   assert(is_num(k_bot) && k_bot>=0 && k_bot<=1, "Curvature parameter k_bot must be in interval [0,1]")
2156   assert(shapedimok,"bottom and top must be 2d or 3d paths with the same dimension")
2157   assert(len(bottom[0])==3 || is_num(height),"Must give height/length with 2d polygon input")
2158   let(
2159     // Determine which points are concave by making bottom 2d if necessary
2160     bot_proj = len(bottom[0])==2 ? bottom :  project_plane(select(bottom,0,2),bottom),
2161     bottom_sign = is_polygon_clockwise(bot_proj) ? 1 : -1,
2162     concave = [for(i=[0:N-1]) bottom_sign*sign(_point_left_of_line2d(select(bot_proj,i+1), select(bot_proj, i-1,i)))>0],
2163     top = is_undef(top) ? path3d(bottom,height/2) :
2164           len(top[0])==2 ? path3d(top,height/2) :
2165           top,
2166     bottom = len(bottom[0])==2 ? path3d(bottom,-height/2) : bottom,
2167     jssingleok = (is_num(joint_sides) && joint_sides >= 0) || (is_vector(joint_sides,2) && joint_sides[0]>=0 && joint_sides[1]>=0),
2168     jsvecok = is_list(joint_sides) && len(joint_sides)==N && []==[for(entry=joint_sides) if (!(is_num(entry) || is_vector(entry,2))) entry]
2169   )
2170   assert(is_num(joint_top) || is_vector(joint_top,2))
2171   assert(is_num(joint_bot) || is_vector(joint_bot,2))
2172   assert(is_num(joint_top) || (joint_top[0]>=0 ||joint_top[1]>=0), "Both entries in joint_top cannot be negative")
2173   assert(is_num(joint_bot) || (joint_bot[0]>=0 ||joint_bot[1]>=0), "Both entries in joint_bot cannot be negative")
2174   assert(jsvecok || jssingleok,
2175          str("Argument joint_sides is invalid.  All entries must be nonnegative, and it must be a number, 2-vector, or a length ",N," list those."))
2176   assert(is_num(k_sides) || is_vector(k_sides,N), str("Curvature parameter k_sides must be a number or length ",N," vector"))
2177   assert(is_coplanar(bottom))
2178   assert(is_coplanar(top))
2179   assert(!is_num(k_sides) || (k_sides>=0 && k_sides<=1), "Curvature parameter k_sides must be in interval [0,1]")
2180   let(
2181     non_coplanar=[for(i=[0:N-1]) if (!is_coplanar(concat(select(top,i,i+1), select(bottom,i,i+1)))) [i,(i+1)%N]],
2182     k_sides_vec = is_num(k_sides) ? repeat(k_sides, N) : k_sides,
2183     kbad = [for(i=[0:N-1]) if (k_sides_vec[i]<0 || k_sides_vec[i]>1) i],
2184     joint_sides_vec = jssingleok ? repeat(joint_sides,N) : joint_sides,
2185     top_collinear = [for(i=[0:N-1]) if (is_collinear(select(top,i-1,i+1))) i],
2186     bot_collinear = [for(i=[0:N-1]) if (is_collinear(select(bottom,i-1,i+1))) i]
2187   )
2188   assert(non_coplanar==[], str("Side faces are non-coplanar at edges: ",non_coplanar))
2189   assert(top_collinear==[], str("Top has collinear or duplicated points at indices: ",top_collinear))
2190   assert(bot_collinear==[], str("Bottom has collinear or duplicated points at indices: ",bot_collinear))
2191   assert(kbad==[], str("k_sides parameter outside interval [0,1] at indices: ",kbad))
2192   let(
2193     top_patch = _rp_compute_patches(top, bottom, joint_top, joint_sides_vec, k_top, k_sides_vec, concave),
2194     bot_patch = _rp_compute_patches(bottom, top, joint_bot, joint_sides_vec, k_bot, k_sides_vec, concave),
2195
2196     vertbad = [for(i=[0:N-1])
2197                   if (norm(top[i]-top_patch[i][4][2]) + norm(bottom[i]-bot_patch[i][4][2]) > norm(bottom[i]-top[i])) i],
2198     topbad = [for(i=[0:N-1])
2199                   if (norm(top_patch[i][2][4]-top_patch[i][2][2]) + norm(select(top_patch,i+1)[2][0]-select(top_patch,i+1)[2][2])
2200                  > norm(top_patch[i][2][2] - select(top_patch,i+1)[2][2]))   [i,(i+1)%N]],
2201     botbad = [for(i=[0:N-1])
2202                   if (norm(bot_patch[i][2][4]-bot_patch[i][2][2]) + norm(select(bot_patch,i+1)[2][0]-select(bot_patch,i+1)[2][2])
2203                  > norm(bot_patch[i][2][2] - select(bot_patch,i+1)[2][2]))   [i,(i+1)%N]],
2204     topinbad = [for(i=[0:N-1])
2205                   if (norm(top_patch[i][0][2]-top_patch[i][0][4]) + norm(select(top_patch,i+1)[0][0]-select(top_patch,i+1)[0][2])
2206                          > norm(top_patch[i][0][2]-select(top_patch,i+1)[0][2])) [i,(i+1)%N]],
2207     botinbad = [for(i=[0:N-1])
2208                   if (norm(bot_patch[i][0][2]-bot_patch[i][0][4]) + norm(select(bot_patch,i+1)[0][0]-select(bot_patch,i+1)[0][2])
2209                          > norm(bot_patch[i][0][2]-select(bot_patch,i+1)[0][2])) [i,(i+1)%N]]
2210   )
2211   assert(debug || vertbad==[], str("Top and bottom joint lengths are too large; they interfere with each other at vertices: ",vertbad))
2212   assert(debug || topbad==[], str("Joint lengths too large at top edges: ",topbad))
2213   assert(debug || botbad==[], str("Joint lengths too large at bottom edges: ",botbad))
2214   assert(debug || topinbad==[], str("Joint length too large on the top face at edges: ", topinbad))
2215   assert(debug || botinbad==[], str("Joint length too large on the bottom face at edges: ", botinbad))
2216   let(
2217     // Entries in the next two lists have the form [edges, vnf] where
2218     // edges is a list [leftedge, rightedge, topedge, botedge]
2219     top_samples = [for(patch=top_patch) bezier_vnf_degenerate_patch(patch,splinesteps,reverse=false,return_edges=true) ],
2220     bot_samples = [for(patch=bot_patch) bezier_vnf_degenerate_patch(patch,splinesteps,reverse=true,return_edges=true) ],
2221     leftidx=0,
2222     rightidx=1,
2223     topidx=2,
2224     botidx=3,
2225     edge_points =
2226       [for(i=[0:N-1])
2227            let(
2228               top_edge  = [ top_samples[i][1][rightidx], select(top_samples, i+1)[1][leftidx]],
2229               bot_edge  = [ select(bot_samples, i+1)[1][leftidx], bot_samples[i][1][rightidx]],
2230               vert_edge = [ bot_samples[i][1][botidx], top_samples[i][1][botidx]]
2231               )
2232               each [top_edge, bot_edge, vert_edge] ],
2233     faces = [
2234              [for(i=[0:N-1]) each top_samples[i][1][topidx]],
2235              [for(i=[N-1:-1:0]) each reverse(bot_samples[i][1][topidx])],
2236              for(i=[0:N-1]) [
2237                                 bot_patch[i][4][4],
2238                                 select(bot_patch,i+1)[4][0],
2239                                 select(top_patch,i+1)[4][0],
2240                                 top_patch[i][4][4]
2241                             ]
2242             ],
2243     top_simple = is_path_simple(project_plane(faces[0],faces[0]),closed=true),
2244     bot_simple = is_path_simple(project_plane(faces[1],faces[1]),closed=true),
2245     // verify vertical edges
2246     verify_vert =
2247       [for(i=[0:N-1],j=[0:4])
2248         let(
2249               vline = concat(select(column(top_patch[i],j),2,4),
2250                              select(column(bot_patch[i],j),2,4))
2251             )
2252         if (!is_collinear(vline)) [i,j]],
2253     //verify horiz edges
2254     verify_horiz=[for(i=[0:N-1], j=[0:4])
2255         let(
2256             hline_top = concat(select(top_patch[i][j],2,4), select(select(top_patch, i+1)[j],0,2)),
2257             hline_bot = concat(select(bot_patch[i][j],2,4), select(select(bot_patch, i+1)[j],0,2))
2258         )
2259         if (!is_collinear(hline_top) || !is_collinear(hline_bot)) [i,j]]
2260    )
2261    assert(debug || top_simple,
2262          "Roundovers interfere with each other on top face: either input is self intersecting or top joint length is too large")
2263    assert(debug || bot_simple,
2264          "Roundovers interfere with each other on bottom face: either input is self intersecting or top joint length is too large")
2265    assert(debug || (verify_vert==[] && verify_horiz==[]), "Curvature continuity failed")
2266    let( 
2267        vnf = vnf_join([ each column(top_samples,0),
2268                          each column(bot_samples,0),
2269                          for(pts=edge_points) vnf_vertex_array(pts),
2270                          debug ? vnf_from_polygons(faces) 
2271                                : vnf_triangulate(vnf_from_polygons(faces))
2272                       ])
2273    )
2274    debug ? [concat(top_patch, bot_patch), vnf] : vnf;
2275
2276
2277
2278// Converts a 2d path to a path on a cylinder at radius r
2279function _cyl_hole(r, path) =
2280    [for(point=path) cylindrical_to_xyz(concat([r],xscale(360/(2*PI*r),p=point)))];
2281
2282// Mask profile of 180 deg of a circle to round an edge
2283function _circle_mask(r) =
2284   let(eps=0.1)
2285
2286   fwd(r+.01,p=
2287   [
2288    [r+eps,0],
2289    each arc(r=r, angle=[0, 180]),
2290    [-r-eps,0],
2291    [-r-eps, r+3*eps],
2292    [r+eps, r+3*eps]
2293   ]);
2294
2295
2296// Module: bent_cutout_mask()
2297// Synopsis: Create a mask for making a round-edged cutout in a cylindrical shell.
2298// SynTags: Geom
2299// Topics: Rounding, Offsets
2300// See Also: offset_sweep(), convex_offset_extrude(), rounded_prism(), bent_cutout_mask(), join_prism()
2301// Usage:
2302//   bent_cutout_mask(r|radius, thickness, path);
2303// Description:
2304//   Creates a mask for cutting a round-edged hole out of a vertical cylindrical shell.  The specified radius
2305//   is the center radius of the cylindrical shell.  The path needs to be sampled finely enough
2306//   so that it can follow the curve of the cylinder.  The thickness may need to be slighly oversized to
2307//   handle the faceting of the cylinder.  The path is wrapped around a cylinder, keeping the
2308//   same dimensions that is has on the plane, with y axis mapping to the z axis and the x axis bending
2309//   around the curve of the cylinder.  The angular span of the path on the cylinder must be somewhat
2310//   less than 180 degrees, and the path shouldn't have closely spaced points at concave points of high curvature because
2311//   this will cause self-intersection in the mask polyhedron, resulting in CGAL failures.
2312// Arguments:
2313//   r / radius = center radius of the cylindrical shell to cut a hole in
2314//   thickness = thickness of cylindrical shell (may need to be slighly oversized)
2315//   path = 2d path that defines the hole to cut
2316// Example: The mask as long pointed ends because this was the most efficient way to close off those ends.
2317//   bent_cutout_mask(10, 1, apply(xscale(3),circle(r=3)),$fn=64);
2318// Example: An elliptical hole.  Note the thickness is slightly increased to 1.05 compared to the actual thickness of 1.
2319//   rot(-90) {
2320//     $fn=128;
2321//     difference(){
2322//       cyl(r=10.5, h=10);
2323//       cyl(r=9.5, h=11);
2324//       bent_cutout_mask(10, 1.05, apply(xscale(3),circle(r=3)),
2325//                        $fn=64);
2326//     }
2327//   }
2328// Example: An elliptical hole in a thick cylinder
2329//   rot(-90) {
2330//     $fn=128;
2331//     difference(){
2332//       cyl(r=14.5, h=15);
2333//       cyl(r=9.5, h=16);
2334//       bent_cutout_mask(12, 5.1, apply(xscale(3),circle(r=3)));
2335//     }
2336//   }
2337// Example: Complex shape example
2338//   rot(-90) {
2339//     $fn=128;
2340//     difference(){
2341//       cyl(r=10.5, h=10, $fn=128);
2342//       cyl(r=9.5, h=11, $fn=128);
2343//       bent_cutout_mask(10, 1.05,
2344//         apply(scale(3),
2345//           supershape(step=2,m1=5, n1=0.3,n2=1.7)),$fn=32);
2346//     }
2347//   }
2348// Example: this shape is invalid due to self-intersections at the inner corners
2349//   rot(-90) {
2350//     $fn=128;
2351//     difference(){
2352//       cylinder(r=10.5, h=10,center=true);
2353//       cylinder(r=9.5, h=11,center=true);
2354//       bent_cutout_mask(10, 1.05,
2355//         apply(scale(3),
2356//           supershape(step=2,m1=5, n1=0.1,n2=1.7)),$fn=32);
2357//     }
2358//   }
2359// Example: increasing the step gives a valid shape, but the shape looks terrible with so few points.
2360//   rot(-90) {
2361//     $fn=128;
2362//     difference(){
2363//       cylinder(r=10.5, h=10,center=true);
2364//       cylinder(r=9.5, h=11,center=true);
2365//       bent_cutout_mask(10, 1.05,
2366//         apply(scale(3),
2367//           supershape(step=12,m1=5, n1=0.1,n2=1.7)),$fn=32);
2368//     }
2369//   }
2370// Example: uniform resampling produces a somewhat better result, but room remains for improvement.  The lesson is that concave corners in your cutout cause trouble.  To get a very good result we need to non-uniformly sample the supershape with more points at the star tips and few points at the inner corners.
2371//   rot(-90) {
2372//     $fn=128;
2373//     difference(){
2374//       cylinder(r=10.5, h=10,center=true);
2375//       cylinder(r=9.5, h=11,center=true);
2376//       bent_cutout_mask(10, 1.05,
2377//         apply(scale(3), resample_path(
2378//              supershape(step=1,m1=5, n1=0.10,n2=1.7),
2379//              60,closed=true)),
2380//         $fn=32);
2381//     }
2382//   }
2383// Example: The cutout spans 177 degrees.  If you decrease the tube radius to 2.5 the cutout spans over 180 degrees and the model fails.
2384//   r=2.6;     // Don't make this much smaller or it will fail
2385//   rot(-90) {
2386//     $fn=128;
2387//     difference(){
2388//       tube(or=r, wall=1, h=10, anchor=CENTER);
2389//       bent_cutout_mask(r-0.5, 1.05,
2390//         apply(scale(3),
2391//           supershape(step=1,m1=5, n1=0.15,n2=1.7)),$fn=32);
2392//     }
2393//   }
2394// Example: A square hole is not as simple as it seems.  The model valid, but wrong, because the square didn't have enough samples to follow the curvature of the cylinder.
2395//   r=25;
2396//   rot(-90) {
2397//     $fn=128;
2398//     difference(){
2399//       tube(or=r, wall=2, h=35, anchor=BOT);
2400//       bent_cutout_mask(r-1, 2.1, back(5,p=square([18,18])));
2401//     }
2402//   }
2403// Example: Adding additional points fixed this problem
2404//   r=25;
2405//   rot(-90) {
2406//     $fn=128;
2407//     difference(){
2408//       tube(or=r, wall=2, h=35, anchor=BOT);
2409//       bent_cutout_mask(r-1, 2.1,
2410//         subdivide_path(back(5,p=square([18,18])),64,closed=true));
2411//     }
2412//   }
2413// Example: Rounding just the exterior corners of this star avoids the problems we had above with concave corners of the supershape, as long as we don't oversample the star.
2414//   r=25;
2415//   rot(-90) {
2416//     $fn=128;
2417//     difference(){
2418//       tube(or=r, wall=2, h=35, anchor=BOT);
2419//       bent_cutout_mask(r-1, 2.1,
2420//         apply(back(15),
2421//           subdivide_path(
2422//             round_corners(star(n=7,ir=5,or=10),
2423//                           cut=flatten(repeat([0.5,0],7)),$fn=32),
2424//             14*15,closed=true)));
2425//     }
2426//   }
2427// Example(2D): Cutting a slot in a cylinder is tricky if you want rounded corners at the top.  This slot profile has slightly angled top edges to blend into the top edge of the cylinder.
2428//   function slot(slotwidth, slotheight, slotradius) = let(
2429//       angle = 85,
2430//       slot = round_corners(
2431//           turtle([
2432//               "right",
2433//               "move", slotwidth,
2434//               "left", angle,
2435//               "move", 2*slotwidth,
2436//               "right", angle,
2437//               "move", slotheight,
2438//               "left",
2439//               "move", slotwidth,
2440//               "left",
2441//               "move", slotheight,
2442//               "right", angle,
2443//               "move", 2*slotwidth,
2444//               "left", angle,
2445//               "move", slotwidth
2446//           ]),
2447//           radius = [0,0,each repeat(slotradius,4),0,0], closed=false
2448//       )
2449//   ) apply(left(max(column(slot,0))/2)*fwd(min(column(slot,1))), slot);
2450//   stroke(slot(15,29,7));
2451// Example: A cylindrical container with rounded edges and a rounded finger slot.
2452//   function slot(slotwidth, slotheight, slotradius) = let(
2453//       angle = 85,
2454//       slot = round_corners(
2455//           turtle([
2456//               "right",
2457//               "move", slotwidth,
2458//               "left", angle,
2459//               "move", 2*slotwidth,
2460//               "right", angle,
2461//               "move", slotheight,
2462//               "left",
2463//               "move", slotwidth,
2464//               "left",
2465//               "move", slotheight,
2466//               "right", angle,
2467//               "move", 2*slotwidth,
2468//               "left", angle,
2469//               "move", slotwidth
2470//           ]),
2471//           radius = [0,0,each repeat(slotradius,4),0,0], closed=false
2472//       )
2473//   ) apply(left(max(column(slot,0))/2)*fwd(min(column(slot,1))), slot);
2474//   diam = 80;
2475//   wall = 4;
2476//   height = 40;
2477//   rot(-90) {
2478//       $fn=128;
2479//       difference(){
2480//           cyl(d=diam, rounding=wall/2, h=height, anchor=BOTTOM);
2481//           up(wall)cyl(d=diam-2*wall, rounding1=wall, rounding2=-wall/2, h=height-wall+.01, anchor=BOTTOM);
2482//           bent_cutout_mask(diam/2-wall/2, wall+.1, subdivide_path(apply(back(10),slot(15, 29, 7)),250));
2483//       }
2484//   }
2485function bent_cutout_mask(r, thickness, path, radius, convexity=10) = no_function("bent_cutout_mask");
2486module bent_cutout_mask(r, thickness, path, radius, convexity=10)
2487{
2488  no_children($children);
2489  r = get_radius(r1=r, r2=radius);
2490  dummy1=assert(is_def(r) && r>0,"Radius of the cylinder to bend around must be positive");
2491  path2 = force_path(path);
2492  dummy2=assert(is_path(path2,2),"Input path must be a 2D path")
2493         assert(r-thickness>0, "Thickness too large for radius")
2494         assert(thickness>0, "Thickness must be positive");
2495  fixpath = clockwise_polygon(path2);
2496  curvepoints = arc(d=thickness, angle = [-180,0]);
2497  profiles = [for(pt=curvepoints) _cyl_hole(r+pt.x,apply(xscale((r+pt.x)/r), offset(fixpath,delta=thickness/2+pt.y,check_valid=false,closed=true)))];
2498  pathx = column(fixpath,0);
2499  minangle = (min(pathx)-thickness/2)*360/(2*PI*r);
2500  maxangle = (max(pathx)+thickness/2)*360/(2*PI*r);
2501  mindist = (r+thickness/2)/cos((maxangle-minangle)/2);
2502  dummy3 = assert(maxangle-minangle<180,"Cutout angle span is too large.  Must be smaller than 180.");
2503  zmean = mean(column(fixpath,1));
2504  innerzero = repeat([0,0,zmean], len(fixpath));
2505  outerpt = repeat( [1.5*mindist*cos((maxangle+minangle)/2),1.5*mindist*sin((maxangle+minangle)/2),zmean], len(fixpath));
2506  default_tag("remove")
2507    vnf_polyhedron(vnf_vertex_array([innerzero, each profiles, outerpt],col_wrap=true),convexity=convexity);
2508}
2509
2510
2511
2512/*
2513
2514join_prism To Do List:
2515
2516special handling for planar joins?
2517   offset method
2518   cut, radius?
2519Access to the derivative smoothing parameter?   
2520
2521*/
2522
2523
2524
2525// Function&Module: join_prism()
2526// Synopsis: Join an arbitrary prism to a plane, sphere, cylinder or another arbitrary prism with a fillet.
2527// SynTags: Geom, VNF
2528// Topics: Rounding, Offsets
2529// See Also: offset_sweep(), convex_offset_extrude(), rounded_prism(), bent_cutout_mask(), join_prism()
2530// Usage: The two main forms with most common options
2531//   join_prism(polygon, base, length=|height=|l=|h=, fillet=, [base_T=], [scale=], [prism_end_T=], [short=], ...) [ATTACHMENTS];
2532//   join_prism(polygon, base, aux=, fillet=, [base_T=], [aux_T=], [scale=], [prism_end_T=], [short=], ...) [ATTACHMENTS];
2533// Usage: As function
2534//   vnf = join_prism( ... );
2535// Description:
2536//   This function creates a smooth fillet between one or both ends of an arbitrary prism and various other shapes: a plane, a sphere, a cylinder,
2537//   or another arbitrary prism.  The fillet is a continuous curvature rounding with a specified width/height.  This module is very general
2538//   and hence has a complex interface.  The examples below form a tutorial on how to use `join_prism` that steps
2539//   through the various options and how they affect the results.  Be sure to check the examples for help understanding how the various options work.
2540//   .
2541//   When joining between planes this function produces similar results to {{rounded_prism()}}.  This function works best when the prism
2542//   cross section is a continuous shape with a high sampling rate and without sharp corners.  If you have sharp corners you should consider
2543//   giving them a small rounding first.  When the prism cross section has concavities the fillet size will be limited by the curvature of those concavities.
2544//   In contrast, {{rounded_prism()}} works best on a prism that has fewer points.  A high sampling rate can lead to problems, and rounding
2545//   over sharp corners leads to poor results.  
2546//   .
2547//   You specify the prism by giving its cross section as a 2D path.  The cross section will always be the orthogonal cross
2548//   section of the prism.  Depending on end conditions, the ends may not be perpendicular to the
2549//   axis of the prism, but the cross section you give *is* always perpendicular to that cross section.
2550// Figure(3D,Big,NoScales,VPR=[74.6, 0, 329.7], VPT=[28.5524, 35.3006, 22.522], VPD=325.228): The layout and terminology used by `join_prism`.  The "base object" is centered on the origin.  The "auxiliary object" (if present) is some distance away so there is room for the "joiner prism" to connect the two objects.  The blue line is the axis of the jointer prism.  It will be at the origin of the shape you supply for defining that prism.  The "root" point of the joiner prism is the point where the prism axis intersects the base.  The prism end point is where the prism axis intersects the auxiliary object.  If you don't give an auxiliary object then the prism end point is distance `length` along the axis from the root.  
2551//   aT = right(-10)*back(0)*up(75)*xrot(-35)*zrot(75);
2552//   br = 17;
2553//   ar = 15;
2554//   xcyl(r=br, l=50, circum=true, $fn=64);
2555//   multmatrix(aT)right(15)xcyl(r=ar,circum=true,l=50,$fn=64);
2556//   %join_prism(circle(r=10), base = "cyl", base_r=br, aux="cyl", aux_r=ar, aux_T=aT,fillet=3);
2557//   root = [-2.26667, 0, 17];
2558//   rback = [15,0,25];
2559//   endpt =  [-7.55915, 0, 56.6937];
2560//   endback = [10,0,55];
2561//   stroke([root,endpt],
2562//          width=1,endcap_width=3,endcaps="dot",endcap_color="red",color="blue",$fn=16);
2563//   stroke(move(3*unit(rback-root), [rback,root]), endcap2="arrow2",width=1/2,$fn=16,color="black");
2564//   down(0)right(4)color("black")move(rback)rot($vpr)text("prism root point",size=4);
2565//   stroke(move(3*unit(endback-endpt), [endback,endpt]), endcap2="arrow2", width=1/2, $fn=16, color="black");
2566//   down(2)right(4)color("black")move(endback)rot($vpr)text("prism end point",size=4);
2567//   right(4)move(-20*[1,1])color("black")rot($vpr)text("base",size=8);
2568//   up(83)right(-10)move(-20*[1,1])color("black")rot($vpr)text("aux",size=8);
2569//   aend=[-13,13,30];
2570//   ast=aend+10*[-1,1,0];
2571//   stroke([ast,aend],endcap2="arrow2", width=1/2, color="black");
2572//   left(2)move(ast)rot($vpr)color("black")text("joiner prism",size=5,anchor=RIGHT);
2573// Continues:
2574//   You must include a base ("plane", "sphere", "cylinder", "cyl"), or a polygon describing the cross section of a base prism.  If you specify a
2575//   sphere or cylinder you must give `base_r` or `base_d` to specify the radius or diameter of the base object.  If you choose a cylinder or a polygonal
2576//   prism then the base object appears aligned with the X axis.  In the case of the planar base, the
2577//   joining prism will have one end of its axis at the origin.  As shown above, the point where the joining prism attaches to its base is the "root" of the prism.
2578//   If you use some other base shape, the root will be adjusted so that it is on the boundary of your shape.  This happens by finding the intersection
2579//   of the joiner prisms's axis and using that as the root.  By default the prism axis is parallel to the Z axis.  
2580//   .
2581//   You may give `base_T`, a rotation operator that will be applied to the base.  This is
2582//   useful to tilt a planar or cylindrical base.  The `base_T` operator must be an origin-centered rotation like yrot(25).  
2583//   .
2584//   You may optionally specify an auxiliary shape.  When you do this, the joining prism connects the base to the auxiliary shape,
2585//   which must be one of "none", "plane", "sphere", "cyl", or "cylinder".  You can also set it to a polygon to create an arbitrary
2586//   prism for the auxiliary shape.  As is the case for the base, auxiliary cylinders and prisms appear oriented along the X axis.  
2587//   For a cylinder or sphere you must use `aux_r` or `aux_d` to specify the radius or diameter.
2588//   The auxiliary shape appears centered on the origin and will most likely be invalid as an end location unless you translate it to a position
2589//   away from the base object.  The `aux_T` operator operates on the auxiliary object, and unlike `base_T` can be a rotation that includes translation
2590//   operations (or is a non-centered rotation).
2591//   .
2592//   When you specify an auxiliary object, the joiner prism axis is initially the line connecting the origin (the base center point) to the auxiliary
2593//   object center point.  The joiner prism end point is determined analogously to how the root is determined, by intersecting the joiner
2594//   prism axis with the auxiliary object.  Note that this means that if `aux_T` is a rotation it will change the joiner prism root, because
2595//   the rotated prism axis will intersect the base in a different location.  If you do not give an auxiliary object then you must give
2596//   the length/height parameter to specify the prism length.  This gives the length of the prism measured from the root to the end point.
2597//   Note that the joint with a curved base may significantly extend the length of the joiner prism: it's total length will often be larger than
2598//   the length you request.  
2599//   .
2600//   For the cylinder and spherical objects you may with to joint a prism to the concave surface.  You can do this by setting a negative
2601//   radius for the base or auxiliary object.  When `base_r` is negative, and the joiner prism axis is vertical, the prism root will be **below** the
2602//   XY plane.  In this case it is actually possible to use the same object for base and aux and you can get a joiner prism that crosses a cylindrical
2603//   or spherical hole.
2604//   .
2605//   When placing prisms inside a hole, an ambiguity can arise about how to identify the root and end of the joiner prism.  The prism axis will have
2606//   two intersections with a cylinder and both are potentially valid roots.  When the auxiliary object is entirely inside the hole, or the auxiliary
2607//   object is a sphere or cylinder with negative radius that intersections the base, both prism directions produce a valid
2608//   joiner prism that meets the hole's concave surface, so two valid interpretations exist.  By default, the longer prism will be returned.
2609//   You can select the shorter prism by setting `short=true`.  If you specify `short=true` when the base has a negative radius, but only one valid
2610//   prism exists, you'll get an error, but it won't clearly identify that a bogus `short=true` was the real cause.  
2611//   .
2612//   You can also alter your prism by using the `prism_end_T` operator which applies to the end point of the prism.  It does not effect
2613//   the root  of the prism.  The `prism_end_T` operator is applied in a coordinate system where the root of the
2614//   prism is the origin, so if you set it to a rotation the prism base will stay rooted at the same location and the prism will rotate 
2615//   in the specified fashion.  After `prism_end_T` is applied, the prism axis will probably be different and the resulting new end point will
2616//   probably not be on the auxiliary object, or it will have changed the length of the prism.  Therefore, the end point is recalculated
2617//   to achieve the specified length (if aux is "none") or to contact the auxiliary object, if you have specified one.  This means, for example,
2618//   that setting `prism_end_T` to a scale operation won't change the result because it doesn't alter the prism axis.  
2619//   .
2620//   The size of the fillets is determined by the fillet, `fillet_base`, and `fillet_aux` parameters.  The fillet parameter will control both
2621//   ends of the prism, or you can set the ends independently.  The fillets must be nonnegative except when the prism joints a plane.
2622//   In this case a negative fillet gives a roundover.  In the case of no auxiliary object you can use `round_end` to round over the planar
2623//   far end of the joiner prism.  By default, the fillet is constructed using a method that produces a fillet with a uniform height along
2624//   the joiner prism.  This can be limiting when connectijng to objects with high curvature, so you can turn it off using the `uniform` option.
2625//   See the figures below for an explanation of the uniform and non-uniform filleting methods.  
2626//   .
2627//   The overlap is a potentially tricky parameter.  It specifies how much extra material to
2628//   create underneath the filleted prism so it overlaps the object that it joins to, ensuring valid unions.
2629//   For joins to convex objects you can choose a small value, but when joining to a concave object the overlap may need to be
2630//   very large to ensure that the base of the joiner prism is well-behaved.  In such cases you may need to use an intersection
2631//   remove excess base.
2632// Figure(2D,Med,NoAxes): Uniform fillet method.  This image shows how the fillet we construct a uniform fillet.  The pictures shows the cross section that is perpendicular to the prism.  The blue curve represents the base object surface.  The vertical line is the side of the prism.  To construct a fillet we travel along the surface of the base, following the curve, until we have moved the fillet length, `a`.  This defines the point `u`.  We then construct a tangent line to the base and find its intersection, `v`, with the prism.  Note that if the base is steeply curved, this tangent may fail to intersect, and the algorithm will fail with an error because `v` does not exist.  Finally we locate `w` to be distance `a` above the point where the prism intersects the base object.  The fillet is defined by the `[u,v,w]` triple and is shown in red.  Note that with this method, the fillet is always height `a` above the base, so it makes a uniform curve parallel to the base object.  However, when the base curvature is more extreme, point `v` may end up above point `w`, resulting in an invalid configuration.  It also happens that point `v`, while below `w`, is very close to `w`, so the resulting fillet has an abrupt angle near `w` instead of a smooth transition.  
2633//   R=60;
2634//   base = R*[cos(70),sin(70)];
2635//   end = R*[cos(45),sin(45)];
2636//   tang = [-sin(45),cos(45)];
2637//   isect = line_intersection([base,back(1,base)], [end,end+tang]);
2638//   toppt = base+[0,2*PI*R*25/360];
2639//   bez = _smooth_bez_fill([toppt, isect,end], 0.8);
2640//   color("red")
2641//     stroke(bezier_curve(bez,30,endpoint=true), width=.5);
2642//   color("blue"){
2643//      stroke(arc(n=50,angle=[35,80], r=R), width=1);
2644//      stroke([base, back(40,base)]);
2645//      move(R*[cos(35),sin(35)])text("Base", size=5,anchor=BACK);
2646//      back(1)move(base+[0,40]) text("Prism", size=5, anchor=FWD);
2647//   }
2648//   color([.3,1,.3]){
2649//     right(2)move(toppt)text("w",size=5);
2650//     right(2)move(end)text("u",size=5);
2651//     stroke([isect+[1,1/4], isect+[16,4]], width=.5, endcap1="arrow2");
2652//     move([16.5,3])move(isect)text("v",size=5);
2653//     stroke([end,isect],dots=true);
2654//     stroke([isect,toppt], dots=true);
2655//   }
2656//   color("black")  {
2657//      stroke(arc(n=50, angle=[45,70], r=R-3), color="black", width=.6, endcaps="arrow2");
2658//       move( (R-10)*[cos(57.5),sin(57.5)]) text("a",size=5);
2659//      left(3)move( base+[0,PI*R*25/360]) text("a", size=5,anchor=RIGHT);
2660//      left(2)stroke( [base, toppt],endcaps="arrow2",width=.6);
2661//   }
2662// Figure(2D,Med,NoAxes): Non-Uniform fillet method.  This method differs because point `w` is found by moving the fillet distance `a` starting at the intersection point `v` instead of at the base surface.  This means that the `[u,v,w]` triple is always in the correct order to produce a valid fillet.  However, the height of the fillet above the surface will vary.  When the base concave, point `v` is below the surface of the base, which in more extreme cases can produce a fillet that goes below the base surface.  The uniform method is less likely to produce this kind of result.  When the base surface is a plane, the uniform and non-uniform methods are identical.
2663//   R=60;
2664//   base = R*[cos(70),sin(70)];
2665//   end = R*[cos(45),sin(45)];
2666//   tang = [-sin(45),cos(45)];
2667//   isect = line_intersection([base,back(1,base)], [end,end+tang]);
2668//   toppt = isect+[0,2*PI*R*25/360];
2669//   bez = _smooth_bez_fill([toppt, isect,end], 0.8);
2670//   color("red")stroke(bezier_curve(bez,30,endpoint=true), width=.5);
2671//   color("blue"){
2672//      stroke(arc(n=50,angle=[35,80], r=R), width=1);
2673//      stroke([base, back(40,base)]);
2674//      move(R*[cos(35),sin(35)])text("Base", size=5,anchor=BACK);
2675//      back(1)move(base+[0,40]) text("Prism", size=5, anchor=FWD);
2676//   }
2677//   color([.3,1,.3]){
2678//     right(2)move(toppt)text("w",size=5);
2679//     right(2)move(end)text("u",size=5);
2680//     stroke([isect+[1,1/4], isect+[16,4]], width=.5, endcap1="arrow2");
2681//     move([16.5,3])move(isect)text("v",size=5);
2682//     stroke([end,isect],dots=true);
2683//     stroke([isect,toppt], dots=true);
2684//   }
2685//   color("black")  {
2686//      stroke(arc(n=50, angle=[45,70], r=R-3), width=.6, endcaps="arrow2");
2687//      move( (R-10)*[cos(57.5),sin(57.5)]) text("a",size=5);
2688//      left(3)move( (isect+toppt)/2) text("a", size=5,anchor=RIGHT);
2689//      left(2)stroke( [isect, toppt],endcaps="arrow2",width=.6);
2690//   }
2691// Arguments:
2692//   polygon = polygon giving prism cross section
2693//   base = string specifying base object to join to ("plane","cyl","cylinder", "sphere") or a point list to use an arbitrary prism as the base.
2694//   ---
2695//   length / height / l / h = length/height of prism if aux=="none"
2696//   scale = scale factor for prism far end.  Default: 1
2697//   prism_end_T = root-centered arbitrary transform to apply to the prism's far point.  Default: IDENT
2698//   short = flip prism direction for concave sphere or cylinder base, when there are two valid prisms.  Default: false
2699//   base_T = origin-centered rotation operator to apply to the base
2700//   base_r / base_d = base radius or diameter if you picked sphere or cylinder
2701//   aux = string specifying auxilary object to connect to ("none", "plane", "cyl", "cylinder", or "sphere") or a point list to use an arbitrary prism.  Default: "none"
2702//   aux_T = rotation operator that may include translation when aux is not "none" to apply to aux
2703//   aux_r / aux_d = radius or diameter of auxiliary object if you picked sphere or cylinder
2704//   n = number of segments in the fillet at both ends.  Default: 15
2705//   base_n = number of segments to use in fillet at the base
2706//   aux_n = number of segments to use in fillet at the aux object
2707//   end_n = number of segments to use in roundover at the end of prism with no aux object
2708//   fillet = fillet for both ends of the prism (if applicable)  Must be nonnegative except for joiner prisms with planar ends
2709//   base_fillet = fillet for base end of prism 
2710//   aux_fillet = fillet for joint with aux object
2711//   end_round = roundover of end of prism with no aux object 
2712//   overlap = amount of overlap of prism fillet into objects at both ends.  Default: 1 for normal fillets, 0 for negative fillets and roundovers
2713//   base_overlap = amount of overlap of prism fillet into the base object
2714//   aux_overlap = amount of overlap of the prism fillet into aux object
2715//   k = fillet curvature parameter for both ends of prism
2716//   base_k = fillet curvature parameter for base end of prism
2717//   end_k / aux_k = fillet curvature parameter for end of prism where the aux object is
2718//   uniform = set to false to get non-uniform filleting at both ends (see Figures 2-3).  Default: true
2719//   base_uniform = set to false to get non-uniform filleting at the base
2720//   aux_uniform = set to false to get non-uniform filleting at the auxiliary object
2721//   debug = set to true to allow return of various cases where self-intersection was detected
2722//   anchor = Translate so anchor point is at the origin.  (module only) Default: "origin"
2723//   spin = Rotate this many degrees around Z axis after anchor.  (module only) Default: 0
2724//   orient = Vector to rotate top towards after spin  (module only)
2725//   atype = Select "hull" or "intersect" anchor types.  (module only) Default: "hull"
2726//   cp = Centerpoint for determining "intersect" anchors or centering the shape.  Determintes the base of the anchor vector.  Can be "centroid", "mean", "box" or a 3D point.  (module only) Default: "centroid"
2727// Extra Anchors:
2728//   "root" = Root point of the joiner prism, pointing out in the direction of the prism axis
2729//   "end" = End point of the joiner prism, pointing out in the direction of the prism axis
2730// Example(3D,NoScales): Here is the simplest case, a circular prism with a specified length standing vertically on a plane.  
2731//   join_prism(circle(r=15,$fn=60),base="plane",
2732//              length=18, fillet=3, n=12);
2733//   cube([50,50,5],anchor=TOP);
2734// Example(3D,NoScales): Here we substitute an abitrary prism. 
2735//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2736//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2737//   join_prism(flower,base="plane",length=18, fillet=3, n=12);
2738//   cube([50,50,5],anchor=TOP);
2739// Example(3D,NoScales): Here we apply a rotation of the prism, using prism_end_T, which rotates around the prism root.  Note that aux_T will rotate around the origin, which is the same when the prism is joined to a plane.  
2740//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2741//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2742//   join_prism(flower,base="plane",length=18, fillet=3,
2743//              n=12, prism_end_T=yrot(25));
2744//   cube([50,50,5],anchor=TOP);
2745// Example(3D,NoScales): We can use `end_round` to get a roundover
2746//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2747//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2748//   join_prism(flower,base="plane",length=18, fillet=3,
2749//              n=12, prism_end_T=yrot(25), end_round=4);
2750//   cube([50,50,5],anchor=TOP);
2751// Example(3D,NoScales): We can tilt the base plane by applying a base rotation.  Note that because we did not tilt the prism, it still points upwards.  
2752//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2753//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2754//   join_prism(flower,base="plane",length=18, fillet=3,
2755//              n=12, base_T=yrot(25));
2756//   yrot(25)cube([50,50,5],anchor=TOP);
2757// Example(3D,NoScales): Next consider attaching the prism to a sphere.  You must use a circumscribed sphere to avoid a lip or gap between the sphere and prism.  Note that the prism is attached to the sphere's boundary above the origin and projects by the specified length away from the attachment point.  
2758//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2759//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2760//   join_prism(flower,base="sphere",base_r=30, length=18,
2761//              fillet=3, n=12);
2762//   spheroid(r=30,circum=true,$fn=64);
2763// Example(3D,NoScales): Rotating using the prism_end_T option rotates around the attachment point.  Note that if you rotate too far, some points of the prism will miss the sphere, which is an error.  
2764//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2765//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2766//   join_prism(flower,base="sphere",base_r=30, length=18,
2767//              fillet=3, n=12, prism_end_T=yrot(-15));
2768//   spheroid(r=30,circum=true,$fn=64);
2769// Example(3D,NoScales): Rotating using the aux_T option rotates around the origin.  You could get the same result in this case by rotating the whole model.  
2770//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2771//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2772//   join_prism(flower,base="sphere",base_r=30, length=18,
2773//              fillet=3, n=12, aux_T=yrot(-45));
2774//   spheroid(r=30,circum=true,$fn=64);
2775// Example(3D,NoScales): The origin in the prism cross section always aligns with the origin of the object you attach to.  If you want to attach off center, then shift your prism cross section.  If you shift too far so that parts of the prism miss the base object then you will get an error.  
2776//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2777//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2778//   join_prism(right(10,flower),base="sphere",base_r=30,
2779//              length=18, fillet=3, n=12);
2780//   spheroid(r=30,circum=true,$fn=64);
2781// Example(3D,NoScales): The third available base shape is the cylinder.  
2782//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2783//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2784//   join_prism(flower,base="cylinder",base_r=30,
2785//              length=18, fillet=4, n=12); 
2786//   xcyl(r=30,l=75,circum=true,$fn=64);
2787// Example(3D,NoScales): You can rotate the cylinder the same way we rotated the plane.
2788//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2789//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2790//   join_prism(flower,base="cylinder",base_r=30, length=18,
2791//              fillet=4, n=12, base_T=zrot(33)); 
2792//   zrot(33)xcyl(r=30,l=75,circum=true,$fn=64);
2793// Example(3D,NoScales): And you can rotate the prism around its attachment point with prism_end_T
2794//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2795//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2796//   join_prism(flower,base="cylinder",base_r=30, length=18,
2797//              fillet=4, n=12, prism_end_T=yrot(22));
2798//   xcyl(r=30,l=75,circum=true,$fn=64);
2799// Example(3D,NoScales): Or you can rotate the prism around the origin with aux_T
2800//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2801//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2802//   join_prism(flower,base="cylinder",base_r=30, length=18,
2803//              fillet=4, n=12, aux_T=xrot(22));
2804//   xcyl(r=30,l=75,circum=true,$fn=64);
2805// Example(3D,NoScales): Here's a prism where the scale changes
2806//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2807//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2808//   join_prism(flower,base="cylinder",base_r=30, length=18,
2809//              fillet=4, n=12,scale=.5);
2810//   xcyl(r=30,l=75,circum=true,$fn=64);
2811// Example(3D,NoScales,VPD=190,VPR=[61.3,0,69.1],VPT=[41.8956,-9.49649,4.896]): Giving a negative radius attaches to the inside of a sphere or cylinder.  Note you want the inscribed cylinder for the inner wall.  
2812//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2813//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2814//   join_prism(flower,base="cylinder",base_r=-30, length=18,
2815//              fillet=4, n=12);
2816//   bottom_half(z=-10)
2817//     tube(ir=30,wall=3,l=74,$fn=64,orient=RIGHT,anchor=CENTER);
2818// Example(3D,NoScales,VPD=140,VPR=[72.5,0,73.3],VPT=[40.961,-19.8319,-3.03302]): A hidden problem lurks with concave attachments.  The bottom of the prism does not follow the curvature of the base.  Here you can see a gap.  In some cases you can create a self-intersection in the prism.  
2819//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2820//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2821//   left_half(){
2822//     join_prism(flower,base="cylinder",base_r=-30, length=18,
2823//                fillet=4, n=12);
2824//     bottom_half(z=-10)
2825//       tube(ir=30,wall=3,l=74,$fn=64,orient=RIGHT,anchor=CENTER);
2826//   }
2827// Example(3D,NoScales,VPD=140,VPR=[72.5,0,73.3],VPT=[40.961,-19.8319,-3.03302]): The solution to both problems is to increase the overlap parameter, but you may then have excess base that must be differenced or intersected away.  In this case, an overlap of 2 is sufficient to eliminate the hole.  
2828//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2829//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2830//   left_half(){
2831//     join_prism(flower,base="cylinder",base_r=-30, length=18,
2832//                fillet=4, n=12, overlap=2);     
2833//     bottom_half(z=-10)
2834//       tube(ir=30,wall=3,l=74,$fn=64,orient=RIGHT,anchor=CENTER);
2835//   }
2836// Example(3D,NoScales,VPD=126,VPR=[76.7,0,111.1],VPT=[6.99093,2.52831,-14.8461]): Here is an example with a spherical base.  This overlap is near the minimum required to eliminate the gap, but it creates a large excess structure around the base of the prism.  
2837//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2838//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2839//   left_half(){
2840//     join_prism(flower,base="sphere",base_r=-30, length=18,
2841//                fillet=4, n=12, overlap=7);
2842//     bottom_half(z=-10) difference(){
2843//       sphere(r=33,$fn=16);
2844//       sphere(r=30,$fn=64);
2845//     }
2846//   }
2847// Example(3D,NoScales,VPD=126,VPR=[55,0,25],VPT=[1.23541,-1.80334,-16.9789]): Here is an example with a spherical base.  This overlap is near the minimum required to eliminate the gap, but it creates a large excess structure around the base of the prism.  
2848//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2849//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2850//   intersection(){
2851//     union(){
2852//       join_prism(flower,base="sphere",base_r=-30, length=18, 
2853//                  fillet=4, n=12, overlap=7);
2854//       difference(){
2855//         down(18)cuboid([68,68,30],anchor=TOP);
2856//         sphere(r=30,$fn=64);
2857//       }
2858//     }
2859//     sphere(r=33,$fn=16);
2860//   }
2861// Example(3D,NoScales,VPD=126,VPR=[55,0,25],VPT=[1.23541,-1.80334,-16.9789]): As before, rotating with aux_T rotates around the origin. 
2862//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2863//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2864//   intersection(){
2865//     union(){
2866//       join_prism(flower,base="sphere",base_r=-30, length=18,
2867//                  fillet=4, n=12, overlap=7, aux_T=yrot(13));
2868//       difference(){
2869//         down(18)cuboid([68,68,30],anchor=TOP);
2870//         sphere(r=30,$fn=64);
2871//       }
2872//     }
2873//     sphere(r=33,$fn=16);
2874//   }
2875// Example(3D,NoScales,VPD=102.06,VPR=[55,0,25],VPT=[3.96744,-2.80884,-19.9293]): Rotating with prism_end_T rotates around the attachment point.  We shrank the prism to allow a significant rotation.
2876//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2877//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
2878//   intersection(){
2879//     union(){
2880//       join_prism(scale(.5,flower),base="sphere",base_r=-30,
2881//                  length=18, fillet=2, n=12, overlap=7,
2882//                  prism_end_T=yrot(25));
2883//       difference(){
2884//         down(23)cuboid([68,68,30],anchor=TOP);
2885//         sphere(r=30,$fn=64);
2886//       }
2887//     }
2888//     sphere(r=33,$fn=16);
2889//   }
2890// Example(3D,NoScales,VPR=[65.5,0,105.3],VPT=[8.36329,13.0211,9.98397],VPD=237.091): You can create a prism that crosses the inside of a cylinder or sphere by giving the same negative radius twice and leaving both objects with the same center, as shown here.  
2891//   left_half(x=7){
2892//     join_prism(circle(r=15),base="cylinder",base_r=-30, n=12,
2893//                aux="cylinder", aux_r=-30, fillet=8, overlap=3);
2894//     tube(ir=30,wall=5,l=74,$fn=64,orient=RIGHT,anchor=CENTER);     
2895//   }
2896// Example(3D,NoScales,VPR=[65.5,0,105.3],VPT=[8.36329,13.0211,9.98397],VPD=237.091): Here's a similar example with a plane for the auxiliary object.  Note that we observe the 1 unit overlap on the top surface.  
2897//   left_half(x=7){
2898//     join_prism(circle(r=15),base="cylinder",base_r=-30,
2899//                aux="plane", fillet=8, n=12, overlap=3);
2900//     tube(ir=30,wall=5,l=74,$fn=64,orient=RIGHT,anchor=CENTER);     
2901//   }
2902// Example(3D,NoScales,VPR=[65.5,0,105.3],VPT=[8.36329,13.0211,9.98397],VPD=237.091): We have tweaked the previous example just slightly by lowering the height of the plane.  The result is a bit of a surprise:  the prism flips upside down!  This happens because there is an ambiguity in creating a prism between a plane and the inside of the cylinder.  By default, this ambiguity is resolved by choosing the longer prism.  
2903//   left_half(x=7){
2904//     join_prism(circle(r=15),base="cylinder",base_r=-30, n=12,
2905//                aux="plane", aux_T=down(5), fillet=8, overlap=3);
2906//     tube(ir=30,wall=5,l=74,$fn=64,orient=RIGHT,anchor=CENTER);     
2907//   }
2908// Example(3D,NoScales,VPR=[65.5,0,105.3],VPT=[8.36329,13.0211,9.98397],VPD=237.091): Adding `short=true` resolves the ambiguity of which prism to construct in the other way, by choosing the shorter option.  
2909//   left_half(x=7){
2910//     join_prism(circle(r=15),base="cylinder",base_r=-30,
2911//                aux="plane", aux_T=down(5), fillet=8,
2912//                n=12, overlap=3, short=true);
2913//     tube(ir=30,wall=5,l=74,$fn=64,orient=RIGHT,anchor=CENTER);
2914//   }
2915// Example(3D,NoScales,VPR=[85.1,0,107.4],VPT=[8.36329,13.0211,9.98397],VPD=237.091): The problem does not arise in this case because the auxiliary object only allows one possible way to make the connection. 
2916//   left_half(x=7){
2917//     join_prism(circle(r=15),base="cylinder",base_r=-30,
2918//                aux="cylinder", aux_r=30, aux_T=up(20),
2919//                fillet=8, n=12, overlap=3);
2920//     tube(ir=30,wall=5,l=74,$fn=64,orient=RIGHT,anchor=CENTER);
2921//     up(20)xcyl(r=30,l=74,$fn=64);
2922//   }
2923// Example(3D,NoScales,VPT=[-1.23129,-3.61202,-0.249883],VPR=[87.9,0,295.7],VPD=213.382): When the aux cylinder is inside the base cylinder we can select the two options, shown here as red for the default and blue for the `short=true` case. 
2924//   color("red")
2925//     join_prism(circle(r=5),base="cylinder",base_r=-30, 
2926//                aux="cyl",aux_r=10, aux_T=up(12), fillet=4,
2927//                 n=12, overlap=3, short=false);
2928//   color("blue")
2929//     join_prism(circle(r=5),base="cylinder",base_r=-30, 
2930//                aux="cyl",aux_r=10, aux_T=up(12), fillet=4,
2931//                n=12, overlap=3, short=true);
2932//   tube(ir=30,wall=5,$fn=64,l=18,orient=RIGHT,anchor=CENTER);
2933//   up(12)xcyl(r=10, circum=true, l=18);
2934// Example(3D,NoScales,VPR=[94.9,0,106.7],VPT=[4.34503,1.48579,-2.32228],VPD=237.091): The same thing is true when you use a negative radius for the aux cylinder. This is the default long case.  
2935//   join_prism(circle(r=5,$fn=64),base="cylinder",base_r=-30, 
2936//              aux="cyl",aux_r=-10, aux_T=up(12), fillet=4,
2937//              n=12, overlap=3, short=false);
2938//   tube(ir=30,wall=5,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2939//   up(12) top_half()
2940//      tube(ir=10,wall=4,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2941// Example(3D,NoScales,VPR=[94.9,0,106.7],VPT=[4.34503,1.48579,-2.32228],VPD=237.091): And here is the short case:
2942//   join_prism(circle(r=5,$fn=64),base="cylinder",base_r=-30, 
2943//              aux="cyl",aux_r=-10, aux_T=up(12), fillet=4,
2944//              n=12, overlap=3, short=true);
2945//   tube(ir=30,l=24,wall=5,$fn=64,orient=RIGHT,anchor=CENTER);
2946//   up(12) bottom_half()
2947//     tube(ir=10,wall=4,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2948// Example(3D,NoScales,VPR=[94.9,0,106.7],VPT=[0.138465,6.78002,24.2731],VPD=325.228): Another example where the cylinders overlap, with the long case here:
2949//   auxT=up(40);
2950//   join_prism(circle(r=5,$fn=64),base="cylinder",base_r=-30, 
2951//              aux="cyl",aux_r=-40, aux_T=auxT, fillet=4,
2952//              n=12, overlap=3, short=false);
2953//   tube(ir=30,wall=4,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2954//   multmatrix(auxT)
2955//     tube(ir=40,wall=4,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2956// Example(3D,NoScales,VPR=[94.9,0,106.7],VPT=[0.138465,6.78002,24.2731],VPD=325.228): And the short case:
2957//   auxT=up(40);
2958//   join_prism(circle(r=5,$fn=64),base="cylinder",base_r=-30, 
2959//              aux="cyl",aux_r=-40, aux_T=auxT, fillet=4,
2960//              n=12, overlap=3, short=true);
2961//   tube(ir=30,wall=4,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2962//   multmatrix(auxT)
2963//     tube(ir=40,wall=4,l=24,$fn=64,orient=RIGHT,anchor=CENTER);
2964// Example(3D,NoScales): Many of the preceeding examples feature a prism with a concave shape cross section.  Concave regions can limit the amount of rounding that is possible.  This occurs because the algorithm is not able to handle a fillet that intersects itself.  Fillets on a convex prism always grow larger as they move away from the prism, so they cannot self intersect.  This means that you can make the fillet as big as will fit on the base shape.  The fillet will fail to fit if the tangent plane to the base at the fillet distance from the prism fails to intersect the prism.  Here is an extreme example, almost the largest possible fillet to the convex elliptical convex prism.  
2965//   ellipse = ellipse([17,10],$fn=164);  
2966//   join_prism(ellipse,base="sphere",base_r=30, length=18,
2967//              fillet=18, n=25, overlap=1);
2968//   spheroid(r=30,circum=true, $fn=96);
2969// Example(3D,NoScales): This example shows a failed rounding attempt where the result is self-intersecting.  Using the `debug=true` option makes it possible to view the result to understand what went wrong.  Note that the concave corners have a crease where the fillet crosses itself.  The error message will advise you to decrease the size of the fillet.  You can also fix the problem by making your concave curves shallower.  
2970//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
2971//             (15+2.5*sin(6*theta))*[cos(theta),sin(theta)]];
2972//   join_prism(flower,base="cylinder",base_r=30, length=18,
2973//              fillet=6, n=12, debug=true); 
2974// Example(3D,NoScales): Your prism needs to be finely sampled enough to follow the contour of the base you are attaching it to.  If it is not, you get a result like this.  The fillet joints the prism smoothly, but makes a poor transition to the sphere. 
2975//   sq = rect(15);
2976//   join_prism(sq, base="sphere", base_r=25,
2977//              length=18, fillet=4, n=12);
2978//   spheroid(r=25, circum=true, $fn=96);
2979// Example(3D,NoScales): To fix the problem, you must subdivide the polygon that defines the prism.  But note that the join_prism method works poorly at sharp corners.
2980//   sq = subdivide_path(rect(15),n=64);
2981//   join_prism(sq, base="sphere", base_r=25,
2982//              length=18, fillet=4, n=12);
2983//   spheroid(r=25, circum=true,$fn=96);
2984// Example(3D,NoScales): In the previous example, a small rounding of the prism corners produces a nicer result.
2985//   sq = subdivide_path(
2986//          round_corners(rect(15),cut=.5,$fn=32),
2987//          n=128);
2988//   join_prism(sq, base="sphere", base_r=25,
2989//              length=18, fillet=4, n=12);
2990//   spheroid(r=25, circum=true,$fn=96);
2991// Example(3D,NoScales): The final option for specifying the base is to use an arbitrary prism, specified by a polygon.  Note that the base prism is oriented to the RIGHT, so the attached prism remains Z oriented.  
2992//   ellipse = ellipse([17,10],$fn=164);  
2993//   join_prism(zrot(90,ellipse), base=2*ellipse, length=19,
2994//              fillet=4, n=12);
2995//   linear_sweep(2*ellipse,height=60, center=true, orient=RIGHT);
2996// Example(3D,NoScales): As usual, you can rotate around the attachment point using prism_end_T. 
2997//   ellipse = ellipse([17,10],$fn=164);  
2998//   join_prism(zrot(90,ellipse), base=2*ellipse, length=19,
2999//              fillet=4, n=12, prism_end_T=yrot(22));
3000//   linear_sweep(2*ellipse,height=60, center=true, orient=RIGHT);
3001// Example(3D,NoScales): And you can rotate around the origin with aux_T.
3002//   ellipse = ellipse([17,10],$fn=164);  
3003//   join_prism(zrot(90,ellipse), base=2*ellipse, length=19,
3004//              fillet=4, n=12, aux_T=yrot(22));
3005//   linear_sweep(2*ellipse,height=60, center=true, orient=RIGHT);
3006// Example(3D,NoScales): The base prism can be a more complicated shape.
3007//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3008//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3009//   join_prism(flower,base=1.4*flower, fillet=3,
3010//              n=15, length=20);
3011//   linear_sweep(1.4*flower,height=60,center=true,
3012//                convexity=10,orient=RIGHT);
3013// Example(3D,NoScales): Here's an example with both prism_end_T and aux_T 
3014//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3015//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3016//   join_prism(flower,base=1.4*flower, length=20,
3017//              prism_end_T=yrot(20),aux_T=xrot(10),
3018//              fillet=3, n=25);
3019//   linear_sweep(1.4*flower,height=60,center=true,
3020//                convexity=10,orient=RIGHT);
3021// Example(3D,NoScales,VPR=[78,0,42],VPT=[12.45,-12.45,10.4],VPD=130): Instead of terminating your prism in a flat face perpendicular to its axis you can attach it to a second object.  The simplest case is to connect to planar attachments.  When connecting to a second object you must position and orient the second object using aux_T, which is now allowed to be a rotation and translation operator.  The `length` parameter is no longer allowed.  
3022//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3023//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3024//   join_prism(flower,base="plane", fillet=4, n=12,
3025//              aux="plane", aux_T=up(12));
3026//   %up(12)cuboid([40,40,4],anchor=BOT); 
3027//   cuboid([40,40,4],anchor=TOP);
3028// Example(3D,NoScales,VPR=[78,0,42],VPT=[12.45,-12.45,10.4],VPD=130): Here's an example where the second object is rotated.  Note that the prism will go from the origin to the origin point of the object.  In this case because the rotation is applied first, the prism is vertical.  
3029//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3030//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3031//   aux_T = up(12)*xrot(-22);
3032//   join_prism(flower,base="plane",fillet=4, n=12,
3033//              aux="plane", aux_T=aux_T); 
3034//   multmatrix(aux_T)cuboid([42,42,4],anchor=BOT);
3035//   cuboid([40,40,4],anchor=TOP);
3036// Example(3D,NoScales,VPR=[78,0,42],VPT=[12.45,-12.45,10.4],VPD=130): In this example, the aux_T transform moves the centerpoint (origin) of the aux object, and the resulting prism connects centerpoints, so it is no longer vertical. 
3037//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3038//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3039//   aux_T = xrot(-22)*up(12);
3040//   join_prism(flower,base="plane",fillet=4, n=12,
3041//              aux="plane", aux_T=aux_T);
3042//   multmatrix(aux_T)cuboid([42,42,4],anchor=BOT);
3043//   cuboid([43,43,4],anchor=TOP);
3044// Example(3D,NoScales,VPR=[78,0,42],VPT=[9.95,-9.98,13.0],VPD=142]): You can combine with base_T
3045//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3046//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3047//   aux_T = xrot(-22)*up(22);
3048//   base_T = xrot(5)*yrot(-12);
3049//   join_prism(flower,base="plane",base_T=base_T, 
3050//              aux="plane",aux_T=aux_T, fillet=4, n=12);
3051//   multmatrix(aux_T)cuboid([42,42,4],anchor=BOT);
3052//   multmatrix(base_T)cuboid([45,45,4],anchor=TOP);
3053// Example(3D,NoScales,VPR=[76.6,0,29.4],VPT=[11.4009,-8.43978,16.1934],VPD=157.778): Using prism_end_T shifts the prism's end without tilting the plane, so the prism ends are not perpendicular to the prism axis.  
3054//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3055//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3056//   join_prism(flower,base="plane", prism_end_T=right(14),
3057//              aux="plane",aux_T=up(24), fillet=4, n=12);
3058//   right(7){
3059//     %up(24)cuboid([65,42,4],anchor=BOT);
3060//     cuboid([65,42,4],anchor=TOP);
3061//   }
3062// Example(3D,NoAxes,NoScales,VPR=[101.9, 0, 205.6], VPT=[5.62846, -5.13283, 12.0751], VPD=102.06): Negative fillets give roundovers and are pemitted only for joints to planes.  Note that overlap defaults to zero for negative fillets.  
3063//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3064//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3065//   aux_T = xrot(-22)*up(22);
3066//   base_T = xrot(5)*yrot(-12);
3067//   join_prism(flower,base="plane",base_T=base_T,
3068//              aux="plane", aux_T=aux_T, fillet=-4,n=12);
3069// Example(3D,NoScales,VPR=[84,0,21],VPT=[13.6,-1,46.8],VPD=446): It works the same way with the other shapes, but make sure you move the shapes far enough apart that there is room for a prism.  
3070//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3071//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3072//   aux_T = up(85);
3073//   base_T = xrot(5)*yrot(-12);
3074//   join_prism(flower,base="cylinder",base_r=25, fillet=4, n=12,
3075//              aux="sphere",aux_r=35,base_T=base_T, aux_T=aux_T);
3076//   multmatrix(aux_T)spheroid(35,circum=true);
3077//   multmatrix(base_T)xcyl(l=75,r=25,circum=true);
3078// Example(3D,NoScales,VPR=[84,0,21],VPT=[13.6,-1,46.8],VPD=446): Here we translate the sphere to the right and the prism goes with it
3079//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3080//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3081//   aux_T = right(40)*up(85);
3082//   join_prism(flower,base="cylinder",base_r=25, n=12,
3083//              aux="sphere",aux_r=35, aux_T=aux_T, fillet=4);
3084//   multmatrix(aux_T)spheroid(35,circum=true);
3085//   xcyl(l=75,r=25,circum=true);
3086// Example(3D,NoScales,VPR=[84,0,21],VPT=[13.6,-1,46.8],VPD=446): This is the previous example with the prism_end_T transformation used to shift the far end of the prism away from the sphere center.  Note that prism_end_T can be any transformation, but it just acts on the location of the prism endpoint to shift the direction the prism points.  
3087//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3088//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3089//   aux_T = right(40)*up(85);
3090//   join_prism(flower,base="cylinder",base_r=25,
3091//              prism_end_T=left(4), fillet=3, n=12, 
3092//              aux="sphere",aux_r=35, aux_T=aux_T); 
3093//   multmatrix(aux_T)spheroid(35,circum=true);
3094//   xcyl(l=75,r=25,circum=true);
3095// Example(3D,NoScales,VPR=[96.9,0,157.5],VPT=[-7.77616,-2.272,37.9424],VPD=366.527): Here the base is a cylinder but the auxilary object is a generic prism, and the joiner prism has a scale factor.  
3096//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3097//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3098//   aux_T = up(85)*zrot(-75);
3099//   ellipse = ellipse([17,10],$fn=164);  
3100//   join_prism(flower,base="cylinder",base_r=25,
3101//              fillet=4, n=12,
3102//              aux=ellipse, aux_T=aux_T,scale=.5);
3103//   multmatrix(aux_T)
3104//     linear_sweep(ellipse,orient=RIGHT,height=75,center=true);
3105//   xcyl(l=75,r=25,circum=true,$fn=100);
3106// Example(3D,NoAxes,VPT=[10.0389,1.71153,26.4635],VPR=[89.3,0,39],VPD=237.091): Base and aux are both a general prism in this case.
3107//   ellipse = ellipse([10,17]/2,$fn=96);  
3108//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3109//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3110//   aux_T=up(50);   
3111//   join_prism(ellipse,base=flower,aux_T=aux_T,aux=flower,
3112//              fillet=3, n=12, prism_end_T=right(9));
3113//   multmatrix(aux_T)
3114//     linear_sweep(flower,height=60,center=true,orient=RIGHT);
3115//   linear_sweep(flower,height=60,center=true,orient=RIGHT);
3116// Example(3D,NoAxes,VPT=[8.57543,0.531762,26.8046],VPR=[89.3,0,39],VPD=172.84): Shifting the joiner prism forward brings it close to a steeply curved edge of the auxiliary prism at the top.  Note that a funny looking bump with a sharp corner has appeared in the fillet.  This bump/corner is a result of the uniform filleting method running out of space.  If we move the joiner prism farther forward, the algorithm fails completely.  
3117//   ellipse = ellipse([10,17]/2,$fn=96);  
3118//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3119//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3120//   aux_T=up(50);   
3121//   join_prism(ellipse,base=flower,aux_T=aux_T,aux=flower,
3122//              fillet=3, n=12, prism_end_T=fwd(1.6));
3123//   multmatrix(aux_T)
3124//     linear_sweep(flower,height=60,center=true,orient=RIGHT);
3125//   linear_sweep(flower,height=60,center=true,orient=RIGHT);
3126// Example(3D,NoAxes,VPT=[8.57543,0.531762,26.8046],VPR=[89.3,0,39],VPD=172.84): This is the same example as above but with uniform turned off.  Note how the line the fillet makes on the joiner prism is not uniform, but the overall curved shape is more pleasing than the previous result, and we can bring the joiner prism a little farther forward and still construct a model. 
3127//   ellipse = ellipse([10,17]/2,$fn=96);  
3128//   flower = [for(theta=lerpn(0,360,180,endpoint=false))
3129//             (15+1.3*sin(6*theta))*[cos(theta),sin(theta)]];
3130//   aux_T=up(50);   
3131//   join_prism(ellipse,base=flower,aux_T=aux_T,aux=flower,
3132//              fillet=3, n=12, prism_end_T=fwd(1.7),
3133//              uniform=false);
3134//   multmatrix(aux_T)
3135//     linear_sweep(flower,height=60,center=true,orient=RIGHT);
3136//   linear_sweep(flower,height=60,center=true,orient=RIGHT);
3137// Example(3D): Positioning a joiner prism as an attachment
3138//   cuboid([20,30,40])
3139//     attach(RIGHT,"root")
3140//       join_prism(circle(r=8,$fn=32),
3141//                  l=10, base="plane", fillet=4);
3142module join_prism(polygon, base, base_r, base_d, base_T=IDENT,
3143                    scale=1, prism_end_T=IDENT, short=false, 
3144                    length, l, height, h,
3145                    aux="none", aux_T=IDENT, aux_r, aux_d,
3146                    overlap, base_overlap,aux_overlap,
3147                    n=15, base_n, end_n, aux_n,
3148                    fillet, base_fillet,aux_fillet,end_round,
3149                    k=0.7, base_k,aux_k,end_k,
3150                    uniform=true, base_uniform, aux_uniform, 
3151                    debug=false, anchor="origin", extent=true, cp="centroid", atype="hull", orient=UP, spin=0,
3152                    convexity=10)
3153{
3154    assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"");
3155    vnf_start_end = join_prism(polygon,base, base_r=base_r, base_d=base_d, base_T=base_T,
3156                   scale=scale, prism_end_T=prism_end_T, short=short,
3157                   length=length, l=l, height=height, h=h,
3158                   aux=aux, aux_T=aux_T, aux_r=aux_r, aux_d=aux_d,
3159                   overlap=overlap, base_overlap=base_overlap, aux_overlap=aux_overlap,
3160                   n=n,base_n=base_n, end_n=end_n, aux_n=aux_n,
3161                   fillet=fillet, base_fillet=base_fillet, aux_fillet=aux_fillet, end_round=end_round,
3162                   k=k, base_k=base_k, aux_k=aux_k, end_k=end_k,
3163                   uniform=uniform, base_uniform=base_uniform, aux_uniform=aux_uniform, 
3164                   debug=debug,
3165                   return_axis=true
3166    );
3167    axis = vnf_start_end[2] - vnf_start_end[1];
3168    anchors = [
3169               named_anchor("root",vnf_start_end[1], -axis),
3170               named_anchor("end",vnf_start_end[2], axis)
3171              ];
3172    attachable(anchor,spin,orient,vnf=vnf_start_end[0], extent=atype=="hull", cp=cp, anchors=anchors) {
3173      vnf_polyhedron(vnf_start_end[0],convexity=convexity);
3174      children();
3175    }
3176}
3177
3178
3179
3180function join_prism(polygon, base, base_r, base_d, base_T=IDENT,
3181                    scale=1, prism_end_T=IDENT, short=false, 
3182                    length, l, height, h,
3183                    aux="none", aux_T=IDENT, aux_r, aux_d,
3184                    overlap, base_overlap,aux_overlap,
3185                    n=15, base_n, aux_n, end_n, 
3186                    fillet, base_fillet,aux_fillet,end_round,
3187                    k=0.7, base_k,aux_k,end_k,
3188                    uniform=true, base_uniform, aux_uniform, 
3189                    debug=false, return_axis=false) =
3190  let(
3191      objects=["cyl","cylinder","plane","sphere"],
3192      length = one_defined([h,height,l,length], "h,height,l,length", dflt=undef)
3193  )
3194  assert(is_path(polygon,2),"Prism polygon must be a 2d path")
3195  assert(is_rotation(base_T,3,centered=true),"Base transformation must be a rotation around the origin")
3196  assert(is_rotation(aux_T,3),"Aux transformation must be a rotation")
3197  assert(aux!="none" || is_rotation(aux_T,centered=true), "With no aux, aux_T must be a rotation centered on the origin")
3198  assert(is_matrix(prism_end_T,4), "Prism endpoint transformation is invalid")
3199  assert(aux!="none" || (is_num(length) && length>0),"With no aux must give positive length")
3200  assert(aux=="none" || is_undef(length), "length parameter allowed only when aux is \"none\"")
3201  assert(aux=="none" || is_path(aux,2) || in_list(aux,objects), "Unknown aux type")
3202  assert(is_path(base,2) || in_list(base,objects), "Unknown base type")
3203  assert(is_undef(length) || (is_num(length) && length>0), "Prism length must be positive")
3204  assert(is_num(scale) && scale>=0, "Prism scale must be non-negative")
3205  assert(num_defined([end_k,aux_k])<2, "Cannot define both end_k and aux_k")
3206  assert(num_defined([end_n,aux_n])<2, "Cannot define both end_n and aux_n")
3207  let(
3208      base_r = get_radius(r=base_r,d=base_d),
3209      aux_r = get_radius(r=aux_r,d=aux_d),
3210      base_k= first_defined([base_k,k]),
3211      aux_k = first_defined([end_k,aux_k,k]),
3212      aux_n = first_defined([end_n,aux_n,n]),
3213      base_n = first_defined([base_n,n]),
3214      base_fillet = one_defined([fillet,base_fillet],"fillet,base_fillet"),
3215      aux_fillet = aux=="none" ? one_defined([aux_fillet,u_mul(-1,end_round)],"aux_fillet,end_round",0)
3216              : one_defined([fillet,aux_fillet],"fillet,aux_fillet"),
3217      base_overlap = one_defined([base_overlap,overlap],"base_overlap,overlap",base_fillet>0?1:0),
3218      aux_overlap = one_defined([aux_overlap,overlap],"aux_overlap,overlap",aux_fillet>0?1:0),
3219      base_uniform = first_defined([base_uniform, uniform]),
3220      aux_uniform = first_defined([aux_uniform, uniform])
3221  )
3222  assert(is_num(base_fillet),"Must give a numeric fillet or base_fillet value")
3223  assert(base=="plane" || base_fillet>=0, "Fillet for non-planar base object must be nonnegative")
3224  assert(is_num(aux_fillet), "Must give numeric fillet or aux_fillet")
3225  assert(in_list(aux,["none","plane"]) || aux_fillet>=0, "Fillet for aux object must be nonnegative")
3226  assert(!in_list(base,["sphere","cyl","cylinder"]) || (is_num(base_r) && !approx(base_r,0)), str("Must give nonzero base_r with base ",base))
3227  assert(!in_list(aux,["sphere","cyl","cylinder"]) || (is_num(aux_r) && !approx(aux_r,0)), str("Must give nonzero aux_r with base ",base))
3228  assert(!short || (in_list(base,["sphere","cyl","cylinder"]) && base_r<0), "You can only set short to true if the base is a sphere or cylinder with radius<0")
3229  let(
3230      base_r=default(base_r,0),
3231      polygon=clockwise_polygon(polygon),
3232      start_center = CENTER,
3233      dir = aux=="none" ? apply(aux_T,UP)
3234          : apply(aux_T,CENTER) == CENTER ? apply(aux_T,UP)
3235          : apply(aux_T,CENTER),
3236      flip = short ? -1 : 1,
3237      start = base=="sphere" ?
3238                let( answer = _sphere_line_isect_best(abs(base_r),[CENTER,flip*dir], sign(base_r)*flip*dir))
3239                assert(answer,"Prism center doesn't intersect sphere (base)")
3240                answer
3241            : base=="cyl" || base=="cylinder" ?
3242                let(
3243                     mapped = apply(yrot(90),[CENTER,flip*dir]),
3244                     answer = _cyl_line_intersection(abs(base_r),mapped,sign(base_r)*mapped[1])
3245                 )
3246                 assert(answer,"Prism center doesn't intersect cylinder (base)")
3247                 apply(yrot(-90),answer)
3248            : is_path(base) ?
3249                let( 
3250                     mapped = apply(yrot(90),[CENTER,flip*dir]),
3251                     answer = _prism_line_isect(pair(base,wrap=true),mapped,mapped[1])[0]
3252                 )
3253                 assert(answer,"Prism center doesn't intersect prism (base)")
3254                 apply(yrot(-90),answer)
3255            : start_center,
3256      aux_T = aux=="none" ? move(start)*prism_end_T*move(-start)*move(length*dir)*move(start)
3257              : aux_T,
3258      prism_end_T = aux=="none" ? IDENT : prism_end_T,
3259      aux = aux=="none" && aux_fillet!=0 ? "plane" : aux, 
3260      end_center = apply(aux_T,CENTER), 
3261      ndir = base_r<0 ? unit(start_center-start) : unit(end_center-start_center,UP),
3262      end_prelim = apply(move(start)*prism_end_T*move(-start),
3263            aux=="sphere" ?
3264                let( answer = _sphere_line_isect_best(abs(aux_r), [start,start+ndir], -sign(aux_r)*ndir))
3265                assert(answer,"Prism center doesn't intersect sphere (aux)")
3266                apply(aux_T,answer)
3267          : aux=="cyl" || aux=="cylinder" ? 
3268                let(
3269                     mapped = apply(yrot(90)*rot_inverse(aux_T),[start,start+ndir]),
3270                     answer = _cyl_line_intersection(abs(aux_r),mapped, -sign(aux_r)*(mapped[1]-mapped[0]))
3271                 )
3272                 assert(answer,"Prism center doesn't intersect cylinder (aux)")
3273                 apply(aux_T*yrot(-90),answer)
3274          : is_path(aux) ?
3275                let( 
3276                     mapped = apply(yrot(90),[start,start+ndir]),
3277                     answer = _prism_line_isect(pair(aux,wrap=true),mapped,mapped[0]-mapped[1])[0]
3278                 )
3279                 assert(answer,"Prism center doesn't intersect prism (aux)")
3280                 apply(aux_T*yrot(-90),answer)
3281          : end_center
3282      ),
3283      end = prism_end_T == IDENT ? end_prelim
3284          : aux=="sphere" ?
3285                let( answer = _sphere_line_isect_best(abs(aux_r), move(-end_center,[start,end_prelim]), -sign(aux_r)*(end_prelim-start)))
3286                assert(answer,"Prism center doesn't intersect sphere (aux)")
3287                answer+end_center
3288          : aux=="cyl" || aux=="cylinder" ? 
3289                let(
3290                     mapped = apply(yrot(90)*move(-end_center),[start,end_prelim]),
3291                     answer = _cyl_line_intersection(abs(aux_r),mapped, -sign(aux_r)*(mapped[1]-mapped[0]))
3292                 )
3293                 assert(answer,"Prism center doesn't intersect cylinder (aux)")
3294                 apply(move(end_center)*yrot(-90),answer)
3295          : is_path(aux) ?
3296                let( 
3297                     mapped = apply(yrot(90)*move(-end_center),[start,end_prelim]),
3298                     answer = _prism_line_isect(pair(aux,wrap=true),mapped,mapped[0]-mapped[1])[0]
3299                 )
3300                 assert(answer,"Prism center doesn't intersect prism (aux)")
3301                 apply(move(end_center)*yrot(-90),answer)
3302          : plane_line_intersection( plane_from_normal(apply(aux_T,UP), end_prelim),[start,end_prelim]),
3303      pangle = rot(from=UP, to=end-start),
3304      truetop = apply(move(start)*pangle,path3d(scale(scale,polygon),norm(start-end))),      
3305      truebot = apply(move(start)*pangle,path3d(polygon)),
3306      base_trans = rot_inverse(base_T),
3307      base_top = apply(base_trans, truetop),
3308      base_bot = apply(base_trans, truebot),
3309      botmesh = apply(base_T,_prism_fillet("base", base, base_r, base_bot, base_top, base_fillet, base_k, n, base_overlap,base_uniform,debug)),
3310      aux_trans = rot_inverse(aux_T),
3311      aux_top = apply(aux_trans, reverse_polygon(truetop)),
3312      aux_bot = apply(aux_trans, reverse_polygon(truebot)),
3313      topmesh_reversed = _prism_fillet("aux",aux, aux_r, aux_top, aux_bot, aux_fillet, aux_k, n, aux_overlap,aux_uniform,debug),
3314      topmesh = apply(aux_T,[for(i=[len(topmesh_reversed)-1:-1:0]) reverse_polygon(topmesh_reversed[i])]),
3315      round_dir = select(topmesh,-1)-botmesh[0],
3316      roundings_cross = [for(i=idx(topmesh)) if (round_dir[i]*(truetop[i]-truebot[i])<0) i],
3317      vnf = vnf_vertex_array(concat(topmesh,botmesh),col_wrap=true, caps=true, reverse=true)
3318  )
3319  assert(debug || roundings_cross==[],"Roundings from the two ends cross on the prism: decrease size of roundings")
3320  return_axis ? [vnf,start,end] : vnf;
3321
3322function _fix_angle_list(list,ind=0, result=[]) =
3323    ind==0 ? _fix_angle_list(list,1,[list[0]])
3324  : ind==len(list) ? result 
3325  : list[ind]-result[ind-1]>90 ? _fix_angle_list(list,ind+1,concat(result,[list[ind]-360]))
3326  : list[ind]-result[ind-1]<-90 ? _fix_angle_list(list,ind+1,concat(result,[list[ind]+360]))
3327  : _fix_angle_list(list,ind+1,concat(result,[list[ind]]));
3328                 
3329
3330
3331// intersection with cylinder of radius R oriented on Z axis, with infinite extent
3332// if ref is given, return point with larger inner product with ref.  
3333function _cyl_line_intersection(R, line, ref) =
3334   let(
3335       line2d = path2d(line),
3336       cisect = circle_line_intersection(r=R, cp=[0,0], line=line2d)
3337   )
3338   len(cisect)<2 ? [] :
3339   let(
3340       linevec = line2d[1]-line2d[0],
3341       dz = line[1].z-line[0].z,
3342       pts = [for(pt=cisect)
3343          let(t = (pt-line2d[0])*linevec/(linevec*linevec))  // position parameter for line
3344          [pt.x,pt.y,dz * t + line[0].z]]
3345   )
3346   is_undef(ref) ? pts :
3347   let(   
3348      dist = [for(pt=pts) ref*pt]
3349   )
3350   dist[0]>dist[1] ? pts[0] : pts[1];
3351
3352
3353function _sphere_line_isect_best(R, line, ref) =
3354   let(
3355        pts = sphere_line_intersection(abs(R), [0,0,0], line=line)
3356   )
3357   len(pts)<2 ? [] :
3358   let(  
3359        dist = [for(pt=pts) ref*pt]
3360   )
3361   dist[0]>dist[1] ? pts[0] : pts[1];
3362
3363// First input is all the pairs of the polygon, e.g. pair(poly,wrap=true)
3364// Unlike the others this returns [point, ind, u], where point is the actual intersection
3365// point, ind ind and u are the segment index and u value.  Prism is z-aligned.  
3366function _prism_line_isect(poly_pairs, line, ref) =
3367   let(
3368       line2d = path2d(line),
3369       ref=point2d(ref),
3370       ilist = [for(j=idx(poly_pairs)) 
3371                 let(segisect = _general_line_intersection(poly_pairs[j],line2d))
3372                 if (segisect && segisect[1]>=-EPSILON && segisect[1]<=1+EPSILON)
3373                    [segisect[0],j,segisect[1],segisect[0]*ref]]
3374   )
3375   len(ilist)==0 ? [] :
3376   let (
3377       ind = max_index(column(ilist,3)),
3378       isect2d = ilist[ind][0],
3379       isect_ind = ilist[ind][1],
3380       isect_u = ilist[ind][2],
3381       slope = (line[1].z-line[0].z)/norm(line[1]-line[0]),
3382       z = slope * norm(line2d[0]-isect2d) + line[0].z
3383   )
3384   [point3d(isect2d,z),isect_ind, isect_u];
3385
3386  
3387function _prism_fillet(name, base, R, bot, top, d, k, N, overlap,uniform,debug) =
3388    base=="none" ? [bot] 
3389  : base=="plane" ? _prism_fillet_plane(name,bot, top, d, k, N, overlap,debug)
3390  : base=="cyl" || base=="cylinder" ? _prism_fillet_cyl(name, R, bot, top, d, k, N, overlap,uniform,debug)
3391  : base=="sphere" ? _prism_fillet_sphere(name, R, bot, top, d, k, N, overlap,uniform,debug)
3392  : is_path(base,2) ? _prism_fillet_prism(name, base, bot, top, d, k, N, overlap,uniform,debug)
3393  : assert(false,"Unknown base type");
3394
3395function _prism_fillet_plane(name, bot, top, d, k, N, overlap,debug) = 
3396    let(
3397        dir = sign(top[0].z-bot[0].z),
3398        isect = [for (i=idx(top)) plane_line_intersection([0,0,1,0], [top[i],bot[i]])],
3399        base_normal = -path3d(path_normals(path2d(isect), closed=true)),
3400        mesh = transpose([for(i=idx(top))
3401          let(
3402              
3403              base_angle = vector_angle(top[i],isect[i],isect[i]+sign(d)*base_normal[i]),
3404              // joint length
3405              // d = r,
3406              r=abs(d)*tan(base_angle/2),
3407              // radius
3408              //d = r/tan(base_angle/2),
3409              // cut
3410              //r = r / (1/sin(base_angle/2) - 1),
3411              //d = r/tan(base_angle/2),
3412              prev = unit(top[i]-isect[i]),
3413              next = sign(d)*dir*base_normal[i],
3414              center = r/sin(base_angle/2) * unit(prev+next) + isect[i]
3415          )
3416          [
3417            each arc(N, cp=center, points = [isect[i]+prev*abs(d), isect[i]+next*d]),
3418            isect[i]+next*d+[0,0,-overlap*dir]
3419          ]
3420        ])
3421    )
3422    assert(debug || is_path_simple(path2d(select(mesh,-2)),closed=true),"Fillet doesn't fit: it intersects itself")
3423    mesh;
3424
3425function _prism_fillet_plane(name, bot, top, d, k, N, overlap,debug) = 
3426    let(
3427        dir = sign(top[0].z-bot[0].z),    // Negative if we are upside down, with "top" below "bot"
3428        isect = [for (i=idx(top)) plane_line_intersection([0,0,1,0], [top[i],bot[i]])]
3429    )
3430    d==0 ? [isect, if (overlap!=0) isect + overlap*dir*DOWN] :
3431    let(
3432        base_normal = -path3d(path_normals(path2d(isect), closed=true)),
3433        mesh = transpose([for(i=idx(top))
3434          assert(norm(top[i]-isect[i])>=d,"Prism is too short for fillet to fit")
3435          let(
3436              d_step = isect[i]+abs(d)*unit(top[i]-isect[i]),
3437              edgepoint = isect[i]+d*dir*base_normal[i],
3438              bez = _smooth_bez_fill([d_step, isect[i], edgepoint],k)
3439          )
3440          [
3441            each bezier_curve(bez,N,endpoint=true),
3442            if (overlap!=0) edgepoint + overlap*dir*DOWN
3443          ]
3444        ])
3445    )
3446    assert(debug || is_path_simple(path2d(select(mesh,-2)),closed=true),"Fillet doesn't fit: it intersects itself")
3447    mesh;
3448
3449
3450// This function was written for a z-aligned cylinder but the actual
3451// upstream assumption is an x-aligned cylinder, so input is rotated and
3452// output is un-rotated.  
3453function _prism_fillet_cyl(name, R, bot, top, d, k, N, overlap, uniform, debug) =
3454    let(
3455        top = yrot(-90,top),
3456        bot = yrot(-90,bot),
3457        isect = [for (i=idx(top))
3458                   let (cisect = _cyl_line_intersection(abs(R), [top[i],bot[i]], sign(R)*(top[i]-bot[i])))
3459                   assert(cisect, str("Prism doesn't fully intersect cylinder (",name,")"))
3460                   cisect
3461                ]
3462    )
3463    d==0 ? [ 
3464             isect,
3465             if (overlap!=0) [for(p=isect) point3d(unit(point2d(p))*(norm(point2d(p))-sign(R)*overlap),p.z)]
3466           ] :
3467    let(
3468        tangent = path_tangents(isect,closed=true),
3469        mesh = transpose([for(i=idx(top))
3470           assert(norm(top[i]-isect[i])>=d,str("Prism is too short for fillet to fit (",name,")"))
3471           let(
3472               dir = sign(R)*unit(cross([isect[i].x,isect[i].y,0],tangent[i])),
3473               zpart = d*dir.z,
3474               curvepart = d*norm(point2d(dir)),
3475               curveang = sign(cross(point2d(isect[i]),point2d(dir))) * curvepart * 180 / PI / abs(R), 
3476               edgepoint = apply(up(zpart)*zrot(curveang), isect[i]),
3477               corner = plane_line_intersection(plane_from_normal([edgepoint.x,edgepoint.y,0], edgepoint),
3478                                                [isect[i],top[i]],
3479                                                bounded=false/*[R>0,true]*/),
3480               d_step = abs(d)*unit(top[i]-isect[i])+(uniform?isect[i]:corner)
3481           )
3482           assert(is_vector(corner,3),str("Fillet does not fit.  Decrease size of fillet (",name,")."))
3483           assert(debug || R<0 || (d_step-corner)*(corner-isect[i])>=0,
3484                 str("Unable to fit fillet, probably due to steep curvature of the cylinder (",name,")."))
3485           let(
3486                bez = _smooth_bez_fill([d_step,corner,edgepoint], k)
3487           )
3488           [ 
3489             each bezier_curve(bez, N, endpoint=true),
3490             if (overlap!=0) point3d(unit(point2d(edgepoint))*(norm(point2d(edgepoint))-sign(R)*overlap),edgepoint.z)
3491           ]
3492        ]),
3493        angle_list = _fix_angle_list([for(pt=select(mesh,-2)) atan2(pt.y,pt.x)]),
3494        z_list = [for(pt=select(mesh,-2)) pt.z],
3495        is_simple = debug || is_path_simple(hstack([angle_list,z_list]), closed=true)
3496    )
3497    assert(is_simple, str("Fillet doesn't fit: its edge is self-intersecting.  Decrease size of roundover. (",name,")"))
3498    yrot(90,mesh);
3499
3500
3501
3502function _prism_fillet_sphere(name, R,bot, top, d, k, N, overlap, uniform, debug) = 
3503    let(
3504        isect = [for (i=idx(top))
3505                    let( isect_pt = _sphere_line_isect_best(abs(R), [top[i],bot[i]],sign(R)*(top[i]-bot[i])))
3506                    assert(isect_pt, str("Prism doesn't fully intersect sphere (",name,")"))
3507                    isect_pt
3508                ]
3509    )
3510    d==0 ? [isect,
3511            if (overlap!=0) [for(p=isect) p - overlap*sign(R)*unit(p)]
3512           ] :
3513    let(          
3514        tangent = path_tangents(isect,closed=true),
3515        mesh = transpose([for(i=idx(top))
3516           assert(norm(top[i]-isect[i])>=d,str("Prism is too short for fillet to fit (",name,")"))
3517           let(   
3518               dir = sign(R)*unit(cross(isect[i],tangent[i])),
3519               curveang = d * 180 / PI / R,
3520               edgepoint = rot(-curveang,v=tangent[i],p=isect[i]),
3521               corner = plane_line_intersection(plane_from_normal(edgepoint, edgepoint),
3522                                                [isect[i],top[i]],
3523                                                bounded=[R>0,true]),
3524               d_step = d*unit(top[i]-isect[i])+(uniform?isect[i]:corner)
3525           ) 
3526           assert(is_vector(corner,3),str("Fillet does not fit (",name,")"))
3527           assert(debug || R<0 || (d_step-corner)*(corner-isect[i])>0, 
3528                  str("Unable to fit fillet, probably due to steep curvature of the sphere (",name,")."))
3529           let(
3530               bez = _smooth_bez_fill([d_step,corner,edgepoint], k)         
3531           ) 
3532           [ 
3533             each bezier_curve(bez, N, endpoint=true),
3534             if (overlap!=0) edgepoint - overlap*sign(R)*unit(edgepoint)
3535           ]
3536        ])
3537      )
3538      // this test will fail if the prism isn't "vertical".  Project along prism direction?  
3539      assert(debug || is_path_simple(path2d(select(mesh,-2)),closed=true),str("Fillet doesn't fit: it intersects itself (",name,")"))
3540      mesh;
3541
3542
3543
3544// Return an interpolated normal to the polygon at segment i, fraction u along the segment.
3545
3546function _getnormal(polygon,index,u,) =
3547  let(
3548      //flat=1/3,
3549      flat=1/8,
3550//     flat=0,
3551      edge = (1-flat)/2,
3552      L=len(polygon),
3553      next_ind = posmod(index+1,L),
3554      prev_ind = posmod(index-1,L),
3555      this_normal = line_normal(select(polygon,index,index+1))
3556  )
3557    u > 1-edge ? lerp(this_normal,line_normal(select(polygon,index+1,index+2)), (u-edge-flat)/edge/2)
3558  : u < edge ? lerp(line_normal(select(polygon,index-1,index)),this_normal, 0.5+u/edge/2)
3559  : this_normal;
3560
3561
3562// Start at segment ind, position u on the polygon and find a point length units
3563// from that starting point.  If dir<0 goes backwards through polygon segments
3564// and if dir>0 goes forwards through polygon segments.
3565// Returns [ point, ind, u] where point is the actual point desired.  
3566function _polygon_step(poly, ind, u, dir, length) =
3567    let(ind = posmod(ind,len(poly)))
3568    u==0 && dir<0 ? _polygon_step(poly, ind-1, 1, dir, length)
3569  : u==1 && dir>0 ? _polygon_step(poly, ind+1, 0, dir, length)
3570  : let(
3571        seg = select(poly,ind,ind+1),
3572        seglen = norm(seg[1]-seg[0]),
3573        frac_needed = length / seglen
3574    )
3575    dir>0 ?
3576            ( (1-u) < frac_needed ? _polygon_step(poly,ind+1,0,dir,length-(1-u)*seglen)
3577                                 : [lerp(seg[0],seg[1],u+frac_needed),ind,u+frac_needed]
3578            )
3579          :
3580            ( u < frac_needed ? _polygon_step(poly,ind-1,1,dir,length-u*seglen)
3581                                 : [lerp(seg[0],seg[1],u-frac_needed),ind,u-frac_needed]
3582            );
3583
3584
3585// This function needs more error checking?
3586// Needs check for zero overlap case and zero joint case
3587function _prism_fillet_prism(name, basepoly, bot, top, d, k, N, overlap, uniform, debug)=
3588    let(
3589         top = yrot(-90,top),
3590         bot = yrot(-90,bot),
3591         basepoly = clockwise_polygon(basepoly),
3592         segpairs = pair(basepoly,wrap=true),
3593         isect_ind = [for (i=idx(top))
3594                         let(isect = _prism_line_isect(segpairs, [top[i], bot[i]], top[i]))
3595                         assert(isect, str("Prism doesn't fully intersect prism (",name,")"))
3596                         isect
3597                     ],
3598         isect=column(isect_ind,0),
3599         index = column(isect_ind,1),
3600         uval = column(isect_ind,2),
3601         tangent = path_tangents(isect,closed=true),
3602         mesh = transpose([for(i=idx(top))
3603           let(
3604               normal = point3d(_getnormal(basepoly,index[i],uval[i])),
3605               dir = unit(cross(normal,tangent[i])),
3606               zpart = d*dir.z,
3607               length_needed = d*norm(point2d(dir)),
3608               edgept2d = _polygon_step(basepoly, index[i], uval[i], sign(cross(point2d(dir),point2d(normal))), length_needed),
3609               edgepoint = point3d(edgept2d[0],isect[i].z+zpart),
3610               corner = plane_line_intersection(plane_from_normal(point3d(_getnormal(basepoly, edgept2d[1],edgept2d[2])),edgepoint),
3611                                                [top[i],isect[i]],
3612                                                bounded=false), // should be true!!!  But fails to intersect if given true.
3613               d_step = abs(d)*unit(top[i]-isect[i])+(uniform?isect[i]:corner)
3614           )
3615           assert(is_vector(corner,3),str("Fillet does not fit.  Decrease size of fillet (",name,")."))
3616           assert(debug  || (top[i]-d_step)*(d_step-corner)>=0,
3617                   str("Unable to fit fillet, probably due to steep curvature of the prism (",name,").",
3618                     d_step," ",corner," ", edgepoint," ", isect[i]
3619                     ))
3620           let(
3621                bez = _smooth_bez_fill([d_step,corner,edgepoint], k)
3622           )
3623           [ 
3624             each bezier_curve(bez, N, endpoint=true),
3625             if (overlap!=0) edgepoint-point3d(normal)*overlap
3626           ]
3627          ])
3628         )
3629        yrot(90,mesh);
3630
3631
3632// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap