Clamping a vector to a minimum and maximum?
I came accross this: t = Clamp(t/d, 0, 1) but I'm not sure how to perform this operation on a vector. What are the steps to clamp a vector if one was writing their own vector implementation?
Thanks
clamp clamping a vector to a minimum and a maximum
ex:
pc = # the point you are coloring now
p0 = # start point
p1 = # end point
v = p1 - p0
d = Length(v)
v = Normalize(v) # or Scale(v, 1/d)
v0 = pc - p0
t = 开发者_JAVA技巧Dot(v0, v)
t = Clamp(t/d, 0, 1)
color = (start_color * t) + (end_color * (1 - t))
I think that once you state clearly what you mean you'll find that most of the work is done for you...
I'm guessing you want to limit the length of the vector quantity (rather than a vector data structure) to lie within a specified range without changing its direction, no?
So:
if (v.length > max)
v.setlength(max)
else if (v.length < min)
v. setlength(min)
where the implementation of length()
and setlength()
depend on how you have stored your vector.
If your vector is stored in (angle,magnitude) form this is nearly trivial. If stored in Cartesian form (ie. (x,y,z) ) you get length
from the Pythagorian theorem and setlength
should scale each commponent by a factor of desired_length/current_length
.
clamp(vec, lb, ub) == min(max(vec, lb), ub)
edit
min and max are usually primitive operations on vectors. For example, if you're using SSE vectors, there are _mm_min_ps and _mm_max_ps intrinsics that turn into MINPS and MAXPS instructions on x86.
The easiest answer is when you consider a vector in a spherical coordinate system: {R, φ, θ}. φ and θ are already limited to [-π,+π] and [-½π, +½π] anyway. Hence, you only need to clamp the distance from the origin R.
Well, I'd assuming you'd want to clamp each of the coordinates individually. So...
void clamp(const Vector3 &v, const Vector3 &min, const Vector3 &max)
{
v.x = clamp(v.x, min.x, max.x);
v.y = clamp(v.y, min.y, max.y);
v.z = clamp(v.z, min.z, max.z);
}
int clamp(int value, int min, int max)
{
if (value < min)
{
return min;
}
else if (value > max)
{
return max;
}
return value;
}
Hope that helps.
精彩评论