scad_tree 0.4.2

Generate OpenSCAD code from Rust.
Documentation
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
// MIT License
//
// Copyright (c) 2023 Michael H. Phillips
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

use crate::{dcos, dsin, Pt2, Pt2s};

/// Create a clockwise circle or part of a circle.
pub fn arc(start: Pt2, degrees: f64, segments: u64) -> Pt2s {
    assert!(degrees <= 360.0);
    let n_pts = if degrees == 360.0 {
        segments
    } else {
        segments + 1
    };
    let mut pts = Pt2s::with_capacity(n_pts as usize);
    for i in 0..n_pts {
        let a = i as f64 * -degrees / segments as f64;
        pts.push(start.rotated(a));
    }
    pts
}

/// Convenience function for circle creation.
pub fn circle(radius: f64, segments: u64) -> Pt2s {
    arc(Pt2::new(radius, 0.0), 360.0, segments)
}

/// Create an inscribed polygon.
///
/// radius: the radius of the circle surrounding the polygon
pub fn inscribed_polygon(n_sides: u64, radius: f64) -> Pt2s {
    circle(radius, n_sides)
}

/// Create a circumscribed polygon.
///
/// radius: the radius of the circle inside the polygon
pub fn circumscribed_polygon(n_sides: u64, radius: f64) -> Pt2s {
    let radius = radius / dcos(180.0 / n_sides as f64);
    inscribed_polygon(n_sides, radius)
}

/// Create a rectangle or square with rounded corners.
pub fn rounded_rect(width: f64, height: f64, radius: f64, segments: u64, center: bool) -> Pt2s {
    let mut tr = arc(Pt2::new(0.0, radius), 90.0, segments);
    tr.translate(Pt2::new(width - radius, height - radius));
    let mut br = arc(Pt2::new(radius, 0.0), 90.0, segments);
    br.translate(Pt2::new(width - radius, radius));
    let mut bl = arc(Pt2::new(-0.0, -radius), 90.0, segments);
    bl.translate(Pt2::new(radius, radius));
    let mut tl = arc(Pt2::new(-radius, 0.0), 90.0, segments);
    tl.translate(Pt2::new(radius, height - radius));

    tr.append(&mut br);
    tr.append(&mut bl);
    tr.append(&mut tl);

    if center {
        tr.translate(Pt2::new(-width / 2.0, -height / 2.0));
    }
    tr
}

/// Creates a profile for chamfering edges at 45 degrees.
///
/// The profile is a triangle when oversize is zero. With
/// oversize the profile is a square with a triangle removed.
/// Extending the shape with oversize gives a cleaner preview
/// in OpenSCAD.
///
/// size: The vertcal and horizontal size of the chamfer.
///
/// oversize: The size of the non-chamfer part.
pub fn chamfer(size: f64, oversize: f64) -> Pt2s {
    Pt2s::from_pt2s(vec![
        Pt2::new(0.0, size + oversize),
        Pt2::new(oversize, size + oversize),
        Pt2::new(oversize, size),
        Pt2::new(size, oversize),
        Pt2::new(size + oversize, oversize),
        Pt2::new(oversize + size, 0.0),
        Pt2::new(0.0, 0.0),
    ])
}

/// Yeilds the points of a quadratic bezier.
///
/// If you want to use a Viewer use QuadraticBezier2D struct instead.
pub fn quadratic_bezier(start: Pt2, control: Pt2, end: Pt2, segments: u64) -> Pt2s {
    let delta = 1.0 / segments as f64;
    let mut points = Pt2s::new();
    for i in 0..(segments + 1) {
        let t = i as f64 * delta;
        points.push(start * (1.0 - t) * (1.0 - t) + control * t * (1.0 - t) * 2.0 + end * t * t);
    }
    points
}

