scadman 0.2.2

Code generator for OpenSCAD.
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
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
use ambassador::Delegate;
use derive_builder::Builder;
use derive_more::derive::From;
use nalgebra as na;

use crate::{
    common::{AffineMatrix3D, DimensionType as _, Point3D, Unit},
    internal::generate_sentence_repr,
    scad_display::{ambassador_impl_ScadDisplay, ScadDisplay},
    value_type::Angle,
};

use crate::common::D3;

macro_rules! __impl_apply_2d {
    ($mod_ty:ident) => {
        __impl_apply_to_modifier!(
            apply_to,
            $mod_ty,
            $crate::scad_3d::ScadModifierBody3D,
            $crate::common::ScadObjectGeneric<$crate::common::D3>,
            $crate::scad_3d::ScadModifier3D,
            $crate::scad_3d::ScadObject3D,
            $crate::common::ScadObjectImpl::Object3D,
            $crate::common::D3, // output_marker
            $crate::common::D2  // child_marker
        );
        __impl_panicking_modifier_methods!($mod_ty, D3);
    };
}

macro_rules! __impl_apply_3d {
    ($mod_ty:ident) => {
        __impl_apply_to_modifier!(
            apply_to,
            $mod_ty,
            $crate::scad_3d::ScadModifierBody3D,
            $crate::common::ScadObjectGeneric<$crate::common::D3>,
            $crate::scad_3d::ScadModifier3D,
            $crate::scad_3d::ScadObject3D,
            $crate::common::ScadObjectImpl::Object3D,
            $crate::common::D3, // output_marker
            $crate::common::D3  // child_marker
        );
        __impl_panicking_modifier_methods!($mod_ty, D3);
    };
}

/// Translate modifier `translate()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 3D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct Translate3D {
    /// Translation vector.
    /// `v` option in SCAD.
    #[builder(setter(into))]
    pub v: Point3D,
}

__impl_builder_modifier!(Translate3D);
__impl_modifier_chaining!(Translate3D);
__impl_apply_3d!(Translate3D);

impl ScadDisplay for Translate3D {
    fn repr_scad(&self) -> String {
        generate_sentence_repr("translate", __generate_scad_options!(("", self.v);))
    }
}

/// Angle of rotate (3D) in SCAD.
///
/// `a` option in SCAD.
#[derive(Copy, Clone, Debug, PartialEq, From, Delegate)]
#[delegate(ScadDisplay)]
pub enum Rotate3DAngle {
    /// Rotation angle on `v`
    A(Angle),
    /// Rotation angles in `[x, y, z]` axes
    V(na::Vector3<Angle>),
}

/// Numbers to generate [`Rotate3DAngle`].
///
/// The numbers are the angle.
/// This type have no information about the angle is rad or deg.
#[derive(Copy, Clone, Debug, PartialEq, From)]
pub enum Rotate3DAngleEntry {
    /// Number to generate [`Rotate3DAngle::A`].
    Single(Unit),
    /// Pair of numbers to generate [`Rotate3DAngle::V`].
    Triple([Unit; 3]),
}

/// Rotate modifier `rotate()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 3D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct Rotate3D {
    /// Rotation angle.
    /// `a` option in SCAD.
    ///
    /// See also [`AngleRotate3D`].
    #[builder(setter(custom))]
    pub a: Rotate3DAngle,
    /// Rotation axis.
    #[builder(setter(into, strip_option), default)]
    pub v: Option<Point3D>,
}

__impl_builder_modifier!(Rotate3D);
__impl_modifier_chaining!(Rotate3D);
__impl_apply_3d!(Rotate3D);

