开发者

is there a function in C or C++ to do "saturation" on an integer

开发者 https://www.devze.com 2023-01-28 23:05 出处:网络
I am doing some 3D graphics and I have an open ocean. For this ocean, I have a matrix representing the sea state (i.e. wave heights) for a particular rectangular subsection of the sea. The rest of the

I am doing some 3D graphics and I have an open ocean. For this ocean, I have a matrix representing the sea state (i.e. wave heights) for a particular rectangular subsection of the sea. The rest of the ocean is flat. My problem is that my controlled sea, where there are waves, is positioned in the middle of open flat sea, and the discontinuity at the edges of my grid causes some bad artifacts. The reason I am only generating waves for a subsection and not the entire sea is because my noise function is prohibitively expensive to compute on the entire sea (and I know the easiest solution is to use a cheaper noise function like simplex noise, but that's not an option).

Having said that my question is really rather simple. If say I have a grid (aka matrix aka 2d array) of size 100x40, and I want to find the value for position 120x33, I simply want to take the nearest neighbour, which would be 100x33. So for any number that lies outside a given range, I want that number to saturate to lie within the given range. Is there a function in C or C++ that does this?

Edit: the position parameters are of type 开发者_Python百科float

I know I can do this with some simple if statements, but it just seems like something that the standard libraries would include.


And now there is, in the form of std::clamp. And I'm barely seven years late :)


template<typename T>
T saturate(T val, T min, T max) {
    return std::min(std::max(val, min), max);
}


ISO/IEC JTC1 SC22 WG14 N1169 (Programming languages - C - Extensions to support embedded processors) specifies a _Sat type qualifier for saturating data types. I have never tried to use it in any compiler, but it is included in the GCC 4.x documentation.

VC++ 2003 onward supports MMX intrinsics that allow saturating arithmetic.


Min and Max no?

x = std::min(100,x);
y = std::min(40,y);


Or if you like complicated defines !

#define DERIVE_MAX (100)

//Saturate X at +/-DERIVE_MAX
#define SAT(x) ( ((x) > DERIVE_MAX) ? DERIVE_MAX : ( (-(x) > DERIVE_MAX) ? (-DERIVE_MAX) : (x) ) )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号