CopyRegion.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #pragma once
  2. #include "Common/Assert.h"
  3. #include "Common/MathUtil.h"
  4. #include <cmath>
  5. namespace SW
  6. {
  7. // Copies a region of source to a region of destination, performing nearest-neighbor rescaling
  8. template <typename T>
  9. void CopyRegion(const T* const source, const MathUtil::Rectangle<int>& srcrect, const int src_width,
  10. const int src_height, T* destination, const MathUtil::Rectangle<int>& dstrect,
  11. const int dst_width, const int dst_height)
  12. {
  13. ASSERT(srcrect.top >= 0 && srcrect.bottom <= src_height);
  14. ASSERT(srcrect.left >= 0 && srcrect.right <= src_width);
  15. ASSERT(dstrect.top >= 0 && dstrect.bottom <= dst_height);
  16. ASSERT(dstrect.left >= 0 && dstrect.right <= dst_width);
  17. int copy_width = dstrect.GetWidth();
  18. int copy_height = dstrect.GetHeight();
  19. double x_ratio = srcrect.GetWidth() / static_cast<double>(dstrect.GetWidth());
  20. double y_ratio = srcrect.GetHeight() / static_cast<double>(dstrect.GetHeight());
  21. for (int y_off = 0; y_off < copy_height; y_off++)
  22. {
  23. for (int x_off = 0; x_off < copy_width; x_off++)
  24. {
  25. int dst_x = dstrect.left + x_off;
  26. int dst_y = dstrect.top + y_off;
  27. int dst_offset = (dst_y * dst_width) + dst_x;
  28. int src_x = srcrect.left + static_cast<int>(std::round(x_off * x_ratio));
  29. int src_y = srcrect.top + static_cast<int>(std::round(y_off * y_ratio));
  30. int src_offset = (src_y * src_width) + src_x;
  31. destination[dst_offset] = source[src_offset];
  32. }
  33. }
  34. }
  35. // Copies the entire image from source to destination, performing nearest-neighbor rescaling
  36. template <typename T>
  37. void CopyRegion(const T* const source, const int src_width, const int src_height, T* destination,
  38. const int dst_width, const int dst_height)
  39. {
  40. MathUtil::Rectangle<int> srcrect{0, 0, src_width, src_height};
  41. MathUtil::Rectangle<int> dstrect{0, 0, dst_width, dst_height};
  42. CopyRegion(source, srcrect, src_width, src_height, destination, dstrect, dst_width, dst_height);
  43. }
  44. } // namespace SW