Related
I am trying to draw lines connected to each other. Let's say they are creating a
rectangle. At each corner also I have points. When I have tested code in my
Samsung Galaxy Note 4 after several rotations, using touch, all rectangle ended up
with a single point at the center. I could not figure out why this was happening.
Code works fine in emulator. Also I am storing line and point data as array list
in my code. These array lists are used to create line and point object classes to
render.
public class GLRender implements GLSurfaceView.Renderer {
private final float[] mMVPMatrix = new float[16];
private final float[] mProjectionMatrix = new float[16];
private final float[] mViewMatrix = new float[16];
private float[] mRotationMatrix = new float[16];
private float[] mVRMatrix = new float[16];
private static ArrayList<Line> DrLine = new ArrayList<Line>();
private static ArrayList<Point> DrPoint = new ArrayList<Point>();
private float ratio;
private float Joint1;
private float Joint2;
private float x1, y1, z1, x2, y2, z2;
private float px, py, pz, ps;
private float[] nearN = new float[4];
private static ArrayList<ArrayList<String>> LineArray = new ArrayList<ArrayList<String>>();
private ArrayList<String> L = new ArrayList<String>();
private ArrayList<String> P = new ArrayList<String>();
private static ArrayList<ArrayList<String>> PointArray = new ArrayList<ArrayList<String>>();
private static ArrayList<String> EmptyLine = new ArrayList<String>();
private static ArrayList<String> EmptyPoint = new ArrayList<String>();
private static ArrayList<ArrayList<ArrayList<String>>> UndoL = new ArrayList<ArrayList<ArrayList<String>>>();
private static ArrayList<ArrayList<ArrayList<String>>> UndoP = new ArrayList<ArrayList<ArrayList<String>>>();
public GLRender(Activity activity) {
}
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
// Set the background frame color
//GLES20.glClearColor(0.53f, 0.53f, 0.53f, 1.0f);
GLES20.glClearColor(0.474f, 0.537f, 0.078f, 1.0f);
}
public void onDrawFrame(GL10 unused) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
Drawer();
Line XLine = new Line();
XLine.SetVerts(0.0f, 0.0f, 0.0f, 1.0f / 10, 0.0f, 0.0f);
XLine.SetColor(1.0f, 0.0f, 0.0f, 1.0f);
Line YLine = new Line();
YLine.SetVerts(0.0f, 0.0f, 0.0f, 0.0f, 1.0f / 10, 0.0f);
YLine.SetColor(0.0f, 1.0f, 0.0f, 1.0f);
Line ZLine = new Line();
ZLine.SetVerts(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f / 10);
ZLine.SetColor(0.0f, 0.0f, 1.0f, 1.0f);
Matrix.setIdentityM(mViewMatrix, 0);
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 1.0f , 0f, 0f, 0f, 0f, 1.0f, 0.0f);
Matrix.setIdentityM(mRotationMatrix, 0);
Matrix.rotateM(mRotationMatrix, 0, mXAngle, 0, 1f, 0);
Matrix.rotateM(mRotationMatrix, 0, mYAngle, 1f, 0, 0);
Matrix.setIdentityM(mVRMatrix, 0);
Matrix.multiplyMM(mVRMatrix, 0, mViewMatrix, 0, mRotationMatrix, 0);
Matrix.setIdentityM(mMVPMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mVRMatrix, 0);
Matrix.scaleM(mMVPMatrix,0,mScale,mScale,mScale);
if (DrLine.size() > 0) {
for (Line LineX : DrLine) {
LineX.draw(mMVPMatrix);
}
}
if (DrPoint.size() > 0) {
for (Point PointX : DrPoint) {
PointX.draw(mMVPMatrix);
}
}
XLine.draw(mMVPMatrix);
YLine.draw(mMVPMatrix);
ZLine.draw(mMVPMatrix);
}
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
ratio = (float) width / height;
//Matrix.frustumM(mProjectionMatrix, 0, -ratio*10, ratio*10, -10, 10, 1, 9);
Matrix.orthoM(mProjectionMatrix, 0, -ratio, ratio, -1.0f, 1.0f, -5.0f, 5.0f);
}
public static int loadShader(int type, String shaderCode){
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
private Float TempMaxPointHolder = 0.0f;
private Float MaxPointHolder = 0.0f;
public Float Scaler(){
Float TempScaler = 1.0f;
Iterator<ArrayList<String>> MaxPointFinder = PointArray.iterator();
while (MaxPointFinder.hasNext()){
ArrayList<String> MaxPoint = MaxPointFinder.next();
TempMaxPointHolder = Math.abs(Math.max(Math.max(Float.parseFloat(MaxPoint.get(1)),Float.parseFloat(MaxPoint.get(2))),Float.parseFloat(MaxPoint.get(3))));
if (TempMaxPointHolder > MaxPointHolder){
MaxPointHolder = TempMaxPointHolder;
}
}
TempScaler = 0.9f / MaxPointHolder;
return TempScaler;
}
public void Drawer(){
Float Scaler = Scaler();
Integer Lindex = 0;
ArrayList<Point> TempDrPoint = new ArrayList<Point>();
ArrayList<Line> TempDrLine = new ArrayList<Line>();
Iterator<ArrayList<String>> Litr = LineArray.iterator();
while (Litr.hasNext()) {
L = Litr.next();
Joint1 = Float.parseFloat(L.get(1));
Joint2 = Float.parseFloat(L.get(2));
Iterator<ArrayList<String>> PitrL = PointArray.iterator();
while (PitrL.hasNext()){
P = PitrL.next();
if (Float.parseFloat(P.get(0)) == Joint1) {
x1 = Float.parseFloat(P.get(1)) * Scaler;
y1 = Float.parseFloat(P.get(2)) * Scaler;
z1 = Float.parseFloat(P.get(3)) * Scaler;
}
if (Float.parseFloat(P.get(0)) == Joint2) {
x2 = Float.parseFloat(P.get(1)) * Scaler;
y2 = Float.parseFloat(P.get(2)) * Scaler;
z2 = Float.parseFloat(P.get(3)) * Scaler;
}
}
Line TempLine = new Line();
TempLine.SetVerts(x1, y1, z1, x2, y2, z2);
if (L.get(3) == "0") {
TempLine.SetColor(0.0f, 0.0f, 0.0f, 1.0f);
}
else if (L.get(3) == "1"){
TempLine.SetColor(0.66f, 0.73f, 0.21f, 1.0f);
}
TempDrLine.add(TempLine);
Lindex = Lindex + 1;
}
setDrLine(TempDrLine);
Integer Pindex = 0;
Iterator<ArrayList<String>> Pitr = PointArray.iterator();
while (Pitr.hasNext()){
P = Pitr.next();
px = Float.parseFloat(P.get(1)) * Scaler;
py = Float.parseFloat(P.get(2)) * Scaler;
pz = Float.parseFloat(P.get(3)) * Scaler;
ps = Float.parseFloat(P.get(4));
Point TempPoint = new Point();
TempPoint.SetPointVerts(px, py, pz);
if (ps == 0.0f) {
TempPoint.SetPointColor(0.65f, 0.37f, 0.11f, 1.0f);
}
else if (ps == 1.0f) {
TempPoint.SetPointColor(0.68f, 0.07f, 0.32f, 1.0f);
}
TempDrPoint.add(TempPoint);
Pindex = Pindex + 1;
}
setDrPoint(TempDrPoint);
}
public volatile float mXAngle;
public volatile float mYAngle;
public ArrayList<Line> getDrLine() {
return DrLine;
}
public ArrayList<Point> getDrPoint(){
return DrPoint;
}
public void setDrLine(ArrayList<Line> XDrLine) {
DrLine = XDrLine;
}
public void setDrPoint(ArrayList<Point> XDrPoint) {
DrPoint = XDrPoint;
}
public float getXAngle() {
return mXAngle;
}
public float getYAngle(){
return mYAngle;
}
public void setAngleX(float Xangle) {
mXAngle = Xangle;
}
public void setAngleY(float Yangle) {
mYAngle = Yangle;
}
public volatile float mScale = 1;
public volatile float mXFocus;
public volatile float mYFocus;
public void setZoom(float scale){
mScale = scale;
}
public void setFocus(float XFocus, float YFocus){
mXFocus = XFocus;
mYFocus = YFocus;
}
public float getmScale(){
return mScale;
}
public float getmXFocus(){
return mXFocus;
}
public float getmYFocus(){
return mYFocus;
}
public void setLineArray(ArrayList<ArrayList<String>> XLine){
LineArray = XLine;
}
public ArrayList<ArrayList<String>> getLineArray(){
return LineArray;
}
public void setUndoL(ArrayList<ArrayList<String>> UndoLine){
this.UndoL.add(new ArrayList<ArrayList<String>>(UndoLine));
}
public ArrayList<ArrayList<ArrayList<String>>> getUndoL() {
return UndoL;
}
public void setUndoP(ArrayList<ArrayList<String>> UndoPoint){
this.UndoP.add(new ArrayList<ArrayList<String>>(UndoPoint));
}
public ArrayList<ArrayList<ArrayList<String>>> getUndoP() {
return UndoP;
}
public void setPointArray(ArrayList<ArrayList<String>> XPoint){
PointArray = XPoint;
}
public ArrayList<ArrayList<String>> getPointArray(){
return PointArray;
}
gives error contents_sample_state: [ agr({[3 ,38]=11, [3 ,7 ,38]=28}) ]
public class Line {
private FloatBuffer VertexBuffer;
private final String VertexShaderCode =
// This matrix member variable provides a hook to manipulate
// the coordinates of the objects that use this vertex shader
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
// the matrix must be included as a modifier of gl_Position
" gl_Position = uMVPMatrix * vPosition;" +
"}";
private final String FragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
protected int GlProgram;
protected int PositionHandle;
protected int ColorHandle;
protected int MVPMatrixHandle;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float LineCoords[] = {
0.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f
};
private final int VertexCount = LineCoords.length / COORDS_PER_VERTEX;
private final int VertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
// Set color with red, green, blue and alpha (opacity) values
float color[] = { 0.0f, 0.0f, 0.0f, 1.0f };
public Line() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
LineCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
VertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
VertexBuffer.put(LineCoords);
// set the buffer to read the first coordinate
VertexBuffer.position(0);
int vertexShader = GLRender.loadShader(GLES20.GL_VERTEX_SHADER, VertexShaderCode);
int fragmentShader = GLRender.loadShader(GLES20.GL_FRAGMENT_SHADER, FragmentShaderCode);
GlProgram = GLES20.glCreateProgram(); // create empty OpenGL ES Program
GLES20.glAttachShader(GlProgram, vertexShader); // add the vertex shader to program
GLES20.glAttachShader(GlProgram, fragmentShader); // add the fragment shader to program
GLES20.glLinkProgram(GlProgram); // creates OpenGL ES program executables
}
public void SetVerts(float v0, float v1, float v2, float v3, float v4, float v5) {
LineCoords[0] = v0;
LineCoords[1] = v1;
LineCoords[2] = v2;
LineCoords[3] = v3;
LineCoords[4] = v4;
LineCoords[5] = v5;
VertexBuffer.put(LineCoords);
// set the buffer to read the first coordinate
VertexBuffer.position(0);
}
public void SetColor(float red, float green, float blue, float alpha) {
color[0] = red;
color[1] = green;
color[2] = blue;
color[3] = alpha;
}
public void draw(float[] mvpMatrix) {
// Add program to OpenGL ES environment
GLES20.glUseProgram(GlProgram);
// get handle to vertex shader's vPosition member
PositionHandle = GLES20.glGetAttribLocation(GlProgram, "vPosition");
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(PositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(PositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
VertexStride, VertexBuffer);
// get handle to fragment shader's vColor member
ColorHandle = GLES20.glGetUniformLocation(GlProgram, "vColor");
// Set color for drawing the triangle
GLES20.glUniform4fv(ColorHandle, 1, color, 0);
// get handle to shape's transformation matrix
MVPMatrixHandle = GLES20.glGetUniformLocation(GlProgram, "uMVPMatrix");
//GLRender.checkGlError("glGetUniformLocation");
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(MVPMatrixHandle, 1, false, mvpMatrix, 0);
//GLRender.checkGlError("glUniformMatrix4fv");
GLES20.glLineWidth(5);
// Draw the triangle
GLES20.glDrawArrays(GLES20.GL_LINES, 0, VertexCount);
// Disable vertex array
GLES20.glDisableVertexAttribArray(PositionHandle);
}
}
public class GLSurface extends GLSurfaceView {
//public static GLRender xRender;
ScaleGestureDetector ScaleDetect;
MainActivity mMain;
OpenGL XOPL = mMain.xOpenGL;
public GLSurface(Context context, AttributeSet attrs){
super(context, attrs);
// Render the view only when there is a change in the drawing data
//setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
ScaleDetect = new ScaleGestureDetector(context, new ScaleDetectorListener());
}
private float mPreviousX;
private float mPreviousY;
float density = this.getResources().getDisplayMetrics().density;
private static final int MAX_CLICK_DURATION = 300;
private long pressStartTime;
#Override
public boolean onTouchEvent(MotionEvent e) {
ScaleDetect.onTouchEvent(e);
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
if(!ScaleDetect.isInProgress()) {
float xMoveRange = x - mPreviousX;
float yMoveRange = y - mPreviousY;
float dx = 0.0f;
float dy = 0.0f;
float w = this.getWidth();
float h = this.getHeight();
if (Math.abs(xMoveRange) > w / 100 && Math.abs(yMoveRange) < h / 100){
dx = xMoveRange / density / 2.0f;
XOPL.xRender.setAngleX(XOPL.xRender.getXAngle() + dx);
}
if (Math.abs(xMoveRange) < w / 100 && Math.abs(yMoveRange) > h / 100){
dy = yMoveRange / density / 2.0f;
XOPL.xRender.setAngleY(XOPL.xRender.getYAngle() + dy);
}
XOPL.myGLView.requestRender();
}
break;
case MotionEvent.ACTION_DOWN:
pressStartTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
long pressDuration = System.currentTimeMillis() - pressStartTime;
if (pressDuration < MAX_CLICK_DURATION) {
float Nx = (x - Float.parseFloat(Double.toString(this.getWidth())) * 0.5f) / (Float.parseFloat(Double.toString(this.getWidth())) * 0.5f);
float Ny = (y - Float.parseFloat(Double.toString(this.getHeight())) * 0.5f) / (Float.parseFloat(Double.toString(this.getHeight())) * 0.5f);
float Nz = 1.0f;
XOPL.xRender.setNCoordinate(Nx, Ny, Nz);
XOPL.xRender.Selection();
XOPL.myGLView.requestRender();
}
break;
}
mPreviousX = x;
mPreviousY = y;
return true;
}
private float sizeCoef = 1;
public class ScaleDetectorListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
float scaleFocusX = 0;
float scaleFocusY = 0;
public boolean onScale(ScaleGestureDetector arg0) {
float scale = arg0.getScaleFactor() * sizeCoef;
sizeCoef = scale;
XOPL.xRender.setZoom(sizeCoef);
XOPL.myGLView.requestRender();
return true;
}
public boolean onScaleBegin(ScaleGestureDetector arg0) {
invalidate();
scaleFocusX = arg0.getFocusX();
scaleFocusY = arg0.getFocusY();
XOPL.xRender.setFocus(scaleFocusX,scaleFocusY);
return true;
}
public void onScaleEnd(ScaleGestureDetector arg0) {
scaleFocusX = 0;
scaleFocusY = 0;
XOPL.xRender.setFocus(scaleFocusX,scaleFocusY);
}
}
}
Not sure if this is the problem, but watch out for things like:
XOPL.xRender.setAngleX(XOPL.xRender.getXAngle() + dx)
... especially when using mediump precision in shaders. Generally I'd recommend changing setAngle functions to exploit rotational symmetry and wrap the value around so you get an absolute range used at the API-level of of +-Pi.
In your current code if the user keeps swiping in one direction, eventually you'll run our of bits and everything will either stop rotating (at best), or fail with infinities or NaN results (at worst).
Note using "-Pi to +Pi" is preferred to using "0 to +2Pi", because the sign-bit is free in most floating point representations so preserves more dynamic precision.
Example code:
public float wrapRadians(float angle) {
// If angle is negative ensure value is higher than minus pi
if (angle < 0) {
while (angle < -math.PI) {
angle += 2 * math.PI;
}
// Else angle is positive so ensure value is less than pi
} else {
while (angle > math.PI) {
angle -= 2 * math.PI;
}
}
return angle;
}
public float setXAngle(float XAngle) {
mXAngle = wrapRadians(XAngle);
}
public float setYAngle(float YAngle) {
mYAngle = wrapRadians(YAngle);
}
Ok so I was able to get the coordinates in 3d space for the touch now I need to test whether that ray intersected a triangle. What I am asking is for help to understand the Test Class. BTW this code came from http://android-raypick.blogspot.ca/2012/04/first-i-want-to-state-this-is-my-first.html. I know to pass in the ray and an empty float array into intersectRayAndTriangle() but the Test T is the V0[], V1[], and V2[] but where do I get those at? Are they the converted coordinates of my object? If so then how would I implement a object with more than one triangle?
My code is:
Surface View:
public class MGLSurface extends GLSurfaceView {
MRenderer mRenderer = new MRenderer();
public static int select_Touch=0;
public static boolean selectButtonOn = false;
float x,y;
static float touchX;
static float touchY;
public MGLSurface(Context context) {
super(context);
// setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setRenderer(new MRenderer());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
x = event.getX();
y = event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
x = event.getX();
y = event.getY();
return true;
case MotionEvent.ACTION_UP:
if (selectButtonOn== true) {
select_Touch = 1;
touchX = event.getX();
touchY = event.getY();
requestRender();
}
}
return true;
}
}
Then my Renderer:
public class MRenderer implements GLSurfaceView.Renderer {
private final String TAG ="Ray Picked";
private int H,W;
Cube cube;
float[] convertedSquare = new float[Cube.vertices.length];
float[] resultVector = new float[4];
float[] inputVector = new float[4];
MatrixGrabber matrixGrabber = new MatrixGrabber();
public MRenderer() {
cube = new Cube();
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_FASTEST);
gl.glClearColor(.8f,0f,.2f,1f);
gl.glClearDepthf(1f);
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0,0,width,height);
H = height;
W = width;
float ratio = (float) width/height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio,ratio,-1,1f,1,25);
}
#Override
public void onDrawFrame(GL10 gl) {
gl.glDisable(GL10.GL_DITHER);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);
matrixGrabber.getCurrentState(gl);
// long time = SystemClock.uptimeMillis()% 400l;
// float angle = 0.90f* ((int)time);
gl.glRotatef(1,1,0,0);
gl.glRotatef(10,0,0,5);
cube.draw(gl);
//Converting object cords to 3d space
for(int i =0; i < Cube.vertices.length;i = i+3){
inputVector[0] = Cube.vertices[i];
inputVector[1] = Cube.vertices[i+1];
inputVector[2] = Cube.vertices[i+2];
inputVector[3] = 1;
Matrix.multiplyMV(resultVector, 0, matrixGrabber.mModelView, 0, inputVector, 0);
convertedSquare[i] = resultVector[0]/resultVector[3];
convertedSquare[i+1] = resultVector[1]/resultVector[3];
convertedSquare[i+2] = resultVector[2]/resultVector[3];
//Handle Touch in gl thread
if (MGLSurface.selectButtonOn==true && MGLSurface.select_Touch==1 ) {
this.Ray(gl, W, H, MGLSurface.touchX, MGLSurface.touchY);
MainActivity.mHandler.sendEmptyMessage(1);
MGLSurface.select_Touch = 0;
Log.d(TAG, "Near Coord =" + Arrays.toString(MainActivity.P0));
Log.d(TAG, "Far Coord =" + Arrays.toString(MainActivity.P1));
}
else {
}
}}
public void Ray(GL10 gl, int width, int height, float xTouch, float yTouch) {
matrixGrabber.getCurrentState(gl);
int[] viewport = {0, 0, width, height};
float[] nearCoOrds = new float[3];
float[] farCoOrds = new float[3];
float[] temp = new float[4];
float[] temp2 = new float[4];
// get the near and far ords for the click
float winx = xTouch, winy =(float)viewport[3] - yTouch;
// Log.d(TAG, "modelView is =" + Arrays.toString(matrixGrabber.mModelView));
// Log.d(TAG, "projection view is =" + Arrays.toString(matrixGrabber.mProjection));
int result = GLU.gluUnProject(winx, winy, 1.0f, matrixGrabber.mModelView, 0,
matrixGrabber.mProjection, 0, viewport, 0, temp, 0);
Matrix.multiplyMV(temp2, 0, matrixGrabber.mModelView, 0, temp, 0);
if(result == GL10.GL_TRUE){
nearCoOrds[0] = temp2[0] / temp2[3];
nearCoOrds[1] = temp2[1] / temp2[3];
nearCoOrds[2] = temp2[2] / temp2[3];
}
result = GLU.gluUnProject(winx, winy, 0, matrixGrabber.mModelView, 0,
matrixGrabber.mProjection, 0, viewport, 0, temp, 0);
Matrix.multiplyMV(temp2,0,matrixGrabber.mModelView, 0, temp, 0);
if(result == GL10.GL_TRUE){
farCoOrds[0] = temp2[0] / temp2[3];
farCoOrds[1] = temp2[1] / temp2[3];
farCoOrds[2] = temp2[2] / temp2[3];
}
MainActivity.P0 = farCoOrds;
MainActivity.P1 = nearCoOrds;
}
}
The Test Class:
public class Tests {
public float[] V0;
public float[] V1;
public float[] V2;
public Tests(float[] V0, float[] V1, float[] V2){
this.V0 =V0;
this.V1 = V1;
this.V2 = V2;
}
private static final float SMALL_NUM = 0.00000001f; // anything that avoids division overflow
// intersectRayAndTriangle(): intersect a ray with a 3D triangle
// Input: a ray R, and a triangle T
// Output: *I = intersection point (when it exists)
// Return: -1 = triangle is degenerate (a segment or point)
// 0 = disjoint (no intersect)
// 1 = intersect in unique point I1
// 2 = are in the same plane
public static int intersectRayAndTriangle(MRenderer R, Tests T, float[] I)
{
float[] u, v, n; // triangle vectors
float[] dir, w0, w; // ray vectors
float r, a, b; // params to calc ray-plane intersect
// get triangle edge vectors and plane normal
u = Vector.minus(T.V1, T.V0);
v = Vector.minus(T.V2, T.V0);
n = Vector.crossProduct(u, v); // cross product
if (Arrays.equals(n, new float[]{0.0f, 0.0f, 0.0f})){ // triangle is degenerate
return -1; // do not deal with this case
}
dir = Vector.minus(MainActivity.P1, MainActivity.P0); // ray direction vector
w0 = Vector.minus( MainActivity.P0 , T.V0);
a = - Vector.dot(n,w0);
b = Vector.dot(n,dir);
if (Math.abs(b) < SMALL_NUM) { // ray is parallel to triangle plane
if (a == 0){ // ray lies in triangle plane
return 2;
}else{
return 0; // ray disjoint from plane
}
}
// get intersect point of ray with triangle plane
r = a / b;
if (r < 0.0f){ // ray goes away from triangle
return 0; // => no intersect
}
// for a segment, also test if (r > 1.0) => no intersect
float[] tempI = Vector.addition(MainActivity.P0, Vector.scalarProduct(r,
dir)); // intersect point of ray and plane
I[0] = tempI[0];
I[1] = tempI[1];
I[2] = tempI[2];
// is I inside T?
float uu, uv, vv, wu, wv, D;
uu = Vector.dot(u,u);
uv = Vector.dot(u,v);
vv = Vector.dot(v,v);
w = Vector.minus(I, T.V0);
wu = Vector.dot(w,u);
wv = Vector.dot(w,v);
D = (uv * uv) - (uu * vv);
// get and test parametric coords
float s, t;
s = ((uv * wv) - (vv * wu)) / D;
if (s < 0.0f || s > 1.0f) // I is outside T
return 0;
t = (uv * wu - uu * wv) / D;
if (t < 0.0f || (s + t) > 1.0f) // I is outside T
return 0;
return 1; // I is in T
}
}
I've a 3d-model in OpenGL ES in Android. I've already implemented swipe-gestures for translating, rotating and zooming into the model. Everything but the zooming works fine. I'm not sure what I'm missing or what I have to change but I'm not able to zoom into my model.
The model is a building. What I'd like to do is to zoom into the different floors of the building. But no matter how I change my implementation, I'm not able to do this.
Either the building disappears when I zoom in or the zoom has a limitation so that I can't zoom into it further....
First of all I decreased the field of view by modifying the Matrix:
frustumM(matrix, 0, -ratio/zoom, ratio/zoom, -1/zoom, 1/zoom, nearPlane, farPlane).
Someone told me, that this is not the correct approach and I should modify the eyeZ value like:
eyeZ = -1.0/zoom
The first approach is working, but I'd like to know what my mistake with the second approach is, because it has the issues I mentioned in the beginning.
My renderer-class is the following:
public class MyGLRenderer implements GLSurfaceView.Renderer {
private float[] mModelMatrix = new float[16];
private final float[] mMVMatrix = new float[16];
private final float[] mProjectionMatrix = new float[16];
private final float[] mViewMatrix = new float[16];
private float nearPlaneDistance = 1f;
private float farPlaneDistance = 200f;
private float modelRatio = 1.0f;
private int offset = 0;
private float eyeX = 0;
private float eyeY = 0;
private float eyeZ = -1;
private float centerX = 0f;
private float centerY = 0f;
private float centerZ = 0f;
private float upX = 0f;
private float upY = 1.0f;
private float upZ = 0.0f;
private float mZoomLevel = 1f;
private float defaultRotationX = 100.0f; //building otherwise on the wrong side
private float defaultRotationZ = 180.0f; //building otherwise on the wrong side
private float rotationX = defaultRotationX;
private float rotationY = 0.0f;
private float rotationZ = defaultRotationZ;
private float translateX = 0.0f;
private float translateY = 0.0f;
private float translateZ = 0.0f;
private float scaleFactor = 20.0f; //no matter what scale factor -> it's not possible to zoom into the building...
private float ratio;
private float width;
private float height;
private List<IDrawableObject> drawableObjects;
public Model3D model3d;
public MyGLRenderer(Model3D model3d) {
this.model3d = model3d;
getModelScale();
}
private void getModelScale() {
float highestValue = (model3d.width > model3d.height) ? model3d.width
: model3d.height;
modelRatio = 2f / highestValue;
}
#Override
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
// Set the background frame color
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
drawableObjects = ... ; //to much detail, basically getting triangles
}
#Override
public void onDrawFrame(GL10 unused) {
float[] mMVPMatrix = new float[16];
// Draw background color
Matrix.setIdentityM(mModelMatrix, 0);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
// model is in origin-solution too big
Matrix.scaleM(mModelMatrix, 0, modelRatio * scaleFactor, modelRatio
* scaleFactor, modelRatio * scaleFactor);
Matrix.translateM(mModelMatrix, 0, translateX, translateY, translateZ);
rotateModel(mModelMatrix, rotationX, rotationY, rotationZ, true);
// Set the camera position (View matrix)
Matrix.setLookAtM(mViewMatrix, offset, eyeX, eyeY, eyeZ / mZoomLevel,
centerX, centerY, centerZ, upX, upY, upZ);
// combine the model with the view matrix
Matrix.multiplyMM(mMVMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
// this projection matrix is applied to object coordinates
// in the onDrawFrame() method
Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, 1, -1,
nearPlaneDistance, farPlaneDistance);
// Calculate the projection and view transformation
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVMatrix, 0);
for (IDrawableObject d : drawableObjects) {
d.draw(mMVPMatrix);
}
}
private void rotateModel(float[] mModelMatrix, Float x, Float y, Float z,
boolean rotateAroundCenter) {
// translation for rotating the model around its center
if (rotateAroundCenter) {
Matrix.translateM(mModelMatrix, 0, (model3d.width / 2f), 0,
(model3d.height / 2f));
}
if (x != null) {
Matrix.rotateM(mModelMatrix, 0, x, 1.0f, 0.0f, 0.0f);
}
if (y != null) {
Matrix.rotateM(mModelMatrix, 0, y, 0.0f, 1.0f, 0.0f);
}
if (z != null) {
Matrix.rotateM(mModelMatrix, 0, z, 0.0f, 0.0f, 1.0f);
}
// translation back to the origin
if (rotateAroundCenter) {
Matrix.translateM(mModelMatrix, 0, -(model3d.width / 2f), 0,
-(model3d.height / 2f));
}
}
#Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
// Adjust the viewport based on geometry changes,
// such as screen rotation
GLES20.glViewport(0, 0, width, height);
this.width = width;
this.height = height;
ratio = (float) width / height;
}
public static int loadShader(int type, String shaderCode) {
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
public int getFPS() {
return lastMFPS;
}
public static void checkGlError(String glOperation) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, glOperation + ": glError " + error);
throw new RuntimeException(glOperation + ": glError " + error);
}
}
public void setZoom(float zoom) {
this.mZoomLevel = zoom;
}
public void setDistance(float distance) {
eyeZ = distance;
}
public float getDistance() {
return eyeZ;
}
public float getRotationX() {
return rotationX;
}
public void setRotationX(float rotationX) {
this.rotationX = defaultRotationX + rotationX;
}
public float getRotationY() {
return rotationY;
}
public void setRotationY(float rotationY) {
this.rotationY = rotationY;
}
public float getRotationZ() {
return rotationZ;
}
public void setRotationZ(float rotationZ) {
this.rotationZ = defaultRotationZ + rotationZ;
}
public float getFarPlane() {
return farPlaneDistance;
}
public float getNearPlane() {
return nearPlaneDistance;
}
public void addTranslation(float mPosX, float mPosY) {
this.translateX = mPosX;
this.translateY = mPosY;
}
public void downPressed() {
translateX -= 10;
}
public void upPressed() {
translateX += 10;
}
public void actionMoved(float mPosX, float mPosY) {
float translationX = (mPosX / width);
float translationY = -(mPosY / height);
addTranslation(translationX, translationY);
}
public float getmZoomLevel() {
return mZoomLevel;
}
public void setmZoomLevel(float mZoomLevel) {
this.mZoomLevel = mZoomLevel;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public void setTranslation(Float x, Float y, Float z) {
if (x != null) {
this.translateX = -x;
}
if (y != null) {
this.translateY = y;
}
if (z != null) {
this.translateZ = -z;
}
}
public void setRotation(Float x, Float y, Float z) {
if (x != null) {
this.rotationX = defaultRotationX + x;
}
if (y != null) {
this.rotationY = y;
}
if (z != null) {
this.rotationZ = defaultRotationZ + z;
}
}
public void setScale(float scale) {
this.mZoomLevel = scale;
}
public float getDefaultRotationX() {
return defaultRotationX;
}
}
Do you see any mistake I'm currently doing? You can also have a look into the github repository: https://github.com/Dalanie/OpenGL-ES/tree/master/buildingGL
First you must define what you mean by "zoom". In the scenario of a perspective projection, there are a few possibilities:
You change the field of view. This is analogous to the zoom of cameras, where zooming results in changing the focal width.
You just scale the model before the projection.
You change the distance of the model (nearer to the camera to zoom in, farer away to zoom out)
The variant 1 is what you did by changing the frustum. In my opinion, that is the most intuitive effect. At least to someone who is used to cameras. ALso note that this has the same effect as upscaling some sub-rectangle of the 2d projected image to fill the whole screen.
Changing eyeZ is approach 3. But now you must be carefol to not move the object out of the viewing volume (which seems to be the issue you are describing). Ideally you would modify the frustum here, too. But to keep the field of view, while moving the near/far planes so that the object always stays inbetween. Note that this requires changing all 6 values of the frustum, what stays the same should be the ratios left/near, right/near, top/near and bottom/near to keep the FOV/aspect you had before.
I have 8 images which are placed circularly on the dial which resembles a speedometer with first image placed at the position which is similar to 0 and the last image on the position similar to 200 or the last value of the speedometer.
Now i want to rotate the needle which is fixed at the base and moves from the first image to last.While the needle rotates,as it moves over the images,the images changes.
The needle moves from first image to the last and moves back to first image.!
Have removed the sensor's code as i didnt wanted and remove the background and major chunk added a new method called reverse() for reversing the movement not able to find where i am going wrong. it just execute the loop once and comes out.
public final class Thermometer extends View
{
private static final String TAG = Thermometer.class.getSimpleName();
private Handler handler;
// drawing tools
private Paint scalePaint;
private RectF scaleRect;
private Paint logoPaint;
private Bitmap logo;
private Matrix logoMatrix;
private float logoScale;
private Paint handPaint;
private Path handPath;
private Paint handScrewPaint;
private Paint backgroundPaint;
// end drawing tools
private Bitmap background; // holds the cached static part
// scale configuration
private static final int totalNicks = 100;
private static final float degreesPerNick = 360.0f / totalNicks;
private static final int centerDegree = 40; // the one in the top center (12
// o'clock)
private static final int minDegrees = -30;
private static final int maxDegrees = 110;
// hand dynamics -- all are angular expressed in F degrees
private boolean handInitialized = false;
private float handPosition = minDegrees;
private float handTarget = minDegrees;
private float handVelocity = 0.0f;
private float handAcceleration = 0.0f;
private long lastHandMoveTime = -1L;
public Thermometer(Context context)
{
super(context);
init();
}
public Thermometer(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
public Thermometer(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
#Override
protected void onRestoreInstanceState(Parcelable state)
{
Bundle bundle = (Bundle) state;
Parcelable superState = bundle.getParcelable("superState");
super.onRestoreInstanceState(superState);
handInitialized = bundle.getBoolean("handInitialized");
handPosition = bundle.getFloat("handPosition");
handTarget = bundle.getFloat("handTarget");
handVelocity = bundle.getFloat("handVelocity");
handAcceleration = bundle.getFloat("handAcceleration");
lastHandMoveTime = bundle.getLong("lastHandMoveTime");
}
#Override
protected Parcelable onSaveInstanceState()
{
Parcelable superState = super.onSaveInstanceState();
Bundle state = new Bundle();
state.putParcelable("superState", superState);
state.putBoolean("handInitialized", handInitialized);
state.putFloat("handPosition", handPosition);
state.putFloat("handTarget", handTarget);
state.putFloat("handVelocity", handVelocity);
state.putFloat("handAcceleration", handAcceleration);
state.putLong("lastHandMoveTime", lastHandMoveTime);
return state;
}
private void init()
{
handler = new Handler();
initDrawingTools();
}
private void initDrawingTools()
{
// the linear gradient is a bit skewed for realism
logoPaint = new Paint();
logoPaint.setFilterBitmap(true);
logo = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.logo);
logoMatrix = new Matrix();
logoScale = (1.0f / logo.getWidth()) * 0.3f;
logoMatrix.setScale(logoScale, logoScale);
handPaint = new Paint();
handPaint.setAntiAlias(true);
handPaint.setColor(0xff392f2c);
handPaint.setShadowLayer(0.01f, -0.005f, -0.005f, 0x7f000000);
handPaint.setStyle(Paint.Style.FILL);
handPath = new Path();
handPath.moveTo(0.5f, 0.5f + 0.2f);
handPath.lineTo(0.5f - 0.010f, 0.5f + 0.2f - 0.007f);
handPath.lineTo(0.5f - 0.002f, 0.5f - 0.32f);
handPath.lineTo(0.5f + 0.002f, 0.5f - 0.32f);
handPath.lineTo(0.5f + 0.010f, 0.5f + 0.2f - 0.007f);
handPath.lineTo(0.5f, 0.5f + 0.2f);
handPath.addCircle(0.5f, 0.5f, 0.025f, Path.Direction.CW);
handScrewPaint = new Paint();
handScrewPaint.setAntiAlias(true);
handScrewPaint.setColor(0xff493f3c);
handScrewPaint.setStyle(Paint.Style.FILL);
backgroundPaint = new Paint();
backgroundPaint.setFilterBitmap(true);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
Log.d(TAG, "Width spec: " + MeasureSpec.toString(widthMeasureSpec));
Log.d(TAG, "Height spec: " + MeasureSpec.toString(heightMeasureSpec));
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int chosenWidth = chooseDimension(widthMode, widthSize);
int chosenHeight = chooseDimension(heightMode, heightSize);
int chosenDimension = Math.min(chosenWidth, chosenHeight);
setMeasuredDimension(chosenDimension, chosenDimension);
}
private int chooseDimension(int mode, int size)
{
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY)
{
return size;
}
else
{ // (mode == MeasureSpec.UNSPECIFIED)
return getPreferredSize();
}
}
// in case there is no size specified
private int getPreferredSize()
{
return 300;
}
private void drawScale(Canvas canvas)
{
canvas.drawOval(scaleRect, scalePaint);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
for (int i = 0; i < totalNicks; ++i)
{
float y1 = scaleRect.top;
float y2 = y1 - 0.020f;
canvas.drawLine(0.5f, y1, 0.5f, y2, scalePaint);
if (i % 5 == 0)
{
int value = nickToDegree(i);
if (value >= minDegrees && value <= maxDegrees)
{
String valueString = Integer.toString(value);
canvas.drawText(valueString, 0.5f, y2 - 0.015f, scalePaint);
}
}
canvas.rotate(degreesPerNick, 0.5f, 0.5f);
}
canvas.restore();
}
private int nickToDegree(int nick)
{
int rawDegree = ((nick < totalNicks / 2) ? nick : (nick - totalNicks)) * 2;
int shiftedDegree = rawDegree + centerDegree;
return shiftedDegree;
}
private float degreeToAngle(float degree)
{
return (degree - centerDegree) / 2.0f * degreesPerNick;
}
private void drawLogo(Canvas canvas)
{
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(0.5f - logo.getWidth() * logoScale / 2.0f,0.5f - logo.getHeight() * logoScale / 2.0f);
int color = 0x00000000;
float position = getRelativeTemperaturePosition();
if (position < 0)
{
color |= (int) ((0xf0) * -position); // blue
}
else
{
color |= ((int) ((0xf0) * position)) << 16; // red
}
Log.d(TAG, "*** " + Integer.toHexString(color));
LightingColorFilter logoFilter = new LightingColorFilter(0xff338822,color);
logoPaint.setColorFilter(logoFilter);
canvas.drawBitmap(logo, logoMatrix, logoPaint);
canvas.restore();
}
private void drawHand(Canvas canvas)
{
if (handInitialized)
{
float handAngle = degreeToAngle(handPosition);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.rotate(handAngle, 0.5f, 0.5f);
canvas.drawPath(handPath, handPaint);
canvas.restore();
canvas.drawCircle(0.5f, 0.5f, 0.01f, handScrewPaint);
}
}
private void drawBackground(Canvas canvas)
{
if (background == null)
{
Log.w(TAG, "Background not created");
}
else
{
canvas.drawBitmap(background, 0, 0, backgroundPaint);
}
}
#Override
protected void onDraw(Canvas canvas)
{
drawBackground(canvas);
float scale = (float) getWidth();
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(scale, scale);
drawLogo(canvas);
drawHand(canvas);
canvas.restore();
moveHand();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
Log.d(TAG, "Size changed to " + w + "x" + h);
regenerateBackground();
}
private void regenerateBackground()
{
// free the old bitmap
if (background != null)
{
background.recycle();
}
background = Bitmap.createBitmap(getWidth(), getHeight(),Bitmap.Config.ARGB_8888);
Canvas backgroundCanvas = new Canvas(background);
float scale = (float) getWidth();
backgroundCanvas.scale(scale, scale);
}
private boolean handNeedsToMove()
{
return Math.abs(handPosition - handTarget) > 0.01f;
}
private void moveHand()
{
setHandTarget(maxDegrees);
if (!handNeedsToMove())
{
return;
}
if (lastHandMoveTime != -1L)
{
long currentTime = System.currentTimeMillis();
float delta = (currentTime - lastHandMoveTime) / 1500.0f;
float direction = Math.signum(handVelocity);
if (Math.abs(handVelocity) < 90.0f)
{
handAcceleration = 5.0f * (handTarget - handPosition);
}
else
{
handAcceleration = 0.0f;
}
handPosition += handVelocity * delta;
handVelocity += handAcceleration * delta;
if ((handTarget - handPosition) * direction < 0.01f * direction)
{
handPosition = handTarget;
handVelocity = 0.0f;
handAcceleration = 0.0f;
lastHandMoveTime = -1L;
}
else
{
Log.i("inside ","direction else loop");
lastHandMoveTime = System.currentTimeMillis();
}
invalidate();
}
else
{
Log.i("inside ","direction first final else loop");
lastHandMoveTime = System.currentTimeMillis();
moveHand();
}
if(handPosition==maxDegrees)
{
reverse();
}
}
public void reverse()
{
handAcceleration=1.0f;
Log.i("Hand Velocity",Float.toString(handVelocity));
Log.i("Inside","next loop");
setHandTarget(minDegrees);
if (!handNeedsToMove())
{
return;
}
if (lastHandMoveTime != -1L)
{
long currentTime = System.currentTimeMillis();
float delta = (currentTime -lastHandMoveTime) / 1500.0f;
float direction = Math.signum(handVelocity);
if (Math.abs(handVelocity) <90.0f)
{
handAcceleration = 5.0f * (handPosition+handTarget);
Log.i("Hand Acceleration",Float.toString(handAcceleration));
}
else
{
handAcceleration = 0.0f;
}
handPosition -= handVelocity * delta;
handVelocity -= handAcceleration *delta;
if ((handPosition + handTarget) * direction < 0.01f * direction)
{
handPosition = handTarget;
handVelocity = 0.0f;
handAcceleration = 0.0f;
lastHandMoveTime =-1L;
}
else
{
lastHandMoveTime = System.currentTimeMillis();
}
invalidate();
}
else
{
lastHandMoveTime = System.currentTimeMillis();
reverse();
}
}
private float getRelativeTemperaturePosition()
{
if (handPosition < centerDegree)
{
return -(centerDegree - handPosition)/ (float) (centerDegree - minDegrees);
}
else
{
return (handPosition - centerDegree)/ (float) (maxDegrees - centerDegree);
}
}
private void setHandTarget(float temperature)
{
if (temperature < minDegrees)
{
temperature = minDegrees;
}
else if (temperature > maxDegrees)
{
temperature = maxDegrees;
}
handTarget = temperature;
handInitialized = true;
invalidate();
}
}
Just initialize the hand position to max degree and in the moveHand() method setHandTarget(minDegrees) for anticlockwise rotation It worked for me.
For clockwise rotation just do the opposite.
I have solved hand showing and moving inserting this in main activity:
View termometro = (View)findViewById(R.id.termometro);
termometro.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
It has to do with hardware acceleration
I am new to open GL, I just want to move a circle randomly in the screen , when the user touches the circle , I need to know the hit and miss.
this is what I'm able to achieve through the online classes.
render class:
public class HelloOpenGLES10Renderer implements Renderer {
private int points = 250;
private float vertices[] = { 0.0f, 0.0f, 0.0f };
private FloatBuffer vertBuff;
public float x = 0.0f, y = 0.0f;
public boolean color = false;
boolean first = true;
#Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(x, y, 0);
gl.glColor4f(1.0f, 1.0f, 1.0f, 0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points);
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
Log.i("TAG", "change" + width + ":" + height);
gl.glViewport(0, 0, width, height);
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);
GLU.gluLookAt(gl, 0f, 0f, -5f, 0.0f, 0.0f, 0f, 0.0f, 1.0f, 0.0f);
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.i("TAG", "CREATE");
gl.glClearColor(0.1f, 0.1f, 0.0f, 1.0f);
initShapes();
}
private void initShapes() {
vertices = new float[(points + 1) * 3];
for (int i = 3; i < (points + 1) * 3; i += 3) {
double rad = (i * 360 / points * 3) * (3.14 / 180);
vertices[i] = (float) Math.cos(rad) * 0.10f;
vertices[i + 1] = (float) Math.sin(rad) * 0.10f;
vertices[i + 2] = 0;
}
ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4);
bBuff.order(ByteOrder.nativeOrder());
vertBuff = bBuff.asFloatBuffer();
vertBuff.put(vertices);
vertBuff.position(0);
}
}
Activity:
package com.example.opengltrail;
import java.util.Random;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity implements OnTouchListener {
private GLSurfaceView mGLView;
float oldx = 0, oldy = 0;
private HelloOpenGLES10Renderer m;
ProgressDialogThread p;
ProgressDialogThread123 t;
boolean stop = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLView = new GLSurfaceView(this);
m = new HelloOpenGLES10Renderer();
mGLView.setRenderer(m);
mGLView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setContentView(mGLView);
mGLView.setOnTouchListener(this);
p = new ProgressDialogThread();
}
#Override
protected void onPause() {
super.onPause();
mGLView.onPause();
p.stop();
stop = false;
}
#Override
protected void onResume() {
super.onResume();
mGLView.onResume();
t = new ProgressDialogThread123();
t.start();
p.start();
}
/**
* gets u the random number btw 0.0 to 1.0
*/
public float getmearandom() {
Random rng = new Random();
float next = rng.nextFloat();
Integer i = rng.nextInt();
if (i % 2 == 0)
next = next * (-1);
return next;
}
class ProgressDialogThread123 extends Thread {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
for (; stop;) {
p.run();
}
}
}
class ProgressDialogThread extends Thread {
#Override
public void run() {
super.run();
if (stop) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
m.x = getmearandom();
m.y = getmearandom();
Log.i("m.x=" + m.x + ":", "m.y=" + m.y);
mGLView.requestRender();
}
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
float x1 = ((x * 2) / 480);
float y1 = ((y * 2) / 724);
x1 = -1 + x1;
y1 = -1 + y1;
if (y < 362) {
if (y1 > 0)
y1 = -y1;
} else if (y > 362) {
if (y1 < 0)
y1 = -y1;
} else {
y1 = 0;
}
if (x > 240) {
if (x1 < 0)
x1 = -x1;
} else if (x < 240) {
if (x1 > 0)
x1 = -x1;
} else {
x1 = 0;
}
Log.i("x1=" + x1, "y1=" + y1);
float d = (((m.x - x1) * (m.x - x1)) + ((m.y - y1) * (m.y - y1)));
float dd = FloatMath.sqrt(d);
if (dd <= 0.10f) {
m.color = true;
// mGLView.requestRender();
Log.i("Tag", "Circle");
}
// m.x += 0.10f;
return true;
}
}
Please anyone help me !! thanks in advance
If you are only drawing in 2d I suggest you loose "frustum" and "lookAt" and replace them with "ortho" with coordinates: ortho(viewOrigin.x, viewOrigin.x + viewSize.width, viewOrigin.y + viewSize.height, viewOrigin.y, -1.0f, 1.0f). This will make your GL coordinate system same as your view coordinates. As for circle vertices rather create them with radius of 1.0f. Now to draw the circle, before the draw call you just have to "push" matrix, translate to screen coordinates (X, Y, .0f), scale to radius R in pixels (R, R, 1.0f) and "pop" the matrix after the call.. Now to check on touch if the circle was hit:
`bool didHit = ((touch.x-cicrcleCenter.x)*(touch.x-cicrcleCenter.x) +
(touch.y-cicrcleCenter.y)*(touch.y-cicrcleCenter.y))
< R*R`;
Note that "viewOrigin" in "ortho" depends on where you are catching touches: If you are catching them in the same view it will probably be at (0,0) no matter where the view is. Those coordinates should correspond to coordinates you receive in your touch event when pressing at upper left and bottom right corners of your view.
If you really need to draw in 3d and you will have to use frustum, you will need to get inverse of your projection matrix to create 3d rays from your touches and then check for hits the same way you would for bullets if you like.