/// Yeilds the points of a cubic bezier.
///
/// If you want to use a Viewer use CubicBezier2D struct instead.
pub fn cubic_bezier(start: Pt2, control1: Pt2, control2: Pt2, end: Pt2, segments: u64) -> Pt2s {
    let delta = 1.0 / segments as f64;
    let mut points = Pt2s::new();
    for i in 0..(segments + 1) {
        let t = i as f64 * delta;
        points.push(
            start * (1.0 - t) * (1.0 - t) * (1.0 - t)
                + control1 * t * (1.0 - t) * (1.0 - t) * 3.0
                + control2 * t * t * (1.0 - t) * 3.0
                + end * t * t * t,
        );
    }
    points
}

/// Create a star profile.
pub fn star(n_points: usize, inner_radius: f64, outer_radius: f64) -> Pt2s {
    let angle = -360.0 / n_points as f64;
    let mut points = Pt2s::new();
    for i in 0..n_points {
        points.push(Pt2::new(
            dcos(angle * i as f64) * inner_radius,
            dsin(angle * i as f64) * inner_radius,
        ));
        points.push(Pt2::new(
            dcos(angle * (i as f64 + 0.5)) * outer_radius,
            dsin(angle * (i as f64 + 0.5)) * outer_radius,
        ));
    }
    points
}

/// Create a star profile with rounded corners.
pub fn bezier_star(
    n_points: u64,
    inner_radius: f64,
    inner_handle_length: f64,
    outer_radius: f64,
    outer_handle_length: f64,
    segments: u64,
) -> Pt2s {
    let mut controls = Vec::new();
    let mut knots = Vec::new();

    let angle = -360.0 / n_points as f64;
    for i in 0..n_points {
        knots.push(Pt2::new(
            dcos(angle * i as f64) * outer_radius,
            dsin(angle * i as f64) * outer_radius,
        ));
        knots.push(Pt2::new(
            dcos(angle * (i as f64 + 0.5)) * inner_radius,
            dsin(angle * (i as f64 + 0.5)) * inner_radius,
        ));
    }
    let n_knots = knots.len();
    for i in 0..n_knots {
        controls.push(
            knots[(i + 1) % n_knots]
                - (knots[(i + 2) % n_knots] - knots[i]).normalized()
                    * if i % 2 == 0 {
                        inner_handle_length
                    } else {
                        outer_handle_length
                    },
        );
    }

    let mut chain = CubicBezierChain2D::new(knots[0], controls[0], controls[0], knots[1], segments);
    for i in 1..(n_knots - 1) {
        chain.add(
            if i % 2 == 0 {
                outer_handle_length
            } else {
                inner_handle_length
            },
            controls[i],
            knots[i + 1],
            segments,
        );
    }
    chain.close(
        inner_handle_length,
        controls[n_knots - 1],
        outer_handle_length,
        segments,
    );

    chain.gen_points()
}

/// A 2D quadratic bezier curve.
#[derive(Clone, Copy)]
pub struct QuadraticBezier2D {
    pub start: Pt2,
    pub control: Pt2,
    pub end: Pt2,
    pub segments: u64,
}

impl QuadraticBezier2D {
    /// Create a new QuadraticBezier2D.
    pub fn new(start: Pt2, control: Pt2, end: Pt2, segments: u64) -> Self {
        Self {
            start,
            control,
            end,
            segments,
        }
    }

    /// Yeilds the points of the curve.
    pub fn gen_points(&self) -> Pt2s {
        quadratic_bezier(self.start, self.control, self.end, self.segments)
    }
}

/// A 2D cubic bezier curve.
#[derive(Clone, Copy)]
pub struct CubicBezier2D {
    pub start: Pt2,
    pub control1: Pt2,
    pub control2: Pt2,
    pub end: Pt2,
    pub segments: u64,
}

impl CubicBezier2D {
    /// Create a new curve.
    pub fn new(start: Pt2, control1: Pt2, control2: Pt2, end: Pt2, segments: u64) -> Self {
        Self {
            start,
            control1,
            control2,
            end,
            segments,
        }
    }

    /// Yeilds the points of the curve.
    pub fn gen_points(&self) -> Pt2s {
        cubic_bezier(
            self.start,
            self.control1,
            self.control2,
            self.end,
            self.segments,
        )
    }
}

