ThreatIndicatorGLRenderer.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package de.tudarmstadt.informatik.hostage.ui.fragment.opengl;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.nio.ByteBuffer;
  5. import java.nio.ByteOrder;
  6. import java.nio.FloatBuffer;
  7. import java.util.Scanner;
  8. import javax.microedition.khronos.egl.EGLConfig;
  9. import javax.microedition.khronos.opengles.GL10;
  10. import android.content.Context;
  11. import android.content.res.AssetManager;
  12. import android.graphics.Bitmap;
  13. import android.graphics.BitmapFactory;
  14. import android.graphics.Color;
  15. import android.opengl.GLES20;
  16. import android.opengl.GLSurfaceView.Renderer;
  17. import android.opengl.GLUtils;
  18. import android.opengl.Matrix;
  19. import android.util.Log;
  20. import de.tudarmstadt.informatik.hostage.R;
  21. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  22. /**
  23. * @author Fabio Arnold
  24. *
  25. * ThreatIndicatorGLRenderer
  26. * This class is responsible for drawing an animation representing the current threat level.
  27. * Use the method setThreatLevel to set the state (0 to 3).
  28. */
  29. public class ThreatIndicatorGLRenderer implements Renderer {
  30. public enum ThreatLevel {
  31. NOT_MONITORING,
  32. NO_THREAT,
  33. PAST_THREAT,
  34. LIVE_THREAT
  35. }
  36. /**
  37. * Set the threat level which should be indicated
  38. * @param threatLevel
  39. */
  40. public static void setThreatLevel(ThreatLevel threatLevel) {
  41. mNextThreatLevel = threatLevel;
  42. }
  43. /**
  44. * Match the background color of the view holding this renderer
  45. * @param color 32 bit integer encoding the color
  46. */
  47. public static void setBackgroundColor(int color) {
  48. mBackgroundColor[0] = (float)Color.red(color) / 255.0f;
  49. mBackgroundColor[1] = (float)Color.green(color) / 255.0f;
  50. mBackgroundColor[2] = (float)Color.blue(color) / 255.0f;
  51. }
  52. private static float[] mBackgroundColor = new float[3];
  53. // OpenGL data
  54. private int mAnimatedProgram;
  55. private int mTexturedProgram;
  56. private float [] mModelview;
  57. private float [] mProjection;
  58. private float [] mMVP;
  59. private AnimatedMesh androidMesh = null;
  60. private AnimatedMesh beeMesh = null;
  61. private int androidTexture;
  62. private int beeTexture;
  63. private int speechBubbleTexture;
  64. private int mQuadVertexBuffer;
  65. private GLFont font = null;
  66. // threat state
  67. private static ThreatLevel mNextThreatLevel = ThreatLevel.NO_THREAT;
  68. private ThreatLevel mCurrentThreatLevel = ThreatLevel.NO_THREAT;
  69. private ThreatLevel mTargetThreatLevel = ThreatLevel.NO_THREAT;
  70. private float mThreatLevelTransition = 1.0f; // 1.0 means transition is complete
  71. private static boolean sPlayGreetingAnimation = true; // greet the first time
  72. private long mStartTimeMillis; // for animation
  73. public ThreatIndicatorGLRenderer() {
  74. mStartTimeMillis = System.currentTimeMillis();
  75. }
  76. /**
  77. * Initialization will be called after GL context is created and is current
  78. */
  79. public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
  80. GLES20.glClearColor(mBackgroundColor[0], mBackgroundColor[1], mBackgroundColor[2], 1.0f);
  81. GLES20.glEnable(GLES20.GL_DEPTH_TEST);
  82. GLES20.glEnable(GLES20.GL_CULL_FACE);
  83. GLES20.glEnable(GLES20.GL_TEXTURE_2D);
  84. AssetManager assets = MainActivity.getInstance().getAssets();
  85. try {
  86. InputStream is = assets.open("meshes/android.amh");
  87. androidMesh = new AnimatedMesh(is);
  88. /* play the greeting animation the first time the gets opened
  89. not each time the threatindicator gets created */
  90. if (sPlayGreetingAnimation) {
  91. androidMesh.startAction("greet", false, false);
  92. sPlayGreetingAnimation = false;
  93. } else if (mCurrentThreatLevel == ThreatLevel.NO_THREAT) { // default state
  94. androidMesh.startAction("happy", true, false); // play NO_THREAT animation
  95. }
  96. } catch (IOException e) {
  97. Log.e("gl", "Couldn't open android mesh");
  98. }
  99. androidTexture = loadTexture("textures/android-tex.png");
  100. try {
  101. InputStream is = assets.open("meshes/bee.amh");
  102. beeMesh = new AnimatedMesh(is);
  103. beeMesh.startAction("bee_armatureAct", true, false);
  104. } catch (IOException e) {
  105. Log.e("gl", "Couldn't open bee mesh");
  106. }
  107. beeTexture = loadTexture("textures/bee-tex.png");
  108. speechBubbleTexture = loadTexture("textures/speech-bubble.png");
  109. int buffers[] = new int[1];
  110. GLES20.glGenBuffers(1, buffers, 0); // buffer names
  111. mQuadVertexBuffer = buffers[0];
  112. font = new GLFont("fonts/laCartoonerie.png", "fonts/laCartoonerie.bin");
  113. mModelview = new float[16];
  114. Matrix.setIdentityM(mModelview, 0);
  115. mProjection = new float[16];
  116. mMVP = new float[16];
  117. // default shader
  118. String vertexSource = "attribute vec3 position; void main() {gl_Position = vec4(position, 1.0);}";
  119. String fragmentSource = "void main() {gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);}";
  120. try {
  121. vertexSource = inputStreamToString(assets.open("shaders/skinned.vert"));
  122. } catch (IOException e) {
  123. e.printStackTrace();
  124. }
  125. try {fragmentSource = inputStreamToString(assets.open("shaders/skinned.frag"));
  126. } catch (IOException e) {
  127. e.printStackTrace();
  128. }
  129. mAnimatedProgram = loadProgram(vertexSource, fragmentSource);
  130. mTexturedProgram = loadProgram(
  131. "uniform vec2 resolution;" // vertex
  132. + "attribute vec2 position;"
  133. + "attribute vec2 texCoord;"
  134. + "varying vec2 vertexTexCoord;"
  135. + "void main() {"
  136. + " vertexTexCoord = texCoord;"
  137. + " gl_Position = vec4(2.0 * (position / resolution) - 1.0, 0.0, 1.0);"
  138. + "}",
  139. "uniform sampler2D colormap;" // fragment
  140. + "uniform vec3 color;"
  141. + "varying vec2 vertexTexCoord;"
  142. + "void main() {"
  143. + " vec4 texel = texture2D(colormap, vertexTexCoord);"
  144. + " gl_FragColor = vec4(color * texel.rgb, texel.a);"
  145. + "}");
  146. }
  147. private void updateAndroidAndBee() {
  148. // threat level state machine
  149. if (mTargetThreatLevel != mCurrentThreatLevel) {
  150. boolean blocked = false; // block until current action is completed
  151. if (mThreatLevelTransition == 0.0f) {
  152. if (androidMesh.isActionDone()) {
  153. switch (mTargetThreatLevel) {
  154. case NOT_MONITORING:
  155. androidMesh.startAction("sleep", false, false);
  156. break;
  157. case NO_THREAT:
  158. androidMesh.startAction("happy", true, false);
  159. break;
  160. case PAST_THREAT:
  161. androidMesh.startAction("fear", true, false);
  162. break;
  163. case LIVE_THREAT:
  164. androidMesh.startAction("panic", true, false);
  165. break;
  166. }
  167. } else blocked = true;
  168. }
  169. if (!blocked) {
  170. mThreatLevelTransition += 0.016f;
  171. if (mThreatLevelTransition >= 1.0f) {
  172. mCurrentThreatLevel = mTargetThreatLevel;
  173. mThreatLevelTransition = 1.0f;
  174. }
  175. }
  176. } else {
  177. if (mNextThreatLevel != mTargetThreatLevel) {
  178. mTargetThreatLevel = mNextThreatLevel;
  179. mThreatLevelTransition = 0.0f;
  180. // HACK!!! reverses the sleep animation to create smooth transition into other states
  181. if (mCurrentThreatLevel == ThreatLevel.NOT_MONITORING)
  182. androidMesh.startAction("sleep", false, true);
  183. }
  184. }
  185. androidMesh.tick(); // animate android
  186. }
  187. private void drawAndroidAndBee(double animTime) {
  188. GLES20.glUseProgram(mAnimatedProgram);
  189. int colorUniformLoc = GLES20.glGetUniformLocation(mAnimatedProgram, "color");
  190. int textureUniformLoc = GLES20.glGetUniformLocation(mAnimatedProgram, "texture");
  191. int mvpUniformLoc = GLES20.glGetUniformLocation(mAnimatedProgram, "mvp");
  192. // animate color
  193. final float[] whiteColor = {1.0f, 1.0f, 1.0f, 1.0f};
  194. final float[] greyColor = {0.5f, 0.5f, 0.5f, 1.0f};
  195. final float[] redColor = {2.0f, 0.4f, 0.2f, 1.0f};
  196. final float[] yellowColor = {1.1f * 255.0f / 166.0f, 1.2f * 255.0f / 200.0f, 0.0f, 1.0f};
  197. float[] currentColor = whiteColor;
  198. float blink = 0.5f + 0.5f * (float)Math.sin(12.0 * animTime);
  199. switch (mCurrentThreatLevel) {
  200. case NOT_MONITORING:
  201. currentColor = greyColor;
  202. break;
  203. case PAST_THREAT:
  204. currentColor = mixColor(blink, whiteColor, yellowColor);
  205. break;
  206. case LIVE_THREAT:
  207. currentColor = mixColor(blink, whiteColor, redColor);
  208. break;
  209. }
  210. if (mTargetThreatLevel != mCurrentThreatLevel) {
  211. float[] targetColor = whiteColor;
  212. switch (mTargetThreatLevel) {
  213. case NOT_MONITORING:
  214. targetColor = greyColor;
  215. break;
  216. case PAST_THREAT:
  217. targetColor = mixColor(blink, whiteColor, yellowColor);
  218. break;
  219. case LIVE_THREAT:
  220. targetColor = mixColor(blink, whiteColor, redColor);
  221. break;
  222. }
  223. currentColor = mixColor(mThreatLevelTransition, currentColor, targetColor);
  224. }
  225. GLES20.glUniform4fv(colorUniformLoc, 1, currentColor, 0);
  226. GLES20.glUniform1i(textureUniformLoc, 0);
  227. // animate camera
  228. Matrix.setIdentityM(mModelview, 0);
  229. if (mCurrentThreatLevel == ThreatLevel.LIVE_THREAT || mTargetThreatLevel == ThreatLevel.LIVE_THREAT) {
  230. float delta = 1.0f;
  231. if (mThreatLevelTransition < 0.4f) { // animate only during the first 40% of the transition
  232. delta = mThreatLevelTransition / 0.4f;
  233. delta = -2.0f * delta * delta * delta + 3.0f * delta * delta; // ease in/out
  234. }
  235. if (mTargetThreatLevel != ThreatLevel.LIVE_THREAT)
  236. delta = 1.0f - delta;
  237. Matrix.translateM(mModelview, 0, 0.0f, -0.6f - 0.2f * delta, -1.6f - 0.4f * delta); // 0.0f, -0.8f, -2.0f
  238. Matrix.rotateM(mModelview, 0, -85.0f + 5.0f * delta, 1.0f, 0.0f, 0.0f); // -80.0f
  239. } else {
  240. Matrix.translateM(mModelview, 0, 0.0f, -0.6f, -1.6f);
  241. Matrix.rotateM(mModelview, 0, -85.0f, 1.0f, 0.0f, 0.0f);
  242. }
  243. Matrix.multiplyMM(mMVP, 0, mProjection, 0, mModelview, 0);
  244. GLES20.glUniformMatrix4fv(mvpUniformLoc, 1, false, mMVP, 0);
  245. GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, androidTexture);
  246. androidMesh.draw(mAnimatedProgram);
  247. // restore color
  248. GLES20.glUniform4fv(colorUniformLoc, 1, whiteColor, 0);
  249. if (mCurrentThreatLevel == ThreatLevel.LIVE_THREAT || mTargetThreatLevel == ThreatLevel.LIVE_THREAT) {
  250. // draw a bee rotating around the android
  251. float fadeIn = mThreatLevelTransition;
  252. if (mTargetThreatLevel != ThreatLevel.LIVE_THREAT) fadeIn = 1.0f - fadeIn; // fade out
  253. float beePositionZ = 2.0f * (1.0f - fadeIn) * (1.0f - fadeIn); // animate the bee going in/out
  254. final float beeSize = 0.2f;
  255. Matrix.rotateM(mModelview, 0, (float)((-240.0 * animTime) % 360.0), 0.0f, 0.0f, 1.0f); // rotate around android
  256. Matrix.translateM(mModelview, 0, 0.6f, 0.0f, 0.7f + 0.1f * (float)Math.sin(12.0 * animTime) + beePositionZ); // go up and down
  257. Matrix.rotateM(mModelview, 0, 20.0f * (float)Math.cos(12.0 * animTime), 1.0f, 0.0f, 0.0f); // rock back and forth
  258. Matrix.scaleM(mModelview, 0, beeSize, beeSize, beeSize);
  259. Matrix.multiplyMM(mMVP, 0, mProjection, 0, mModelview, 0);
  260. GLES20.glUniformMatrix4fv(mvpUniformLoc, 1, false, mMVP, 0);
  261. GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, beeTexture);
  262. beeMesh.tick();
  263. beeMesh.draw(mAnimatedProgram);
  264. }
  265. }
  266. /**
  267. * Tries to render at 30 Hz (see bottom part)
  268. */
  269. public void onDrawFrame(GL10 arg0) {
  270. Context ctx = MainActivity.getInstance();
  271. long timeMillis = System.currentTimeMillis() - mStartTimeMillis;
  272. double animTime = 0.001 * (double)timeMillis; // in seconds
  273. // OpenGL drawing
  274. GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
  275. updateAndroidAndBee();
  276. drawAndroidAndBee(animTime);
  277. GLES20.glDisable(GLES20.GL_DEPTH_TEST);
  278. GLES20.glEnable(GLES20.GL_BLEND);
  279. GLES20.glDisable(GLES20.GL_CULL_FACE);
  280. GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
  281. GLES20.glUseProgram(mTexturedProgram);
  282. int resolutionUniformLoc = GLES20.glGetUniformLocation(mTexturedProgram, "resolution");
  283. int textureUniformLoc = GLES20.glGetUniformLocation(mTexturedProgram, "colormap");
  284. int colorUniformLoc = GLES20.glGetUniformLocation(mTexturedProgram, "color");
  285. GLES20.glUniform2f(resolutionUniformLoc, 1024.0f, 1024.0f);
  286. GLES20.glUniform1i(textureUniformLoc, 0);
  287. GLES20.glUniform3f(colorUniformLoc, 1.0f, 1.0f, 1.0f);
  288. String message = "???";
  289. switch (mNextThreatLevel) {
  290. case NOT_MONITORING:
  291. message = ctx.getString(R.string.honeypot_not_monitoring);
  292. break;
  293. case NO_THREAT:
  294. message = ctx.getString(R.string.honeypot_no_threat);
  295. break;
  296. case PAST_THREAT:
  297. message = ctx.getString(R.string.honeypot_past_threat);
  298. break;
  299. case LIVE_THREAT:
  300. message = ctx.getString(R.string.honeypot_live_threat);
  301. break;
  302. }
  303. float textWidth = font.getTextWidth(message);
  304. float textHeight = 40.0f;
  305. float bubbleSize = textWidth + 100.0f;
  306. float y = 0.75f * 1024.0f + 32.0f * (float)Math.sin(2.0*animTime);
  307. float x = 0.5f * 1024.0f + 16.0f * (float)Math.cos(1.0*animTime);
  308. drawTexturedQuad(speechBubbleTexture, x - 0.5f*bubbleSize, y - 0.25f*bubbleSize, bubbleSize, 0.5f*bubbleSize);
  309. GLES20.glUniform3f(colorUniformLoc, 0.0f, 0.0f, 0.0f);
  310. font.drawText(mTexturedProgram, message, x - 0.5f*textWidth,
  311. y - 0.5f*textHeight);
  312. GLES20.glUseProgram(0);
  313. GLES20.glEnable(GLES20.GL_DEPTH_TEST);
  314. GLES20.glDisable(GLES20.GL_BLEND);
  315. long deltaTime = System.currentTimeMillis() - mStartTimeMillis - timeMillis; // time for one frame
  316. if (deltaTime < 33) {
  317. try {
  318. Thread.sleep(33 - deltaTime); // sleep remaining time for 30 Hz
  319. } catch (InterruptedException e) {
  320. e.printStackTrace();
  321. }
  322. }
  323. }
  324. /**
  325. * Informs renderer of changed surface dimensions
  326. */
  327. public void onSurfaceChanged(GL10 arg0, int w, int h) {
  328. int width = w;
  329. int height = h;
  330. float aspectRatio = (float) w / (float) h;
  331. //Matrix.orthoM(mProjection, 0, -aspectRatio, aspectRatio, -1.0f, 1.0f, -1.0f, 1.0f);
  332. float near = 0.1f;
  333. float fov = 2.0f;
  334. Matrix.frustumM(mProjection, 0, near * -aspectRatio, near * aspectRatio, -near, near, fov * near, 100.0f);
  335. GLES20.glViewport(0, 0, width, height);
  336. }
  337. // some helper functions
  338. private void drawTexturedQuad(int texture, float x, float y, float w, float h) {
  339. int vertexCount = 4;
  340. int vertexSize = (2+2)*4; // size in bytes
  341. FloatBuffer buffer = ByteBuffer.allocateDirect(vertexCount * vertexSize).order(ByteOrder.nativeOrder()).asFloatBuffer();
  342. buffer.put(x); buffer.put(y);
  343. buffer.put(0.0f); buffer.put(0.0f);
  344. buffer.put(x+w); buffer.put(y);
  345. buffer.put(1.0f); buffer.put(0.0f);
  346. buffer.put(x); buffer.put(y+h);
  347. buffer.put(0.0f); buffer.put(1.0f);
  348. buffer.put(x+w); buffer.put(y+h);
  349. buffer.put(1.0f); buffer.put(1.0f);
  350. buffer.position(0); // rewind
  351. GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
  352. GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, mQuadVertexBuffer);
  353. GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, vertexSize * vertexCount, buffer, GLES20.GL_STREAM_DRAW);
  354. int positionIndex = GLES20.glGetAttribLocation(mTexturedProgram, "position");
  355. int texCoordIndex = GLES20.glGetAttribLocation(mTexturedProgram, "texCoord");
  356. GLES20.glEnableVertexAttribArray(positionIndex);
  357. GLES20.glEnableVertexAttribArray(texCoordIndex);
  358. GLES20.glVertexAttribPointer(positionIndex, 2, GLES20.GL_FLOAT, false, vertexSize, 0);
  359. GLES20.glVertexAttribPointer(texCoordIndex, 2, GLES20.GL_FLOAT, false, vertexSize, 8);
  360. GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, vertexCount);
  361. GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
  362. GLES20.glDisableVertexAttribArray(positionIndex);
  363. GLES20.glDisableVertexAttribArray(texCoordIndex);
  364. }
  365. private float[] mixColor(float alpha, float[] color1, float[] color2) {
  366. float[] color3 = new float[4];
  367. color3[0] = (1.0f - alpha) * color1[0] + alpha * color2[0];
  368. color3[1] = (1.0f - alpha) * color1[1] + alpha * color2[1];
  369. color3[2] = (1.0f - alpha) * color1[2] + alpha * color2[2];
  370. color3[3] = (1.0f - alpha) * color1[3] + alpha * color2[3];
  371. return color3;
  372. }
  373. public static int loadTexture(String filePath) {
  374. AssetManager assets = MainActivity.getInstance().getAssets();
  375. Bitmap bitmap;
  376. try {
  377. bitmap = BitmapFactory.decodeStream(assets.open(filePath));
  378. } catch (IOException e) {
  379. e.printStackTrace();
  380. return 0;
  381. }
  382. int[] names = {0};
  383. GLES20.glGenTextures(1, names, 0);
  384. int tex = names[0];
  385. GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex);
  386. GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
  387. GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
  388. GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
  389. bitmap.recycle(); // memory is now gpu -> free it
  390. GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex);
  391. return tex;
  392. }
  393. // see http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
  394. private static String inputStreamToString(InputStream is) {
  395. Scanner scanner = new Scanner(is);
  396. Scanner s = scanner.useDelimiter("\\A");
  397. String result = s.hasNext() ? s.next() : "";
  398. scanner.close();
  399. return result;
  400. }
  401. private static int loadShader(int type, String source) {
  402. int shader = GLES20.glCreateShader(type);
  403. GLES20.glShaderSource(shader, source);
  404. GLES20.glCompileShader(shader);
  405. Log.i("gl", GLES20.glGetShaderInfoLog(shader));
  406. return shader;
  407. }
  408. private static int loadProgram(String vertexSource, String fragmentSource) {
  409. int program = GLES20.glCreateProgram();
  410. GLES20.glAttachShader(program, loadShader(GLES20.GL_VERTEX_SHADER, vertexSource));
  411. GLES20.glAttachShader(program, loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource));
  412. GLES20.glLinkProgram(program);
  413. return program;
  414. }
  415. }