android opengl bitmap image not rendered with texImage2D - android

I want to create a waving flag as live wallpaper, the problem is it does not draw image(with no error!) but it draws other textures successfully.
I considered other similar questions and solutions of them but no success.
here is the code for StripesSurfaceView that implements GLSurfaceView.Renderer :
private final class StripesSurfaceView extends GLSurfaceView implements
GLSurfaceView.Renderer {
private Context context;
private int textures[];
private OpenGLFlag flag;
private boolean paused = false;
public StripesSurfaceView(Context context) {
super(context);
this.context = context;
setRenderer(this);
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
#Override
public final SurfaceHolder getHolder() {
return WallpaperEngine.this.getSurfaceHolder();
}
public final void onDestroy() {
super.onDetachedFromWindow();
}
#Override
public final void onDrawFrame(GL10 gl) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
gl.glPushMatrix();
// rotate
gl.glRotatef(Constants.FLAG_ROTATION_X, 1.0f, 0.0f, 0.0f);
gl.glRotatef(Constants.FLAG_ROTATION_Y, 0.0f, 1.0f, 0.0f);
gl.glRotatef(Constants.FLAG_ROTATION_Z, 0.0f, 0.0f, 1.0f);
// draw
flag.draw(gl, paused);
gl.glPopMatrix();
}
#Override
public final void onSurfaceChanged(GL10 gl, int width,
int height) {
float ratio = (float) width / height;
// flag
flag = new OpenGLFlag(textures[0], 0, 0, 0, ratio * 2, ratio);
gl.glShadeModel(GL10.GL_SMOOTH);
GLES20.glClearDepthf(1.0f);
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthFunc(GLES20.GL_LEQUAL);
GLES20.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GLES20.GL_NICEST);
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glEnable(GL10.GL_POINT_SMOOTH);
GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA); // https://www.opengl.org/sdk/docs/man2/xhtml/glBlendFunc.xml
GLES20.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // https://www.opengl.org/sdk/docs/man2/xhtml/glFrustum.xml
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0, 0, 3.5f, 0, 0, 0, 0, 1.0f, 0); // https://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml
}
#Override
public final void onSurfaceCreated(GL10 gl, EGLConfig config)
{
// bind texture
textures = new int[1];
GLES20.glEnable(GLES20.GL_TEXTURE_2D);
GLES20.glGenTextures(textures.length, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
Log.d("gfd", context.getResources()+" :: "+ Constants.FLAG_TEXTURE);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.s);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
}
}
and here is where StripesSurfaceView called:
private final class WallpaperEngine extends Engine {
private StripesSurfaceView mGLSurfaceView;
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
mGLSurfaceView = new StripesSurfaceView(getApplicationContext());
}
// ..... etc
here is the current result:
texture to wave:

