spinning_cube.cc revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This example program is based on Simple_VertexShader.c from:
6
7//
8// Book:      OpenGL(R) ES 2.0 Programming Guide
9// Authors:   Aaftab Munshi, Dan Ginsburg, Dave Shreiner
10// ISBN-10:   0321502795
11// ISBN-13:   9780321502797
12// Publisher: Addison-Wesley Professional
13// URLs:      http://safari.informit.com/9780321563835
14//            http://www.opengles-book.com
15//
16
17#include "mojo/examples/sample_app/spinning_cube.h"
18
19#include <math.h>
20#include <stdlib.h>
21#include <string.h>
22#include "gpu/command_buffer/client/gles2_interface.h"
23
24namespace mojo {
25namespace examples {
26
27namespace {
28
29const float kPi = 3.14159265359f;
30
31int GenerateCube(gpu::gles2::GLES2Interface* gl,
32                 GLuint *vbo_vertices,
33                 GLuint *vbo_indices) {
34  const int num_indices = 36;
35
36  const GLfloat cube_vertices[] = {
37    -0.5f, -0.5f, -0.5f,
38    -0.5f, -0.5f,  0.5f,
39    0.5f, -0.5f,  0.5f,
40    0.5f, -0.5f, -0.5f,
41    -0.5f,  0.5f, -0.5f,
42    -0.5f,  0.5f,  0.5f,
43    0.5f,  0.5f,  0.5f,
44    0.5f,  0.5f, -0.5f,
45    -0.5f, -0.5f, -0.5f,
46    -0.5f,  0.5f, -0.5f,
47    0.5f,  0.5f, -0.5f,
48    0.5f, -0.5f, -0.5f,
49    -0.5f, -0.5f, 0.5f,
50    -0.5f,  0.5f, 0.5f,
51    0.5f,  0.5f, 0.5f,
52    0.5f, -0.5f, 0.5f,
53    -0.5f, -0.5f, -0.5f,
54    -0.5f, -0.5f,  0.5f,
55    -0.5f,  0.5f,  0.5f,
56    -0.5f,  0.5f, -0.5f,
57    0.5f, -0.5f, -0.5f,
58    0.5f, -0.5f,  0.5f,
59    0.5f,  0.5f,  0.5f,
60    0.5f,  0.5f, -0.5f,
61  };
62
63  const GLushort cube_indices[] = {
64    0, 2, 1,
65    0, 3, 2,
66    4, 5, 6,
67    4, 6, 7,
68    8, 9, 10,
69    8, 10, 11,
70    12, 15, 14,
71    12, 14, 13,
72    16, 17, 18,
73    16, 18, 19,
74    20, 23, 22,
75    20, 22, 21
76  };
77
78  if (vbo_vertices) {
79    gl->GenBuffers(1, vbo_vertices);
80    gl->BindBuffer(GL_ARRAY_BUFFER, *vbo_vertices);
81    gl->BufferData(
82      GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
83    gl->BindBuffer(GL_ARRAY_BUFFER, 0);
84  }
85
86  if (vbo_indices) {
87    gl->GenBuffers(1, vbo_indices);
88    gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, *vbo_indices);
89    gl->BufferData(GL_ELEMENT_ARRAY_BUFFER,
90                   sizeof(cube_indices),
91                   cube_indices,
92                   GL_STATIC_DRAW);
93    gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
94  }
95
96  return num_indices;
97}
98
99GLuint LoadShader(gpu::gles2::GLES2Interface* gl,
100                  GLenum type,
101                  const char* shader_source) {
102  GLuint shader = gl->CreateShader(type);
103  gl->ShaderSource(shader, 1, &shader_source, NULL);
104  gl->CompileShader(shader);
105
106  GLint compiled = 0;
107  gl->GetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
108
109  if (!compiled) {
110    gl->DeleteShader(shader);
111    return 0;
112  }
113
114  return shader;
115}
116
117GLuint LoadProgram(gpu::gles2::GLES2Interface* gl,
118                   const char* vertext_shader_source,
119                   const char* fragment_shader_source) {
120  GLuint vertex_shader = LoadShader(gl,
121                                    GL_VERTEX_SHADER,
122                                    vertext_shader_source);
123  if (!vertex_shader)
124    return 0;
125
126  GLuint fragment_shader = LoadShader(gl,
127                                      GL_FRAGMENT_SHADER,
128                                      fragment_shader_source);
129  if (!fragment_shader) {
130    gl->DeleteShader(vertex_shader);
131    return 0;
132  }
133
134  GLuint program_object = gl->CreateProgram();
135  gl->AttachShader(program_object, vertex_shader);
136  gl->AttachShader(program_object, fragment_shader);
137
138  gl->LinkProgram(program_object);
139
140  gl->DeleteShader(vertex_shader);
141  gl->DeleteShader(fragment_shader);
142
143  GLint linked = 0;
144  gl->GetProgramiv(program_object, GL_LINK_STATUS, &linked);
145
146  if (!linked) {
147    gl->DeleteProgram(program_object);
148    return 0;
149  }
150
151  return program_object;
152}
153
154class ESMatrix {
155 public:
156  GLfloat m[4][4];
157
158  ESMatrix() {
159    LoadZero();
160  }
161
162  void LoadZero() {
163    memset(this, 0x0, sizeof(ESMatrix));
164  }
165
166  void LoadIdentity() {
167    LoadZero();
168    m[0][0] = 1.0f;
169    m[1][1] = 1.0f;
170    m[2][2] = 1.0f;
171    m[3][3] = 1.0f;
172  }
173
174  void Multiply(ESMatrix* a, ESMatrix* b) {
175    ESMatrix result;
176    for (int i = 0; i < 4; ++i) {
177      result.m[i][0] = (a->m[i][0] * b->m[0][0]) +
178                       (a->m[i][1] * b->m[1][0]) +
179                       (a->m[i][2] * b->m[2][0]) +
180                       (a->m[i][3] * b->m[3][0]);
181
182      result.m[i][1] = (a->m[i][0] * b->m[0][1]) +
183                       (a->m[i][1] * b->m[1][1]) +
184                       (a->m[i][2] * b->m[2][1]) +
185                       (a->m[i][3] * b->m[3][1]);
186
187      result.m[i][2] = (a->m[i][0] * b->m[0][2]) +
188                       (a->m[i][1] * b->m[1][2]) +
189                       (a->m[i][2] * b->m[2][2]) +
190                       (a->m[i][3] * b->m[3][2]);
191
192      result.m[i][3] = (a->m[i][0] * b->m[0][3]) +
193                       (a->m[i][1] * b->m[1][3]) +
194                       (a->m[i][2] * b->m[2][3]) +
195                       (a->m[i][3] * b->m[3][3]);
196    }
197    *this = result;
198  }
199
200  void Frustum(float left,
201               float right,
202               float bottom,
203               float top,
204               float near_z,
205               float far_z) {
206    float delta_x = right - left;
207    float delta_y = top - bottom;
208    float delta_z = far_z - near_z;
209
210    if ((near_z <= 0.0f) ||
211        (far_z <= 0.0f) ||
212        (delta_z <= 0.0f) ||
213        (delta_y <= 0.0f) ||
214        (delta_y <= 0.0f))
215      return;
216
217    ESMatrix frust;
218    frust.m[0][0] = 2.0f * near_z / delta_x;
219    frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f;
220
221    frust.m[1][1] = 2.0f * near_z / delta_y;
222    frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f;
223
224    frust.m[2][0] = (right + left) / delta_x;
225    frust.m[2][1] = (top + bottom) / delta_y;
226    frust.m[2][2] = -(near_z + far_z) / delta_z;
227    frust.m[2][3] = -1.0f;
228
229    frust.m[3][2] = -2.0f * near_z * far_z / delta_z;
230    frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f;
231
232    Multiply(&frust, this);
233  }
234
235  void Perspective(float fov_y, float aspect, float near_z, float far_z) {
236    GLfloat frustum_h = tanf(fov_y / 360.0f * kPi) * near_z;
237    GLfloat frustum_w = frustum_h * aspect;
238    Frustum(-frustum_w, frustum_w, -frustum_h, frustum_h, near_z, far_z);
239  }
240
241  void Translate(GLfloat tx, GLfloat ty, GLfloat tz) {
242    m[3][0] += m[0][0] * tx + m[1][0] * ty + m[2][0] * tz;
243    m[3][1] += m[0][1] * tx + m[1][1] * ty + m[2][1] * tz;
244    m[3][2] += m[0][2] * tx + m[1][2] * ty + m[2][2] * tz;
245    m[3][3] += m[0][3] * tx + m[1][3] * ty + m[2][3] * tz;
246  }
247
248  void Rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) {
249    GLfloat mag = sqrtf(x * x + y * y + z * z);
250
251    GLfloat sin_angle = sinf(angle * kPi / 180.0f);
252    GLfloat cos_angle = cosf(angle * kPi / 180.0f);
253    if (mag > 0.0f) {
254      GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs;
255      GLfloat one_minus_cos;
256      ESMatrix rotation;
257
258      x /= mag;
259      y /= mag;
260      z /= mag;
261
262      xx = x * x;
263      yy = y * y;
264      zz = z * z;
265      xy = x * y;
266      yz = y * z;
267      zx = z * x;
268      xs = x * sin_angle;
269      ys = y * sin_angle;
270      zs = z * sin_angle;
271      one_minus_cos = 1.0f - cos_angle;
272
273      rotation.m[0][0] = (one_minus_cos * xx) + cos_angle;
274      rotation.m[0][1] = (one_minus_cos * xy) - zs;
275      rotation.m[0][2] = (one_minus_cos * zx) + ys;
276      rotation.m[0][3] = 0.0F;
277
278      rotation.m[1][0] = (one_minus_cos * xy) + zs;
279      rotation.m[1][1] = (one_minus_cos * yy) + cos_angle;
280      rotation.m[1][2] = (one_minus_cos * yz) - xs;
281      rotation.m[1][3] = 0.0F;
282
283      rotation.m[2][0] = (one_minus_cos * zx) - ys;
284      rotation.m[2][1] = (one_minus_cos * yz) + xs;
285      rotation.m[2][2] = (one_minus_cos * zz) + cos_angle;
286      rotation.m[2][3] = 0.0F;
287
288      rotation.m[3][0] = 0.0F;
289      rotation.m[3][1] = 0.0F;
290      rotation.m[3][2] = 0.0F;
291      rotation.m[3][3] = 1.0F;
292
293      Multiply(&rotation, this);
294    }
295  }
296};
297
298}
299
300class SpinningCube::GLState {
301 public:
302  GLState();
303
304  void OnGLContextLost();
305
306  GLfloat angle_;  // Survives losing the GL context.
307
308  GLuint program_object_;
309  GLint position_location_;
310  GLint mvp_location_;
311  GLuint vbo_vertices_;
312  GLuint vbo_indices_;
313  int num_indices_;
314  ESMatrix mvp_matrix_;
315};
316
317SpinningCube::GLState::GLState()
318    : angle_(0) {
319  OnGLContextLost();
320}
321
322void SpinningCube::GLState::OnGLContextLost() {
323  program_object_ = 0;
324  position_location_ = 0;
325  mvp_location_ = 0;
326  vbo_vertices_ = 0;
327  vbo_indices_ = 0;
328  num_indices_ = 0;
329}
330
331SpinningCube::SpinningCube()
332    : gl_(NULL),
333      state_(new GLState()) {
334  state_->angle_ = 45.0f;
335}
336
337SpinningCube::~SpinningCube() {
338  if (!gl_)
339    return;
340  if (state_->vbo_vertices_)
341    gl_->DeleteBuffers(1, &state_->vbo_vertices_);
342  if (state_->vbo_indices_)
343    gl_->DeleteBuffers(1, &state_->vbo_indices_);
344  if (state_->program_object_)
345    gl_->DeleteProgram(state_->program_object_);
346}
347
348void SpinningCube::BindTo(gpu::gles2::GLES2Interface* gl,
349                          int width,
350                          int height) {
351  gl_ = gl;
352  width_ = width;
353  height_ = height;
354
355  const char vertext_shader_source[] =
356      "uniform mat4 u_mvpMatrix;                   \n"
357      "attribute vec4 a_position;                  \n"
358      "void main()                                 \n"
359      "{                                           \n"
360      "   gl_Position = u_mvpMatrix * a_position;  \n"
361      "}                                           \n";
362
363  const char fragment_shader_source[] =
364      "precision mediump float;                            \n"
365      "void main()                                         \n"
366      "{                                                   \n"
367      "  gl_FragColor = vec4( 0.0, 1.0, 0.0, 1.0 );        \n"
368      "}                                                   \n";
369
370  state_->program_object_ = LoadProgram(
371      gl_, vertext_shader_source, fragment_shader_source);
372  state_->position_location_ = gl_->GetAttribLocation(
373      state_->program_object_, "a_position");
374  state_->mvp_location_ = gl_->GetUniformLocation(
375      state_->program_object_, "u_mvpMatrix");
376  state_->num_indices_ = GenerateCube(
377      gl_, &state_->vbo_vertices_, &state_->vbo_indices_);
378
379  gl_->ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
380}
381
382void SpinningCube::OnGLContextLost() {
383  gl_ = NULL;
384  state_->OnGLContextLost();
385}
386
387void SpinningCube::Update(float delta_time) {
388  state_->angle_ += ( delta_time * 40.0f );
389  if (state_->angle_ >= 360.0f )
390    state_->angle_ -= 360.0f;
391
392  float aspect = static_cast<GLfloat>(width_) / static_cast<GLfloat>(height_);
393
394  ESMatrix perspective;
395  perspective.LoadIdentity();
396  perspective.Perspective(60.0f, aspect, 1.0f, 20.0f );
397
398  ESMatrix modelview;
399  modelview.LoadIdentity();
400  modelview.Translate(0.0, 0.0, -2.0);
401  modelview.Rotate(state_->angle_, 1.0, 0.0, 1.0);
402
403  state_->mvp_matrix_.Multiply(&modelview, &perspective);
404}
405
406void SpinningCube::Draw() {
407  gl_->Viewport(0, 0, width_, height_);
408  gl_->Clear(GL_COLOR_BUFFER_BIT);
409  gl_->UseProgram(state_->program_object_);
410  gl_->BindBuffer(GL_ARRAY_BUFFER, state_->vbo_vertices_);
411  gl_->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, state_->vbo_indices_);
412  gl_->VertexAttribPointer(state_->position_location_,
413                           3,
414                           GL_FLOAT,
415                           GL_FALSE, 3 * sizeof(GLfloat),
416                           0);
417  gl_->EnableVertexAttribArray(state_->position_location_);
418  gl_->UniformMatrix4fv(state_->mvp_location_,
419                        1,
420                        GL_FALSE,
421                        (GLfloat*) &state_->mvp_matrix_.m[0][0]);
422  gl_->DrawElements(GL_TRIANGLES,
423                    state_->num_indices_,
424                    GL_UNSIGNED_SHORT,
425                    0);
426  gl_->SwapBuffers();
427}
428
429}  // namespace examples
430}  // namespace mojo
431