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
use crate::packed_location::RotatedBy;
use crate::{BoxSizeHeuristicFn, PackedLocation, RectToInsert, WidthHeightDepth};

use core::{
    cmp::Ordering,
    fmt::{Debug, Display, Error as FmtError, Formatter},
};

mod overlaps;

/// Given two sets of containers, which of these is the more suitable for our packing.
///
/// Useful when we're determining how to split up the remaining volume/area of a box/rectangle.
///
/// For example - we might deem it best to cut the remaining region vertically, or horizontally,
/// or along the Z-axis.
///
/// This decision is based on the more suitable contains heuristic. We determine all 6 possible
/// ways to divide up remaining space, sort them using the more suitable contains heuristic function
/// and choose the best one.
///
/// Ordering::Greater means the first set of containers is better.
/// Ordering::Less means the second set of containers is better.
pub type ComparePotentialContainersFn =
    dyn Fn([WidthHeightDepth; 3], [WidthHeightDepth; 3], &BoxSizeHeuristicFn) -> Ordering;

/// Select the container that has the smallest box.
///
/// If there is a tie on the smallest boxes, select whichever also has the second smallest box.
pub fn contains_smallest_box(
    mut container1: [WidthHeightDepth; 3],
    mut container2: [WidthHeightDepth; 3],
    heuristic: &BoxSizeHeuristicFn,
) -> Ordering {
    container1.sort_by(|a, b| heuristic(*a).cmp(&heuristic(*b)));
    container2.sort_by(|a, b| heuristic(*a).cmp(&heuristic(*b)));

    match heuristic(container2[0]).cmp(&heuristic(container1[0])) {
        Ordering::Equal => heuristic(container2[1]).cmp(&heuristic(container1[1])),
        o => o,
    }
}

/// A rectangular section within a target bin that takes up one or more layers
#[derive(Debug, Eq, PartialEq, Copy, Clone, Default, Ord, PartialOrd)]
pub struct BinSection {
    pub(crate) x: u32,
    pub(crate) y: u32,
    pub(crate) z: u32,
    pub(crate) whd: WidthHeightDepth,
}

/// An error while attempting to place a rectangle within a bin section;
#[derive(Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum BinSectionError {
    PlacementWiderThanBinSection,
    PlacementTallerThanBinSection,
    PlacementDeeperThanBinSection,
}

impl Display for BinSectionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        let err = match self {
            BinSectionError::PlacementWiderThanBinSection => {
                "Can not place a rectangle inside of a bin that is wider than that rectangle."
            }
            BinSectionError::PlacementTallerThanBinSection => {
                "Can not place a rectangle inside of a bin that is taller than that rectangle."
            }
            BinSectionError::PlacementDeeperThanBinSection => {
                "Can not place a rectangle inside of a bin that is deeper than that rectangle."
            }
        };

        f.write_str(err)
    }
}

impl BinSection {
    /// Create a new BinSection
    pub fn new(x: u32, y: u32, z: u32, whd: WidthHeightDepth) -> Self {
        BinSection { x, y, z, whd }
    }

    // TODO: Delete - just the old API before we had the WidthHeightDepth struct
    fn new_spread(x: u32, y: u32, z: u32, width: u32, height: u32, depth: u32) -> Self {
        BinSection {
            x,
            y,
            z,
            whd: WidthHeightDepth {
                width,
                height,
                depth,
            },
        }
    }
}

impl BinSection {
    /// See if a `LayeredRect` can fit inside of this BinSection.
    ///
    /// If it can we return the `BinSection`s that would be created by placing the `LayeredRect`
    /// inside of this `BinSection`.
    ///
    /// Consider the diagram below of a smaller box placed into of a larger one.
    ///
    /// The remaining space can be divided into three new sections.
    ///
    /// There are several ways to make this division.
    ///
    /// You could keep all of the space above the smaller box intact and split up the space
    /// behind and to the right of it.
    ///
    /// But within that you have a choice between whether the overlapping space goes to right
    /// or behind box.
    ///
    /// Or you could keep the space to the right and split the top and behind space.
    ///
    /// etc.
    ///
    /// There are six possible configurations of newly created sections. The configuration to use
    /// is decided on based on a a function provided by the consumer.
    ///
    ///
    /// ```text
    ///             ┌┬───────────────────┬┐
    ///           ┌─┘│                 ┌─┘│
    ///         ┌─┘  │               ┌─┘  │
    ///       ┌─┘    │             ┌─┘    │
    ///     ┌─┘      │           ┌─┘      │
    ///   ┌─┘        │         ┌─┘        │
    /// ┌─┴──────────┼───────┬─┘          │
    /// │            │       │            │
    /// │            │       │            │
    /// │       ┌┬───┴────┬─┐│            │
    /// │     ┌─┘│      ┌─┘ ││            │
    /// │   ┌─┘  │    ┌─┘   ││            │
    /// │ ┌─┘    │  ┌─┘     ├┼───────────┬┘
    /// ├─┴──────┤ ─┘       ││         ┌─┘
    /// │       ┌┴─┬───────┬┘│       ┌─┘   
    /// │     ┌─┘  │     ┌─┘ │     ┌─┘     
    /// │   ┌─┘    │   ┌─┘   │   ┌─┘       
    /// │ ┌─┘      │ ┌─┘     │ ┌─┘         
    /// └─┴────────┴─┴───────┴─┘           
    /// ```
    ///
    /// # Note
    ///
    /// Written to be readable/maintainable, not to minimize conditional logic, under the
    /// (unverified) assumption that a release compilation will inline and dedupe the function
    /// calls and conditionals.
    pub fn try_place(
        &self,
        incoming: &RectToInsert,
        container_comparison_fn: &ComparePotentialContainersFn,
        heuristic_fn: &BoxSizeHeuristicFn,
    ) -> Result<(PackedLocation, [BinSection; 3]), BinSectionError> {
        self.incoming_can_fit(incoming)?;

        let mut all_combinations = [
            self.depth_largest_height_second_largest_width_smallest(incoming),
            self.depth_largest_width_second_largest_height_smallest(incoming),
            self.height_largest_depth_second_largest_width_smallest(incoming),
            self.height_largest_width_second_largest_depth_smallest(incoming),
            self.width_largest_depth_second_largest_height_smallest(incoming),
            self.width_largest_height_second_largest_depth_smallest(incoming),
        ];

        all_combinations.sort_by(|a, b| {
            container_comparison_fn(
                [a[0].whd, a[1].whd, a[2].whd],
                [b[0].whd, b[1].whd, b[2].whd],
                heuristic_fn,
            )
        });

        let packed_location = PackedLocation {
            x: self.x,
            y: self.y,
            z: self.z,
            whd: WidthHeightDepth {
                width: incoming.width(),
                height: incoming.height(),
                depth: incoming.depth(),
            },
            x_axis_rotation: RotatedBy::ZeroDegrees,
            y_axis_rotation: RotatedBy::ZeroDegrees,
            z_axis_rotation: RotatedBy::ZeroDegrees,
        };

        Ok((packed_location, all_combinations[5]))
    }

    fn incoming_can_fit(&self, incoming: &RectToInsert) -> Result<(), BinSectionError> {
        if incoming.width() > self.whd.width {
            return Err(BinSectionError::PlacementWiderThanBinSection);
        }
        if incoming.height() > self.whd.height {
            return Err(BinSectionError::PlacementTallerThanBinSection);
        }

        if incoming.depth() > self.whd.depth {
            return Err(BinSectionError::PlacementDeeperThanBinSection);
        }

        Ok(())
    }

    fn width_largest_height_second_largest_depth_smallest(
        &self,
        incoming: &RectToInsert,
    ) -> [BinSection; 3] {
        [
            self.empty_space_directly_right(incoming),
            self.all_empty_space_above_excluding_behind(incoming),
            self.all_empty_space_behind(incoming),
        ]
    }

    fn width_largest_depth_second_largest_height_smallest(
        &self,
        incoming: &RectToInsert,
    ) -> [BinSection; 3] {
        [
            self.empty_space_directly_right(incoming),
            self.all_empty_space_above(incoming),
            self.all_empty_space_behind_excluding_above(incoming),
        ]
    }

    fn height_largest_width_second_largest_depth_smallest(
        &self,
        incoming: &RectToInsert,
    ) -> [BinSection; 3] {
        [
            self.all_empty_space_right_excluding_behind(incoming),
            self.empty_space_directly_above(incoming),
            self.all_empty_space_behind(incoming),
        ]
    }

    fn height_largest_depth_second_largest_width_smallest(
        &self,
        incoming: &RectToInsert,
    ) -> [BinSection; 3] {
        [
            self.all_empty_space_right(incoming),
            self.empty_space_directly_above(incoming),
            self.all_empty_space_behind_excluding_right(incoming),
        ]
    }

    fn depth_largest_width_second_largest_height_smallest(
        &self,
        incoming: &RectToInsert,
    ) -> [BinSection; 3] {
        [
            self.all_empty_space_right_excluding_above(incoming),
            self.all_empty_space_above(incoming),
            self.empty_space_directly_behind(incoming),
        ]
    }

    fn depth_largest_height_second_largest_width_smallest(
        &self,
        incoming: &RectToInsert,
    ) -> [BinSection; 3] {
        [
            self.all_empty_space_right(incoming),
            self.all_empty_space_above_excluding_right(incoming),
            self.empty_space_directly_behind(incoming),
        ]
    }

    fn all_empty_space_above(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new_spread(
            self.x,
            self.y + incoming.height(),
            self.z,
            self.whd.width,
            self.whd.height - incoming.height(),
            self.whd.depth,
        )
    }

    fn all_empty_space_right(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new_spread(
            self.x + incoming.width(),
            self.y,
            self.z,
            self.whd.width - incoming.width(),
            self.whd.height,
            self.whd.depth,
        )
    }

    fn all_empty_space_behind(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new_spread(
            self.x,
            self.y,
            self.z + incoming.depth(),
            self.whd.width,
            self.whd.height,
            self.whd.depth - incoming.depth(),
        )
    }

    fn empty_space_directly_above(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new_spread(
            self.x,
            self.y + incoming.height(),
            self.z,
            incoming.width(),
            self.whd.height - incoming.height(),
            incoming.depth(),
        )
    }

    fn empty_space_directly_right(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new_spread(
            self.x + incoming.width(),
            self.y,
            self.z,
            self.whd.width - incoming.width(),
            incoming.height(),
            incoming.depth(),
        )
    }

    fn empty_space_directly_behind(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x,
            self.y,
            self.z + incoming.depth(),
            WidthHeightDepth {
                width: incoming.width(),
                height: incoming.height(),
                depth: self.whd.depth - incoming.depth(),
            },
        )
    }

    fn all_empty_space_above_excluding_right(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x,
            self.y + incoming.height(),
            self.z,
            WidthHeightDepth {
                width: incoming.width(),
                height: self.whd.height - incoming.height(),
                depth: self.whd.depth,
            },
        )
    }

    fn all_empty_space_above_excluding_behind(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x,
            self.y + incoming.height(),
            self.z,
            WidthHeightDepth {
                width: self.whd.width,
                height: self.whd.height - incoming.height(),
                depth: incoming.depth(),
            },
        )
    }

    fn all_empty_space_right_excluding_above(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x + incoming.width(),
            self.y,
            self.z,
            WidthHeightDepth {
                width: self.whd.width - incoming.width(),
                height: incoming.height(),
                depth: self.whd.depth,
            },
        )
    }

    fn all_empty_space_right_excluding_behind(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x + incoming.width(),
            self.y,
            self.z,
            WidthHeightDepth {
                width: self.whd.width - incoming.width(),
                height: self.whd.height,
                depth: incoming.depth(),
            },
        )
    }

    fn all_empty_space_behind_excluding_above(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x,
            self.y,
            self.z + incoming.depth(),
            WidthHeightDepth {
                width: self.whd.width,
                height: incoming.height(),
                depth: self.whd.depth - incoming.depth(),
            },
        )
    }

    fn all_empty_space_behind_excluding_right(&self, incoming: &RectToInsert) -> BinSection {
        BinSection::new(
            self.x,
            self.y,
            self.z + incoming.depth(),
            WidthHeightDepth {
                width: incoming.width(),
                height: self.whd.height,
                depth: self.whd.depth - incoming.depth(),
            },
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{volume_heuristic, RectToInsert};

    const BIGGEST: u32 = 50;
    const MIDDLE: u32 = 25;
    const SMALLEST: u32 = 10;

    const FULL: u32 = 100;

    /// If we're trying to place a rectangle that is wider than the container we return an error
    #[test]
    fn error_if_placement_is_wider_than_bin_section() {
        let bin_section = bin_section_width_height_depth(5, 20, 1);
        let placement = RectToInsert::new(6, 20, 1);

        assert_eq!(
            bin_section
                .try_place(&placement, &contains_smallest_box, &volume_heuristic)
                .unwrap_err(),
            BinSectionError::PlacementWiderThanBinSection
        );
    }

    /// If we're trying to place a rectangle that is taller than the container we return an error
    #[test]
    fn error_if_placement_is_taller_than_bin_section() {
        let bin_section = bin_section_width_height_depth(5, 20, 1);
        let placement = RectToInsert::new(5, 21, 1);

        assert_eq!(
            bin_section
                .try_place(&placement, &contains_smallest_box, &volume_heuristic)
                .unwrap_err(),
            BinSectionError::PlacementTallerThanBinSection
        );
    }

    /// If we're trying to place a rectangle that is deeper than the container we return an error
    #[test]
    fn error_if_placement_is_deeper_than_bin_section() {
        let bin_section = bin_section_width_height_depth(5, 20, 1);
        let placement = RectToInsert::new(5, 20, 2);

        assert_eq!(
            bin_section
                .try_place(&placement, &contains_smallest_box, &volume_heuristic)
                .unwrap_err(),
            BinSectionError::PlacementDeeperThanBinSection
        );
    }

    fn test_splits(
        container_dimensions: u32,
        rect_to_place: WidthHeightDepth,
        mut expected: [BinSection; 3],
    ) {
        let dim = container_dimensions;
        let bin_section = bin_section_width_height_depth(dim, dim, dim);

        let whd = rect_to_place;

        let placement = RectToInsert::new(whd.width, whd.height, whd.depth);

        let mut packed = bin_section
            .try_place(&placement, &contains_smallest_box, &volume_heuristic)
            .unwrap();

        packed.1.sort();
        expected.sort();

        assert_eq!(packed.1, expected);
    }

    /// Verify that we choose the correct splits when the placed rectangle is width > height > depth
    #[test]
    fn width_largest_height_second_largest_depth_smallest() {
        let whd = WidthHeightDepth {
            width: BIGGEST,
            height: MIDDLE,
            depth: SMALLEST,
        };

        test_splits(
            FULL,
            whd,
            [
                BinSection::new_spread(whd.width, 0, 0, FULL - whd.width, whd.height, whd.depth),
                BinSection::new_spread(0, whd.height, 0, FULL, FULL - whd.height, whd.depth),
                BinSection::new_spread(0, 0, whd.depth, FULL, FULL, FULL - whd.depth),
            ],
        );
    }

    /// Verify that we choose the correct splits when the placed rectangle is width > depth > height
    #[test]
    fn width_largest_depth_second_largest_height_smallest() {
        let whd = WidthHeightDepth {
            width: BIGGEST,
            height: SMALLEST,
            depth: MIDDLE,
        };

        test_splits(
            FULL,
            whd,
            [
                BinSection::new_spread(whd.width, 0, 0, FULL - whd.width, whd.height, whd.depth),
                BinSection::new_spread(0, whd.height, 0, FULL, FULL - whd.height, FULL),
                BinSection::new_spread(0, 0, whd.depth, FULL, whd.height, FULL - whd.depth),
            ],
        );
    }

    /// Verify that we choose the correct splits when the placed rectangle is height > width > depth
    #[test]
    fn height_largest_width_second_largest_depth_smallest() {
        let whd = WidthHeightDepth {
            width: MIDDLE,
            height: BIGGEST,
            depth: SMALLEST,
        };

        test_splits(
            FULL,
            whd,
            [
                BinSection::new_spread(whd.width, 0, 0, FULL - whd.width, FULL, whd.depth),
                BinSection::new_spread(0, whd.height, 0, whd.width, FULL - whd.height, whd.depth),
                BinSection::new_spread(0, 0, whd.depth, FULL, FULL, FULL - whd.depth),
            ],
        );
    }

    /// Verify that we choose the correct splits when the placed rectangle is height > depth > width
    #[test]
    fn height_largest_depth_second_largest_width_smallest() {
        let whd = WidthHeightDepth {
            width: SMALLEST,
            height: BIGGEST,
            depth: MIDDLE,
        };

        test_splits(
            FULL,
            whd,
            [
                BinSection::new_spread(whd.width, 0, 0, FULL - whd.width, FULL, FULL),
                BinSection::new_spread(0, whd.height, 0, whd.width, FULL - whd.height, whd.depth),
                BinSection::new_spread(0, 0, whd.depth, whd.width, FULL, FULL - whd.depth),
            ],
        );
    }

    /// Verify that we choose the correct splits when the placed rectangle is depth > width > height
    #[test]
    fn depth_largest_width_second_largest_height_smallest() {
        let whd = WidthHeightDepth {
            width: MIDDLE,
            height: SMALLEST,
            depth: BIGGEST,
        };

        test_splits(
            FULL,
            whd,
            [
                BinSection::new_spread(whd.width, 0, 0, FULL - whd.width, whd.height, FULL),
                BinSection::new_spread(0, whd.height, 0, FULL, FULL - whd.height, FULL),
                BinSection::new_spread(0, 0, whd.depth, whd.width, whd.height, FULL - whd.depth),
            ],
        );
    }

    /// Verify that we choose the correct splits when the placed rectangle is depth > height > width
    #[test]
    fn depth_largest_height_second_largest_width_smallest() {
        let whd = WidthHeightDepth {
            width: SMALLEST,
            height: MIDDLE,
            depth: BIGGEST,
        };

        test_splits(
            FULL,
            whd,
            [
                BinSection::new_spread(whd.width, 0, 0, FULL - whd.width, FULL, FULL),
                BinSection::new_spread(0, whd.height, 0, whd.width, FULL - whd.height, FULL),
                BinSection::new_spread(0, 0, whd.depth, whd.width, whd.height, FULL - whd.depth),
            ],
        );
    }

    // #[test]
    // fn todo() {
    //    unimplemented!("Add tests for supporting rotation");
    // }

    fn bin_section_width_height_depth(width: u32, height: u32, depth: u32) -> BinSection {
        BinSection::new(
            0,
            0,
            0,
            WidthHeightDepth {
                width,
                height,
                depth,
            },
        )
    }
}