I implemented a day/night shader built on the basis that only pixels on the side of an object that is facing the directional light source are illuminated. I calculate this based on the unit vectors between the directional light's position and the position of the pixel in 3D space:
float3 direction = normalize(Light.Position - Object.Position);
float theta = abs(acos(dot(normalize(Object.Position), direction))) * 180 / 3.14f;
if (theta < 180)
color = float3(1.0f);
else
color = float3(0.2f);
return float4(color, 1.0f);
This works well, but since I am brushing up on my math lately, it got me thinking that I should make sure I understand what acos is returning.
Mathematically, I know that the arccosine should give me an angle in radians from a value between -1 and 1, while cosine should give me a value between -1 and 1 from an angle in radians.
The documentation states that the input value should be between -1 and 1 for acos which follows that idea, but it doesn't tell me if the return value is 0 - π, -π - π, 0 - 2π, or a similar range.
Return Value
The arccosine of the x parameter.
Type Description
Name [Template Type] 'Component Type' Size
x [scalar, vector, or matrix] 'float' any
ret [same as input x] 'float' same dimension(s) as input x
HLSL doesn't really give me a way to test this very easily, so I'm wondering if anyone has any documentation on this.
What is the return range for the HLSL function acos?
I went through some testing on this topic and have discovered that the HLSL version of acos returns a value between 0 and π. I proved this to be true with the following:
n = 0..3
d = [0, 90, 180, 181]
r = π / 180 * d[n]
c = cos(r)
a = acos(c)
The following is the result of the evaluations for d[n]:
d[0] returns a = 0.
d[1] returns a = π/2.
d[2] returns a = π.
d[3] returns a ~= 3.12....
This tells us that the return value for acos stays true to the range of usual principle values for arccosine:
0 ≤ acos(x) ≤ π
Also remaining consistent with the definition:
acos(cos(θ)) = θ
I have provided feedback to Microsoft with regards to the lack of detailed documentation on HLSL intrinsic functions in comparison to more common languages.
Related
Making a game using Golang since it seems to work quite well for games. I made the player face the mouse always, but wanted a turn rate to make certain characters turn slower than others. Here is how it calculates the turn circle:
func (p *player) handleTurn(win pixelgl.Window, dt float64) {
mouseRad := math.Atan2(p.pos.Y-win.MousePosition().Y, win.MousePosition().X-p.pos.X) // the angle the player needs to turn to face the mouse
if mouseRad > p.rotateRad-(p.turnSpeed*dt) {
p.rotateRad += p.turnSpeed * dt
} else if mouseRad < p.rotateRad+(p.turnSpeed*dt) {
p.rotateRad -= p.turnSpeed * dt
}
}
The mouseRad being the radians for the turn to face the mouse, and I'm just adding the turn rate [in this case, 2].
What's happening is when the mouse reaches the left side and crosses the center y axis, the radian angle goes from -pi to pi or vice-versa. This causes the player to do a full 360.
What is a proper way to fix this? I've tried making the angle an absolute value and it only made it occur at pi and 0 [left and right side of the square at the center y axis].
I have attached a gif of the problem to give better visualization.
Basic summarization:
Player slowly rotates to follow mouse, but when the angle reaches pi, it changes polarity which causes the player to do a 360 [counts all the back to the opposite polarity angle].
Edit:
dt is delta time, just for proper frame-decoupled changes in movement obviously
p.rotateRad starts at 0 and is a float64.
Github repo temporarily: here
You need this library to build it! [go get it]
Note beforehand: I downloaded your example repo and applied my change on it, and it worked flawlessly. Here's a recording of it:
(for reference, GIF recorded with byzanz)
An easy and simple solution would be to not compare the angles (mouseRad and the changed p.rotateRad), but rather calculate and "normalize" the difference so it's in the range of -Pi..Pi. And then you can decide which way to turn based on the sign of the difference (negative or positive).
"Normalizing" an angle can be achieved by adding / subtracting 2*Pi until it falls in the -Pi..Pi range. Adding / subtracting 2*Pi won't change the angle, as 2*Pi is exactly a full circle.
This is a simple normalizer function:
func normalize(x float64) float64 {
for ; x < -math.Pi; x += 2 * math.Pi {
}
for ; x > math.Pi; x -= 2 * math.Pi {
}
return x
}
And use it in your handleTurn() like this:
func (p *player) handleTurn(win pixelglWindow, dt float64) {
// the angle the player needs to turn to face the mouse:
mouseRad := math.Atan2(p.pos.Y-win.MousePosition().Y,
win.MousePosition().X-p.pos.X)
if normalize(mouseRad-p.rotateRad-(p.turnSpeed*dt)) > 0 {
p.rotateRad += p.turnSpeed * dt
} else if normalize(mouseRad-p.rotateRad+(p.turnSpeed*dt)) < 0 {
p.rotateRad -= p.turnSpeed * dt
}
}
You can play with it in this working Go Playground demo.
Note that if you store your angles normalized (being in the range -Pi..Pi), the loops in the normalize() function will have at most 1 iteration, so that's gonna be really fast. Obviously you don't want to store angles like 100*Pi + 0.1 as that is identical to 0.1. normalize() would produce correct result with both of these input angles, while the loops in case of the former would have 50 iterations, in the case of the latter would have 0 iterations.
Also note that normalize() could be optimized for "big" angles by using floating operations analogue to integer division and remainder, but if you stick to normalized or "small" angles, this version is actually faster.
Preface: this answer assumes some knowledge of linear algebra, trigonometry, and rotations/transformations.
Your problem stems from the usage of rotation angles. Due to the discontinuous nature of the inverse trigonometric functions, it is quite difficult (if not outright impossible) to eliminate "jumps" in the value of the functions for relatively close inputs. Specifically, when x < 0, atan2(+0, x) = +pi (where +0 is a positive number very close to zero), but atan2(-0, x) = -pi. This is exactly why you experience the difference of 2 * pi which causes your problem.
Because of this, it is often better to work directly with vectors, rotation matrices and/or quaternions. They use angles as arguments to trigonometric functions, which are continuous and eliminate any discontinuities. In our case, spherical linear interpolation (slerp) should do the trick.
Since your code measures the angle formed by the relative position of the mouse to the absolute rotation of the object, our goal boils down to rotating the object such that the local axis (1, 0) (= (cos rotateRad, sin rotateRad) in world space) points towards the mouse. In effect, we have to rotate the object such that (cos p.rotateRad, sin p.rotateRad) equals (win.MousePosition().Y - p.pos.Y, win.MousePosition().X - p.pos.X).normalized.
How does slerp come into play here? Considering the above statement, we simply have to slerp geometrically from (cos p.rotateRad, sin p.rotateRad) (represented by current) to (win.MousePosition().Y - p.pos.Y, win.MousePosition().X - p.pos.X).normalized (represented by target) by an appropriate parameter which will be determined by the rotation speed.
Now that we have laid out the groundwork, we can move on to actually calculating the new rotation. According to the slerp formula,
slerp(p0, p1; t) = p0 * sin(A * (1-t)) / sin A + p1 * sin (A * t) / sin A
Where A is the angle between unit vectors p0 and p1, or cos A = dot(p0, p1).
In our case, p0 == current and p1 == target. The only thing that remains is the calculation of the parameter t, which can also be considered as the fraction of the angle to slerp through. Since we know that we are going to rotate by an angle p.turnSpeed * dt at every time step, t = p.turnSpeed * dt / A. After substituting the value of t, our slerp formula becomes
p0 * sin(A - p.turnSpeed * dt) / sin A + p1 * sin (p.turnSpeed * dt) / sin A
To avoid having to calculate A using acos, we can use the compound angle formula for sin to simplify this further. Note that the result of the slerp operation is stored in result.
result = p0 * (cos(p.turnSpeed * dt) - sin(p.turnSpeed * dt) * cos A / sin A) + p1 * sin(p.turnSpeed * dt) / sin A
We now have everything we need to calculate result. As noted before, cos A = dot(p0, p1). Similarly, sin A = abs(cross(p0, p1)), where cross(a, b) = a.X * b.Y - a.Y * b.X.
Now comes the problem of actually finding the rotation from result. Note that result = (cos newRotation, sin newRotation). There are two possibilities:
Directly calculate rotateRad by p.rotateRad = atan2(result.Y, result.X), or
If you have access to the 2D rotation matrix, simply replace the rotation matrix with the matrix
|result.X -result.Y|
|result.Y result.X|
I have two vectors and I want to get the angle between those vectors, I am currently doing it with this formula :
acos(dot(v1.unitVector, v2.unitVector))
Here is what I get with it :
I would want the green angle rather than the red angle, but I don't know what formula I should use...
Thank you.
EDIT : So, hen the vectors are still in a certain position (like the first two pairs of vectors, it's ok, but whenever it is in a configuration like in the third pair, it doesn't give me the right angle anymore)
With the dot product you get always an angle that is independent of the order of the vectors and the smaller of the two possibilities.
For what you want, you need the argument function of complex numbers that is realized by the atan2 function. The angle from a=ax+i*ay to b=bx+i*by is the argument of the conjugate of a times b (rotating b backwards by the angle of a, scale not considered), which in coordinates is
(ax-i*ay) * (bx+i*by) = ax*bx+ay*by + i*(ax*by-ay*bx)
so the angle is
atan2( ax*by-ay*bx, ax*bx+ay*by ).
Adding to the accepted answer, the problem with atan2 is that, if you imagine vector a being static and vector b rotating in anti-clockwise direction, you will see the return value ranging from 0 to π, but then it suddenly turns negative and proceeds from -π to 0, which is not exactly good if you're interested in an angle increasing from 0 to 2π.
To tackle that problem, the function below conveniently maps the result from atan2 and returns a value between 0 and 2π as one would expect:
const TAU = Math.PI * 2;
/**
* Gives the angle in radians from vector a to vector b in anticlockwise direction,
* ranging from 0 to 2π.
*
* #param {Vector} a
* #param {Vector} b
* #returns {Number}
*/
static angle(a, b) {
let angle = Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y);
if (angle < 0) {
angle += TAU;
}
return angle;
}
It is written in JavaScript, but it's easily portable to other languages.
Lutz already answered this correctly but let me add that I highly recommend basing modern vector math code on Geometric Algebra which raises the abstraction level dramatically.
Using GA, you can simply multiply the two vectors U and V to get a rotor. The rotor internally looks like A + Bxy where A = U dot V = |U|V|cos(angle) and Bxy = U wedge V = |U||V|sin(angle)xy (this is isomorphic to the complex numbers). Then you can return the rotor's signed CCW angle which is atan2( B, A ).
So with operator overloading, you can just type (u * v).Angle. The final calculations end up the same, but the abstraction level you think and work in is much higher.
Maybe this one is more fit:
atan2( ax*by-ay*bx, ax*bx+ay*by ) % (PI*2)
the calculation which could get the full anti-clockwise radian.
The magnitude of the cross product describes the signed area of the parallelogram described by the two vectors (u, v) used to build the cross product, it has its uses. This same magnitude can be calculated as the magnitude of u times the magnitude of v times the sine of the angle between u and v:
||u||||v||sin(theta).
Now the dot product of u (normalized) and v (normalized) gives the cosine of the angle between u and v:
cos(theta)==dot(normalize(u), normalize(v))
I want to be able to get the signed sine value that is related to the cosine value. It is related because the sine and cosine waves are PI/2 out of sync. I know that the square root of 1 less the cosine value squared gives the unsigned sine value:
sin(theta)==sqrt(1 - (cos(theta) * cos(theta))
Where by cos(theta) I mean the dot product not the angle.
But the attendant sign calculation (+/-) requires theta as an angle:
(cos(theta + PI / 2)) > or == or < 0
If I have to perform an acos function I might as well just do the cross product and find the magnitude.
Is there a known ratio or step that can be added to a cosine value to get its related sine value?
For each possible cosine, both signs are possible for the sine if the corresponding angle is unrestricted.
If you know the angle is between [0,pi], then the sine must be positive or zero.
If you want to know the area of a parallelogram, always take the positive branch sin(x) = sqrt(1 - cos(x)^2). Negative area rarely makes sense (only to define orientation w.r.t. to a plane such as for backface culling)
If you have the two vectors, use a cross product or dot product directly, not the other one and convert.
Seems to me like a complicated way to get to atan2 identities:
d = 𝐚·𝐛 = |𝐚||𝐛|cosθ
c = |𝐚×𝐛| = |𝐚||𝐛|sinθ (with 0° < θ < 180°)
tanθ = 𝐚·𝐛 / |𝐚×𝐛|
θ = atan2(c·sgn(c|z), d) (= four quadrant)
where sgn(c|z) is the sign of the z-component in c (unless 𝐚 and 𝐛 both run exactly parallel with the xz or yz plane, then its the sign of the y-component and x-component, respectively).
Now, from basic trig identities,
r = √(x²+y²)
cos(atan2(y,x)) = x/r
sin(atan2(y,x)) = y/r
Therefore,
sinθ = c·sgn(c|z)/√(c²+d²)
cosθ = d/√(c²+d²)
I think I have found a solution.
cos(b) == sin(a)
v_parallel = dot(normalize(u), v) // the projection of v on u
v_perp = normalize(v) - v_parallel
cos(b) = dot(normalize(v), v_perp) // v_perp is already normalized
Therefore, the magnitude of
u cross v = magnitude(u) * magnitude(v) * cos(b)
I have a specific question about reversing atan2, I will write my code example in PHP.
$radial = 1.12*PI();
$transformed = -atan2(cos($radial)*2, sin($radial)*1.5);
$backToRadial = ?
Is there a way to reverse the transformed value to the start radial, without knowing the start radial?
This is how code flow should be: $radial => transform($radial) => transformback(transform($radial)) => $radial.
I have searched on the web (incl. stack) but I couldn't find any correct code. Also looked on Wikipedia, but it was overwhelming. My question is more a algebra question I think ;).
Let me know what you think!
_
Answered by Jason S:
Answer (by radial range: -PI-PI):
$backToRadial = atan2(2*cos($transformed), -1.5*sin($transformed));
Answer (by radial range: 0-2PI):
$backToRadial = PI() + atan2(-(2*cos($transformed)), -(-1.5*sin($transformed)));
A simple answer that will work for principal angles (angles over the range θ = -π to +π) is as follows:
θ' = -atan2(2cos θ, 1.5sin θ)
θ = atan2(2cos θ', -1.5sin θ')
where the first equation is your forward transformation, and the second equation is one of many inverse transformations.
The reason for this is that what you're doing is equivalent to a reflection + scaling + unit-magnitude-normalization of the cartesian coordinate pair (x,y) = (r cos θ, r sin θ) for r =1, since atan2(y,x) = θ.
A specific transformation that will work is (x',y') = (1.5y, -2x).
θ' = atan2(y',x') = atan2(-2x, 1.5y) = atan2(-2Rcos θ, 1.5Rsin θ) = -atan2(2 cos θ, 1.5 sin θ),
with the last step true since atan2(ky,kx) = atan2(y,x) for any k > 0, and -atan2(y,x) = atan2(-y, x).
This can be reversed by solving for x and y, namely y = 1/1.5 * x' and x = -1/2 * y':
θ = atan2(y,x) = atan2(1/1.5 * x', -1/2 * y')
and we choose to multiply (x,y) by k = 3/R to leave the angle unchanged:
θ = atan2(2x'/R, -1.5y'/R) = atan2(2 cos θ', -1.5 sin θ')
Q.E.D.
edit: Jason points out, correctly, that your example angle 1.12π is not in the principal angle range -π to +π. You need to define the range of angles you wish to be able to handle, and it has to be a range of at most length 2π.
My answer can be adjusted accordingly, but it takes a bit of work to verify, and you would make it easier on yourself if you stuck to the -π to +π range, since you are using atan2() and its output is in this range.
If you want to use a modified version of atan2() that outputs angles in the 0-2π range, I'd recommend using
atan2b(y,x) = pi+atan2(-y,-x)
where atan2b now outputs between 0 and 2π, since the calculation atan2(-y,-x) differs from atan2(y,x) by an angle of π (mod 2π)
If you're going to take this approach, don't calculate -atan2b(y,x); instead calculate atan2b(-y,x), (equivalent mod 2π) so that the range of output angles is left unchanged.
First, atan2 is not the same as tan-1 or arctan as seen below from the Wiki article on atan2:
As you can see, you cannot map it back without some information regarding x and y. However, if x>0 is always true, then you just take use the inverse tangent function, etc.
You could use this representation, to compute the inverse function:
In your example, y = 2cos(r) and x = 1.5sin(r). Therefore, if you divide the above expression with y, you get it in the form of x/y which in your case is 4/3 cot(r).
If this representation is correct, some simple algebra gives you:
where r = radial and k = cot(transformed/2)
WolframAlpha gave a solution to this:
But depending on your resources, it's probably better to find the root of the function with a fixed value of k. E.g. if k = 1.35, then you need to solve:
Any decent solver (and hence the comment on the resources you have) such as MATLAB will solve this. WolframAlpha provided the following approximate real solution:
I have a unit vector in 3D space whose direction I wish to perturb by some angle within the range 0 to theta, with the position of the vector remaining the same. What is a way I can accomplish this?
Thanks.
EDIT: After thinking about the way I posed the question, it seems to be a bit too general. I'll attempt to make it more specific: Assume that the vector originates from the surface of an object (i.e. sphere, circle, box, line, cylinder, cone). If there are different methods to finding the new direction for each of those objects, then providing help for the sphere one is fine.
EDIT 2: I was going to type this in a comment but it was too much.
So I have orig_vector, which I wish to perturb in some direction between 0 and theta. The theta can be thought of as forming a cone around my vector (with theta being the angle between the center and one side of the cone) and I wish to generate a new vector within that cone. I can generate a point lying on the plane that is tangent to my vector and thus creating a unit vector in the direction of the point, call it rand_vector. At this time, I orig_vector and trand_vector are two unit vectors perpendicular to each other.
I generate my first angle, angle1 between 0 and 2pi and I rotate rand_vector around orig_vector by angle1, forming rand_vector2. I looked up a resource online and it said that the second angle, angle2 should be between 0 and sin(theta) (where theta is the original "cone" angle). Then I rotate rand_vector2 by acos(angle2) around the vector defined by the cross product between rand_vector2 and orig_vector.
When I do this, I don't obtain the desired results. That is, when theta=0, I still get perturbed vectors, and I expect to get orig_vector. If anyone can explain the reason for the angles and why they are the way they are, I would greatly appreciate it.
EDIT 3: This is the final edit, I promise =). So I fixed my bug and everything that I described above works (it was an implementation bug, not a theory bug). However, my question about the angles (i.e. why is angle2 = sin(theta)*rand() and why is perturbed_vector = rand_vector2.Rotate(rand_vector2.Cross(orig_vector), acos(angle2)). Thanks so much!
Here's the algorithm that I've used for this kind of problem before. It was described in Ray Tracing News.
1) Make a third vector perpendicular to the other two to build an orthogonal basis:
cross_vector = unit( cross( orig_vector, rand_vector ) )
2) Pick two uniform random numbers in [0,1]:
s = rand( 0, 1 )
r = rand( 0, 1 )
3) Let h be the cosine of the cone's angle:
h = cos( theta )
4) Modify uniform sampling on a sphere to pick a random vector in the cone around +Z:
phi = 2 * pi * s
z = h + ( 1 - h ) * r
sinT = sqrt( 1 - z * z )
x = cos( phi ) * sinT
y = sin( phi ) * sinT
5) Change of basis to reorient it around the original angle:
perturbed = rand_vector * x + cross_vector * y + orig_vector * z
If you have another vector to represent an axis of rotation, there are libraries that will take the axis and the angle and give you a rotation matrix, which can then be multiplied by your starting vector to get the result you want.
However, the axis of rotation should be at right angles to your starting vector, to get the amount of rotation you expect. If the axis of rotation does not lie in the plane perpendicular to your vector, the result will be somewhat different than theta.
That being said, if you already have a vector at right angles to the one you want to perturb, and you're not picky about the direction of the perturbation, you can just as easily take a linear combination of your starting vector with the perpendicular one, adjust for magnitude as needed.
I.e., if P and Q are vectors having identical magnitude, and are perpendicular, and you want to rotate P in the direction of Q, then the vector R given by R = [Pcos(theta)+Qsin(theta)] will satisfy the constraints you've given. If P and Q have differing magnitude, then there will be some scaling involved.
You may be interested in 3D-coordinate transformations to change your vector angle.
I don't know how many directions you want to change your angle in, but transforming your Cartesian coordinates to spherical coordinates should allow you to make your angle change as you like.
Actually, it is very easy to do that. All you have to do is multiply your vector by the correct rotation matrix. The resulting vector will be your rotated vector. Now, how do you obtain such rotation matrix? That depends on the 3d framework/engine you are using. Any 3d framework must provide functions for obtaining rotation matrices, normally as static methods of the Matrix class.
Good luck.
Like said in other comments you can rotate your vector using a rotation matrix.
The rotation matrix has two angles you rotate your vector around. You can pick them with a random number generator, but just picking two from a flat generator is not correct. To ensure that your rotation vector is generated flat, you have to pick one random angle φ from a flat generator and the other one from a generator flat in cosθ ;this ensures that your solid angle element dcos(θ)dφ is defined correctly (φ and θ defined as usual for spherical coordinates).
Example: picking a random direction with no restriction on range, random() generates flat in [0,1]
angle1 = acos(random())
angle2 = 2*pi*random()
My code in unity - tested and working:
/*
* this is used to perturb given vector 'direction' by changing it by angle not more than 'angle' vector from
* base direction. Used to provide errors for player playing algorithms
*
*/
Vector3 perturbDirection( Vector3 direction, float angle ) {
// division by zero protection
if( Mathf.Approximately( direction.z, 0f )) {
direction.z = 0.0001f;
}
// 1 get some orthogonal vector to direction ( solve direction and orthogonal dot product = 0, assume x = 1, y = 1, then z = as below ))
Vector3 orthogonal = new Vector3( 1f, 1f, - ( direction.x + direction.y ) / direction.z );
// 2 get random vector from circle on flat orthogonal to direction vector. get full range to assume all cone space randomization (-180, 180 )
float orthoAngle = UnityEngine.Random.Range( -180f, 180f );
Quaternion rotateTowardsDirection = Quaternion.AngleAxis( orthoAngle, direction );
Vector3 randomOrtho = rotateTowardsDirection * orthogonal;
// 3 rotate direction towards random orthogonal vector by vector from our available range
float perturbAngle = UnityEngine.Random.Range( 0f, angle ); // range from (0, angle), full cone cover guarantees previous (-180,180) range
Quaternion rotateDirection = Quaternion.AngleAxis( perturbAngle, randomOrtho );
Vector3 perturbedDirection = rotateDirection * direction;
return perturbedDirection;
}