problem solved using decodestream :
private Bitmap getBitmapFromAssets(Context context, String fileName, int width, int height) {
AssetManager asset = context.getAssets();
InputStream is;
try {
is = asset.open(fileName);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bit=BitmapFactory.decodeStream(is, null, options);
return bit;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I released source here:
https://github.com/ataafarin/android-live-wallpaper-wavingflag

Related

Change opengl object vertices in Android onCameraFrme

I am making an application with Opengl and Opencv.
Opencv identifies the corners of a square on the screen.
I apply an algorithm that converts the screen coordinates of points into Cartesian coordinates into opengl, and I create the vertices.
But each point taken from the four caught in the square is modified to each frame,
so the float array of vertices also changes with each frame, how to change the vertices to each frame?
this is MyGLSurfaceView
public class MyGLSurfaceView implements GLSurfaceView.Renderer{
Context context;
Model3D model3D;
float[] vertices;
public MyGLSurfaceView(Context context, float[] vertices){
this.context = context;
this.vertices = vertices;
//ColocaModel(gl,vertices);
model3D = new Model3D(vertices);
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
model3D.model3DTexture(gl,context);
gl.glEnable(GL10.GL_TEXTURE_2D); // Enable texture (NEW)
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
if (height == 0) height = 1; // To prevent divide by zero
float aspect = (float)width / height;
// Set the viewport (display area) to cover the entire window
gl.glViewport(0, 0, width, height);
// Setup perspective projection, with aspect ratio matches viewport
gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix
gl.glLoadIdentity(); // Reset projection matrix
// Use perspective projection
GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f);
gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix
gl.glLoadIdentity();
}
#Override
public void onDrawFrame(GL10 gl) {
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -6.0f);
//gl.glTranslatex(200, 500, -6);
//gl.glRotatef(angleCube, 0.1f, 1.0f, 0.2f);
model3D = new Model3D(vertices);
model3D.draw(gl,vertices);
}
}
My object
public class Model3D {
float[] texCoords = { // Texture coords for the above face (NEW)
0.0f, 1.0f, // A. left-bottom (NEW)
1.0f, 1.0f, // B. right-bottom (NEW)
0.0f, 0.0f, // C. left-top (NEW)
1.0f, 0.0f // D. right-top (NEW)
};
int[] textureIDs = new int[1]; //array para 1 textura
private FloatBuffer vertexBuffer;
private FloatBuffer texBuffer;
public Model3D(float[] vertices){
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
vertexBuffer = vbb.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
ByteBuffer tbb = ByteBuffer.allocateDirect(texCoords.length * 4);
tbb.order(ByteOrder.nativeOrder());
texBuffer = tbb.asFloatBuffer();
texBuffer.put(texCoords);
texBuffer.position(0);
}
public void model3DTexture(GL10 gl, Context context) {
gl.glGenTextures(1, textureIDs, 0); // Generate texture-ID array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureIDs[0]); // Bind to texture ID
// Set up texture filters
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);
// Construct an input stream to texture image "res\drawable\nehe.png"
#SuppressLint("ResourceType") InputStream istream = context.getResources().openRawResource(R.drawable.image2);
Bitmap bitmap;
try {
// Read and decode input as bitmap
bitmap = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch(IOException e) { }
}
// Build Texture from loaded bitmap for the currently-bind texture ID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
public void draw(GL10 gl,float[] vertices){
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable texture-coords-array (NEW)
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texBuffer); // Define texture-coords buffer (NEW)
gl.glVertexPointer(3, GL10.GL_FLOAT, 0,vertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,0,vertices.length/3);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
}
My call
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyGLSurfaceView view = new MyGLSurfaceView(this,vertices);
glView = new GLSurfaceView(this);
glView = (GLSurfaceView) findViewById(R.id.glView);
glView.setZOrderOnTop(true);
glView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
glView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
glView.setRenderer(view);
glView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
At this point is where I would like to make the vertex change
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
...
...
These are my converted vertices
public float[] vertices = {
xCP4, yCP4, 0.0f,
xCP3, yCP3, 0.0f,
xCP1, yCP1, 0.0f,
xCP2, yCP2, 0.0f
};

Image Target Vufroria Sample example

