summaryrefslogtreecommitdiffstats
path: root/src/com/android/nfc/FireflyRenderer.java
blob: 40c931d14402e0a55bd1302c801494b02eba8926 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.android.nfc;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.opengl.GLUtils;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.egl.EGL10;
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.GL10;

public class FireflyRenderer {
    private static final String LOG_TAG = "NfcFireflyThread";

    static final int NUM_FIREFLIES = 200;

    static final float NEAR_CLIPPING_PLANE = 50f;
    static final float FAR_CLIPPING_PLANE = 100f;

    // All final variables below only need to be allocated once
    // and can be reused between subsequent Beams
    static final int[] sEglConfig = {
        EGL10.EGL_RED_SIZE, 8,
        EGL10.EGL_GREEN_SIZE, 8,
        EGL10.EGL_BLUE_SIZE, 8,
        EGL10.EGL_ALPHA_SIZE, 0,
        EGL10.EGL_DEPTH_SIZE, 0,
        EGL10.EGL_STENCIL_SIZE, 0,
        EGL10.EGL_NONE
    };

    // Vertices for drawing a 32x32 rect
    static final float mVertices[] = {
        0.0f,  0.0f, 0.0f,  // 0, Top Left
        0.0f,  32.0f, 0.0f, // 1, Bottom Left
        32.0f, 32.0f, 0.0f, // 2, Bottom Right
        32.0f, 0.0f, 0.0f,  // 3, Top Right
    };

    // Mapping coordinates for the texture
    static final float mTextCoords[] = {
        0.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 1.0f,
        0.0f, 1.0f
    };

    // Connecting order (draws a square)
    static final short[] mIndices = { 0, 1, 2, 0, 2, 3 };

    final Context mContext;

    // Buffer holding the vertices
    final FloatBuffer mVertexBuffer;

    // Buffer holding the indices
    final ShortBuffer mIndexBuffer;

    // Buffer holding the texture mapping coordinates
    final FloatBuffer mTextureBuffer;

    final Firefly[] mFireflies;

    FireflyRenderThread mFireflyRenderThread;

    // The surface to render the flies on, including width and height
    SurfaceTexture mSurface;
    int mDisplayWidth;
    int mDisplayHeight;

    public FireflyRenderer(Context context) {
        mContext = context;

        // First, build the vertex, texture and index buffers
        ByteBuffer vbb = ByteBuffer.allocateDirect(mVertices.length * 4); // Float => 4 bytes
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asFloatBuffer();
        mVertexBuffer.put(mVertices);
        mVertexBuffer.position(0);

        ByteBuffer ibb = ByteBuffer.allocateDirect(mIndices.length * 2); // Short => 2 bytes
        ibb.order(ByteOrder.nativeOrder());
        mIndexBuffer = ibb.asShortBuffer();
        mIndexBuffer.put(mIndices);
        mIndexBuffer.position(0);

        ByteBuffer tbb = ByteBuffer.allocateDirect(mTextCoords.length * 4);
        tbb.order(ByteOrder.nativeOrder());
        mTextureBuffer = tbb.asFloatBuffer();
        mTextureBuffer.put(mTextCoords);
        mTextureBuffer.position(0);

        mFireflies = new Firefly[NUM_FIREFLIES];
        for (int i = 0; i < NUM_FIREFLIES; i++) {
            mFireflies[i] = new Firefly();
        }
    }

    /**
     * Starts rendering fireflies on the given surface.
     * Must be called from the UI-thread.
     */
    public void start(SurfaceTexture surface, int width, int height) {
        mSurface = surface;
        mDisplayWidth = width;
        mDisplayHeight = height;

        mFireflyRenderThread = new FireflyRenderThread();
        mFireflyRenderThread.start();
    }

