How do you convert quaternion/accelerometer data to opengl usable data - android

I have some data from a sensor device, i.e., accelerometer x,y,z and a quaternion. Using this information i would like to render a "line image" in an Android OpenGL View. Can someone help me about the part on how to convert acceleration values to something that can be used by OpenGL glTranslatef and glRotatef function's.

You shouldn't be using the deprecate gltranslate or glrotate. instead just manage the correct transformation matrices directly.
converting a quaternion to matrix can be done with the following: (sourced from my previous code)
float[] quatToMat(quaternion q, float* result)
{
//based on algorithm on wikipedia
// http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
float w = q.scalar ();
float x = q.x();
float y = q.y();
float z = q.z();
float n = x*x + y*y + z*z + w*w;
float s = n == 0? 0 : 2 / n;
float wx = s * w * x, wy = s * w * y, wz = s * w * z;
float xx = s * x * x, xy = s * x * y, xz = s * x * z;
float yy = s * y * y, yz = s * y * z, zz = s * z * z;
return new float[]{ 1 - (yy + zz), xy + wz , xz - wy ,0,
xy - wz , 1 - (xx + zz), yz + wx ,0,
xz + wy , yz - wx , 1 - (xx + yy),0,
0 , 0 , 0 ,1 };
}
If you still want to use the fixed function pipeline then push that into glMultMatrix.

Related

How to get Pitch and Tilt value in android when the screen is landscape mode

In android using jetpack compose i am trying to implement a spirit level app.
i got pitch, tilt and azimuth value from TYPE_ROTATION_VECTOR and it's working fine in portrait mode. But in landscape mode it seems like the co-ordinate system remain same.
when i tilting my phone the sensor still recognize i am pitching. Seems like the X, Y axis still same as portrait mode. How can i get pitch and tilt value according to landscape mode?
I am new in development, i am sorry if my question doesn't make sense.
I tried with the help of How to measure the tilt of the phone in XY plane using accelerometer in Android link.
here is my code.
if (event?.sensor?.type == Sensor.TYPE_ROTATION_VECTOR) {
// get the rotation vector values
val g = event.values.clone()
// Normalize each values
val norm: Double = sqrt(g[0].toDouble() * g[0] + g[1] * g[1] + g[2] * g[2] + g[3] * g[3])
g[0] /= norm.toFloat()
g[1] /= norm.toFloat()
g[2] /= norm.toFloat()
g[3] /= norm.toFloat()
// get all axis values
val x: Float = g[0]
val y: Float = g[1]
val z: Float = g[2]
val w: Float = g[3]
//Calculate Pitch in degrees (-180 to 180)
val sinP: Float = 2f * (w * x + y * z)
val cosP: Float = 1f - 2f * (x * x + y * y)
pitch = atan2(sinP, cosP) * (180/ Math.PI.toFloat())
//Calculate Tilt in degrees (-90 to 90)
val sinT = 2f * (w * y - z * x)
tilt = if (abs(sinT) >= 1)
(Math.PI / 2).withSign(sinT.toDouble()).toFloat() * (180 / Math.PI.toFloat())
else asin(sinT) * (180 / Math.PI.toFloat())
//Calculate Azimuth in degrees (0 to 360; 0 = North, 90 = East, 180 = South, 270 = West)
val sinA = 2f * (w * z + x * y)
val cosA = 1f - 2f * (y * y + z * z)
azimuth = atan2(sinA, cosA) * (180 / Math.PI.toFloat())
}

Find new control point when endpoint change in cubic bezier curve

