]> Pileus Git - ~andy/spades/blob - src/org/pileus/spades/Cards.java
Remove some debug messages
[~andy/spades] / src / org / pileus / spades / Cards.java
1 package org.pileus.spades;
2
3 import java.util.Map;
4 import java.util.HashMap;
5
6 import java.nio.ByteBuffer;
7 import java.nio.ByteOrder;
8 import java.nio.FloatBuffer;
9
10 import javax.microedition.khronos.egl.EGLConfig;
11 import javax.microedition.khronos.opengles.GL10;
12
13 import android.content.Context;
14 import android.content.res.Resources;
15 import android.graphics.Bitmap;
16 import android.graphics.BitmapFactory;
17 import android.opengl.GLES20;
18 import android.opengl.GLSurfaceView;
19 import android.opengl.GLUtils;
20 import android.opengl.Matrix;
21 import android.view.MotionEvent;
22
23 public class Cards extends GLSurfaceView implements GLSurfaceView.Renderer
24 {
25         /* Shader data */
26         private final String vertSource
27                 = "uniform   mat4 u_model;"
28                 + "uniform   mat4 u_view;"
29                 + "uniform   mat4 u_proj;"
30                 + "attribute vec4 a_position;"
31                 + "attribute vec2 a_mapping;"
32                 + "varying   vec2 v_mapping;"
33                 + "void main() {"
34                 + "  gl_Position = u_proj"
35                 + "              * u_view"
36                 + "              * u_model"
37                 + "              * a_position;"
38                 + "  v_mapping   = a_mapping;"
39                 + "}";
40
41         private final String fragSource
42                 = "precision mediump   float;"
43                 + "uniform   sampler2D u_texture;"
44                 + "uniform   vec4      u_color;"
45                 + "varying   vec2      v_mapping;"
46                 + "void main() {"
47                 + "  gl_FragColor = texture2D("
48                 + "    u_texture, v_mapping);"
49                 + "}";
50
51         /* Drawing data */
52         private final float  faceCoords[] = {
53                 -0.063f,  0.088f, 0.05f, // Standard poker size:
54                 -0.063f, -0.088f, 0.05f, //   2.5in x 3.5in
55                  0.063f, -0.088f, 0.05f, //   63mm  x 88mm
56                  0.063f,  0.088f, 0.05f, //
57         };
58
59         private final float  backCoords[] = {
60                  0.063f,  0.088f, 0.05f, // Standard poker size:
61                  0.063f, -0.088f, 0.05f, //   2.5in x 3.5in
62                 -0.063f, -0.088f, 0.05f, //   63mm  x 88mm
63                 -0.063f,  0.088f, 0.05f, //
64         };
65
66         private final float  tableCoords[] = {
67                 -0.75f,  0.75f, 0,
68                 -0.75f, -0.75f, 0,
69                  0.75f, -0.75f, 0,
70                  0.75f,  0.75f, 0,
71         };
72
73         private final float  mapCoords[] = {
74                 0.0f, 0.0f,
75                 0.0f, 1.0f,
76                 1.0f, 1.0f,
77                 1.0f, 0.0f,
78         };
79
80         private final float  color[] = {
81                 1, 0, 0, 1
82         };
83
84         /* Cards data */
85         private final String cards[] = {
86                 "As", "Ks", "Qs", "Js", "10s", "9s", "8s", "7s", "6s", "5s", "4s", "3s", "2s",
87                 "Ah", "Kh", "Qh", "Jh", "10h", "9h", "8h", "7h", "6h", "5h", "4h", "3h", "2h",
88                 "Ac", "Kc", "Qc", "Jc", "10c", "9c", "8c", "7c", "6c", "5c", "4c", "3c", "2c",
89                 "Ad", "Kd", "Qd", "Jd", "10d", "9d", "8d", "7d", "6d", "5d", "4d", "3d", "2d",
90         };
91
92         /* Private data */
93         private Resources    res;         // app resources
94         private int          program;     // opengl program
95
96         private float[]      model;       // model matrix
97         private float[]      view;        // view matrix
98         private float[]      proj;        // projection matrix
99
100         private FloatBuffer  faceBuf;     // vertex positions for front of card
101         private FloatBuffer  backBuf;     // vertex positions for back of card
102         private FloatBuffer  tableBuf;    // vertex positions for table
103         private FloatBuffer  mapBuf;      // texture mapping coord buffer
104
105         private int          modelHandle; // model matrix
106         private int          viewHandle;  // view matrix
107         private int          projHandle;  // projection matrix
108         private int          vertHandle;  // vertex positions
109         private int          mapHandle;   // texture mapping coords
110         private int          texHandle;   // texture data
111         private int          colorHandle; // color data
112
113         private int[]        face;        // card face textures
114         private int          red;         // red card back
115         private int          blue;        // blue card back
116         private int          table;       // table top texture
117
118         private boolean      drag;        // currently in drag event
119         private int          pick;        // currently picked card
120         private float        xpos;        // x drag position (0=left   - 1-right)
121         private float        ypos;        // y drag position (0=bottom - 1-top)
122         private float        ylim;        // y limit for a play
123
124         private Map<String,Integer> index; // card name to index map
125
126         /* Properties */
127         public String[]      hand;        // cards to display
128         public String[]      pile;        // played cards to display
129
130         /* GLSurfaceView Methods */
131         public Cards(Context context)
132         {
133                 super(context);
134                 Os.debug("Cards: create");
135
136                 this.res   = context.getResources();
137
138                 this.model = new float[4*4];
139                 this.view  = new float[4*4];
140                 this.proj  = new float[4*4];
141
142                 this.face  = new int[52];
143
144                 this.ylim  = 0.4f;
145
146                 this.hand  = new String[] {
147                         "As", "7s", "6s",  "6h", "2h", "Ac",
148                         "Kc", "3c", "10d", "9d", "8d", "7d", "2d"
149                 };
150
151                 this.pile  = new String[] {
152                         "As", "7s", "6s"
153                 };
154
155                 this.index = new HashMap<String,Integer>(52);
156                 for (int i = 0; i < 52; i++)
157                         this.index.put(this.cards[i], i);
158
159                 this.setEGLContextClientVersion(2);
160                 this.setRenderer(this);
161                 this.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
162         }
163
164         /* Renderer methods */
165         @Override
166         public void onSurfaceCreated(GL10 unused, EGLConfig config)
167         {
168                 Os.debug("Cards: onSurfaceCreate");
169
170                 /* Initialize shaders */
171                 int vertShader = this.loadShader(GLES20.GL_VERTEX_SHADER,   vertSource);
172                 int fragShader = this.loadShader(GLES20.GL_FRAGMENT_SHADER, fragSource);
173
174                 /* Link shaders into an OpenGL program */
175                 this.program = GLES20.glCreateProgram();
176                 GLES20.glAttachShader(program, vertShader);
177                 GLES20.glAttachShader(program, fragShader);
178                 GLES20.glLinkProgram(program);
179
180                 /* Get shaders attributes */
181                 this.modelHandle = GLES20.glGetUniformLocation(program, "u_model");
182                 this.viewHandle  = GLES20.glGetUniformLocation(program, "u_view");
183                 this.projHandle  = GLES20.glGetUniformLocation(program, "u_proj");
184                 this.vertHandle  = GLES20.glGetAttribLocation(program, "a_position");
185                 this.mapHandle   = GLES20.glGetAttribLocation(program, "a_mapping");
186                 this.texHandle   = GLES20.glGetUniformLocation(program, "u_texture");
187                 this.colorHandle = GLES20.glGetUniformLocation(program, "u_color");
188
189                 /* Create vertex array  */
190                 this.faceBuf  = this.loadBuffer(this.faceCoords);
191                 this.backBuf  = this.loadBuffer(this.backCoords);
192                 this.tableBuf = this.loadBuffer(this.tableCoords);
193                 this.mapBuf   = this.loadBuffer(this.mapCoords);
194
195                 /* Load textures */
196                 for (int i = 0; i < 52; i++) {
197                         String name = "card_" + this.cards[i].toLowerCase();
198                         this.face[i] = this.loadTexture(name);
199                 }
200                 this.red   = this.loadTexture("card_red");
201                 this.blue  = this.loadTexture("card_blue");
202                 this.table = this.loadTexture("table");
203
204                 /* Debug */
205                 Os.debug("Cards: onSurfaceCreate");
206         }
207
208         @Override
209         public void onDrawFrame(GL10 unused)
210         {
211                 //Os.debug("Cards: onDrawFrame");
212
213                 /* Turn on the program */
214                 GLES20.glUseProgram(program);
215
216                 /* Reset view */
217                 GLES20.glClearColor(0, 0, 0, 1);
218                 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
219
220                 /* Setup projection matricies */
221                 GLES20.glUniformMatrix4fv(this.viewHandle, 1, false, this.view, 0);
222                 GLES20.glUniformMatrix4fv(this.projHandle, 1, false, this.proj, 0);
223
224                 /* Setup buffers objects */
225                 GLES20.glEnableVertexAttribArray(this.vertHandle);
226                 GLES20.glEnableVertexAttribArray(this.mapHandle);
227
228                 /* Setup texturing */
229                 GLES20.glEnable(GLES20.GL_CULL_FACE);
230                 GLES20.glEnable(GLES20.GL_BLEND);
231                 GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);
232                 GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
233                 GLES20.glUniform1i(this.texHandle, 0);
234
235                 /* Draw objects */
236                 this.drawTable();
237                 this.drawPile();
238                 this.drawHand();
239                 this.drawPick();
240         }
241
242         @Override
243         public void onSurfaceChanged(GL10 unused, int width, int height)
244         {
245                 Os.debug("Cards: onSurfaceChanged");
246
247                 GLES20.glViewport(0, 0, width, height);
248
249                 Matrix.setIdentityM(this.model, 0);
250                 Matrix.setIdentityM(this.view, 0);
251                 Matrix.setIdentityM(this.proj, 0);
252
253                 // Setup camera
254                 float xang = 0.5f;
255                 float yang = xang * ((float)height / (float)width);
256
257                 Matrix.frustumM(this.proj, 0,
258                                 -1E-6f * xang, // left
259                                 1E-6f  * xang, // right
260                                 -1E-6f * yang, // bottom
261                                 1E-6f  * yang, // top
262                                 1E-6f,         // near
263                                 10f);          // far
264
265                 Matrix.rotateM(this.view, 0, 10f, 1, 0, 0);
266                 Matrix.translateM(this.view, 0, 0, 0, -1.5f);
267                 Matrix.rotateM(this.view, 0, -45f, 1, 0, 0);
268         }
269
270         @Override
271         public boolean onTouchEvent(MotionEvent event)
272         {
273                 boolean up = event.getActionMasked() == MotionEvent.ACTION_UP;
274
275                 float x =    event.getX() / this.getWidth();
276                 float y = 1-(event.getY() / this.getHeight());
277
278                 this.ypos = y;
279                 if (y < this.ylim) {
280                         int num = this.hand.length;
281                         this.xpos = x;
282                         this.pick = (int)Math.floor((x*num));
283                         if (this.pick <    0) this.pick = 0;
284                         if (this.pick >= num) this.pick = num-1;
285                 }
286                 if (y < this.ylim && !this.drag) {
287                         //Os.debug("Cards: onTouchEvent - starting drag");
288                         this.drag = true;
289                 }
290                 if (this.drag) {
291                         //Os.debug("Cards: onTouchEvent - move " + x + "," + y);
292                         this.requestRender();
293                 }
294                 if (y >= this.ylim && this.drag && up) {
295                         //Os.debug("Cards: onTouchEvent - playing card");
296                 }
297                 if (up) {
298                         //Os.debug("Cards: onTouchEvent - ending drag");
299                         this.drag = false;
300                 }
301                 return true;
302         }
303
304         /* Private loading methods */
305         private int loadShader(int type, String code)
306         {
307                 Os.debug("Cards: loadShader");
308
309                 int shader = GLES20.glCreateShader(type);
310                 GLES20.glShaderSource(shader, code);
311                 GLES20.glCompileShader(shader);
312                 return shader;
313         }
314
315         private int loadTexture(String name)
316         {
317                 //Os.debug("Cards: loadTexture - " + name);
318
319                 final int[] tex = new int[1];
320
321                 /* Lookup the resource ID */
322                 int id = 0;
323                 try {
324                         id = R.drawable.class.getField(name).getInt(null);
325                 } catch(Exception e) {
326                         Os.debug("Cards: lookup failed for '" + name + "'", e);
327                         return 0;
328                 }
329
330                 /* Load the bitmap */
331                 Bitmap bitmap = BitmapFactory.decodeResource(this.res, id);
332
333                 /* Copy into OpenGL */
334                 GLES20.glGenTextures(1, tex, 0);
335                 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex[0]);
336                 GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
337                 GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
338                 GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
339
340                 return tex[0];
341         }
342
343         private FloatBuffer loadBuffer(float[] data)
344         {
345                 ByteBuffer bytes = ByteBuffer.allocateDirect(data.length * 4);
346                 bytes.order(ByteOrder.nativeOrder());
347
348                 FloatBuffer buf = bytes.asFloatBuffer();
349                 buf.put(data);
350                 buf.position(0);
351
352                 return buf;
353         }
354
355         /* Private drawing methods */
356         private void drawTable()
357         {
358                 /* Setup view */
359                 Matrix.setIdentityM(this.model, 0);
360                 GLES20.glUniformMatrix4fv(this.modelHandle, 1, false, this.model, 0);
361
362                 /* Draw table */
363                 GLES20.glVertexAttribPointer(this.vertHandle, 3, GLES20.GL_FLOAT, false, 3*4, this.tableBuf);
364                 GLES20.glVertexAttribPointer(this.mapHandle,  2, GLES20.GL_FLOAT, false, 2*4, this.mapBuf);
365                 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, this.table);
366                 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4);
367         }
368
369         private void drawPile()
370         {
371                 /* Draw played cards */
372                 for (int i = 0; i < 4; i++) {
373                         if (i >= this.pile.length || this.pile[i] == null)
374                                 continue;
375
376                         float ang = i * 90f;
377
378                         Matrix.setIdentityM(this.model, 0);
379
380                         Matrix.rotateM(this.model, 0, -ang, 0f, 0f, 1f);
381                         Matrix.translateM(this.model, 0, -0.30f, 0f, 0f);
382                         Matrix.rotateM(this.model, 0,  ang, 0f, 0f, 1f);
383                         Matrix.scaleM(this.model, 0, 3f, 3f, 0f);
384
385                         this.drawCard(this.pile[i]);
386                 }
387         }
388
389         private void drawHand()
390         {
391                 /* Draw hand */
392                 int num = this.hand.length;
393                 for (int i = 0; i < num; i++) {
394                         if (this.drag && this.ypos >= this.ylim && i == this.pick)
395                                 continue;
396
397                         Matrix.setIdentityM(this.model, 0);
398
399                         Matrix.rotateM(this.model, 0, 45f, 1f, 0f, 0f);
400                         Matrix.translateM(this.model, 0, 0f, -0.3f, 1.20f);
401
402                         if (this.drag) {
403                                 float pct = (float)(i+0.5) / num;
404                                 float err = this.xpos - pct;
405                                 float y   = (float)this.ypos / this.ylim;
406                                 float lim = Math.min(Math.max(y,0),1);
407                                 float fcn = 0.1f
408                                         * (float)Math.exp(-10*num*Math.pow(y*err,2))
409                                         * (1f-(float)Math.pow(1-lim, 2));
410                                 Matrix.translateM(this.model, 0, 0, fcn, 0);
411                         }
412
413                         float left  = -20f + 20f*(1f/num);
414                         float right =  54f - 54f*(1f/num);
415                         float ang   = left + i*(right-left)/num;
416                         Matrix.rotateM(this.model, 0, ang, 0f, 0f, -1f);
417                         Matrix.translateM(this.model, 0, 0f, 0.15f, 0f);
418
419                         this.drawCard(this.hand[i]);
420                 }
421         }
422
423         private void drawPick()
424         {
425                 /* Draw selected card */
426                 if (this.drag && this.ypos >= this.ylim) {
427                         Matrix.setIdentityM(this.model, 0);
428                         Matrix.rotateM(this.model, 0, 45f, 1f, 0f, 0f);
429                         Matrix.translateM(this.model, 0, 0f, 0f, 1.20f);
430                         this.drawCard(this.hand[this.pick]);
431                 }
432         }
433
434         private void drawCard(String name)
435         {
436                 int idx   = this.index.get(name);
437                 int front = this.face[idx];
438                 int back  = this.red;
439
440                 /* Set model matrix */
441                 GLES20.glUniformMatrix4fv(this.modelHandle, 1, false, this.model, 0);
442
443                 /* Draw front */
444                 GLES20.glVertexAttribPointer(this.vertHandle, 3, GLES20.GL_FLOAT, false, 3*4, this.faceBuf);
445                 GLES20.glVertexAttribPointer(this.mapHandle,  2, GLES20.GL_FLOAT, false, 2*4, this.mapBuf);
446                 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, front);
447                 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4);
448
449                 /* Draw back */
450                 GLES20.glVertexAttribPointer(this.vertHandle, 3, GLES20.GL_FLOAT, false, 3*4, this.backBuf);
451                 GLES20.glVertexAttribPointer(this.mapHandle,  2, GLES20.GL_FLOAT, false, 2*4, this.mapBuf);
452                 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, back);
453                 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4);
454         }
455 }