    /**
     * Stops rendering fireflies.
     * Must be called from the UI-thread.
     */
    public void stop() {
        if (mFireflyRenderThread != null) {
            mFireflyRenderThread.finish();
            try {
                mFireflyRenderThread.join();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, "Couldn't wait for FireflyRenderThread.");
            }
            mFireflyRenderThread = null;
        }
    }

    private class FireflyRenderThread extends Thread {
        EGL10 mEgl;
        EGLDisplay mEglDisplay;
        EGLConfig mEglConfig;
        EGLContext mEglContext;
        EGLSurface mEglSurface;
        GL10 mGL;

        // Holding the handle to the texture
        int mTextureId;

        // Read/written by multiple threads
        volatile boolean mFinished;

        @Override
        public void run() {
            if (!initGL()) {
                Log.e(LOG_TAG, "Failed to initialize OpenGL.");
                return;
            }
            loadStarTexture();

            mGL.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

            mGL.glViewport(0, 0, mDisplayWidth, mDisplayHeight);

            // make adjustments for screen ratio
            mGL.glMatrixMode(GL10.GL_PROJECTION);
            mGL.glLoadIdentity();
            mGL.glFrustumf(-mDisplayWidth, mDisplayWidth, mDisplayHeight, -mDisplayHeight, NEAR_CLIPPING_PLANE, FAR_CLIPPING_PLANE);

            // Switch back to modelview
            mGL.glMatrixMode(GL10.GL_MODELVIEW);
            mGL.glLoadIdentity();

            mGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
            mGL.glDepthMask(true);


            for (Firefly firefly : mFireflies) {
                firefly.reset();
            }

            for (int i = 0; i < 3; i++) {
                // Call eglSwapBuffers 3 times - this will allocate the necessary
                // buffers, and make sure the animation looks smooth from the start.
                mGL.glClear(GL10.GL_COLOR_BUFFER_BIT);
                if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                    Log.e(LOG_TAG, "Could not swap buffers");
                    mFinished = true;
                }
            }

            long startTime = System.currentTimeMillis();

            while (!mFinished) {
                long timeElapsedMs = System.currentTimeMillis() - startTime;
                startTime = System.currentTimeMillis();

                checkCurrent();

                mGL.glClear(GL10.GL_COLOR_BUFFER_BIT);
                mGL.glLoadIdentity();

                mGL.glEnable(GL10.GL_TEXTURE_2D);
                mGL.glEnable(GL10.GL_BLEND);
                mGL.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);

                for (Firefly firefly : mFireflies) {
                    firefly.updatePositionAndScale(timeElapsedMs);
                    firefly.draw(mGL);
                }

                if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                    Log.e(LOG_TAG, "Could not swap buffers");
                    mFinished = true;
                }

                long elapsed = System.currentTimeMillis() - startTime;
                try {
                    Thread.sleep(Math.max(30 - elapsed, 0));
                } catch (InterruptedException e) {

                }
            }
            finishGL();
        }

        public void finish() {
            mFinished = true;
        }

        void loadStarTexture() {
            int[] textureIds = new int[1];
            mGL.glGenTextures(1, textureIds, 0);
            mTextureId = textureIds[0];

            InputStream in = null;
            try {
                // Remember that both texture dimensions must be a power of 2!
                in = mContext.getAssets().open("star.png");

                Bitmap bitmap = BitmapFactory.decodeStream(in);
                mGL.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);

                mGL.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
                mGL.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

                GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

                bitmap.recycle();

            } catch (IOException e) {
                Log.e(LOG_TAG, "IOException opening assets.");
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) { }
                }
            }
        }

        private void checkCurrent() {
            if (!mEglContext.equals(mEgl.eglGetCurrentContext()) ||
                    !mEglSurface.equals(mEgl.eglGetCurrentSurface(EGL10.EGL_DRAW))) {
                if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
                    throw new RuntimeException("eglMakeCurrent failed "
                            + GLUtils.getEGLErrorString(mEgl.eglGetError()));
                }
            }
        }

        boolean initGL() {
            // Initialize openGL engine
            mEgl = (EGL10) EGLContext.getEGL();

            mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
            if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
                Log.e(LOG_TAG, "eglGetDisplay failed " +
                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
                return false;
            }

            int[] version = new int[2];
            if (!mEgl.eglInitialize(mEglDisplay, version)) {
                Log.e(LOG_TAG, "eglInitialize failed " +
                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
                return false;
            }

            mEglConfig = chooseEglConfig();
            if (mEglConfig == null) {
                Log.e(LOG_TAG, "eglConfig not initialized.");
                return false;
            }

            mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null);

            mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, mSurface, null);

            if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
                int error = mEgl.eglGetError();
                Log.e(LOG_TAG,"createWindowSurface returned error " + Integer.toString(error));
                return false;
            }

            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
                Log.e(LOG_TAG, "eglMakeCurrent failed " +
                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
                return false;
            }

            mGL = (GL10) mEglContext.getGL();

            return true;
        }

        private void finishGL() {
            if (mEgl == null || mEglDisplay == null) {
                // Nothing to free
                return;
            }
            // Unbind the current surface and context from the display
            mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE,
                    EGL10.EGL_NO_CONTEXT);

            if (mEglSurface != null) {
                mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
            }

            if (mEglContext != null) {
                mEgl.eglDestroyContext(mEglDisplay, mEglContext);
            }
        }

        private EGLConfig chooseEglConfig() {
            int[] configsCount = new int[1];
            EGLConfig[] configs = new EGLConfig[1];
            if (!mEgl.eglChooseConfig(mEglDisplay, sEglConfig, configs, 1, configsCount)) {
                throw new IllegalArgumentException("eglChooseConfig failed " +
                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
            } else if (configsCount[0] > 0) {
                return configs[0];
            }
            return null;
        }
    }

    private class Firefly {
        static final float TEXTURE_HEIGHT = 30f; // TODO use measurement of texture size
        static final float SPEED = .5f;

        float mX; // between -mDisplayHeight and mDisplayHeight
        float mY; // between -mDisplayWidth and mDisplayWidth
        float mZ; // between 0.0 (near) and 1.0 (far)
        float mZ0;
        float mT;
        float mScale;
        float mAlpha;

        public Firefly() {
        }

        void reset() {
            mX = (float) (Math.random() * mDisplayWidth) * 4 - 2 * mDisplayWidth;
            mY = (float) (Math.random() * mDisplayHeight) * 4 - 2 * mDisplayHeight;
            mZ0 = mZ = (float) (Math.random()) * 2 - 1;
            mT = 0f;
            mScale = 1.5f;
            mAlpha = 0f;
        }

        public void updatePositionAndScale(long timeElapsedMs) {
               mT += timeElapsedMs;
               mZ = mZ0 + mT/1000f * SPEED;
               mAlpha = 1f-mZ;
               if(mZ > 1.0) reset();
        }

        public void draw(GL10 gl) {
            gl.glLoadIdentity();

            // Counter clockwise winding
            gl.glFrontFace(GL10.GL_CCW);

            gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
            gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

            gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
            gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);

            gl.glTranslatef(mX, mY, -NEAR_CLIPPING_PLANE-mZ*(FAR_CLIPPING_PLANE-NEAR_CLIPPING_PLANE));
            gl.glColor4f(1, 1, 1, mAlpha);

            // scale around center
            gl.glTranslatef(TEXTURE_HEIGHT/2, TEXTURE_HEIGHT/2, 0);
            gl.glScalef(mScale, mScale, 0);
            gl.glTranslatef(-TEXTURE_HEIGHT/2, -TEXTURE_HEIGHT/2, 0);

            gl.glDrawElements(GL10.GL_TRIANGLES, mIndices.length, GL10.GL_UNSIGNED_SHORT,
                    mIndexBuffer);

            gl.glColor4f(1, 1, 1, 1);
            gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
            gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        }
    }
}