i want to make my own object of tracker like in Image Target example i want to replace the Teapot by another 3D shape , the problem is i can't understand the code very well! here is the Code:
Teapot Class:
have two Functions:
setVerts() and setIndices() with alot of indices and vertices numbers
and the ImageTargetRender is:
// The renderer class for the ImageTargets sample.
public class ImageTargetRenderer implements GLSurfaceView.Renderer
{
private static final String LOGTAG = "ImageTargetRenderer";
private SampleApplicationSession vuforiaAppSession;
private ImageTargets mActivity;
private Vector<Texture> mTextures;
private int shaderProgramID;
private int vertexHandle;
private int normalHandle;
private int textureCoordHandle;
private int mvpMatrixHandle;
private int texSampler2DHandle;
private Teapot mTeapot;
private float kBuildingScale = 12.0f;
private SampleApplication3DModel mBuildingsModel;
private Renderer mRenderer;
boolean mIsActive = false;
private static final float OBJECT_SCALE_FLOAT = 3.0f;
public ImageTargetRenderer(ImageTargets activity,
SampleApplicationSession session)
{
mActivity = activity;
vuforiaAppSession = session;
}
// Called to draw the current frame.
#Override
public void onDrawFrame(GL10 gl)
{
if (!mIsActive)
return;
// Call our function to render content
renderFrame();
}
// Called when the surface is created or recreated.
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
Log.d(LOGTAG, "GLRenderer.onSurfaceCreated");
initRendering();
// Call Vuforia function to (re)initialize rendering after first use
// or after OpenGL ES context was lost (e.g. after onPause/onResume):
vuforiaAppSession.onSurfaceCreated();
}
// Called when the surface changed size.
#Override
public void onSurfaceChanged(GL10 gl, int width, int height)
{
Log.d(LOGTAG, "GLRenderer.onSurfaceChanged");
// Call Vuforia function to handle render surface size changes:
vuforiaAppSession.onSurfaceChanged(width, height);
}
// Function for initializing the renderer.
private void initRendering()
{
mTeapot = new Teapot();
mRenderer = Renderer.getInstance();
GLES20.glClearColor(0.0f, 0.0f, 0.0f, Vuforia.requiresAlpha() ? 0.0f
: 1.0f);
for (Texture t : mTextures)
{
GLES20.glGenTextures(1, t.mTextureID, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t.mTextureID[0]);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA,
t.mWidth, t.mHeight, 0, GLES20.GL_RGBA,
GLES20.GL_UNSIGNED_BYTE, t.mData);
}
shaderProgramID = SampleUtils.createProgramFromShaderSrc(
CubeShaders.CUBE_MESH_VERTEX_SHADER,
CubeShaders.CUBE_MESH_FRAGMENT_SHADER);
vertexHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexPosition");
normalHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexNormal");
textureCoordHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexTexCoord");
mvpMatrixHandle = GLES20.glGetUniformLocation(shaderProgramID,
"modelViewProjectionMatrix");
texSampler2DHandle = GLES20.glGetUniformLocation(shaderProgramID,
"texSampler2D");
try
{
mBuildingsModel = new SampleApplication3DModel();
mBuildingsModel.loadModel(mActivity.getResources().getAssets(),
"ImageTargets/Buildings.txt");
} catch (IOException e)
{
Log.e(LOGTAG, "Unable to load buildings");
}
// Hide the Loading Dialog
mActivity.loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.HIDE_LOADING_DIALOG);
}
// The render function.
private void renderFrame()
{
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
State state = mRenderer.begin();
mRenderer.drawVideoBackground();
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
// handle face culling, we need to detect if we are using reflection
// to determine the direction of the culling
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_BACK);
if (Renderer.getInstance().getVideoBackgroundConfig().getReflection() == VIDEO_BACKGROUND_REFLECTION.VIDEO_BACKGROUND_REFLECTION_ON)
GLES20.glFrontFace(GLES20.GL_CW); // Front camera
else
GLES20.glFrontFace(GLES20.GL_CCW); // Back camera
// did we find any trackables this frame?
for (int tIdx = 0; tIdx < state.getNumTrackableResults(); tIdx++)
{
TrackableResult result = state.getTrackableResult(tIdx);
Trackable trackable = result.getTrackable();
printUserData(trackable);
Matrix44F modelViewMatrix_Vuforia = Tool
.convertPose2GLMatrix(result.getPose());
float[] modelViewMatrix = modelViewMatrix_Vuforia.getData();
int textureIndex = trackable.getName().equalsIgnoreCase("stones") ? 0
: 1;
textureIndex = trackable.getName().equalsIgnoreCase("tarmac") ? 2
: textureIndex;
// deal with the modelview and projection matrices
float[] modelViewProjection = new float[16];
if (!mActivity.isExtendedTrackingActive())
{
Matrix.translateM(modelViewMatrix, 0, 0.0f, 0.0f,
OBJECT_SCALE_FLOAT);
Matrix.scaleM(modelViewMatrix, 0, OBJECT_SCALE_FLOAT,
OBJECT_SCALE_FLOAT, OBJECT_SCALE_FLOAT);
} else
{
Matrix.rotateM(modelViewMatrix, 0, 90.0f, 1.0f, 0, 0);
Matrix.scaleM(modelViewMatrix, 0, kBuildingScale,
kBuildingScale, kBuildingScale);
}
Matrix.multiplyMM(modelViewProjection, 0, vuforiaAppSession
.getProjectionMatrix().getData(), 0, modelViewMatrix, 0);
// activate the shader program and bind the vertex/normal/tex coords
GLES20.glUseProgram(shaderProgramID);
if (!mActivity.isExtendedTrackingActive())
{
GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
false, 0, mTeapot.getVertices());
GLES20.glVertexAttribPointer(normalHandle, 3, GLES20.GL_FLOAT,
false, 0, mTeapot.getNormals());
GLES20.glVertexAttribPointer(textureCoordHandle, 2,
GLES20.GL_FLOAT, false, 0, mTeapot.getTexCoords());
GLES20.glEnableVertexAttribArray(vertexHandle);
GLES20.glEnableVertexAttribArray(normalHandle);
GLES20.glEnableVertexAttribArray(textureCoordHandle);
// activate texture 0, bind it, and pass to shader
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
mTextures.get(textureIndex).mTextureID[0]);
GLES20.glUniform1i(texSampler2DHandle, 0);
// pass the model view matrix to the shader
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
modelViewProjection, 0);
// finally draw the teapot
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
mTeapot.getNumObjectIndex(), GLES20.GL_UNSIGNED_SHORT,
mTeapot.getIndices());
// disable the enabled arrays
GLES20.glDisableVertexAttribArray(vertexHandle);
GLES20.glDisableVertexAttribArray(normalHandle);
GLES20.glDisableVertexAttribArray(textureCoordHandle);
} else
{
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
false, 0, mBuildingsModel.getVertices());
GLES20.glVertexAttribPointer(normalHandle, 3, GLES20.GL_FLOAT,
false, 0, mBuildingsModel.getNormals());
GLES20.glVertexAttribPointer(textureCoordHandle, 2,
GLES20.GL_FLOAT, false, 0, mBuildingsModel.getTexCoords());
GLES20.glEnableVertexAttribArray(vertexHandle);
GLES20.glEnableVertexAttribArray(normalHandle);
GLES20.glEnableVertexAttribArray(textureCoordHandle);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
mTextures.get(3).mTextureID[0]);
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
modelViewProjection, 0);
GLES20.glUniform1i(texSampler2DHandle, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,
mBuildingsModel.getNumObjectVertex());
SampleUtils.checkGLError("Renderer DrawBuildings");
}
SampleUtils.checkGLError("Render Frame");
}
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
mRenderer.end();
}
private void printUserData(Trackable trackable)
{
String userData = (String) trackable.getUserData();
Log.d(LOGTAG, "UserData:Retreived User Data \"" + userData + "\"");
}
public void setTextures(Vector<Texture> textures)
{
mTextures = textures;
}
}
building.xml is another file with diffrent numbers of vertices and indices
i'm Confused about the numbers in building.xml and in setVertx() ,setindcises()
plz help.
You shouldn't define a 3d object the way teapot have been defined.
I would use a library like RajawaliVuforia, If i was you.

