concentric_circles 0.1.0

Efficient generation and iteration of concentric circle perimeters using Bresenham's algorithm.
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
use crate::concentric_circles_adapters::{scaling_range_skip_r, scaling_range_take_r};
use crate::{Add, FromAs, PhantomData, Radii, RangeInclusive, Scaling, Zero};

impl<T: ?Sized> PointWithColor for T where T: Iterator {}

/// The `PointWithColor` trait provides iterator adapters for working with points that have associated color information.
///
/// This trait extends the standard `Iterator` trait and offers methods for cropping points to a rectangular area,
/// adjusting color within sectors or by radius, and converting coordinates. These adapters are useful for image
/// processing tasks such as masking, cropping, and color manipulation of points in 2D space.
///
/// # Provided Methods
///
/// - `crown_with_color`: Crops points to a specified rectangular area.
/// - `crown_with_size_color`: Crops points to a rectangular area, considering a given size for each point.
/// - `map_circle_sector`: Updates the color of points within a specified sector of circles using a closure.
/// - `map_color_radial`: Updates the color of points based on their radius using a closure.
/// - `to_image_coordinates_with_color`: Converts point coordinates to image coordinates with an offset.
///
/// See individual method documentation for usage examples.
pub trait PointWithColor: Iterator {
    /// Returns an iterator adapter that yields only those points (with color) which lie inside the specified rectangular area.
    ///
    /// This adapter is useful for cropping or masking points with color to a given width and height, for example, to fit them within image boundaries.
    ///
    /// # Arguments
    ///
    /// * `width` - The width of the rectangular area.
    /// * `height` - The height of the rectangular area.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use concentric_circles::{ConcentricCircles, ConcentricCirclesAdapters, PointWithColor};
    ///
    /// let width = 4_usize;
    /// let height = 4;
    /// let start_radius = 1_usize;
    /// let end_radius = 5;
    /// let rgb = [32, 64, 128];
    ///
    /// let iter = ConcentricCircles::new(start_radius, end_radius)
    ///     .to_image_coordinates((width / 2) as isize, (height /2) as isize)
    ///     .add_color(rgb)
    ///     .crown_with_color(width, height);
    ///     
    /// assert_eq!(
    ///     iter.collect::<Vec<_>>(),
    ///     vec![
    ///         (2, 1, rgb), (2, 2, rgb), (1, 2, rgb), (1, 1, rgb), (2, 0, rgb),
    ///         (3, 0, rgb), (3, 1, rgb), (3, 2, rgb), (3, 3, rgb), (2, 3, rgb),
    ///         (1, 3, rgb), (0, 3, rgb), (0, 2, rgb), (0, 1, rgb), (0, 0, rgb),
    ///         (1, 0, rgb), (3, 0, rgb), (3, 3, rgb), (0, 3, rgb), (0, 0, rgb),
    ///     ]
    /// );
    /// ```
    #[inline]
    fn crown_with_color<U, Color>(self, width: U, height: U) -> CrownWithColor<Self, U, Color>
    where
        Self: Sized + Iterator<Item = (U, U, Color)>,
        U: Zero + Copy,
    {
        CrownWithColor {
            iter: self,
            x_bound_min: U::zero(),
            y_bound_min: U::zero(),
            x_bound_max: width,
            y_bound_max: height,
        }
    }