impl Rotate3DBuilder {
    /// Set rotation angle in degrees.
    ///
    /// # Arguments
    ///
    /// + `value` - The rotation angle in degrees.
    pub fn deg<T: Into<Rotate3DAngleEntry>>(&mut self, value: T) -> &mut Self {
        let new = self;
        new.a = match value.into() {
            Rotate3DAngleEntry::Single(a) => Some(Rotate3DAngle::A(Angle::Deg(a))),
            Rotate3DAngleEntry::Triple(a) => Some(Rotate3DAngle::V(na::Vector3::from_iterator(
                a.into_iter().map(Angle::Deg),
            ))),
        };
        new
    }

    /// Set rotation angle in radians.
    ///
    /// # Arguments
    ///
    /// + `value` - The rotation angle in radians.
    pub fn rad<T: Into<Rotate3DAngleEntry>>(&mut self, value: T) -> &mut Self {
        let new = self;
        new.a = match value.into() {
            Rotate3DAngleEntry::Single(a) => Some(Rotate3DAngle::A(Angle::Rad(a))),
            Rotate3DAngleEntry::Triple(a) => Some(Rotate3DAngle::V(na::Vector3::from_iterator(
                a.into_iter().map(Angle::Rad),
            ))),
        };
        new
    }
}

impl ScadDisplay for Rotate3D {
    fn repr_scad(&self) -> String {
        generate_sentence_repr(
            "rotate",
            __generate_scad_options!(
                ("a", self.a); opt:(("v", self.v);)
            ),
        )
    }
}

/// Scale modifier `scale()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 3D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct Scale3D {
    /// Scaling vector.
    /// `v` option in SCAD.
    #[builder(setter(into))]
    pub v: Point3D,
}

__impl_builder_modifier!(Scale3D);
__impl_modifier_chaining!(Scale3D);
__impl_apply_3d!(Scale3D);

impl ScadDisplay for Scale3D {
    fn repr_scad(&self) -> String {
        generate_sentence_repr("scale", __generate_scad_options!(("", self.v);))
    }
}

/// `auto` option in 3D resize modifier.
#[derive(Copy, Clone, Debug, PartialEq, Eq, From, Delegate)]
#[delegate(ScadDisplay)]
pub enum ResizeAuto3D {
    /// Same value for all dimensions.
    B(bool),
    /// Values for each dimension.
    V([bool; 3]),
}

/// Resize modifier `resize()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 3D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct Resize3D {
    /// New size.
    ///
    /// `0` means no change if the corresponding dimension of `auto` is `false`,
    /// or auto value if `true`.
    #[builder(setter(into))]
    pub size: Point3D,
    /// `auto` option in SCAD.
    ///
    /// See also [`ResizeAuto`].
    #[builder(setter(into, strip_option), default)]
    pub auto: Option<ResizeAuto3D>,
}

__impl_builder_modifier!(Resize3D);
__impl_modifier_chaining!(Resize3D);
__impl_apply_3d!(Resize3D);

impl ScadDisplay for Resize3D {
    fn repr_scad(&self) -> String {
        generate_sentence_repr(
            "resize",
            __generate_scad_options!(
                ("", self.size); opt:(("auto", self.auto);)
            ),
        )
    }
}

/// Mirror modifier `mirror()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 3D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct Mirror3D {
    /// Normal vector of the mirror plane.
    #[builder(setter(into))]
    pub v: Point3D,
}

__impl_builder_modifier!(Mirror3D);
__impl_modifier_chaining!(Mirror3D);
__impl_apply_3d!(Mirror3D);

impl ScadDisplay for Mirror3D {
    fn repr_scad(&self) -> String {
        generate_sentence_repr("mirror", __generate_scad_options!(("", self.v);))
    }
}

/// Affine tranformation modifier `multmatrix()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 3D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct MultMatrix3D {
    /// Affine transformation matrix for 3D vector.
    #[builder(setter(into))]
    pub m: AffineMatrix3D,
}

__impl_builder_modifier!(MultMatrix3D);
__impl_modifier_chaining!(MultMatrix3D);
__impl_apply_3d!(MultMatrix3D);