Android 2D Game With OpenGL

Recently I worked on a 2D Game using SurfaceView and I learned a lot about game loops and everything. But now I want to make the same game using OpenGL. I read that the GLSurfaceView is the class that would be relative to what SurfaceView was. But I'm not sure about other things as:
Using SurfaceView, I used the Bitmap class to load a image resource that would be lets say a character. And that bitmap would be a property of my Character class. And for the gameloop I used a different Thread
I'm new to OpenGL so I'd like to know how to load image resources (do I load them using the Bitmap class?), or what to use instead of a Thread for the game loop?
do I load them using the Bitmap class?
Yes, you can load bitmap and use it as textImage2D.
Example:
public void loadTextures(GL10 gl, Context context) {
Log.e(LOG_TAG, "ExplosionSprite :: loadTextures");
mFrame = 0;
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(DRAW_SOURCE);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
gl.glGenTextures(TEXTURE_COUNT, textures, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
Before 4 month I did the same, because of performance switched to OpenGL ES 2D.
Its a bit complicated but after some time seems easy enough.
I don't have right now example for single image but have pretty good example for sprite sheet where I animate my Image. I'm sure you can remove not relevant data to make it for one static image. Google has enough resources "how to" so I'll point what I used for my purposes:
link 1
link 2
link 3
Cast_001_Sprite_.java
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
import net.obviam.droidz.R;
import net.obviam.droidz.model.components.ESpriteDirection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
public class Cast_001_Sprite_ {
private static final String LOG_TAG = Cast_001_Sprite.class.getSimpleName();
/** Sprite sheet definition */
private static final int SPRITE_WIDTH = 5;
private static final int SPRITE_HEIGHT = 4;
private int DRAW_SOURCE = R.drawable.a1;
private int mX = Location._1[0]; // 100;
private int mY = Location._1[1]; // 100;
private float mScreenWidth, mScreenHeight, wRatio, hRatio;
private int mFrame = 0;
private int mSwitcher = 0;
private final static int TEXTURE_COUNT = 1; // for sprite sheet we use 1 image all the time.
private int[] textures = new int[TEXTURE_COUNT]; // frame animation
protected FloatBuffer vertexBuffer;
private final static ESpriteDirection mDirection = ESpriteDirection.TOP_TO_DOWN_LEFT_TO_RIGHT;
public float x, y, initPos, finalPos, initSpeed, currentPos;
private ByteBuffer bb1;
private final static int TOTAL_IMAGE_COUNT_IN_SPRITE = SPRITE_WIDTH * SPRITE_HEIGHT;
private FloatBuffer[] floatBufferArray = new FloatBuffer[TOTAL_IMAGE_COUNT_IN_SPRITE];
private float xOffset = 1.0f/SPRITE_WIDTH;
private float yOffset = 1.0f/SPRITE_HEIGHT;
float[] vertices = new float[] {
-1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f };
private float storage[][] = new float[TOTAL_IMAGE_COUNT_IN_SPRITE][];
private int[] sprite_X_Indexes = new int[SPRITE_WIDTH];//{1,2,3,4};
private int[] sprite_Y_Indexes = new int[SPRITE_HEIGHT];//{1,2,3,4};
public Cast_001_Sprite_(float screenWidth, float screenHeight){
generateSpriteIndexes();
updateScreenData(screenWidth, screenHeight);
int index = 0;
switch (mDirection) {
case TOP_TO_DOWN_LEFT_TO_RIGHT:
for(int row = 0; row<SPRITE_HEIGHT; row++){
for(int column = 0; column<SPRITE_WIDTH; column++){
storage[index] = generateTextures(column, row);
index++;
}
}
break;
case DOWN_TO_TOP_LEFT_TO_RIGHT:
//TODO
// for(int row = spriteLength; row>0; row--){
// for(int column = 0; column<spriteHeight; column++){
// storage[index] = generateTextures( row-1, column);
// index++;
// }
// }
break;
default:
break;
}
// vertices buffer
bb1 = ByteBuffer.allocateDirect(vertices.length * 4);
bb1.order(ByteOrder.nativeOrder());
vertexBuffer = bb1.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
for(int i=0; i<TOTAL_IMAGE_COUNT_IN_SPRITE; i++){
bb1 = ByteBuffer.allocateDirect(storage[i].length * 4);
bb1.order(ByteOrder.nativeOrder());
FloatBuffer textureBuffer = bb1.asFloatBuffer();
textureBuffer.put(storage[i]);
textureBuffer.position(0);
floatBufferArray[i] = textureBuffer;
}
}
private void generateSpriteIndexes() {
for(int indexX = 0; indexX<SPRITE_WIDTH; indexX++){
sprite_X_Indexes[indexX] = indexX+1;
}
for(int indexY = 0; indexY<SPRITE_HEIGHT; indexY++){
sprite_Y_Indexes[indexY] = indexY+1;
}
}
public void updateScreenData(float screenWidth, float screenHeight){
// takes screen Height and Width
this.mScreenWidth = (screenWidth > 0) ? screenWidth : 1f;
this.mScreenHeight = screenHeight;
wRatio = 10f/mScreenWidth;
hRatio = mScreenHeight/10f;
addExplosion(mX,mY);
}
public void addExplosion(float x, float y) {
this.x = x;
this.y = y;
this.initPos = y;
}
/**
* Generates texture by location
*
* #param texture - fill current texture
* #param placeX - image place in sprite scale X
* #param placeY - image place in sprite scale Y
* #return
*/
private float[] generateTextures(int placeX, int placeY) {
float texture[] = new float[8];
/*
V1 _____ V3
| |
| |
V2|_____|V4
*/
//StringBuffer buff = new StringBuffer();
/** V1 */
texture[0] = (placeX == 0)?0.0f : xOffset*sprite_X_Indexes[placeX-1];
texture[1] = yOffset*sprite_Y_Indexes[placeY];
/** V2 */
texture[2] = (placeX == 0)?0.0f : xOffset*sprite_X_Indexes[placeX-1];
texture[3] = (placeY == 0)?0.0f : yOffset*sprite_Y_Indexes[placeY-1];
/** V3 */
texture[4] = xOffset*sprite_X_Indexes[placeX];
texture[5] = yOffset*sprite_Y_Indexes[placeY];
/** V4 */
texture[6] = xOffset*sprite_X_Indexes[placeX];
texture[7] = (placeY == 0)?0.0f : yOffset*sprite_Y_Indexes[placeY-1];
return texture;
}
private void update() {
if(mSwitcher == 1){
mFrame = ++mFrame % TOTAL_IMAGE_COUNT_IN_SPRITE;
mSwitcher = 0;
// Log.e(LOG_TAG, "DevQuestSpriteBase :: " + mFrame);
}
else{
mSwitcher++;
}
}
public void reset(){
mFrame = 0;
}
public void loadTextures(GL10 gl, Context context) {
Log.e(LOG_TAG, "ExplosionSprite :: loadTextures");
mFrame = 0;
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(DRAW_SOURCE);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
gl.glGenTextures(TEXTURE_COUNT, textures, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
public void draw(GL10 gl){
// if(mFrame == TOTAL_IMAGE_COUNT_IN_SPRITE - 1){
// return;
// }
gl.glPushMatrix();
try {
float transx = + (wRatio * x);
float transy = + (mScreenHeight*wRatio) - (wRatio * y) - 1/hRatio;
// Log.e(LOG_TAG, "transx: " + transx + "; transy: " + transy + "; sprite.x: "+ sprite.x + "; sprite.y: " + sprite.y);
gl.glTranslatef(transx, transy, 0.0f);
//########### draw ##############
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, floatBufferArray[mFrame]);
update();
gl.glColor4f(1f, 1f, 1f, 0.2f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
//###############################
} catch (NullPointerException e) {
}
gl.glPopMatrix();
}
}
DevQuest1Activity.java
public class DevQuest1Activity extends Activity {
private DevQuestGLSurfaceView mGLView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mGLView = new DevQuestGLSurfaceView(this);
setContentView(mGLView);
}
#Override
protected void onPause() {
super.onPause();
mGLView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mGLView.onResume();
}
}
DevQuestGLRenderer.java
public class DevQuestGLRenderer implements GLSurfaceView.Renderer {
private static final String LOG_TAG = "Fess";//DevQuestGLRenderer.class.getSimpleName();
private Context context;
private float ratio;
private int screenWidth, screenHeight;
public Cast_001_Sprite Cast_001_Sprite;
public DevQuestGLRenderer(Context context){
this.context = context;
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig confid) {
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.glClearDepthf(1.0f);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
gl.glEnable(GL10.GL_BLEND);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, /*GL10.GL_REPLACE*/ GL10.GL_MODULATE);
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
Log.e(LOG_TAG, "onSurfaceChanged");
// prevent 0 divise
if(height == 0) { height=1;}
screenWidth = width; screenHeight = height;
ratio = (float) width/height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, width, 0, height, -10f, 10f);
gl.glViewport(0, 0, screenWidth, screenHeight);
Cast_001_Sprite = new Cast_001_Sprite(width, height);
Cast_001_Sprite.loadTextures(gl, context);
}
#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.glPushMatrix();
gl.glScalef((screenWidth)/10, (screenHeight*ratio)/10, 1.0f);
Cast_001_Sprite.draw(gl);
gl.glPopMatrix();
}
}
DevQuestGLSurfaceView.java
public class DevQuestGLSurfaceView extends GLSurfaceView {
private DevQuestGLRenderer mRenderer;
private int count = 0;
public DevQuestGLSurfaceView(Context context) {
super(context);
mRenderer = new DevQuestGLRenderer(context);
setRenderer(mRenderer);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}
ESpriteDirection.java
public enum ESpriteDirection {
TOP_TO_DOWN_LEFT_TO_RIGHT,
DOWN_TO_TOP_LEFT_TO_RIGHT,
TOP_TO_DOWN_RIGHT_TO_LEFT,
DOWN_TO_TOP_RIGHT_TO_LEFT
}
And this is an image I used:
USE THIS CODE TO LOAD YOUR IMAGE..
public static int loadTexture(Context context, int resourceId) {
final int[] textureObjectIds = new int[1];
glGenTextures(1, textureObjectIds, 0);
if (textureObjectIds[0] == 0) {
if (LoggerConfig.ON) {
Log.w(TAG, "Could not generate a new OpenGL texture object.");
}
return 0;
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
// Read in the resource
final Bitmap bitmap = BitmapFactory.decodeResource(
context.getResources(), resourceId, options);
if (bitmap == null) {
if (LoggerConfig.ON) {
Log.w(TAG, "Resource ID " + resourceId + " could not be decoded.");
}
glDeleteTextures(1, textureObjectIds, 0);
return 0;
}
// Bind to the texture in OpenGL
glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]);
// Set filtering: a default must be set, or the texture will be
// black.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Load the bitmap into the bound texture.
texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
// Note: Following code may cause an error to be reported in the
// ADB log as follows: E/IMGSRV(20095): :0: HardwareMipGen:
// Failed to generate texture mipmap levels (error=3)
// No OpenGL error will be encountered (glGetError() will return
// 0). If this happens, just squash the source image to be
// square. It will look the same because of texture coordinates,
// and mipmap generation will work.
glGenerateMipmap(GL_TEXTURE_2D);
// Recycle the bitmap, since its data has been loaded into
// OpenGL.
bitmap.recycle();
// Unbind from the texture.
glBindTexture(GL_TEXTURE_2D, 0);
return textureObjectIds[0];
}

