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