-
Notifications
You must be signed in to change notification settings - Fork 115
/
shapes2d.scad
2182 lines (2071 loc) · 107 KB
/
shapes2d.scad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//////////////////////////////////////////////////////////////////////
// LibFile: shapes2d.scad
// This file includes redefinitions of the core modules to
// work with attachment, and functional forms of those modules
// that produce paths. You can create regular polygons
// with optional rounded corners and alignment features not
// available with circle(). The file also provides teardrop2d,
// which is useful for 3D printable holes.
// Many of the commands have module forms that produce geometry and
// function forms that produce a path.
// Includes:
// include <BOSL2/std.scad>
// FileGroup: Basic Modeling
// FileSummary: Attachable circles, squares, polygons, teardrop. Can make geometry or paths.
// FileFootnotes: STD=Included in std.scad
//////////////////////////////////////////////////////////////////////
use <builtins.scad>
// Section: 2D Primitives
// Function&Module: square()
// Synopsis: Creates a 2D square or rectangle.
// SynTags: Geom, Path, Ext
// Topics: Shapes (2D), Path Generators (2D)
// See Also: rect()
// Usage: As a Module
// square(size, [center], ...);
// Usage: With Attachments
// square(size, [center], ...) [ATTACHMENTS];
// Usage: As a Function
// path = square(size, [center], ...);
// Description:
// When called as the built-in module, creates a 2D square or rectangle of the given size.
// When called as a function, returns a 2D path/list of points for a square/rectangle of the given size.
// Arguments:
// size = The size of the square to create. If given as a scalar, both X and Y will be the same size.
// center = If given and true, overrides `anchor` to be `CENTER`. If given and false, overrides `anchor` to be `FRONT+LEFT`.
// ---
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Example(2D):
// square(40);
// Example(2D): Centered
// square([40,30], center=true);
// Example(2D): Called as Function
// path = square([40,30], anchor=FRONT, spin=30);
// stroke(path, closed=true);
// move_copies(path) color("blue") circle(d=2,$fn=8);
function square(size=1, center, anchor, spin=0) =
let(
anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]),
size = is_num(size)? [size,size] : point2d(size)
)
assert(all_positive(size), "All components of size must be positive.")
let(
path = [
[ size.x,-size.y],
[-size.x,-size.y],
[-size.x, size.y],
[ size.x, size.y],
] / 2
) reorient(anchor,spin, two_d=true, size=size, p=path);
module square(size=1, center, anchor, spin) {
anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]);
rsize = is_num(size)? [size,size] : point2d(size);
size = [for (c = rsize) max(0,c)];
attachable(anchor,spin, two_d=true, size=size) {
if (all_positive(size))
_square(size, center=true);
children();
}
}
// Function&Module: rect()
// Synopsis: Creates a 2d rectangle with optional corner rounding.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: square()
// Usage: As Module
// rect(size, [rounding], [chamfer], ...) [ATTACHMENTS];
// Usage: As Function
// path = rect(size, [rounding], [chamfer], ...);
// Description:
// When called as a module, creates a 2D rectangle of the given size, with optional rounding or chamfering.
// When called as a function, returns a 2D path/list of points for a square/rectangle of the given size.
// Arguments:
// size = The size of the rectangle to create. If given as a scalar, both X and Y will be the same size.
// ---
// 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)
// 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)
// corner_flip = Flips the direction of the rouding curve or roudover and chamfer spikes. If true it produces spikes on the Y axis. If false it produces spikes on the X axis. If given as a list of four booleans it flips the direction for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: false (no flip)
// 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"
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Anchor Types:
// box = Anchor is with respect to the rectangular bounding box of the shape.
// perim = Anchors are placed along the rounded or chamfered perimeter of the shape.
// Example(2D):
// rect(40);
// Example(2D): Anchored
// rect([40,30], anchor=FRONT);
// Example(2D): Spun
// rect([40,30], anchor=FRONT, spin=30);
// Example(2D): Chamferred Rect
// rect([40,30], chamfer=5);
// Example(2D): Rounded Rect
// rect([40,30], rounding=5);
// Example(2D): Negative-Chamferred Rect
// rect([40,30], chamfer=-5);
// Example(2D): Negative-Rounded Rect
// rect([40,30], rounding=-5);
// Example(2D): Combined Rounded-Chamfered Rect with corner flips
// rect([1,1], chamfer = 0.25*[0,1,-1,0],
// rounding=.25*[1,0,0,-1], corner_flip = true, $fn=32);
// Example(2D): Default "box" Anchors
// color("red") rect([40,30]);
// rect([40,30], rounding=10)
// show_anchors();
// Example(2D): "perim" Anchors
// rect([40,30], rounding=10, atype="perim")
// show_anchors();
// Example(2D): "perim" Anchors
// rect([40,30], rounding=[-10,-8,-3,-7], atype="perim")
// show_anchors();
// Example(2D): Mixed Chamferring and Rounding
// rect([40,30],rounding=[5,0,10,0],chamfer=[0,8,0,15],$fa=1,$fs=1);
// Example(2D): Called as Function
// path = rect([40,30], chamfer=5, anchor=FRONT, spin=30);
// stroke(path, closed=true);
// move_copies(path) color("blue") circle(d=2,$fn=8);
module rect(size=1, rounding=0, atype="box", chamfer=0, anchor=CENTER, spin=0, corner_flip = false) {
errchk = assert(in_list(atype, ["box", "perim"]));
size = [for (c = force_list(size,2)) max(0,c)];
if (!all_positive(size)) {
attachable(anchor,spin, two_d=true, size=size) {
union();
children();
}
} else if (rounding==0 && chamfer==0) {
attachable(anchor, spin, two_d=true, size=size) {
square(size, center=true);
children();
}
} else {
pts_over = rect(size=size, rounding=rounding, chamfer=chamfer, atype=atype, corner_flip = corner_flip, _return_override=true);
pts = pts_over[0];
override = pts_over[1];
attachable(anchor, spin, two_d=true, size=size,override=override) {
polygon(pts);
children();
}
}
}
function rect(size=1, rounding=0, chamfer=0, atype="box", anchor=CENTER, spin=0, _return_override, corner_flip = false) =
assert(is_num(size) || is_vector(size,2))
assert(is_num(chamfer) || is_vector(chamfer,4))
assert(is_num(rounding) || is_vector(rounding,4))
assert(in_list(atype, ["box", "perim"]))
let(
anchor=_force_anchor_2d(anchor),
size = [for (c = force_list(size,2)) max(0,c)],
corner_flip = [for (c = force_list(corner_flip,4)) c ? true : false],
chamfer = force_list(chamfer,4),
rounding = force_list(rounding,4)
)
assert(all_nonnegative(size), "All components of size must be >=0")
all_zero(concat(chamfer,rounding),0) ?
let(
path = [
[ size.x/2, -size.y/2],
[-size.x/2, -size.y/2],
[-size.x/2, size.y/2],
[ size.x/2, size.y/2],
]
)
rot(spin, p=move(-v_mul(anchor,size/2), p=path))
:
assert(all_zero(v_mul(chamfer,rounding),0), "Cannot specify chamfer and rounding at the same corner")
let(
quadorder = [3,2,1,0],
quadpos = [[1,1],[-1,1],[-1,-1],[1,-1]],
eps = 1e-9,
insets = [for (i=[0:3]) abs(chamfer[i])>=eps? chamfer[i] : abs(rounding[i])>=eps? rounding[i] : 0],
insets_x = max(insets[0]+insets[1],insets[2]+insets[3]),
insets_y = max(insets[0]+insets[3],insets[1]+insets[2])
)
assert(insets_x <= size.x, "Requested roundings and/or chamfers exceed the rect width.")
assert(insets_y <= size.y, "Requested roundings and/or chamfers exceed the rect height.")
let(
corners = [
for(i = [0:3])
let(
quad = quadorder[i],
qinset = insets[quad],
qpos = quadpos[quad],
qchamf = chamfer[quad],
qround = rounding[quad],
cverts = quant(segs(abs(qinset)),4)/4,
step = 90/cverts,
cp = v_mul(size/2 + (corner_flip[quad] ? (qinset > 0 ? 0 : 1) : -1)*[qinset,abs(qinset)], qpos),
qpts = abs(qchamf) >= eps? [[0,abs(qinset)], [qinset,0]] :
abs(qround) >= eps? [for (j=[0:1:cverts]) let(a=90-j*step) v_mul(polar_to_xy(abs(qinset),a),[sign(qinset),1])] :
[[0,0]],
qfpts = [for (p=qpts) v_mul(p,corner_flip[quad] ? -qpos : qpos)],
qrpts = (corner_flip[quad] && qinset > 0 ? -1 : 1) * qpos.x*qpos.y < 0? reverse(qfpts) : qfpts,
cornerpt = atype=="box" || (qround==0 && qchamf==0) ? undef
: qround<0 || qchamf<0 ? [[0,-qpos.y*min(qround,qchamf)]]
: [for(seg=pair(qrpts)) let(isect=line_intersection(seg, [[0,0],qpos],SEGMENT,LINE)) if (is_def(isect) && isect!=seg[0]) isect]
)
assert(is_undef(cornerpt) || len(cornerpt)==1,"Cannot find corner point to anchor")
[move(cp, p=qrpts), is_undef(cornerpt)? undef : move(cp,p=
(min(chamfer[quad],rounding[quad])<0 && corner_flip[quad] ? [quadpos[quad].x*quadpos[quad].y*cornerpt[0].y, cornerpt[0].x] : cornerpt[0]))]
],
path = deduplicate(flatten(column(corners,0)),closed=true),
override = [for(i=[0:3])
let(quad=quadorder[i])
if (is_def(corners[i][1])) [quadpos[quad], [corners[i][1], min(chamfer[quad],rounding[quad])<0 ? (corner_flip[quad] ? [0, quadpos[quad].y] : [quadpos[quad].x, 0]) : undef]]]
) _return_override ? [reorient(anchor,spin, two_d=true, size=size, p=path, override=override), override]
: reorient(anchor,spin, two_d=true, size=size, p=path, override=override);
// Function&Module: circle()
// Synopsis: Creates the approximation of a circle.
// SynTags: Geom, Path, Ext
// Topics: Shapes (2D), Path Generators (2D)
// See Also: ellipse(), circle_2tangents(), circle_3points()
// Usage: As a Module
// circle(r|d=, ...) [ATTACHMENTS];
// circle(points=) [ATTACHMENTS];
// circle(r|d=, corner=) [ATTACHMENTS];
// Usage: As a Function
// path = circle(r|d=, ...);
// path = circle(points=);
// path = circle(r|d=, corner=);
// Description:
// When called as the built-in module, creates a 2D polygon that approximates a circle of the given size.
// When called as a function, returns a 2D list of points (path) for a polygon that approximates a circle of the given size.
// 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.
// If `points=` is given three 2D points, centers and sizes the circle so that it passes through all three points.
// Arguments:
// r = The radius of the circle to create.
// d = The diameter of the circle to create.
// ---
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Example(2D): By Radius
// circle(r=25);
// Example(2D): By Diameter
// circle(d=50);
// Example(2D): Fit to Three Points
// pts = [[50,25], [25,-25], [-10,0]];
// circle(points=pts);
// color("red") move_copies(pts) circle();
// Example(2D): Fit Tangent to Inside Corner of Two Segments
// path = [[50,25], [-10,0], [25,-25]];
// circle(corner=path, r=15);
// color("red") stroke(path);
// Example(2D): Called as Function
// path = circle(d=50, anchor=FRONT, spin=45);
// stroke(path);
function circle(r, d, points, corner, anchor=CENTER, spin=0) =
assert(is_undef(corner) || (is_path(corner,[2]) && len(corner) == 3))
assert(is_undef(points) || is_undef(corner), "Cannot specify both points and corner.")
let(
data = is_def(points)?
assert(is_path(points,[2]) && len(points) == 3)
assert(is_undef(corner), "Cannot specify corner= when points= is given.")
assert(is_undef(r) && is_undef(d), "Cannot specify r= or d= when points= is given.")
let( c = circle_3points(points) )
assert(!is_undef(c[0]), "Points cannot be collinear.")
let( cp = c[0], r = c[1] )
[cp, r] :
is_def(corner)?
assert(is_path(corner,[2]) && len(corner) == 3)
assert(is_undef(points), "Cannot specify points= when corner= is given.")
let(
r = get_radius(r=r, d=d, dflt=1),
c = circle_2tangents(r=r, pt1=corner[0], pt2=corner[1], pt3=corner[2])
)
assert(c!=undef, "Corner path cannot be collinear.")
let( cp = c[0] )
[cp, r] :
let(
cp = [0, 0],
r = get_radius(r=r, d=d, dflt=1)
) [cp, r],
cp = data[0],
r = data[1]
)
assert(r>0, "Radius/diameter must be positive")
let(
sides = segs(r),
path = [for (i=[0:1:sides-1]) let(a=360-i*360/sides) r*[cos(a),sin(a)]+cp]
) reorient(anchor,spin, two_d=true, r=r, p=path);
module circle(r, d, points, corner, anchor=CENTER, spin=0) {
if (is_path(points)) {
c = circle_3points(points);
check = assert(c!=undef && c[0] != undef, "Points must not be collinear.");
cp = c[0];
r = c[1];
translate(cp) {
attachable(anchor,spin, two_d=true, r=r) {
if (r>0) _circle(r=r);
children();
}
}
} else if (is_path(corner)) {
r = get_radius(r=r, d=d, dflt=1);
c = circle_2tangents(r=r, pt1=corner[0], pt2=corner[1], pt3=corner[2]);
check = assert(c != undef && c[0] != undef, "Points must not be collinear.");
cp = c[0];
translate(cp) {
attachable(anchor,spin, two_d=true, r=r) {
if (r>0) _circle(r=r);
children();
}
}
} else {
r = get_radius(r=r, d=d, dflt=1);
attachable(anchor,spin, two_d=true, r=r) {
if (r>0) _circle(r=r);
children();
}
}
}
// Function&Module: ellipse()
// Synopsis: Creates the approximation of an ellipse or a circle.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: circle(), circle_2tangents(), circle_3points()
// Usage: As a Module
// ellipse(r|d=, [realign=], [circum=], [uniform=], ...) [ATTACHMENTS];
// Usage: As a Function
// path = ellipse(r|d=, [realign=], [circum=], [uniform=], ...);
// Description:
// When called as a module, creates a 2D polygon that approximates a circle or ellipse of the given size.
// 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.
// 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
// attachments to the ellipse will retain their dimensions, whereas scaling a circle with attachments will also scale the attachments.
// If you set `uniform` to true then you will get a polygon with congruent sides whose vertices lie on the ellipse. The `circum` option
// requests a polygon that circumscribes the requested ellipse (so the specified ellipse will fit into the resulting polygon). Note that
// you cannot gives `circum=true` and `uniform=true`.
// Arguments:
// r = Radius of the circle or pair of semiaxes of ellipse
// ---
// d = Diameter of the circle or a pair giving the full X and Y axis lengths.
// 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
// uniform = If true, the polygon that approximates the circle will have segments of equal length. Only works if `circum=false`. Default: false
// 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
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Example(2D): By Radius
// ellipse(r=25);
// Example(2D): By Diameter
// ellipse(d=50);
// Example(2D): Anchoring
// ellipse(d=50, anchor=FRONT);
// Example(2D): Spin
// ellipse(d=50, anchor=FRONT, spin=45);
// Example(NORENDER): Called as Function
// path = ellipse(d=50, anchor=FRONT, spin=45);
// Example(2D,NoAxes): Uniformly sampled hexagon at the top, regular non-uniform one at the bottom
// r=[10,3];
// ydistribute(7){
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
// stroke([ellipse(r=r, $fn=6)],width=0.1,color="red");
// }
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
// stroke([ellipse(r=r, $fn=6,uniform=true)],width=0.1,color="red");
// }
// }
// Example(2D): The realigned hexagons are even more different
// r=[10,3];
// ydistribute(7){
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
// stroke([ellipse(r=r, $fn=6,realign=true)],width=0.1,color="red");
// }
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
// stroke([ellipse(r=r, $fn=6,realign=true,uniform=true)],width=0.1,color="red");
// }
// }
// Example(2D): For odd $fn the result may not look very elliptical:
// r=[10,3];
// ydistribute(7){
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
// stroke([ellipse(r=r, $fn=5,realign=false)],width=0.1,color="red");
// }
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
// stroke([ellipse(r=r, $fn=5,realign=false,uniform=true)],width=0.1,color="red");
// }
// }
// Example(2D): The same ellipse, turned 90 deg, gives a very different result:
// r=[3,10];
// xdistribute(7){
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.1,color="blue");
// stroke([ellipse(r=r, $fn=5,realign=false)],width=0.2,color="red");
// }
// union(){
// stroke([ellipse(r=r, $fn=100)],width=0.1,color="blue");
// stroke([ellipse(r=r, $fn=5,realign=false,uniform=true)],width=0.2,color="red");
// }
// }
module ellipse(r, d, realign=false, circum=false, uniform=false, anchor=CENTER, spin=0)
{
r = force_list(get_radius(r=r, d=d, dflt=1),2);
dummy = assert(is_vector(r,2) && all_positive(r), "Invalid radius or diameter for ellipse");
sides = segs(max(r));
sc = circum? (1 / cos(180/sides)) : 1;
rx = r.x * sc;
ry = r.y * sc;
attachable(anchor,spin, two_d=true, r=[rx,ry]) {
if (uniform) {
check = assert(!circum, "Circum option not allowed when \"uniform\" is true");
polygon(ellipse(r,realign=realign, circum=circum, uniform=true));
}
else if (rx < ry) {
xscale(rx/ry) {
zrot(realign? 180/sides : 0) {
circle(r=ry, $fn=sides);
}
}
} else {
yscale(ry/rx) {
zrot(realign? 180/sides : 0) {
circle(r=rx, $fn=sides);
}
}
}
children();
}
}
// Iterative refinement to produce an inscribed polygon
// in an ellipse whose side lengths are all equal
function _ellipse_refine(a,b,N, _theta=[]) =
len(_theta)==0? _ellipse_refine(a,b,N,lerpn(0,360,N,endpoint=false))
:
let(
pts = [for(t=_theta) [a*cos(t),b*sin(t)]],
lenlist= path_segment_lengths(pts,closed=true),
meanlen = mean(lenlist),
error = lenlist/meanlen
)
all_equal(error,EPSILON) ? pts
:
let(
dtheta = [each deltas(_theta),
360-last(_theta)],
newdtheta = [for(i=idx(dtheta)) dtheta[i]/error[i]],
adjusted = [0,each cumsum(list_head(newdtheta / sum(newdtheta) * 360))]
)
_ellipse_refine(a,b,N,adjusted);
function _ellipse_refine_realign(a,b,N, _theta=[],i=0) =
len(_theta)==0?
_ellipse_refine_realign(a,b,N, count(N-1,180/N,360/N))
:
let(
pts = [for(t=_theta) [a*cos(t),b*sin(t)],
[a*cos(_theta[0]), -b*sin(_theta[0])]],
lenlist= path_segment_lengths(pts,closed=true),
meanlen = mean(lenlist),
error = lenlist/meanlen
)
all_equal(error,EPSILON) ? pts
:
let(
dtheta = [each deltas(_theta),
360-last(_theta)-_theta[0],
2*_theta[0]],
newdtheta = [for(i=idx(dtheta)) dtheta[i]/error[i]],
normdtheta = newdtheta / sum(newdtheta) * 360,
adjusted = cumsum([last(normdtheta)/2, each list_head(normdtheta, -3)])
)
_ellipse_refine_realign(a,b,N,adjusted, i+1);
function ellipse(r, d, realign=false, circum=false, uniform=false, anchor=CENTER, spin=0) =
let(
r = force_list(get_radius(r=r, d=d, dflt=1),2),
sides = segs(max(r))
)
assert(all_positive(r), "All components of the radius must be positive.")
uniform
? assert(!circum, "Circum option not allowed when \"uniform\" is true")
reorient(anchor,spin,
two_d=true, r=[r.x,r.y],
p=realign
? reverse(_ellipse_refine_realign(r.x,r.y,sides))
: reverse_polygon(_ellipse_refine(r.x,r.y,sides))
)
: let(
offset = realign? 180/sides : 0,
sc = circum? (1 / cos(180/sides)) : 1,
rx = r.x * sc,
ry = r.y * sc,
pts = [
for (i=[0:1:sides-1])
let (a = 360-offset-i*360/sides)
[rx*cos(a), ry*sin(a)]
]
) reorient(anchor,spin, two_d=true, r=[rx,ry], p=pts);
// Section: Polygons
// Function&Module: regular_ngon()
// Synopsis: Creates a regular N-sided polygon.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: debug_polygon(), circle(), pentagon(), hexagon(), octagon(), ellipse(), star()
// Usage:
// regular_ngon(n, r|d=|or=|od=, [realign=]) [ATTACHMENTS];
// regular_ngon(n, ir=|id=, [realign=]) [ATTACHMENTS];
// regular_ngon(n, side=, [realign=]) [ATTACHMENTS];
// Description:
// When called as a function, returns a 2D path for a regular N-sided polygon.
// When called as a module, creates a 2D regular N-sided polygon.
// Arguments:
// n = The number of sides.
// r/or = Outside radius, at points.
// ---
// d/od = Outside diameter, at points.
// ir = Inside radius, at center of sides.
// id = Inside diameter, at center of sides.
// side = Length of each side.
// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
// 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
// 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.
// 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.
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Named Anchors:
// "tip0", "tip1", etc. = Each tip has an anchor, pointing outwards.
// "side0", "side1", etc. = The center of each side has an anchor, pointing outwards.
// Example(2D): by Outer Size
// regular_ngon(n=5, or=30);
// regular_ngon(n=5, od=60);
// Example(2D): by Inner Size
// regular_ngon(n=5, ir=30);
// regular_ngon(n=5, id=60);
// Example(2D): by Side Length
// regular_ngon(n=8, side=20);
// Example(2D): Realigned
// regular_ngon(n=8, side=20, realign=true);
// Example(2D): Alignment by Tip
// regular_ngon(n=5, r=30, align_tip=BACK+RIGHT)
// attach("tip0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Alignment by Side
// regular_ngon(n=5, r=30, align_side=BACK+RIGHT)
// attach("side0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Rounded
// regular_ngon(n=5, od=100, rounding=20, $fn=20);
// Example(2D): Called as Function
// stroke(closed=true, regular_ngon(n=6, or=30));
function 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) =
assert(is_int(n) && n>=3)
assert(is_undef(align_tip) || is_vector(align_tip))
assert(is_undef(align_side) || is_vector(align_side))
assert(is_undef(align_tip) || is_undef(align_side), "Can only specify one of align_tip and align-side")
let(
sc = 1/cos(180/n),
ir = is_finite(ir)? ir*sc : undef,
id = is_finite(id)? id*sc : undef,
side = is_finite(side)? side/2/sin(180/n) : undef,
r = get_radius(r1=ir, r2=or, r=r, d1=id, d2=od, d=d, dflt=side)
)
assert(!is_undef(r), "regular_ngon(): need to specify one of r, d, or, od, ir, id, side.")
assert(all_positive([r]), "polygon size must be a positive value")
let(
inset = opp_ang_to_hyp(rounding, (180-360/n)/2),
mat = !is_undef(_mat) ? _mat :
( realign? zrot(-180/n) : ident(4)) * (
!is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
!is_undef(align_side)? rot(from=RIGHT, to=point2d(align_side)) * zrot(180/n) :
1
),
path4 = rounding==0? ellipse(r=r, $fn=n) : (
let(
steps = floor(segs(r)/n),
step = 360/n/steps,
path2 = [
for (i = [0:1:n-1]) let(
a = 360 - i*360/n,
p = polar_to_xy(r-inset, a)
)
each arc(n=steps, cp=p, r=rounding, start=a+180/n, angle=-360/n)
],
maxx_idx = max_index(column(path2,0)),
path3 = list_rotate(path2,maxx_idx)
) path3
),
path = apply(mat, path4),
anchors = !is_undef(_anchs) ? _anchs :
!is_string(anchor)? [] : [
for (i = [0:1:n-1]) let(
a1 = 360 - i*360/n,
a2 = a1 - 360/n,
p1 = apply(mat, polar_to_xy(r,a1)),
p2 = apply(mat, polar_to_xy(r,a2)),
tipp = apply(mat, polar_to_xy(r-inset+rounding,a1)),
pos = (p1+p2)/2
) each [
named_anchor(str("tip",i), tipp, unit(tipp,BACK), 0),
named_anchor(str("side",i), pos, unit(pos,BACK), 0),
]
]
) reorient(anchor,spin, two_d=true, path=path, extent=false, p=path, anchors=anchors);
module regular_ngon(n=6, r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) {
sc = 1/cos(180/n);
ir = is_finite(ir)? ir*sc : undef;
id = is_finite(id)? id*sc : undef;
side = is_finite(side)? side/2/sin(180/n) : undef;
r = get_radius(r1=ir, r2=or, r=r, d1=id, d2=od, d=d, dflt=side);
check = assert(!is_undef(r), "regular_ngon(): need to specify one of r, d, or, od, ir, id, side.")
assert(all_positive([r]), "polygon size must be a positive value");
mat = ( realign? zrot(-180/n) : ident(4) ) * (
!is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
!is_undef(align_side)? rot(from=RIGHT, to=point2d(align_side)) * zrot(180/n) :
1
);
inset = opp_ang_to_hyp(rounding, (180-360/n)/2);
anchors = [
for (i = [0:1:n-1]) let(
a1 = 360 - i*360/n,
a2 = a1 - 360/n,
p1 = apply(mat, polar_to_xy(r,a1)),
p2 = apply(mat, polar_to_xy(r,a2)),
tipp = apply(mat, polar_to_xy(r-inset+rounding,a1)),
pos = (p1+p2)/2
) each [
named_anchor(str("tip",i), tipp, unit(tipp,BACK), 0),
named_anchor(str("side",i), pos, unit(pos,BACK), 0),
]
];
path = regular_ngon(n=n, r=r, rounding=rounding, _mat=mat, _anchs=anchors);
attachable(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors) {
polygon(path);
children();
}
}
// Function&Module: pentagon()
// Synopsis: Creates a regular pentagon.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: circle(), regular_ngon(), hexagon(), octagon(), ellipse(), star()
// Usage:
// pentagon(or|od=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
// pentagon(ir=|id=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
// pentagon(side=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
// Usage: as function
// path = pentagon(...);
// Description:
// When called as a function, returns a 2D path for a regular pentagon.
// When called as a module, creates a 2D regular pentagon.
// Arguments:
// r/or = Outside radius, at points.
// ---
// d/od = Outside diameter, at points.
// ir = Inside radius, at center of sides.
// id = Inside diameter, at center of sides.
// side = Length of each side.
// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
// 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
// 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.
// 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.
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Named Anchors:
// "tip0" ... "tip4" = Each tip has an anchor, pointing outwards.
// "side0" ... "side4" = The center of each side has an anchor, pointing outwards.
// Example(2D): by Outer Size
// pentagon(or=30);
// pentagon(od=60);
// Example(2D): by Inner Size
// pentagon(ir=30);
// pentagon(id=60);
// Example(2D): by Side Length
// pentagon(side=20);
// Example(2D): Realigned
// pentagon(side=20, realign=true);
// Example(2D): Alignment by Tip
// pentagon(r=30, align_tip=BACK+RIGHT)
// attach("tip0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Alignment by Side
// pentagon(r=30, align_side=BACK+RIGHT)
// attach("side0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Rounded
// pentagon(od=100, rounding=20, $fn=20);
// Example(2D): Called as Function
// stroke(closed=true, pentagon(or=30));
function pentagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
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);
module pentagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
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();
// Function&Module: hexagon()
// Synopsis: Creates a regular hexagon.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: circle(), regular_ngon(), pentagon(), octagon(), ellipse(), star()
// Usage: As Module
// hexagon(r/or, [realign=], <align_tip=|align_side=>, [rounding=], ...) [ATTACHMENTS];
// hexagon(d=/od=, ...) [ATTACHMENTS];
// hexagon(ir=/id=, ...) [ATTACHMENTS];
// hexagon(side=, ...) [ATTACHMENTS];
// Usage: As Function
// path = hexagon(...);
// Description:
// When called as a function, returns a 2D path for a regular hexagon.
// When called as a module, creates a 2D regular hexagon.
// Arguments:
// r/or = Outside radius, at points.
// ---
// d/od = Outside diameter, at points.
// ir = Inside radius, at center of sides.
// id = Inside diameter, at center of sides.
// side = Length of each side.
// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
// 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
// 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.
// 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.
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Named Anchors:
// "tip0" ... "tip5" = Each tip has an anchor, pointing outwards.
// "side0" ... "side5" = The center of each side has an anchor, pointing outwards.
// Example(2D): by Outer Size
// hexagon(or=30);
// hexagon(od=60);
// Example(2D): by Inner Size
// hexagon(ir=30);
// hexagon(id=60);
// Example(2D): by Side Length
// hexagon(side=20);
// Example(2D): Realigned
// hexagon(side=20, realign=true);
// Example(2D): Alignment by Tip
// hexagon(r=30, align_tip=BACK+RIGHT)
// attach("tip0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Alignment by Side
// hexagon(r=30, align_side=BACK+RIGHT)
// attach("side0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Rounded
// hexagon(od=100, rounding=20, $fn=20);
// Example(2D): Called as Function
// stroke(closed=true, hexagon(or=30));
function hexagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
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);
module hexagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
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();
// Function&Module: octagon()
// Synopsis: Creates a regular octagon.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: circle(), regular_ngon(), pentagon(), hexagon(), ellipse(), star()
// Usage: As Module
// octagon(r/or, [realign=], [align_tip=|align_side=], [rounding=], ...) [ATTACHMENTS];
// octagon(d=/od=, ...) [ATTACHMENTS];
// octagon(ir=/id=, ...) [ATTACHMENTS];
// octagon(side=, ...) [ATTACHMENTS];
// Usage: As Function
// path = octagon(...);
// Description:
// When called as a function, returns a 2D path for a regular octagon.
// When called as a module, creates a 2D regular octagon.
// Arguments:
// r/or = Outside radius, at points.
// d/od = Outside diameter, at points.
// ir = Inside radius, at center of sides.
// id = Inside diameter, at center of sides.
// side = Length of each side.
// rounding = Radius of rounding for the tips of the polygon. Default: 0 (no rounding)
// 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
// 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.
// 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.
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Named Anchors:
// "tip0" ... "tip7" = Each tip has an anchor, pointing outwards.
// "side0" ... "side7" = The center of each side has an anchor, pointing outwards.
// Example(2D): by Outer Size
// octagon(or=30);
// octagon(od=60);
// Example(2D): by Inner Size
// octagon(ir=30);
// octagon(id=60);
// Example(2D): by Side Length
// octagon(side=20);
// Example(2D): Realigned
// octagon(side=20, realign=true);
// Example(2D): Alignment by Tip
// octagon(r=30, align_tip=BACK+RIGHT)
// attach("tip0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Alignment by Side
// octagon(r=30, align_side=BACK+RIGHT)
// attach("side0", FWD) color("blue")
// stroke([[0,0],[0,7]], endcap2="arrow2");
// Example(2D): Rounded
// octagon(od=100, rounding=20, $fn=20);
// Example(2D): Called as Function
// stroke(closed=true, octagon(or=30));
function octagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
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);
module octagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
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();
// Function&Module: right_triangle()
// Synopsis: Creates a right triangle.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: square(), rect(), regular_ngon(), pentagon(), hexagon(), octagon(), star()
// Usage: As Module
// right_triangle(size, [center], ...) [ATTACHMENTS];
// Usage: As Function
// path = right_triangle(size, [center], ...);
// Description:
// When called as a module, creates a right triangle with the Hypotenuse in the X+Y+ quadrant.
// When called as a function, returns a 2D path for a right triangle with the Hypotenuse in the X+Y+ quadrant.
// Arguments:
// size = The width and length of the right triangle, given as a scalar or an XY vector.
// center = If true, forces `anchor=CENTER`. If false, forces `anchor=[-1,-1]`. Default: undef (use `anchor=`)
// ---
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Named Anchors:
// "hypot" = Center of angled side, perpendicular to that side.
// Example(2D):
// right_triangle([40,30]);
// Example(2D): With `center=true`
// right_triangle([40,30], center=true);
// Example(2D): Standard Anchors
// right_triangle([80,30], center=true)
// show_anchors(custom=false);
// color([0.5,0.5,0.5,0.1])
// square([80,30], center=true);
// Example(2D): Named Anchors
// right_triangle([80,30], center=true)
// show_anchors(std=false);
function right_triangle(size=[1,1], center, anchor, spin=0) =
let(
size = is_num(size)? [size,size] : size,
anchor = get_anchor(anchor, center, [-1,-1], [-1,-1])
)
assert(is_vector(size,2))
assert(min(size)>0, "Must give positive size")
let(
path = [ [size.x/2,-size.y/2], [-size.x/2,-size.y/2], [-size.x/2,size.y/2] ],
anchors = [
named_anchor("hypot", CTR, unit([size.y,size.x])),
]
) reorient(anchor,spin, two_d=true, size=[size.x,size.y], anchors=anchors, p=path);
module right_triangle(size=[1,1], center, anchor, spin=0) {
size = is_num(size)? [size,size] : size;
anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]);
check = assert(is_vector(size,2));
path = right_triangle(size, anchor="origin");
anchors = [
named_anchor("hypot", CTR, unit([size.y,size.x])),
];
attachable(anchor,spin, two_d=true, size=[size.x,size.y], anchors=anchors) {
polygon(path);
children();
}
}
// Function&Module: trapezoid()
// Synopsis: Creates a trapezoid with parallel top and bottom sides.
// SynTags: Geom, Path
// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
// See Also: rect(), square()
// Usage: As Module
// trapezoid(h, w1, w2, [shift=], [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
// trapezoid(h, w1, ang=, [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
// trapezoid(h, w2=, ang=, [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
// trapezoid(w1=, w2=, ang=, [rounding=], [chamfer=], [flip=], ...) [ATTACHMENTS];
// Usage: As Function
// path = trapezoid(...);
// Description:
// When called as a function, returns a 2D path for a trapezoid with parallel front and back (top and bottom) sides.
// When called as a module, creates a 2D trapezoid. You can specify the trapezoid by giving its height and the lengths
// of its two bases. Alternatively, you can omit one of those parameters and specify the lower angle(s).
// The shift parameter, which cannot be combined with ang, shifts the back (top) of the trapezoid to the right.
// Arguments:
// h = The Y axis height of the trapezoid.
// w1 = The X axis width of the front end of the trapezoid.
// w2 = The X axis width of the back end of the trapezoid.
// ---
// 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.
// shift = Scalar value to shift the back of the trapezoid along the X axis by. Cannot be combined with ang. Default: 0
// 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)
// 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)
// flip = If true, negative roundings and chamfers will point forward and back instead of left and right. Default: `false`.
// 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"
// anchor = Translate so anchor point is at origin (0,0,0). See [anchor](attachments.scad#subsection-anchor). Default: `CENTER`
// spin = Rotate this many degrees around the Z axis after anchor. See [spin](attachments.scad#subsection-spin). Default: `0`
// Anchor Types:
// box = Anchor is with respect to the rectangular bounding box of the shape.
// perim = Anchors are placed along the rounded or chamfered perimeter of the shape.
// Examples(2D):
// trapezoid(h=30, w1=40, w2=20);
// trapezoid(h=25, w1=20, w2=35);
// trapezoid(h=20, w1=40, w2=0);
// trapezoid(h=20, w1=30, ang=60);
// trapezoid(h=20, w1=20, ang=120);
// trapezoid(h=20, w2=10, ang=60);
// trapezoid(h=20, w1=50, ang=[40,60]);
// trapezoid(w1=30, w2=10, ang=[30,90]);
// Example(2D): Chamfered Trapezoid
// trapezoid(h=30, w1=60, w2=40, chamfer=5);
// Example(2D): Negative Chamfered Trapezoid
// trapezoid(h=30, w1=60, w2=40, chamfer=-5);
// Example(2D): Flipped Negative Chamfered Trapezoid
// trapezoid(h=30, w1=60, w2=40, chamfer=-5, flip=true);
// Example(2D): Rounded Trapezoid
// trapezoid(h=30, w1=60, w2=40, rounding=5);
// Example(2D): Negative Rounded Trapezoid
// trapezoid(h=30, w1=60, w2=40, rounding=-5);
// Example(2D): Flipped Negative Rounded Trapezoid
// trapezoid(h=30, w1=60, w2=40, rounding=-5, flip=true);
// Example(2D): Mixed Chamfering and Rounding
// trapezoid(h=30, w1=60, w2=40, rounding=[5,0,-10,0],chamfer=[0,8,0,-15],$fa=1,$fs=1);
// Example(2D): default anchors for roundings
// trapezoid(h=30, w1=100, ang=[66,44],rounding=5) show_anchors();
// Example(2D): default anchors for negative roundings are still at the trapezoid corners
// trapezoid(h=30, w1=100, ang=[66,44],rounding=-5) show_anchors();
// Example(2D): "perim" anchors are at the tips of negative roundings
// trapezoid(h=30, w1=100, ang=[66,44],rounding=-5, atype="perim") show_anchors();
// Example(2D): They point the other direction if you flip them
// trapezoid(h=30, w1=100, ang=[66,44],rounding=-5, atype="perim",flip=true) show_anchors();
// Example(2D): Called as Function
// stroke(closed=true, trapezoid(h=30, w1=40, w2=20));
function _trapezoid_dims(h,w1,w2,shift,ang) =
let(
h = is_def(h)? h
: num_defined([w1,w2,each ang])==4 ? (w1-w2) * sin(ang[0]) * sin(ang[1]) / sin(ang[0]+ang[1])
: undef
)
is_undef(h) ? [h]
:
let(
x1 = is_undef(ang[0]) || ang[0]==90 ? 0 : h/tan(ang[0]),
x2 = is_undef(ang[1]) || ang[1]==90 ? 0 : h/tan(ang[1]),
w1 = is_def(w1)? w1
: is_def(w2) && is_def(ang[0]) ? w2 + x1 + x2
: undef,
w2 = is_def(w2)? w2
: is_def(w1) && is_def(ang[0]) ? w1 - x1 - x2
: undef,
shift = first_defined([shift,(x1-x2)/2])
)