Android OpenGL ES not drawing Texture

I have a very basic Activity at the moment. It creates a GLSurfaceView and sets the Renderer. The problem is all I see is red, which is from glClearColor, and no texture. Not even a white area. Also glGetError() is not reporting anything.
Here is the Renderer:
public class MyRenderer implements Renderer {
public MyRenderer(Context context)
{
mContext = context;
}
public void onDrawFrame(GL10 gl) {
gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertex);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texCoords);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(-160.0f, 160.0f, -240.0f, 240.0f, 0.1f, 1.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
float vertexBuffer[] = {
-160.0f, -240.0f,
-160.0f, 240.0f,
160.0f, -240.0f,
160.0f, 240.0f
};
vertex = ByteBuffer.allocateDirect(8 * 4).asFloatBuffer().put(vertexBuffer);
float texCoordsBuffer[] = {
0.0f, 0.0f,
0.0f, 480.0f/512.0f,
320.0f/512.0f, 0.0f,
320.0f/512.0f, 480.0f/512.0f
};
texCoords = ByteBuffer.allocateDirect(8 * 4).asFloatBuffer().put(texCoordsBuffer);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = 240; // needed so that the image will be 512x512
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.image, options);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Log.i(TAG, "Bitmap:{w:" + width + " h:" + height + "}");
gl.glEnable(GL10.GL_TEXTURE_2D);
texture = new int[1];
gl.glGenTextures(1, texture, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR)
{
Log.e(TAG, "GL Texture Load Error: " + error);
}
}
private Context mContext;
private int texture[];
private FloatBuffer vertex;
private FloatBuffer texCoords;
}
There are several problems with your code:
You need to set the byte order of your buffers to native:
vertex.order(ByteOrder.nativeOrder())
After copying data into your buffers, reset the position to 0:
vertex.position(0)
(Do both for texCoord as well).
It would probably also help to put your near clipping plane at -1.0 instead of .1 (in glOrthof).
// needed because the image won't be 512x512
To have OpenGL render the texture, the texture size needs to be a power of 2, ie 64x64, 128x32 or 256x1024