    /// Returns an iterator adapter that yields only those points (with color) which lie inside the specified rectangular area,
    /// taking into account the given bounding box for each point.
    ///
    /// This adapter is useful for cropping or masking points with color to a given area, considering that each point
    /// occupies a rectangular region defined by its bounding box. This is helpful, for example, when rendering points as shapes (like rectangles or circles)
    /// and you want to ensure that the entire shape fits within the image boundaries.
    ///
    /// # Arguments
    ///
    /// * `size` - The bounding box for each point, given as a tuple `(x_min, y_min, x_max, y_max)`.
    ///   These values define the minimum and maximum x and y coordinates that the point occupies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use concentric_circles::{ConcentricCircles, ConcentricCirclesAdapters, PointWithColor};
    ///
    /// let width = 6_usize;
    /// let height = 6;
    /// let size = (2, 2, 4, 4); // x_min, y_min, x_max, y_max
    /// let rgb = [16, 32, 64];
    ///
    /// let iter = ConcentricCircles::new(1_usize, 5)
    ///     .to_image_coordinates((width / 2) as isize, (height / 2) as isize)
    ///     .add_color(rgb)
    ///     .crown_with_size_color(size);
    ///
    /// assert_eq!(
    ///     iter.collect::<Vec<_>>(),
    ///     vec![
    ///         (3, 2, [16, 32, 64]), (3, 3, [16, 32, 64]), (2, 3, [16, 32, 64]), (2, 2, [16, 32, 64])
    ///     ]
    /// );
    /// ```
    #[inline]
    fn crown_with_size_color<T, Color>(self, size: (T, T, T, T)) -> CrownWithColor<Self, T, Color>
    where
        Self: Sized + Iterator<Item = (T, T, Color)>,
        T: Copy,
    {
        CrownWithColor {
            iter: self,
            x_bound_min: size.0,
            y_bound_min: size.1,
            x_bound_max: size.2,
            y_bound_max: size.3,
        }
    }

    /// Updates the color for points within a specified sector of circles using a closure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use concentric_circles::{ConcentricCircles, ConcentricCirclesAdapters, PointWithColor};
    ///
    /// let a = [0, 255, 0];
    /// let b = [255, 255, 0];
    /// let angle_take_from = 90_usize;
    /// let angle_take_to = 180;
    ///
    /// let iter = ConcentricCircles::new(1_usize, 3)
    ///     .add_color([0, 255, 0])
    ///     .map_circle_sector(angle_take_from, angle_take_to, |_, color| {
    ///         color[0] = 255;
    ///     });
    ///     
    /// assert_eq!(
    ///     iter.collect::<Vec<_>>(),
    ///     vec![
    ///         (0, -1, a), (0, 0, b), (-1, 0, a), (-1, -1, a),
    ///         (0, -2, a), (1, -2, a), (1, -1, a), (1, 0, b), (1, 1, b), (0, 1, b), (-1, 1, a), (-2, 1, a),
    ///         (-2, 0, a), (-2, -1, a), (-2, -2, a), (-1, -2, a),
    ///         (0, -3, a), (1, -3, a), (1, -2, a), (2, -2, a), (2, -1, a), (2, 0, b), (2, 1, b), (1, 1, b),
    ///         (1, 2, b), (0, 2, b), (-1, 2, a), (-2, 2, a), (-2, 1, a), (-3, 1, a), (-3, 0, a), (-3, -1, a),
    ///         (-3, -2, a), (-2, -2, a), (-2, -3, a), (-1, -3, a),
    ///     ]
    /// );
    /// ```
    #[inline]
    fn map_circle_sector<T, F, Color>(
        self,
        angle_take_from: usize,
        angle_take_to: usize,
        f: F,
    ) -> MapCircleSector<Self, F>
    where
        Self: Iterator<Item = (T, T, Color)> + Radii + Sized,
        F: FnMut(usize, &mut Color),
    {
        let inner_radius: usize = self.current_inner_radius();
        let outer_radius: usize = self.outer_radius();

        let (angle_take_from, angle_take_to) = if angle_take_from >= angle_take_to {
            (360, 360)
        } else {
            (
                angle_take_from,
                if angle_take_to > 360 {
                    360
                } else {
                    angle_take_to
                },
            )
        };

        let mut take_values_iter = scaling_range_take_r(outer_radius, angle_take_to);
        let mut skip_values_iter = scaling_range_skip_r(outer_radius, angle_take_from);

        if inner_radius > 1 {
            let _ = take_values_iter.nth(inner_radius - 2);
            let _ = skip_values_iter.nth(inner_radius - 2);
        }

        MapCircleSector {
            iter: self,
            f,
            take_values_iter,
            skip_values_iter,
            take_values: 0,
            skip_values: 0,
            inner_radius: 0,
            count_points: 0,
        }
    }