impl ScadDisplay for MultMatrix3D {
    fn repr_scad(&self) -> String {
        generate_sentence_repr("multmatrix", __generate_scad_options!(("m", self.m);))
    }
}

/// Linear extrude modifier `linear_extrude()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 2D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct LinearExtrude {
    /// The length of the extruded object.
    ///
    /// `height` must be positive.
    #[builder(setter(into), default)]
    pub height: Unit,
    /// The vector that extrusion follows.
    #[builder(setter(into, strip_option), default)]
    pub v: Option<Point3D>,
    /// `center` option in SCAD.
    ///
    /// + `true` - Z range is from 0 to height.
    /// + `false` - Z range is -height/2 to height/2.
    #[builder(setter(into, strip_option), default)]
    pub center: Option<bool>,
    /// Twist degrees of through which the shape is extruded.
    ///
    /// Setting the parameter twist = 360 extrudes through one revolution.
    /// The twist direction follows the left hand rule.
    #[builder(setter(into, strip_option), default)]
    pub twist: Option<Unit>,
    /// `convexity` option in SCAD.
    #[builder(setter(into, strip_option), default)]
    pub convexity: Option<u64>,
    /// The number of intermediate points along the Z axis of the extrusion.
    #[builder(setter(into, strip_option), default)]
    pub slices: Option<u64>,
    /// Scales value over the height of the extrusion.
    #[builder(setter(into, strip_option), default)]
    pub scale: Option<Unit>,
    /// `$fn` option in SCAD.
    #[builder(setter(into, strip_option), default)]
    pub r#fn: Option<u64>,
}

__impl_builder_modifier!(LinearExtrude);
__impl_modifier_chaining!(LinearExtrude);
__impl_apply_2d!(LinearExtrude);

impl ScadDisplay for LinearExtrude {
    fn repr_scad(&self) -> String {
        generate_sentence_repr(
            "linear_extrude",
            __generate_scad_options!(
                ("height", self.height);
                opt: (
                    ("v", self.v);
                    ("center", self.center);
                    ("twist", self.twist);
                    ("convexity", self.convexity);
                    ("slices", self.slices);
                    ("scale", self.scale);
                    ("$fn", self.r#fn);
                )
            ),
        )
    }
}

/// Rotate extrude modifier `rotate_extrude()` in SCAD.
/// This Rust type is regarded as 3D object and only applys to 2D objects.
#[derive(Builder, Debug, Clone, Copy)]
pub struct RotateExtrude {
    /// The number of degrees to sweep.
    ///
    /// Starting at the positive X axis.
    /// The direction of the sweep follows the Right Hand Rule,
    /// hence a negative angle sweeps clockwise.
    #[builder(setter(into, strip_option), default)]
    pub angle: Option<Unit>,
    /// Specifies the starting angle of the extrusion,
    /// counter-clockwise from the positive X axis.
    ///
    /// Defaults to 0 if angle is specified, and 180 if not.
    #[builder(setter(into, strip_option), default)]
    pub start: Option<Unit>,
    /// `convexity` option in SCAD.
    #[builder(setter(into, strip_option), default)]
    pub convexity: Option<u64>,
    /// `$fa` option in SCAD.
    #[builder(setter(into, strip_option), default)]
    pub fa: Option<Unit>,
    /// `$fn` option in SCAD.
    #[builder(setter(into, strip_option), default)]
    pub r#fn: Option<u64>,
    /// `$fs` option in SCAD.
    #[builder(setter(into, strip_option), default)]
    pub fs: Option<Unit>,
}

__impl_builder_modifier!(RotateExtrude);
__impl_modifier_chaining!(RotateExtrude);
__impl_apply_2d!(RotateExtrude);

impl ScadDisplay for RotateExtrude {
    fn repr_scad(&self) -> String {
        generate_sentence_repr(
            "rotate_extrude",
            __generate_scad_options!(
                opt: (
                ("angle", self.angle);
                ("start", self.start);
                ("convexity", self.convexity);
                ("$fa", self.fa);
                ("$fn", self.r#fn);
                ("$fs", self.fs);
                )
            ),
        )
    }
}

#[cfg(test)]
mod tests {
    use std::f64::consts::PI;