I'm implementing cubic bezier curve logic in my one of Android Application.
I've implemented cubic bezier curve code on canvas in onDraw of custom view.
// Path to draw cubic bezier curve
Path cubePath = new Path();
// Move to startPoint(200,200) (P0)
cubePath.moveTo(200,200);
// Cubic to with ControlPoint1(200,100) (C1), ControlPoint2(300,100) (C2) , EndPoint(300,200) (P1)
cubePath.cubicTo(200,100,300,100,300,200);
// Draw on Canvas
canvas.drawPath(cubePath, paint);
I visualize above code in following image.
[Updated]
Logic for selecting first control points, I've taken ,
baseX = 200 , baseY = 200 and curve_size = X of Endpoint - X of Start Point
Start Point : x = baseX and y = baseY
Control Point 1 : x = baseX and y = baseY - curve_size
Control Point 2 : x = baseX + curve_size and y = baseY - curve_size
End Point : x = baseX + curve_size and y = baseY
I want to allow user to change EndPoint of above curve, and based on the new End points, I invalidate the canvas.
But problem is that, Curve maintain by two control points, which needs to be recalculate upon the change in EndPoint.
Like, I just want to find new Control Points when EndPoint change from (300,200) to (250,250)
Like in following image :
Please help me to calculate two new Control Points based on new End Point that curve shape will maintain same as previous end point.
I refer following reference links during searching:
http://pomax.github.io/bezierinfo/
http://jsfiddle.net/hitesh24by365/jHbVE/3/
http://en.wikipedia.org/wiki/B%C3%A9zier_curve
http://cubic-bezier.com/
Any reference link also appreciated in answer of this question.
changing the endpoint means two things, a rotation along P1 and a scaling factor.
The scaling factor (lets call it s) is len(p1 - p0) / len(p2 - p0)
For the rotation factor (lets call it r) i defer you to Calculating the angle between three points in android , which also gives a platform specific implementation, but you can check correctness by scaling/rotationg p1 in relation to p0, and you should get p2 as a result.
next, apply scaling and rotation with respect to p0 to c1 and c2. for convenience i will call the new c1 'd1' and the new d2.
d1 = rot(c1 - p0, factor) * s + p0
d2 = rot(c2 - p0, factor) * s + p0
to define some pseudocode for rot() (rotation http://en.wikipedia.org/wiki/Rotation_%28mathematics%29)
rot(point p, double angle){
point q;
q.x = p.x * cos(angle) - p.y * sin(angle);
q.y = p.x * sin(angle) + p.y * cos(angle);
}
Your bezier curve is now scaled and rotated in relation to p0, with p1 changed to p2,
Firstly I would ask you to look into following articles :
Bezier Curves
Why B-Spline Curve
B-Spline Curve Summary
What you are trying to implement is a piecewise composite Bézier curve. From the Summary page for n control points (include start/end) you get (n - 1)/3 piecewise Bézier curves.
The control points shape the curve literally. If you don't give proper control points with new point, you will not be able to create smoothly connected bezier curve. Generating them will not work, as it is too complex and there is no universally accepted way.
If you don't have/want to give extra control points, you should use Catmull-Rom spline, which passes through all control points and will be C1 continous (derivative is continuous at any point on curve).
Links for Catmull Rom Spline in java/android :
http://hawkesy.blogspot.in/2010/05/catmull-rom-spline-curve-implementation.html
https://github.com/Dongseob-Park/catmull-rom-spline-curve-android
catmull-rom splines for Android (similar to your question)
Bottom line is if you don't have the control points don't use cubic bezier curve. Generating them is a problem not the solution.
It seems that you are here rotating and scaling a square where you know the bottom two points and need to calculate the other two. The two known points form two triangles with the other two, so we just need to find the third point in a triangle. Supose the end point is x1, y1:
PointF c1 = calculateTriangle(x0, y0, x1, y1, true); //find left third point
PointF c2 = calculateTriangle(x0, y0, x1, y1, false); //find right third point
cubePath.reset();
cubePath.moveTo(x0, y0);
cubePath.cubicTo(c1.x, c1.y, c2.x, c2.y, x1, y1);
private PointF calculateTriangle(float x1, float y1, float x2, float y2, boolean left) {
PointF result = new PointF(0,0);
float dy = y2 - y1;
float dx = x2 - x1;
float dangle = (float) (Math.atan2(dy, dx) - Math.PI /2f);
float sideDist = (float) Math.sqrt(dx * dx + dy * dy); //square
if (left){
result.x = (int) (Math.cos(dangle) * sideDist + x1);
result.y = (int) (Math.sin(dangle) * sideDist + y1);
}else{
result.x = (int) (Math.cos(dangle) * sideDist + x2);
result.y = (int) (Math.sin(dangle) * sideDist + y2);
}
return result;
}
...
There is other way to do this where it does not matter how many points you have in between the first and the last point in the path or event its shape.
//Find scale
Float oldDist = (float) Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
Float newDist = (float) Math.sqrt((x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0));
Float scale = newDist/oldDist;
//find angle
Float oldAngle = (float) (Math.atan2(y1 - y0, x1 - x0) - Math.PI /2f);
Float newAngle = (float) (Math.atan2(y2 - y0, x2 - x0) - Math.PI /2f);
Float angle = newAngle - oldAngle;
//set matrix
Matrix matrix = new Matrix();
matrix.postScale(scale, scale, x0, y0);
matrix.postRotate(angle, x0, y0);
//transform the path
cubePath.transform(matrix);
A small variant on the suggestion by Lumis
// Find scale
Float oldDist = (float) Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
Float newDist = (float) Math.sqrt((x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0));
Float scale = newDist/oldDist;
// Find angle
Float oldAngle = (float) (Math.atan2(y1 - y0, x1 - x0));
Float newAngle = (float) (Math.atan2(y2 - y0, x2 - x0));
Float angle = newAngle - oldAngle;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
matrix.postRotate(angle);
float[] p = { c1.x, c1.y, c2.x, c2.y };
matrix.mapVectors(p);
PointF newC1 = new PointF(p[0], p[1]);
PointF newC2 = new PointF(p[2], p[3]);

Animation Along a path with Auto Rotation based on the path in android

I have been trying to animate an image of a fly which moves in a path like the following image(which i have added for a clear idea) in android version 2.2
Well,this can be done in a very simple manner in the iphone as they have a property forsetting this auto rotation after the path is drawn using
animation.rotationMode = kCAAnimationRotateAuto;
which i believe would rotate the object based on the path`
I am able to animate ma fly through this path using the nineoldandroid library using the methods
path.moveTo(float x, float y);
path.lineTo(float x, float y);
path.curveTo(float c0X, float c0Y, float c1X, float c1Y, float x, float y);
Such that the curves are drawn through cubic B�zier curve.
Now what i have been trying is to implement something that would allow my fly to rotate itself along the path and i just cant seem to reach anywhere.
Please Help Me out with some ideas!!! :( :(
You have to download the demo and the lib of nineoldandroids and these 4 java files if you want to use my solution
That was easy, I modified the evaluator in the demo of nineoldandroids.
It's too much to post here:
Just to get the idea:
I extend the PathPoint with the field angle.
Then write all calculated Points in a stack (a simple float[][])
After the first calculation the angle can be calculated by the atan and the last 2 points in the stack.
If you don't want to use a stack you can modify the timeparam and look forward to where the next point will be drawn and calculate the angle out of these.
Just think about:
Do you first watch where you are walking to and then walk or do you just walk and then chose the angle for the destination. It's not neccessary since we have display densities that high and calculating the angle for each pixel.
Here's the PathEvaluator
public class PathEvaluatorAngle implements TypeEvaluator<PathPointAngle> {
private static final int POINT_COUNT = 5000;
private float[][] stack = new float[POINT_COUNT][2];
private int stackC = 0;
#Override
public PathPointAngle evaluate(float t, PathPointAngle startValue, PathPointAngle endValue) {
float x, y;
if (endValue.mOperation == PathPointAngle.CURVE) {
float oneMinusT = 1 - t;
x = oneMinusT * oneMinusT * oneMinusT * startValue.mX +
3 * oneMinusT * oneMinusT * t * endValue.mControl0X +
3 * oneMinusT * t * t * endValue.mControl1X +
t * t * t * endValue.mX;
y = oneMinusT * oneMinusT * oneMinusT * startValue.mY +
3 * oneMinusT * oneMinusT * t * endValue.mControl0Y +
3 * oneMinusT * t * t * endValue.mControl1Y +
t * t * t * endValue.mY;
} else if (endValue.mOperation == PathPointAngle.LINE) {
x = startValue.mX + t * (endValue.mX - startValue.mX);
y = startValue.mY + t * (endValue.mY - startValue.mY);
} else {
x = endValue.mX;
y = endValue.mY;
}
stack[stackC][0] = x;
stack[stackC][1] = y;
double angle;
if (stackC == 0){
angle = 0;
} else if (stackC >= POINT_COUNT){
throw new IllegalStateException("set the stack POINT_COUNT higher!");
} else {
angle = Math.atan(
(stack[stackC][1] - stack[stackC-1][1]) /
(stack[stackC][0] - stack[stackC-1][0])
) * 180d/Math.PI;
}
stackC++;
return PathPointAngle.moveTo(x, y, angle);
}
}
Please check the below link.Hope it will help.
https://github.com/JakeWharton/NineOldAndroids

Calculation of proper Rotation Values from Gyroscope Sensor in Android

I am working on rotating the rectangle using the orientation values from gyroscope sensors in Android 3.1 device.
I have to rotate my device very fast to get values 1.0 and more.
Here is the code
final float currentRotVector[] = { 1, 0, 0, 0 };
if (timestamp != 0)
{
final float dT = (event.timestamp - timestamp) * NS2S;
// Axis of the rotation sample, not normalized yet.
// Calculate the angular speed of the sample
float omegaMagnitude = (float) Math.sqrt(X * X + Y * Y + Z * Z);
// Normalize the rotation vector if it's big enough to get the axis
if (omegaMagnitude > EPSILON)
{
X /= omegaMagnitude;
Y /= omegaMagnitude;
Z /= omegaMagnitude;
}
// Integrate around this axis with the angular speed by the timestep
// in order to get a delta rotation from this sample over the timestep
// We will convert this axis-angle representation of the delta rotation
// into a quaternion before turning it into the rotation matrix.
float thetaOverTwo = dT * omegaMagnitude / 2.0f;
float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);
float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);
deltaRotationVector[0] = cosThetaOverTwo;
deltaRotationVector[1] = sinThetaOverTwo * X;
deltaRotationVector[2] = sinThetaOverTwo * Y;
deltaRotationVector[3] = sinThetaOverTwo * Z;
/* quaternion multiplication
Reference: http://www.cprogramming.com/tutorial/3d/quaternions.html
*/
currentRotVector[0] = deltaRotationVector[0] * currentRotVector[0] -
deltaRotationVector[1] * currentRotVector[1] -
deltaRotationVector[2] * currentRotVector[2] -
deltaRotationVector[3] * currentRotVector[3];
currentRotVector[1] = deltaRotationVector[0] * currentRotVector[1] +
deltaRotationVector[1] * currentRotVector[0] +
deltaRotationVector[2] * currentRotVector[3] -
deltaRotationVector[3] * currentRotVector[2];
currentRotVector[2] = deltaRotationVector[0] * currentRotVector[2] -
deltaRotationVector[1] * currentRotVector[3] +
deltaRotationVector[2] * currentRotVector[0] +
deltaRotationVector[3] * currentRotVector[1];
currentRotVector[3] = deltaRotationVector[0] * currentRotVector[3] +
deltaRotationVector[1] * currentRotVector[2] -
deltaRotationVector[2] * currentRotVector[1] +
deltaRotationVector[3] * currentRotVector[0];
final float rad2deg = (float) (180.0f / Math.PI);
RotAngle = currentRotVector[0] * rad2deg;
axisX = currentRotVector[1];
axisY = currentRotVector[2];
axisZ = currentRotVector[3];
Log.i("Sensor Orientation GyroScope", "axisX: " + axisX + //
" axisY: " + axisY + //
" axisZ: " + axisZ + //
" RotAngle: " + RotAngle);
}
timestamp = event.timestamp;
I am getting some outputs like
axisX: 0.69363713 axisY: 0.18359372 axisZ: 0.0228636 RotAngle: 36.7191
And because of the axis values, the output rectangle looked tweaked when the device is lay down on the table.
Is there any problem in the above code?
The values are measeured in rad/s. This has been standarized starting from Android 2.3
To get values of about 1.0 you have to turn at a speed of almost 60 deg/s
Some devices having previous Android versions return (returned) values in degrees/s, but these are just a few. As an example, the LG Optimus Black (P970) with android 2.2 is one of these devices returning deg/s, but this is not the common case.

Remap rotation matrix to different axis system

I am using an adapted version of android's getRotationMatrix in a c++ program that reads the phone's sensor data over the network and calculates the device's matrix.
The function works fine and calculates the device's orientation. Unfortunately, Ogre3d has a different axis system than the device. So even though rotation about the x-axis works fine, the y and z axis are wrong. Holding the device level and pointing to north (identity matrix). When I pitch, the rotation is correct. But when I roll and yaw the rotations are alternated. Roll is yaw in Ogre3d and vice versa.
(Ogre3d) ([Device][5])
^ +y-axis ^ +z-axis
* *
* *
* * ^ +y-axis
* * *
* * *
* * *
************> + x-axis ************> +x-axis
*
*
v +z-axis
A quick look at the two axis system looks like Ogre's system (on the left) is essentially the device's system rotated 90 degrees counter clockwise about the x-axis.
I tried to experiment with various combinations when I fist assign sensor values before the matrix is calculated but no combination seems to work correctly. How would I make sure that the rotation matrix getRotationMatrix() produces displays correctly on Ogre3D?
For Reference here is the function that calculates the matrix:
bool getRotationMatrix() {
//sensor data coming through the network are
//stored in accel(accelerometer) and mag(geomagnetic)
//vars which the function has access to
float Ax = accel[0]; float Ay = accel[1]; float Az = accel[2];
float Ex = mag[0]; float Ey = mag[1]; float Ez = mag[2];
float Hx = Ey * Az - Ez * Ay;
float Hy = Ez * Ax - Ex * Az;
float Hz = Ex * Ay - Ey * Ax;
float normH = (float) Math::Sqrt(Hx * Hx + Hy * Hy + Hz * Hz);
if (normH < 0.1f) {
// device is close to free fall (or in space?), or close to
// magnetic north pole. Typical values are > 100.
return false;
}
float invH = 1.0f / normH;
Hx *= invH;
Hy *= invH;
Hz *= invH;
float invA = 1.0f / (float) Math::Sqrt(Ax * Ax + Ay * Ay + Az * Az);
Ax *= invA;
Ay *= invA;
Az *= invA;
float Mx = Ay * Hz - Az * Hy;
float My = Az * Hx - Ax * Hz;
float Mz = Ax * Hy - Ay * Hx;
//ogre3d's matrix3 is column-major whereas getrotatinomatrix produces
//a row-major matrix thus i have tranposed it here
orientation[0][0] = Hx; orientation[0][2] = Mx; orientation[0][2] = Ax;
orientation[1][0] = Hy; orientation[1][3] = My; orientation[1][2] = Ay;
orientation[2][0] = Hz; orientation[2][4] = Mz; orientation[2][2] = Az;
return true;
}
Why not just add the one additional rotation you've already identified before you use it in ogre?
I found the problem. In my function the unit vectors calculated after the cross products I put them in columns whereas I should be putting them in the rows in their appointed matrix3 cells as usual. Something about row-major and column-major confused me even though I was referring to the elements in 2d [][].
multiplying the outcome of the matrix calculation function with this matrix:
1 0 0
0 0 1
0 -1 0
Then pitching the whole result by another p/2 about axis solved the remap problem but I fear my geometry is inverted.
I don't know much about Matrix Rotation, but if the Systems rotates like you are showing, I think that youshould do the following:
X Axis stays the same way, so:
float Ax = accel[0];
float Ex = mag[0];
Y Axis in (Ogre3d) is Z axis in ([Device][5]), so:
float Ay = accel[2];
float Ey = mag[2];
Z Axis in (Ogre3d) is the oposite of Y axis in ([Device][5]), so:
float Az = accel[1] * (-1);
float Ez = mag[1] * (-1);
Try that

Categories

Resources