/// Multiple cubic bezier curves linked together.
#[derive(Clone)]
pub struct CubicBezierChain2D {
    pub curves: Vec<CubicBezier2D>,
    closed: bool,
}

impl CubicBezierChain2D {
    /// Create the start of the chain.
    pub fn new(start: Pt2, control1: Pt2, control2: Pt2, end: Pt2, segments: u64) -> Self {
        Self {
            curves: vec![CubicBezier2D {
                start,
                control1,
                control2,
                end,
                segments,
            }],
            closed: false,
        }
    }

    /// Add an additional curve to the chain.
    pub fn add(
        &mut self,
        control1_length: f64,
        control2: Pt2,
        end: Pt2,
        segments: u64,
    ) -> &mut Self {
        let chain_end = &self.curves[self.curves.len() - 1];
        self.curves.push(CubicBezier2D {
            start: chain_end.end,
            control1: chain_end.end
                + (chain_end.end - chain_end.control2).normalized() * control1_length,
            control2,
            end,
            segments,
        });
        self
    }

    /// Connect the ends of the chain to form a closed profile.
    pub fn close(
        &mut self,
        control1_length: f64,
        control2: Pt2,
        start_control1_len: f64,
        segments: u64,
    ) {
        self.closed = true;
        self.add(control1_length, control2, self.curves[0].start, segments);
        let chain_end = &self.curves[self.curves.len() - 1];
        self.curves[0].control1 =
            chain_end.end + (chain_end.end - chain_end.control2).normalized() * start_control1_len;
    }

    /// Yeilds the points of the curve.
    pub fn gen_points(&self) -> Pt2s {
        let mut pts = Pt2s::from_pt2s(vec![Pt2::new(0.0, 0.0)]);
        for i in 0..self.curves.len() {
            pts.pop();
            pts.append(&mut cubic_bezier(
                self.curves[i].start,
                self.curves[i].control1,
                self.curves[i].control2,
                self.curves[i].end,
                self.curves[i].segments,
            ));
        }
        if self.closed {
            pts.pop();
        }
        pts
    }
}

/// A 2D star with rounded corners.
#[derive(Clone)]
pub struct BezierStar {
    pub chain: CubicBezierChain2D,
}

impl BezierStar {
    /// Create a new BezierStar.
    pub fn new(
        n_points: u64,
        inner_radius: f64,
        inner_handle_length: f64,
        outer_radius: f64,
        outer_handle_length: f64,
        segments: u64,
    ) -> Self {
        let mut controls = Vec::new();
        let mut knots = Vec::new();

        let angle = -360.0 / n_points as f64;
        for i in 0..n_points {
            knots.push(Pt2::new(
                dcos(angle * i as f64) * outer_radius,
                dsin(angle * i as f64) * outer_radius,
            ));
            knots.push(Pt2::new(
                dcos(angle * (i as f64 + 0.5)) * inner_radius,
                dsin(angle * (i as f64 + 0.5)) * inner_radius,
            ));
        }
        let n_knots = knots.len();
        for i in 0..n_knots {
            controls.push(
                knots[(i + 1) % n_knots]
                    - (knots[(i + 2) % n_knots] - knots[i]).normalized()
                        * if i % 2 == 0 {
                            inner_handle_length
                        } else {
                            outer_handle_length
                        },
            );
        }

        let mut chain =
            CubicBezierChain2D::new(knots[0], controls[0], controls[0], knots[1], segments);
        for i in 1..(n_knots - 1) {
            chain.add(
                if i % 2 == 0 {
                    outer_handle_length
                } else {
                    inner_handle_length
                },
                controls[i],
                knots[i + 1],
                segments,
            );
        }
        chain.close(
            inner_handle_length,
            controls[n_knots - 1],
            outer_handle_length,
            segments,
        );

        Self { chain }
    }

    /// Yields the points of the bezier star.
    pub fn gen_points(&self) -> Pt2s {
        self.chain.gen_points()
    }
}