    /// The `map_color_radial` adapter uses a closure to change the color of points.
    /// The radius can be used to select which circles to update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use concentric_circles::{ConcentricCircles, ConcentricCirclesAdapters, PointWithColor};
    ///
    /// let iter = ConcentricCircles::new(1_usize, 3)
    ///     .add_color([0, 0, 255])
    ///     .map_color_radial(|radius, color| {
    ///         if radius == 3 {
    ///             color[0] = 255;
    ///         }
    ///     });
    ///
    /// assert_eq!(iter.collect::<Vec<_>>(),
    ///      vec![
    ///          (0, -1, [0, 0, 255]), (0, 0, [0, 0, 255]), (-1, 0, [0, 0, 255]), (-1, -1, [0, 0, 255]),
    ///
    ///          (0, -2, [0, 0, 255]), (1, -2, [0, 0, 255]), (1, -1, [0, 0, 255]), (1, 0, [0, 0, 255]),
    ///          (1, 1, [0, 0, 255]), (0, 1, [0, 0, 255]), (-1, 1, [0, 0, 255]), (-2, 1, [0, 0, 255]),
    ///          (-2, 0, [0, 0, 255]), (-2, -1, [0, 0, 255]), (-2, -2, [0, 0, 255]), (-1, -2, [0, 0, 255]),
    ///
    ///          (0, -3, [255, 0, 255]), (1, -3, [255, 0, 255]), (1, -2, [255, 0, 255]), (2, -2, [255, 0, 255]),
    ///          (2, -1, [255, 0, 255]), (2, 0, [255, 0, 255]), (2, 1, [255, 0, 255]), (1, 1, [255, 0, 255]),
    ///          (1, 2, [255, 0, 255]), (0, 2, [255, 0, 255]), (-1, 2, [255, 0, 255]), (-2, 2, [255, 0, 255]),
    ///          (-2, 1, [255, 0, 255]), (-3, 1, [255, 0, 255]), (-3, 0, [255, 0, 255]), (-3, -1, [255, 0, 255]),
    ///          (-3, -2, [255, 0, 255]), (-2, -2, [255, 0, 255]), (-2, -3, [255, 0, 255]), (-1, -3, [255, 0, 255])
    ///      ]
    /// );
    /// ```
    #[inline]
    fn map_color_radial<T, F, Color>(self, f: F) -> MapColorRadial<Self, F>
    where
        Self: Iterator<Item = (T, T, Color)> + Sized,
        F: FnMut(usize, &mut Color),
    {
        MapColorRadial { iter: self, f }
    }

    #[inline]
    /// Converts point coordinates (with color) to image coordinates using the specified x and y offsets.
    ///
    /// This adapter is useful for translating points to image space, applying the given offsets to each point's coordinates.
    ///
    /// # Arguments
    ///
    /// * `x_offset` - The offset to add to the x-coordinate.
    /// * `y_offset` - The offset to add to the y-coordinate.
    ///
    /// # Returns
    ///
    /// An iterator that yields points with updated coordinates and their associated color.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use concentric_circles::{ConcentricCircles, ConcentricCirclesAdapters, PointWithColor};
    ///
    /// let iter = ConcentricCircles::new(1_usize, 2)
    ///     .add_color([0, 0, 64])
    ///     .to_image_coordinates_with_color(2, 2);
    ///
    /// assert_eq!(iter.collect::<Vec<_>>(),
    ///     vec![
    ///         (2, 1, [0, 0, 64]), (2, 2, [0, 0, 64]), (1, 2, [0, 0, 64]), (1, 1, [0, 0, 64]),
    ///         (2, 0, [0, 0, 64]), (3, 0, [0, 0, 64]), (3, 1, [0, 0, 64]), (3, 2, [0, 0, 64]),
    ///         (3, 3, [0, 0, 64]), (2, 3, [0, 0, 64]), (1, 3, [0, 0, 64]), (0, 3, [0, 0, 64]),
    ///         (0, 2, [0, 0, 64]), (0, 1, [0, 0, 64]), (0, 0, [0, 0, 64]), (1, 0, [0, 0, 64])
    ///     ]);
    /// ```
    fn to_image_coordinates_with_color<T, U>(
        self,
        x_offset: T,
        y_offset: T,
    ) -> ToImageCoordinatesWithColor<Self, T, U>
    where
        Self: Sized + Iterator,
    {
        ToImageCoordinatesWithColor {
            iter: self,
            x_offset,
            y_offset,
            phantom: PhantomData,
        }
    }
}

