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 
17 #ifndef __UTIL_RECT_H__
18 #define __UTIL_RECT_H__
19 
20 #include "util/util_types.h"
21 
22 CCL_NAMESPACE_BEGIN
23 
24 /* Rectangles are represented as a int4 containing the coordinates of the lower-left and
25  * upper-right corners in the order (x0, y0, x1, y1). */
26 
rect_from_shape(int x0,int y0,int w,int h)27 ccl_device_inline int4 rect_from_shape(int x0, int y0, int w, int h)
28 {
29   return make_int4(x0, y0, x0 + w, y0 + h);
30 }
31 
rect_expand(int4 rect,int d)32 ccl_device_inline int4 rect_expand(int4 rect, int d)
33 {
34   return make_int4(rect.x - d, rect.y - d, rect.z + d, rect.w + d);
35 }
36 
37 /* Returns the intersection of two rects. */
rect_clip(int4 a,int4 b)38 ccl_device_inline int4 rect_clip(int4 a, int4 b)
39 {
40   return make_int4(max(a.x, b.x), max(a.y, b.y), min(a.z, b.z), min(a.w, b.w));
41 }
42 
rect_is_valid(int4 rect)43 ccl_device_inline bool rect_is_valid(int4 rect)
44 {
45   return (rect.z > rect.x) && (rect.w > rect.y);
46 }
47 
48 /* Returns the local row-major index of the pixel inside the rect. */
coord_to_local_index(int4 rect,int x,int y)49 ccl_device_inline int coord_to_local_index(int4 rect, int x, int y)
50 {
51   int w = rect.z - rect.x;
52   return (y - rect.y) * w + (x - rect.x);
53 }
54 
55 /* Finds the coordinates of a pixel given by its row-major index in the rect,
56  * and returns whether the pixel is inside it. */
local_index_to_coord(int4 rect,int idx,int * x,int * y)57 ccl_device_inline bool local_index_to_coord(int4 rect, int idx, int *x, int *y)
58 {
59   int w = rect.z - rect.x;
60   *x = (idx % w) + rect.x;
61   *y = (idx / w) + rect.y;
62   return (*y < rect.w);
63 }
64 
rect_size(int4 rect)65 ccl_device_inline int rect_size(int4 rect)
66 {
67   return (rect.z - rect.x) * (rect.w - rect.y);
68 }
69 
70 CCL_NAMESPACE_END
71 
72 #endif /* __UTIL_RECT_H__ */
73