kodiak211
Member
I'm new to this. I've created one app on my own, with help of reading things online and books. But the one thing I'm really trying to do is make liveWallpapers. Its my niche area, as I am a artiest. But I can't get a clear idea how to build a LiveWallpaper. I did come a cross a template, but is copyrighted. What I'm trying to build is a OpenGL liveWallpaper using models I've built using "Blender". This template I'm using allows me to do this. If you can help, or have any ideas, please help. Here's the copyrighted code. ---->
FileTexture.java
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import com.Beck.GLExample.R;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
public class FileTexture {
public Context context;
private GL10 gl;
private int[] textures = new int[1];
private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
private Bitmap bitmap;
private String fname;
public FileTexture(GL10 gl,String fname) {
if(gl==null)return;
this.gl = gl;
this.fname=fname;
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
context = GLExample.context;
}
public void loadTexture() {
InputStream is = context.getResources().openRawResource(R.drawable.texture);
bitmap = BitmapFactory.decodeStream(is);
createTexture();
}
private void createTexture() {
gl.glGenTextures(1, textures, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
gl.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1);
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);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_REPEAT);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.w("", "" + error);
}
//}
}
public void setTexture() {
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.textures[0]);
}
}
GLExample.java
its says copyrighted
import java.io.InputStream;
import java.util.Calendar;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.content.SharedPreferences;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGestureListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.service.wallpaper.WallpaperService.Engine;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.hardware.*;
public class GLExample extends GLWallpaperService {
public static final String SHARED_PREFS_NAME="flicker";
private SharedPreferences mPrefs;
public static Context context;
private OpenGLRenderer renderer;
private float mOffset;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public Engine onCreateEngine() {
return new CubeEngine();
}
class CubeEngine extends GLEngine implements SharedPreferences.OnSharedPreferenceChangeListener {
private boolean mVisible;
CubeEngine() {
mPrefs = GLExample.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
}
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
// By default we don't get touch events, so enable them.
setTouchEventsEnabled(true);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onVisibilityChanged(boolean visible) {
mVisible = visible;
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
}
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
super.onSurfaceCreated(holder);
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
}
@Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xStep, float yStep, int xPixels, int yPixels) {
}
@Override
public void onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
}
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
String mode = sharedPreferences.getString("cube2_mode", "2");
}
}
}
GLModel.java
its says coyprighted
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import com.Beck.GLExample.R;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Handler;
import android.util.Log;
class GLModel implements Serializable {
private static String mTex;
private static int intTex;
private float moonangle = 0f;
private int IdxCnt;
private float langle = 0f;
public static boolean useshading = false;
public static float shadowcolor = 0.50f;
private static FileTexture filetexture;
// public static final Handler mHandler = new Handler();
// Create runnable for posting
public static final Runnable mUpdateTex = new Runnable() {
public void run() {
InitTex();
}
};
public GLModel(Context context) {
mContext = context;
loadObj();
Log.e("Model", "LOADED");
}
public static void InitTex() {
intTex = 3;
setTexture(1);
filetexture = new FileTexture(gl11, "null");
filetexture.loadTexture();
textures = new GLTextures(gl11, mContext);
textures.add(R.drawable.texture);
textures.loadTextures();
}
public void Init(GL10 gl) {
if (gl == null)
return;
gl11 = (GL11) gl;
InitTex();
int[] buffer = new int[1];
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mVertexBuffer.capacity() * 4,
mVertexBuffer, GL11.GL_STATIC_DRAW);
Log.e("Vertex", "ok");
gl11.glGenBuffers(1, buffer, 0);
mNormBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mNormBufferIndex);
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mNormBuffer.capacity() * 4,
mNormBuffer, GL11.GL_STATIC_DRAW);
Log.e("Normal", "ok");
// texcoord buffer
gl11.glGenBuffers(1, buffer, 0);
mTexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTexBufferIndex);
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mTexBuffer.capacity() * 4,
mTexBuffer, GL11.GL_STATIC_DRAW);
Log.e("Texture", "ok");
// unbind array buffer
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Buffer d'indices
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBuffer.capacity() * 2, mIndexBuffer, GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
Log.e("VboCube", "Idx ok");
IdxCnt = mIndexBuffer.capacity();
}
private void loadObj() {
try {
AssetManager am = mContext.getAssets();
String str;
String[] tmp;
String[] ftmp;
float v;
ArrayList<Float> vlist = new ArrayList<Float>();
ArrayList<Float> tlist = new ArrayList<Float>();
ArrayList<Float> nlist = new ArrayList<Float>();
ArrayList<Fp> fplist = new ArrayList<Fp>();
BufferedReader inb = new BufferedReader(new InputStreamReader(am
.open("tree.obj")), 1024);
while ((str = inb.readLine()) != null) {
tmp = str.split(" ");
if (tmp[0].equalsIgnoreCase("v")) {
for (int i = 1; i < 4; i++) {
v = Float.parseFloat(tmp);
vlist.add(v);
}
}
if (tmp[0].equalsIgnoreCase("vn")) {
for (int i = 1; i < 4; i++) {
v = Float.parseFloat(tmp);
nlist.add(v);
}
}
if (tmp[0].equalsIgnoreCase("vt")) {
for (int i = 1; i < 3; i++) {
v = Float.parseFloat(tmp);
tlist.add(v);
}
}
if (tmp[0].equalsIgnoreCase("f")) {
for (int i = 1; i < 4; i++) {
ftmp = tmp.split("/");
long chi = Integer.parseInt(ftmp[0]) - 1;
int cht = Integer.parseInt(ftmp[1]) - 1;
int chn = Integer.parseInt(ftmp[2]) - 1;
fplist.add(new Fp(chi, cht, chn));
}
NBFACES++;
}
}
ByteBuffer vbb = ByteBuffer.allocateDirect(fplist.size() * 4 * 3);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asFloatBuffer();
ByteBuffer vtbb = ByteBuffer.allocateDirect(fplist.size() * 4 * 2);
vtbb.order(ByteOrder.nativeOrder());
mTexBuffer = vtbb.asFloatBuffer();
ByteBuffer nbb = ByteBuffer.allocateDirect(fplist.size() * 4 * 3);
nbb.order(ByteOrder.nativeOrder());
mNormBuffer = nbb.asFloatBuffer();
for (int j = 0; j < fplist.size(); j++) {
mVertexBuffer.put(vlist.get((int) (fplist.get(j).Vi * 3)));
mVertexBuffer.put(vlist.get((int) (fplist.get(j).Vi * 3 + 1)));
mVertexBuffer.put(vlist.get((int) (fplist.get(j).Vi * 3 + 2)));
mTexBuffer.put(tlist.get(fplist.get(j).Ti * 2));
mTexBuffer.put(tlist.get((fplist.get(j).Ti * 2) + 1));
mNormBuffer.put(nlist.get(fplist.get(j).Ni * 3));
mNormBuffer.put(nlist.get((fplist.get(j).Ni * 3) + 1));
mNormBuffer.put(nlist.get((fplist.get(j).Ni * 3) + 2));
}
mIndexBuffer = CharBuffer.allocate(fplist.size());
for (int j = 0; j < fplist.size(); j++) {
mIndexBuffer.put((char) j);
}
mVertexBuffer.position(0);
mTexBuffer.position(0);
mNormBuffer.position(0);
mIndexBuffer.position(0);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void draw(GL10 gl, boolean showmoon) {
if (gl11 == null)
return;
if (gl11 == null)
return;
gl.glPushMatrix();
gl.glEnable(GL10.GL_TEXTURE_2D);
filetexture.setTexture();
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTexBufferIndex);
gl11.glClientActiveTexture(GL10.GL_TEXTURE0); // lightmap
gl11.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0);
gl11.glClientActiveTexture(GL10.GL_TEXTURE1); // color
gl11.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0);
gl11.glActiveTexture(GL10.GL_TEXTURE0);
gl11.glEnable(GL10.GL_TEXTURE_2D);
gl11.glActiveTexture(GL10.GL_TEXTURE1);
gl11.glEnable(GL10.GL_TEXTURE_2D);
gl11.glColor4f(shadowcolor, shadowcolor, shadowcolor, shadowcolor);
gl11.glActiveTexture(GL10.GL_TEXTURE0);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL11.GL_COMBINE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB,
GL10.GL_ADD);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB,
GL10.GL_TEXTURE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB,
GL11.GL_PREVIOUS);
gl11.glActiveTexture(GL10.GL_TEXTURE1);
filetexture.setTexture();
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL11.GL_COMBINE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB,
GL10.GL_MODULATE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB,
GL11.GL_PREVIOUS);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB,
GL10.GL_TEXTURE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_OPERAND0_RGB,
GL10.GL_SRC_COLOR);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_OPERAND1_RGB,
GL10.GL_SRC_COLOR);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, GL10.GL_FLOAT, 0, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mNormBufferIndex);
gl11.glNormalPointer(GL10.GL_FLOAT, 0, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, IdxCnt, GL11.GL_UNSIGNED_SHORT,
0);
gl.glPopMatrix();
}
public void freeHardwareBuffers() {
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
buffer[0] = mTexBufferIndex;
buffer[0] = mNormBufferIndex;
buffer[0] = mIndexBufferIndex;
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTexBufferIndex = 0;
mNormBufferIndex = 0;
Log.d("Log", "hardware buffer freed");
}
public static void setTexture(int t) {
intTex = t;
t = 1;
switch (t) {
case 0:
mTex = "0";
break;
}
}
private class Fp {
public long Vi;
public int Ti;
public int Ni;
public Fp(long chi, int ti, int ni) {
Vi = chi;
Ti = ti;
Ni = ni;
}
}
public static GL11 gl11;
private static int NBFACES = 0;
private static GLTextures textures;
private static int mVertBufferIndex;
private static int mNormBufferIndex;
private static int mTexBufferIndex;
private static int mIndexBufferIndex;
private static FloatBuffer mVertexBuffer;
private static FloatBuffer mTexBuffer;
private static FloatBuffer mNormBuffer;
private static CharBuffer mIndexBuffer;
private static Context mContext;
}
GLTextures.java
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
public class GLTextures {
private int[] mCropWorkspace;
private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
public GLTextures(GL10 gl, Context context) {
if(gl==null)return;
this.gl = gl;
this.context = context;
this.textureMap = new java.util.HashMap<Integer, Integer>();
mCropWorkspace = new int[4];
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
}
public void freeTexs(){
gl.glDeleteTextures(textures.length, textures,0);
}
public void loadTextures() {
if(gl==null)return;
int[] tmp_tex = new int[textureFiles.length];
gl.glGenTextures(textureFiles.length, tmp_tex, 0);
textures = tmp_tex;
for (int i = 0; i < textureFiles.length; i++) {
// Load it up
this.textureMap.put(new Integer(textureFiles), new Integer(i));
int tex = tmp_tex;
gl.glBindTexture(GL10.GL_TEXTURE_2D, tex);
gl.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1);
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);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE);
InputStream is = context.getResources().openRawResource(textureFiles);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.w("VboCube", "Texture Load GLError: " + error);
}
}
}
public void setTexture(int id) {
if(gl==null)return;
try {
int textureid = this.textureMap.get(new Integer(id)).intValue();
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.textures[textureid]);
} catch (Exception e) {
return;
}
}
public void add(int resource) {
if (textureFiles == null) {
textureFiles = new int[1];
textureFiles[0] = resource;
} else {
int[] newarray = new int[textureFiles.length + 1];
for (int i = 0; i < textureFiles.length; i++) {
newarray = textureFiles;
}
newarray[textureFiles.length] = resource;
textureFiles = newarray;
}
}
private java.util.HashMap<Integer, Integer> textureMap;
private int[] textureFiles;
private GL10 gl;
private Context context;
private int[] textures;
}
GLWallpaperService.java
import java.io.Writer;
import java.util.ArrayList;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;
import com.Beck.GLExample.OpenGLRenderer;
import com.Beck.GLExample.BaseConfigChooser.ComponentSizeChooser;
import com.Beck.GLExample.BaseConfigChooser.SimpleEGLConfigChooser;
public class GLWallpaperService extends WallpaperService {
private static final String TAG = "GLWallpaperService";
@Override
public Engine onCreateEngine() {
return new GLEngine();
}
public class GLEngine extends Engine {
public final static int RENDERMODE_WHEN_DIRTY = 0;
public final static int RENDERMODE_CONTINUOUSLY = 1;
private GLThread mGLThread;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
private int mDebugFlags;
public GLEngine() {
super();
setRenderer(new OpenGLRenderer());
setRenderMode(RENDERMODE_CONTINUOUSLY);
}
@Override
public void onVisibilityChanged(boolean visible) {
if (visible) {
onResume();
} else {
onPause();
}
super.onVisibilityChanged(visible);
}
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
// Log.d(TAG, "GLEngine.onCreate()");
}
@Override
public void onDestroy() {
super.onDestroy();
// Log.d(TAG, "GLEngine.onDestroy()");
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Log.d(TAG, "onSurfaceChanged()");
mGLThread.onWindowResize(width, height);
super.onSurfaceChanged(holder, format, width, height);
}
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceCreated()");
mGLThread.surfaceCreated(holder);
super.onSurfaceCreated(holder);
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceDestroyed()");
mGLThread.surfaceDestroyed();
super.onSurfaceDestroyed(holder);
}
/**
* An EGL helper class.
*/
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setDebugFlags(int debugFlags) {
mDebugFlags = debugFlags;
}
public int getDebugFlags() {
return mDebugFlags;
}
public void setRenderer(Renderer renderer) {
checkRenderThreadState();
if (mEGLConfigChooser == null) {
mEGLConfigChooser = new SimpleEGLConfigChooser(true);
}
if (mEGLContextFactory == null) {
mEGLContextFactory = new DefaultContextFactory();
}
if (mEGLWindowSurfaceFactory == null) {
mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
}
mGLThread = new GLThread(renderer, mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper);
mGLThread.start();
}
public void setEGLContextFactory(EGLContextFactory factory) {
checkRenderThreadState();
mEGLContextFactory = factory;
}
public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
checkRenderThreadState();
mEGLWindowSurfaceFactory = factory;
}
public void setEGLConfigChooser(EGLConfigChooser configChooser) {
checkRenderThreadState();
mEGLConfigChooser = configChooser;
}
public void setEGLConfigChooser(boolean needDepth) {
setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
}
public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize,
int stencilSize) {
setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize,
stencilSize));
}
public void setRenderMode(int renderMode) {
mGLThread.setRenderMode(renderMode);
}
public int getRenderMode() {
return mGLThread.getRenderMode();
}
public void requestRender() {
mGLThread.requestRender();
}
public void onPause() {
mGLThread.onPause();
}
public void onResume() {
mGLThread.onResume();
}
public void queueEvent(Runnable r) {
mGLThread.queueEvent(r);
}
private void checkRenderThreadState() {
if (mGLThread != null) {
throw new IllegalStateException("setRenderer has already been called for this instance.");
}
}
}
public interface Renderer {
public void onSurfaceCreated(GL10 gl, EGLConfig config);
public void onSurfaceChanged(GL10 gl, int width, int height);
public void onDrawFrame(GL10 gl);
}
}
class LogWriter extends Writer {
private StringBuilder mBuilder = new StringBuilder();
@Override
public void close() {
flushBuilder();
}
@Override
public void flush() {
flushBuilder();
}
@Override
public void write(char[] buf, int offset, int count) {
for (int i = 0; i < count; i++) {
char c = buf[offset + i];
if (c == '\n') {
flushBuilder();
} else {
mBuilder.append(c);
}
}
}
private void flushBuilder() {
if (mBuilder.length() > 0) {
Log.v("GLSurfaceView", mBuilder.toString());
mBuilder.delete(0, mBuilder.length());
}
}
}
// ----------------------------------------------------------------------
/**
* An interface for customizing the eglCreateContext and eglDestroyContext calls.
*
* This interface must be implemented by clients wishing to call
* {@link GLWallpaperService#setEGLContextFactory(EGLContextFactory)}
*/
interface EGLContextFactory {
EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
}
class DefaultContextFactory implements EGLContextFactory {
public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null);
}
public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
egl.eglDestroyContext(display, context);
}
}
/**
* An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
*
* This interface must be implemented by clients wishing to call
* {@link GLWallpaperService#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
*/
interface EGLWindowSurfaceFactory {
EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow);
void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
}
class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow) {
return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
}
public void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface) {
egl.eglDestroySurface(display, surface);
}
}
interface GLWrapper {
/**
* Wraps a gl interface in another gl interface.
*
* @param gl
* a GL interface that is to be wrapped.
* @return either the input argument or another GL object that wraps the input argument.
*/
GL wrap(GL gl);
}
class EglHelper {
private EGL10 mEgl;
private EGLDisplay mEglDisplay;
private EGLSurface mEglSurface;
private EGLContext mEglContext;
EGLConfig mEglConfig;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
public EglHelper(EGLConfigChooser chooser, EGLContextFactory contextFactory,
EGLWindowSurfaceFactory surfaceFactory, GLWrapper wrapper) {
this.mEGLConfigChooser = chooser;
this.mEGLContextFactory = contextFactory;
this.mEGLWindowSurfaceFactory = surfaceFactory;
this.mGLWrapper = wrapper;
}
/**
* Initialize EGL for a given configuration spec.
*
* @param configSpec
*/
public void start() {
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
/*
* Create an OpenGL ES context. This must be done only once, an OpenGL context is a somewhat heavy object.
*/
mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
throw new RuntimeException("createContext failed");
}
mEglSurface = null;
}
/*
* React to the creation of a new surface by creating and returning an OpenGL interface that renders to that
* surface.
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new surface.
*/
if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
/*
* Unbind and destroy the old EGL surface, if there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, mEglDisplay, mEglConfig, holder);
if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
throw new RuntimeException("createWindowSurface failed");
}
/*
* Before we can issue GL commands, we need to make sure the context is current and bound to a surface.
*/
if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
throw new RuntimeException("eglMakeCurrent failed.");
}
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
/*
* if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) { int configFlags = 0; Writer log =
* null; if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; }
* if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = GLDebugHelper.wrap(gl,
* configFlags, log); }
*/
return gl;
}
/**
* Display the current render surface.
*
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context and all associated data were lost (For instance
* because the device went to sleep). We need to sleep until we get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void destroySurface() {
if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
mEglSurface = null;
}
}
public void finish() {
if (mEglContext != null) {
mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
}
class GLThread extends Thread {
private final static boolean LOG_THREADS = false;
public final static int DEBUG_CHECK_GL_ERROR = 1;
public final static int DEBUG_LOG_GL_CALLS = 2;
private final GLThreadManager sGLThreadManager = new GLThreadManager();
private GLThread mEglOwner;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
public SurfaceHolder mHolder;
private boolean mSizeChanged = true;
// Once the thread is started, all accesses to the following member
// variables are protected by the sGLThreadManager monitor
public boolean mDone;
private boolean mPaused;
private boolean mHasSurface;
private boolean mWaitingForSurface;
private boolean mHaveEgl;
private int mWidth;
private int mHeight;
private int mRenderMode;
private boolean mRequestRender;
private boolean mEventsWaiting;
// End of member variables protected by the sGLThreadManager monitor.
private GLWallpaperService.Renderer mRenderer;
private ArrayList mEventQueue = new ArrayList();
private EglHelper mEglHelper;
GLThread(GLWallpaperService.Renderer renderer, EGLConfigChooser chooser, EGLContextFactory contextFactory,
EGLWindowSurfaceFactory surfaceFactory, GLWrapper wrapper) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRequestRender = true;
mRenderMode = GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY;
mRenderer = renderer;
this.mEGLConfigChooser = chooser;
this.mEGLContextFactory = contextFactory;
this.mEGLWindowSurfaceFactory = surfaceFactory;
this.mGLWrapper = wrapper;
}
@Override
public void run() {
setName("GLThread " + getId());
if (LOG_THREADS) {
Log.i("GLThread", "starting tid=" + getId());
}
try {
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sGLThreadManager.threadExiting(this);
}
}
/*
* This private method should only be called inside a synchronized(sGLThreadManager) block.
*/
private void stopEglLocked() {
if (mHaveEgl) {
mHaveEgl = false;
mEglHelper.destroySurface();
mEglHelper.finish();
sGLThreadManager.releaseEglSurface(this);
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper(mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper);
try {
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until asked to quit.
*/
while (!isDone()) {
/*
* Update the asynchronous state (window size)
*/
int w = 0;
int h = 0;
boolean changed = false;
boolean needStart = false;
boolean eventsWaiting = false;
synchronized (sGLThreadManager) {
while (true) {
// Manage acquiring and releasing the SurfaceView
// surface and the EGL surface.
if (mPaused) {
stopEglLocked();
}
if (!mHasSurface) {
if (!mWaitingForSurface) {
stopEglLocked();
mWaitingForSurface = true;
sGLThreadManager.notifyAll();
}
} else {
if (!mHaveEgl) {
if (sGLThreadManager.tryAcquireEglSurface(this)) {
mHaveEgl = true;
mEglHelper.start();
mRequestRender = true;
needStart = true;
}
}
}
// Check if we need to wait. If not, update any state
// that needs to be updated, copy any state that
// needs to be copied, and use "break" to exit the
// wait loop.
if (mDone) {
return;
}
if (mEventsWaiting) {
eventsWaiting = true;
mEventsWaiting = false;
break;
}
if ((!mPaused) && mHasSurface && mHaveEgl && (mWidth > 0) && (mHeight > 0)
&& (mRequestRender || (mRenderMode == GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY))) {
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
mRequestRender = false;
if (mHasSurface && mWaitingForSurface) {
changed = true;
mWaitingForSurface = false;
sGLThreadManager.notifyAll();
}
break;
}
// By design, this is the only place where we wait().
if (LOG_THREADS) {
Log.i("GLThread", "waiting tid=" + getId());
}
sGLThreadManager.wait();
}
} // end of synchronized(sGLThreadManager)
/*
* Handle queued events
*/
if (eventsWaiting) {
Runnable r;
while ((r = getEvent()) != null) {
r.run();
if (isDone()) {
return;
}
}
// Go back and see if we need to wait to render.
continue;
}
if (needStart) {
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.onSurfaceChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
/* draw a frame here */
mRenderer.onDrawFrame(gl);
/*
* Once we're done with GL, we need to call swapBuffers() to instruct the system to display the
* rendered frame
*/
mEglHelper.swap();
}
}
} finally {
/*
* clean-up everything...
*/
synchronized (sGLThreadManager) {
stopEglLocked();
}
}
}
private boolean isDone() {
synchronized (sGLThreadManager) {
return mDone;
}
}
public void setRenderMode(int renderMode) {
if (!((GLWallpaperService.GLEngine.RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY))) {
throw new IllegalArgumentException("renderMode");
}
synchronized (sGLThreadManager) {
mRenderMode = renderMode;
if (renderMode == GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY) {
sGLThreadManager.notifyAll();
}
}
}
public int getRenderMode() {
synchronized (sGLThreadManager) {
return mRenderMode;
}
}
public void requestRender() {
synchronized (sGLThreadManager) {
mRequestRender = true;
sGLThreadManager.notifyAll();
}
}
public void surfaceCreated(SurfaceHolder holder) {
mHolder = holder;
synchronized (sGLThreadManager) {
if (LOG_THREADS) {
Log.i("GLThread", "surfaceCreated tid=" + getId());
}
mHasSurface = true;
sGLThreadManager.notifyAll();
}
}
public void surfaceDestroyed() {
synchronized (sGLThreadManager) {
if (LOG_THREADS) {
Log.i("GLThread", "surfaceDestroyed tid=" + getId());
}
mHasSurface = false;
sGLThreadManager.notifyAll();
while (!mWaitingForSurface && isAlive() && !mDone) {
try {
sGLThreadManager.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public void onPause() {
synchronized (sGLThreadManager) {
mPaused = true;
sGLThreadManager.notifyAll();
}
}
public void onResume() {
synchronized (sGLThreadManager) {
mPaused = false;
mRequestRender = true;
sGLThreadManager.notifyAll();
}
}
public void onWindowResize(int w, int h) {
synchronized (sGLThreadManager) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
sGLThreadManager.notifyAll();
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized (sGLThreadManager) {
mDone = true;
sGLThreadManager.notifyAll();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
*
* @param r
* the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
synchronized (this) {
mEventQueue.add(r);
synchronized (sGLThreadManager) {
mEventsWaiting = true;
sGLThreadManager.notifyAll();
}
}
}
private Runnable getEvent() {
synchronized (this) {
if (mEventQueue.size() > 0) {
return (Runnable) mEventQueue.remove(0);
}
}
return null;
}
private class GLThreadManager {
public synchronized void threadExiting(GLThread thread) {
if (LOG_THREADS) {
Log.i("GLThread", "exiting tid=" + thread.getId());
}
thread.mDone = true;
if (mEglOwner == thread) {
mEglOwner = null;
}
notifyAll();
}
/*
* Tries once to acquire the right to use an EGL surface. Does not block.
*
* @return true if the right to use an EGL surface was acquired.
*/
public synchronized boolean tryAcquireEglSurface(GLThread thread) {
if (mEglOwner == thread || mEglOwner == null) {
mEglOwner = thread;
notifyAll();
return true;
}
return false;
}
public synchronized void releaseEglSurface(GLThread thread) {
if (mEglOwner == thread) {
mEglOwner = null;
}
notifyAll();
}
}
}
interface EGLConfigChooser {
EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
}
abstract class BaseConfigChooser implements EGLConfigChooser {
public BaseConfigChooser(int[] configSpec) {
mConfigSpec = configSpec;
}
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int[] num_config = new int[1];
egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config);
int numConfigs = num_config[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
EGLConfig[] configs = new EGLConfig[numConfigs];
egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config);
EGLConfig config = chooseConfig(egl, display, configs);
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs);
protected int[] mConfigSpec;
public static class ComponentSizeChooser extends BaseConfigChooser {
public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize,
int stencilSize) {
super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE,
blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE,
stencilSize, EGL10.EGL_NONE });
mValue = new int[1];
mRedSize = redSize;
mGreenSize = greenSize;
mBlueSize = blueSize;
mAlphaSize = alphaSize;
mDepthSize = depthSize;
mStencilSize = stencilSize;
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) {
EGLConfig closestConfig = null;
int closestDistance = 1000;
for (EGLConfig config : configs) {
int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
if (d >= mDepthSize && s >= mStencilSize) {
int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize)
+ Math.abs(a - mAlphaSize);
if (distance < closestDistance) {
closestDistance = distance;
closestConfig = config;
}
}
}
return closestConfig;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0];
}
return defaultValue;
}
private int[] mValue;
// Subclasses can adjust these values:
protected int mRedSize;
protected int mGreenSize;
protected int mBlueSize;
protected int mAlphaSize;
protected int mDepthSize;
protected int mStencilSize;
}
/**
* This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer.
*
*/
public static class SimpleEGLConfigChooser extends ComponentSizeChooser {
public SimpleEGLConfigChooser(boolean withDepthBuffer) {
super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0);
// Adjust target values. This way we'll accept a 4444 or
// 555 buffer if there's no 565 buffer available.
mRedSize = 5;
mGreenSize = 6;
mBlueSize = 5;
}
}
}
OpenGLRenderer.java
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.*;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
public class OpenGLRenderer implements GLWallpaperService.Renderer {
public int toss;
public int count;
private GLModel model;
public Context context;
public float angle =0;
public OpenGLRenderer() {
this.context = GLExample.context;
model = new GLModel(this.context);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition
* .khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background color to black ( rgba ).
model.Init(gl);
gl.glEnable(GL10.GL_TEXTURE_2D); //Enable Texture Mapping ( NEW )
gl.glShadeModel(GL10.GL_SMOOTH); //Enable Smooth Shading
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); //Black Background
gl.glClearDepthf(1.0f); //Depth Buffer Setup
gl.glEnable(GL10.GL_DEPTH_TEST); //Enables Depth Testing
gl.glDepthFunc(GL10.GL_LEQUAL); //The Type Of Depth Testing To Do
//Really Nice Perspective Calculations
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.
* khronos.opengles.GL10)
*/
public void onDrawFrame(GL10 gl) {
if (gl == null)
return;
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glPushMatrix();
gl.glScalef(.2f, .2f, .2f);
gl.glTranslatef(0, -1f, -17f);
gl.glRotatef (angle, 0.0f, 1.0f, 0.0f);
gl.glRotatef (90f, 0.0f, 0.0f, 1.0f);
gl.glRotatef(-90f, 0.0f, 0.0f, 1.0f);
gl.glScalef(1.6f, 1.6f, 1.6f);
model.draw(gl, false);
gl.glPopMatrix();
angle = angle + .4f;
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition
* .khronos.opengles.GL10, int, int)
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
// Sets the current view port to the new size.
model.Init(gl);
//model.InitTex();
//square.loadGLTexture(gl, this.context);
//square2.loadGLTexture(gl, this.context);
gl.glViewport(0, 0, width, height);
// Select the projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
// Reset the projection matrix
gl.glLoadIdentity();
// Calculate the aspect ratio of the window
GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
100.0f);
// Select the modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Reset the modelview matrix
gl.glLoadIdentity();
}
}
Settings.java
says its coyprighted
import com.Beck.GLExample.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Settings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
getPreferenceManager().setSharedPreferencesName(
GLExample.SHARED_PREFS_NAME);
addPreferencesFromResource(R.xml.setting_xml);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(
this);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
}
}
FileTexture.java
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import com.Beck.GLExample.R;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
public class FileTexture {
public Context context;
private GL10 gl;
private int[] textures = new int[1];
private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
private Bitmap bitmap;
private String fname;
public FileTexture(GL10 gl,String fname) {
if(gl==null)return;
this.gl = gl;
this.fname=fname;
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
context = GLExample.context;
}
public void loadTexture() {
InputStream is = context.getResources().openRawResource(R.drawable.texture);
bitmap = BitmapFactory.decodeStream(is);
createTexture();
}
private void createTexture() {
gl.glGenTextures(1, textures, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
gl.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1);
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);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_REPEAT);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.w("", "" + error);
}
//}
}
public void setTexture() {
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.textures[0]);
}
}
GLExample.java
its says copyrighted
import java.io.InputStream;
import java.util.Calendar;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.content.SharedPreferences;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGestureListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.service.wallpaper.WallpaperService.Engine;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.hardware.*;
public class GLExample extends GLWallpaperService {
public static final String SHARED_PREFS_NAME="flicker";
private SharedPreferences mPrefs;
public static Context context;
private OpenGLRenderer renderer;
private float mOffset;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public Engine onCreateEngine() {
return new CubeEngine();
}
class CubeEngine extends GLEngine implements SharedPreferences.OnSharedPreferenceChangeListener {
private boolean mVisible;
CubeEngine() {
mPrefs = GLExample.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
}
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
// By default we don't get touch events, so enable them.
setTouchEventsEnabled(true);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onVisibilityChanged(boolean visible) {
mVisible = visible;
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
}
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
super.onSurfaceCreated(holder);
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
}
@Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xStep, float yStep, int xPixels, int yPixels) {
}
@Override
public void onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
}
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
String mode = sharedPreferences.getString("cube2_mode", "2");
}
}
}
GLModel.java
its says coyprighted
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import com.Beck.GLExample.R;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Handler;
import android.util.Log;
class GLModel implements Serializable {
private static String mTex;
private static int intTex;
private float moonangle = 0f;
private int IdxCnt;
private float langle = 0f;
public static boolean useshading = false;
public static float shadowcolor = 0.50f;
private static FileTexture filetexture;
// public static final Handler mHandler = new Handler();
// Create runnable for posting
public static final Runnable mUpdateTex = new Runnable() {
public void run() {
InitTex();
}
};
public GLModel(Context context) {
mContext = context;
loadObj();
Log.e("Model", "LOADED");
}
public static void InitTex() {
intTex = 3;
setTexture(1);
filetexture = new FileTexture(gl11, "null");
filetexture.loadTexture();
textures = new GLTextures(gl11, mContext);
textures.add(R.drawable.texture);
textures.loadTextures();
}
public void Init(GL10 gl) {
if (gl == null)
return;
gl11 = (GL11) gl;
InitTex();
int[] buffer = new int[1];
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mVertexBuffer.capacity() * 4,
mVertexBuffer, GL11.GL_STATIC_DRAW);
Log.e("Vertex", "ok");
gl11.glGenBuffers(1, buffer, 0);
mNormBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mNormBufferIndex);
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mNormBuffer.capacity() * 4,
mNormBuffer, GL11.GL_STATIC_DRAW);
Log.e("Normal", "ok");
// texcoord buffer
gl11.glGenBuffers(1, buffer, 0);
mTexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTexBufferIndex);
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mTexBuffer.capacity() * 4,
mTexBuffer, GL11.GL_STATIC_DRAW);
Log.e("Texture", "ok");
// unbind array buffer
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Buffer d'indices
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBuffer.capacity() * 2, mIndexBuffer, GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
Log.e("VboCube", "Idx ok");
IdxCnt = mIndexBuffer.capacity();
}
private void loadObj() {
try {
AssetManager am = mContext.getAssets();
String str;
String[] tmp;
String[] ftmp;
float v;
ArrayList<Float> vlist = new ArrayList<Float>();
ArrayList<Float> tlist = new ArrayList<Float>();
ArrayList<Float> nlist = new ArrayList<Float>();
ArrayList<Fp> fplist = new ArrayList<Fp>();
BufferedReader inb = new BufferedReader(new InputStreamReader(am
.open("tree.obj")), 1024);
while ((str = inb.readLine()) != null) {
tmp = str.split(" ");
if (tmp[0].equalsIgnoreCase("v")) {
for (int i = 1; i < 4; i++) {
v = Float.parseFloat(tmp);
vlist.add(v);
}
}
if (tmp[0].equalsIgnoreCase("vn")) {
for (int i = 1; i < 4; i++) {
v = Float.parseFloat(tmp);
nlist.add(v);
}
}
if (tmp[0].equalsIgnoreCase("vt")) {
for (int i = 1; i < 3; i++) {
v = Float.parseFloat(tmp);
tlist.add(v);
}
}
if (tmp[0].equalsIgnoreCase("f")) {
for (int i = 1; i < 4; i++) {
ftmp = tmp.split("/");
long chi = Integer.parseInt(ftmp[0]) - 1;
int cht = Integer.parseInt(ftmp[1]) - 1;
int chn = Integer.parseInt(ftmp[2]) - 1;
fplist.add(new Fp(chi, cht, chn));
}
NBFACES++;
}
}
ByteBuffer vbb = ByteBuffer.allocateDirect(fplist.size() * 4 * 3);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asFloatBuffer();
ByteBuffer vtbb = ByteBuffer.allocateDirect(fplist.size() * 4 * 2);
vtbb.order(ByteOrder.nativeOrder());
mTexBuffer = vtbb.asFloatBuffer();
ByteBuffer nbb = ByteBuffer.allocateDirect(fplist.size() * 4 * 3);
nbb.order(ByteOrder.nativeOrder());
mNormBuffer = nbb.asFloatBuffer();
for (int j = 0; j < fplist.size(); j++) {
mVertexBuffer.put(vlist.get((int) (fplist.get(j).Vi * 3)));
mVertexBuffer.put(vlist.get((int) (fplist.get(j).Vi * 3 + 1)));
mVertexBuffer.put(vlist.get((int) (fplist.get(j).Vi * 3 + 2)));
mTexBuffer.put(tlist.get(fplist.get(j).Ti * 2));
mTexBuffer.put(tlist.get((fplist.get(j).Ti * 2) + 1));
mNormBuffer.put(nlist.get(fplist.get(j).Ni * 3));
mNormBuffer.put(nlist.get((fplist.get(j).Ni * 3) + 1));
mNormBuffer.put(nlist.get((fplist.get(j).Ni * 3) + 2));
}
mIndexBuffer = CharBuffer.allocate(fplist.size());
for (int j = 0; j < fplist.size(); j++) {
mIndexBuffer.put((char) j);
}
mVertexBuffer.position(0);
mTexBuffer.position(0);
mNormBuffer.position(0);
mIndexBuffer.position(0);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void draw(GL10 gl, boolean showmoon) {
if (gl11 == null)
return;
if (gl11 == null)
return;
gl.glPushMatrix();
gl.glEnable(GL10.GL_TEXTURE_2D);
filetexture.setTexture();
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTexBufferIndex);
gl11.glClientActiveTexture(GL10.GL_TEXTURE0); // lightmap
gl11.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0);
gl11.glClientActiveTexture(GL10.GL_TEXTURE1); // color
gl11.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0);
gl11.glActiveTexture(GL10.GL_TEXTURE0);
gl11.glEnable(GL10.GL_TEXTURE_2D);
gl11.glActiveTexture(GL10.GL_TEXTURE1);
gl11.glEnable(GL10.GL_TEXTURE_2D);
gl11.glColor4f(shadowcolor, shadowcolor, shadowcolor, shadowcolor);
gl11.glActiveTexture(GL10.GL_TEXTURE0);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL11.GL_COMBINE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB,
GL10.GL_ADD);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB,
GL10.GL_TEXTURE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB,
GL11.GL_PREVIOUS);
gl11.glActiveTexture(GL10.GL_TEXTURE1);
filetexture.setTexture();
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL11.GL_COMBINE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB,
GL10.GL_MODULATE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB,
GL11.GL_PREVIOUS);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB,
GL10.GL_TEXTURE);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_OPERAND0_RGB,
GL10.GL_SRC_COLOR);
gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_OPERAND1_RGB,
GL10.GL_SRC_COLOR);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, GL10.GL_FLOAT, 0, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mNormBufferIndex);
gl11.glNormalPointer(GL10.GL_FLOAT, 0, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, IdxCnt, GL11.GL_UNSIGNED_SHORT,
0);
gl.glPopMatrix();
}
public void freeHardwareBuffers() {
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
buffer[0] = mTexBufferIndex;
buffer[0] = mNormBufferIndex;
buffer[0] = mIndexBufferIndex;
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTexBufferIndex = 0;
mNormBufferIndex = 0;
Log.d("Log", "hardware buffer freed");
}
public static void setTexture(int t) {
intTex = t;
t = 1;
switch (t) {
case 0:
mTex = "0";
break;
}
}
private class Fp {
public long Vi;
public int Ti;
public int Ni;
public Fp(long chi, int ti, int ni) {
Vi = chi;
Ti = ti;
Ni = ni;
}
}
public static GL11 gl11;
private static int NBFACES = 0;
private static GLTextures textures;
private static int mVertBufferIndex;
private static int mNormBufferIndex;
private static int mTexBufferIndex;
private static int mIndexBufferIndex;
private static FloatBuffer mVertexBuffer;
private static FloatBuffer mTexBuffer;
private static FloatBuffer mNormBuffer;
private static CharBuffer mIndexBuffer;
private static Context mContext;
}
GLTextures.java
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
public class GLTextures {
private int[] mCropWorkspace;
private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
public GLTextures(GL10 gl, Context context) {
if(gl==null)return;
this.gl = gl;
this.context = context;
this.textureMap = new java.util.HashMap<Integer, Integer>();
mCropWorkspace = new int[4];
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
}
public void freeTexs(){
gl.glDeleteTextures(textures.length, textures,0);
}
public void loadTextures() {
if(gl==null)return;
int[] tmp_tex = new int[textureFiles.length];
gl.glGenTextures(textureFiles.length, tmp_tex, 0);
textures = tmp_tex;
for (int i = 0; i < textureFiles.length; i++) {
// Load it up
this.textureMap.put(new Integer(textureFiles), new Integer(i));
int tex = tmp_tex;
gl.glBindTexture(GL10.GL_TEXTURE_2D, tex);
gl.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1);
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);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE);
InputStream is = context.getResources().openRawResource(textureFiles);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.w("VboCube", "Texture Load GLError: " + error);
}
}
}
public void setTexture(int id) {
if(gl==null)return;
try {
int textureid = this.textureMap.get(new Integer(id)).intValue();
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.textures[textureid]);
} catch (Exception e) {
return;
}
}
public void add(int resource) {
if (textureFiles == null) {
textureFiles = new int[1];
textureFiles[0] = resource;
} else {
int[] newarray = new int[textureFiles.length + 1];
for (int i = 0; i < textureFiles.length; i++) {
newarray = textureFiles;
}
newarray[textureFiles.length] = resource;
textureFiles = newarray;
}
}
private java.util.HashMap<Integer, Integer> textureMap;
private int[] textureFiles;
private GL10 gl;
private Context context;
private int[] textures;
}
GLWallpaperService.java
import java.io.Writer;
import java.util.ArrayList;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;
import com.Beck.GLExample.OpenGLRenderer;
import com.Beck.GLExample.BaseConfigChooser.ComponentSizeChooser;
import com.Beck.GLExample.BaseConfigChooser.SimpleEGLConfigChooser;
public class GLWallpaperService extends WallpaperService {
private static final String TAG = "GLWallpaperService";
@Override
public Engine onCreateEngine() {
return new GLEngine();
}
public class GLEngine extends Engine {
public final static int RENDERMODE_WHEN_DIRTY = 0;
public final static int RENDERMODE_CONTINUOUSLY = 1;
private GLThread mGLThread;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
private int mDebugFlags;
public GLEngine() {
super();
setRenderer(new OpenGLRenderer());
setRenderMode(RENDERMODE_CONTINUOUSLY);
}
@Override
public void onVisibilityChanged(boolean visible) {
if (visible) {
onResume();
} else {
onPause();
}
super.onVisibilityChanged(visible);
}
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
// Log.d(TAG, "GLEngine.onCreate()");
}
@Override
public void onDestroy() {
super.onDestroy();
// Log.d(TAG, "GLEngine.onDestroy()");
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Log.d(TAG, "onSurfaceChanged()");
mGLThread.onWindowResize(width, height);
super.onSurfaceChanged(holder, format, width, height);
}
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceCreated()");
mGLThread.surfaceCreated(holder);
super.onSurfaceCreated(holder);
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceDestroyed()");
mGLThread.surfaceDestroyed();
super.onSurfaceDestroyed(holder);
}
/**
* An EGL helper class.
*/
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setDebugFlags(int debugFlags) {
mDebugFlags = debugFlags;
}
public int getDebugFlags() {
return mDebugFlags;
}
public void setRenderer(Renderer renderer) {
checkRenderThreadState();
if (mEGLConfigChooser == null) {
mEGLConfigChooser = new SimpleEGLConfigChooser(true);
}
if (mEGLContextFactory == null) {
mEGLContextFactory = new DefaultContextFactory();
}
if (mEGLWindowSurfaceFactory == null) {
mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
}
mGLThread = new GLThread(renderer, mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper);
mGLThread.start();
}
public void setEGLContextFactory(EGLContextFactory factory) {
checkRenderThreadState();
mEGLContextFactory = factory;
}
public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
checkRenderThreadState();
mEGLWindowSurfaceFactory = factory;
}
public void setEGLConfigChooser(EGLConfigChooser configChooser) {
checkRenderThreadState();
mEGLConfigChooser = configChooser;
}
public void setEGLConfigChooser(boolean needDepth) {
setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
}
public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize,
int stencilSize) {
setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize,
stencilSize));
}
public void setRenderMode(int renderMode) {
mGLThread.setRenderMode(renderMode);
}
public int getRenderMode() {
return mGLThread.getRenderMode();
}
public void requestRender() {
mGLThread.requestRender();
}
public void onPause() {
mGLThread.onPause();
}
public void onResume() {
mGLThread.onResume();
}
public void queueEvent(Runnable r) {
mGLThread.queueEvent(r);
}
private void checkRenderThreadState() {
if (mGLThread != null) {
throw new IllegalStateException("setRenderer has already been called for this instance.");
}
}
}
public interface Renderer {
public void onSurfaceCreated(GL10 gl, EGLConfig config);
public void onSurfaceChanged(GL10 gl, int width, int height);
public void onDrawFrame(GL10 gl);
}
}
class LogWriter extends Writer {
private StringBuilder mBuilder = new StringBuilder();
@Override
public void close() {
flushBuilder();
}
@Override
public void flush() {
flushBuilder();
}
@Override
public void write(char[] buf, int offset, int count) {
for (int i = 0; i < count; i++) {
char c = buf[offset + i];
if (c == '\n') {
flushBuilder();
} else {
mBuilder.append(c);
}
}
}
private void flushBuilder() {
if (mBuilder.length() > 0) {
Log.v("GLSurfaceView", mBuilder.toString());
mBuilder.delete(0, mBuilder.length());
}
}
}
// ----------------------------------------------------------------------
/**
* An interface for customizing the eglCreateContext and eglDestroyContext calls.
*
* This interface must be implemented by clients wishing to call
* {@link GLWallpaperService#setEGLContextFactory(EGLContextFactory)}
*/
interface EGLContextFactory {
EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
}
class DefaultContextFactory implements EGLContextFactory {
public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null);
}
public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
egl.eglDestroyContext(display, context);
}
}
/**
* An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
*
* This interface must be implemented by clients wishing to call
* {@link GLWallpaperService#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
*/
interface EGLWindowSurfaceFactory {
EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow);
void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
}
class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow) {
return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
}
public void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface) {
egl.eglDestroySurface(display, surface);
}
}
interface GLWrapper {
/**
* Wraps a gl interface in another gl interface.
*
* @param gl
* a GL interface that is to be wrapped.
* @return either the input argument or another GL object that wraps the input argument.
*/
GL wrap(GL gl);
}
class EglHelper {
private EGL10 mEgl;
private EGLDisplay mEglDisplay;
private EGLSurface mEglSurface;
private EGLContext mEglContext;
EGLConfig mEglConfig;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
public EglHelper(EGLConfigChooser chooser, EGLContextFactory contextFactory,
EGLWindowSurfaceFactory surfaceFactory, GLWrapper wrapper) {
this.mEGLConfigChooser = chooser;
this.mEGLContextFactory = contextFactory;
this.mEGLWindowSurfaceFactory = surfaceFactory;
this.mGLWrapper = wrapper;
}
/**
* Initialize EGL for a given configuration spec.
*
* @param configSpec
*/
public void start() {
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
/*
* Create an OpenGL ES context. This must be done only once, an OpenGL context is a somewhat heavy object.
*/
mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
throw new RuntimeException("createContext failed");
}
mEglSurface = null;
}
/*
* React to the creation of a new surface by creating and returning an OpenGL interface that renders to that
* surface.
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new surface.
*/
if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
/*
* Unbind and destroy the old EGL surface, if there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, mEglDisplay, mEglConfig, holder);
if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
throw new RuntimeException("createWindowSurface failed");
}
/*
* Before we can issue GL commands, we need to make sure the context is current and bound to a surface.
*/
if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
throw new RuntimeException("eglMakeCurrent failed.");
}
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
/*
* if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) { int configFlags = 0; Writer log =
* null; if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; }
* if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = GLDebugHelper.wrap(gl,
* configFlags, log); }
*/
return gl;
}
/**
* Display the current render surface.
*
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context and all associated data were lost (For instance
* because the device went to sleep). We need to sleep until we get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void destroySurface() {
if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
mEglSurface = null;
}
}
public void finish() {
if (mEglContext != null) {
mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
}
class GLThread extends Thread {
private final static boolean LOG_THREADS = false;
public final static int DEBUG_CHECK_GL_ERROR = 1;
public final static int DEBUG_LOG_GL_CALLS = 2;
private final GLThreadManager sGLThreadManager = new GLThreadManager();
private GLThread mEglOwner;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
public SurfaceHolder mHolder;
private boolean mSizeChanged = true;
// Once the thread is started, all accesses to the following member
// variables are protected by the sGLThreadManager monitor
public boolean mDone;
private boolean mPaused;
private boolean mHasSurface;
private boolean mWaitingForSurface;
private boolean mHaveEgl;
private int mWidth;
private int mHeight;
private int mRenderMode;
private boolean mRequestRender;
private boolean mEventsWaiting;
// End of member variables protected by the sGLThreadManager monitor.
private GLWallpaperService.Renderer mRenderer;
private ArrayList mEventQueue = new ArrayList();
private EglHelper mEglHelper;
GLThread(GLWallpaperService.Renderer renderer, EGLConfigChooser chooser, EGLContextFactory contextFactory,
EGLWindowSurfaceFactory surfaceFactory, GLWrapper wrapper) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRequestRender = true;
mRenderMode = GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY;
mRenderer = renderer;
this.mEGLConfigChooser = chooser;
this.mEGLContextFactory = contextFactory;
this.mEGLWindowSurfaceFactory = surfaceFactory;
this.mGLWrapper = wrapper;
}
@Override
public void run() {
setName("GLThread " + getId());
if (LOG_THREADS) {
Log.i("GLThread", "starting tid=" + getId());
}
try {
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sGLThreadManager.threadExiting(this);
}
}
/*
* This private method should only be called inside a synchronized(sGLThreadManager) block.
*/
private void stopEglLocked() {
if (mHaveEgl) {
mHaveEgl = false;
mEglHelper.destroySurface();
mEglHelper.finish();
sGLThreadManager.releaseEglSurface(this);
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper(mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper);
try {
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until asked to quit.
*/
while (!isDone()) {
/*
* Update the asynchronous state (window size)
*/
int w = 0;
int h = 0;
boolean changed = false;
boolean needStart = false;
boolean eventsWaiting = false;
synchronized (sGLThreadManager) {
while (true) {
// Manage acquiring and releasing the SurfaceView
// surface and the EGL surface.
if (mPaused) {
stopEglLocked();
}
if (!mHasSurface) {
if (!mWaitingForSurface) {
stopEglLocked();
mWaitingForSurface = true;
sGLThreadManager.notifyAll();
}
} else {
if (!mHaveEgl) {
if (sGLThreadManager.tryAcquireEglSurface(this)) {
mHaveEgl = true;
mEglHelper.start();
mRequestRender = true;
needStart = true;
}
}
}
// Check if we need to wait. If not, update any state
// that needs to be updated, copy any state that
// needs to be copied, and use "break" to exit the
// wait loop.
if (mDone) {
return;
}
if (mEventsWaiting) {
eventsWaiting = true;
mEventsWaiting = false;
break;
}
if ((!mPaused) && mHasSurface && mHaveEgl && (mWidth > 0) && (mHeight > 0)
&& (mRequestRender || (mRenderMode == GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY))) {
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
mRequestRender = false;
if (mHasSurface && mWaitingForSurface) {
changed = true;
mWaitingForSurface = false;
sGLThreadManager.notifyAll();
}
break;
}
// By design, this is the only place where we wait().
if (LOG_THREADS) {
Log.i("GLThread", "waiting tid=" + getId());
}
sGLThreadManager.wait();
}
} // end of synchronized(sGLThreadManager)
/*
* Handle queued events
*/
if (eventsWaiting) {
Runnable r;
while ((r = getEvent()) != null) {
r.run();
if (isDone()) {
return;
}
}
// Go back and see if we need to wait to render.
continue;
}
if (needStart) {
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.onSurfaceChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
/* draw a frame here */
mRenderer.onDrawFrame(gl);
/*
* Once we're done with GL, we need to call swapBuffers() to instruct the system to display the
* rendered frame
*/
mEglHelper.swap();
}
}
} finally {
/*
* clean-up everything...
*/
synchronized (sGLThreadManager) {
stopEglLocked();
}
}
}
private boolean isDone() {
synchronized (sGLThreadManager) {
return mDone;
}
}
public void setRenderMode(int renderMode) {
if (!((GLWallpaperService.GLEngine.RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY))) {
throw new IllegalArgumentException("renderMode");
}
synchronized (sGLThreadManager) {
mRenderMode = renderMode;
if (renderMode == GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY) {
sGLThreadManager.notifyAll();
}
}
}
public int getRenderMode() {
synchronized (sGLThreadManager) {
return mRenderMode;
}
}
public void requestRender() {
synchronized (sGLThreadManager) {
mRequestRender = true;
sGLThreadManager.notifyAll();
}
}
public void surfaceCreated(SurfaceHolder holder) {
mHolder = holder;
synchronized (sGLThreadManager) {
if (LOG_THREADS) {
Log.i("GLThread", "surfaceCreated tid=" + getId());
}
mHasSurface = true;
sGLThreadManager.notifyAll();
}
}
public void surfaceDestroyed() {
synchronized (sGLThreadManager) {
if (LOG_THREADS) {
Log.i("GLThread", "surfaceDestroyed tid=" + getId());
}
mHasSurface = false;
sGLThreadManager.notifyAll();
while (!mWaitingForSurface && isAlive() && !mDone) {
try {
sGLThreadManager.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public void onPause() {
synchronized (sGLThreadManager) {
mPaused = true;
sGLThreadManager.notifyAll();
}
}
public void onResume() {
synchronized (sGLThreadManager) {
mPaused = false;
mRequestRender = true;
sGLThreadManager.notifyAll();
}
}
public void onWindowResize(int w, int h) {
synchronized (sGLThreadManager) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
sGLThreadManager.notifyAll();
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized (sGLThreadManager) {
mDone = true;
sGLThreadManager.notifyAll();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
*
* @param r
* the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
synchronized (this) {
mEventQueue.add(r);
synchronized (sGLThreadManager) {
mEventsWaiting = true;
sGLThreadManager.notifyAll();
}
}
}
private Runnable getEvent() {
synchronized (this) {
if (mEventQueue.size() > 0) {
return (Runnable) mEventQueue.remove(0);
}
}
return null;
}
private class GLThreadManager {
public synchronized void threadExiting(GLThread thread) {
if (LOG_THREADS) {
Log.i("GLThread", "exiting tid=" + thread.getId());
}
thread.mDone = true;
if (mEglOwner == thread) {
mEglOwner = null;
}
notifyAll();
}
/*
* Tries once to acquire the right to use an EGL surface. Does not block.
*
* @return true if the right to use an EGL surface was acquired.
*/
public synchronized boolean tryAcquireEglSurface(GLThread thread) {
if (mEglOwner == thread || mEglOwner == null) {
mEglOwner = thread;
notifyAll();
return true;
}
return false;
}
public synchronized void releaseEglSurface(GLThread thread) {
if (mEglOwner == thread) {
mEglOwner = null;
}
notifyAll();
}
}
}
interface EGLConfigChooser {
EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
}
abstract class BaseConfigChooser implements EGLConfigChooser {
public BaseConfigChooser(int[] configSpec) {
mConfigSpec = configSpec;
}
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int[] num_config = new int[1];
egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config);
int numConfigs = num_config[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
EGLConfig[] configs = new EGLConfig[numConfigs];
egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config);
EGLConfig config = chooseConfig(egl, display, configs);
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs);
protected int[] mConfigSpec;
public static class ComponentSizeChooser extends BaseConfigChooser {
public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize,
int stencilSize) {
super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE,
blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE,
stencilSize, EGL10.EGL_NONE });
mValue = new int[1];
mRedSize = redSize;
mGreenSize = greenSize;
mBlueSize = blueSize;
mAlphaSize = alphaSize;
mDepthSize = depthSize;
mStencilSize = stencilSize;
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) {
EGLConfig closestConfig = null;
int closestDistance = 1000;
for (EGLConfig config : configs) {
int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
if (d >= mDepthSize && s >= mStencilSize) {
int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize)
+ Math.abs(a - mAlphaSize);
if (distance < closestDistance) {
closestDistance = distance;
closestConfig = config;
}
}
}
return closestConfig;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0];
}
return defaultValue;
}
private int[] mValue;
// Subclasses can adjust these values:
protected int mRedSize;
protected int mGreenSize;
protected int mBlueSize;
protected int mAlphaSize;
protected int mDepthSize;
protected int mStencilSize;
}
/**
* This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer.
*
*/
public static class SimpleEGLConfigChooser extends ComponentSizeChooser {
public SimpleEGLConfigChooser(boolean withDepthBuffer) {
super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0);
// Adjust target values. This way we'll accept a 4444 or
// 555 buffer if there's no 565 buffer available.
mRedSize = 5;
mGreenSize = 6;
mBlueSize = 5;
}
}
}
OpenGLRenderer.java
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.*;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
public class OpenGLRenderer implements GLWallpaperService.Renderer {
public int toss;
public int count;
private GLModel model;
public Context context;
public float angle =0;
public OpenGLRenderer() {
this.context = GLExample.context;
model = new GLModel(this.context);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition
* .khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background color to black ( rgba ).
model.Init(gl);
gl.glEnable(GL10.GL_TEXTURE_2D); //Enable Texture Mapping ( NEW )
gl.glShadeModel(GL10.GL_SMOOTH); //Enable Smooth Shading
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); //Black Background
gl.glClearDepthf(1.0f); //Depth Buffer Setup
gl.glEnable(GL10.GL_DEPTH_TEST); //Enables Depth Testing
gl.glDepthFunc(GL10.GL_LEQUAL); //The Type Of Depth Testing To Do
//Really Nice Perspective Calculations
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.
* khronos.opengles.GL10)
*/
public void onDrawFrame(GL10 gl) {
if (gl == null)
return;
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glPushMatrix();
gl.glScalef(.2f, .2f, .2f);
gl.glTranslatef(0, -1f, -17f);
gl.glRotatef (angle, 0.0f, 1.0f, 0.0f);
gl.glRotatef (90f, 0.0f, 0.0f, 1.0f);
gl.glRotatef(-90f, 0.0f, 0.0f, 1.0f);
gl.glScalef(1.6f, 1.6f, 1.6f);
model.draw(gl, false);
gl.glPopMatrix();
angle = angle + .4f;
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition
* .khronos.opengles.GL10, int, int)
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
// Sets the current view port to the new size.
model.Init(gl);
//model.InitTex();
//square.loadGLTexture(gl, this.context);
//square2.loadGLTexture(gl, this.context);
gl.glViewport(0, 0, width, height);
// Select the projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
// Reset the projection matrix
gl.glLoadIdentity();
// Calculate the aspect ratio of the window
GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
100.0f);
// Select the modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Reset the modelview matrix
gl.glLoadIdentity();
}
}
Settings.java
says its coyprighted
import com.Beck.GLExample.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Settings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
getPreferenceManager().setSharedPreferencesName(
GLExample.SHARED_PREFS_NAME);
addPreferencesFromResource(R.xml.setting_xml);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(
this);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
}
}