    use super::*;

    #[test]
    fn test_translate3d() {
        assert_eq!(
            Translate3DBuilder::default()
                .v([8., -4., 6.])
                .build()
                .unwrap()
                .repr_scad(),
            "translate([8, -4, 6])"
        );
    }

    #[test]
    fn test_rotate3d() {
        assert_eq!(
            Rotate3DBuilder::default()
                .deg([45., 0., 90.])
                .build()
                .unwrap()
                .repr_scad(),
            "rotate(a = [45, 0, 90])"
        );
        assert_eq!(
            Rotate3DBuilder::default()
                .rad([PI / 4., 0., PI / 2.])
                .build()
                .unwrap()
                .repr_scad(),
            "rotate(a = [45, 0, 90])"
        );
        assert_eq!(
            Rotate3DBuilder::default()
                .rad(PI / 4.)
                .v([1., 1., 0.])
                .build()
                .unwrap()
                .repr_scad(),
            "rotate(a = 45, v = [1, 1, 0])"
        );
    }

    #[test]
    fn test_mirror3d() {
        assert_eq!(
            Mirror3DBuilder::default()
                .v([1., -1., 0.])
                .build()
                .unwrap()
                .repr_scad(),
            "mirror([1, -1, 0])"
        );
    }

    #[test]
    fn test_scale3d() {
        assert_eq!(
            Scale3DBuilder::default()
                .v([3., 2., 4.])
                .build()
                .unwrap()
                .repr_scad(),
            "scale([3, 2, 4])"
        );
    }

    #[test]
    fn test_resize3d() {
        let mut r1 = Resize3DBuilder::default();
        _ = r1.size([3., 2., 1.]);
        assert_eq!(r1.clone().build().unwrap().repr_scad(), "resize([3, 2, 1])");
        assert_eq!(
            r1.clone().auto(true).build().unwrap().repr_scad(),
            "resize([3, 2, 1], auto = true)"
        );
        assert_eq!(
            r1.auto([true, false, true]).build().unwrap().repr_scad(),
            "resize([3, 2, 1], auto = [true, false, true])"
        );
    }

    #[test]
    fn test_multimatrix2d() {
        let m = AffineMatrix3D::new(1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.);
        assert_eq!(
            MultMatrix3DBuilder::default()
                .m(m)
                .build()
                .unwrap()
                .repr_scad(),
            "multmatrix(m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])"
        );
    }

    #[test]
    fn test_linear_extrude() {
        assert_eq!(
            LinearExtrudeBuilder::default()
                .height(5.)
                .build()
                .unwrap()
                .repr_scad(),
            "linear_extrude(height = 5)"
        );
        assert_eq!(
            LinearExtrudeBuilder::default()
                .height(5.)
                .v([0., 0.2, 1.])
                .center(true)
                .twist(180.)
                .convexity(10_u64)
                .slices(30_u64)
                .scale(0.7)
                .r#fn(20_u64)
                .build()
                .unwrap()
                .repr_scad(),
            "linear_extrude(height = 5, v = [0, 0.2, 1], center = true, twist = 180, convexity = 10, slices = 30, scale = 0.7, $fn = 20)"
        );
    }

    #[test]
    fn test_rotate_extrude() {
        assert_eq!(
            RotateExtrudeBuilder::default().build().unwrap().repr_scad(),
            "rotate_extrude()"
        );
        assert_eq!(
            RotateExtrudeBuilder::default()
                .angle(180.)
                .start(90.)
                .convexity(10_u64)
                .fa(5.)
                .build()
                .unwrap()
                .repr_scad(),
            "rotate_extrude(angle = 180, start = 90, convexity = 10, $fa = 5)"
        );
    }
}