/// An iterator adapter that filters points within a specified rectangular area.
#[derive(Clone, Debug)]
pub struct CrownWithColor<I: Iterator<Item = (U, U, Color)>, U, Color> {
    iter: I,
    x_bound_min: U,
    y_bound_min: U,
    x_bound_max: U,
    y_bound_max: U,
}

impl<I, U, Color> Iterator for CrownWithColor<I, U, Color>
where
    I: Iterator<Item = (U, U, Color)>,
    U: PartialOrd + Copy,
{
    type Item = (U, U, Color);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        for (x, y, color) in self.iter.by_ref() {
            if x >= self.x_bound_min
                && y >= self.y_bound_min
                && x < self.x_bound_max
                && y < self.y_bound_max
            {
                return Some((x, y, color));
            }
        }

        None
    }
}

/// An iterator adapter that updates the color for points within a specified sector of a circle using a closure.
#[derive(Debug, Clone)]
pub struct MapCircleSector<I, F>
where
    I: Iterator,
{
    iter: I,
    f: F,
    take_values_iter: Scaling<RangeInclusive<usize>, usize, usize>,
    skip_values_iter: Scaling<RangeInclusive<usize>, usize, usize>,
    take_values: usize,
    skip_values: usize,
    inner_radius: usize,
    count_points: usize,
}

impl<I, T, F, Color> Iterator for MapCircleSector<I, F>
where
    I: Iterator<Item = (T, T, Color)> + Radii,
    F: FnMut(usize, &mut Color),
{
    type Item = I::Item;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let (x, y, mut a) = self.iter.next()?;

        let current_inner_radius = self.current_inner_radius();
        if self.inner_radius != current_inner_radius {
            self.inner_radius = current_inner_radius;
            self.skip_values = self.skip_values_iter.next()?;
            self.take_values = self.take_values_iter.next()?;
            self.count_points = 0;
        }

        self.count_points += 1;
        if self.skip_values < self.count_points && self.count_points <= self.take_values {
            (self.f)(current_inner_radius, &mut a);
        }

        Some((x, y, a))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

/// An iterator adapter that updates the color based on the radius, using a closure.
#[derive(Debug, Clone)]
pub struct MapColorRadial<I, F> {
    iter: I,
    f: F,
}

impl<I, T, F, Color> Iterator for MapColorRadial<I, F>
where
    I: Iterator<Item = (T, T, Color)> + Radii,
    F: FnMut(usize, &mut Color),
{
    type Item = I::Item;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let (x, y, mut a) = self.iter.next()?;

        (self.f)(self.iter.current_inner_radius(), &mut a);

        Some((x, y, a))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

/// An iterator adapter for converting `ConcentricCircles` coordinates with color to image coordinates.
#[derive(Clone, Debug)]
pub struct ToImageCoordinatesWithColor<I, T, U> {
    iter: I,
    x_offset: T,
    y_offset: T,
    phantom: PhantomData<U>,
}

impl<I, T, U, Color> Iterator for ToImageCoordinatesWithColor<I, T, U>
where
    I: Iterator<Item = (T, T, Color)>,
    T: Add<Output = T> + Copy,
    U: FromAs<T> + Copy,
{
    type Item = (U, U, Color);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|(x, y, color)| {
            (
                U::from_as(x + self.x_offset),
                U::from_as(y + self.y_offset),
                color,
            )
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<I, F> Radii for MapCircleSector<I, F>
where
    I: Iterator + Radii,
{
    #[inline]
    fn outer_radius(&self) -> usize {
        self.iter.outer_radius()
    }

    #[inline]
    fn current_inner_radius(&self) -> usize {
        self.iter.current_inner_radius()
    }
}

impl<I, F> Radii for MapColorRadial<I, F>
where
    I: Iterator + Radii,
{
    #[inline]
    fn outer_radius(&self) -> usize {
        self.iter.outer_radius()
    }

    #[inline]
    fn current_inner_radius(&self) -> usize {
        self.iter.current_inner_radius()
    }
}

impl<I, T, U> Radii for ToImageCoordinatesWithColor<I, T, U>
where
    I: Iterator<Item = (T, T)> + Radii,
{
    #[inline]
    fn outer_radius(&self) -> usize {
        self.iter.outer_radius()
    }

    #[inline]
    fn current_inner_radius(&self) -> usize {
        self.iter.current_inner_radius()
    }
}