diff options
author | penghuang@chromium.org <penghuang@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-06-16 14:20:26 +0000 |
---|---|---|
committer | penghuang@chromium.org <penghuang@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-06-16 14:20:26 +0000 |
commit | c44620b2cb57378a518ee97427e7c3d319507c8d (patch) | |
tree | ccc8f088aab4dc3758fc71de6b9eca133e3637c9 /ppapi/examples | |
parent | d765198b19590e158a609cc34c29af39b6cd9e9d (diff) | |
download | chromium_src-c44620b2cb57378a518ee97427e7c3d319507c8d.zip chromium_src-c44620b2cb57378a518ee97427e7c3d319507c8d.tar.gz chromium_src-c44620b2cb57378a518ee97427e7c3d319507c8d.tar.bz2 |
[PPAPI] Compositor API implementation.
Implement the compositor API which allows a plugin to combine different sources of visual data efficiently, such as PPB_ImageData and OpengGL texture.
API Proposal http://goo.gl/V7xcu3
BUG=374383
Committed: https://src.chromium.org/viewvc/chrome?view=rev&revision=277208
Review URL: https://codereview.chromium.org/298023004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@277422 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'ppapi/examples')
-rw-r--r-- | ppapi/examples/compositor/compositor.cc | 439 | ||||
-rw-r--r-- | ppapi/examples/compositor/compositor.html | 28 | ||||
-rw-r--r-- | ppapi/examples/compositor/spinning_cube.cc | 459 | ||||
-rw-r--r-- | ppapi/examples/compositor/spinning_cube.h | 42 |
4 files changed, 968 insertions, 0 deletions
diff --git a/ppapi/examples/compositor/compositor.cc b/ppapi/examples/compositor/compositor.cc new file mode 100644 index 0000000..d437bc84 --- /dev/null +++ b/ppapi/examples/compositor/compositor.cc @@ -0,0 +1,439 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Needed on Windows to get |M_PI| from math.h. +#ifdef _WIN32 +#define _USE_MATH_DEFINES +#endif + +#include <math.h> + +#include <vector> + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/pp_input_event.h" +#include "ppapi/cpp/compositor.h" +#include "ppapi/cpp/compositor_layer.h" +#include "ppapi/cpp/graphics_3d.h" +#include "ppapi/cpp/graphics_3d_client.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/input_event.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/var_dictionary.h" +#include "ppapi/examples/compositor/spinning_cube.h" +#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h" +#include "ppapi/lib/gl/include/GLES2/gl2.h" +#include "ppapi/lib/gl/include/GLES2/gl2ext.h" +#include "ppapi/utility/completion_callback_factory.h" + +// Use assert as a poor-man's CHECK, even in non-debug mode. +// Since <assert.h> redefines assert on every inclusion (it doesn't use +// include-guards), make sure this is the last file #include'd in this file. +#undef NDEBUG +#include <assert.h> + +// When compiling natively on Windows, PostMessage can be #define-d to +// something else. +#ifdef PostMessage +#undef PostMessage +#endif + +// Assert |context_| isn't holding any GL Errors. Done as a macro instead of a +// function to preserve line number information in the failure message. +#define AssertNoGLError() \ + PP_DCHECK(!glGetError()); + +namespace { + +const int32_t kTextureWidth = 800; +const int32_t kTextureHeight = 800; +const int32_t kImageWidth = 256; +const int32_t kImageHeight = 256; + +class DemoInstance : public pp::Instance, public pp::Graphics3DClient { + public: + DemoInstance(PP_Instance instance); + virtual ~DemoInstance(); + + // pp::Instance implementation (see PPP_Instance). + virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); + virtual void DidChangeView(const pp::Rect& position, + const pp::Rect& clip); + virtual bool HandleInputEvent(const pp::InputEvent& event); + + // pp::Graphics3DClient implementation. + virtual void Graphics3DContextLost(); + + private: + // GL-related functions. + void InitGL(int32_t result); + GLuint PrepareFramebuffer(); + pp::ImageData PrepareImage(); + void Paint(int32_t result, int32_t frame); + void OnTextureReleased(int32_t result, GLuint texture); + void OnImageReleased(int32_t result, const pp::ImageData& image); + + pp::CompletionCallbackFactory<DemoInstance> callback_factory_; + + // Owned data. + pp::Graphics3D* context_; + + GLuint fbo_; + GLuint rbo_; + + std::vector<GLuint> textures_; + std::vector<pp::ImageData> images_; + + pp::Compositor compositor_; + pp::CompositorLayer color_layer_; + pp::CompositorLayer stable_texture_layer_; + pp::CompositorLayer texture_layer_; + pp::CompositorLayer image_layer_; + + bool rebuild_layers_; + int32_t total_resource_; + + SpinningCube* cube_; +}; + +DemoInstance::DemoInstance(PP_Instance instance) + : pp::Instance(instance), + pp::Graphics3DClient(this), + callback_factory_(this), + context_(NULL), + fbo_(0), + rbo_(0), + compositor_(this), + rebuild_layers_(false), + total_resource_(0), + cube_(new SpinningCube()) { + RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); +} + +DemoInstance::~DemoInstance() { + delete cube_; + assert(glTerminatePPAPI()); + delete context_; +} + +bool DemoInstance::Init(uint32_t /*argc*/, + const char* /*argn*/[], + const char* /*argv*/[]) { + return !!glInitializePPAPI(pp::Module::Get()->get_browser_interface()); +} + +void DemoInstance::DidChangeView( + const pp::Rect& position, const pp::Rect& /*clip*/) { + if (position.width() == 0 || position.height() == 0) + return; + // Initialize graphics. + InitGL(0); +} + +bool DemoInstance::HandleInputEvent(const pp::InputEvent& event) { + switch (event.GetType()) { + case PP_INPUTEVENT_TYPE_MOUSEDOWN: + rebuild_layers_ = true; + return true; + default: + break; + } + return false; +} + +void DemoInstance::Graphics3DContextLost() { + fbo_ = 0; + rbo_ = 0; + compositor_.ResetLayers(); + color_layer_ = pp::CompositorLayer(); + stable_texture_layer_ = pp::CompositorLayer(); + texture_layer_ = pp::CompositorLayer(); + image_layer_ = pp::CompositorLayer(); + total_resource_ -= static_cast<int32_t>(textures_.size()); + textures_.clear(); + delete context_; + context_ = NULL; + cube_->OnGLContextLost(); + pp::CompletionCallback cb = callback_factory_.NewCallback( + &DemoInstance::InitGL); + pp::Module::Get()->core()->CallOnMainThread(0, cb, 0); +} + +void DemoInstance::InitGL(int32_t /*result*/) { + if (context_) + return; + int32_t context_attributes[] = { + PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8, + PP_GRAPHICS3DATTRIB_BLUE_SIZE, 8, + PP_GRAPHICS3DATTRIB_GREEN_SIZE, 8, + PP_GRAPHICS3DATTRIB_RED_SIZE, 8, + PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 0, + PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 0, + PP_GRAPHICS3DATTRIB_SAMPLES, 0, + PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0, + PP_GRAPHICS3DATTRIB_WIDTH, 32, + PP_GRAPHICS3DATTRIB_HEIGHT, 32, + PP_GRAPHICS3DATTRIB_NONE, + }; + context_ = new pp::Graphics3D(this, context_attributes); + assert(!context_->is_null()); + assert(BindGraphics(compositor_)); + + glSetCurrentContextPPAPI(context_->pp_resource()); + + cube_->Init(kTextureWidth, kTextureHeight); + + Paint(PP_OK, 0); +} + +GLuint DemoInstance::PrepareFramebuffer() { + GLuint texture = 0; + if (textures_.empty()) { + total_resource_++; + // Create a texture object + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, kTextureWidth, kTextureHeight, 0, + GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindTexture(GL_TEXTURE_2D, 0); + } else { + texture = textures_.back(); + textures_.pop_back(); + } + + if (!rbo_) { + // create a renderbuffer object to store depth info + glGenRenderbuffers(1, &rbo_); + glBindRenderbuffer(GL_RENDERBUFFER, rbo_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, + kTextureWidth, kTextureHeight); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + } + + if (!fbo_) { + // create a framebuffer object + glGenFramebuffers(1, &fbo_); + } + + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + + // attach the texture to FBO color attachment point + glFramebufferTexture2D(GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + texture, + 0); + + // attach the renderbuffer to depth attachment point + glFramebufferRenderbuffer(GL_FRAMEBUFFER, + GL_DEPTH_ATTACHMENT, + GL_RENDERBUFFER, + rbo_); + + // check FBO status + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + assert(status == GL_FRAMEBUFFER_COMPLETE); + + AssertNoGLError(); + return texture; +} + +pp::ImageData DemoInstance::PrepareImage() { + if (images_.empty()) { + total_resource_++; + return pp::ImageData(this, + PP_IMAGEDATAFORMAT_RGBA_PREMUL, + pp::Size(kImageWidth, kImageHeight), + false); + } + pp::ImageData image = images_.back(); + images_.pop_back(); + return image; +} + +void DemoInstance::Paint(int32_t result, int32_t frame) { + assert(result == PP_OK); + + if (result != PP_OK || !context_) + return; + + int32_t rv; + + if (rebuild_layers_) { + compositor_.ResetLayers(); + color_layer_ = pp::CompositorLayer(); + stable_texture_layer_ = pp::CompositorLayer(); + texture_layer_ = pp::CompositorLayer(); + image_layer_ = pp::CompositorLayer(); + frame = 0; + rebuild_layers_ = false; + } + + float factor_sin = sin(M_PI / 180 * frame); + float factor_cos = cos(M_PI / 180 * frame); + { + // Set the background color layer. + if (color_layer_.is_null()) { + color_layer_ = compositor_.AddLayer(); + assert(!color_layer_.is_null()); + static const float transform[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f, + }; + rv = color_layer_.SetTransform(transform); + assert(rv == PP_OK); + } + rv = color_layer_.SetColor(fabs(factor_sin), + fabs(factor_cos), + fabs(factor_sin * factor_cos), + 1.0f, + pp::Size(800, 600)); + assert(rv == PP_OK); + } + + { + // Set the image layer + if (image_layer_.is_null()) { + image_layer_ = compositor_.AddLayer(); + assert(!image_layer_.is_null()); + } + float x = frame % 800; + float y = 200 - 200 * factor_sin; + const float transform[16] = { + fabs(factor_sin) + 0.2f, 0.0f, 0.0f, 0.0f, + 0.0f, fabs(factor_sin) + 0.2f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + x, y, 0.0f, 1.0f, + }; + rv = image_layer_.SetTransform(transform); + assert(rv == PP_OK); + + pp::ImageData image = PrepareImage(); + uint8_t *p = static_cast<uint8_t*>(image.data()); + for (int x = 0; x < kImageWidth; ++x) { + for (int y = 0; y < kImageHeight; ++y) { + *(p++) = frame; + *(p++) = frame * x; + *(p++) = frame * y; + *(p++) = 255; + } + } + rv = image_layer_.SetImage(image, pp::Size(kImageWidth, kImageHeight), + callback_factory_.NewCallback(&DemoInstance::OnImageReleased, image)); + assert(rv == PP_OK_COMPLETIONPENDING); + } + + { + // Set the stable texture layer + if (stable_texture_layer_.is_null()) { + stable_texture_layer_ = compositor_.AddLayer(); + assert(!stable_texture_layer_.is_null()); + GLuint texture = PrepareFramebuffer(); + cube_->UpdateForTimeDelta(0.02f); + cube_->Draw(); + rv = stable_texture_layer_.SetTexture( + *context_, + texture, pp::Size(600, 600), + callback_factory_.NewCallback(&DemoInstance::OnTextureReleased, + texture)); + assert(rv == PP_OK_COMPLETIONPENDING); + rv = stable_texture_layer_.SetPremultipliedAlpha(PP_FALSE); + assert(rv == PP_OK); + } + + int32_t delta = 200 * fabsf(factor_sin); + if (delta != 0) { + int32_t x_y = 25 + delta; + int32_t w_h = 650 - delta - delta; + rv = stable_texture_layer_.SetClipRect(pp::Rect(x_y, x_y, w_h, w_h)); + } else { + rv = stable_texture_layer_.SetClipRect(pp::Rect()); + } + assert(rv == PP_OK); + + const float transform[16] = { + factor_cos, -factor_sin, 0.0f, 0.0f, + factor_sin, factor_cos, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 50.0f, 50.0f, 0.0f, 1.0f, + }; + rv = stable_texture_layer_.SetTransform(transform); + assert(rv == PP_OK); + } + + { + // Set the dynamic texture layer. + if (texture_layer_.is_null()) { + texture_layer_ = compositor_.AddLayer(); + assert(!texture_layer_.is_null()); + static const float transform[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 200.0f, 0.0f, 0.0f, 1.0f, + }; + rv = texture_layer_.SetTransform(transform); + assert(rv == PP_OK); + } + + GLuint texture = PrepareFramebuffer(); + cube_->UpdateForTimeDelta(0.02f); + cube_->Draw(); + rv = texture_layer_.SetTexture(*context_, texture, pp::Size(400, 400), + callback_factory_.NewCallback(&DemoInstance::OnTextureReleased, + texture)); + assert(rv == PP_OK_COMPLETIONPENDING); + rv = texture_layer_.SetPremultipliedAlpha(PP_FALSE); + assert(rv == PP_OK); + } + + rv = compositor_.CommitLayers( + callback_factory_.NewCallback(&DemoInstance::Paint, ++frame)); + assert(rv == PP_OK_COMPLETIONPENDING); + + pp::VarDictionary dict; + dict.Set(pp::Var("total_resource"), pp::Var(total_resource_)); + dict.Set(pp::Var("free_resource"), + pp::Var((int32_t)(textures_.size() + images_.size()))); + PostMessage(dict); +} + +void DemoInstance::OnTextureReleased(int32_t result, GLuint texture) { + if (result == PP_OK) + textures_.push_back(texture); +} + +void DemoInstance::OnImageReleased(int32_t result, const pp::ImageData& image) { + if (result == PP_OK) + images_.push_back(image); +} + +// This object is the global object representing this plugin library as long +// as it is loaded. +class DemoModule : public pp::Module { + public: + DemoModule() : Module() {} + virtual ~DemoModule() {} + + virtual pp::Instance* CreateInstance(PP_Instance instance) { + return new DemoInstance(instance); + } +}; + +} // anonymous namespace + +namespace pp { +// Factory function for your specialization of the Module object. +Module* CreateModule() { + return new DemoModule(); +} +} // namespace pp diff --git a/ppapi/examples/compositor/compositor.html b/ppapi/examples/compositor/compositor.html new file mode 100644 index 0000000..a0dcfbe --- /dev/null +++ b/ppapi/examples/compositor/compositor.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html> + <!-- + Copyright 2014 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. + --> +<head> + <title>GLES2 Spinning Cube Example</title> +</head> + +<body> + +<embed id="plugin" type="application/x-ppapi-example-compositor" + width="800" height="600"/> <br/> + Total resource: <input id="total" > <br/> + Free resource: <input id="free" > <br/> +<script type="text/javascript"> + var plugin = document.getElementById('plugin'); + var total = document.getElementById('total'); + var free = document.getElementById('free'); + plugin.addEventListener('message', function(message) { + total.value = message.data.total_resource; + free.value = message.data.free_resource; + }, false); +</script> +</body> +</html> diff --git a/ppapi/examples/compositor/spinning_cube.cc b/ppapi/examples/compositor/spinning_cube.cc new file mode 100644 index 0000000..2e76699 --- /dev/null +++ b/ppapi/examples/compositor/spinning_cube.cc @@ -0,0 +1,459 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This example program is based on Simple_VertexShader.c from: + +// +// Book: OpenGL(R) ES 2.0 Programming Guide +// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner +// ISBN-10: 0321502795 +// ISBN-13: 9780321502797 +// Publisher: Addison-Wesley Professional +// URLs: http://safari.informit.com/9780321563835 +// http://www.opengles-book.com +// + +#include "ppapi/examples/compositor/spinning_cube.h" + +#include <math.h> +#include <stdlib.h> +#include <string.h> + +#include <algorithm> + +#include "ppapi/lib/gl/include/GLES2/gl2.h" + +namespace { + +const float kPi = 3.14159265359f; + +int GenerateCube(GLuint *vbo_vertices, + GLuint *vbo_indices) { + const int num_indices = 36; + + const GLfloat cube_vertices[] = { + -0.5f, -0.5f, -0.5f, + 0.5f, -0.5f, -0.5f, + 0.5f, -0.5f, 0.5f, + -0.5f, -0.5f, 0.5f, + -0.5f, 0.5f, -0.5f, + 0.5f, 0.5f, -0.5f, + 0.5f, 0.5f, 0.5f, + -0.5f, 0.5f, 0.5f, + }; + + const GLushort cube_indices[] = { + 0, 2, 1, + 0, 3, 2, + 4, 5, 6, + 4, 6, 7, + 3, 6, 2, + 3, 7, 6, + 0, 1, 5, + 0, 5, 4, + 0, 7, 3, + 0, 4, 7, + 1, 2, 6, + 1, 6, 5, + }; + + if (vbo_vertices) { + glGenBuffers(1, vbo_vertices); + glBindBuffer(GL_ARRAY_BUFFER, *vbo_vertices); + glBufferData(GL_ARRAY_BUFFER, + sizeof(cube_vertices), + cube_vertices, + GL_STATIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); + } + + if (vbo_indices) { + glGenBuffers(1, vbo_indices); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *vbo_indices); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, + sizeof(cube_indices), + cube_indices, + GL_STATIC_DRAW); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + return num_indices; +} + +GLuint LoadShader(GLenum type, + const char* shader_source) { + GLuint shader = glCreateShader(type); + glShaderSource(shader, 1, &shader_source, NULL); + glCompileShader(shader); + + GLint compiled = 0; + glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); + + if (!compiled) { + glDeleteShader(shader); + return 0; + } + + return shader; +} + +GLuint LoadProgram(const char* vertext_shader_source, + const char* fragment_shader_source) { + GLuint vertex_shader = LoadShader(GL_VERTEX_SHADER, + vertext_shader_source); + if (!vertex_shader) + return 0; + + GLuint fragment_shader = LoadShader(GL_FRAGMENT_SHADER, + fragment_shader_source); + if (!fragment_shader) { + glDeleteShader(vertex_shader); + return 0; + } + + GLuint program_object = glCreateProgram(); + glAttachShader(program_object, vertex_shader); + glAttachShader(program_object, fragment_shader); + + glLinkProgram(program_object); + + glDeleteShader(vertex_shader); + glDeleteShader(fragment_shader); + + GLint linked = 0; + glGetProgramiv(program_object, GL_LINK_STATUS, &linked); + + if (!linked) { + glDeleteProgram(program_object); + return 0; + } + + return program_object; +} + +class ESMatrix { + public: + GLfloat m[4][4]; + + ESMatrix() { + LoadZero(); + } + + void LoadZero() { + memset(this, 0x0, sizeof(ESMatrix)); + } + + void LoadIdentity() { + LoadZero(); + m[0][0] = 1.0f; + m[1][1] = 1.0f; + m[2][2] = 1.0f; + m[3][3] = 1.0f; + } + + void Multiply(ESMatrix* a, ESMatrix* b) { + ESMatrix result; + for (int i = 0; i < 4; ++i) { + result.m[i][0] = (a->m[i][0] * b->m[0][0]) + + (a->m[i][1] * b->m[1][0]) + + (a->m[i][2] * b->m[2][0]) + + (a->m[i][3] * b->m[3][0]); + + result.m[i][1] = (a->m[i][0] * b->m[0][1]) + + (a->m[i][1] * b->m[1][1]) + + (a->m[i][2] * b->m[2][1]) + + (a->m[i][3] * b->m[3][1]); + + result.m[i][2] = (a->m[i][0] * b->m[0][2]) + + (a->m[i][1] * b->m[1][2]) + + (a->m[i][2] * b->m[2][2]) + + (a->m[i][3] * b->m[3][2]); + + result.m[i][3] = (a->m[i][0] * b->m[0][3]) + + (a->m[i][1] * b->m[1][3]) + + (a->m[i][2] * b->m[2][3]) + + (a->m[i][3] * b->m[3][3]); + } + *this = result; + } + + void Frustum(float left, + float right, + float bottom, + float top, + float near_z, + float far_z) { + float delta_x = right - left; + float delta_y = top - bottom; + float delta_z = far_z - near_z; + + if ((near_z <= 0.0f) || + (far_z <= 0.0f) || + (delta_z <= 0.0f) || + (delta_y <= 0.0f) || + (delta_y <= 0.0f)) + return; + + ESMatrix frust; + frust.m[0][0] = 2.0f * near_z / delta_x; + frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f; + + frust.m[1][1] = 2.0f * near_z / delta_y; + frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f; + + frust.m[2][0] = (right + left) / delta_x; + frust.m[2][1] = (top + bottom) / delta_y; + frust.m[2][2] = -(near_z + far_z) / delta_z; + frust.m[2][3] = -1.0f; + + frust.m[3][2] = -2.0f * near_z * far_z / delta_z; + frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f; + + Multiply(&frust, this); + } + + void Perspective(float fov_y, float aspect, float near_z, float far_z) { + GLfloat frustum_h = tanf(fov_y / 360.0f * kPi) * near_z; + GLfloat frustum_w = frustum_h * aspect; + Frustum(-frustum_w, frustum_w, -frustum_h, frustum_h, near_z, far_z); + } + + void Translate(GLfloat tx, GLfloat ty, GLfloat tz) { + m[3][0] += m[0][0] * tx + m[1][0] * ty + m[2][0] * tz; + m[3][1] += m[0][1] * tx + m[1][1] * ty + m[2][1] * tz; + m[3][2] += m[0][2] * tx + m[1][2] * ty + m[2][2] * tz; + m[3][3] += m[0][3] * tx + m[1][3] * ty + m[2][3] * tz; + } + + void Rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) { + GLfloat mag = sqrtf(x * x + y * y + z * z); + + GLfloat sin_angle = sinf(angle * kPi / 180.0f); + GLfloat cos_angle = cosf(angle * kPi / 180.0f); + if (mag > 0.0f) { + GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs; + GLfloat one_minus_cos; + ESMatrix rotation; + + x /= mag; + y /= mag; + z /= mag; + + xx = x * x; + yy = y * y; + zz = z * z; + xy = x * y; + yz = y * z; + zx = z * x; + xs = x * sin_angle; + ys = y * sin_angle; + zs = z * sin_angle; + one_minus_cos = 1.0f - cos_angle; + + rotation.m[0][0] = (one_minus_cos * xx) + cos_angle; + rotation.m[0][1] = (one_minus_cos * xy) - zs; + rotation.m[0][2] = (one_minus_cos * zx) + ys; + rotation.m[0][3] = 0.0F; + + rotation.m[1][0] = (one_minus_cos * xy) + zs; + rotation.m[1][1] = (one_minus_cos * yy) + cos_angle; + rotation.m[1][2] = (one_minus_cos * yz) - xs; + rotation.m[1][3] = 0.0F; + + rotation.m[2][0] = (one_minus_cos * zx) - ys; + rotation.m[2][1] = (one_minus_cos * yz) + xs; + rotation.m[2][2] = (one_minus_cos * zz) + cos_angle; + rotation.m[2][3] = 0.0F; + + rotation.m[3][0] = 0.0F; + rotation.m[3][1] = 0.0F; + rotation.m[3][2] = 0.0F; + rotation.m[3][3] = 1.0F; + + Multiply(&rotation, this); + } + } +}; + +float RotationForTimeDelta(float delta_time) { + return delta_time * 40.0f; +} + +float RotationForDragDistance(float drag_distance) { + return drag_distance / 5; // Arbitrary damping. +} + +} // namespace + +class SpinningCube::GLState { + public: + GLState(); + + void OnGLContextLost(); + + GLfloat angle_; // Survives losing the GL context. + + GLuint program_object_; + GLint position_location_; + GLint mvp_location_; + GLuint vbo_vertices_; + GLuint vbo_indices_; + int num_indices_; + ESMatrix mvp_matrix_; +}; + +SpinningCube::GLState::GLState() + : angle_(0) { + OnGLContextLost(); +} + +void SpinningCube::GLState::OnGLContextLost() { + program_object_ = 0; + position_location_ = 0; + mvp_location_ = 0; + vbo_vertices_ = 0; + vbo_indices_ = 0; + num_indices_ = 0; +} + +SpinningCube::SpinningCube() + : initialized_(false), + width_(0), + height_(0), + state_(new GLState()), + fling_multiplier_(1.0f), + direction_(1) { + state_->angle_ = 45.0f; +} + +SpinningCube::~SpinningCube() { + if (!initialized_) + return; + if (state_->vbo_vertices_) + glDeleteBuffers(1, &state_->vbo_vertices_); + if (state_->vbo_indices_) + glDeleteBuffers(1, &state_->vbo_indices_); + if (state_->program_object_) + glDeleteProgram(state_->program_object_); + + delete state_; +} + +void SpinningCube::Init(uint32_t width, uint32_t height) { + width_ = width; + height_ = height; + + if (!initialized_) { + initialized_ = true; + const char vertext_shader_source[] = + "uniform mat4 u_mvpMatrix; \n" + "attribute vec4 a_position; \n" + "varying vec4 v_color; \n" + "void main() \n" + "{ \n" + " gl_Position = u_mvpMatrix * a_position; \n" + " v_color = vec4(a_position.x + 0.5, \n" + " a_position.y + 0.5, \n" + " a_position.z + 0.5, \n" + " 0.8); \n" + "} \n"; + + const char fragment_shader_source[] = + "precision mediump float; \n" + "varying vec4 v_color; \n" + "void main() \n" + "{ \n" + " gl_FragColor = v_color; \n" + "} \n"; + + state_->program_object_ = LoadProgram( + vertext_shader_source, fragment_shader_source); + state_->position_location_ = glGetAttribLocation( + state_->program_object_, "a_position"); + state_->mvp_location_ = glGetUniformLocation( + state_->program_object_, "u_mvpMatrix"); + state_->num_indices_ = GenerateCube(&state_->vbo_vertices_, + &state_->vbo_indices_); + + glClearColor(0.0f, 0.0f, 0.0f, 0.2f); + } +} + +void SpinningCube::OnGLContextLost() { + // TODO(yzshen): Is it correct that in this case we don't need to do cleanup + // for program and buffers? + initialized_ = false; + height_ = 0; + width_ = 0; + state_->OnGLContextLost(); +} + +void SpinningCube::SetFlingMultiplier(float drag_distance, + float drag_time) { + fling_multiplier_ = RotationForDragDistance(drag_distance) / + RotationForTimeDelta(drag_time); + +} + +void SpinningCube::UpdateForTimeDelta(float delta_time) { + state_->angle_ += RotationForTimeDelta(delta_time) * fling_multiplier_; + if (state_->angle_ >= 360.0f) + state_->angle_ -= 360.0f; + + // Arbitrary 50-step linear reduction in spin speed. + if (fling_multiplier_ > 1.0f) { + fling_multiplier_ = + std::max(1.0f, fling_multiplier_ - (fling_multiplier_ - 1.0f) / 50); + } + + Update(); +} + +void SpinningCube::UpdateForDragDistance(float distance) { + state_->angle_ += RotationForDragDistance(distance); + if (state_->angle_ >= 360.0f ) + state_->angle_ -= 360.0f; + + Update(); +} + +void SpinningCube::Draw() { + glViewport(0, 0, width_, height_); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glEnable(GL_DEPTH_TEST); + glUseProgram(state_->program_object_); + + glBindBuffer(GL_ARRAY_BUFFER, state_->vbo_vertices_); + glVertexAttribPointer(state_->position_location_, + 3, + GL_FLOAT, + GL_FALSE, 3 * sizeof(GLfloat), + 0); + glEnableVertexAttribArray(state_->position_location_); + + glUniformMatrix4fv(state_->mvp_location_, + 1, + GL_FALSE, + (GLfloat*) &state_->mvp_matrix_.m[0][0]); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, state_->vbo_indices_); + glDrawElements(GL_TRIANGLES, + state_->num_indices_, + GL_UNSIGNED_SHORT, + 0); +} + +void SpinningCube::Update() { + float aspect = static_cast<GLfloat>(width_) / static_cast<GLfloat>(height_); + + ESMatrix perspective; + perspective.LoadIdentity(); + perspective.Perspective(60.0f, aspect, 1.0f, 20.0f ); + + ESMatrix modelview; + modelview.LoadIdentity(); + modelview.Translate(0.0, 0.0, -2.0); + modelview.Rotate(state_->angle_ * direction_, 1.0, 0.0, 1.0); + + state_->mvp_matrix_.Multiply(&modelview, &perspective); +} diff --git a/ppapi/examples/compositor/spinning_cube.h b/ppapi/examples/compositor/spinning_cube.h new file mode 100644 index 0000000..84a302c2 --- /dev/null +++ b/ppapi/examples/compositor/spinning_cube.h @@ -0,0 +1,42 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_ +#define PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_ + +#include "ppapi/c/pp_stdint.h" + +class SpinningCube { + public: + SpinningCube(); + ~SpinningCube(); + + void Init(uint32_t width, uint32_t height); + void set_direction(int direction) { direction_ = direction; } + void SetFlingMultiplier(float drag_distance, float drag_time); + void UpdateForTimeDelta(float delta_time); + void UpdateForDragDistance(float distance); + void Draw(); + + void OnGLContextLost(); + + private: + class GLState; + + // Disallow copy and assign. + SpinningCube(const SpinningCube& other); + SpinningCube& operator=(const SpinningCube& other); + + void Update(); + + bool initialized_; + uint32_t width_; + uint32_t height_; + // Owned ptr. + GLState* state_; + float fling_multiplier_; + int direction_; +}; + +#endif // PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_ |