1//////////////////////////////////////////////////////////////////////
2// LibFile: shapes2d.scad
3// This file includes redefinitions of the core modules to
4// work with attachment, and functional forms of those modules
5// that produce paths. You can create regular polygons
6// with optional rounded corners and alignment features not
7// available with circle(). The file also provides teardrop2d,
8// which is useful for 3D printable holes.
9// Many of the commands have module forms that produce geometry and
10// function forms that produce a path.
11// Includes:
12// include <BOSL2/std.scad>
13// FileGroup: Basic Modeling
14// FileSummary: Attachable circles, squares, polygons, teardrop. Can make geometry or paths.
15// FileFootnotes: STD=Included in std.scad
16//////////////////////////////////////////////////////////////////////
17
18use <builtins.scad>
19
20
21// Section: 2D Primitives
22
23// Function&Module: square()
24// Synopsis: Creates a 2D square or rectangle.
25// SynTags: Geom, Path
26// Topics: Shapes (2D), Path Generators (2D)
27// See Also: rect()
28// Usage: As a Module
29// square(size, [center], ...);
30// Usage: With Attachments
31// square(size, [center], ...) [ATTACHMENTS];
32// Usage: As a Function
33// path = square(size, [center], ...);
34// Description:
35// When called as the builtin module, creates a 2D square or rectangle of the given size.
36// When called as a function, returns a 2D path/list of points for a square/rectangle of the given size.
37// Arguments:
38// size = The size of the square to create. If given as a scalar, both X and Y will be the same size.
39// center = If given and true, overrides `anchor` to be `CENTER`. If given and false, overrides `anchor` to be `FRONT+LEFT`.
40// ---
41// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
42// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
43// Example(2D):
44// square(40);
45// Example(2D): Centered
46// square([40,30], center=true);
47// Example(2D): Called as Function
48// path = square([40,30], anchor=FRONT, spin=30);
49// stroke(path, closed=true);
50// move_copies(path) color("blue") circle(d=2,$fn=8);
51function square(size=1, center, anchor, spin=0) =
52 let(
53 anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]),
54 size = is_num(size)? [size,size] : point2d(size)
55 )
56 assert(all_positive(size), "All components of size must be positive.")
57 let(
58 path = [
59 [ size.x,-size.y],
60 [-size.x,-size.y],
61 [-size.x, size.y],
62 [ size.x, size.y],
63 ] / 2
64 ) reorient(anchor,spin, two_d=true, size=size, p=path);
65
66
67module square(size=1, center, anchor, spin) {
68 anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]);
69 rsize = is_num(size)? [size,size] : point2d(size);
70 size = [for (c = rsize) max(0,c)];
71 attachable(anchor,spin, two_d=true, size=size) {
72 if (all_positive(size))
73 _square(size, center=true);
74 children();
75 }
76}
77
78
79
80// Function&Module: rect()
81// Synopsis: Creates a 2d rectangle with optional corner rounding.
82// SynTags: Geom, Path
83// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
84// See Also: square()
85// Usage: As Module
86// rect(size, [rounding], [chamfer], ...) [ATTACHMENTS];
87// Usage: As Function
88// path = rect(size, [rounding], [chamfer], ...);
89// Description:
90// When called as a module, creates a 2D rectangle of the given size, with optional rounding or chamfering.
91// When called as a function, returns a 2D path/list of points for a square/rectangle of the given size.
92// Arguments:
93// size = The size of the rectangle to create. If given as a scalar, both X and Y will be the same size.
94// ---
95// rounding = The rounding radius for the corners. If negative, produces external roundover spikes on the X axis. If given as a list of four numbers, gives individual radii for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: 0 (no rounding)
96// chamfer = The chamfer size for the corners. If negative, produces external chamfer spikes on the X axis. If given as a list of four numbers, gives individual chamfers for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: 0 (no chamfer)
97// atype = The type of anchoring to use with `anchor=`. Valid opptions are "box" and "perim". This lets you choose between putting anchors on the rounded or chamfered perimeter, or on the square bounding box of the shape. Default: "box"
98// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
99// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
100// Anchor Types:
101// box = Anchor is with respect to the rectangular bounding box of the shape.
102// perim = Anchors are placed along the rounded or chamfered perimeter of the shape.
103// Example(2D):
104// rect(40);
105// Example(2D): Anchored
106// rect([40,30], anchor=FRONT);
107// Example(2D): Spun
108// rect([40,30], anchor=FRONT, spin=30);
109// Example(2D): Chamferred Rect
110// rect([40,30], chamfer=5);
111// Example(2D): Rounded Rect
112// rect([40,30], rounding=5);
113// Example(2D): Negative-Chamferred Rect
114// rect([40,30], chamfer=-5);
115// Example(2D): Negative-Rounded Rect
116// rect([40,30], rounding=-5);
117// Example(2D): Default "box" Anchors
118// color("red") rect([40,30]);
119// rect([40,30], rounding=10)
120// show_anchors();
121// Example(2D): "perim" Anchors
122// rect([40,30], rounding=10, atype="perim")
123// show_anchors();
124// Example(2D): "perim" Anchors
125// rect([40,30], rounding=[-10,-8,-3,-7], atype="perim")
126// show_anchors();
127// Example(2D): Mixed Chamferring and Rounding
128// rect([40,30],rounding=[5,0,10,0],chamfer=[0,8,0,15],$fa=1,$fs=1);
129// Example(2D): Called as Function
130// path = rect([40,30], chamfer=5, anchor=FRONT, spin=30);
131// stroke(path, closed=true);
132// move_copies(path) color("blue") circle(d=2,$fn=8);
133module rect(size=1, rounding=0, atype="box", chamfer=0, anchor=CENTER, spin=0) {
134 errchk = assert(in_list(atype, ["box", "perim"]));
135 size = [for (c = force_list(size,2)) max(0,c)];
136 if (!all_positive(size)) {
137 attachable(anchor,spin, two_d=true, size=size) {
138 union();
139 children();
140 }
141 } else if (rounding==0 && chamfer==0) {
142 attachable(anchor, spin, two_d=true, size=size) {
143 square(size, center=true);
144 children();
145 }
146 } else {
147 pts_over = rect(size=size, rounding=rounding, chamfer=chamfer, atype=atype, _return_override=true);
148 pts = pts_over[0];
149 override = pts_over[1];
150 attachable(anchor, spin, two_d=true, size=size,override=override) {
151 polygon(pts);
152 children();
153 }
154 }
155}
156
157
158
159function rect(size=1, rounding=0, chamfer=0, atype="box", anchor=CENTER, spin=0, _return_override) =
160 assert(is_num(size) || is_vector(size,2))
161 assert(is_num(chamfer) || is_vector(chamfer,4))
162 assert(is_num(rounding) || is_vector(rounding,4))
163 assert(in_list(atype, ["box", "perim"]))
164 let(
165 anchor=_force_anchor_2d(anchor),
166 size = [for (c = force_list(size,2)) max(0,c)],
167 chamfer = force_list(chamfer,4),
168 rounding = force_list(rounding,4)
169 )
170 assert(all_nonnegative(size), "All components of size must be >=0")
171 all_zero(concat(chamfer,rounding),0) ?
172 let(
173 path = [
174 [ size.x/2, -size.y/2],
175 [-size.x/2, -size.y/2],
176 [-size.x/2, size.y/2],
177 [ size.x/2, size.y/2],
178 ]
179 )
180 rot(spin, p=move(-v_mul(anchor,size/2), p=path))
181 :
182 assert(all_zero(v_mul(chamfer,rounding),0), "Cannot specify chamfer and rounding at the same corner")
183 let(
184 quadorder = [3,2,1,0],
185 quadpos = [[1,1],[-1,1],[-1,-1],[1,-1]],
186 eps = 1e-9,
187 insets = [for (i=[0:3]) abs(chamfer[i])>=eps? chamfer[i] : abs(rounding[i])>=eps? rounding[i] : 0],
188 insets_x = max(insets[0]+insets[1],insets[2]+insets[3]),
189 insets_y = max(insets[0]+insets[3],insets[1]+insets[2])
190 )
191 assert(insets_x <= size.x, "Requested roundings and/or chamfers exceed the rect width.")
192 assert(insets_y <= size.y, "Requested roundings and/or chamfers exceed the rect height.")
193 let(
194 corners = [
195 for(i = [0:3])
196 let(
197 quad = quadorder[i],
198 qinset = insets[quad],
199 qpos = quadpos[quad],
200 qchamf = chamfer[quad],
201 qround = rounding[quad],
202 cverts = quant(segs(abs(qinset)),4)/4,
203 step = 90/cverts,
204 cp = v_mul(size/2-[qinset,abs(qinset)], qpos),
205 qpts = abs(qchamf) >= eps? [[0,abs(qinset)], [qinset,0]] :
206 abs(qround) >= eps? [for (j=[0:1:cverts]) let(a=90-j*step) v_mul(polar_to_xy(abs(qinset),a),[sign(qinset),1])] :
207 [[0,0]],
208 qfpts = [for (p=qpts) v_mul(p,qpos)],
209 qrpts = qpos.x*qpos.y < 0? reverse(qfpts) : qfpts,
210 cornerpt = atype=="box" || (qround==0 && qchamf==0) ? undef
211 : qround<0 || qchamf<0 ? [[0,-qpos.y*min(qround,qchamf)]]
212 : [for(seg=pair(qrpts)) let(isect=line_intersection(seg, [[0,0],qpos],SEGMENT,LINE)) if (is_def(isect) && isect!=seg[0]) isect]
213 )
214 assert(is_undef(cornerpt) || len(cornerpt)==1,"Cannot find corner point to anchor")
215 [move(cp, p=qrpts), is_undef(cornerpt)? undef : move(cp,p=cornerpt[0])]
216 ],
217 path = flatten(column(corners,0)),
218 override = [for(i=[0:3])
219 let(quad=quadorder[i])
220 if (is_def(corners[i][1])) [quadpos[quad], [corners[i][1], min(chamfer[quad],rounding[quad])<0 ? [quadpos[quad].x,0] : undef]]]
221 ) _return_override ? [reorient(anchor,spin, two_d=true, size=size, p=path, override=override), override]
222 : reorient(anchor,spin, two_d=true, size=size, p=path, override=override);
223
224
225// Function&Module: circle()
226// Synopsis: Creates the approximation of a circle.
227// SynTags: Geom, Path
228// Topics: Shapes (2D), Path Generators (2D)
229// See Also: ellipse(), circle_2tangents(), circle_3points()
230// Usage: As a Module
231// circle(r|d=, ...) [ATTACHMENTS];
232// circle(points=) [ATTACHMENTS];
233// circle(r|d=, corner=) [ATTACHMENTS];
234// Usage: As a Function
235// path = circle(r|d=, ...);
236// path = circle(points=);
237// path = circle(r|d=, corner=);
238// Description:
239// When called as the builtin module, creates a 2D polygon that approximates a circle of the given size.
240// When called as a function, returns a 2D list of points (path) for a polygon that approximates a circle of the given size.
241// If `corner=` is given three 2D points, centers the circle so that it will be tangent to both segments of the path, on the inside corner.
242// If `points=` is given three 2D points, centers and sizes the circle so that it passes through all three points.
243// Arguments:
244// r = The radius of the circle to create.
245// d = The diameter of the circle to create.
246// ---
247// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
248// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
249// Example(2D): By Radius
250// circle(r=25);
251// Example(2D): By Diameter
252// circle(d=50);
253// Example(2D): Fit to Three Points
254// pts = [[50,25], [25,-25], [-10,0]];
255// circle(points=pts);
256// color("red") move_copies(pts) circle();
257// Example(2D): Fit Tangent to Inside Corner of Two Segments
258// path = [[50,25], [-10,0], [25,-25]];
259// circle(corner=path, r=15);
260// color("red") stroke(path);
261// Example(2D): Called as Function
262// path = circle(d=50, anchor=FRONT, spin=45);
263// stroke(path);
264function circle(r, d, points, corner, anchor=CENTER, spin=0) =
265 assert(is_undef(corner) || (is_path(corner,[2]) && len(corner) == 3))
266 assert(is_undef(points) || is_undef(corner), "Cannot specify both points and corner.")
267 let(
268 data = is_def(points)?
269 assert(is_path(points,[2]) && len(points) == 3)
270 assert(is_undef(corner), "Cannot specify corner= when points= is given.")
271 assert(is_undef(r) && is_undef(d), "Cannot specify r= or d= when points= is given.")
272 let( c = circle_3points(points) )
273 assert(!is_undef(c[0]), "Points cannot be collinear.")
274 let( cp = c[0], r = c[1] )
275 [cp, r] :
276 is_def(corner)?
277 assert(is_path(corner,[2]) && len(corner) == 3)
278 assert(is_undef(points), "Cannot specify points= when corner= is given.")
279 let(
280 r = get_radius(r=r, d=d, dflt=1),
281 c = circle_2tangents(r=r, pt1=corner[0], pt2=corner[1], pt3=corner[2])
282 )
283 assert(c!=undef, "Corner path cannot be collinear.")
284 let( cp = c[0] )
285 [cp, r] :
286 let(
287 cp = [0, 0],
288 r = get_radius(r=r, d=d, dflt=1)
289 ) [cp, r],
290 cp = data[0],
291 r = data[1]
292 )
293 assert(r>0, "Radius/diameter must be positive")
294 let(
295 sides = segs(r),
296 path = [for (i=[0:1:sides-1]) let(a=360-i*360/sides) r*[cos(a),sin(a)]+cp]
297 ) reorient(anchor,spin, two_d=true, r=r, p=path);
298
299module circle(r, d, points, corner, anchor=CENTER, spin=0) {
300 if (is_path(points)) {
301 c = circle_3points(points);
302 check = assert(c!=undef && c[0] != undef, "Points must not be collinear.");
303 cp = c[0];
304 r = c[1];
305 translate(cp) {
306 attachable(anchor,spin, two_d=true, r=r) {
307 if (r>0) _circle(r=r);
308 children();
309 }
310 }
311 } else if (is_path(corner)) {
312 r = get_radius(r=r, d=d, dflt=1);
313 c = circle_2tangents(r=r, pt1=corner[0], pt2=corner[1], pt3=corner[2]);
314 check = assert(c != undef && c[0] != undef, "Points must not be collinear.");
315 cp = c[0];
316 translate(cp) {
317 attachable(anchor,spin, two_d=true, r=r) {
318 if (r>0) _circle(r=r);
319 children();
320 }
321 }
322 } else {
323 r = get_radius(r=r, d=d, dflt=1);
324 attachable(anchor,spin, two_d=true, r=r) {
325 if (r>0) _circle(r=r);
326 children();
327 }
328 }
329}
330
331
332
333// Function&Module: ellipse()
334// Synopsis: Creates the approximation of an ellipse or a circle.
335// SynTags: Geom, Path
336// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
337// See Also: circle(), circle_2tangents(), circle_3points()
338// Usage: As a Module
339// ellipse(r|d=, [realign=], [circum=], [uniform=], ...) [ATTACHMENTS];
340// Usage: As a Function
341// path = ellipse(r|d=, [realign=], [circum=], [uniform=], ...);
342// Description:
343// When called as a module, creates a 2D polygon that approximates a circle or ellipse of the given size.
344// When called as a function, returns a 2D list of points (path) for a polygon that approximates a circle or ellipse of the given size.
345// By default the point list or shape is the same as the one you would get by scaling the output of {{circle()}}, but with this module your
346// attachments to the ellipse will retain their dimensions, whereas scaling a circle with attachments will also scale the attachments.
347// If you set `uniform` to true then you will get a polygon with congruent sides whose vertices lie on the ellipse. The `circum` option
348// requests a polygon that circumscribes the requested ellipse (so the specified ellipse will fit into the resulting polygon). Note that
349// you cannot gives `circum=true` and `uniform=true`.
350// Arguments:
351// r = Radius of the circle or pair of semiaxes of ellipse
352// ---
353// d = Diameter of the circle or a pair giving the full X and Y axis lengths.
354// realign = If false starts the approximate ellipse with a point on the X+ axis. If true the midpoint of a side is on the X+ axis and the first point of the polygon is below the X+ axis. This can result in a very different polygon when $fn is small. Default: false
355// uniform = If true, the polygon that approximates the circle will have segments of equal length. Only works if `circum=false`. Default: false
356// circum = If true, the polygon that approximates the circle will be upsized slightly to circumscribe the theoretical circle. If false, it inscribes the theoretical circle. If this is true then `uniform` must be false. Default: false
357// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
358// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
359// Example(2D): By Radius
360// ellipse(r=25);
361// Example(2D): By Diameter
362// ellipse(d=50);
363// Example(2D): Anchoring
364// ellipse(d=50, anchor=FRONT);
365// Example(2D): Spin
366// ellipse(d=50, anchor=FRONT, spin=45);
367// Example(NORENDER): Called as Function
368// path = ellipse(d=50, anchor=FRONT, spin=45);
369// Example(2D,NoAxes): Uniformly sampled hexagon at the top, regular non-uniform one at the bottom
370// r=[10,3];
371// ydistribute(7){
372// union(){
373// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
374// stroke([ellipse(r=r, $fn=6)],width=0.1,color="red");
375// }
376// union(){
377// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
378// stroke([ellipse(r=r, $fn=6,uniform=true)],width=0.1,color="red");
379// }
380// }
381// Example(2D): The realigned hexagons are even more different
382// r=[10,3];
383// ydistribute(7){
384// union(){
385// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
386// stroke([ellipse(r=r, $fn=6,realign=true)],width=0.1,color="red");
387// }
388// union(){
389// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
390// stroke([ellipse(r=r, $fn=6,realign=true,uniform=true)],width=0.1,color="red");
391// }
392// }
393// Example(2D): For odd $fn the result may not look very elliptical:
394// r=[10,3];
395// ydistribute(7){
396// union(){
397// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
398// stroke([ellipse(r=r, $fn=5,realign=false)],width=0.1,color="red");
399// }
400// union(){
401// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
402// stroke([ellipse(r=r, $fn=5,realign=false,uniform=true)],width=0.1,color="red");
403// }
404// }
405// Example(2D): The same ellipse, turned 90 deg, gives a very different result:
406// r=[3,10];
407// xdistribute(7){
408// union(){
409// stroke([ellipse(r=r, $fn=100)],width=0.1,color="blue");
410// stroke([ellipse(r=r, $fn=5,realign=false)],width=0.2,color="red");
411// }
412// union(){
413// stroke([ellipse(r=r, $fn=100)],width=0.1,color="blue");
414// stroke([ellipse(r=r, $fn=5,realign=false,uniform=true)],width=0.2,color="red");
415// }
416// }
417module ellipse(r, d, realign=false, circum=false, uniform=false, anchor=CENTER, spin=0)
418{
419 r = force_list(get_radius(r=r, d=d, dflt=1),2);
420 dummy = assert(is_vector(r,2) && all_positive(r), "Invalid radius or diameter for ellipse");
421 sides = segs(max(r));
422 sc = circum? (1 / cos(180/sides)) : 1;
423 rx = r.x * sc;
424 ry = r.y * sc;
425 attachable(anchor,spin, two_d=true, r=[rx,ry]) {
426 if (uniform) {
427 check = assert(!circum, "Circum option not allowed when \"uniform\" is true");
428 polygon(ellipse(r,realign=realign, circum=circum, uniform=true));
429 }
430 else if (rx < ry) {
431 xscale(rx/ry) {
432 zrot(realign? 180/sides : 0) {
433 circle(r=ry, $fn=sides);
434 }
435 }
436 } else {
437 yscale(ry/rx) {
438 zrot(realign? 180/sides : 0) {
439 circle(r=rx, $fn=sides);
440 }
441 }
442 }
443 children();
444 }
445}
446
447
448// Iterative refinement to produce an inscribed polygon
449// in an ellipse whose side lengths are all equal
450function _ellipse_refine(a,b,N, _theta=[]) =
451 len(_theta)==0? _ellipse_refine(a,b,N,lerpn(0,360,N,endpoint=false))
452 :
453 let(
454 pts = [for(t=_theta) [a*cos(t),b*sin(t)]],
455 lenlist= path_segment_lengths(pts,closed=true),
456 meanlen = mean(lenlist),
457 error = lenlist/meanlen
458 )
459 all_equal(error,EPSILON) ? pts
460 :
461 let(
462 dtheta = [each deltas(_theta),
463 360-last(_theta)],
464 newdtheta = [for(i=idx(dtheta)) dtheta[i]/error[i]],
465 adjusted = [0,each cumsum(list_head(newdtheta / sum(newdtheta) * 360))]
466 )
467 _ellipse_refine(a,b,N,adjusted);
468
469
470
471
472function _ellipse_refine_realign(a,b,N, _theta=[],i=0) =
473 len(_theta)==0?
474 _ellipse_refine_realign(a,b,N, count(N-1,180/N,360/N))
475 :
476 let(
477 pts = [for(t=_theta) [a*cos(t),b*sin(t)],
478 [a*cos(_theta[0]), -b*sin(_theta[0])]],
479 lenlist= path_segment_lengths(pts,closed=true),
480 meanlen = mean(lenlist),
481 error = lenlist/meanlen
482 )
483 all_equal(error,EPSILON) ? pts
484 :
485 let(
486 dtheta = [each deltas(_theta),
487 360-last(_theta)-_theta[0],
488 2*_theta[0]],
489 newdtheta = [for(i=idx(dtheta)) dtheta[i]/error[i]],
490 normdtheta = newdtheta / sum(newdtheta) * 360,
491 adjusted = cumsum([last(normdtheta)/2, each list_head(normdtheta, -3)])
492 )
493 _ellipse_refine_realign(a,b,N,adjusted, i+1);
494
495
496
497function ellipse(r, d, realign=false, circum=false, uniform=false, anchor=CENTER, spin=0) =
498 let(
499 r = force_list(get_radius(r=r, d=d, dflt=1),2),
500 sides = segs(max(r))
501 )
502 assert(all_positive(r), "All components of the radius must be positive.")
503 uniform
504 ? assert(!circum, "Circum option not allowed when \"uniform\" is true")
505 reorient(anchor,spin,
506 two_d=true, r=[r.x,r.y],
507 p=realign
508 ? reverse(_ellipse_refine_realign(r.x,r.y,sides))
509 : reverse_polygon(_ellipse_refine(r.x,r.y,sides))
510 )
511 : let(
512 offset = realign? 180/sides : 0,
513 sc = circum? (1 / cos(180/sides)) : 1,
514 rx = r.x * sc,
515 ry = r.y * sc,
516 pts = [
517 for (i=[0:1:sides-1])
518 let (a = 360-offset-i*360/sides)
519 [rx*cos(a), ry*sin(a)]
520 ]
521 ) reorient(anchor,spin, two_d=true, r=[rx,ry], p=pts);
522
523
524// Section: Polygons
525
526// Function&Module: regular_ngon()
527// Synopsis: Creates a regular N-sided polygon.
528// SynTags: Geom, Path
529// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
530// See Also: debug_polygon(), circle(), pentagon(), hexagon(), octagon(), ellipse(), star()
531// Usage:
532// regular_ngon(n, r|d=|or=|od=, [realign=]) [ATTACHMENTS];
533// regular_ngon(n, ir=|id=, [realign=]) [ATTACHMENTS];
534// regular_ngon(n, side=, [realign=]) [ATTACHMENTS];
535// Description:
536// When called as a function, returns a 2D path for a regular N-sided polygon.
537// When called as a module, creates a 2D regular N-sided polygon.
538// Arguments:
539// n = The number of sides.
540// r/or = Outside radius, at points.
541// ---
542// d/od = Outside diameter, at points.
543// ir = Inside radius, at center of sides.
544// id = Inside diameter, at center of sides.
545// side = Length of each side.
546// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
547// realign = If false, vertex 0 will lie on the X+ axis. If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis. Default: false
548// align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction. This occurs before spin.
549// align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction. This occurs before spin.
550// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
551// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
552// Extra Anchors:
553// "tip0", "tip1", etc. = Each tip has an anchor, pointing outwards.
554// "side0", "side1", etc. = The center of each side has an anchor, pointing outwards.
555// Example(2D): by Outer Size
556// regular_ngon(n=5, or=30);
557// regular_ngon(n=5, od=60);
558// Example(2D): by Inner Size
559// regular_ngon(n=5, ir=30);
560// regular_ngon(n=5, id=60);
561// Example(2D): by Side Length
562// regular_ngon(n=8, side=20);
563// Example(2D): Realigned
564// regular_ngon(n=8, side=20, realign=true);
565// Example(2D): Alignment by Tip
566// regular_ngon(n=5, r=30, align_tip=BACK+RIGHT)
567// attach("tip0", FWD) color("blue")
568// stroke([[0,0],[0,7]], endcap2="arrow2");
569// Example(2D): Alignment by Side
570// regular_ngon(n=5, r=30, align_side=BACK+RIGHT)
571// attach("side0", FWD) color("blue")
572// stroke([[0,0],[0,7]], endcap2="arrow2");
573// Example(2D): Rounded
574// regular_ngon(n=5, od=100, rounding=20, $fn=20);
575// Example(2D): Called as Function
576// stroke(closed=true, regular_ngon(n=6, or=30));
577function regular_ngon(n=6, r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0, _mat, _anchs) =
578 assert(is_int(n) && n>=3)
579 assert(is_undef(align_tip) || is_vector(align_tip))
580 assert(is_undef(align_side) || is_vector(align_side))
581 assert(is_undef(align_tip) || is_undef(align_side), "Can only specify one of align_tip and align-side")
582 let(
583 sc = 1/cos(180/n),
584 ir = is_finite(ir)? ir*sc : undef,
585 id = is_finite(id)? id*sc : undef,
586 side = is_finite(side)? side/2/sin(180/n) : undef,
587 r = get_radius(r1=ir, r2=or, r=r, d1=id, d2=od, d=d, dflt=side)
588 )
589 assert(!is_undef(r), "regular_ngon(): need to specify one of r, d, or, od, ir, id, side.")
590 assert(all_positive([r]), "polygon size must be a positive value")
591 let(
592 inset = opp_ang_to_hyp(rounding, (180-360/n)/2),
593 mat = !is_undef(_mat) ? _mat :
594 ( realign? zrot(-180/n) : ident(4)) * (
595 !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
596 !is_undef(align_side)? rot(from=RIGHT, to=point2d(align_side)) * zrot(180/n) :
597 1
598 ),
599 path4 = rounding==0? ellipse(r=r, $fn=n) : (
600 let(
601 steps = floor(segs(r)/n),
602 step = 360/n/steps,
603 path2 = [
604 for (i = [0:1:n-1]) let(
605 a = 360 - i*360/n,
606 p = polar_to_xy(r-inset, a)
607 )
608 each arc(n=steps, cp=p, r=rounding, start=a+180/n, angle=-360/n)
609 ],
610 maxx_idx = max_index(column(path2,0)),
611 path3 = list_rotate(path2,maxx_idx)
612 ) path3
613 ),
614 path = apply(mat, path4),
615 anchors = !is_undef(_anchs) ? _anchs :
616 !is_string(anchor)? [] : [
617 for (i = [0:1:n-1]) let(
618 a1 = 360 - i*360/n,
619 a2 = a1 - 360/n,
620 p1 = apply(mat, polar_to_xy(r,a1)),
621 p2 = apply(mat, polar_to_xy(r,a2)),
622 tipp = apply(mat, polar_to_xy(r-inset+rounding,a1)),
623 pos = (p1+p2)/2
624 ) each [
625 named_anchor(str("tip",i), tipp, unit(tipp,BACK), 0),
626 named_anchor(str("side",i), pos, unit(pos,BACK), 0),
627 ]
628 ]
629 ) reorient(anchor,spin, two_d=true, path=path, extent=false, p=path, anchors=anchors);
630
631
632module regular_ngon(n=6, r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) {
633 sc = 1/cos(180/n);
634 ir = is_finite(ir)? ir*sc : undef;
635 id = is_finite(id)? id*sc : undef;
636 side = is_finite(side)? side/2/sin(180/n) : undef;
637 r = get_radius(r1=ir, r2=or, r=r, d1=id, d2=od, d=d, dflt=side);
638 check = assert(!is_undef(r), "regular_ngon(): need to specify one of r, d, or, od, ir, id, side.")
639 assert(all_positive([r]), "polygon size must be a positive value");
640 mat = ( realign? zrot(-180/n) : ident(4) ) * (
641 !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
642 !is_undef(align_side)? rot(from=RIGHT, to=point2d(align_side)) * zrot(180/n) :
643 1
644 );
645 inset = opp_ang_to_hyp(rounding, (180-360/n)/2);
646 anchors = [
647 for (i = [0:1:n-1]) let(
648 a1 = 360 - i*360/n,
649 a2 = a1 - 360/n,
650 p1 = apply(mat, polar_to_xy(r,a1)),
651 p2 = apply(mat, polar_to_xy(r,a2)),
652 tipp = apply(mat, polar_to_xy(r-inset+rounding,a1)),
653 pos = (p1+p2)/2
654 ) each [
655 named_anchor(str("tip",i), tipp, unit(tipp,BACK), 0),
656 named_anchor(str("side",i), pos, unit(pos,BACK), 0),
657 ]
658 ];
659 path = regular_ngon(n=n, r=r, rounding=rounding, _mat=mat, _anchs=anchors);
660 attachable(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors) {
661 polygon(path);
662 children();
663 }
664}
665
666
667// Function&Module: pentagon()
668// Synopsis: Creates a regular pentagon.
669// SynTags: Geom, Path
670// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
671// See Also: circle(), regular_ngon(), hexagon(), octagon(), ellipse(), star()
672// Usage:
673// pentagon(or|od=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
674// pentagon(ir=|id=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
675// pentagon(side=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
676// Usage: as function
677// path = pentagon(...);
678// Description:
679// When called as a function, returns a 2D path for a regular pentagon.
680// When called as a module, creates a 2D regular pentagon.
681// Arguments:
682// r/or = Outside radius, at points.
683// ---
684// d/od = Outside diameter, at points.
685// ir = Inside radius, at center of sides.
686// id = Inside diameter, at center of sides.
687// side = Length of each side.
688// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
689// realign = If false, vertex 0 will lie on the X+ axis. If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis. Default: false
690// align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction. This occurs before spin.
691// align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction. This occurs before spin.
692// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
693// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
694// Extra Anchors:
695// "tip0" ... "tip4" = Each tip has an anchor, pointing outwards.
696// "side0" ... "side4" = The center of each side has an anchor, pointing outwards.
697// Example(2D): by Outer Size
698// pentagon(or=30);
699// pentagon(od=60);
700// Example(2D): by Inner Size
701// pentagon(ir=30);
702// pentagon(id=60);
703// Example(2D): by Side Length
704// pentagon(side=20);
705// Example(2D): Realigned
706// pentagon(side=20, realign=true);
707// Example(2D): Alignment by Tip
708// pentagon(r=30, align_tip=BACK+RIGHT)
709// attach("tip0", FWD) color("blue")
710// stroke([[0,0],[0,7]], endcap2="arrow2");
711// Example(2D): Alignment by Side
712// pentagon(r=30, align_side=BACK+RIGHT)
713// attach("side0", FWD) color("blue")
714// stroke([[0,0],[0,7]], endcap2="arrow2");
715// Example(2D): Rounded
716// pentagon(od=100, rounding=20, $fn=20);
717// Example(2D): Called as Function
718// stroke(closed=true, pentagon(or=30));
719function pentagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
720 regular_ngon(n=5, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin);
721
722
723module pentagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
724 regular_ngon(n=5, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin) children();
725
726
727// Function&Module: hexagon()
728// Synopsis: Creates a regular hexagon.
729// SynTags: Geom, Path
730// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
731// See Also: circle(), regular_ngon(), pentagon(), octagon(), ellipse(), star()
732// Usage: As Module
733// hexagon(r/or, [realign=], <align_tip=|align_side=>, [rounding=], ...) [ATTACHMENTS];
734// hexagon(d=/od=, ...) [ATTACHMENTS];
735// hexagon(ir=/id=, ...) [ATTACHMENTS];
736// hexagon(side=, ...) [ATTACHMENTS];
737// Usage: As Function
738// path = hexagon(...);
739// Description:
740// When called as a function, returns a 2D path for a regular hexagon.
741// When called as a module, creates a 2D regular hexagon.
742// Arguments:
743// r/or = Outside radius, at points.
744// ---
745// d/od = Outside diameter, at points.
746// ir = Inside radius, at center of sides.
747// id = Inside diameter, at center of sides.
748// side = Length of each side.
749// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
750// realign = If false, vertex 0 will lie on the X+ axis. If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis. Default: false
751// align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction. This occurs before spin.
752// align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction. This occurs before spin.
753// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
754// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
755// Extra Anchors:
756// "tip0" ... "tip5" = Each tip has an anchor, pointing outwards.
757// "side0" ... "side5" = The center of each side has an anchor, pointing outwards.
758// Example(2D): by Outer Size
759// hexagon(or=30);
760// hexagon(od=60);
761// Example(2D): by Inner Size
762// hexagon(ir=30);
763// hexagon(id=60);
764// Example(2D): by Side Length
765// hexagon(side=20);
766// Example(2D): Realigned
767// hexagon(side=20, realign=true);
768// Example(2D): Alignment by Tip
769// hexagon(r=30, align_tip=BACK+RIGHT)
770// attach("tip0", FWD) color("blue")
771// stroke([[0,0],[0,7]], endcap2="arrow2");
772// Example(2D): Alignment by Side
773// hexagon(r=30, align_side=BACK+RIGHT)
774// attach("side0", FWD) color("blue")
775// stroke([[0,0],[0,7]], endcap2="arrow2");
776// Example(2D): Rounded
777// hexagon(od=100, rounding=20, $fn=20);
778// Example(2D): Called as Function
779// stroke(closed=true, hexagon(or=30));
780function hexagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
781 regular_ngon(n=6, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin);
782
783
784module hexagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
785 regular_ngon(n=6, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin) children();
786
787
788// Function&Module: octagon()
789// Synopsis: Creates a regular octagon.
790// SynTags: Geom, Path
791// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
792// See Also: circle(), regular_ngon(), pentagon(), hexagon(), ellipse(), star()
793// Usage: As Module
794// octagon(r/or, [realign=], [align_tip=|align_side=], [rounding=], ...) [ATTACHMENTS];
795// octagon(d=/od=, ...) [ATTACHMENTS];
796// octagon(ir=/id=, ...) [ATTACHMENTS];
797// octagon(side=, ...) [ATTACHMENTS];
798// Usage: As Function
799// path = octagon(...);
800// Description:
801// When called as a function, returns a 2D path for a regular octagon.
802// When called as a module, creates a 2D regular octagon.
803// Arguments:
804// r/or = Outside radius, at points.
805// d/od = Outside diameter, at points.
806// ir = Inside radius, at center of sides.
807// id = Inside diameter, at center of sides.
808// side = Length of each side.
809// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
810// realign = If false, vertex 0 will lie on the X+ axis. If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis. Default: false
811// align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction. This occurs before spin.
812// align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction. This occurs before spin.
813// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
814// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
815// Extra Anchors:
816// "tip0" ... "tip7" = Each tip has an anchor, pointing outwards.
817// "side0" ... "side7" = The center of each side has an anchor, pointing outwards.
818// Example(2D): by Outer Size
819// octagon(or=30);
820// octagon(od=60);
821// Example(2D): by Inner Size
822// octagon(ir=30);
823// octagon(id=60);
824// Example(2D): by Side Length
825// octagon(side=20);
826// Example(2D): Realigned
827// octagon(side=20, realign=true);
828// Example(2D): Alignment by Tip
829// octagon(r=30, align_tip=BACK+RIGHT)
830// attach("tip0", FWD) color("blue")
831// stroke([[0,0],[0,7]], endcap2="arrow2");
832// Example(2D): Alignment by Side
833// octagon(r=30, align_side=BACK+RIGHT)
834// attach("side0", FWD) color("blue")
835// stroke([[0,0],[0,7]], endcap2="arrow2");
836// Example(2D): Rounded
837// octagon(od=100, rounding=20, $fn=20);
838// Example(2D): Called as Function
839// stroke(closed=true, octagon(or=30));
840function octagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
841 regular_ngon(n=8, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin);
842
843
844module octagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
845 regular_ngon(n=8, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin) children();
846
847
848// Function&Module: right_triangle()
849// Synopsis: Creates a right triangle.
850// SynTags: Geom, Path
851// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
852// See Also: square(), rect(), regular_ngon(), pentagon(), hexagon(), octagon(), star()
853// Usage: As Module
854// right_triangle(size, [center], ...) [ATTACHMENTS];
855// Usage: As Function
856// path = right_triangle(size, [center], ...);
857// Description:
858// When called as a module, creates a right triangle with the Hypotenuse in the X+Y+ quadrant.
859// When called as a function, returns a 2D path for a right triangle with the Hypotenuse in the X+Y+ quadrant.
860// Arguments:
861// size = The width and length of the right triangle, given as a scalar or an XY vector.
862// center = If true, forces `anchor=CENTER`. If false, forces `anchor=[-1,-1]`. Default: undef (use `anchor=`)
863// ---
864// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
865// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
866// Extra Anchors:
867// hypot = Center of angled side, perpendicular to that side.
868// Example(2D):
869// right_triangle([40,30]);
870// Example(2D): With `center=true`
871// right_triangle([40,30], center=true);
872// Example(2D): Standard Anchors
873// right_triangle([80,30], center=true)
874// show_anchors(custom=false);
875// color([0.5,0.5,0.5,0.1])
876// square([80,30], center=true);
877// Example(2D): Named Anchors
878// right_triangle([80,30], center=true)
879// show_anchors(std=false);
880function right_triangle(size=[1,1], center, anchor, spin=0) =
881 let(
882 size = is_num(size)? [size,size] : size,
883 anchor = get_anchor(anchor, center, [-1,-1], [-1,-1])
884 )
885 assert(is_vector(size,2))
886 assert(min(size)>0, "Must give positive size")
887 let(
888 path = [ [size.x/2,-size.y/2], [-size.x/2,-size.y/2], [-size.x/2,size.y/2] ],
889 anchors = [
890 named_anchor("hypot", CTR, unit([size.y,size.x])),
891 ]
892 ) reorient(anchor,spin, two_d=true, size=[size.x,size.y], anchors=anchors, p=path);
893
894module right_triangle(size=[1,1], center, anchor, spin=0) {
895 size = is_num(size)? [size,size] : size;
896 anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]);
897 check = assert(is_vector(size,2));
898 path = right_triangle(size, anchor="origin");
899 anchors = [
900 named_anchor("hypot", CTR, unit([size.y,size.x])),
901 ];
902 attachable(anchor,spin, two_d=true, size=[size.x,size.y], anchors=anchors) {
903 polygon(path);
904 children();
905 }
906}
907
908
909// Function&Module: trapezoid()
910// Synopsis: Creates a trapezoid with parallel top and bottom sides.
911// SynTags: Geom, Path
912// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
913// See Also: rect(), square()
914// Usage: As Module
915// trapezoid(h, w1, w2, [shift=], [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
916// trapezoid(h, w1, ang=, [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
917// trapezoid(h, w2=, ang=, [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
918// trapezoid(w1=, w2=, ang=, [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
919// Usage: As Function
920// path = trapezoid(...);
921// Description:
922// When called as a function, returns a 2D path for a trapezoid with parallel front and back (top and bottom) sides.
923// When called as a module, creates a 2D trapezoid. You can specify the trapezoid by giving its height and the lengths
924// of its two bases. Alternatively, you can omit one of those parameters and specify the lower angle(s).
925// The shift parameter, which cannot be combined with ang, shifts the back (top) of the trapezoid to the right.
926// Arguments:
927// h = The Y axis height of the trapezoid.
928// w1 = The X axis width of the front end of the trapezoid.
929// w2 = The X axis width of the back end of the trapezoid.
930// ---
931// ang = Specify the bottom angle(s) of the trapezoid. Can give a scalar for an isosceles trapezoid or a list of two angles, the left angle and right angle. You must omit one of `h`, `w1`, or `w2` to allow the freedom to control the angles.
932// shift = Scalar value to shift the back of the trapezoid along the X axis by. Cannot be combined with ang. Default: 0
933// rounding = The rounding radius for the corners. If given as a list of four numbers, gives individual radii for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: 0 (no rounding)
934// chamfer = The Length of the chamfer faces at the corners. If given as a list of four numbers, gives individual chamfers for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: 0 (no chamfer)
935// flip = If true, negative roundings and chamfers will point forward and back instead of left and right. Default: `false`.
936// atype = The type of anchoring to use with `anchor=`. Valid opptions are "box" and "perim". This lets you choose between putting anchors on the rounded or chamfered perimeter, or on the square bounding box of the shape. Default: "box"
937// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
938// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
939// Anchor Types:
940// box = Anchor is with respect to the rectangular bounding box of the shape.
941// perim = Anchors are placed along the rounded or chamfered perimeter of the shape.
942// Examples(2D):
943// trapezoid(h=30, w1=40, w2=20);
944// trapezoid(h=25, w1=20, w2=35);
945// trapezoid(h=20, w1=40, w2=0);
946// trapezoid(h=20, w1=30, ang=60);
947// trapezoid(h=20, w1=20, ang=120);
948// trapezoid(h=20, w2=10, ang=60);
949// trapezoid(h=20, w1=50, ang=[40,60]);
950// trapezoid(w1=30, w2=10, ang=[30,90]);
951// Example(2D): Chamfered Trapezoid
952// trapezoid(h=30, w1=60, w2=40, chamfer=5);
953// Example(2D): Negative Chamfered Trapezoid
954// trapezoid(h=30, w1=60, w2=40, chamfer=-5);
955// Example(2D): Flipped Negative Chamfered Trapezoid
956// trapezoid(h=30, w1=60, w2=40, chamfer=-5, flip=true);
957// Example(2D): Rounded Trapezoid
958// trapezoid(h=30, w1=60, w2=40, rounding=5);
959// Example(2D): Negative Rounded Trapezoid
960// trapezoid(h=30, w1=60, w2=40, rounding=-5);
961// Example(2D): Flipped Negative Rounded Trapezoid
962// trapezoid(h=30, w1=60, w2=40, rounding=-5, flip=true);
963// Example(2D): Mixed Chamfering and Rounding
964// trapezoid(h=30, w1=60, w2=40, rounding=[5,0,-10,0],chamfer=[0,8,0,-15],$fa=1,$fs=1);
965// Example(2D): default anchors for roundings
966// trapezoid(h=30, w1=100, ang=[66,44],rounding=5) show_anchors();
967// Example(2D): default anchors for negative roundings are still at the trapezoid corners
968// trapezoid(h=30, w1=100, ang=[66,44],rounding=-5) show_anchors();
969// Example(2D): "perim" anchors are at the tips of negative roundings
970// trapezoid(h=30, w1=100, ang=[66,44],rounding=-5, atype="perim") show_anchors();
971// Example(2D): They point the other direction if you flip them
972// trapezoid(h=30, w1=100, ang=[66,44],rounding=-5, atype="perim",flip=true) show_anchors();
973// Example(2D): Called as Function
974// stroke(closed=true, trapezoid(h=30, w1=40, w2=20));
975
976function _trapezoid_dims(h,w1,w2,shift,ang) =
977 let(
978 h = is_def(h)? h
979 : num_defined([w1,w2,each ang])==4 ? (w1-w2) * sin(ang[0]) * sin(ang[1]) / sin(ang[0]+ang[1])
980 : undef
981 )
982 is_undef(h) ? [h]
983 :
984 let(
985 x1 = is_undef(ang[0]) || ang[0]==90 ? 0 : h/tan(ang[0]),
986 x2 = is_undef(ang[1]) || ang[1]==90 ? 0 : h/tan(ang[1]),
987 w1 = is_def(w1)? w1
988 : is_def(w2) && is_def(ang[0]) ? w2 + x1 + x2
989 : undef,
990 w2 = is_def(w2)? w2
991 : is_def(w1) && is_def(ang[0]) ? w1 - x1 - x2
992 : undef,
993 shift = first_defined([shift,(x1-x2)/2])
994 )
995 [h,w1,w2,shift];
996
997
998
999function trapezoid(h, w1, w2, ang, shift, chamfer=0, rounding=0, flip=false, anchor=CENTER, spin=0,atype="box", _return_override, angle) =
1000 assert(is_undef(angle), "The angle parameter has been replaced by ang, which specifies trapezoid interior angle")
1001 assert(is_undef(h) || is_finite(h))
1002 assert(is_undef(w1) || is_finite(w1))
1003 assert(is_undef(w2) || is_finite(w2))
1004 assert(is_undef(ang) || is_finite(ang) || is_vector(ang,2))
1005 assert(num_defined([h, w1, w2, ang]) == 3, "Must give exactly 3 of the arguments h, w1, w2, and angle.")
1006 assert(is_undef(shift) || is_finite(shift))
1007 assert(num_defined([shift,ang])<2, "Cannot specify shift and ang together")
1008 assert(is_finite(chamfer) || is_vector(chamfer,4))
1009 assert(is_finite(rounding) || is_vector(rounding,4))
1010 let(
1011 ang = force_list(ang,2),
1012 angOK = len(ang)==2 && (ang==[undef,undef] || (all_positive(ang) && ang[0]<180 && ang[1]<180))
1013 )
1014 assert(angOK, "trapezoid angles must be scalar or 2-vector, strictly between 0 and 180")
1015 let(
1016 h_w1_w2_shift = _trapezoid_dims(h,w1,w2,shift,ang),
1017 h = h_w1_w2_shift[0],
1018 w1 = h_w1_w2_shift[1],
1019 w2 = h_w1_w2_shift[2],
1020 shift = h_w1_w2_shift[3],
1021 chamfer = force_list(chamfer,4),
1022 rounding = force_list(rounding,4)
1023 )
1024 assert(all_zero(v_mul(chamfer,rounding),0), "Cannot specify chamfer and rounding at the same corner")
1025 let(
1026 srads = chamfer+rounding,
1027 rads = v_abs(srads)
1028 )
1029 assert(w1>=0 && w2>=0 && h>0, "Degenerate trapezoid geometry.")
1030 assert(w1+w2>0, "Degenerate trapezoid geometry.")
1031 let(
1032 base = [
1033 [ w2/2+shift, h/2],
1034 [-w2/2+shift, h/2],
1035 [-w1/2,-h/2],
1036 [ w1/2,-h/2],
1037 ],
1038 ang1 = v_theta(base[0]-base[3])-90,
1039 ang2 = v_theta(base[1]-base[2])-90,
1040 angs = [ang1, ang2, ang2, ang1],
1041 qdirs = [[1,1], [-1,1], [-1,-1], [1,-1]],
1042 hyps = [for (i=[0:3]) adj_ang_to_hyp(rads[i],angs[i])],
1043 offs = [
1044 for (i=[0:3]) let(
1045 xoff = adj_ang_to_opp(rads[i],angs[i]),
1046 a = [xoff, -rads[i]] * qdirs[i].y * (srads[i]<0 && flip? -1 : 1),
1047 b = a + [hyps[i] * qdirs[i].x * (srads[i]<0 && !flip? 1 : -1), 0]
1048 ) b
1049 ],
1050 corners = [
1051 (
1052 let(i = 0)
1053 rads[i] == 0? [base[i]]
1054 : srads[i] > 0? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[angs[i], 90], r=rads[i])
1055 : flip? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[angs[i],-90], r=rads[i])
1056 : arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[180+angs[i],90], r=rads[i])
1057 ),
1058 (
1059 let(i = 1)
1060 rads[i] == 0? [base[i]]
1061 : srads[i] > 0? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[90,180+angs[i]], r=rads[i])
1062 : flip? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[270,180+angs[i]], r=rads[i])
1063 : arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[90,angs[i]], r=rads[i])
1064 ),
1065 (
1066 let(i = 2)
1067 rads[i] == 0? [base[i]]
1068 : srads[i] > 0? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[180+angs[i],270], r=rads[i])
1069 : flip? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[180+angs[i],90], r=rads[i])
1070 : arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[angs[i],-90], r=rads[i])
1071 ),
1072 (
1073 let(i = 3)
1074 rads[i] == 0? [base[i]]
1075 : srads[i] > 0? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[-90,angs[i]], r=rads[i])
1076 : flip? arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[90,angs[i]], r=rads[i])
1077 : arc(n=rounding[i]?undef:2, cp=base[i]+offs[i], angle=[270,180+angs[i]], r=rads[i])
1078 ),
1079 ],
1080 path = reverse(flatten(corners)),
1081 override = [for(i=[0:3])
1082 if (atype!="box" && srads[i]!=0)
1083 srads[i]>0?
1084 let(dir = unit(base[i]-select(base,i-1)) + unit(base[i]-select(base,i+1)),
1085 pt=[for(seg=pair(corners[i])) let(isect=line_intersection(seg, [base[i],base[i]+dir],SEGMENT,LINE))
1086 if (is_def(isect) && isect!=seg[0]) isect]
1087 )
1088 [qdirs[i], [pt[0], undef]]
1089 : flip?
1090 let( dir=unit(base[i] - select(base,i+(i%2==0?-1:1))))
1091 [qdirs[i], [select(corners[i],i%2==0?0:-1), dir]]
1092 : let( dir = [qdirs[i].x,0])
1093 [qdirs[i], [select(corners[i],i%2==0?-1:0), dir]]]
1094 ) _return_override ? [reorient(anchor,spin, two_d=true, size=[w1,h], size2=w2, shift=shift, p=path, override=override),override]
1095 : reorient(anchor,spin, two_d=true, size=[w1,h], size2=w2, shift=shift, p=path, override=override);
1096
1097
1098
1099
1100module trapezoid(h, w1, w2, ang, shift, chamfer=0, rounding=0, flip=false, anchor=CENTER, spin=0, atype="box", angle) {
1101 path_over = trapezoid(h=h, w1=w1, w2=w2, ang=ang, shift=shift, chamfer=chamfer, rounding=rounding,
1102 flip=flip, angle=angle,atype=atype,anchor="origin",_return_override=true);
1103 path=path_over[0];
1104 override = path_over[1];
1105 ang = force_list(ang,2);
1106 h_w1_w2_shift = _trapezoid_dims(h,w1,w2,shift,ang);
1107 h = h_w1_w2_shift[0];
1108 w1 = h_w1_w2_shift[1];
1109 w2 = h_w1_w2_shift[2];
1110 shift = h_w1_w2_shift[3];
1111 attachable(anchor,spin, two_d=true, size=[w1,h], size2=w2, shift=shift, override=override) {
1112 polygon(path);
1113 children();
1114 }
1115}
1116
1117
1118
1119// Function&Module: star()
1120// Synopsis: Creates a star-shaped polygon or returns a star-shaped region.
1121// SynTags: Geom, Path
1122// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1123// See Also: circle(), ellipse(), regular_ngon()
1124// Usage: As Module
1125// star(n, r/or, ir, [realign=], [align_tip=], [align_pit=], ...) [ATTACHMENTS];
1126// star(n, r/or, step=, ...) [ATTACHMENTS];
1127// Usage: As Function
1128// path = star(n, r/or, ir, [realign=], [align_tip=], [align_pit=], ...);
1129// path = star(n, r/or, step=, ...);
1130// Description:
1131// When called as a function, returns the path needed to create a star polygon with N points.
1132// When called as a module, creates a star polygon with N points.
1133// Arguments:
1134// n = The number of stellate tips on the star.
1135// r/or = The radius to the tips of the star.
1136// ir = The radius to the inner corners of the star.
1137// ---
1138// d/od = The diameter to the tips of the star.
1139// id = The diameter to the inner corners of the star.
1140// step = Calculates the radius of the inner star corners by virtually drawing a straight line `step` tips around the star. 2 <= step < n/2
1141// realign = If false, vertex 0 will lie on the X+ axis. If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis. Default: false
1142// align_tip = If given as a 2D vector, rotates the whole shape so that the first star tip points in that direction. This occurs before spin.
1143// align_pit = If given as a 2D vector, rotates the whole shape so that the first inner corner is pointed towards that direction. This occurs before spin.
1144// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
1145// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
1146// atype = Choose "hull" or "intersect" anchor methods. Default: "hull"
1147// Extra Anchors:
1148// "tip0" ... "tip4" = Each tip has an anchor, pointing outwards.
1149// "pit0" ... "pit4" = The inside corner between each tip has an anchor, pointing outwards.
1150// "midpt0" ... "midpt4" = The center-point between each pair of tips has an anchor, pointing outwards.
1151// Examples(2D):
1152// star(n=5, r=50, ir=25);
1153// star(n=5, r=50, step=2);
1154// star(n=7, r=50, step=2);
1155// star(n=7, r=50, step=3);
1156// Example(2D): Realigned
1157// star(n=7, r=50, step=3, realign=true);
1158// Example(2D): Alignment by Tip
1159// star(n=5, ir=15, or=30, align_tip=BACK+RIGHT)
1160// attach("tip0", FWD) color("blue")
1161// stroke([[0,0],[0,7]], endcap2="arrow2");
1162// Example(2D): Alignment by Pit
1163// star(n=5, ir=15, or=30, align_pit=BACK+RIGHT)
1164// attach("pit0", FWD) color("blue")
1165// stroke([[0,0],[0,7]], endcap2="arrow2");
1166// Example(2D): Called as Function
1167// stroke(closed=true, star(n=5, r=50, ir=25));
1168function star(n, r, ir, d, or, od, id, step, realign=false, align_tip, align_pit, anchor=CENTER, spin=0, atype="hull", _mat, _anchs) =
1169 assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"")
1170 assert(is_undef(align_tip) || is_vector(align_tip))
1171 assert(is_undef(align_pit) || is_vector(align_pit))
1172 assert(is_undef(align_tip) || is_undef(align_pit), "Can only specify one of align_tip and align_pit")
1173 assert(is_def(n), "Must specify number of points, n")
1174 let(
1175 r = get_radius(r1=or, d1=od, r=r, d=d),
1176 count = num_defined([ir,id,step]),
1177 stepOK = is_undef(step) || (step>1 && step<n/2)
1178 )
1179 assert(count==1, "Must specify exactly one of ir, id, step")
1180 assert(stepOK, n==4 ? "Parameter 'step' not allowed for 4 point stars"
1181 : n==5 || n==6 ? str("Parameter 'step' must be 2 for ",n," point stars")
1182 : str("Parameter 'step' must be between 2 and ",floor(n/2-1/2)," for ",n," point stars"))
1183 let(
1184 mat = !is_undef(_mat) ? _mat :
1185 ( realign? zrot(-180/n) : ident(4) ) * (
1186 !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
1187 !is_undef(align_pit)? rot(from=RIGHT, to=point2d(align_pit)) * zrot(180/n) :
1188 1
1189 ),
1190 stepr = is_undef(step)? r : r*cos(180*step/n)/cos(180*(step-1)/n),
1191 ir = get_radius(r=ir, d=id, dflt=stepr),
1192 offset = realign? 180/n : 0,
1193 path1 = [for(i=[2*n:-1:1]) let(theta=180*i/n, radius=(i%2)?ir:r) radius*[cos(theta), sin(theta)]],
1194 path = apply(mat, path1),
1195 anchors = !is_undef(_anchs) ? _anchs :
1196 !is_string(anchor)? [] : [
1197 for (i = [0:1:n-1]) let(
1198 a1 = 360 - i*360/n,
1199 a2 = a1 - 180/n,
1200 a3 = a1 - 360/n,
1201 p1 = apply(mat, polar_to_xy(r,a1)),
1202 p2 = apply(mat, polar_to_xy(ir,a2)),
1203 p3 = apply(mat, polar_to_xy(r,a3)),
1204 pos = (p1+p3)/2
1205 ) each [
1206 named_anchor(str("tip",i), p1, unit(p1,BACK), 0),
1207 named_anchor(str("pit",i), p2, unit(p2,BACK), 0),
1208 named_anchor(str("midpt",i), pos, unit(pos,BACK), 0),
1209 ]
1210 ]
1211 ) reorient(anchor,spin, two_d=true, path=path, p=path, extent=atype=="hull", anchors=anchors);
1212
1213
1214module star(n, r, ir, d, or, od, id, step, realign=false, align_tip, align_pit, anchor=CENTER, spin=0, atype="hull") {
1215 checks =
1216 assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"")
1217 assert(is_undef(align_tip) || is_vector(align_tip))
1218 assert(is_undef(align_pit) || is_vector(align_pit))
1219 assert(is_undef(align_tip) || is_undef(align_pit), "Can only specify one of align_tip and align_pit");
1220 r = get_radius(r1=or, d1=od, r=r, d=d, dflt=undef);
1221 stepr = is_undef(step)? r : r*cos(180*step/n)/cos(180*(step-1)/n);
1222 ir = get_radius(r=ir, d=id, dflt=stepr);
1223 mat = ( realign? zrot(-180/n) : ident(4) ) * (
1224 !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
1225 !is_undef(align_pit)? rot(from=RIGHT, to=point2d(align_pit)) * zrot(180/n) :
1226 1
1227 );
1228 anchors = [
1229 for (i = [0:1:n-1]) let(
1230 a1 = 360 - i*360/n - (realign? 180/n : 0),
1231 a2 = a1 - 180/n,
1232 a3 = a1 - 360/n,
1233 p1 = apply(mat, polar_to_xy(r,a1)),
1234 p2 = apply(mat, polar_to_xy(ir,a2)),
1235 p3 = apply(mat, polar_to_xy(r,a3)),
1236 pos = (p1+p3)/2
1237 ) each [
1238 named_anchor(str("tip",i), p1, unit(p1,BACK), 0),
1239 named_anchor(str("pit",i), p2, unit(p2,BACK), 0),
1240 named_anchor(str("midpt",i), pos, unit(pos,BACK), 0),
1241 ]
1242 ];
1243 path = star(n=n, r=r, ir=ir, realign=realign, _mat=mat, _anchs=anchors);
1244 attachable(anchor,spin, two_d=true, path=path, extent=atype=="hull", anchors=anchors) {
1245 polygon(path);
1246 children();
1247 }
1248}
1249
1250
1251
1252/// Internal Function: _path_add_jitter()
1253/// Topics: Paths
1254/// See Also: jittered_poly()
1255/// Usage:
1256/// jpath = _path_add_jitter(path, [dist], [closed=]);
1257/// Description:
1258/// Adds tiny jitter offsets to collinear points in the given path so that they
1259/// are no longer collinear. This is useful for preserving subdivision on long
1260/// straight segments, when making geometry with `polygon()`, for use with
1261/// `linear_exrtrude()` with a `twist()`.
1262/// Arguments:
1263/// path = The path to add jitter to.
1264/// dist = The amount to jitter points by. Default: 1/512 (0.00195)
1265/// ---
1266/// closed = If true, treat path like a closed polygon. Default: true
1267/// Example(3D):
1268/// d = 100; h = 75; quadsize = 5;
1269/// path = pentagon(d=d);
1270/// spath = subdivide_path(path, maxlen=quadsize, closed=true);
1271/// jpath = _path_add_jitter(spath, closed=true);
1272/// linear_extrude(height=h, twist=72, slices=h/quadsize)
1273/// polygon(jpath);
1274function _path_add_jitter(path, dist=1/512, closed=true) =
1275 assert(is_path(path))
1276 assert(is_finite(dist))
1277 assert(is_bool(closed))
1278 [
1279 path[0],
1280 for (i=idx(path,s=1,e=closed?-1:-2)) let(
1281 n = line_normal([path[i-1],path[i]])
1282 ) path[i] + n * (is_collinear(select(path,i-1,i+1))? (dist * ((i%2)*2-1)) : 0),
1283 if (!closed) last(path)
1284 ];
1285
1286
1287
1288// Module: jittered_poly()
1289// Synopsis: Creates a polygon with extra points for smoother twisted extrusions.
1290// SynTags: Geom
1291// Topics: Extrusions
1292// See Also: subdivide_path()
1293// Usage:
1294// jittered_poly(path, [dist]);
1295// Description:
1296// Creates a 2D polygon shape from the given path in such a way that any extra
1297// collinear points are not stripped out in the way that `polygon()` normally does.
1298// This is useful for refining the mesh of a `linear_extrude()` with twist.
1299// Arguments:
1300// path = The path to add jitter to.
1301// dist = The amount to jitter points by. Default: 1/512 (0.00195)
1302// Example:
1303// d = 100; h = 75; quadsize = 5;
1304// path = pentagon(d=d);
1305// spath = subdivide_path(path, maxlen=quadsize, closed=true);
1306// linear_extrude(height=h, twist=72, slices=h/quadsize)
1307// jittered_poly(spath);
1308module jittered_poly(path, dist=1/512) {
1309 no_children($children);
1310 polygon(_path_add_jitter(path, dist, closed=true));
1311}
1312
1313
1314// Section: Curved 2D Shapes
1315
1316
1317// Function&Module: teardrop2d()
1318// Synopsis: Creates a 2D teardrop shape.
1319// SynTags: Geom, Path
1320// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1321// See Also: teardrop(), onion()
1322// Description:
1323// When called as a module, makes a 2D teardrop shape. Useful for extruding into 3D printable holes as it limits overhang to 45 degrees. Uses "intersect" style anchoring.
1324// The cap_h parameter truncates the top of the teardrop. If cap_h is taller than the untruncated form then
1325// the result will be the full, untruncated shape. The segments of the bottom section of the teardrop are
1326// calculated to be the same as a circle or cylinder when rotated 90 degrees. (Note that this agreement is poor when `$fn=6` or `$fn=7`.
1327// If `$fn` is a multiple of four then the teardrop will reach its extremes on all four axes. The circum option
1328// produces a teardrop that circumscribes the circle; in this case set `realign=true` to get a teardrop that meets its internal extremes
1329// on the axes.
1330// When called as a function, returns a 2D path to for a teardrop shape.
1331//
1332// Usage: As Module
1333// teardrop2d(r/d=, [ang], [cap_h]) [ATTACHMENTS];
1334// Usage: As Function
1335// path = teardrop2d(r|d=, [ang], [cap_h]);
1336//
1337// Arguments:
1338// r = radius of circular part of teardrop. (Default: 1)
1339// ang = angle of hat walls from the Y axis (half the angle of the peak). (Default: 45 degrees)
1340// cap_h = if given, height above center where the shape will be truncated.
1341// ---
1342// d = diameter of circular portion of bottom. (Use instead of r)
1343// circum = if true, create a circumscribing teardrop. Default: false
1344// realign = if true, change whether bottom of teardrop is a point or a flat. Default: false
1345// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
1346// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
1347//
1348// Example(2D): Typical Shape
1349// teardrop2d(r=30, ang=30);
1350// Example(2D): Crop Cap
1351// teardrop2d(r=30, ang=30, cap_h=40);
1352// Example(2D): Close Crop
1353// teardrop2d(r=30, ang=30, cap_h=20);
1354module teardrop2d(r, ang=45, cap_h, d, circum=false, realign=false, anchor=CENTER, spin=0)
1355{
1356 path = teardrop2d(r=r, d=d, ang=ang, circum=circum, realign=realign, cap_h=cap_h);
1357 attachable(anchor,spin, two_d=true, path=path, extent=false) {
1358 polygon(path);
1359 children();
1360 }
1361}
1362
1363// _extrapt = true causes the point to be duplicated so a teardrop with no cap
1364// has the same point count as one with a cap.
1365
1366function teardrop2d(r, ang=45, cap_h, d, circum=false, realign=false, anchor=CENTER, spin=0, _extrapt=false) =
1367 let(
1368 r = get_radius(r=r, d=d, dflt=1),
1369 minheight = r*sin(ang),
1370 maxheight = r/sin(ang), //cos(90-ang),
1371 pointycap = is_undef(cap_h) || cap_h>=maxheight
1372 )
1373 assert(is_undef(cap_h) || cap_h>=minheight, str("cap_h cannot be less than ",minheight," but it is ",cap_h))
1374 let(
1375 cap = [
1376 pointycap? [0,maxheight] : [(maxheight-cap_h)*tan(ang), cap_h],
1377 r*[cos(ang),sin(ang)]
1378 ],
1379 fullcircle = ellipse(r=r, realign=realign, circum=circum,spin=90),
1380
1381 // Chose the point on the circle that is lower than the cap but also creates a segment bigger than
1382 // seglen/skipfactor so we don't have a teeny tiny segment at the end of the cap, except for the hexagoin
1383 // case which is treated specially
1384 skipfactor = len(fullcircle)==6 ? 15 : 3,
1385 path = !circum ?
1386 let(seglen = norm(fullcircle[0]-fullcircle[1]))
1387 [
1388 each cap,
1389 for (p=fullcircle)
1390 if (
1391 p.y<last(cap).y-EPSILON
1392 && norm([abs(p.x)-last(cap).x,p.y-last(cap.y)])>seglen/skipfactor
1393 ) p,
1394 xflip(cap[1]),
1395 if (_extrapt || !pointycap) xflip(cap[0])
1396 ]
1397 : let(
1398 isect = [for(i=[0:1:len(fullcircle)/4])
1399 let(p = line_intersection(cap, select(fullcircle,[i,i+1]), bounded1=RAY, bounded2=SEGMENT))
1400 if (p) [i,p]
1401 ],
1402 i = last(isect)[0],
1403 p = last(isect)[1]
1404 )
1405 [
1406 cap[0],
1407 p,
1408 each select(fullcircle,i+1,-i-1-(realign?1:0)),
1409 xflip(p),
1410 if(_extrapt || !pointycap) xflip(cap[0])
1411 ]
1412 )
1413 reorient(anchor,spin, two_d=true, path=path, p=path, extent=false);
1414
1415
1416
1417// Function&Module: egg()
1418// Synopsis: Creates an egg-shaped 2d object.
1419// SynTags: Geom, Path
1420// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1421// See Also: circle(), ellipse(), glued_circles()
1422// Usage: As Module
1423// egg(length, r1|d1=, r2|d2=, R|D=) [ATTACHMENTS];
1424// Usage: As Function
1425// path = egg(length, r1|d1=, r2|d2=, R|D=);
1426// Description:
1427// When called as a module, constructs an egg-shaped object by connecting two circles with convex arcs that are tangent to the circles.
1428// You specify the length of the egg, the radii of the two circles, and the desired arc radius.
1429// Note that because the side radius, R, is often much larger than the end radii, you may get better
1430// results using `$fs` and `$fa` to control the number of semgments rather than using `$fn`.
1431// This shape may be useful for creating a cam.
1432// When called as a function, returns a 2D path for an egg-shaped object.
1433// Arguments:
1434// length = length of the egg
1435// r1 = radius of the left-hand circle
1436// r2 = radius of the right-hand circle
1437// R = radius of the joining arcs
1438// ---
1439// d1 = diameter of the left-hand circle
1440// d2 = diameter of the right-hand circle
1441// D = diameter of the joining arcs
1442// Extra Anchors:
1443// "left" = center of the left circle
1444// "right" = center of the right circle
1445// Example(2D,NoAxes): This first example shows how the egg is constructed from two circles and two joining arcs.
1446// $fn=100;
1447// color("red") stroke(egg(78,25,12, 60),closed=true);
1448// stroke([left(14,circle(25)),
1449// right(27,circle(12))]);
1450// Example(2D,Anim,VPD=250,VPR=[0,0,0]): Varying length between circles
1451// r1 = 25; r2 = 12; R = 65;
1452// length = floor(lookup($t, [[0,55], [0.5,90], [1,55]]));
1453// egg(length,r1,r2,R,$fn=180);
1454// color("black") text(str("length=",length), size=8, halign="center", valign="center");
1455// Example(2D,Anim,VPD=250,VPR=[0,0,0]): Varying tangent arc radius R
1456// length = 78; r1 = 25; r2 = 12;
1457// R = floor(lookup($t, [[0,45], [0.5,150], [1,45]]));
1458// egg(length,r1,r2,R,$fn=180);
1459// color("black") text(str("R=",R), size=8, halign="center", valign="center");
1460// Example(2D,Anim,VPD=250,VPR=[0,0,0]): Varying circle radius r2
1461// length = 78; r1 = 25; R = 65;
1462// r2 = floor(lookup($t, [[0,5], [0.5,30], [1,5]]));
1463// egg(length,r1,r2,R,$fn=180);
1464// color("black") text(str("r2=",r2), size=8, halign="center", valign="center");
1465function egg(length, r1, r2, R, d1, d2, D, anchor=CENTER, spin=0) =
1466 let(
1467 r1 = get_radius(r1=r1,d1=d1),
1468 r2 = get_radius(r1=r2,d1=d2),
1469 D = get_radius(r1=R, d1=D)
1470 )
1471 assert(length>0)
1472 assert(R>length/2, "Side radius R must be larger than length/2")
1473 assert(length>r1+r2, "Length must be longer than 2*(r1+r2)")
1474 assert(length>2*r2, "Length must be longer than 2*r2")
1475 assert(length>2*r1, "Length must be longer than 2*r1")
1476 let(
1477 c1 = [-length/2+r1,0],
1478 c2 = [length/2-r2,0],
1479 Rmin = (r1+r2+norm(c1-c2))/2,
1480 Mlist = circle_circle_intersection(R-r1, c1, R-r2, c2),
1481 arcparms = reverse([for(M=Mlist) [M, c1+r1*unit(c1-M), c2+r2*unit(c2-M)]]),
1482 path = concat(
1483 arc(r=r2, cp=c2, points=[[length/2,0],arcparms[0][2]],endpoint=false),
1484 arc(r=R, cp=arcparms[0][0], points=select(arcparms[0],[2,1]),endpoint=false),
1485 arc(r=r1, points=[arcparms[0][1], [-length/2,0], arcparms[1][1]],endpoint=false),
1486 arc(r=R, cp=arcparms[1][0], points=select(arcparms[1],[1,2]),endpoint=false),
1487 arc(r=r2, cp=c2, points=[arcparms[1][2], [length/2,0]],endpoint=false)
1488 ),
1489 anchors = [named_anchor("left", c1, BACK, 0),
1490 named_anchor("right", c2, BACK, 0)]
1491 )
1492 reorient(anchor, spin, two_d=true, path=path, extent=true, p=path, anchors=anchors);
1493
1494module egg(length,r1,r2,R,d1,d2,D,anchor=CENTER, spin=0)
1495{
1496 path = egg(length,r1,r2,R,d1,d2,D);
1497 anchors = [named_anchor("left", [-length/2+r1,0], BACK, 0),
1498 named_anchor("right", [length/2-r2,0], BACK, 0)];
1499 attachable(anchor, spin, two_d=true, path=path, extent=true, anchors=anchors){
1500 polygon(path);
1501 children();
1502 }
1503}
1504
1505
1506
1507// Function&Module: glued_circles()
1508// Synopsis: Creates a shape of two circles joined by a curved waist.
1509// SynTags: Geom, Path
1510// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1511// See Also: circle(), ellipse(), egg()
1512// Usage: As Module
1513// glued_circles(r/d=, [spread], [tangent], ...) [ATTACHMENTS];
1514// Usage: As Function
1515// path = glued_circles(r/d=, [spread], [tangent], ...);
1516// Description:
1517// When called as a function, returns a 2D path forming a shape of two circles joined by curved waist.
1518// When called as a module, creates a 2D shape of two circles joined by curved waist. Uses "hull" style anchoring.
1519// Arguments:
1520// r = The radius of the end circles.
1521// spread = The distance between the centers of the end circles. Default: 10
1522// tangent = The angle in degrees of the tangent point for the joining arcs, measured away from the Y axis. Default: 30
1523// ---
1524// d = The diameter of the end circles.
1525// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
1526// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
1527// Examples(2D):
1528// glued_circles(r=15, spread=40, tangent=45);
1529// glued_circles(d=30, spread=30, tangent=30);
1530// glued_circles(d=30, spread=30, tangent=15);
1531// glued_circles(d=30, spread=30, tangent=-30);
1532// Example(2D): Called as Function
1533// stroke(closed=true, glued_circles(r=15, spread=40, tangent=45));
1534function glued_circles(r, spread=10, tangent=30, d, anchor=CENTER, spin=0) =
1535 let(
1536 r = get_radius(r=r, d=d, dflt=10),
1537 r2 = (spread/2 / sin(tangent)) - r,
1538 cp1 = [spread/2, 0],
1539 cp2 = [0, (r+r2)*cos(tangent)],
1540 sa1 = 90-tangent,
1541 ea1 = 270+tangent,
1542 lobearc = ea1-sa1,
1543 lobesegs = ceil(segs(r)*lobearc/360),
1544 sa2 = 270-tangent,
1545 ea2 = 270+tangent,
1546 subarc = ea2-sa2,
1547 arcsegs = ceil(segs(r2)*abs(subarc)/360),
1548 // In the tangent zero case the inner curves are missing so we need to complete the two
1549 // outer curves. In the other case the inner curves are present and endpoint=false
1550 // prevents point duplication.
1551 path = tangent==0 ?
1552 concat(arc(n=lobesegs+1, r=r, cp=-cp1, angle=[sa1,ea1]),
1553 arc(n=lobesegs+1, r=r, cp=cp1, angle=[sa1+180,ea1+180]))
1554 :
1555 concat(arc(n=lobesegs, r=r, cp=-cp1, angle=[sa1,ea1], endpoint=false),
1556 [for(theta=lerpn(ea2+180,ea2-subarc+180,arcsegs,endpoint=false)) r2*[cos(theta),sin(theta)] - cp2],
1557 arc(n=lobesegs, r=r, cp=cp1, angle=[sa1+180,ea1+180], endpoint=false),
1558 [for(theta=lerpn(ea2,ea2-subarc,arcsegs,endpoint=false)) r2*[cos(theta),sin(theta)] + cp2]),
1559 maxx_idx = max_index(column(path,0)),
1560 path2 = reverse_polygon(list_rotate(path,maxx_idx))
1561 ) reorient(anchor,spin, two_d=true, path=path2, extent=true, p=path2);
1562
1563
1564module glued_circles(r, spread=10, tangent=30, d, anchor=CENTER, spin=0) {
1565 path = glued_circles(r=r, d=d, spread=spread, tangent=tangent);
1566 attachable(anchor,spin, two_d=true, path=path, extent=true) {
1567 polygon(path);
1568 children();
1569 }
1570}
1571
1572
1573
1574function _superformula(theta,m1,m2,n1,n2=1,n3=1,a=1,b=1) =
1575 pow(pow(abs(cos(m1*theta/4)/a),n2)+pow(abs(sin(m2*theta/4)/b),n3),-1/n1);
1576
1577// Function&Module: supershape()
1578// Synopsis: Creates a 2D [Superformula](https://en.wikipedia.org/wiki/Superformula) shape.
1579// SynTags: Geom, Path
1580// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1581// See Also: circle(), ellipse()
1582// Usage: As Module
1583// supershape([step],[n=], [m1=], [m2=], [n1=], [n2=], [n3=], [a=], [b=], [r=/d=]) [ATTACHMENTS];
1584// Usage: As Function
1585// path = supershape([step], [n=], [m1=], [m2=], [n1=], [n2=], [n3=], [a=], [b=], [r=/d=]);
1586// Description:
1587// When called as a function, returns a 2D path for the outline of the [Superformula](https://en.wikipedia.org/wiki/Superformula) shape.
1588// When called as a module, creates a 2D [Superformula](https://en.wikipedia.org/wiki/Superformula) shape.
1589// Note that the "hull" type anchoring (the default) is more intuitive for concave star-like shapes, but the anchor points do not
1590// necesarily lie on the line of the anchor vector, which can be confusing, especially for simpler, ellipse-like shapes.
1591// Note that the default step angle of 0.5 is very fine and can be slow, but due to the complex curves of the supershape,
1592// many points are often required to give a good result.
1593// Arguments:
1594// step = The angle step size for sampling the superformula shape. Smaller steps are slower but more accurate. Default: 0.5
1595// ---
1596// n = Produce n points as output. Alternative to step. Not to be confused with shape parameters n1 and n2.
1597// m1 = The m1 argument for the superformula. Default: 4.
1598// m2 = The m2 argument for the superformula. Default: m1.
1599// n1 = The n1 argument for the superformula. Default: 1.
1600// n2 = The n2 argument for the superformula. Default: n1.
1601// n3 = The n3 argument for the superformula. Default: n2.
1602// a = The a argument for the superformula. Default: 1.
1603// b = The b argument for the superformula. Default: a.
1604// r = Radius of the shape. Scale shape to fit in a circle of radius r.
1605// d = Diameter of the shape. Scale shape to fit in a circle of diameter d.
1606// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
1607// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
1608// atype = Select "hull" or "intersect" style anchoring. Default: "hull".
1609// Example(2D):
1610// supershape(step=0.5,m1=16,m2=16,n1=0.5,n2=0.5,n3=16,r=50);
1611// Example(2D): Called as Function
1612// stroke(closed=true, supershape(step=0.5,m1=16,m2=16,n1=0.5,n2=0.5,n3=16,d=100));
1613// Examples(2D,Med):
1614// for(n=[2:5]) right(2.5*(n-2)) supershape(m1=4,m2=4,n1=n,a=1,b=2); // Superellipses
1615// m=[2,3,5,7]; for(i=[0:3]) right(2.5*i) supershape(.5,m1=m[i],n1=1);
1616// m=[6,8,10,12]; for(i=[0:3]) right(2.7*i) supershape(.5,m1=m[i],n1=1,b=1.5); // m should be even
1617// m=[1,2,3,5]; for(i=[0:3]) fwd(1.5*i) supershape(m1=m[i],n1=0.4);
1618// supershape(m1=5, n1=4, n2=1); right(2.5) supershape(m1=5, n1=40, n2=10);
1619// m=[2,3,5,7]; for(i=[0:3]) right(2.5*i) supershape(m1=m[i], n1=60, n2=55, n3=30);
1620// n=[0.5,0.2,0.1,0.02]; for(i=[0:3]) right(2.5*i) supershape(m1=5,n1=n[i], n2=1.7);
1621// supershape(m1=2, n1=1, n2=4, n3=8);
1622// supershape(m1=7, n1=2, n2=8, n3=4);
1623// supershape(m1=7, n1=3, n2=4, n3=17);
1624// supershape(m1=4, n1=1/2, n2=1/2, n3=4);
1625// supershape(m1=4, n1=4.0,n2=16, n3=1.5, a=0.9, b=9);
1626// for(i=[1:4]) right(3*i) supershape(m1=i, m2=3*i, n1=2);
1627// m=[4,6,10]; for(i=[0:2]) right(i*5) supershape(m1=m[i], n1=12, n2=8, n3=5, a=2.7);
1628// for(i=[-1.5:3:1.5]) right(i*1.5) supershape(m1=2,m2=10,n1=i,n2=1);
1629// for(i=[1:3],j=[-1,1]) translate([3.5*i,1.5*j])supershape(m1=4,m2=6,n1=i*j,n2=1);
1630// for(i=[1:3]) right(2.5*i)supershape(step=.5,m1=88, m2=64, n1=-i*i,n2=1,r=1);
1631// Examples:
1632// linear_extrude(height=0.3, scale=0) supershape(step=1, m1=6, n1=0.4, n2=0, n3=6);
1633// linear_extrude(height=5, scale=0) supershape(step=1, b=3, m1=6, n1=3.8, n2=16, n3=10);
1634function supershape(step=0.5, n, m1=4, m2, n1=1, n2, n3, a=1, b, r, d,anchor=CENTER, spin=0, atype="hull") =
1635 assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"")
1636 let(
1637 n = first_defined([n, ceil(360/step)]),
1638 angs = lerpn(360,0,n,endpoint=false),
1639 r = get_radius(r=r, d=d, dflt=undef),
1640 m2 = is_def(m2) ? m2 : m1,
1641 n2 = is_def(n2) ? n2 : n1,
1642 n3 = is_def(n3) ? n3 : n2,
1643 b = is_def(b) ? b : a,
1644 // superformula returns r(theta), the point in polar coordinates
1645 rvals = [for (theta = angs) _superformula(theta=theta,m1=m1,m2=m2,n1=n1,n2=n2,n3=n3,a=a,b=b)],
1646 scale = is_def(r) ? r/max(rvals) : 1,
1647 path = [for (i=idx(angs)) scale*rvals[i]*[cos(angs[i]), sin(angs[i])]]
1648 ) reorient(anchor,spin, two_d=true, path=path, p=path, extent=atype=="hull");
1649
1650module supershape(step=0.5,n,m1=4,m2=undef,n1,n2=undef,n3=undef,a=1,b=undef, r=undef, d=undef, anchor=CENTER, spin=0, atype="hull") {
1651 check = assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"");
1652 path = supershape(step=step,n=n,m1=m1,m2=m2,n1=n1,n2=n2,n3=n3,a=a,b=b,r=r,d=d);
1653 attachable(anchor,spin,extent=atype=="hull", two_d=true, path=path) {
1654 polygon(path);
1655 children();
1656 }
1657}
1658
1659
1660// Function&Module: reuleaux_polygon()
1661// Synopsis: Creates a constant-width shape that is not circular.
1662// SynTags: Geom, Path
1663// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1664// See Also: regular_ngon(), pentagon(), hexagon(), octagon()
1665// Usage: As Module
1666// reuleaux_polygon(n, r|d=, ...) [ATTACHMENTS];
1667// Usage: As Function
1668// path = reuleaux_polygon(n, r|d=, ...);
1669// Description:
1670// When called as a module, reates a 2D Reuleaux Polygon; a constant width shape that is not circular. Uses "intersect" type anchoring.
1671// When called as a function, returns a 2D path for a Reulaux Polygon.
1672// Arguments:
1673// n = Number of "sides" to the Reuleaux Polygon. Must be an odd positive number. Default: 3
1674// r = Radius of the shape. Scale shape to fit in a circle of radius r.
1675// ---
1676// d = Diameter of the shape. Scale shape to fit in a circle of diameter d.
1677// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
1678// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
1679// Extra Anchors:
1680// "tip0", "tip1", etc. = Each tip has an anchor, pointing outwards.
1681// Examples(2D):
1682// reuleaux_polygon(n=3, r=50);
1683// reuleaux_polygon(n=5, d=100);
1684// Examples(2D): Standard vector anchors are based on extents
1685// reuleaux_polygon(n=3, d=50) show_anchors(custom=false);
1686// Examples(2D): Named anchors exist for the tips
1687// reuleaux_polygon(n=3, d=50) show_anchors(std=false);
1688module reuleaux_polygon(n=3, r, d, anchor=CENTER, spin=0) {
1689 check = assert(n>=3 && (n%2)==1);
1690 r = get_radius(r=r, d=d, dflt=1);
1691 path = reuleaux_polygon(n=n, r=r);
1692 anchors = [
1693 for (i = [0:1:n-1]) let(
1694 ca = 360 - i * 360/n,
1695 cp = polar_to_xy(r, ca)
1696 ) named_anchor(str("tip",i), cp, unit(cp,BACK), 0),
1697 ];
1698 attachable(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors) {
1699 polygon(path);
1700 children();
1701 }
1702}
1703
1704
1705function reuleaux_polygon(n=3, r, d, anchor=CENTER, spin=0) =
1706 assert(n>=3 && (n%2)==1)
1707 let(
1708 r = get_radius(r=r, d=d, dflt=1),
1709 ssegs = max(3,ceil(segs(r)/n)),
1710 slen = norm(polar_to_xy(r,0)-polar_to_xy(r,180-180/n)),
1711 path = [
1712 for (i = [0:1:n-1]) let(
1713 ca = 180 - (i+0.5) * 360/n,
1714 sa = ca + 180 + (90/n),
1715 ea = ca + 180 - (90/n),
1716 cp = polar_to_xy(r, ca)
1717 ) each arc(n=ssegs-1, r=slen, cp=cp, angle=[sa,ea], endpoint=false)
1718 ],
1719 anchors = [
1720 for (i = [0:1:n-1]) let(
1721 ca = 360 - i * 360/n,
1722 cp = polar_to_xy(r, ca)
1723 ) named_anchor(str("tip",i), cp, unit(cp,BACK), 0),
1724 ]
1725 ) reorient(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors, p=path);
1726
1727
1728
1729// Section: Text
1730
1731// Module: text()
1732// Synopsis: Creates an attachable block of text.
1733// SynTags: Geom
1734// Topics: Attachments, Text
1735// See Also: text3d(), attachable()
1736// Usage:
1737// text(text, [size], [font], ...);
1738// Description:
1739// Creates a 3D text block that can be attached to other attachable objects.
1740// You cannot attach children to text.
1741// .
1742// Historically fonts were specified by their "body size", the height of the metal body
1743// on which the glyphs were cast. This means the size was an upper bound on the size
1744// of the font glyphs, not a direct measurement of their size. In digital typesetting,
1745// the metal body is replaced by an invisible box, the em square, whose side length is
1746// defined to be the font's size. The glyphs can be contained in that square, or they
1747// can extend beyond it, depending on the choices made by the font designer. As a
1748// result, the meaning of font size varies between fonts: two fonts at the "same" size
1749// can differ significantly in the actual size of their characters. Typographers
1750// customarily specify the size in the units of "points". A point is 1/72 inch. In
1751// OpenSCAD, you specify the size in OpenSCAD units (often treated as millimeters for 3d
1752// printing), so if you want points you will need to perform a suitable unit conversion.
1753// In addition, the OpenSCAD font system has a bug: if you specify size=s you will
1754// instead get a font whose size is s/0.72. For many fonts this means the size of
1755// capital letters will be approximately equal to s, because it is common for fonts to
1756// use about 70% of their height for the ascenders in the font. To get the customary
1757// font size, you should multiply your desired size by 0.72.
1758// .
1759// To find the fonts that you have available in your OpenSCAD installation,
1760// go to the Help menu and select "Font List".
1761// Arguments:
1762// text = Text to create.
1763// size = The font will be created at this size divided by 0.72. Default: 10
1764// font = Font to use. Default: "Liberation Sans"
1765// ---
1766// halign = If given, specifies the horizontal alignment of the text. `"left"`, `"center"`, or `"right"`. Overrides `anchor=`.
1767// valign = If given, specifies the vertical alignment of the text. `"top"`, `"center"`, `"baseline"` or `"bottom"`. Overrides `anchor=`.
1768// spacing = The relative spacing multiplier between characters. Default: `1.0`
1769// direction = The text direction. `"ltr"` for left to right. `"rtl"` for right to left. `"ttb"` for top to bottom. `"btt"` for bottom to top. Default: `"ltr"`
1770// language = The language the text is in. Default: `"en"`
1771// script = The script the text is in. Default: `"latin"`
1772// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `"baseline"`
1773// spin = Rotate this many degrees around the Z axis. See [spin](attachments.scad#subsection-spin). Default: `0`
1774// Extra Anchors:
1775// "baseline" = Anchors at the baseline of the text, at the start of the string.
1776// str("baseline",VECTOR) = Anchors at the baseline of the text, modified by the X and Z components of the appended vector.
1777// Examples(2D):
1778// text("Foobar", size=10);
1779// text("Foobar", size=12, font="Helvetica");
1780// text("Foobar", anchor=CENTER);
1781// text("Foobar", anchor=str("baseline",CENTER));
1782// Example: Using line_copies() distributor
1783// txt = "This is the string.";
1784// line_copies(spacing=[10,-5],n=len(txt))
1785// text(txt[$idx], size=10, anchor=CENTER);
1786// Example: Using arc_copies() distributor
1787// txt = "This is the string";
1788// arc_copies(r=50, n=len(txt), sa=0, ea=180)
1789// text(select(txt,-1-$idx), size=10, anchor=str("baseline",CENTER), spin=-90);
1790module text(text, size=10, font="Helvetica", halign, valign, spacing=1.0, direction="ltr", language="en", script="latin", anchor="baseline", spin=0) {
1791 no_children($children);
1792 dummy1 =
1793 assert(is_undef(anchor) || is_vector(anchor) || is_string(anchor), str("Got: ",anchor))
1794 assert(is_undef(spin) || is_vector(spin,3) || is_num(spin), str("Got: ",spin));
1795 anchor = default(anchor, CENTER);
1796 spin = default(spin, 0);
1797 geom = attach_geom(size=[size,size],two_d=true);
1798 anch = !any([for (c=anchor) c=="["])? anchor :
1799 let(
1800 parts = str_split(str_split(str_split(anchor,"]")[0],"[")[1],","),
1801 vec = [for (p=parts) parse_float(str_strip(p," ",start=true))]
1802 ) vec;
1803 ha = halign!=undef? halign :
1804 anchor=="baseline"? "left" :
1805 anchor==anch && is_string(anchor)? "center" :
1806 anch.x<0? "left" :
1807 anch.x>0? "right" :
1808 "center";
1809 va = valign != undef? valign :
1810 starts_with(anchor,"baseline")? "baseline" :
1811 anchor==anch && is_string(anchor)? "center" :
1812 anch.y<0? "bottom" :
1813 anch.y>0? "top" :
1814 "center";
1815 base = anchor=="baseline"? CENTER :
1816 anchor==anch && is_string(anchor)? CENTER :
1817 anch.z<0? BOTTOM :
1818 anch.z>0? TOP :
1819 CENTER;
1820 m = _attach_transform(base,spin,undef,geom);
1821 multmatrix(m) {
1822 $parent_anchor = anchor;
1823 $parent_spin = spin;
1824 $parent_orient = undef;
1825 $parent_geom = geom;
1826 $parent_size = _attach_geom_size(geom);
1827 $attach_to = undef;
1828 if (_is_shown()){
1829 _color($color) {
1830 _text(
1831 text=text, size=size, font=font,
1832 halign=ha, valign=va, spacing=spacing,
1833 direction=direction, language=language,
1834 script=script
1835 );
1836 }
1837 }
1838 }
1839}
1840
1841
1842// Section: Rounding 2D shapes
1843
1844// Module: round2d()
1845// Synopsis: Rounds the corners of 2d objects.
1846// SynTags: Geom
1847// Topics: Rounding
1848// See Also: shell2d(), round3d(), minkowski_difference()
1849// Usage:
1850// round2d(r) [ATTACHMENTS];
1851// round2d(or=) [ATTACHMENTS];
1852// round2d(ir=) [ATTACHMENTS];
1853// round2d(or=, ir=) [ATTACHMENTS];
1854// Description:
1855// Rounds arbitrary 2D objects. Giving `r` rounds all concave and convex corners. Giving just `ir`
1856// rounds just concave corners. Giving just `or` rounds convex corners. Giving both `ir` and `or`
1857// can let you round to different radii for concave and convex corners. The 2D object must not have
1858// any parts narrower than twice the `or` radius. Such parts will disappear.
1859// Arguments:
1860// r = Radius to round all concave and convex corners to.
1861// ---
1862// or = Radius to round only outside (convex) corners to. Use instead of `r`.
1863// ir = Radius to round only inside (concave) corners to. Use instead of `r`.
1864// Examples(2D):
1865// round2d(r=10) {square([40,100], center=true); square([100,40], center=true);}
1866// round2d(or=10) {square([40,100], center=true); square([100,40], center=true);}
1867// round2d(ir=10) {square([40,100], center=true); square([100,40], center=true);}
1868// round2d(or=16,ir=8) {square([40,100], center=true); square([100,40], center=true);}
1869module round2d(r, or, ir)
1870{
1871 or = get_radius(r1=or, r=r, dflt=0);
1872 ir = get_radius(r1=ir, r=r, dflt=0);
1873 offset(or) offset(-ir-or) offset(delta=ir,chamfer=true) children();
1874}
1875
1876
1877// Module: shell2d()
1878// Synopsis: Creates a shell from 2D children.
1879// SynTags: Geom
1880// Topics: Shell
1881// See Also: round2d(), round3d(), minkowski_difference()
1882// Usage:
1883// shell2d(thickness, [or], [ir])
1884// Description:
1885// Creates a hollow shell from 2D children, with optional rounding.
1886// Arguments:
1887// thickness = Thickness of the shell. Positive to expand outward, negative to shrink inward, or a two-element list to do both.
1888// or = Radius to round corners on the outside of the shell. If given a list of 2 radii, [CONVEX,CONCAVE], specifies the radii for convex and concave corners separately. Default: 0 (no outside rounding)
1889// ir = Radius to round corners on the inside of the shell. If given a list of 2 radii, [CONVEX,CONCAVE], specifies the radii for convex and concave corners separately. Default: 0 (no inside rounding)
1890// Examples(2D):
1891// shell2d(10) {square([40,100], center=true); square([100,40], center=true);}
1892// shell2d(-10) {square([40,100], center=true); square([100,40], center=true);}
1893// shell2d([-10,10]) {square([40,100], center=true); square([100,40], center=true);}
1894// shell2d(10,or=10) {square([40,100], center=true); square([100,40], center=true);}
1895// shell2d(10,ir=10) {square([40,100], center=true); square([100,40], center=true);}
1896// shell2d(10,or=[10,0]) {square([40,100], center=true); square([100,40], center=true);}
1897// shell2d(10,or=[0,10]) {square([40,100], center=true); square([100,40], center=true);}
1898// shell2d(10,ir=[10,0]) {square([40,100], center=true); square([100,40], center=true);}
1899// shell2d(10,ir=[0,10]) {square([40,100], center=true); square([100,40], center=true);}
1900// shell2d(8,or=[16,8],ir=[16,8]) {square([40,100], center=true); square([100,40], center=true);}
1901module shell2d(thickness, or=0, ir=0)
1902{
1903 thickness = is_num(thickness)? (
1904 thickness<0? [thickness,0] : [0,thickness]
1905 ) : (thickness[0]>thickness[1])? (
1906 [thickness[1],thickness[0]]
1907 ) : thickness;
1908 orad = is_finite(or)? [or,or] : or;
1909 irad = is_finite(ir)? [ir,ir] : ir;
1910 difference() {
1911 round2d(or=orad[0],ir=orad[1])
1912 offset(delta=thickness[1])
1913 children();
1914 round2d(or=irad[1],ir=irad[0])
1915 offset(delta=thickness[0])
1916 children();
1917 }
1918}
1919
1920
1921// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap