-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy path2d_rectangle_presolve.cc
More file actions
1568 lines (1439 loc) · 62.9 KB
/
2d_rectangle_presolve.cc
File metadata and controls
1568 lines (1439 loc) · 62.9 KB
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
// Copyright 2010-2025 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/2d_rectangle_presolve.h"
#include <algorithm>
#include <array>
#include <limits>
#include <memory>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/log_severity.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/log/vlog_is_on.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "ortools/base/stl_util.h"
#include "ortools/graph/minimum_vertex_cover.h"
#include "ortools/graph/strongly_connected_components.h"
#include "ortools/sat/diffn_util.h"
#include "ortools/sat/integer_base.h"
namespace operations_research {
namespace sat {
namespace {
std::vector<Rectangle> FindSpacesThatCannotBeOccupied(
absl::Span<const Rectangle> fixed_boxes,
absl::Span<const RectangleInRange> non_fixed_boxes,
const Rectangle& bounding_box, IntegerValue min_x_size,
IntegerValue min_y_size) {
std::vector<Rectangle> optional_boxes = {fixed_boxes.begin(),
fixed_boxes.end()};
if (bounding_box.x_min > std::numeric_limits<IntegerValue>::min() &&
bounding_box.y_min > std::numeric_limits<IntegerValue>::min() &&
bounding_box.x_max < std::numeric_limits<IntegerValue>::max() &&
bounding_box.y_max < std::numeric_limits<IntegerValue>::max()) {
// Add fake rectangles to build a frame around the bounding box. This allows
// to find more areas that must be empty. The frame is as follows:
// +************
// +...........+
// +...........+
// +...........+
// ************+
optional_boxes.push_back({.x_min = bounding_box.x_min - 1,
.x_max = bounding_box.x_max,
.y_min = bounding_box.y_min - 1,
.y_max = bounding_box.y_min});
optional_boxes.push_back({.x_min = bounding_box.x_max,
.x_max = bounding_box.x_max + 1,
.y_min = bounding_box.y_min - 1,
.y_max = bounding_box.y_max});
optional_boxes.push_back({.x_min = bounding_box.x_min,
.x_max = bounding_box.x_max + 1,
.y_min = bounding_box.y_max,
.y_max = bounding_box.y_max + 1});
optional_boxes.push_back({.x_min = bounding_box.x_min - 1,
.x_max = bounding_box.x_min,
.y_min = bounding_box.y_min,
.y_max = bounding_box.y_max + 1});
}
// All items we added to `optional_boxes` at this point are only to be used by
// the "gap between items" logic below. They are not actual optional boxes and
// should be removed right after the logic is applied.
const int num_optional_boxes_to_remove = optional_boxes.size();
// Add a rectangle to `optional_boxes` but respecting that rectangles must
// remain disjoint.
const auto add_box = [&optional_boxes](Rectangle new_box) {
std::vector<Rectangle> to_add = {std::move(new_box)};
for (int i = 0; i < to_add.size(); ++i) {
Rectangle new_box = to_add[i];
bool is_disjoint = true;
for (const Rectangle& existing_box : optional_boxes) {
if (!new_box.IsDisjoint(existing_box)) {
is_disjoint = false;
for (const Rectangle& disjoint_box :
new_box.RegionDifference(existing_box)) {
to_add.push_back(disjoint_box);
}
break;
}
}
if (is_disjoint) {
optional_boxes.push_back(std::move(new_box));
}
}
};
// Now check if there is any space that cannot be occupied by any non-fixed
// item.
// TODO(user): remove the limit of 1000 and reimplement FindEmptySpaces()
// using a sweep line algorithm.
if (non_fixed_boxes.size() < 1000) {
std::vector<Rectangle> bounding_boxes;
bounding_boxes.reserve(non_fixed_boxes.size());
for (const RectangleInRange& box : non_fixed_boxes) {
bounding_boxes.push_back(box.bounding_area);
}
std::vector<Rectangle> empty_spaces =
FindEmptySpaces(bounding_box, std::move(bounding_boxes));
for (const Rectangle& r : empty_spaces) {
add_box(r);
}
}
// Now look for gaps between objects that are too small to place anything.
for (int i = 1; i < optional_boxes.size(); ++i) {
const Rectangle cur_box = optional_boxes[i];
for (int j = 0; j < i; ++j) {
const Rectangle& other_box = optional_boxes[j];
const IntegerValue lower_top = std::min(cur_box.y_max, other_box.y_max);
const IntegerValue higher_bottom =
std::max(other_box.y_min, cur_box.y_min);
const IntegerValue rightmost_left_edge =
std::max(other_box.x_min, cur_box.x_min);
const IntegerValue leftmost_right_edge =
std::min(other_box.x_max, cur_box.x_max);
if (rightmost_left_edge < leftmost_right_edge) {
if (lower_top < higher_bottom &&
higher_bottom - lower_top < min_y_size) {
add_box({.x_min = rightmost_left_edge,
.x_max = leftmost_right_edge,
.y_min = lower_top,
.y_max = higher_bottom});
}
}
if (higher_bottom < lower_top) {
if (leftmost_right_edge < rightmost_left_edge &&
rightmost_left_edge - leftmost_right_edge < min_x_size) {
add_box({.x_min = leftmost_right_edge,
.x_max = rightmost_left_edge,
.y_min = higher_bottom,
.y_max = lower_top});
}
}
}
}
optional_boxes.erase(optional_boxes.begin(),
optional_boxes.begin() + num_optional_boxes_to_remove);
return optional_boxes;
}
} // namespace
bool PresolveFixed2dRectangles(
absl::Span<const RectangleInRange> non_fixed_boxes,
std::vector<Rectangle>* fixed_boxes) {
// This implementation compiles a set of areas that cannot be occupied by any
// item, then calls ReduceNumberofBoxes() to use these areas to minimize
// `fixed_boxes`.
bool changed = false;
DCHECK(FindPartialRectangleIntersections(*fixed_boxes).empty());
IntegerValue original_area = 0;
std::vector<Rectangle> fixed_boxes_copy;
if (VLOG_IS_ON(1)) {
for (const Rectangle& r : *fixed_boxes) {
original_area += r.Area();
}
}
if (VLOG_IS_ON(2)) {
fixed_boxes_copy = *fixed_boxes;
}
const int original_num_boxes = fixed_boxes->size();
// The greedy algorithm is really fast. Run it first since it might greatly
// reduce the size of large trivial instances.
std::vector<Rectangle> empty_vec;
if (ReduceNumberofBoxesGreedy(fixed_boxes, &empty_vec)) {
changed = true;
}
IntegerValue min_x_size = std::numeric_limits<IntegerValue>::max();
IntegerValue min_y_size = std::numeric_limits<IntegerValue>::max();
CHECK(!non_fixed_boxes.empty());
Rectangle bounding_box = non_fixed_boxes[0].bounding_area;
for (const RectangleInRange& box : non_fixed_boxes) {
bounding_box.GrowToInclude(box.bounding_area);
min_x_size = std::min(min_x_size, box.x_size);
min_y_size = std::min(min_y_size, box.y_size);
}
DCHECK_GT(min_x_size, 0);
DCHECK_GT(min_y_size, 0);
// Fixed items are only useful to constraint where the non-fixed items can be
// placed. This means in particular that any part of a fixed item outside the
// bounding box of the non-fixed items is useless. Clip them.
int new_size = 0;
while (new_size < fixed_boxes->size()) {
Rectangle& rectangle = (*fixed_boxes)[new_size];
DCHECK_GT(rectangle.SizeX(), 0);
DCHECK_GT(rectangle.SizeY(), 0);
if (rectangle.x_min < bounding_box.x_min) {
rectangle.x_min = bounding_box.x_min;
changed = true;
}
if (rectangle.x_max > bounding_box.x_max) {
rectangle.x_max = bounding_box.x_max;
changed = true;
}
if (rectangle.y_min < bounding_box.y_min) {
rectangle.y_min = bounding_box.y_min;
changed = true;
}
if (rectangle.y_max > bounding_box.y_max) {
rectangle.y_max = bounding_box.y_max;
changed = true;
}
if (rectangle.SizeX() <= 0 || rectangle.SizeY() <= 0) {
// The whole rectangle was outside of the domain, remove it.
std::swap(rectangle, (*fixed_boxes)[fixed_boxes->size() - 1]);
fixed_boxes->resize(fixed_boxes->size() - 1);
changed = true;
continue;
} else {
new_size++;
}
}
std::vector<Rectangle> optional_boxes = FindSpacesThatCannotBeOccupied(
*fixed_boxes, non_fixed_boxes, bounding_box, min_x_size, min_y_size);
// TODO(user): instead of doing the greedy algorithm first with optional
// boxes, and then the one that is exact for mandatory boxes but weak for
// optional ones, refactor the second algorithm. One possible way of doing
// that would be to follow the shape boundary of optional+mandatory boxes and
// look whether we can shave off some turns. For example, if we have a shape
// like below, with the "+" representing area covered by optional boxes, we
// can replace the turns by a straight line.
//
// -->
// ^ ++++
// . ++++ .
// . ++++ . =>
// ++++ \/
// --> ++++ --> -->
// *********** ***********
// *********** ***********
//
// Since less turns means less edges, this should be a good way to reduce the
// number of boxes.
if (ReduceNumberofBoxesGreedy(fixed_boxes, &optional_boxes)) {
changed = true;
}
const int num_after_first_pass = fixed_boxes->size();
if (ReduceNumberOfBoxesExactMandatory(fixed_boxes, &optional_boxes)) {
changed = true;
}
if (changed && VLOG_IS_ON(1)) {
IntegerValue area = 0;
for (const Rectangle& r : *fixed_boxes) {
area += r.Area();
}
VLOG_EVERY_N_SEC(1, 1) << "Presolved " << original_num_boxes
<< " fixed rectangles (area=" << original_area
<< ") into " << num_after_first_pass << " then "
<< fixed_boxes->size() << " (area=" << area << ")";
VLOG_EVERY_N_SEC(2, 2) << "Presolved rectangles:\n"
<< RenderDot(bounding_box, fixed_boxes_copy)
<< "Into:\n"
<< RenderDot(bounding_box, *fixed_boxes)
<< (optional_boxes.empty()
? ""
: absl::StrCat("Unused optional rects:\n",
RenderDot(bounding_box,
optional_boxes)));
}
return changed;
}
namespace {
struct Edge {
IntegerValue x_start;
IntegerValue y_start;
IntegerValue size;
static Edge GetEdge(const Rectangle& rectangle, EdgePosition pos) {
switch (pos) {
case EdgePosition::TOP:
return {.x_start = rectangle.x_min,
.y_start = rectangle.y_max,
.size = rectangle.SizeX()};
case EdgePosition::BOTTOM:
return {.x_start = rectangle.x_min,
.y_start = rectangle.y_min,
.size = rectangle.SizeX()};
case EdgePosition::LEFT:
return {.x_start = rectangle.x_min,
.y_start = rectangle.y_min,
.size = rectangle.SizeY()};
case EdgePosition::RIGHT:
return {.x_start = rectangle.x_max,
.y_start = rectangle.y_min,
.size = rectangle.SizeY()};
}
LOG(FATAL) << "Invalid edge position: " << static_cast<int>(pos);
}
template <typename H>
friend H AbslHashValue(H h, const Edge& e) {
return H::combine(std::move(h), e.x_start, e.y_start, e.size);
}
bool operator==(const Edge& other) const {
return x_start == other.x_start && y_start == other.y_start &&
size == other.size;
}
static bool CompareXThenY(const Edge& a, const Edge& b) {
return std::tie(a.x_start, a.y_start, a.size) <
std::tie(b.x_start, b.y_start, b.size);
}
static bool CompareYThenX(const Edge& a, const Edge& b) {
return std::tie(a.y_start, a.x_start, a.size) <
std::tie(b.y_start, b.x_start, b.size);
}
};
} // namespace
bool ReduceNumberofBoxesGreedy(std::vector<Rectangle>* mandatory_rectangles,
std::vector<Rectangle>* optional_rectangles) {
// The current implementation just greedly merge rectangles that shares an
// edge.
std::vector<std::unique_ptr<Rectangle>> rectangle_storage;
enum class OptionalEnum { OPTIONAL, MANDATORY };
// bool for is_optional
std::vector<std::pair<const Rectangle*, OptionalEnum>> rectangles_ptr;
absl::flat_hash_map<Edge, int> top_edges_to_rectangle;
absl::flat_hash_map<Edge, int> bottom_edges_to_rectangle;
absl::flat_hash_map<Edge, int> left_edges_to_rectangle;
absl::flat_hash_map<Edge, int> right_edges_to_rectangle;
bool changed_optional = false;
bool changed_mandatory = false;
auto add_rectangle = [&](const Rectangle* rectangle_ptr,
OptionalEnum optional) {
const int index = rectangles_ptr.size();
rectangles_ptr.push_back({rectangle_ptr, optional});
const Rectangle& rectangle = *rectangles_ptr[index].first;
top_edges_to_rectangle[Edge::GetEdge(rectangle, EdgePosition::TOP)] = index;
bottom_edges_to_rectangle[Edge::GetEdge(rectangle, EdgePosition::BOTTOM)] =
index;
left_edges_to_rectangle[Edge::GetEdge(rectangle, EdgePosition::LEFT)] =
index;
right_edges_to_rectangle[Edge::GetEdge(rectangle, EdgePosition::RIGHT)] =
index;
};
for (const Rectangle& rectangle : *mandatory_rectangles) {
add_rectangle(&rectangle, OptionalEnum::MANDATORY);
}
for (const Rectangle& rectangle : *optional_rectangles) {
add_rectangle(&rectangle, OptionalEnum::OPTIONAL);
}
auto remove_rectangle = [&](const int index) {
const Rectangle& rectangle = *rectangles_ptr[index].first;
const Edge top_edge = Edge::GetEdge(rectangle, EdgePosition::TOP);
const Edge bottom_edge = Edge::GetEdge(rectangle, EdgePosition::BOTTOM);
const Edge left_edge = Edge::GetEdge(rectangle, EdgePosition::LEFT);
const Edge right_edge = Edge::GetEdge(rectangle, EdgePosition::RIGHT);
top_edges_to_rectangle.erase(top_edge);
bottom_edges_to_rectangle.erase(bottom_edge);
left_edges_to_rectangle.erase(left_edge);
right_edges_to_rectangle.erase(right_edge);
rectangles_ptr[index].first = nullptr;
};
bool iteration_did_merge = true;
while (iteration_did_merge) {
iteration_did_merge = false;
for (int i = 0; i < rectangles_ptr.size(); ++i) {
if (!rectangles_ptr[i].first) {
continue;
}
const Rectangle& rectangle = *rectangles_ptr[i].first;
const Edge top_edge = Edge::GetEdge(rectangle, EdgePosition::TOP);
const Edge bottom_edge = Edge::GetEdge(rectangle, EdgePosition::BOTTOM);
const Edge left_edge = Edge::GetEdge(rectangle, EdgePosition::LEFT);
const Edge right_edge = Edge::GetEdge(rectangle, EdgePosition::RIGHT);
int index = -1;
if (const auto it = right_edges_to_rectangle.find(left_edge);
it != right_edges_to_rectangle.end()) {
index = it->second;
} else if (const auto it = left_edges_to_rectangle.find(right_edge);
it != left_edges_to_rectangle.end()) {
index = it->second;
} else if (const auto it = bottom_edges_to_rectangle.find(top_edge);
it != bottom_edges_to_rectangle.end()) {
index = it->second;
} else if (const auto it = top_edges_to_rectangle.find(bottom_edge);
it != top_edges_to_rectangle.end()) {
index = it->second;
}
if (index == -1) {
continue;
}
iteration_did_merge = true;
// Merge two rectangles!
const OptionalEnum new_optional =
(rectangles_ptr[i].second == OptionalEnum::MANDATORY ||
rectangles_ptr[index].second == OptionalEnum::MANDATORY)
? OptionalEnum::MANDATORY
: OptionalEnum::OPTIONAL;
changed_mandatory =
changed_mandatory || (new_optional == OptionalEnum::MANDATORY);
changed_optional =
changed_optional ||
(rectangles_ptr[i].second == OptionalEnum::OPTIONAL ||
rectangles_ptr[index].second == OptionalEnum::OPTIONAL);
rectangle_storage.push_back(std::make_unique<Rectangle>(rectangle));
Rectangle& new_rectangle = *rectangle_storage.back();
new_rectangle.GrowToInclude(*rectangles_ptr[index].first);
remove_rectangle(i);
remove_rectangle(index);
add_rectangle(&new_rectangle, new_optional);
}
}
if (changed_mandatory) {
std::vector<Rectangle> new_rectangles;
for (auto [rectangle, optional] : rectangles_ptr) {
if (rectangle && optional == OptionalEnum::MANDATORY) {
new_rectangles.push_back(*rectangle);
}
}
*mandatory_rectangles = std::move(new_rectangles);
}
if (changed_optional) {
std::vector<Rectangle> new_rectangles;
for (auto [rectangle, optional] : rectangles_ptr) {
if (rectangle && optional == OptionalEnum::OPTIONAL) {
new_rectangles.push_back(*rectangle);
}
}
*optional_rectangles = std::move(new_rectangles);
}
return changed_mandatory;
}
Neighbours BuildNeighboursGraph(absl::Span<const Rectangle> rectangles) {
// To build a graph of neighbours, we build a sorted vector for each one of
// the edges (top, bottom, etc) of the rectangles. Then we merge the bottom
// and top vectors and iterate on it. Due to the sorting order, segments where
// the bottom of a rectangle touches the top of another one must consecutive.
std::vector<std::pair<Edge, int>> edges_to_rectangle[4];
std::vector<std::tuple<int, EdgePosition, int>> neighbours;
neighbours.reserve(2 * rectangles.size());
for (int edge_int = 0; edge_int < 4; ++edge_int) {
const EdgePosition edge_position = static_cast<EdgePosition>(edge_int);
edges_to_rectangle[edge_position].reserve(rectangles.size());
}
for (int i = 0; i < rectangles.size(); ++i) {
const Rectangle& rectangle = rectangles[i];
for (int edge_int = 0; edge_int < 4; ++edge_int) {
const EdgePosition edge_position = static_cast<EdgePosition>(edge_int);
const Edge edge = Edge::GetEdge(rectangle, edge_position);
edges_to_rectangle[edge_position].push_back({edge, i});
}
}
for (int edge_int = 0; edge_int < 4; ++edge_int) {
const EdgePosition edge_position = static_cast<EdgePosition>(edge_int);
const bool sort_x_then_y = edge_position == EdgePosition::LEFT ||
edge_position == EdgePosition::RIGHT;
const auto cmp =
sort_x_then_y
? [](const std::pair<Edge, int>& a,
const std::pair<Edge, int>&
b) { return Edge::CompareXThenY(a.first, b.first); }
: [](const std::pair<Edge, int>& a, const std::pair<Edge, int>& b) {
return Edge::CompareYThenX(a.first, b.first);
};
absl::c_sort(edges_to_rectangle[edge_position], cmp);
}
constexpr struct EdgeData {
EdgePosition edge;
EdgePosition opposite_edge;
bool (*cmp)(const Edge&, const Edge&);
} edge_data[4] = {{.edge = EdgePosition::BOTTOM,
.opposite_edge = EdgePosition::TOP,
.cmp = &Edge::CompareYThenX},
{.edge = EdgePosition::TOP,
.opposite_edge = EdgePosition::BOTTOM,
.cmp = &Edge::CompareYThenX},
{.edge = EdgePosition::LEFT,
.opposite_edge = EdgePosition::RIGHT,
.cmp = &Edge::CompareXThenY},
{.edge = EdgePosition::RIGHT,
.opposite_edge = EdgePosition::LEFT,
.cmp = &Edge::CompareXThenY}};
for (int edge_int = 0; edge_int < 4; ++edge_int) {
const EdgePosition edge_position = edge_data[edge_int].edge;
const EdgePosition opposite_edge_position =
edge_data[edge_int].opposite_edge;
auto it = edges_to_rectangle[edge_position].begin();
for (const auto& [edge, index] :
edges_to_rectangle[opposite_edge_position]) {
while (it != edges_to_rectangle[edge_position].end() &&
edge_data[edge_int].cmp(it->first, edge)) {
++it;
}
if (it == edges_to_rectangle[edge_position].end()) {
break;
}
if (edge_position == EdgePosition::BOTTOM ||
edge_position == EdgePosition::TOP) {
while (it != edges_to_rectangle[edge_position].end() &&
it->first.y_start == edge.y_start &&
it->first.x_start < edge.x_start + edge.size) {
neighbours.push_back({index, opposite_edge_position, it->second});
neighbours.push_back({it->second, edge_position, index});
++it;
}
} else {
while (it != edges_to_rectangle[edge_position].end() &&
it->first.x_start == edge.x_start &&
it->first.y_start < edge.y_start + edge.size) {
neighbours.push_back({index, opposite_edge_position, it->second});
neighbours.push_back({it->second, edge_position, index});
++it;
}
}
}
}
gtl::STLSortAndRemoveDuplicates(&neighbours);
return Neighbours(rectangles, neighbours);
}
std::vector<std::vector<int>> SplitInConnectedComponents(
const Neighbours& neighbours) {
class GraphView {
public:
explicit GraphView(const Neighbours& neighbours)
: neighbours_(neighbours) {}
absl::Span<const int> operator[](int node) const {
temp_.clear();
for (int edge = 0; edge < 4; ++edge) {
const auto edge_neighbors = neighbours_.GetSortedNeighbors(
node, static_cast<EdgePosition>(edge));
for (int neighbor : edge_neighbors) {
temp_.push_back(neighbor);
}
}
return temp_;
}
private:
const Neighbours& neighbours_;
mutable std::vector<int> temp_;
};
std::vector<std::vector<int>> components;
FindStronglyConnectedComponents(neighbours.NumRectangles(),
GraphView(neighbours), &components);
return components;
}
namespace {
IntegerValue GetClockwiseStart(EdgePosition edge, const Rectangle& rectangle) {
switch (edge) {
case EdgePosition::LEFT:
return rectangle.y_min;
case EdgePosition::RIGHT:
return rectangle.y_max;
case EdgePosition::BOTTOM:
return rectangle.x_max;
case EdgePosition::TOP:
return rectangle.x_min;
}
LOG(FATAL) << "Invalid edge position: " << static_cast<int>(edge);
}
IntegerValue GetClockwiseEnd(EdgePosition edge, const Rectangle& rectangle) {
switch (edge) {
case EdgePosition::LEFT:
return rectangle.y_max;
case EdgePosition::RIGHT:
return rectangle.y_min;
case EdgePosition::BOTTOM:
return rectangle.x_min;
case EdgePosition::TOP:
return rectangle.x_max;
}
LOG(FATAL) << "Invalid edge position: " << static_cast<int>(edge);
}
// Given a list of rectangles and their neighbours graph, find the list of
// vertical and horizontal segments that touches a single rectangle edge. Or,
// view in another way, the pieces of an edge that is touching the empty space.
// For example, this corresponds to the "0" segments in the example below:
//
// 000000
// 0****0 000000
// 0****0 0****0
// 0****0 0****0
// 00******00000****00000
// 0********************0
// 0********************0
// 0000000000000000000000
void GetAllSegmentsTouchingVoid(
absl::Span<const Rectangle> rectangles, const Neighbours& neighbours,
std::vector<std::pair<Edge, int>>& vertical_edges_on_boundary,
std::vector<std::pair<Edge, int>>& horizontal_edges_on_boundary) {
for (int i = 0; i < rectangles.size(); ++i) {
const Rectangle& rectangle = rectangles[i];
for (int edge_int = 0; edge_int < 4; ++edge_int) {
const EdgePosition edge = static_cast<EdgePosition>(edge_int);
const auto box_neighbors = neighbours.GetSortedNeighbors(i, edge);
if (box_neighbors.empty()) {
if (edge == EdgePosition::LEFT || edge == EdgePosition::RIGHT) {
vertical_edges_on_boundary.push_back(
{Edge::GetEdge(rectangle, edge), i});
} else {
horizontal_edges_on_boundary.push_back(
{Edge::GetEdge(rectangle, edge), i});
}
continue;
}
IntegerValue previous_pos = GetClockwiseStart(edge, rectangle);
for (int n = 0; n <= box_neighbors.size(); ++n) {
IntegerValue neighbor_start;
const Rectangle* neighbor;
if (n == box_neighbors.size()) {
// On the last iteration we consider instead of the next neighbor the
// end of the current box.
neighbor_start = GetClockwiseEnd(edge, rectangle);
} else {
const int neighbor_idx = box_neighbors[n];
neighbor = &rectangles[neighbor_idx];
neighbor_start = GetClockwiseStart(edge, *neighbor);
}
switch (edge) {
case EdgePosition::LEFT:
if (neighbor_start > previous_pos) {
vertical_edges_on_boundary.push_back(
{Edge{.x_start = rectangle.x_min,
.y_start = previous_pos,
.size = neighbor_start - previous_pos},
i});
}
break;
case EdgePosition::RIGHT:
if (neighbor_start < previous_pos) {
vertical_edges_on_boundary.push_back(
{Edge{.x_start = rectangle.x_max,
.y_start = neighbor_start,
.size = previous_pos - neighbor_start},
i});
}
break;
case EdgePosition::BOTTOM:
if (neighbor_start < previous_pos) {
horizontal_edges_on_boundary.push_back(
{Edge{.x_start = neighbor_start,
.y_start = rectangle.y_min,
.size = previous_pos - neighbor_start},
i});
}
break;
case EdgePosition::TOP:
if (neighbor_start > previous_pos) {
horizontal_edges_on_boundary.push_back(
{Edge{.x_start = previous_pos,
.y_start = rectangle.y_max,
.size = neighbor_start - previous_pos},
i});
}
break;
}
if (n != box_neighbors.size()) {
previous_pos = GetClockwiseEnd(edge, *neighbor);
}
}
}
}
}
// Trace a boundary (interior or exterior) that contains the edge described by
// starting_edge_position and starting_step_point. This method removes the edges
// that were added to the boundary from `segments_to_follow`.
ShapePath TraceBoundary(
const EdgePosition& starting_edge_position,
std::pair<IntegerValue, IntegerValue> starting_step_point,
std::array<absl::btree_map<std::pair<IntegerValue, IntegerValue>,
std::pair<IntegerValue, int>>,
4>& segments_to_follow) {
// The boundary is composed of edges on the `segments_to_follow` map. So all
// we need is to find and glue them together on the right order.
ShapePath path;
auto extracted =
segments_to_follow[starting_edge_position].extract(starting_step_point);
CHECK(!extracted.empty());
const int first_index = extracted.mapped().second;
std::pair<IntegerValue, IntegerValue> cur = starting_step_point;
int cur_index = first_index;
// Now we navigate from one edge to the next. To avoid going back, we remove
// used edges from the hash map.
while (true) {
path.step_points.push_back(cur);
bool can_go[4] = {false, false, false, false};
EdgePosition direction_to_take = EdgePosition::LEFT;
for (int edge_int = 0; edge_int < 4; ++edge_int) {
const EdgePosition edge = static_cast<EdgePosition>(edge_int);
if (segments_to_follow[edge].contains(cur)) {
can_go[edge] = true;
direction_to_take = edge;
}
}
if (can_go == absl::Span<const bool>{false, false, false, false}) {
// Cannot move anywhere, we closed the loop.
break;
}
// Handle one pathological case.
if (can_go[EdgePosition::LEFT] && can_go[EdgePosition::RIGHT]) {
// Corner case (literally):
// ********
// ********
// ********
// ********
// ^ +++++++++
// | +++++++++
// | +++++++++
// +++++++++
//
// In this case we keep following the same box.
auto it_x = segments_to_follow[EdgePosition::LEFT].find(cur);
if (cur_index == it_x->second.second) {
direction_to_take = EdgePosition::LEFT;
} else {
direction_to_take = EdgePosition::RIGHT;
}
} else if (can_go[EdgePosition::TOP] && can_go[EdgePosition::BOTTOM]) {
auto it_y = segments_to_follow[EdgePosition::TOP].find(cur);
if (cur_index == it_y->second.second) {
direction_to_take = EdgePosition::TOP;
} else {
direction_to_take = EdgePosition::BOTTOM;
}
}
auto extracted = segments_to_follow[direction_to_take].extract(cur);
cur_index = extracted.mapped().second;
switch (direction_to_take) {
case EdgePosition::LEFT:
cur.first -= extracted.mapped().first;
segments_to_follow[EdgePosition::RIGHT].erase(
cur); // Forbid going back
break;
case EdgePosition::RIGHT:
cur.first += extracted.mapped().first;
segments_to_follow[EdgePosition::LEFT].erase(cur); // Forbid going back
break;
case EdgePosition::TOP:
cur.second += extracted.mapped().first;
segments_to_follow[EdgePosition::BOTTOM].erase(
cur); // Forbid going back
break;
case EdgePosition::BOTTOM:
cur.second -= extracted.mapped().first;
segments_to_follow[EdgePosition::TOP].erase(cur); // Forbid going back
break;
}
path.touching_box_index.push_back(cur_index);
}
path.touching_box_index.push_back(cur_index);
return path;
}
} // namespace
std::vector<SingleShape> BoxesToShapes(absl::Span<const Rectangle> rectangles,
const Neighbours& neighbours) {
std::vector<std::pair<Edge, int>> vertical_edges_on_boundary;
std::vector<std::pair<Edge, int>> horizontal_edges_on_boundary;
GetAllSegmentsTouchingVoid(rectangles, neighbours, vertical_edges_on_boundary,
horizontal_edges_on_boundary);
std::array<absl::btree_map<std::pair<IntegerValue, IntegerValue>,
std::pair<IntegerValue, int>>,
4>
segments_to_follow;
for (const auto& [edge, box_index] : vertical_edges_on_boundary) {
segments_to_follow[EdgePosition::TOP][{edge.x_start, edge.y_start}] = {
edge.size, box_index};
segments_to_follow[EdgePosition::BOTTOM][{
edge.x_start, edge.y_start + edge.size}] = {edge.size, box_index};
}
for (const auto& [edge, box_index] : horizontal_edges_on_boundary) {
segments_to_follow[EdgePosition::RIGHT][{edge.x_start, edge.y_start}] = {
edge.size, box_index};
segments_to_follow[EdgePosition::LEFT][{
edge.x_start + edge.size, edge.y_start}] = {edge.size, box_index};
}
const auto components = SplitInConnectedComponents(neighbours);
std::vector<SingleShape> result(components.size());
std::vector<int> box_to_component(rectangles.size());
for (int i = 0; i < components.size(); ++i) {
for (const int box_index : components[i]) {
box_to_component[box_index] = i;
}
}
while (!segments_to_follow[EdgePosition::LEFT].empty()) {
// Get edge most to the bottom left
const int box_index =
segments_to_follow[EdgePosition::RIGHT].begin()->second.second;
const std::pair<IntegerValue, IntegerValue> starting_step_point =
segments_to_follow[EdgePosition::RIGHT].begin()->first;
const int component_index = box_to_component[box_index];
// The left-most vertical edge of the connected component must be of its
// exterior boundary. So we must always see the exterior boundary before
// seeing any holes.
const bool is_hole = !result[component_index].boundary.step_points.empty();
ShapePath& path = is_hole ? result[component_index].holes.emplace_back()
: result[component_index].boundary;
path = TraceBoundary(EdgePosition::RIGHT, starting_step_point,
segments_to_follow);
if (is_hole) {
// Follow the usual convention that holes are in the inverse orientation
// of the external boundary.
absl::c_reverse(path.step_points);
absl::c_reverse(path.touching_box_index);
}
}
return result;
}
namespace {
struct PolygonCut {
std::pair<IntegerValue, IntegerValue> start;
std::pair<IntegerValue, IntegerValue> end;
int start_index;
int end_index;
struct CmpByStartY {
bool operator()(const PolygonCut& a, const PolygonCut& b) const {
return std::tie(a.start.second, a.start.first) <
std::tie(b.start.second, b.start.first);
}
};
struct CmpByEndY {
bool operator()(const PolygonCut& a, const PolygonCut& b) const {
return std::tie(a.end.second, a.end.first) <
std::tie(b.end.second, b.end.first);
}
};
struct CmpByStartX {
bool operator()(const PolygonCut& a, const PolygonCut& b) const {
return a.start < b.start;
}
};
struct CmpByEndX {
bool operator()(const PolygonCut& a, const PolygonCut& b) const {
return a.end < b.end;
}
};
template <typename Sink>
friend void AbslStringify(Sink& sink, const PolygonCut& diagonal) {
absl::Format(&sink, "(%v,%v)-(%v,%v)", diagonal.start.first,
diagonal.start.second, diagonal.end.first,
diagonal.end.second);
}
};
// A different representation of a shape. The two vectors must have the same
// size. The first one contains the points of the shape and the second one
// contains the index of the next point in the shape.
//
// Note that we code in this file is only correct for shapes with points
// connected only by horizontal or vertical lines.
struct FlatShape {
std::vector<std::pair<IntegerValue, IntegerValue>> points;
std::vector<int> next;
};
EdgePosition GetSegmentDirection(
const std::pair<IntegerValue, IntegerValue>& curr_segment,
const std::pair<IntegerValue, IntegerValue>& next_segment) {
if (curr_segment.first == next_segment.first) {
return next_segment.second > curr_segment.second ? EdgePosition::TOP
: EdgePosition::BOTTOM;
} else {
return next_segment.first > curr_segment.first ? EdgePosition::RIGHT
: EdgePosition::LEFT;
}
}
// Given a polygon, this function returns all line segments that start on a
// concave vertex and follow horizontally or vertically until it reaches the
// border of the polygon. This function returns all such segments grouped on the
// direction the line takes after starting in the concave vertex. Some of those
// segments start and end on a convex vertex, so they will appear twice in the
// output. This function modifies the shape by splitting some of the path
// segments in two. This is needed to make sure that `PolygonCut.start_index`
// and `PolygonCut.end_index` always corresponds to points in the FlatShape,
// even if they are not edges.
std::array<std::vector<PolygonCut>, 4> GetPotentialPolygonCuts(
FlatShape& shape) {
std::array<std::vector<PolygonCut>, 4> cuts;
// First, for each concave vertex we create a cut that starts at it and
// crosses the polygon until infinite (in practice, int_max/int_min).
for (int i = 0; i < shape.points.size(); i++) {
const auto& it = &shape.points[shape.next[i]];
const auto& previous = &shape.points[i];
const auto& next_segment = &shape.points[shape.next[shape.next[i]]];
const EdgePosition previous_dir = GetSegmentDirection(*previous, *it);
const EdgePosition next_dir = GetSegmentDirection(*it, *next_segment);
if ((previous_dir == EdgePosition::TOP && next_dir == EdgePosition::LEFT) ||
(previous_dir == EdgePosition::RIGHT &&
next_dir == EdgePosition::TOP)) {
cuts[EdgePosition::RIGHT].push_back(
{.start = *it,
.end = {std::numeric_limits<IntegerValue>::max(), it->second},
.start_index = shape.next[i]});
}
if ((previous_dir == EdgePosition::BOTTOM &&
next_dir == EdgePosition::RIGHT) ||
(previous_dir == EdgePosition::LEFT &&
next_dir == EdgePosition::BOTTOM)) {
cuts[EdgePosition::LEFT].push_back(
{.start = {std::numeric_limits<IntegerValue>::min(), it->second},
.end = *it,
.end_index = shape.next[i]});
}
if ((previous_dir == EdgePosition::RIGHT &&
next_dir == EdgePosition::TOP) ||
(previous_dir == EdgePosition::BOTTOM &&
next_dir == EdgePosition::RIGHT)) {
cuts[EdgePosition::BOTTOM].push_back(
{.start = {it->first, std::numeric_limits<IntegerValue>::min()},
.end = *it,
.end_index = shape.next[i]});
}
if ((previous_dir == EdgePosition::TOP && next_dir == EdgePosition::LEFT) ||
(previous_dir == EdgePosition::LEFT &&
next_dir == EdgePosition::BOTTOM)) {
cuts[EdgePosition::TOP].push_back(
{.start = *it,
.end = {it->first, std::numeric_limits<IntegerValue>::max()},
.start_index = shape.next[i]});
}
}
// Now that we have one of the points of the segment (the one starting on a
// vertex), we need to find the other point. This is basically finding the
// first path segment that crosses each cut connecting edge->infinity we
// collected above. We do a rather naive implementation of that below and its
// complexity is O(N^2) even if it should be fast in most cases. If it
// turns out to be costly on profiling we can use a more sophisticated
// algorithm for finding the first intersection.
// We need to sort the cuts so we can use binary search to quickly find cuts
// that cross a segment.
std::sort(cuts[EdgePosition::RIGHT].begin(), cuts[EdgePosition::RIGHT].end(),
PolygonCut::CmpByStartY());