util_rect.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2017 Blender Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef __UTIL_RECT_H__
  17. #define __UTIL_RECT_H__
  18. #include "util/util_types.h"
  19. CCL_NAMESPACE_BEGIN
  20. /* Rectangles are represented as a int4 containing the coordinates of the lower-left and
  21. * upper-right corners in the order (x0, y0, x1, y1). */
  22. ccl_device_inline int4 rect_from_shape(int x0, int y0, int w, int h)
  23. {
  24. return make_int4(x0, y0, x0 + w, y0 + h);
  25. }
  26. ccl_device_inline int4 rect_expand(int4 rect, int d)
  27. {
  28. return make_int4(rect.x - d, rect.y - d, rect.z + d, rect.w + d);
  29. }
  30. /* Returns the intersection of two rects. */
  31. ccl_device_inline int4 rect_clip(int4 a, int4 b)
  32. {
  33. return make_int4(max(a.x, b.x), max(a.y, b.y), min(a.z, b.z), min(a.w, b.w));
  34. }
  35. ccl_device_inline bool rect_is_valid(int4 rect)
  36. {
  37. return (rect.z > rect.x) && (rect.w > rect.y);
  38. }
  39. /* Returns the local row-major index of the pixel inside the rect. */
  40. ccl_device_inline int coord_to_local_index(int4 rect, int x, int y)
  41. {
  42. int w = rect.z - rect.x;
  43. return (y - rect.y) * w + (x - rect.x);
  44. }
  45. /* Finds the coordinates of a pixel given by its row-major index in the rect,
  46. * and returns whether the pixel is inside it. */
  47. ccl_device_inline bool local_index_to_coord(int4 rect, int idx, int *x, int *y)
  48. {
  49. int w = rect.z - rect.x;
  50. *x = (idx % w) + rect.x;
  51. *y = (idx / w) + rect.y;
  52. return (*y < rect.w);
  53. }
  54. ccl_device_inline int rect_size(int4 rect)
  55. {
  56. return (rect.z - rect.x) * (rect.w - rect.y);
  57. }
  58. CCL_NAMESPACE_END
  59. #endif /* __UTIL_RECT_H__ */