Android Opengl doesn't render my display like emulator - android

I recently i stumbled accross a weird problem(or at least i think so).I made in a little opengl es app for Android.The problem is that on the emulator it run's fine but on the phone it just doesn't render what the emulator showed me!
I tested the app on 2 devices:Samsung Ace and Sony Xperia x10 with the same result!
I just don't know what is the problem(i don't have too much experience with opengl on android) so please if you have some ideas... point me out
Some code:
Class that implements Renderer
public class GLOrbitor implements Renderer{
OrbitorLayer layer;
TexFont text; //this is used to render 1-9 and A-Z
TexFont text1; //this one to render a-z
int x;
int y;
private int atomNumber;
private int width;
private int height;
private Context context;
private final static float consty = 0.15f;
GLOrbitor(Context context){
setContext(context);
}
#Override
public void onDrawFrame(GL10 gl) {
// TODO Auto-generated method stub
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, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
gl.glPushMatrix();
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glEnable(GL10.GL_BLEND); // We know this is a 32bit font so set blending to suit
gl.glBlendFunc(GL10.GL_SRC_ALPHA,GL10.GL_ONE_MINUS_SRC_ALPHA);
drawNumAndLetters(gl);
gl.glDisable(GL10.GL_BLEND);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glPopMatrix();
gl.glPushMatrix();
//gl.glTranslatef(-0.8f, 0.8f, 0f);
layer.draw(gl,getAtomNumber());
gl.glPopMatrix();
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
// TODO Auto-generated method stub
gl.glViewport(0,0, width, height);
this.width = width;
this.height = height;
float ratio = (float)width/height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, 1, 1, 3, 7);
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
layer = new OrbitorLayer();
text = new TexFont(getContext(),gl);
text1 = new TexFont(getContext(),gl);
try {
text.LoadFont("ubunturegular.bff", gl); // 0-9 and A-Z
text1.LoadFont("ubunturegular1.bff", gl); //a-z
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_NICEST);
gl.glClearColor(0.0f,0.0f,0.0f, 1f);
gl.glEnable(GL10.GL_DEPTH_TEST | GL10.GL_SMOOTH);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glFrontFace(GL10.GL_CCW);
//gl.glEnable(GL10.GL_CULL_FACE);
//gl.glCullFace(GL10.GL_BACK);
}
}`
//this code draw a tiny rectangle
public GLRectangle(){
setFilled(false);
ByteBuffer vbb = ByteBuffer.allocateDirect(12 * 4);
vbb.order(ByteOrder.nativeOrder());
mFVertexBuffer = vbb.asFloatBuffer();
ByteBuffer ibb = ByteBuffer.allocateDirect(6 * 2);
ibb.order(ByteOrder.nativeOrder());
mIndexBuffer = ibb.asShortBuffer();
float[] coords = {
-poz, -poz, 0,
poz, -poz, 0,
poz, poz, 0,
-poz,poz,0
};
mFVertexBuffer.put(coords);
short[] myIndecesArray = {0,1,2,0,2,3};
mIndexBuffer.put(myIndecesArray);
mFVertexBuffer.position(0);
mIndexBuffer.position(0);
}
public void draw(GL10 gl)
{
if(isFilled())
gl.glColor4f(1f, 0f, 0f, 1f);
else gl.glColor4f(1f, 1f, 1f, 1f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLES, 6,GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
//and this one draw an array of rectangles
public class OrbitorLayer {
GLRectangle[] rectangle;
GLMargin margin;
private final static float consty = 0.15f;
OrbitorLayer(){
margin = new GLMargin();
rectangle = new GLRectangle[118];
}
public void draw(GL10 gl,int atomNumber){
for(int i = 0;i<118;i++){
rectangle[i] = new GLRectangle();
if((i>=0) && (i<atomNumber))
rectangle[i].setFilled(true);
}
//there's some exception for chromium with z = 24 and copper with z=29
//they have 4s1 and 3d5 also 4s1 and 3d10
if(atomNumber == 24){
//4s2 is at 19 and 24
rectangle[19].setFilled(false);
rectangle[24].setFilled(true);
}
else if(atomNumber == 29){
//3d10 is at 29
rectangle[19].setFilled(false);
rectangle[29].setFilled(true);
}
gl.glPushMatrix();
margin.draw(gl);
gl.glPopMatrix();
int index = -1;
float startx = -0.9f;
float starty = 0.8f;
//start with 1s layer
for(int i=0;i<2;i++){
index++;
//rectangle[index] = new GLRectangle();
//translate and draw
gl.glPushMatrix();
gl.glTranslatef((float) (startx + (i * 0.05)), starty, 0.0f);
rectangle[index].draw(gl);
gl.glPopMatrix();
}
//2 s layer
startx = -0.9f;
starty = (float)(0.8f - (1 * consty));
for(int i=0;i<2;i++){
index++;
//rectangle[index] = new GLRectangle();
//translate and draw
gl.glPushMatrix();
gl.glTranslatef((float) (startx + (i * 0.05)), starty, 0.0f);
rectangle[index].draw(gl);
gl.glPopMatrix();
}
//2 p layer
startx = 0.7f;
starty = (float)(0.8f - (1 * consty));
for(int i=0;i<6;i++){
index++;
//rectangle[index] = new GLRectangle();
//translate and draw
gl.glPushMatrix();
gl.glTranslatef((float) (startx + (i * 0.05)), starty, 0.0f);
rectangle[index].draw(gl);
gl.glPopMatrix();
}
}
And a screenshot on how it's rendered on emulator
On a real android smartphone those filled rectangles and blue rounded shape aren't visible only the letters and number's which are drawn with these code
http://www.codehead.co.uk/cbfg/TexFont.java
If you have some ideas please don't hesitate!
Update:
Thank you Craigy and Matthew
Craigy:On a real phone i can't see those red and white little rectangles. Everything else work as exepected.By the way :only the the zone that fill the blue rectangle is an GLSurfaceView everything else has no link with opengl!Sorry if i can't provide a screenshot from a real device.My app was tested by 2 friends on their device's.
Matthew:the only thing where i use texture is displaying:1,2,3,4,5,6,7 and s,f,d,p.And what's funny is that they are rendered well on a real device.My question is why drawing texture's affects drawing and translating those rectangles.Anyway i will play a little more with the info you suggested me and i will let you guys now!
If you have any new intel about these problem...please i beg you..it's driving me nut's just displaying a few rectangles and some text give me so much problem's!!

You aren't specifying texture coordinates.
By default, the opengl implementation in the emulator doesn't do texturing correctly. By default it uses a 'fast' mode that blits the image without regard to texture coordinates. So your images show up on the 'incorrect' emulator, but don't work on a 'correct' device.
I'd suggest forgetting about the emulator for opengl development.
A few more things to keep in mind:
The emulator will work with non power-or-two textures; the device won't.
Android will scale images to match the density of the device, potentially resulting in your power-of-two texture ending up being non-power-of-two. Be sure to set BitmapFactory.Options.inScaled to false to prevent this.

Related

Line drawing drawn inverted in OpenGL ES

I'm trying to draw a simple line drawing connecting several vertices in OpenGL ES. However, the line is drawn inverted or in a different position from where it should be drawn. I've attached the class for the line drawing below
ConnectingPath.java
--------------------
public class ConnectingPath {
int positionBufferId;
PointF[] verticesList;
public float vertices[];
public FloatBuffer vertexBuffer;
public ConnectingPath(LinkedList<PointF> verticesList, float[] colors)
{
List<PointF> tempCorners = verticesList;
int i = 0;
this.verticesList = new PointF[tempCorners.size()];
for (PointF corner : tempCorners) {
this.verticesList[i++] = corner;
}
}
public float[] getTransformedVertices()
{
float z;
List<Float> finalVertices = new ArrayList<Float>();
finalVertices.clear();
for(PointF point : verticesList){
finalVertices.add(point.x);
finalVertices.add(point.y);
finalVertices.add(0.0f);
}
int i = 0;
float[] verticesArray = new float[finalVertices.size()];
for (Float f : finalVertices) {
verticesArray[i++] = (f != null ? f : Float.NaN);
}
return verticesArray;
}
public void initBooth(){
vertices = this.getTransformedVertices();
for(Float f : vertices){
Log.d("Mapsv3--", f + "");
}
ByteBuffer bb = ByteBuffer.allocateDirect(vertices.length * 4);
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
int[] buffers = new int[1];
GLES11.glGenBuffers(1, buffers, 0);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, buffers[0]);
GLES11.glBufferData(GLES11.GL_ARRAY_BUFFER, 4 * vertices.length, vertexBuffer, GLES11.GL_STATIC_DRAW);
positionBufferId = buffers[0];
}
public void Render(GL10 gl){
GLES11.glPushMatrix();
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, positionBufferId);
GLES11.glEnableClientState(GL10.GL_VERTEX_ARRAY);
GLES11.glVertexPointer(3, GL10.GL_FLOAT, 0, 0);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
GLES11.glFrontFace(GL10.GL_CW);
GLES11.glLineWidth(10.0f);
GLES11.glColor4f(0.0f,0.0f,0.0f,1.0f);
GLES11.glDrawArrays(GL10.GL_LINE_STRIP, 0, verticesList.length);
GLES11.glDisableClientState(GL10.GL_VERTEX_ARRAY);
GLES11.glPopMatrix();
}
}
Drawing code :
Renderer.java
--------------
// Variables here
public void onSurfaceChanged(GL10 gl, int width, int height) {
viewWidth = width;
viewHeight = height;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glEnable(GL10.GL_TEXTURE_2D); //Enable Texture Mapping
gl.glShadeModel(GL10.GL_SMOOTH); //Enable Smooth Shading
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); //Grey Background
gl.glClearDepthf(1.0f); //Depth Buffer Setup
gl.glEnable(GL10.GL_DEPTH_TEST); //Enables Depth Testing
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, -viewWidth/2, viewWidth/2, -viewHeight/2,viewHeight/2);
gl.glTranslatef(center.x,center.y,0);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0,0, 0);
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glCullFace(GL10.GL_FRONT);
if(connectingPath!=null){
connectingPath.Render(gl);
}
gl.glDisable(GL10.GL_CULL_FACE);
gl.glLoadIdentity();
}
Screenshot :
The drawing in OpenGL seems to be inverted for you due to the way OpenGL defines it's screen coordinates. In contrast to most 2D drawing API's, the origin is located in the bottom left corner, which means that the y axis values increase when moving upwards. A very nice explanation is available in the OpenGL common pitfalls (Number 12):
Given a sheet of paper, people write from the top of the page to the bottom. The origin for writing text is at the upper left-hand margin of the page (at least in European languages). However, if you were to ask any decent math student to plot a few points on an X-Y graph, the origin would certainly be at the lower left-hand corner of the graph. Most 2D rendering APIs mimic writers and use a 2D coordinate system where the origin is in the upper left-hand corner of the screen or window (at least by default). On the other hand, 3D rendering APIs adopt the mathematically minded convention and assume a lower left-hand origin for their 3D coordinate systems.

What is a technique to animate objects from sprite sheet in OpenGL ES Android?

Because of performance I moved to OpenGL ES 2D from canvas.drawBitmap
This is sprite sheet 4x1:
Now to make it work I had followed class:
public Vulcan(ScreenObjectsView objectsView, int vulkanSpriteID, Context context) {
this.b = BitmapFactory.decodeResource(context.getResources(), vulkanSpriteID);
// 1x4
height = b.getHeight();
width = b.getWidth()/4;
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
x = display.getWidth()/2-width/2; // deprecated
y = display.getHeight()-height; // deprecated
}
public void update() {
frameFreq++;
if(frameFreq > 0){
currentFrame = ++currentFrame % 4;
frameFreq = 0;
}
}
#Override
public void draw(Canvas canvas) {
update();
int srcX = currentFrame * width;
Rect src = new Rect(srcX, 0, srcX+width, height);
Rect dst = new Rect(x, y, x+width, y+height);
canvas.drawBitmap(b, src, dst, null);
}
Each period of time I take Rect and shift from left to right (in loop):
currentFrame = ++currentFrame % 4;
So far so good.
How can I animate above mentioned sprite sheet in in OpenGL ES?
Today, I know how to draw and move objects in OpenGL ES (thanks to good demo)
but don't know to play with sprites.
Any ideas, links, snippets of code?
[Edit]
Ther is no mater to use sprite sheet or 4 images like:
, and so on.
Strange that still didn't get any answer or direction.
Thank you,
[Edit 2]
According to what Aert says I implemented the following code and it works.
But it seems messy
Too much code for OpenGL ES. For each texture (I have 4), I need create FloatBuffer:
Maybe someone have shorter way, or I did something wrong.
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
public class DevQuestSpriteBase {
private static final String LOG_TAG = "Fess";//DevQuestSpriteBase.class.getSimpleName();
protected int mFrame = 0;
protected int mSwitcher = 0;
private int textureCount = 1; // frame animation
protected int[] textures = new int[textureCount]; // frame animation
// texture and verts
protected FloatBuffer vertexBuffer,
textureBuffer1,
textureBuffer2,
textureBuffer3,
textureBuffer4;
ByteBuffer bb1;
protected float vertices[] = {
0f,0f,0.0f,
1f,0f,0.0f,
0f,1f,0.0f,
1f,1f,0.0f
};
/** 1 frame */
protected float texture1[] = {
0.0f, 1.0f,
0.0f, 0.0f,
0.25f, 1.0f,
0.25f, 0.0f
};
/** 2 frame */
protected float texture2[] = {
0.25f, 1.0f,
0.25f, 0.0f,
0.5f, 1.0f,
0.5f, 0.0f
};
/** 3 frame */
protected float texture3[] = {
0.5f, 1.0f,
0.5f, 0.0f,
0.75f, 1.0f,
0.75f, 0.0f
};
/** 4 frame */
protected float texture4[] = {
0.75f, 1.0f,
0.75f, 0.0f,
1.0f, 1.0f,
1.0f, 0.0f
};
public DevQuestSpriteBase(){
// vertices buffer
bb1 = ByteBuffer.allocateDirect(vertices.length * 4);
bb1.order(ByteOrder.nativeOrder());
vertexBuffer = bb1.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
// texture buffer
bb1 = ByteBuffer.allocateDirect(texture1.length * 4);
bb1.order(ByteOrder.nativeOrder());
textureBuffer1 = bb1.asFloatBuffer();
textureBuffer1.put(texture1);
textureBuffer1.position(0);
//#########################################################
// texture buffer
bb1 = ByteBuffer.allocateDirect(texture2.length * 4);
bb1.order(ByteOrder.nativeOrder());
textureBuffer2 = bb1.asFloatBuffer();
textureBuffer2.put(texture2);
textureBuffer2.position(0);
//#########################################################
// texture buffer
bb1 = ByteBuffer.allocateDirect(texture3.length * 4);
bb1.order(ByteOrder.nativeOrder());
textureBuffer3 = bb1.asFloatBuffer();
textureBuffer3.put(texture3);
textureBuffer3.position(0);
//#########################################################
// texture buffer
bb1 = ByteBuffer.allocateDirect(texture4.length * 4);
bb1.order(ByteOrder.nativeOrder());
textureBuffer4 = bb1.asFloatBuffer();
textureBuffer4.put(texture4);
textureBuffer4.position(0);
}
private void update() {
if(mSwitcher == 5){
mFrame = ++mFrame % 4;
mSwitcher = 0;
// Log.e(LOG_TAG, "DevQuestSpriteBase :: " + mFrame);
}
else{
mSwitcher++;
}
}
public void draw(GL10 gl){
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
if(mFrame == 0){
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer1);
}
else if(mFrame == 1){
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer2);
}
else if(mFrame == 2){
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer3);
}
else if(mFrame == 3){
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer4);
}
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
//Log.e(LOG_TAG, "DevQuestSpriteBase :: draw");
update();
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
//gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer1);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
public int[] getTextures() {
return textures;
}
}
Without going into a lot of detail, you need to do the following (assuming you are already drawing a sprite using 4 vertices):
Define the texture coordinates corresponding to the vertices of the sprite for each animation frame, e.g.
texCoordsFrame1 = [0.0f, 0.0f, 0.25f, 0.0f, 0.0f, 1.0f, 0.25f, 1.0f];
Upload the spritesheet texture, e.g.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
Draw using the texture coordinates corresponding to the frame you want to show when required, e.g.
...
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexCoordPointer(2, GL_FLOAT, 0, texCoordsFrame1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
Alternatively, you can upload the separate frames as individual textures, but that is undesirable from a performance point of view.
There are a few gotcha's
When using GLES1, you can only use power-of-two textures. In that case you'll have to scale the texture or increase its size to be power-of-two and adjust the texture coordinates.
The bitmap vs GL y-coordinate direction difference is a bit confusing, and you might end up with a vertically flipped sprite.

GL Wallpaper example only shows green screen in Emulator, but it's working in device

Do there is any special emulator settings needed to run OpenGL Apps?
I already set "GPU emulation" property to "yes".
I am trying to run an Android sample live wallpaper, using the sample source found from this link, The desired output is a rotating triangle.
After a little effort I got the app running but it doesn't draw anything in emulator but when I tested in device it works, But in the emulator it still just shows a green screen, I found a discussion on it in Google groups here. I tried to set view port as said in it. But still it doesn't show any result, on surface changed I had added this line
gl.glViewport(0, 0, width, height);
Do this is the correct way to set view port?
This is my render class,
public class MyRenderer implements GLWallpaperService.Renderer {
GLTriangle mTriangle;
public void onDrawFrame(GL10 gl) {
gl.glClearColor(0.2f, 0.4f, 0.2f, 1f);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
autoRotate(gl);
gl.glColor4f(.2f, 0f, .5f, 1f);
mTriangle.draw(gl);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluPerspective(gl, 60f, (float)width/(float)height, 1f, 100f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -5);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
mTriangle = new GLTriangle();
gl.glClearDepthf(1f);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
}
/**
* Called when the engine is destroyed. Do any necessary clean up because
* at this point your renderer instance is now done for.
*/
public void release() {
}
private void autoRotate(GL10 gl) {
gl.glRotatef(1, 0, 1, 0);
gl.glRotatef(0.5f, 1, 0, 0);
}
}
Herse is GLTriangle class
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
public class GLTriangle {
private FloatBuffer _vertexBuffer;
private final int _nrOfVertices = 3;
private ShortBuffer _indexBuffer;
public GLTriangle() {
init();
}
private void init() {
// We use ByteBuffer.allocateDirect() to get memory outside of
// the normal, garbage collected heap. I think this is done
// because the buffer is subject to native I/O.
// See http://download.oracle.com/javase/1.4.2/docs/api/java/nio/ByteBuffer.html#direct
// 3 is the number of coordinates to each vertex.
_vertexBuffer = BufferFactory.createFloatBuffer(_nrOfVertices * 3);
_indexBuffer = BufferFactory.createShortBuffer(_nrOfVertices);
// Coordinates for the vertexes of the triangle.
float[] coords = {
-1f, -1f, 0f, // (x1, y1, z1)
1f, -1f, 0f, // (x2, y2, z2)
0f, 1f, 0f // (x3, y3, z3)
};
short[] _indicesArray = {0, 1, 2};
_vertexBuffer.put(coords);
_indexBuffer.put(_indicesArray);
_vertexBuffer.position(0);
_indexBuffer.position(0);
}
public void draw(GL10 gl) {
// 3 coordinates in each vertex
// 0 is the space between each vertex. They are densely packed
// in the array, so the value is 0
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, getVertexBuffer());
// Draw the primitives, in this case, triangles.
gl.glDrawElements(GL10.GL_TRIANGLES, _nrOfVertices, GL10.GL_UNSIGNED_SHORT, _indexBuffer);
}
private FloatBuffer getVertexBuffer() {
return _vertexBuffer;
}
}
What's going wrong here? Is there a better sample code for Open GL live wallpaper?
AT LAST I FOUND IT..
What I need to do is just add
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
to onSurfaceCreated method along with the code line
gl.glViewport(0, 0, width, height);
in the onSurfaceChanged method in MyRenderer Class
I found a similar question in stack itself [ But Solution worked for me is not marked as correct :( ]

android/openGL: fill a 2d viewport with a square

What I've managed to accomplish so far is:
Initialise the GLSurfaceView/Renderer
Draw a triangle on the screen
Render a square/rectangle on the screen
Add a bitmap texture to the screen
Ensure PNG transparency is honoured when rendering
Automatically scale the triangles so they show up correctly for all screen sizes
However, after fixing the scaled triangles, the background rectangle (with texture) no longer fills up the screen.
I've been stuck on this for a while now and absolutely baffled to the point I have thrown in the towel.
The main parts I'm unsure about is the use of glFrustumf() and gluLookAt().
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode
gl.glLoadIdentity(); // reset the matrix to its default state
gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix
}
#Override
public void onDrawFrame(GL10 gl) {
// Clear the screen
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Set GL_MODELVIEW transformation mode
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity(); // reset the matrix to its default state
// When using GL_MODELVIEW, you must set the camera view
GLU.gluLookAt(gl, 0, 0, -5f, 0f, 0f, 0f, 0.0f, 1.0f, 0.0f);
bg.draw(gl);
// ...
}
If anybody has a moment to take a look at the problem, I've uploaded the files to https://bitbucket.org/koonkii/test_opengl/src so you don't have to recreate the code by copy-pasting.
GLU.gluLookAt(gl, 0, 0, -5f, 0f, 0f, 0f, 0.0f, 1.0f, 0.0f);
Try to change -5f to 0, what you're saying here is displace the camera 5 units back, therefore unless you're doing an orthogonal projection (which I think you're not, try checking out this) what OpenGL is doing is scaling your background polygon according to your perspective view, and you see it as 'smaller'.
If you do an orthogonal projection, no matter how much you move your camera in the z axis, you will always see it the same size. This is useful for 2D OpenGL-based games, so do check out the link above.
EDIT: gluPerspective and glOrtho
gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
gluPerspective has a parameter called 'fovy', which is basically the 'Field of View in the Y axis'. The field of view expresses the amount of space the camera can see, basically 'expanding' or 'contracting' whatever vertices happen to be before it. A typical human eye has a 45ยบ FOV.
The zNear and zFar express the near and far frustum limits, the frustum being an invisible 'box' which determines which vertices are outside the viewing area.
Aspect determines the ratio between the width and height of the camera.
glOrtho is a special case of gluPerspective in the sense that the FOV is always 0.
gl.glOrthof(0.0f, (float) width, (float) height, 0.0f, 1.0f, -1.0f);
The first four parameters specify the size of the clipping plane (normally the size of the screen), the other two values specifiy the frustum near and far (which you don't need unless you want to hide objects by placing them 'far away'.
I hope this cleared it up a bit for you.
Alright, after a good nights sleep and applying RedOrav's advice regarding orthogonal projection, I did more browsing into it and got it working!
The code snippets given by RedOrav did actually work, however after switching to the orthogonal projection I was still drawing the squares and triangles as small as 0.15f in width. Barely be visible as it's less than 1 pixel wide!
After changing the background/square/triangle code to something more reasonable (30.0f), they showed up!
Played around with the code a bit more and got positioning working properly. I've submitted the code to bitbucket for those who want to check out a working copy of the project.
The reason why I needed G.getYPos() is because the bottom coordinate = 0, and top is screen height. Couldn't figure out a nicer way of inverting it without turning all the textures upside-down.
The important initialisation parts are:
Global helper
public class G {
public static float ratio;
public static int width, height;
/** The texture pointer */
public static int[] textures = new int[3];
final static int TEXTURE_DEFAULT = 0;
final static int TEXTURE_BG = 1;
final static int TEXTURE_ANDROID = 2;
final static int TEXTURE_TURTLE = 3;
/**
* Since (bottom = 0, top = height), we need to invert the values so they make sense logically.
*/
public static int getYPos(int top) {
return G.height - top;
}
}
Renderer class
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
this.loadGLTextures(gl);
gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f); //Red Background
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
// Save these for global use.
G.width = width;
G.height = height;
G.ratio = (float) width / height;
// Set up orthogonal viewport and make adjustments for screen ratio
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0, width, 0, height); // The parameters are weird but bottom = 0 so we need an inverter function G.
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
// Start setting up the constructs we need
bg = new Background();
squares = new ArrayList<Square>();
squares.add(new Square(width / 2, G.getYPos(0))); // middle/top of the screen
squares.add(new Square(width / 2, G.height /2)); // center of the screen
triangles = new ArrayList<Triangle>();
triangles.add(new Triangle(0, G.getYPos(0))); // top left
triangles.add(new Triangle(width, G.getYPos(height))); // bottom right
triangles.add(new Triangle(width /2, height /2)); // middle
}
#Override
public void onDrawFrame(GL10 gl) {
// Clear the screen
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
bg.draw(gl);
for (Square s : squares) {
s.draw(gl);
}
// Draw correctly scaled triangles
for (Triangle t : triangles) {
t.draw(gl);
}
try {
Thread.sleep(400);
}
catch (InterruptedException e) {
}
}
/**
* Loads the textures up.
*/
public void loadGLTextures(GL10 gl) {
int[] texture_map = new int[] { R.drawable.bg_game, R.drawable.ic_launcher };
Bitmap bitmap;
// generate one texture pointer, keep 0 as blank/default
gl.glGenTextures(texture_map.length, G.textures, 0);
for (int i = 0; i < texture_map.length; i++) {
// loading texture
bitmap = BitmapFactory.decodeResource(context.getResources(), texture_map[i]);
// ...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, G.textures[i +1]);
// create nearest filtered texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
// Use Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
// Clean up
bitmap.recycle();
}
}
Background class
p
ublic class Background {
private FloatBuffer vertexBuffer; // buffer holding the vertices
private float vertices[] = {
-1.0f, -1.0f, 0.0f, // V1 - bottom left
-1.0f, 1.0f, 0.0f, // V2 - top left
1.0f, -1.0f, 0.0f, // V3 - bottom right
1.0f, 1.0f, 0.0f // V4 - top right
};
private FloatBuffer textureBuffer; // buffer holding the texture coordinates
private float texture[] = {
// Mapping coordinates for the vertices
0.0f, 1.0f, // top left (V2)
0.0f, 0.0f, // bottom left (V1)
1.0f, 1.0f, // top right (V4)
1.0f, 0.0f // bottom right (V3)
};
public Background() {
// Recalculate the vertices so they fit the screen
vertices[0] = 0; // v1 left
vertices[1] = G.height; // v1 bottom
vertices[3] = 0; // v2 left
vertices[4] = 0; // v2 top
vertices[6] = G.width; // v3 right
vertices[7] = G.height; // v3 bottom
vertices[9] = G.width; // v4 right
vertices[10] = 0; // v4 top
// a float has 4 bytes so we allocate for each coordinate 4 bytes
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
// allocates the memory from the byte buffer
vertexBuffer = byteBuffer.asFloatBuffer();
// fill the vertexBuffer with the vertices
vertexBuffer.put(vertices);
// set the cursor position to the beginning of the buffer
vertexBuffer.position(0);
byteBuffer = ByteBuffer.allocateDirect(texture.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
textureBuffer = byteBuffer.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glEnable(GL10.GL_TEXTURE_2D); // Twig;
// Bind the previously generated texture
gl.glBindTexture(GL10.GL_TEXTURE_2D, G.textures[G.TEXTURE_BG]);
// Point to our buffers
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Point to our vertex buffer
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
// Draw the vertices as triangle strip
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
//Disable the client state before leaving
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D); // twig;
}
}
Square class
Very similar to background except it has a position and applies alpha transparency.
public class Square {
private FloatBuffer vertexBuffer; // buffer holding the vertices
private float vertices[] = {
-1.0f, -1.0f, 0.0f, // V1 - bottom left
-1.0f, 1.0f, 0.0f, // V2 - top left
1.0f, -1.0f, 0.0f, // V3 - bottom right
1.0f, 1.0f, 0.0f // V4 - top right
};
private FloatBuffer textureBuffer; // buffer holding the texture coordinates
private float texture[] = {
// Mapping coordinates for the vertices
0.0f, 1.0f, // top left (V2)
0.0f, 0.0f, // bottom left (V1)
1.0f, 1.0f, // top right (V4)
1.0f, 0.0f // bottom right (V3)
};
public Square(float posX, float posY) {
float w = 30f;
float h = w;
vertices[0] = posX - w; // left
vertices[3] = posX - w;
vertices[6] = posX + w; // right
vertices[9] = posX + w;
vertices[1] = posY - h; // top
vertices[4] = posY + h;
vertices[7] = posY - h; // bottom
vertices[10] = posY + h;
// a float has 4 bytes so we allocate for each coordinate 4 bytes
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
// allocates the memory from the byte buffer
vertexBuffer = byteBuffer.asFloatBuffer();
// fill the vertexBuffer with the vertices
vertexBuffer.put(vertices);
// set the cursor position to the beginning of the buffer
vertexBuffer.position(0);
byteBuffer = ByteBuffer.allocateDirect(texture.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
textureBuffer = byteBuffer.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);
}
/** The draw method for the square with the GL context */
public void draw(GL10 gl) {
// Enable alpha transparency
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
// bind the previously generated texture
gl.glEnable(GL10.GL_TEXTURE_2D); // Twig;
gl.glBindTexture(GL10.GL_TEXTURE_2D, G.textures[G.TEXTURE_ANDROID]);
// Point to our buffers
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// reset the colour for the square
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
// Point to our vertex buffer
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
// Draw the vertices as triangle strip
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
//Disable the client state before leaving
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Disable alpha transparency
gl.glDisable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDisable(GL10.GL_TEXTURE_2D); // twig;
}
}
Triangle class
public class Triangle {
private FloatBuffer vertexBuffer; // buffer holding the vertices
private float vertices[] = {
-0.5f, -0.5f, 0.0f, // V1 - first vertex (x,y,z)
0.5f, -0.5f, 0.0f, // V2 - second vertex
0.0f, 0.5f, 0.0f // V3 - third vertex
};
public Triangle(float posX, float posY) {
int w = 30;
int h = w;
vertices[0] = posX - (w/2); // left
vertices[3] = posX + (w/2); // right
vertices[6] = posX; // middle
vertices[1] = posY - (h/2); // bottom
vertices[4] = posY - (h/2); // bottom
vertices[7] = posY + (h/2); // top
// a float has 4 bytes so we allocate for each coordinate 4 bytes
ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
vertexByteBuffer.order(ByteOrder.nativeOrder());
// allocates the memory from the byte buffer
vertexBuffer = vertexByteBuffer.asFloatBuffer();
// fill the vertexBuffer with the vertices
vertexBuffer.put(vertices);
// set the cursor position to the beginning of the buffer
vertexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
// set the colour for the triangle
gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
// Point to our vertex buffer
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
// Draw the vertices as triangle strip
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
// Reset the colour
gl.glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
//Disable the client state before leaving
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
}
Hope this helps anyone else having similar issues with starting OpenGL.

OpenGL ES object shape is not drawing properly in earlier version of android honeycomb

Im drawing a circle and even if i draw a basic shape (eg.square, diamond) using java opengl ES in android.
If I run the application in honeycomb the shape is coming fine but if I run it in gingerbread with the shape few more unnecessary points where getting drawn(it getting scattered) and if I keep on executing it rarely it comes without those points.
My Renderer class,
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(0, 0, -5.0f);
gl.glRotatef(-100, 1.0f, 0.0f, 0.0f);
gl.glRotatef(40, 1.0f, 0.0f, 0.0f);
mCircle= new Circle();
Circle.setCirclePoints(1.5f,4, 1, 360);
Circle.draw(gl);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(-6.5f, +6.5f, -6.5f, 6.5f, 6.5f, -6.5f);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
gl.glClearColor(0,0,0,0);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
}
In my Circle Class
public void setCirclePoints(float radius, int slices, int stacks,
float angle)
ByteBuffer vbb = ByteBuffer.allocateDirect(((slices+2)* 3 * 4));
vbb.order(ByteOrder.nativeOrder());
mSliceVertexBuffer = vbb.asFloatBuffer();
mSliceVertexBuffer.put(0.0f);
mSliceVertexBuffer.put(0.0f);
mSliceVertexBuffer.put(nsign * radius);
for (int j = 0; j <= slices; j++) {
theta = j * dtheta;
x = (float) 1.25f * (float) (Math.cos(theta + dupTheta));
y = (float) Math.sin(theta + dupTheta);
z = nsign;
mSliceVertexBuffer.put(x * radius);
mSliceVertexBuffer.put(y * radius);
mSliceVertexBuffer.put(z * radius);
}
}
public void draw(GL10 gl){
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mSliceVertexBuffer);
gl.glColor4f(212,21,54,34);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0,sliceCount);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
Im really clue less.. I dont know why its not drawing properly in android version <3.0.
edit: I tried to solve it, I found that when I'm trying to plot the points, few vertex are going out of the viewport(may be infinity, I dont know) in android 2.3.3, but for the same points in android 3.0 it drawing the proper shape.
Help me out.
x = (float) 1.25f * (float) (Math.cos(theta + dupTheta));
What's that factor 1.25 supposed to mean? If your circle is coming out as an ellipse, then that's because your projection matrix doesn't take into account window aspect.
I made a blunder mistake
The issue was in
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0,sliceCount);
where the sliceCount is total number of points x,y,z. I divided that one by 3.
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0,sliceCount/3);

Categories

Resources