DisjointRectSet.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <SharedGraphics/DisjointRectSet.h>
  2. void DisjointRectSet::add(const Rect& new_rect)
  3. {
  4. for (auto& rect : m_rects) {
  5. if (rect.contains(new_rect))
  6. return;
  7. }
  8. m_rects.append(new_rect);
  9. if (m_rects.size() > 1)
  10. shatter();
  11. }
  12. void DisjointRectSet::shatter()
  13. {
  14. Vector<Rect> output;
  15. output.ensure_capacity(m_rects.size());
  16. bool pass_had_intersections = false;
  17. do {
  18. pass_had_intersections = false;
  19. output.clear_with_capacity();
  20. for (size_t i = 0; i < m_rects.size(); ++i) {
  21. auto& r1 = m_rects[i];
  22. for (size_t j = 0; j < m_rects.size(); ++j) {
  23. if (i == j)
  24. continue;
  25. auto& r2 = m_rects[j];
  26. if (!r1.intersects(r2))
  27. continue;
  28. pass_had_intersections = true;
  29. auto pieces = r1.shatter(r2);
  30. for (auto& piece : pieces)
  31. output.append(piece);
  32. m_rects.remove(i);
  33. for (; i < m_rects.size(); ++i)
  34. output.append(m_rects[i]);
  35. goto next_pass;
  36. }
  37. output.append(r1);
  38. }
  39. next_pass:
  40. swap(output, m_rects);
  41. } while(pass_had_intersections);
  42. }