Android Opengl ES: GLUtils.glTexImage2D causing GL_INVALID_ENUM

I'm trying to render a simple textured quad on Android 2.2 using GLSurfaceView. I'm loading a BMP image (128x128) with BitmapFactory.decodeResource() - this seems to work. But whenever I try to put this bitmap into an OpenGL texture using GLUtils.glTexImage2D I get an OpenGL error: glGetError() returns 1280, GL_INVALID_ENUM. What am I doing wrong?
This is the code for my Renderer:
public class MyRenderer implements GLSurfaceView.Renderer {
Context context;
int texId;
public MyRenderer(Context c) {
this.context = c;
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glEnable(GL10.GL_TEXTURE_2D);
this.texId = loadTexture(gl);
}
int loadTexture(GL10 gl) {
int[] tmp = new int[1];
gl.glGenTextures(1, tmp, 0);
int id = tmp[0];
Bitmap bmp = BitmapFactory.decodeResource(this.context.getResources(), R.drawable.myimage);
gl.glGetError();
GLUtils.texImage2D(id, 0, bmp, 0);
int err = gl.glGetError();
if (err != 0) {
// err == 1280, prints "invalid enum":
System.err.println(GLU.gluErrorString(err));
}
return id;
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0, width, height, 0);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
#Override
public void onDrawFrame(GL10 gl) {
// ...
}
}
It should probably be something like:
gl.glBindTexture(GL10.GL_TEXTURE_2D, id);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bmp, 0);

Categories

Resources