diff options
author | binji@chromium.org <binji@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-06-12 21:58:35 +0000 |
---|---|---|
committer | binji@chromium.org <binji@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-06-12 21:58:35 +0000 |
commit | 22df770ad3608dce56c0a422f2af04f7788f4fde (patch) | |
tree | 5e8c7ff75033f576939f192836a2ca5cab32d88d | |
parent | fd082c6d2e122587e06acd13034f8cd28d1a1ec1 (diff) | |
download | chromium_src-22df770ad3608dce56c0a422f2af04f7788f4fde.zip chromium_src-22df770ad3608dce56c0a422f2af04f7788f4fde.tar.gz chromium_src-22df770ad3608dce56c0a422f2af04f7788f4fde.tar.bz2 |
[NaCl SDK] Remove unused examples.
BUG=none
R=sbc@chromium.org
Review URL: https://codereview.chromium.org/16629009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@205948 0039d316-1c4b-4281-b951-d872f2087c98
42 files changed, 0 insertions, 3839 deletions
diff --git a/native_client_sdk/src/examples/common/check_browser.js b/native_client_sdk/src/examples/common/check_browser.js deleted file mode 100644 index 0c54ba4..0000000 --- a/native_client_sdk/src/examples/common/check_browser.js +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2012 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. - */ - -/** - * @fileoverview This file provides a BrowserChecker Javascript class. - * Users can create a BrowserChecker object, invoke checkBrowser(|version|), - * and then use getIsValidBrowser() and getBrowserSupportStatus() - * to determine if the browser version is greater than |version| - * and if the Native Client plugin is found. - */ - -// Create a namespace object -var browser_version = browser_version || {}; - -/** - * Class to provide checking for version and NativeClient. - * @param {integer} arg1 An argument that indicates major version of Chrome we - * require, such as 14. - */ - -/** - * Constructor for the BrowserChecker. Sets the major version of - * Chrome that is required to |minChromeVersion|. - * @param minChromeVersion The earliest major version of chrome that - * is supported. If the Chrome browser version is less than - * |minChromeVersion| then |isValidBrowswer| will be set to false. - * @param opt_maxChromeVersion Ignored. Retained for backwards compatibility. - * @param appVersion The application version string. - * @param plugins The plugins that exist in the browser. - * @constructor - */ -browser_version.BrowserChecker = function(minChromeVersion, - appVersion, plugins, - opt_maxChromeVersion) { - /** - * Version specified by the user. This class looks to see if the browser - * version is >= |minChromeVersion_|. - * @type {integer} - * @private - */ - this.minChromeVersion_ = minChromeVersion; - - /** - * List of Browser plugin objects. - * @type {Ojbect array} - * @private - */ - this.plugins_ = plugins; - - /** - * Application version string from the Browser. - * @type {integer} - * @private - */ - this.appVersion_ = appVersion; - - /** - * Flag used to indicate if the browser has Native Client and is if the - * browser version is recent enough. - * @type {boolean} - * @private - */ - this.isValidBrowser_ = false; - - /** - * Actual major version of Chrome -- found by querying the browser. - * @type {integer} - * @private - */ - this.chromeVersion_ = null; - - /** - * Browser support status. This allows the user to get a detailed status - * rather than using this.browserSupportMessage. - */ - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.UNKNOWN; -} - -/** - * The values used for BrowserChecker status to indicate success or - * a specific error. - * @enum {id} - */ -browser_version.BrowserChecker.StatusValues = { - UNKNOWN: 0, - NACL_ENABLED: 1, - UNKNOWN_BROWSER: 2, - CHROME_VERSION_TOO_OLD: 3, - NACL_NOT_ENABLED: 4, - NOT_USING_SERVER: 5 -}; - -/** - * Determines if the plugin with name |name| exists in the browser. - * @param {string} name The name of the plugin. - * @param {Object array} plugins The plugins in this browser. - * @return {bool} |true| if the plugin is found. - */ -browser_version.BrowserChecker.prototype.pluginExists = function(name, - plugins) { - for (var index=0; index < plugins.length; index++) { - var plugin = this.plugins_[index]; - var plugin_name = plugin['name']; - // If the plugin is not found, you can use the Javascript console - // to see the names of the plugins that were found when debugging. - if (plugin_name.indexOf(name) != -1) { - return true; - } - } - return false; -} - -/** - * Returns browserSupportStatus_ which indicates if the browser supports - * Native Client. Values are defined as literals in - * browser_version.BrowserChecker.StatusValues. - * @ return {int} Level of NaCl support. - */ -browser_version.BrowserChecker.prototype.getBrowserSupportStatus = function() { - return this.browserSupportStatus_; -} - -/** - * Returns isValidBrowser (true/false) to indicate if the browser supports - * Native Client. - * @ return {bool} If this browser has NativeClient and correct version. - */ -browser_version.BrowserChecker.prototype.getIsValidBrowser = function() { - return this.isValidBrowser_; -} - -/** - * Checks to see if this browser can support Native Client applications. - * For Chrome browsers, checks to see if the "Native Client" plugin is - * enabled. - */ -browser_version.BrowserChecker.prototype.checkBrowser = function() { - var versionPatt = /Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/; - var result = this.appVersion_.match(versionPatt); - - // |result| stores the Chrome version number. - if (!result) { - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.UNKNOWN_BROWSER; - } else { - this.chromeVersion_ = result[1]; - // We know we have Chrome, check version and/or plugin named Native Client - if (this.chromeVersion_ >= this.minChromeVersion_) { - var found_nacl = this.pluginExists('Native Client', this.plugins_); - if (found_nacl) { - this.isValidBrowser_ = true; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.NACL_ENABLED; - } else { - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.NACL_NOT_ENABLED; - } - } else { - // We are in a version that is less than |minChromeVersion_| - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.CHROME_VERSION_TOO_OLD; - } - } - var my_protocol = window.location.protocol; - if (my_protocol.indexOf('file') == 0) { - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.NOT_USING_SERVER; - } -} - diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/bind.js b/native_client_sdk/src/examples/fullscreen_tumbler/bind.js deleted file mode 100644 index b04e964..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/bind.js +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2012 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. - -/** - * @fileoverview This class implements an extension to Function object that - * lets you bind a scope for |this| to a function. - */ - -/** - * Bind a scope to a function. Used to bind an object to |this| for event - * handlers. - * @param {!Object} scope The scope in which the function executes. |scope| - * becomes |this| during function execution. - * @return {function} the bound version of the original function. - */ -Function.prototype.bind = function(scope) { - var boundContext = this; - return function() { - return boundContext.apply(scope, arguments); - } -} diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/callback.h b/native_client_sdk/src/examples/fullscreen_tumbler/callback.h deleted file mode 100644 index 781f759..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/callback.h +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_CALLBACK_H_ -#define EXAMPLES_TUMBLER_CALLBACK_H_ - -#include <map> -#include <string> -#include <vector> - -namespace tumbler { - -class ScriptingBridge; - -// Templates used to support method call-backs when a method or property is -// accessed from the browser code. - -// Class suite used to publish a method name to Javascript. Typical use is -// like this: -// photo::MethodCallback<Calculator>* calculate_callback_; -// calculate_callback_ = -// new scripting::MethodCallback<Calculator>(this, -// &Calculator::Calculate); -// bridge->AddMethodNamed("calculate", calculate_callback_); -// ... -// delete calculate_callback_; -// -// The caller must delete the callback. - -// Methods get parameters as a dictionary that maps parameter names to values. -typedef std::map<std::string, std::string> MethodParameter; - -// Pure virtual class used in STL containers. -class MethodCallbackExecutor { - public: - virtual ~MethodCallbackExecutor() {} - virtual void Execute(const ScriptingBridge& bridge, - const MethodParameter& parameters) = 0; -}; - -template <class T> class MethodCallback : public MethodCallbackExecutor { - public: - typedef void(T::* Method)(const ScriptingBridge& bridge, - const MethodParameter& parameters); - - MethodCallback(T* instance, Method method) - : instance_(instance), method_(method) {} - virtual ~MethodCallback() {} - virtual void Execute(const ScriptingBridge& bridge, - const MethodParameter& parameters) { - // Use "this->" to force C++ to look inside our templatized base class; see - // Effective C++, 3rd Ed, item 43, p210 for details. - ((this->instance_)->*(this->method_))(bridge, parameters); - } - - private: - T* instance_; - Method method_; -}; - -template <class T> class ConstMethodCallback : public MethodCallbackExecutor { - public: - typedef void(T::* ConstMethod)(const ScriptingBridge& bridge, - const MethodParameter& parameters) const; - - ConstMethodCallback(const T* instance, ConstMethod method) - : instance_(instance), const_method_(method) {} - virtual ~ConstMethodCallback() {} - virtual void Execute(const ScriptingBridge& bridge, - const MethodParameter& parameters) { - // Use "this->" to force C++ to look inside our templatized base class; see - // Effective C++, 3rd Ed, item 43, p210 for details. - ((this->instance_)->*(this->const_method_))(bridge, parameters); - } - - private: - const T* instance_; - ConstMethod const_method_; -}; - -} // namespace tumbler - -#endif // EXAMPLES_TUMBLER_CALLBACK_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/check_browser.js b/native_client_sdk/src/examples/fullscreen_tumbler/check_browser.js deleted file mode 100644 index 0c54ba4..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/check_browser.js +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2012 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. - */ - -/** - * @fileoverview This file provides a BrowserChecker Javascript class. - * Users can create a BrowserChecker object, invoke checkBrowser(|version|), - * and then use getIsValidBrowser() and getBrowserSupportStatus() - * to determine if the browser version is greater than |version| - * and if the Native Client plugin is found. - */ - -// Create a namespace object -var browser_version = browser_version || {}; - -/** - * Class to provide checking for version and NativeClient. - * @param {integer} arg1 An argument that indicates major version of Chrome we - * require, such as 14. - */ - -/** - * Constructor for the BrowserChecker. Sets the major version of - * Chrome that is required to |minChromeVersion|. - * @param minChromeVersion The earliest major version of chrome that - * is supported. If the Chrome browser version is less than - * |minChromeVersion| then |isValidBrowswer| will be set to false. - * @param opt_maxChromeVersion Ignored. Retained for backwards compatibility. - * @param appVersion The application version string. - * @param plugins The plugins that exist in the browser. - * @constructor - */ -browser_version.BrowserChecker = function(minChromeVersion, - appVersion, plugins, - opt_maxChromeVersion) { - /** - * Version specified by the user. This class looks to see if the browser - * version is >= |minChromeVersion_|. - * @type {integer} - * @private - */ - this.minChromeVersion_ = minChromeVersion; - - /** - * List of Browser plugin objects. - * @type {Ojbect array} - * @private - */ - this.plugins_ = plugins; - - /** - * Application version string from the Browser. - * @type {integer} - * @private - */ - this.appVersion_ = appVersion; - - /** - * Flag used to indicate if the browser has Native Client and is if the - * browser version is recent enough. - * @type {boolean} - * @private - */ - this.isValidBrowser_ = false; - - /** - * Actual major version of Chrome -- found by querying the browser. - * @type {integer} - * @private - */ - this.chromeVersion_ = null; - - /** - * Browser support status. This allows the user to get a detailed status - * rather than using this.browserSupportMessage. - */ - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.UNKNOWN; -} - -/** - * The values used for BrowserChecker status to indicate success or - * a specific error. - * @enum {id} - */ -browser_version.BrowserChecker.StatusValues = { - UNKNOWN: 0, - NACL_ENABLED: 1, - UNKNOWN_BROWSER: 2, - CHROME_VERSION_TOO_OLD: 3, - NACL_NOT_ENABLED: 4, - NOT_USING_SERVER: 5 -}; - -/** - * Determines if the plugin with name |name| exists in the browser. - * @param {string} name The name of the plugin. - * @param {Object array} plugins The plugins in this browser. - * @return {bool} |true| if the plugin is found. - */ -browser_version.BrowserChecker.prototype.pluginExists = function(name, - plugins) { - for (var index=0; index < plugins.length; index++) { - var plugin = this.plugins_[index]; - var plugin_name = plugin['name']; - // If the plugin is not found, you can use the Javascript console - // to see the names of the plugins that were found when debugging. - if (plugin_name.indexOf(name) != -1) { - return true; - } - } - return false; -} - -/** - * Returns browserSupportStatus_ which indicates if the browser supports - * Native Client. Values are defined as literals in - * browser_version.BrowserChecker.StatusValues. - * @ return {int} Level of NaCl support. - */ -browser_version.BrowserChecker.prototype.getBrowserSupportStatus = function() { - return this.browserSupportStatus_; -} - -/** - * Returns isValidBrowser (true/false) to indicate if the browser supports - * Native Client. - * @ return {bool} If this browser has NativeClient and correct version. - */ -browser_version.BrowserChecker.prototype.getIsValidBrowser = function() { - return this.isValidBrowser_; -} - -/** - * Checks to see if this browser can support Native Client applications. - * For Chrome browsers, checks to see if the "Native Client" plugin is - * enabled. - */ -browser_version.BrowserChecker.prototype.checkBrowser = function() { - var versionPatt = /Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/; - var result = this.appVersion_.match(versionPatt); - - // |result| stores the Chrome version number. - if (!result) { - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.UNKNOWN_BROWSER; - } else { - this.chromeVersion_ = result[1]; - // We know we have Chrome, check version and/or plugin named Native Client - if (this.chromeVersion_ >= this.minChromeVersion_) { - var found_nacl = this.pluginExists('Native Client', this.plugins_); - if (found_nacl) { - this.isValidBrowser_ = true; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.NACL_ENABLED; - } else { - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.NACL_NOT_ENABLED; - } - } else { - // We are in a version that is less than |minChromeVersion_| - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.CHROME_VERSION_TOO_OLD; - } - } - var my_protocol = window.location.protocol; - if (my_protocol.indexOf('file') == 0) { - this.isValidBrowser_ = false; - this.browserSupportStatus_ = - browser_version.BrowserChecker.StatusValues.NOT_USING_SERVER; - } -} - diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/cube.cc b/native_client_sdk/src/examples/fullscreen_tumbler/cube.cc deleted file mode 100644 index 3a790b7..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/cube.cc +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) 2012 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. - -#include <algorithm> -#include <GLES2/gl2.h> - -#include "ppapi/gles2/gl2ext_ppapi.h" - -#include "cube.h" -#include "shader_util.h" -#include "transforms.h" - -namespace tumbler { - -static const size_t kVertexCount = 24; -static const int kIndexCount = 36; - -Cube::Cube(SharedOpenGLContext opengl_context) - : opengl_context_(opengl_context), width_(1), height_(1) { - eye_[0] = eye_[1] = 0.0f; - eye_[2] = 2.0f; - orientation_[0] = 0.0f; - orientation_[1] = 0.0f; - orientation_[2] = 0.0f; - orientation_[3] = 1.0f; -} - -Cube::~Cube() { - glDeleteBuffers(3, cube_vbos_); - glDeleteProgram(shader_program_object_); -} - -void Cube::PrepareOpenGL() { - CreateShaders(); - CreateCube(); - glClearColor(1.0f, 1.0f, 1.0f, 1.0f); - glEnable(GL_DEPTH_TEST); -} - -void Cube::Resize(int width, int height) { - width_ = std::max(width, 1); - height_ = std::max(height, 1); - // Set the viewport - glViewport(0, 0, width_, height_); - // Compute the perspective projection matrix with a 60 degree FOV. - GLfloat aspect = static_cast<GLfloat>(width_) / static_cast<GLfloat>(height_); - transform_4x4::LoadIdentity(perspective_proj_); - transform_4x4::Perspective(perspective_proj_, 60.0f, aspect, 1.0f, 20.0f); -} - -void Cube::Draw() { - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - // Compute a new model-view matrix, then use that to make the composite - // model-view-projection matrix: MVP = MV . P. - GLfloat model_view[16]; - ComputeModelViewTransform(model_view); - transform_4x4::Multiply(mvp_matrix_, model_view, perspective_proj_); - - glBindBuffer(GL_ARRAY_BUFFER, cube_vbos_[0]); - glUseProgram(shader_program_object_); - glEnableVertexAttribArray(position_location_); - glVertexAttribPointer( - position_location_, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL); - glEnableVertexAttribArray(color_location_); - glBindBuffer(GL_ARRAY_BUFFER, cube_vbos_[1]); - glVertexAttribPointer( - color_location_, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL); - glUniformMatrix4fv(mvp_location_, 1, GL_FALSE, mvp_matrix_); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube_vbos_[2]); - glDrawElements(GL_TRIANGLES, kIndexCount, GL_UNSIGNED_SHORT, 0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -} - -bool Cube::CreateShaders() { - const char vertex_shader_src[] = - "uniform mat4 u_mvpMatrix; \n" - "attribute vec4 a_position; \n" - "attribute vec3 a_color; \n" - "varying lowp vec4 v_color; \n" - "void main() \n" - "{ \n" - " v_color.xyz = a_color; \n" - " v_color.w = 1.0; \n" - " gl_Position = u_mvpMatrix * a_position; \n" - "} \n"; - - const char fragment_shader_src[] = - "varying lowp vec4 v_color; \n" - "void main() \n" - "{ \n" - " gl_FragColor = v_color; \n" - "} \n"; - - // Load the shaders and get a linked program object - shader_program_object_ = - shader_util::CreateProgramFromVertexAndFragmentShaders( - vertex_shader_src, fragment_shader_src); - if (shader_program_object_ == 0) - return false; - position_location_ = - glGetAttribLocation(shader_program_object_, "a_position"); - color_location_ = glGetAttribLocation(shader_program_object_, "a_color"); - mvp_location_ = glGetUniformLocation(shader_program_object_, "u_mvpMatrix"); - return true; -} - -void Cube::CreateCube() { - static const GLfloat cube_vertices[] = { - // Vertex coordinates interleaved with color values - // Bottom - -0.5f, -0.5f, -0.5f, - -0.5f, -0.5f, 0.5f, - 0.5f, -0.5f, 0.5f, - 0.5f, -0.5f, -0.5f, - // Top - -0.5f, 0.5f, -0.5f, - -0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, -0.5f, - // Back - -0.5f, -0.5f, -0.5f, - -0.5f, 0.5f, -0.5f, - 0.5f, 0.5f, -0.5f, - 0.5f, -0.5f, -0.5f, - // Front - -0.5f, -0.5f, 0.5f, - -0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, 0.5f, - 0.5f, -0.5f, 0.5f, - // Left - -0.5f, -0.5f, -0.5f, - -0.5f, -0.5f, 0.5f, - -0.5f, 0.5f, 0.5f, - -0.5f, 0.5f, -0.5f, - // Right - 0.5f, -0.5f, -0.5f, - 0.5f, -0.5f, 0.5f, - 0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, -0.5f - }; - - static const GLfloat cube_colors[] = { - // Vertex coordinates interleaved with color values - // Bottom - 1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, - // Top - 0.0, 1.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 1.0, 0.0, - // Back - 0.0, 0.0, 1.0, - 0.0, 0.0, 1.0, - 0.0, 0.0, 1.0, - 0.0, 0.0, 1.0, - // Front - 1.0, 0.0, 1.0, - 1.0, 0.0, 1.0, - 1.0, 0.0, 1.0, - 1.0, 0.0, 1.0, - // Left - 1.0, 1.0, 0.0, - 1.0, 1.0, 0.0, - 1.0, 1.0, 0.0, - 1.0, 1.0, 0.0, - // Right - 0.0, 1.0, 1.0, - 0.0, 1.0, 1.0, - 0.0, 1.0, 1.0, - 0.0, 1.0, 1.0 - }; - - static const GLushort cube_indices[] = { - // Bottom - 0, 2, 1, - 0, 3, 2, - // Top - 4, 5, 6, - 4, 6, 7, - // Back - 8, 9, 10, - 8, 10, 11, - // Front - 12, 15, 14, - 12, 14, 13, - // Left - 16, 17, 18, - 16, 18, 19, - // Right - 20, 23, 22, - 20, 22, 21 - }; - - // Generate the VBOs and upload them to the graphics context. - glGenBuffers(3, cube_vbos_); - glBindBuffer(GL_ARRAY_BUFFER, cube_vbos_[0]); - glBufferData(GL_ARRAY_BUFFER, - kVertexCount * sizeof(GLfloat) * 3, - cube_vertices, - GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, cube_vbos_[1]); - glBufferData(GL_ARRAY_BUFFER, - kVertexCount * sizeof(GLfloat) * 3, - cube_colors, - GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube_vbos_[2]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, - kIndexCount * sizeof(GL_UNSIGNED_SHORT), - cube_indices, - GL_STATIC_DRAW); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -} - -void Cube::ComputeModelViewTransform(GLfloat* model_view) { - // This method takes into account the possibility that |orientation_| - // might not be normalized. - double sqrx = orientation_[0] * orientation_[0]; - double sqry = orientation_[1] * orientation_[1]; - double sqrz = orientation_[2] * orientation_[2]; - double sqrw = orientation_[3] * orientation_[3]; - double sqrLength = 1.0 / (sqrx + sqry + sqrz + sqrw); - - transform_4x4::LoadIdentity(model_view); - model_view[0] = (sqrx - sqry - sqrz + sqrw) * sqrLength; - model_view[5] = (-sqrx + sqry - sqrz + sqrw) * sqrLength; - model_view[10] = (-sqrx - sqry + sqrz + sqrw) * sqrLength; - - double temp1 = orientation_[0] * orientation_[1]; - double temp2 = orientation_[2] * orientation_[3]; - model_view[1] = 2.0 * (temp1 + temp2) * sqrLength; - model_view[4] = 2.0 * (temp1 - temp2) * sqrLength; - - temp1 = orientation_[0] * orientation_[2]; - temp2 = orientation_[1] * orientation_[3]; - model_view[2] = 2.0 * (temp1 - temp2) * sqrLength; - model_view[8] = 2.0 * (temp1 + temp2) * sqrLength; - temp1 = orientation_[1] * orientation_[2]; - temp2 = orientation_[0] * orientation_[3]; - model_view[6] = 2.0 * (temp1 + temp2) * sqrLength; - model_view[9] = 2.0 * (temp1 - temp2) * sqrLength; - model_view[3] = 0.0; - model_view[7] = 0.0; - model_view[11] = 0.0; - - // Concatenate the translation to the eye point. - model_view[12] = -eye_[0]; - model_view[13] = -eye_[1]; - model_view[14] = -eye_[2]; - model_view[15] = 1.0; -} - -} // namespace tumbler diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/cube.h b/native_client_sdk/src/examples/fullscreen_tumbler/cube.h deleted file mode 100644 index dfe427f..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/cube.h +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_CUBE_H_ -#define EXAMPLES_TUMBLER_CUBE_H_ - -#include <GLES2/gl2.h> -#include <vector> - -#include "opengl_context.h" -#include "opengl_context_ptrs.h" - -namespace tumbler { - -// The Cube class provides a place to implement 3D rendering. It has a -// frame that it occupies in a browser window. -class Cube { - public: - explicit Cube(SharedOpenGLContext opengl_context); - ~Cube(); - - // Called once when a new RenderContext is first bound to the view. The - // bound context is guaranteed to be current and valid before calling this - // method. - void PrepareOpenGL(); - - // Called whenever the size of the browser view changes. This method is - // called at least once when the view is first made visible. Clamps the - // sizes to 1. - void Resize(int width, int height); - - // Called every time the view need to be drawn. The bound context is - // guaranteed to be current and valid before this method is called. The - // visible portion of the context is flushed to the browser after this - // method returns. - void Draw(); - - // Accessor for width and height. To change these, call Resize. - const int width() const { return width_; } - - const int height() const { return height_; } - - // Accessor/mutator for the camera orientation. - void GetOrientation(std::vector<float>* orientation) const { - if (!orientation) - return; - (*orientation)[0] = static_cast<float>(orientation_[0]); - (*orientation)[1] = static_cast<float>(orientation_[1]); - (*orientation)[2] = static_cast<float>(orientation_[2]); - (*orientation)[3] = static_cast<float>(orientation_[3]); - } - void SetOrientation(const std::vector<float>& orientation) { - orientation_[0] = static_cast<GLfloat>(orientation[0]); - orientation_[1] = static_cast<GLfloat>(orientation[1]); - orientation_[2] = static_cast<GLfloat>(orientation[2]); - orientation_[3] = static_cast<GLfloat>(orientation[3]); - } - - private: - // Create the shaders used to draw the cube, and link them into a program. - // Initializes |shader_program_object_|, |position_location_| and - // |mvp_location_|. - bool CreateShaders(); - - // Generates a cube as a series of GL_TRIANGLE_STRIPs, and initializes - // |index_count_| to the number of indices in the index list used as a VBO. - // Creates the |vbo_ids_| required for the vertex and index data and uploads - // the VBO data. - void CreateCube(); - - // Build up the model-view transform from the eye and orientation properties. - // Assumes that |model_view| is a 4x4 matrix. - void ComputeModelViewTransform(GLfloat* model_view); - - SharedOpenGLContext opengl_context_; - int width_; - int height_; - GLuint shader_program_object_; // The compiled shaders. - GLint position_location_; // The position attribute location. - GLint color_location_; // The color attribute location. - GLint mvp_location_; // The Model-View-Projection composite matrix. - GLuint cube_vbos_[3]; - GLfloat eye_[3]; // The eye point of the virtual camera. - // The orientation of the virtual camera stored as a quaternion. The - // quaternion is laid out as {{x, y, z}, w}. - GLfloat orientation_[4]; - GLfloat perspective_proj_[16]; - GLfloat mvp_matrix_[16]; -}; - -} // namespace tumbler - -#endif // EXAMPLES_TUMBLER_CUBE_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/dragger.js b/native_client_sdk/src/examples/fullscreen_tumbler/dragger.js deleted file mode 100644 index 5414c64..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/dragger.js +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) 2012 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. - -/** - * @fileoverview This class implements a mouse-drag event. It registers for - * mousedown events, and when it sees one, starts capturing mousemove events - * until it gets a mousup event. It manufactures three drag events: the - * DRAG_START, DRAG and DRAG_END. - */ - -// Requires bind - -var tumbler = tumbler || {}; - -/** - * Constructor for the Dragger. Register for mousedown events that happen on - * |opt_target|. If |opt_target| is null or undefined, then this object - * observes mousedown on the whole document. - * @param {?Element} opt_target The event target. Defaults to the whole - * document. - * @constructor - */ -tumbler.Dragger = function(opt_target) { - /** - * The event target. - * @type {Element} - * @private - */ - this.target_ = opt_target || document; - - /** - * The array of objects that get notified of drag events. Each object in - * this array get sent a handleStartDrag(), handleDrag() and handleEndDrag() - * message. - * @type {Array.<Object>} - * @private - */ - this.listeners_ = []; - - /** - * Flag to indicate whether the object is in a drag sequence or not. - * @type {boolean} - * @private - */ - this.isDragging_ = false; - - /** - * The function objects that get attached as event handlers. These are - * cached so that they can be removed on mouse up. - * @type {function} - * @private - */ - this.boundMouseMove_ = null; - this.boundMouseUp_ = null; - - this.target_.addEventListener('mousedown', - this.onMouseDown.bind(this), - false); -} - -/** - * The ids used for drag event types. - * @enum {string} - */ -tumbler.Dragger.DragEvents = { - DRAG_START: 'dragstart', // Start a drag sequence - DRAG: 'drag', // Mouse moved during a drag sequence. - DRAG_END: 'dragend' // End a drag sewquence. -}; - -/** - * Add a drag listener. Each listener should respond to thhree methods: - * handleStartDrag(), handleDrag() and handleEndDrag(). This method assumes - * that |listener| does not already exist in the array of listeners. - * @param {!Object} listener The object that will listen to drag events. - */ -tumbler.Dragger.prototype.addDragListener = function(listener) { - this.listeners_.push(listener); -} - -/** - * Handle a mousedown event: register for mousemove and mouseup, then tell - * the target that is has a DRAG_START event. - * @param {Event} event The mousedown event that triggered this method. - */ -tumbler.Dragger.prototype.onMouseDown = function(event) { - this.boundMouseMove_ = this.onMouseMove.bind(this); - this.boundMouseUp_ = this.onMouseUp.bind(this); - this.target_.addEventListener('mousemove', this.boundMouseMove_); - this.target_.addEventListener('mouseup', this.boundMouseUp_); - this.isDragging_ = true; - var dragStartEvent = { type: tumbler.Dragger.DragEvents.DRAG_START, - clientX: event.offsetX, - clientY: event.offsetY }; - var i; - for (i = 0; i < this.listeners_.length; ++i) { - this.listeners_[i].handleStartDrag(this.target_, dragStartEvent); - } -} - -/** - * Handle a mousemove event: tell the target that is has a DRAG event. - * @param {Event} event The mousemove event that triggered this method. - */ -tumbler.Dragger.prototype.onMouseMove = function(event) { - if (!this.isDragging_) - return; - var dragEvent = { type: tumbler.Dragger.DragEvents.DRAG, - clientX: event.offsetX, - clientY: event.offsetY}; - var i; - for (i = 0; i < this.listeners_.length; ++i) { - this.listeners_[i].handleDrag(this.target_, dragEvent); - } -} - -/** - * Handle a mouseup event: un-register for mousemove and mouseup, then tell - * the target that is has a DRAG_END event. - * @param {Event} event The mouseup event that triggered this method. - */ -tumbler.Dragger.prototype.onMouseUp = function(event) { - this.target_.removeEventListener('mouseup', this.boundMouseUp_, false); - this.target_.removeEventListener('mousemove', this.boundMouseMove_, false); - this.boundMouseUp_ = null; - this.boundMouseMove_ = null; - this.isDragging_ = false; - var dragEndEvent = { type: tumbler.Dragger.DragEvents.DRAG_END, - clientX: event.offsetX, - clientY: event.offsetY}; - var i; - for (i = 0; i < this.listeners_.length; ++i) { - this.listeners_[i].handleEndDrag(this.target_, dragEndEvent); - } -} diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/example.dsc b/native_client_sdk/src/examples/fullscreen_tumbler/example.dsc deleted file mode 100644 index bad2219..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/example.dsc +++ /dev/null @@ -1,47 +0,0 @@ -{ - 'DISABLE': True, - 'TOOLS': ['newlib', 'glibc', 'pnacl'], - 'TARGETS': [ - { - 'NAME': 'fullscreen_tumbler', - 'TYPE': 'main', - 'SOURCES': [ - 'callback.h', - 'cube.cc', - 'cube.h', - 'opengl_context.cc', - 'opengl_context.h', - 'opengl_context_ptrs.h', - 'scripting_bridge.cc', - 'scripting_bridge.h', - 'shader_util.cc', - 'shader_util.h', - 'transforms.cc', - 'transforms.h', - 'tumbler.cc', - 'tumbler.h', - 'tumbler_module.cc' - ], - 'LIBS': ['ppapi_gles2', 'ppapi_cpp', 'ppapi', 'pthread'] - } - ], - 'DATA': [ - 'bind.js', - 'check_browser.js', - 'dragger.js', - 'trackball.js', - 'tumbler.js', - 'vector3.js' - ], - 'DEST': 'examples', - 'NAME': 'fullscreen_tumbler', - 'TITLE': 'Interactive Cube Example', - 'DESC': """ -This is a modified version of the Tumbler example above that supports -full-screen display. It is in every way identical to Tumbler in -functionality, except that it adds the ability to switch to/from -full-screen display by pressing the Enter key. -""", - 'INFO': 'Teaching focus: Full-screen.' -} - diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/index.html b/native_client_sdk/src/examples/fullscreen_tumbler/index.html deleted file mode 100644 index bf902f2..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/index.html +++ /dev/null @@ -1,27 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright (c) 2012 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> - <meta http-equiv="Pragma" content="no-cache"> - <meta http-equiv="Expires" content="-1"> - <title>{{title}}</title> - <script type="text/javascript" src="common.js"></script> - <script type="text/javascript" src="check_browser.js"></script> - <script type="text/javascript" src="bind.js"></script> - <script type="text/javascript" src="dragger.js"></script> - <script type="text/javascript" src="tumbler.js"></script> - <script type="text/javascript" src="vector3.js"></script> - <script type="text/javascript" src="trackball.js"></script> -</head> -<body data-width="480" data-height="480" {{attrs}}> - <h1>{{title}}</h1> - <h2>Status: <code id="statusField">NO-STATUS</code></h2> - <!-- The NaCl plugin will be embedded inside the element with id "listener". - See common.js.--> - <div id="listener"></div> -</body> -</html> diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context.cc b/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context.cc deleted file mode 100644 index 153c7e3..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context.cc +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2012 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. - -#include <pthread.h> - -#include "ppapi/c/pp_graphics_3d.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/gles2/gl2ext_ppapi.h" -#include "opengl_context.h" - -namespace { -// This is called by the browser when the 3D context has been flushed to the -// browser window. -void FlushCallback(void* data, int32_t result) { - static_cast<tumbler::OpenGLContext*>(data)->set_flush_pending(false); -} -} // namespace - -namespace tumbler { - -OpenGLContext::OpenGLContext(pp::Instance* instance) - : pp::Graphics3DClient(instance), flush_pending_(false) { - pp::Module* module = pp::Module::Get(); - assert(module); - gles2_interface_ = static_cast<const struct PPB_OpenGLES2*>( - module->GetBrowserInterface(PPB_OPENGLES2_INTERFACE)); - assert(gles2_interface_); -} - -OpenGLContext::~OpenGLContext() { glSetCurrentContextPPAPI(0); } - -bool OpenGLContext::MakeContextCurrent(pp::Instance* instance) { - if (instance == NULL) { - glSetCurrentContextPPAPI(0); - return false; - } - // Lazily create the Pepper context. - if (context_.is_null()) { - int32_t attribs[] = { - PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8, - PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24, - PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8, - PP_GRAPHICS3DATTRIB_SAMPLES, 0, - PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0, - PP_GRAPHICS3DATTRIB_WIDTH, size_.width(), - PP_GRAPHICS3DATTRIB_HEIGHT, size_.height(), - PP_GRAPHICS3DATTRIB_NONE - }; - context_ = pp::Graphics3D(instance, pp::Graphics3D(), attribs); - if (context_.is_null()) { - glSetCurrentContextPPAPI(0); - return false; - } - instance->BindGraphics(context_); - } - glSetCurrentContextPPAPI(context_.pp_resource()); - return true; -} - -void OpenGLContext::InvalidateContext(pp::Instance* instance) { - glSetCurrentContextPPAPI(0); -} - -void OpenGLContext::ResizeContext(const pp::Size& size) { - size_ = size; - if (!context_.is_null()) { - context_.ResizeBuffers(size.width(), size.height()); - } -} - -void OpenGLContext::FlushContext() { - if (flush_pending()) { - // A flush is pending so do nothing; just drop this flush on the floor. - return; - } - set_flush_pending(true); - context_.SwapBuffers(pp::CompletionCallback(&FlushCallback, this)); -} -} // namespace tumbler diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context.h b/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context.h deleted file mode 100644 index f2b284c..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context.h +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_OPENGL_CONTEXT_H_ -#define EXAMPLES_TUMBLER_OPENGL_CONTEXT_H_ - -/// -/// @file -/// OpenGLContext manages the OpenGL context in the browser that is associated -/// with a @a pp::Instance instance. -/// - -#include <assert.h> -#include <pthread.h> - -#include <algorithm> -#include <string> - -#include "ppapi/c/ppb_opengles2.h" -#include "ppapi/cpp/graphics_3d.h" -#include "ppapi/cpp/graphics_3d_client.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/size.h" - -#include "opengl_context_ptrs.h" - -namespace tumbler { - -/// OpenGLContext manages an OpenGL rendering context in the browser. -/// -class OpenGLContext : public pp::Graphics3DClient { - public: - explicit OpenGLContext(pp::Instance* instance); - - /// Release all the in-browser resources used by this context, and make this - /// context invalid. - virtual ~OpenGLContext(); - - /// The Graphics3DClient interface. - virtual void Graphics3DContextLost() { - assert(!"Unexpectedly lost graphics context"); - } - - /// Make @a this the current 3D context in @a instance. - /// @param instance The instance of the NaCl module that will receive the - /// the current 3D context. - /// @return success. - bool MakeContextCurrent(pp::Instance* instance); - - /// Flush the contents of this context to the browser's 3D device. - void FlushContext(); - - /// Make the underlying 3D device invalid, so that any subsequent rendering - /// commands will have no effect. The next call to MakeContextCurrent() will - /// cause the underlying 3D device to get rebound and start receiving - /// receiving rendering commands again. Use InvalidateContext(), for - /// example, when resizing the context's viewing area. - void InvalidateContext(pp::Instance* instance); - - /// Resize the context. - void ResizeContext(const pp::Size& size); - - /// The OpenGL ES 2.0 interface. - const struct PPB_OpenGLES2* gles2() const { return gles2_interface_; } - - /// The PP_Resource needed to make GLES2 calls through the Pepper interface. - const PP_Resource gl_context() const { return context_.pp_resource(); } - - /// Indicate whether a flush is pending. This can only be called from the - /// main thread; it is not thread safe. - bool flush_pending() const { return flush_pending_; } - void set_flush_pending(bool flag) { flush_pending_ = flag; } - - private: - pp::Size size_; - pp::Graphics3D context_; - bool flush_pending_; - - const struct PPB_OpenGLES2* gles2_interface_; -}; - -} // namespace tumbler - -#endif // EXAMPLES_TUMBLER_OPENGL_CONTEXT_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context_ptrs.h b/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context_ptrs.h deleted file mode 100644 index d5da922..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/opengl_context_ptrs.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_OPENGL_CONTEXT_PTRS_H_ -#define EXAMPLES_TUMBLER_OPENGL_CONTEXT_PTRS_H_ - -// A convenience wrapper for a shared OpenGLContext pointer type. As other -// smart pointer types are needed, add them here. - -#include <tr1/memory> - -namespace tumbler { - -class OpenGLContext; - -typedef std::tr1::shared_ptr<OpenGLContext> SharedOpenGLContext; - -} // namespace tumbler - -#endif // EXAMPLES_TUMBLER_OPENGL_CONTEXT_PTRS_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/scripting_bridge.cc b/native_client_sdk/src/examples/fullscreen_tumbler/scripting_bridge.cc deleted file mode 100644 index 0cd49cde..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/scripting_bridge.cc +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2012 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. - -#include "scripting_bridge.h" - -namespace { -const char* const kWhiteSpaceCharacters = " \t"; - -// Helper function to pull out the next token in |token_string|. A token is -// delimited by whitespace. Scanning begins at |*pos|, if pos goes beyond the -// end of |token_string|, it is set to std::string::npos and an empty string -// is returned. On return, |*pos| will point to the beginning of the next -// token. |pos| must not be NULL. -const std::string ScanToken(const std::string& token_string, size_t* pos) { - std::string token; - if (*pos == std::string::npos) { - return token; - } - size_t token_start_pos = - token_string.find_first_not_of(kWhiteSpaceCharacters, *pos); - size_t token_end_pos = - token_string.find_first_of(kWhiteSpaceCharacters, token_start_pos); - if (token_start_pos != std::string::npos) { - token = token_string.substr(token_start_pos, token_end_pos); - } - *pos = token_end_pos; - return token; -} - -// Take a string of the form 'name:value' and split it into two strings, one -// containing 'name' and the other 'value'. If the ':' separator is missing, -// or is the last character in |parameter|, |parameter| is copied to -// |param_name|, |param_value| is left unchanged and false is returned. -bool ParseParameter(const std::string& parameter, - std::string* param_name, - std::string* param_value) { - bool success = false; - size_t sep_pos = parameter.find_first_of(':'); - if (sep_pos != std::string::npos) { - *param_name = parameter.substr(0, sep_pos); - if (sep_pos < parameter.length() - 1) { - *param_value = parameter.substr(sep_pos + 1); - success = true; - } else { - success = false; - } - } else { - *param_name = parameter; - success = false; - } - return success; -} -} // namespace - -namespace tumbler { - -bool ScriptingBridge::AddMethodNamed(const std::string& method_name, - SharedMethodCallbackExecutor method) { - if (method_name.size() == 0 || method == NULL) - return false; - method_dictionary_.insert( - std::pair<std::string, SharedMethodCallbackExecutor>(method_name, - method)); - return true; -} - -bool ScriptingBridge::InvokeMethod(const std::string& method) { - size_t current_pos = 0; - const std::string method_name = ScanToken(method, ¤t_pos); - MethodDictionary::iterator method_iter; - method_iter = method_dictionary_.find(method_name); - if (method_iter != method_dictionary_.end()) { - // Pull out the method parameters and build a dictionary that maps - // parameter names to values. - std::map<std::string, std::string> param_dict; - while (current_pos != std::string::npos) { - const std::string parameter = ScanToken(method, ¤t_pos); - if (parameter.length()) { - std::string param_name; - std::string param_value; - if (ParseParameter(parameter, ¶m_name, ¶m_value)) { - // Note that duplicate parameter names will override each other. The - // last one in the method string will be used. - param_dict[param_name] = param_value; - } - } - } - (*method_iter->second).Execute(*this, param_dict); - return true; - } - return false; -} - -} // namespace tumbler diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/scripting_bridge.h b/native_client_sdk/src/examples/fullscreen_tumbler/scripting_bridge.h deleted file mode 100644 index f4ebfb4..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/scripting_bridge.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_SCRIPTING_BRIDGE_H_ -#define EXAMPLES_TUMBLER_SCRIPTING_BRIDGE_H_ - -#include <map> -#include <string> -#include <tr1/memory> -#include <vector> - -#include "ppapi/cpp/var.h" - -#include "callback.h" - -namespace tumbler { - -class MethodCallbackExecutor; - -// This class handles the interface between the browser and the NaCl module. -// There is a single point of entry from the browser: postMessage(). The -// string passed to postMessage() has this format: -// 'function_name arg_name0:arg_0 arg_name1:arg1 ...' -// The arguments have undetermined type; they are placed in a map of argument -// names and values. Values are all strings, it is up to the target code to -// do any type coercion. -// Methods called by the scripting bridge must have a signature like this: -// void Method(const ScriptingBridge& bridge, -// const ParameterDictionary&); -class ScriptingBridge { - public: - // Shared pointer type used in the method map. - typedef std::tr1::shared_ptr<MethodCallbackExecutor> - SharedMethodCallbackExecutor; - - virtual ~ScriptingBridge() {} - - // Causes |method_name| to be published as a method that can be called via - // postMessage() from the browser. Associates this method with |method|. - bool AddMethodNamed(const std::string& method_name, - SharedMethodCallbackExecutor method); - - bool InvokeMethod(const std::string& method); - - private: - typedef std::map<std::string, SharedMethodCallbackExecutor> MethodDictionary; - - MethodDictionary method_dictionary_; -}; - -} // namespace tumbler - -#endif // EXAMPLES_TUMBLER_SCRIPTING_BRIDGE_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/shader_util.cc b/native_client_sdk/src/examples/fullscreen_tumbler/shader_util.cc deleted file mode 100644 index ad6f5e9..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/shader_util.cc +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2012 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. - -#include <stdio.h> -#include <stdlib.h> -#include <GLES2/gl2.h> - -#include "ppapi/gles2/gl2ext_ppapi.h" -#include "shader_util.h" - -namespace shader_util { - -GLuint CreateShaderOfType(GLenum type, const char* shader_src) { - GLuint shader; - GLint compiled; - - // Create the shader object - shader = glCreateShader(type); - - if (shader == 0) - return 0; - - // Load and compile the shader source - glShaderSource(shader, 1, &shader_src, NULL); - glCompileShader(shader); - - // Check the compile status - glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); - if (compiled == 0) { - GLint info_len = 0; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_len); - if (info_len > 1) { - char* info_log = - reinterpret_cast<char*>(malloc(sizeof(*info_log) * info_len)); - glGetShaderInfoLog(shader, info_len, NULL, info_log); - // TODO(dspringer): We could really use a logging API. - printf("Error compiling shader:\n%s\n", info_log); - free(info_log); - } - glDeleteShader(shader); - return 0; - } - - return shader; -} - -GLuint CreateProgramFromVertexAndFragmentShaders( - const char* vertex_shader_src, - const char* fragment_shader_src) { - GLuint vertex_shader; - GLuint fragment_shader; - GLuint program_object; - GLint linked; - - // Load the vertex/fragment shaders - vertex_shader = CreateShaderOfType(GL_VERTEX_SHADER, vertex_shader_src); - if (vertex_shader == 0) - return 0; - fragment_shader = CreateShaderOfType(GL_FRAGMENT_SHADER, fragment_shader_src); - if (fragment_shader == 0) { - glDeleteShader(vertex_shader); - return 0; - } - - // Create the program object and attach the shaders. - program_object = glCreateProgram(); - if (program_object == 0) - return 0; - glAttachShader(program_object, vertex_shader); - glAttachShader(program_object, fragment_shader); - - // Link the program - glLinkProgram(program_object); - - // Check the link status - glGetProgramiv(program_object, GL_LINK_STATUS, &linked); - if (linked == 0) { - GLint info_len = 0; - glGetProgramiv(program_object, GL_INFO_LOG_LENGTH, &info_len); - if (info_len > 1) { - char* info_log = reinterpret_cast<char*>(malloc(info_len)); - glGetProgramInfoLog(program_object, info_len, NULL, info_log); - // TODO(dspringer): We could really use a logging API. - printf("Error linking program:\n%s\n", info_log); - free(info_log); - } - glDeleteProgram(program_object); - return 0; - } - - // Delete these here because they are attached to the program object. - glDeleteShader(vertex_shader); - glDeleteShader(fragment_shader); - - return program_object; -} - -} // namespace shader_util diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/shader_util.h b/native_client_sdk/src/examples/fullscreen_tumbler/shader_util.h deleted file mode 100644 index f733603..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/shader_util.h +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2012 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. - -// Some simple helper functions that load shaders and create program objects. - -#ifndef EXAMPLES_TUMBLER_SHADER_UTIL_H_ -#define EXAMPLES_TUMBLER_SHADER_UTIL_H_ - -#include <GLES2/gl2.h> - -namespace shader_util { - -// Load and compile a shader. |type| can be one of GL_VERTEX_SHADER or -// GL_FRAGMENT_SHADER. Returns a non-0 value representing the compiled -// shader on success, 0 on failure. The caller is responsible for deleting -// the returned shader using glDeleteShader(). -GLuint CreateShaderOfType(GLenum type, const char* shader_src); - -// Load and compile the vertex and fragment shaders, then link these together -// into a complete program. Returns a non-0 value representing the program on, -// success or 0 on failure. The caller is responsible for deleting the -// returned program using glDeleteProgram(). -GLuint CreateProgramFromVertexAndFragmentShaders( - const char* vertex_shader_src, - const char* fragment_shader_src); - -} // namespace shader_util - -#endif // EXAMPLES_TUMBLER_SHADER_UTIL_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/trackball.js b/native_client_sdk/src/examples/fullscreen_tumbler/trackball.js deleted file mode 100644 index c9d774d..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/trackball.js +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright (c) 2012 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. - -/** - * @fileoverview Implement a virtual trackball in the tumbler.Trackball - * class. This class maps 2D mouse events to 3D rotations by simulating a - * trackball that you roll by dragging the mouse. There are two principle - * methods in the class: startAtPointInFrame which you use to begin a trackball - * simulation and rollToPoint, which you use while dragging the mouse. The - * rollToPoint method returns a rotation expressed as a quaternion. - */ - - -// Requires tumbler.Application -// Requires tumbler.DragEvent -// Requires tumbler.Vector3 - -var tumbler = tumbler || {}; - -/** - * Constructor for the Trackball object. This class maps 2D mouse drag events - * into 3D rotations by simulating a trackball. The idea is to simulate - * clicking on the trackball, and then rolling it as you drag the mouse. - * The math behind the trackball is simple: start with a vector from the first - * mouse-click on the ball to the center of the 3D view. At the same time, set - * the radius of the ball to be the smaller dimension of the 3D view. As you - * drag the mouse around in the 3D view, a second vector is computed from the - * surface of the ball to the center. The axis of rotation is the cross - * product of these two vectors, and the angle of rotation is the angle between - * the two vectors. - * @constructor - */ -tumbler.Trackball = function() { - /** - * The square of the trackball's radius. The math never looks at the radius, - * but looks at the radius squared. - * @type {number} - * @private - */ - this.sqrRadius_ = 0; - - /** - * The 3D vector representing the point on the trackball where the mouse - * was clicked. Default is pointing stright through the center of the ball. - * @type {Object} - * @private - */ - this.rollStart_ = new tumbler.Vector3(0, 0, 1); - - /** - * The 2D center of the frame that encloses the trackball. - * @type {!Object} - * @private - */ - this.center_ = { x: 0, y: 0 }; - - /** - * Cached camera orientation. When a drag START event happens this is set to - * the current orientation in the calling view's plugin. The default is the - * identity quaternion. - * @type {Array.<number>} - * @private - */ - this.cameraOrientation_ = [0, 0, 0, 1]; -}; - -/** - * Compute the dimensions of the virtual trackball to fit inside |frameSize|. - * The radius of the trackball is set to be 1/2 of the smaller of the two frame - * dimensions, the center point is at the midpoint of each side. - * @param {!goog.math.Size} frameSize 2D-point representing the size of the - * element that encloses the virtual trackball. - * @private - */ -tumbler.Trackball.prototype.initInFrame_ = function(frameSize) { - // Compute the radius of the virtual trackball. This is 1/2 of the smaller - // of the frame's width and height. - var halfFrameSize = 0.5 * Math.min(frameSize.width, frameSize.height); - // Cache the square of the trackball's radius. - this.sqrRadius_ = halfFrameSize * halfFrameSize; - // Figure the center of the view. - this.center_.x = frameSize.width * 0.5; - this.center_.y = frameSize.height * 0.5; -}; - -/** - * Method to convert (by translation) a 2D client point from a coordinate space - * with origin in the lower-left corner of the client view to a space with - * origin in the center of the client view. Use this method before mapping the - * 2D point to he 3D tackball point (see also the projectOnTrackball_() method). - * Call the startAtPointInFrame before calling this method so that the - * |center_| property is correctly initialized. - * @param {!Object} clientPoint map this point to the coordinate space with - * origin in thecenter of the client view. - * @return {Object} the converted point. - * @private - */ -tumbler.Trackball.prototype.convertClientPoint_ = function(clientPoint) { - var difference = { x: clientPoint.x - this.center_.x, - y: clientPoint.y - this.center_.y } - return difference; -}; - -/** - * Method to map a 2D point to a 3D point on the virtual trackball that was set - * up using the startAtPointInFrame method. If the point lies outside of the - * radius of the virtual trackball, then the z-coordinate of the 3D point - * is set to 0. - * @param {!Object.<x, y>} point 2D-point in the coordinate space with origin - * in the center of the client view. - * @return {tumbler.Vector3} the 3D point on the virtual trackball. - * @private - */ -tumbler.Trackball.prototype.projectOnTrackball_ = function(point) { - var sqrRadius2D = point.x * point.x + point.y * point.y; - var zValue; - if (sqrRadius2D > this.sqrRadius_) { - // |point| lies outside the virtual trackball's sphere, so use a virtual - // z-value of 0. This is equivalent to clicking on the horizontal equator - // of the trackball. - zValue = 0; - } else { - // A sphere can be defined as: r^2 = x^2 + y^2 + z^2, so z = - // sqrt(r^2 - (x^2 + y^2)). - zValue = Math.sqrt(this.sqrRadius_ - sqrRadius2D); - } - var trackballPoint = new tumbler.Vector3(point.x, point.y, zValue); - return trackballPoint; -}; - -/** - * Method to start up the trackball. The trackball works by pretending that a - * ball encloses the 3D view. You roll this pretend ball with the mouse. For - * example, if you click on the center of the ball and move the mouse straight - * to the right, you roll the ball around its Y-axis. This produces a Y-axis - * rotation. You can click on the "edge" of the ball and roll it around - * in a circle to get a Z-axis rotation. - * @param {!Object.<x, y>} startPoint 2D-point, usually the mouse-down - * point. - * @param {!Object.<width, height>} frameSize 2D-point representing the size of - * the element that encloses the virtual trackball. - */ -tumbler.Trackball.prototype.startAtPointInFrame = - function(startPoint, frameSize) { - this.initInFrame_(frameSize); - // Compute the starting vector from the surface of the ball to its center. - this.rollStart_ = this.projectOnTrackball_( - this.convertClientPoint_(startPoint)); -}; - -/** - * Method to roll the virtual trackball; call this in response to a mouseDrag - * event. Takes |dragPoint| and projects it from 2D mouse coordinates onto the - * virtual track ball that was set up in startAtPointInFrame method. - * Returns a quaternion that represents the rotation from |rollStart_| to - * |rollEnd_|. - * @param {!Object.<x, y>} dragPoint 2D-point representing the - * destination mouse point. - * @return {Array.<number>} a quaternion that represents the rotation from - * the point wnere the mouse was clicked on the trackball to this point. - * The quaternion looks like this: [[v], cos(angle/2)], where [v] is the - * imaginary part of the quaternion and is computed as [x, y, z] * - * sin(angle/2). - */ -tumbler.Trackball.prototype.rollToPoint = function(dragPoint) { - var rollTo = this.convertClientPoint_(dragPoint); - if ((Math.abs(this.rollStart_.x - rollTo.x) < - tumbler.Trackball.DOUBLE_EPSILON) && - (Math.abs(this.rollStart_.y, rollTo.y) < - tumbler.Trackball.DOUBLE_EPSILON)) { - // Not enough change in the vectors to roll the ball, return the identity - // quaternion. - return [0, 0, 0, 1]; - } - - // Compute the ending vector from the surface of the ball to its center. - var rollEnd = this.projectOnTrackball_(rollTo); - - // Take the cross product of the two vectors. r = s X e - var rollVector = this.rollStart_.cross(rollEnd); - var invStartMag = 1.0 / this.rollStart_.magnitude(); - var invEndMag = 1.0 / rollEnd.magnitude(); - - // cos(a) = (s . e) / (||s|| ||e||) - var cosAng = this.rollStart_.dot(rollEnd) * invStartMag * invEndMag; - // sin(a) = ||(s X e)|| / (||s|| ||e||) - var sinAng = rollVector.magnitude() * invStartMag * invEndMag; - // Build a quaternion that represents the rotation about |rollVector|. - // Use atan2 for a better angle. If you use only cos or sin, you only get - // half the possible angles, and you can end up with rotations that flip - // around near the poles. - var rollHalfAngle = Math.atan2(sinAng, cosAng) * 0.5; - rollVector.normalize(); - // The quaternion looks like this: [[v], cos(angle/2)], where [v] is the - // imaginary part of the quaternion and is computed as [x, y, z] * - // sin(angle/2). - rollVector.scale(Math.sin(rollHalfAngle)); - var ballQuaternion = [rollVector.x, - rollVector.y, - rollVector.z, - Math.cos(rollHalfAngle)]; - return ballQuaternion; -}; - -/** - * Handle the drag START event: grab the current camera orientation from the - * sending view and set up the virtual trackball. - * @param {!tumbler.Application} view The view controller that called this - * method. - * @param {!tumbler.DragEvent} dragStartEvent The DRAG_START event that - * triggered this handler. - */ -tumbler.Trackball.prototype.handleStartDrag = - function(controller, dragStartEvent) { - // Cache the camera orientation. The orientations from the trackball as it - // rolls are concatenated to this orientation and pushed back into the - // plugin on the other side of the JavaScript bridge. - controller.setCameraOrientation(this.cameraOrientation_); - // Invert the y-coordinate for the trackball computations. - var frameSize = { width: controller.offsetWidth, - height: controller.offsetHeight }; - var flippedY = { x: dragStartEvent.clientX, - y: frameSize.height - dragStartEvent.clientY }; - this.startAtPointInFrame(flippedY, frameSize); -}; - -/** - * Handle the drag DRAG event: concatenate the current orientation to the - * cached orientation. Send this final value through to the GSPlugin via the - * setValueForKey() method. - * @param {!tumbler.Application} view The view controller that called this - * method. - * @param {!tumbler.DragEvent} dragEvent The DRAG event that triggered this - * handler. - */ -tumbler.Trackball.prototype.handleDrag = - function(controller, dragEvent) { - // Flip the y-coordinate so that the 2D origin is in the lower-left corner. - var frameSize = { width: controller.offsetWidth, - height: controller.offsetHeight }; - var flippedY = { x: dragEvent.clientX, - y: frameSize.height - dragEvent.clientY }; - controller.setCameraOrientation( - tumbler.multQuaternions(this.rollToPoint(flippedY), - this.cameraOrientation_)); -}; - -/** - * Handle the drag END event: get the final orientation and concatenate it to - * the cached orientation. - * @param {!tumbler.Application} view The view controller that called this - * method. - * @param {!tumbler.DragEvent} dragEndEvent The DRAG_END event that triggered - * this handler. - */ -tumbler.Trackball.prototype.handleEndDrag = - function(controller, dragEndEvent) { - // Flip the y-coordinate so that the 2D origin is in the lower-left corner. - var frameSize = { width: controller.offsetWidth, - height: controller.offsetHeight }; - var flippedY = { x: dragEndEvent.clientX, - y: frameSize.height - dragEndEvent.clientY }; - this.cameraOrientation_ = tumbler.multQuaternions(this.rollToPoint(flippedY), - this.cameraOrientation_); - controller.setCameraOrientation(this.cameraOrientation_); -}; - -/** - * A utility function to multiply two quaterions. Returns the product q0 * q1. - * This is effectively the same thing as concatenating the two rotations - * represented in each quaternion together. Note that quaternion multiplication - * is NOT commutative: q0 * q1 != q1 * q0. - * @param {!Array.<number>} q0 A 4-element array representing the first - * quaternion. - * @param {!Array.<number>} q1 A 4-element array representing the second - * quaternion. - * @return {Array.<number>} A 4-element array representing the product q0 * q1. - */ -tumbler.multQuaternions = function(q0, q1) { - // Return q0 * q1 (note the order). - var qMult = [ - q0[3] * q1[0] + q0[0] * q1[3] + q0[1] * q1[2] - q0[2] * q1[1], - q0[3] * q1[1] - q0[0] * q1[2] + q0[1] * q1[3] + q0[2] * q1[0], - q0[3] * q1[2] + q0[0] * q1[1] - q0[1] * q1[0] + q0[2] * q1[3], - q0[3] * q1[3] - q0[0] * q1[0] - q0[1] * q1[1] - q0[2] * q1[2] - ]; - return qMult; -}; - -/** - * Real numbers that are less than this distance apart are considered - * equivalent. - * TODO(dspringer): It seems as though there should be a const like this - * in Closure somewhere (goog.math?). - * @type {number} - */ -tumbler.Trackball.DOUBLE_EPSILON = 1.0e-16; diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/transforms.cc b/native_client_sdk/src/examples/fullscreen_tumbler/transforms.cc deleted file mode 100644 index a15963f..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/transforms.cc +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2012 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. - -#include <GLES2/gl2.h> -#include <math.h> -#include <string.h> - -#include "transforms.h" - -namespace transform_4x4 { - -static const GLfloat kPI = 3.1415926535897932384626433832795f; - -void Translate(GLfloat* m, GLfloat tx, GLfloat ty, GLfloat tz) { - m[12] += (m[0] * tx + m[4] * ty + m[8] * tz); - m[13] += (m[1] * tx + m[5] * ty + m[9] * tz); - m[14] += (m[2] * tx + m[6] * ty + m[10] * tz); - m[15] += (m[3] * tx + m[7] * ty + m[11] * tz); -} - -void Frustum(GLfloat* m, - GLfloat left, - GLfloat right, - GLfloat bottom, - GLfloat top, - GLfloat near_z, - GLfloat far_z) { - GLfloat delta_x = right - left; - GLfloat delta_y = top - bottom; - GLfloat delta_z = far_z - near_z; - GLfloat frustum[16]; - - if ((near_z <= 0.0f) || (far_z <= 0.0f) || (delta_x <= 0.0f) || - (delta_y <= 0.0f) || (delta_z <= 0.0f)) - return; - - frustum[0] = 2.0f * near_z / delta_x; - frustum[1] = frustum[2] = frustum[3] = 0.0f; - - frustum[5] = 2.0f * near_z / delta_y; - frustum[4] = frustum[6] = frustum[7] = 0.0f; - - frustum[8] = (right + left) / delta_x; - frustum[9] = (top + bottom) / delta_y; - frustum[10] = -(near_z + far_z) / delta_z; - frustum[11] = -1.0f; - - frustum[14] = -2.0f * near_z * far_z / delta_z; - frustum[12] = frustum[13] = frustum[15] = 0.0f; - - transform_4x4::Multiply(m, frustum, m); -} - -void Perspective(GLfloat* m, - GLfloat fovy, - GLfloat aspect, - GLfloat near_z, - GLfloat far_z) { - GLfloat frustum_w, frustum_h; - - frustum_h = tanf((fovy * 0.5f) / 180.0f * kPI) * near_z; - frustum_w = frustum_h * aspect; - transform_4x4::Frustum( - m, -frustum_w, frustum_w, -frustum_h, frustum_h, near_z, far_z); -} - -void Multiply(GLfloat* m, GLfloat* a, GLfloat* b) { - GLfloat tmp[16]; - // tmp = a . b - GLfloat a0, a1, a2, a3; - a0 = a[0]; - a1 = a[1]; - a2 = a[2]; - a3 = a[3]; - tmp[0] = a0 * b[0] + a1 * b[4] + a2 * b[8] + a3 * b[12]; - tmp[1] = a0 * b[1] + a1 * b[5] + a2 * b[9] + a3 * b[13]; - tmp[2] = a0 * b[2] + a1 * b[6] + a2 * b[10] + a3 * b[14]; - tmp[3] = a0 * b[3] + a1 * b[7] + a2 * b[11] + a3 * b[15]; - - a0 = a[4]; - a1 = a[5]; - a2 = a[6]; - a3 = a[7]; - tmp[4] = a0 * b[0] + a1 * b[4] + a2 * b[8] + a3 * b[12]; - tmp[5] = a0 * b[1] + a1 * b[5] + a2 * b[9] + a3 * b[13]; - tmp[6] = a0 * b[2] + a1 * b[6] + a2 * b[10] + a3 * b[14]; - tmp[7] = a0 * b[3] + a1 * b[7] + a2 * b[11] + a3 * b[15]; - - a0 = a[8]; - a1 = a[9]; - a2 = a[10]; - a3 = a[11]; - tmp[8] = a0 * b[0] + a1 * b[4] + a2 * b[8] + a3 * b[12]; - tmp[9] = a0 * b[1] + a1 * b[5] + a2 * b[9] + a3 * b[13]; - tmp[10] = a0 * b[2] + a1 * b[6] + a2 * b[10] + a3 * b[14]; - tmp[11] = a0 * b[3] + a1 * b[7] + a2 * b[11] + a3 * b[15]; - - a0 = a[12]; - a1 = a[13]; - a2 = a[14]; - a3 = a[15]; - tmp[12] = a0 * b[0] + a1 * b[4] + a2 * b[8] + a3 * b[12]; - tmp[13] = a0 * b[1] + a1 * b[5] + a2 * b[9] + a3 * b[13]; - tmp[14] = a0 * b[2] + a1 * b[6] + a2 * b[10] + a3 * b[14]; - tmp[15] = a0 * b[3] + a1 * b[7] + a2 * b[11] + a3 * b[15]; - memcpy(m, tmp, sizeof(GLfloat) * 4 * 4); -} - -void LoadIdentity(GLfloat* m) { - memset(m, 0, sizeof(GLfloat) * 4 * 4); - m[0] = m[5] = m[10] = m[15] = 1.0f; -} - -} // namespace transform_4x4 diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/transforms.h b/native_client_sdk/src/examples/fullscreen_tumbler/transforms.h deleted file mode 100644 index 70f6d10..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/transforms.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_TRANSFORMS_H_ -#define EXAMPLES_TUMBLER_TRANSFORMS_H_ - -#include <GLES2/gl2.h> - -// A very simple set of 4x4 matrix routines. In all these routines, the input -// matrix is assumed to be a 4x4 of GLfloats. - -namespace transform_4x4 { - -// Pre-multiply |m| with a projection transformation 4x4 matrix from a -// truncated pyramid viewing frustum. -void Frustum(GLfloat* m, - GLfloat left, - GLfloat right, - GLfloat bottom, - GLfloat top, - GLfloat near_z, - GLfloat far_z); - -// Replace |m| with the 4x4 identity matrix. -void LoadIdentity(GLfloat* m); - -// |m| <- |a| . |b|. |m| can point at the same memory as either |a| or |b|. -void Multiply(GLfloat* m, GLfloat* a, GLfloat* b); - -// Pre-multiply |m| with a single-point perspective matrix based on the viewing -// frustum whose view angle is |fovy|. -void Perspective(GLfloat* m, - GLfloat fovy, - GLfloat aspect, - GLfloat near_z, - GLfloat far_z); - -// Pre-multiply |m| with a matrix that represents a translation by |tx|, |ty|, -// |tz|. -void Translate(GLfloat* m, GLfloat tx, GLfloat ty, GLfloat tz); -} // namespace transform_4x4 - -#endif // EXAMPLES_TUMBLER_TRANSFORMS_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.cc b/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.cc deleted file mode 100644 index 3725f3a..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.cc +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) 2012 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. - -#include <stdio.h> - -#include <cstdlib> -#include <cstring> -#include <string> -#include <vector> - -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/size.h" -#include "ppapi/cpp/var.h" - -#include "cube.h" -#include "opengl_context.h" -#include "scripting_bridge.h" -#include "tumbler.h" - -namespace { -const uint32_t kKeyEnter = 0x0D; -const size_t kQuaternionElementCount = 4; -const char* const kArrayStartCharacter = "["; -const char* const kArrayEndCharacter = "]"; -const char* const kArrayDelimiter = ","; - -// Return the value of parameter named |param_name| from |parameters|. If -// |param_name| doesn't exist, then return an empty string. -std::string GetParameterNamed(const std::string& param_name, - const tumbler::MethodParameter& parameters) { - tumbler::MethodParameter::const_iterator i = parameters.find(param_name); - if (i == parameters.end()) { - return ""; - } - return i->second; -} - -// Convert the JSON string |array| into a vector of floats. |array| is -// expected to be a string bounded by '[' and ']' and containing a -// comma-delimited list of numbers. Any errors result in the return of an -// empty array. -std::vector<float> CreateArrayFromJSON(const std::string& json_array) { - std::vector<float> float_array; - size_t array_start_pos = json_array.find_first_of(kArrayStartCharacter); - size_t array_end_pos = json_array.find_last_of(kArrayEndCharacter); - if (array_start_pos == std::string::npos || - array_end_pos == std::string::npos) - return float_array; // Malformed JSON: missing '[' or ']'. - // Pull out the array elements. - size_t token_pos = array_start_pos + 1; - while (token_pos < array_end_pos) { - float_array.push_back(strtof(json_array.data() + token_pos, NULL)); - size_t delim_pos = json_array.find_first_of(kArrayDelimiter, token_pos); - if (delim_pos == std::string::npos) - break; - token_pos = delim_pos + 1; - } - return float_array; -} -} // namespace - -namespace tumbler { - -Tumbler::Tumbler(PP_Instance instance) - : pp::Instance(instance), - full_screen_(this), - has_focus_(false), - cube_(NULL) { - RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); - RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD); -} - -Tumbler::~Tumbler() { - // Destroy the cube view while GL context is current. - opengl_context_->MakeContextCurrent(this); - delete cube_; -} - -bool Tumbler::Init(uint32_t /* argc */, - const char * /* argn */ [], - const char * /* argv */ []) { - // Add all the methods to the scripting bridge. - ScriptingBridge::SharedMethodCallbackExecutor set_orientation_method( - new tumbler::MethodCallback<Tumbler>(this, - &Tumbler::SetCameraOrientation)); - scripting_bridge_.AddMethodNamed("setCameraOrientation", - set_orientation_method); - return true; -} - -void Tumbler::HandleMessage(const pp::Var& message) { - if (!message.is_string()) - return; - scripting_bridge_.InvokeMethod(message.AsString()); -} - -bool Tumbler::HandleInputEvent(const pp::InputEvent& event) { - switch (event.GetType()) { - case PP_INPUTEVENT_TYPE_UNDEFINED: - break; - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - // If we do not yet have focus, return true. In return Chrome will give - // focus to the NaCl embed. - return !has_focus_; - break; - case PP_INPUTEVENT_TYPE_KEYDOWN: - HandleKeyDownEvent(pp::KeyboardInputEvent(event)); - break; - case PP_INPUTEVENT_TYPE_MOUSEUP: - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - case PP_INPUTEVENT_TYPE_MOUSEENTER: - case PP_INPUTEVENT_TYPE_MOUSELEAVE: - case PP_INPUTEVENT_TYPE_WHEEL: - case PP_INPUTEVENT_TYPE_RAWKEYDOWN: - case PP_INPUTEVENT_TYPE_KEYUP: - case PP_INPUTEVENT_TYPE_CHAR: - case PP_INPUTEVENT_TYPE_CONTEXTMENU: - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START: - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE: - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END: - case PP_INPUTEVENT_TYPE_IME_TEXT: - case PP_INPUTEVENT_TYPE_TOUCHSTART: - case PP_INPUTEVENT_TYPE_TOUCHMOVE: - case PP_INPUTEVENT_TYPE_TOUCHEND: - case PP_INPUTEVENT_TYPE_TOUCHCANCEL: - default: - return false; - } - return false; -} - -void Tumbler::DidChangeView(const pp::View& view) { - pp::Rect position = view.GetRect(); - // Note: When switching to fullscreen, the new View position will be a - // rectangle that encompasses the entire screen - e.g. 1900x1200 - with its - // top-left corner at (0, 0). When switching back to the windowed screen the - // position returns to what it was before going to fullscreen. - int cube_width = cube_ ? cube_->width() : 0; - int cube_height = cube_ ? cube_->height() : 0; - if (position.size().width() == cube_width && - position.size().height() == cube_height) { - return; // Size didn't change, no need to update anything. - } - - if (opengl_context_ == NULL) - opengl_context_.reset(new OpenGLContext(this)); - opengl_context_->InvalidateContext(this); - opengl_context_->ResizeContext(position.size()); - if (!opengl_context_->MakeContextCurrent(this)) - return; - if (cube_ == NULL) { - cube_ = new Cube(opengl_context_); - cube_->PrepareOpenGL(); - } - cube_->Resize(position.size().width(), position.size().height()); - DrawSelf(); -} - -void Tumbler::DidChangeFocus(bool focus) { has_focus_ = focus; } - -void Tumbler::DrawSelf() { - if (cube_ == NULL || opengl_context_ == NULL) - return; - opengl_context_->MakeContextCurrent(this); - cube_->Draw(); - opengl_context_->FlushContext(); -} - -void Tumbler::HandleKeyDownEvent(const pp::KeyboardInputEvent& key_event) { - // Pressing the Enter key toggles the view to/from full screen. - if (key_event.GetKeyCode() == kKeyEnter) { - if (!full_screen_.IsFullscreen()) { - if (!full_screen_.SetFullscreen(true)) { - printf("Failed to switch to fullscreen mode.\n"); - } - } else { - if (!full_screen_.SetFullscreen(false)) { - printf("Failed to switch to normal mode.\n"); - } - } - } -} - -void Tumbler::SetCameraOrientation(const tumbler::ScriptingBridge& bridge, - const tumbler::MethodParameter& parameters) { - // |parameters| is expected to contain one object named "orientation", whose - // value is a JSON string that represents an array of four floats. - if (parameters.size() != 1 || cube_ == NULL) - return; - std::string orientation_desc = GetParameterNamed("orientation", parameters); - std::vector<float> orientation = CreateArrayFromJSON(orientation_desc); - if (orientation.size() != kQuaternionElementCount) { - return; - } - cube_->SetOrientation(orientation); - DrawSelf(); -} - -} // namespace tumbler diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.h b/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.h deleted file mode 100644 index 80b4ea9..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_TUMBLER_TUMBLER_H_ -#define EXAMPLES_TUMBLER_TUMBLER_H_ - -#include <pthread.h> -#include <map> -#include <vector> - -#include "ppapi/cpp/fullscreen.h" -#include "ppapi/cpp/instance.h" - -#include "cube.h" -#include "opengl_context.h" -#include "opengl_context_ptrs.h" -#include "scripting_bridge.h" - -namespace pp { -class KeyboardInputEvent; -} // namespace pp - -namespace tumbler { - -class Tumbler : public pp::Instance { - public: - explicit Tumbler(PP_Instance instance); - - // The dtor makes the 3D context current before deleting the cube view, then - // destroys the 3D context both in the module and in the browser. - virtual ~Tumbler(); - - // Called by the browser when the NaCl module is loaded and all ready to go. - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); - - // Called whenever the in-browser window changes size. - virtual void DidChangeView(const pp::View& view); - - // Called by the browser when the NaCl canvas gets or loses focus. - virtual void DidChangeFocus(bool has_focus); - - // Called by the browser to handle the postMessage() call in Javascript. - virtual void HandleMessage(const pp::Var& message); - - // Called by the browser to handle incoming input events. - virtual bool HandleInputEvent(const pp::InputEvent& event); - - // Bind and publish the module's methods to JavaScript. - void InitializeMethods(ScriptingBridge* bridge); - - // Set the camera orientation to the quaternion in |args[0]|. |args| must - // have length at least 1; the first element is expected to be an Array - // object containing 4 floating point number elements (the quaternion). - // This method is bound to the JavaScript "setCameraOrientation" method and - // is called like this: - // module.setCameraOrientation([0.0, 1.0, 0.0, 0.0]); - void SetCameraOrientation(const tumbler::ScriptingBridge& bridge, - const tumbler::MethodParameter& parameters); - - // Called to draw the contents of the module's browser area. - void DrawSelf(); - - private: - // Process key-down input events. - void HandleKeyDownEvent(const pp::KeyboardInputEvent& key_event); - - pp::Fullscreen full_screen_; - bool has_focus_; - - // Browser connectivity and scripting support. - ScriptingBridge scripting_bridge_; - - SharedOpenGLContext opengl_context_; - // Wouldn't it be awesome if we had boost::scoped_ptr<>? - Cube* cube_; -}; - -} // namespace tumbler - -#endif // EXAMPLES_TUMBLER_TUMBLER_H_ diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.js b/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.js deleted file mode 100644 index d8c485f..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2012 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. - -/** - * @fileoverview The tumbler Application object. This object instantiates a - * Trackball object and connects it to the element named |tumbler_content|. - * It also conditionally embeds a debuggable module or a release module into - * the |tumbler_content| element. - */ - -// Requires tumbler -// Requires tumbler.Dragger -// Requires tumbler.Trackball - -var tumbler = tumbler || {}; - -/** - * Constructor for the Application class. Use the run() method to populate - * the object with controllers and wire up the events. - * @constructor - */ -tumbler.Application = function() { - /** - * The native module for the application. This refers to the module loaded - * using the <embed> tag. - * @type {Element} - * @private - */ - this.module_ = null; - - /** - * The trackball object. - * @type {tumbler.Trackball} - * @private - */ - this.trackball_ = null; - - /** - * The mouse-drag event object. - * @type {tumbler.Dragger} - * @private - */ - this.dragger_ = null; -} - -/** - * Called by common.js when the NaCl module has been loaded. - */ -function moduleDidLoad() { - tumbler.application = new tumbler.Application(); - tumbler.application.moduleDidLoad(); -} - -/** - * Called by the module loading function once the module has been loaded. - */ -tumbler.Application.prototype.moduleDidLoad = function() { - this.module_ = document.getElementById('nacl_module'); - - /** - * Set the camera orientation property on the NaCl module. - * @param {Array.<number>} orientation A 4-element array representing the - * camera orientation as a quaternion. - */ - this.module_.setCameraOrientation = function(orientation) { - var methodString = 'setCameraOrientation ' + - 'orientation:' + - JSON.stringify(orientation); - this.postMessage(methodString); - } - - this.trackball_ = new tumbler.Trackball(); - this.dragger_ = new tumbler.Dragger(this.module_); - this.dragger_.addDragListener(this.trackball_); -} - -/** - * Asserts that cond is true; issues an alert and throws an Error otherwise. - * @param {bool} cond The condition. - * @param {String} message The error message issued if cond is false. - */ -tumbler.Application.prototype.assert = function(cond, message) { - if (!cond) { - message = "Assertion failed: " + message; - alert(message); - throw new Error(message); - } -} diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler_module.cc b/native_client_sdk/src/examples/fullscreen_tumbler/tumbler_module.cc deleted file mode 100644 index d34576e..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/tumbler_module.cc +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2012 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. - -#include <GLES2/gl2.h> - -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/gles2/gl2ext_ppapi.h" - -#include "tumbler.h" - -/// The Module class. The browser calls the CreateInstance() method to create -/// an instance of your NaCl module on the web page. The browser creates a new -/// instance for each <embed> tag with type="application/x-nacl". -class TumberModule : public pp::Module { - public: - TumberModule() : pp::Module() {} - virtual ~TumberModule() { glTerminatePPAPI(); } - - /// Called by the browser when the module is first loaded and ready to run. - /// This is called once per module, not once per instance of the module on - /// the page. - virtual bool Init() { - return glInitializePPAPI(get_browser_interface()) == GL_TRUE; - } - - /// Create and return a Tumbler instance object. - /// @param[in] instance The browser-side instance. - /// @return the plugin-side instance. - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new tumbler::Tumbler(instance); - } -}; - -namespace pp { -/// Factory function called by the browser when the module is first loaded. -/// The browser keeps a singleton of this module. It calls the -/// CreateInstance() method on the object you return to make instances. There -/// is one instance per <embed> tag on the page. This is the main binding -/// point for your NaCl module with the browser. -Module* CreateModule() { return new TumberModule(); } -} // namespace pp diff --git a/native_client_sdk/src/examples/fullscreen_tumbler/vector3.js b/native_client_sdk/src/examples/fullscreen_tumbler/vector3.js deleted file mode 100644 index 71d5d9c..0000000 --- a/native_client_sdk/src/examples/fullscreen_tumbler/vector3.js +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2012 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. - -/** - * @fileoverview A 3D vector class. Proviudes some utility functions on - * 3-dimentional vectors. - */ - -// Requires tumbler - -var tumbler = tumbler || {}; - -/** - * Constructor for the Vector3 object. This class contains a 3-tuple that - * represents a vector in 3D space. - * @param {?number} opt_x The x-coordinate for this vector. If null or - * undefined, the x-coordinate value is set to 0. - * @param {?number} opt_y The y-coordinate for this vector. If null or - * undefined, the y-coordinate value is set to 0. - * @param {?number} opt_z The z-coordinate for this vector. If null or - * undefined, the z-coordinate value is set to 0. - * @constructor - */ -tumbler.Vector3 = function(opt_x, opt_y, opt_z) { - /** - * The vector's 3-tuple. - * @type {number} - */ - this.x = opt_x || 0; - this.y = opt_y || 0; - this.z = opt_z || 0; -} - -/** - * Method to return the magnitude of a Vector3. - * @return {number} the magnitude of the vector. - */ -tumbler.Vector3.prototype.magnitude = function() { - return Math.sqrt(this.dot(this)); -} - -/** - * Normalize the vector in-place. - * @return {number} the magnitude of the vector. - */ -tumbler.Vector3.prototype.normalize = function() { - var mag = this.magnitude(); - if (mag < tumbler.Vector3.DOUBLE_EPSILON) - return 0.0; // |this| is equivalent to the 0-vector, don't normalize. - this.scale(1.0 / mag); - return mag; -} - -/** - * Scale the vector in-place by |s|. - * @param {!number} s The scale factor. - */ -tumbler.Vector3.prototype.scale = function(s) { - this.x *= s; - this.y *= s; - this.z *= s; -} - -/** - * Compute the dot product: |this| . v. - * @param {!tumbler.Vector3} v The vector to dot. - * @return {number} the result of |this| . v. - */ -tumbler.Vector3.prototype.dot = function(v) { - return this.x * v.x + this.y * v.y + this.z * v.z; -} - -/** - * Compute the cross product: |this| X v. - * @param {!tumbler.Vector3} v The vector to cross with. - * @return {tumbler.Vector3} the result of |this| X v. - */ -tumbler.Vector3.prototype.cross = function(v) { - var vCross = new tumbler.Vector3(this.y * v.z - this.z * v.y, - this.z * v.x - this.x * v.z, - this.x * v.y - this.y * v.x); - return vCross; -} - -/** - * Real numbers that are less than this distance apart are considered - * equivalent. - * TODO(dspringer): It seems as though there should be a const like this - * in generally available somewhere. - * @type {number} - */ -tumbler.Vector3.DOUBLE_EPSILON = 1.0e-16; diff --git a/native_client_sdk/src/examples/hello_world_interactive/example.dsc b/native_client_sdk/src/examples/hello_world_interactive/example.dsc deleted file mode 100644 index da6e554..0000000 --- a/native_client_sdk/src/examples/hello_world_interactive/example.dsc +++ /dev/null @@ -1,24 +0,0 @@ -{ - 'DISABLE': True, - 'TOOLS': ['newlib', 'glibc', 'pnacl', 'win', 'linux'], - 'TARGETS': [ - { - 'NAME' : 'hello_world_interactive', - 'TYPE' : 'main', - 'SOURCES' : [ - 'hello_world.cc', - 'helper_functions.cc', - 'helper_functions.h' - ], - 'LIBS': ['ppapi_cpp', 'ppapi', 'pthread'] - } - ], - 'DATA': [ - 'example.js', - ], - 'DEST': 'examples', - 'NAME': 'hello_world_interactive', - 'TITLE': 'Interactive Hello World in C++', - 'GROUP': 'Tools' -} - diff --git a/native_client_sdk/src/examples/hello_world_interactive/example.js b/native_client_sdk/src/examples/hello_world_interactive/example.js deleted file mode 100644 index 7058f73..0000000 --- a/native_client_sdk/src/examples/hello_world_interactive/example.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012 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. - -// Called by the common.js module. -function moduleDidLoad() { - // The module is not hidden by default so we can easily see if the plugin - // failed to load. - common.hideModule(); -} - -// Called by the common.js module. -function attachListeners() { - document.getElementById('fortyTwo').addEventListener('click', fortyTwo); - document.getElementById('reverseText').addEventListener('click', reverseText); -} - -function fortyTwo() { - common.naclModule.postMessage('fortyTwo'); -} - -function reverseText() { - // Grab the text from the text box, pass it into reverseText() - var inputBox = document.getElementById('inputBox'); - common.naclModule.postMessage('reverseText:' + inputBox.value); -} - -function handleMessage(e) { - if (typeof e.data === 'string') { - // Received a reversed message. - common.logMessage('Received "' + e.data + '"\n'); - } else if (typeof e.data === 'number') { - // Recived 42. - common.logMessage('Received "' + e.data + '"\n'); - } -} diff --git a/native_client_sdk/src/examples/hello_world_interactive/hello_world.cc b/native_client_sdk/src/examples/hello_world_interactive/hello_world.cc deleted file mode 100644 index cd09c78..0000000 --- a/native_client_sdk/src/examples/hello_world_interactive/hello_world.cc +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2012 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. - -/// @file -/// This example demonstrates loading, running and scripting a very simple NaCl -/// module. To load the NaCl module, the browser first looks for the -/// CreateModule() factory method (at the end of this file). It calls -/// CreateModule() once to load the module code from your .nexe. After the -/// .nexe code is loaded, CreateModule() is not called again. -/// -/// Once the .nexe code is loaded, the browser then calls the -/// HelloWorldModule::CreateInstance() -/// method on the object returned by CreateModule(). It calls CreateInstance() -/// each time it encounters an <embed> tag that references your NaCl module. - -#include <cstdio> -#include <cstring> -#include <string> -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var.h" - -#include "helper_functions.h" - -namespace hello_world { -/// Method name for ReverseText, as seen by JavaScript code. -const char* const kReverseTextMethodId = "reverseText"; - -/// Method name for FortyTwo, as seen by Javascript code. @see FortyTwo() -const char* const kFortyTwoMethodId = "fortyTwo"; - -/// Separator character for the reverseText method. -static const char kMessageArgumentSeparator = ':'; - -/// This is the module's function that invokes FortyTwo and converts the return -/// value from an int32_t to a pp::Var for return. -pp::Var MarshallFortyTwo() { return pp::Var(FortyTwo()); } - -/// This function is passed the arg list from the JavaScript call to -/// @a reverseText. -/// It makes sure that there is one argument and that it is a string, returning -/// an error message if it is not. -/// On good input, it calls ReverseText and returns the result. The result is -/// then sent back via a call to PostMessage. -pp::Var MarshallReverseText(const std::string& text) { - return pp::Var(ReverseText(text)); -} - -/// The Instance class. One of these exists for each instance of your NaCl -/// module on the web page. The browser will ask the Module object to create -/// a new Instance for each occurrence of the <embed> tag that has these -/// attributes: -/// <pre> -/// type="application/x-nacl" -/// nacl="hello_world.nmf" -/// </pre> -class HelloWorldInstance : public pp::Instance { - public: - explicit HelloWorldInstance(PP_Instance instance) : pp::Instance(instance) { - printf("HelloWorldInstance.\n"); - } - virtual ~HelloWorldInstance() {} - - /// Called by the browser to handle the postMessage() call in Javascript. - /// Detects which method is being called from the message contents, and - /// calls the appropriate function. Posts the result back to the browser - /// asynchronously. - /// @param[in] var_message The message posted by the browser. The possible - /// messages are 'fortyTwo' and 'reverseText:Hello World'. Note that - /// the 'reverseText' form contains the string to reverse following a ':' - /// separator. - virtual void HandleMessage(const pp::Var& var_message); -}; - -void HelloWorldInstance::HandleMessage(const pp::Var& var_message) { - if (!var_message.is_string()) { - return; - } - std::string message = var_message.AsString(); - pp::Var return_var; - if (message == kFortyTwoMethodId) { - // Note that no arguments are passed in to FortyTwo. - return_var = MarshallFortyTwo(); - } else if (message.find(kReverseTextMethodId) == 0) { - // The argument to reverseText is everything after the first ':'. - size_t sep_pos = message.find_first_of(kMessageArgumentSeparator); - if (sep_pos != std::string::npos) { - std::string string_arg = message.substr(sep_pos + 1); - return_var = MarshallReverseText(string_arg); - } - } - // Post the return result back to the browser. Note that HandleMessage() is - // always called on the main thread, so it's OK to post the return message - // directly from here. The return post is asynchronous: PostMessage returns - // immediately. - PostMessage(return_var); -} - -/// The Module class. The browser calls the CreateInstance() method to create -/// an instance of your NaCl module on the web page. The browser creates a new -/// instance for each <embed> tag with -/// <code>type="application/x-nacl"</code>. -class HelloWorldModule : public pp::Module { - public: - HelloWorldModule() : pp::Module() { printf("Got here.\n"); } - virtual ~HelloWorldModule() {} - - /// Create and return a HelloWorldInstance object. - /// @param[in] instance a handle to a plug-in instance. - /// @return a newly created HelloWorldInstance. - /// @note The browser is responsible for calling @a delete when done. - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new HelloWorldInstance(instance); - } -}; -} // namespace hello_world - -namespace pp { -/// Factory function called by the browser when the module is first loaded. -/// The browser keeps a singleton of this module. It calls the -/// CreateInstance() method on the object you return to make instances. There -/// is one instance per <embed> tag on the page. This is the main binding -/// point for your NaCl module with the browser. -/// @return new HelloWorldModule. -/// @note The browser is responsible for deleting returned @a Module. -Module* CreateModule() { return new hello_world::HelloWorldModule(); } -} // namespace pp diff --git a/native_client_sdk/src/examples/hello_world_interactive/helper_functions.cc b/native_client_sdk/src/examples/hello_world_interactive/helper_functions.cc deleted file mode 100644 index 8987493..0000000 --- a/native_client_sdk/src/examples/hello_world_interactive/helper_functions.cc +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2012 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. - -#include <algorithm> - -#include "helper_functions.h" - -namespace hello_world { - -int32_t FortyTwo() { return 42; } - -std::string ReverseText(const std::string& text) { - std::string reversed_string(text); - // Use reverse to reverse |reversed_string| in place. - std::reverse(reversed_string.begin(), reversed_string.end()); - return reversed_string; -} -} // namespace hello_world diff --git a/native_client_sdk/src/examples/hello_world_interactive/helper_functions.h b/native_client_sdk/src/examples/hello_world_interactive/helper_functions.h deleted file mode 100644 index 78b03f1..0000000 --- a/native_client_sdk/src/examples/hello_world_interactive/helper_functions.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_HELLO_WORLD_HELPER_FUNCTIONS_H_ -#define EXAMPLES_HELLO_WORLD_HELPER_FUNCTIONS_H_ - -/// @file -/// These functions are stand-ins for your complicated computations which you -/// want to run in native code. We do two very simple things: return 42, and -/// reverse a string. But you can imagine putting more complicated things here -/// which might be difficult or slow to achieve in JavaScript, such as -/// cryptography, artificial intelligence, signal processing, physics modeling, -/// etc. See hello_world.cc for the code which is required for loading a NaCl -/// application and exposing methods to JavaScript. - -#include <ppapi/c/pp_stdint.h> -#include <string> - -namespace hello_world { - -/// This is the module's function that does the work to compute the value 42. -int32_t FortyTwo(); - -/// This function is passed a string and returns a copy of the string with the -/// characters in reverse order. -/// @param[in] text The string to reverse. -/// @return A copy of @a text with the characters in reverse order. -std::string ReverseText(const std::string& text); - -} // namespace hello_world - -#endif // EXAMPLES_HELLO_WORLD_HELPER_FUNCTIONS_H_ diff --git a/native_client_sdk/src/examples/hello_world_interactive/index.html b/native_client_sdk/src/examples/hello_world_interactive/index.html deleted file mode 100644 index bba2379..0000000 --- a/native_client_sdk/src/examples/hello_world_interactive/index.html +++ /dev/null @@ -1,36 +0,0 @@ -<!DOCTYPE html> -<html> - <!-- - Copyright (c) 2012 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> - <meta http-equiv="Pragma" content="no-cache"> - <meta http-equiv="Expires" content="-1"> - <title>{{title}}</title> - <script type="text/javascript" src="common.js"></script> - <script type="text/javascript" src="example.js"></script> -</head> -<body {{attrs}}> - <h1>{{title}}</h1> - <h2>Status: <code id="statusField">NO-STATUS</code></h2> - <p>The Interactive Hello World C++ example demonstrates the basic structure - of all Native Client applications. This example loads a Native Client - module which uses two way interaction with JavaScript whenever a button - is clicked. The NaCl module will respond with the number 42 or the - reversed version of the string in the text box when the appropriate - button is clicked.</p> - <textarea id="inputBox" rows="4" cols="50">Hello World</textarea> - <div> - <button id="fortyTwo">Call fortyTwo()</button> - <button id="reverseText">Call reverseText()</button> - <div/> - <h2>Output:</h2> - <pre id="log" style="font-weight:bold"></pre> - - <!-- The NaCl plugin will be embedded inside the element with id "listener". - See common.js.--> - <div id="listener"></div> -</body> -</html> diff --git a/native_client_sdk/src/examples/pong/example.dsc b/native_client_sdk/src/examples/pong/example.dsc deleted file mode 100644 index d7b0d64..0000000 --- a/native_client_sdk/src/examples/pong/example.dsc +++ /dev/null @@ -1,31 +0,0 @@ -{ - 'DISABLE': True, - 'TOOLS': ['newlib', 'glibc', 'pnacl'], - 'TARGETS': [ - { - 'NAME' : 'pong', - 'TYPE' : 'main', - 'SOURCES' : [ - 'pong_instance.cc', - 'pong_instance.h', - 'pong_input.cc', - 'pong_input.h', - 'pong_model.cc', - 'pong_model.h', - 'pong_module.cc', - 'pong_view.cc', - 'pong_view.h' - ], - 'LIBS': ['ppapi_cpp', 'ppapi', 'pthread'] - } - ], - 'DATA': ['example.js'], - 'DEST': 'examples', - 'NAME': 'pong', - 'TITLE': 'Pong', - 'DESC': """ -The Pong example demonstrates how to create a basic 2D video game. This game -uses up and down arrow keyboard input events to move the paddle.""", - 'INFO': '2D graphics, input events.' -} - diff --git a/native_client_sdk/src/examples/pong/example.js b/native_client_sdk/src/examples/pong/example.js deleted file mode 100644 index cbf90d6..0000000 --- a/native_client_sdk/src/examples/pong/example.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2012 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. - -// Called by the common.js module. -function attachListeners() { - document.getElementById('resetScore').addEventListener('click', resetScore); -} - -function resetScore() { - common.naclModule.postMessage("resetScore"); -} - -// Handle a message coming from the NaCl module. The message payload is -// assumed to contain the current game score. Update the score text -// display with this value. -// Note that errors are also sent to this handler. A message starting -// with 'ERROR' is considered an error, all other strings are assumed -// to be scores. -function handleMessage(message_event) { - if (message_event.data.indexOf('ERROR') == 0) { - document.getElementById('errorLog').innerHTML = message_event.data; - } else { - document.getElementById('score').innerHTML = message_event.data; - } -} diff --git a/native_client_sdk/src/examples/pong/index.html b/native_client_sdk/src/examples/pong/index.html deleted file mode 100644 index 8fca71e..0000000 --- a/native_client_sdk/src/examples/pong/index.html +++ /dev/null @@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright (c) 2012 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> - <meta http-equiv="Pragma" content="no-cache"> - <meta http-equiv="Expires" content="-1"> - <title>{{title}}</title> - <script type="text/javascript" src="common.js"></script> - <script type="text/javascript" src="example.js"></script> -</head> -<body data-width="800" data-height="600" {{attrs}}> - <h1>{{title}}</h1> - <h2>Status: <code id="statusField">NO-STATUS</code></h2> - <!-- The NaCl plugin will be embedded inside the element with id "listener". - See common.js.--> - <div id="listener"></div> - <p id="score"></p> - <button id="resetScore">Reset score</button> - <p id="errorLog"></p> -</body> -</html> diff --git a/native_client_sdk/src/examples/pong/pong_input.cc b/native_client_sdk/src/examples/pong/pong_input.cc deleted file mode 100644 index be58f5d..0000000 --- a/native_client_sdk/src/examples/pong/pong_input.cc +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012 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. - -#include "pong_input.h" - -#include <stdlib.h> - -namespace { - -// Input event key codes. PPAPI uses Windows Virtual key codes. -const uint32_t kUpArrow = 0x26; -const uint32_t kDownArrow = 0x28; - -/** When the distance between the ball and the center of the paddle is within - * kPaddleAIDeadZone pixels, don't move the paddle. This keeps the paddle from - * bouncing if it can move faster than the ball. - */ -const int kPaddleAIDeadZone = 20; - -} - -PongInputKeyboard::PongInputKeyboard(PongInputKeyboardDelegate* delegate) - : delegate_(delegate) {} - -MoveDirection PongInputKeyboard::GetMove(const PongModel& model, - bool is_left_paddle) { - if (delegate_->IsKeyDown(kUpArrow)) - return MOVE_UP; - else if (delegate_->IsKeyDown(kDownArrow)) - return MOVE_DOWN; - else - return MOVE_NONE; -} - -MoveDirection PongInputAI::GetMove(const PongModel& model, - bool is_left_paddle) { - // A highly advanced AI algorithm that moves the paddle toward the y position - // of the ball. - const PaddleModel& paddle = - is_left_paddle ? model.left_paddle() : model.right_paddle(); - int ball_center_y = model.ball().rect.CenterPoint().y(); - int paddle_center_y = paddle.rect.CenterPoint().y(); - int distance_y = labs(paddle_center_y - ball_center_y); - - if (distance_y < kPaddleAIDeadZone) - return MOVE_NONE; - else if (paddle_center_y > ball_center_y) - return MOVE_UP; - else - return MOVE_DOWN; -} diff --git a/native_client_sdk/src/examples/pong/pong_input.h b/native_client_sdk/src/examples/pong/pong_input.h deleted file mode 100644 index 85bcf08..0000000 --- a/native_client_sdk/src/examples/pong/pong_input.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_PONG_PONG_INPUT_H_ -#define EXAMPLES_PONG_PONG_INPUT_H_ - -#include "pong_model.h" - -class PongInput { - public: - virtual ~PongInput() {} - virtual MoveDirection GetMove(const PongModel& model, - bool is_left_paddle) = 0; -}; - -class PongInputKeyboardDelegate { - public: - virtual bool IsKeyDown(int key_code) = 0; -}; - -class PongInputKeyboard : public PongInput { - public: - PongInputKeyboard(PongInputKeyboardDelegate* delegate); - virtual MoveDirection GetMove(const PongModel& model, bool is_left_paddle); - - private: - PongInputKeyboardDelegate* delegate_; // Weak pointer. -}; - -class PongInputAI : public PongInput { - public: - virtual MoveDirection GetMove(const PongModel& model, bool is_left_paddle); -}; - -#endif // EXAMPLES_PONG_PONG_INPUT_H_ diff --git a/native_client_sdk/src/examples/pong/pong_instance.cc b/native_client_sdk/src/examples/pong/pong_instance.cc deleted file mode 100644 index 5f5cf62..0000000 --- a/native_client_sdk/src/examples/pong/pong_instance.cc +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) 2012 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. - -#include <stdio.h> -#include <string.h> -#include <cmath> -#include <string> -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/var.h" - -#include "pong_instance.h" -#include "pong_view.h" - -namespace { - -const uint32_t kUpArrow = 0x26; -const uint32_t kDownArrow = 0x28; - -const int32_t kMaxPointsAllowed = 256; -const int32_t kUpdateInterval = 17; // milliseconds - -const char kResetScoreMethodId[] = "resetScore"; - -} // namespace - -PongInstance::PongInstance(PP_Instance instance) - : pp::Instance(instance), - factory_(this), - model_(NULL), - view_(NULL), - is_initial_view_change_(true) { - // Request to receive input events. - RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_KEYBOARD); -} - -PongInstance::~PongInstance() { - delete right_paddle_input_; - delete left_paddle_input_; - delete view_; - delete model_; -} - -bool PongInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { - model_ = new PongModel(this); - view_ = new PongView(model_); - left_paddle_input_ = new PongInputKeyboard(this); - right_paddle_input_ = new PongInputAI(); - - UpdateScoreDisplay(); - return true; -} - -void PongInstance::DidChangeView(const pp::View& view) { - if (!view_->DidChangeView(this, view, is_initial_view_change_)) { - PostMessage( - pp::Var("ERROR DidChangeView failed. Could not bind graphics?")); - return; - } - - model_->SetCourtSize(view_->GetSize()); - model_->ResetPositions(); - - if (is_initial_view_change_) { - ScheduleUpdate(); - is_initial_view_change_ = false; - } -} - -bool PongInstance::HandleInputEvent(const pp::InputEvent& event) { - if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP || - event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN) { - // By notifying the browser mouse clicks are handled, the application window - // is able to get focus and receive key events. - return true; - } else if (event.GetType() == PP_INPUTEVENT_TYPE_KEYUP) { - pp::KeyboardInputEvent key = pp::KeyboardInputEvent(event); - key_map_[key.GetKeyCode()] = false; - return true; - } else if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { - pp::KeyboardInputEvent key = pp::KeyboardInputEvent(event); - key_map_[key.GetKeyCode()] = true; - return true; - } - return false; -} - -void PongInstance::HandleMessage(const pp::Var& var_message) { - if (!var_message.is_string()) - return; - std::string message = var_message.AsString(); - if (message == kResetScoreMethodId) { - ResetScore(); - } -} - -void PongInstance::OnScoreChanged() { - if (model_->left_score() > kMaxPointsAllowed || - model_->right_score() > kMaxPointsAllowed) { - ResetScore(); - return; - } - - UpdateScoreDisplay(); -} - -void PongInstance::OnPlayerScored() { model_->ResetPositions(); } - -bool PongInstance::IsKeyDown(int key_code) { return key_map_[key_code]; } - -void PongInstance::ScheduleUpdate() { - pp::Module::Get()->core()->CallOnMainThread( - kUpdateInterval, factory_.NewCallback(&PongInstance::UpdateCallback)); -} - -void PongInstance::UpdateCallback(int32_t result) { - // This is the game loop; UpdateCallback schedules another call to itself to - // occur kUpdateInterval milliseconds later. - ScheduleUpdate(); - - MoveDirection left_move = left_paddle_input_->GetMove(*model_, true); - MoveDirection right_move = right_paddle_input_->GetMove(*model_, false); - model_->Update(left_move, right_move); -} - -void PongInstance::ResetScore() { model_->SetScore(0, 0); } - -void PongInstance::UpdateScoreDisplay() { - char buffer[100]; - snprintf(&buffer[0], - sizeof(buffer), - "You %d: Computer %d", - model_->left_score(), - model_->right_score()); - PostMessage(pp::Var(buffer)); -} diff --git a/native_client_sdk/src/examples/pong/pong_instance.h b/native_client_sdk/src/examples/pong/pong_instance.h deleted file mode 100644 index d571b7d..0000000 --- a/native_client_sdk/src/examples/pong/pong_instance.h +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_PONG_PONG_H_ -#define EXAMPLES_PONG_PONG_H_ - -#include <map> -#include "ppapi/cpp/instance.h" -#include "ppapi/utility/completion_callback_factory.h" -#include "pong_input.h" -#include "pong_model.h" - -class PongView; - -class PongInstance : public pp::Instance, - public PongModelDelegate, - public PongInputKeyboardDelegate { - public: - explicit PongInstance(PP_Instance instance); - virtual ~PongInstance(); - - /** Called when the module is initialized. */ - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); - - /** Called when the module's size changes, or when its visibility changes. */ - virtual void DidChangeView(const pp::View& view); - - /** Called when the module is given mouse or keyboard input. */ - virtual bool HandleInputEvent(const pp::InputEvent& event); - - /** Called when JavaScript calls postMessage() on this embedded module. - * The only message handled here is 'resetScore', which resets the score for - * both players to 0. - */ - virtual void HandleMessage(const pp::Var& var_message); - - // PongModelDelegate implementation. - virtual void OnScoreChanged(); - virtual void OnPlayerScored(); - - // PongInputKeyboardDelegate implementation. - virtual bool IsKeyDown(int key_code); - - private: - void ScheduleUpdate(); - void UpdateCallback(int32_t result); - - void ResetScore(); - void UpdateScoreDisplay(); - - pp::CompletionCallbackFactory<PongInstance> factory_; - PongModel* model_; - PongView* view_; - PongInput* left_paddle_input_; - PongInput* right_paddle_input_; - std::map<uint32_t, bool> key_map_; - bool is_initial_view_change_; - - // Disallow copy constructor and assignment operator. - PongInstance(const PongInstance&); - PongInstance& operator=(const PongInstance&); -}; - -#endif // EXAMPLES_PONG_PONG_H_ diff --git a/native_client_sdk/src/examples/pong/pong_model.cc b/native_client_sdk/src/examples/pong/pong_model.cc deleted file mode 100644 index 6af4b11..0000000 --- a/native_client_sdk/src/examples/pong/pong_model.cc +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright (c) 2012 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. - -#include "pong_model.h" - -#include <algorithm> -#include <cassert> -#include <cstdlib> -#include <cstdio> -#include <limits> - -namespace { - -/** Width of the ball in pixels. */ -const int kBallWidth = 20; -/** Height of the ball in pixels. */ -const int kBallHeight = 20; -/** Width of each paddle in pixels. */ -const int kPaddleWidth = 10; -/** Height of each paddle in pixels. */ -const int kPaddleHeight = 99; -/** Starting X position of the ball, in the range [0, 1]. */ -const float kBallStartX = 0.5f; -/** Starting Y position of the ball, in the range [0, 1]. */ -const float kBallStartY = 0.9f; -/** Starting X position of the left paddle, in the range [0, 1]. */ -const float kLeftPaddleStartX = 0.2f; -/** Starting Y position of the left paddle, in the range [0, 1]. */ -const float kLeftPaddleStartY = 0.5f; -/** Starting X position of the right paddle, in the range [0, 1]. */ -const float kRightPaddleStartX = 0.8f; -/** Starting Y position of the right paddle, in the range [0, 1]. */ -const float kRightPaddleStartY = 0.5f; -/** The number of pixels the ball moves along each axis, per update, by - * default. */ -const int kBallUpdateDistance = 4; -/** The number of pixels the paddle moves per update. */ -const int kPaddleUpdateDistance = 4; -/** If the ball hits the paddle in the range [0, kPaddleSpinUp), then the ball - * will bounce up (even if it was moving down). */ -const float kPaddleSpinUp = 0.2f; -/** If the ball hits the paddle in the range (kPaddleSpinDown, 1], then the ball - * will bounce down (even if it was moving up). */ -const float kPaddleSpinDown = 0.8f; - -/** - * Gets the position of an object in a given range. - * This functions ensures that if fraction is in the range [0, 1], then the - * return value will be in the range [0, region_max - object_width]. - * - * fraction == 0.0: return => region_min - * fraction == 0.5: return => (region_min + region_max - object_width) / 2 - * fraction == 1.0: return => region_max - object_width - * - * @param[in] region_min The minimum value of the range. - * @param[in] region_max The maximum value of the range. - * @param[in] object_width The width of the object. - * @param[in] fraction A value in the range [0, 1]. - * @return The left position of the object, in the range [0, region_max - - * object_width]. - */ -int GetFractionalPos(int region_min, - int region_max, - int object_width, - float fraction) { - return region_min + - static_cast<int>((region_max - object_width - region_min) * fraction); -} - -/** - * Set the position of a pp::Rect (i.e. ball or paddle) given the court size. - * - * @param[in] court The bounds to place |object| in. - * @param[in,out] object The object to place in |court|. - * @param[in] x_fraction A value in the range [0, 1]. 0 is on the left, 1 is on - * the right of the court. - * @param[in] y_fraction A value in the range [0, 1]. 0 is on the top, 1 is on - * the bottom of the court. - */ -void SetFractionalPosition(const pp::Rect& court, - pp::Rect* object, - float x_fraction, - float y_fraction) { - object->set_x( - GetFractionalPos(court.x(), court.right(), object->width(), x_fraction)); - object->set_y(GetFractionalPos( - court.y(), court.bottom(), object->height(), y_fraction)); -} - -} // namespace - -PaddleModel::PaddleModel() : rect(kPaddleWidth, kPaddleHeight) {} - -void PaddleModel::SetPosition(const pp::Rect& court, - float x_fraction, - float y_fraction) { - SetFractionalPosition(court, &rect, x_fraction, y_fraction); -} - -void PaddleModel::Move(const pp::Rect& court, - const BallModel& ball, - MoveDirection dir) { - if (dir == MOVE_NONE) - return; - - int dy = dir == MOVE_UP ? -kPaddleUpdateDistance : kPaddleUpdateDistance; - rect.Offset(0, dy); - - // Don't allow the paddle to move on top of the ball. - if (rect.Intersects(ball.rect)) { - rect.Offset(0, -dy); - return; - } - - if (rect.y() < court.y()) { - rect.set_y(court.y()); - } else if (rect.bottom() > court.bottom()) { - rect.set_y(court.bottom() - rect.height()); - } -} - -PaddleCollision PaddleModel::GetPaddleCollision(float collision_y) const { - float paddle_relative_y_fraction = (collision_y - rect.y()) / rect.height(); - if (paddle_relative_y_fraction < kPaddleSpinUp) - return PADDLE_COLLISION_SPIN_UP; - else if (paddle_relative_y_fraction > kPaddleSpinDown) - return PADDLE_COLLISION_SPIN_DOWN; - else - return PADDLE_COLLISION_NORMAL; -} - -BallModel::BallModel() - : rect(kBallWidth, kBallHeight), - dx(kBallUpdateDistance), - dy(kBallUpdateDistance) {} - -void BallModel::SetPosition(const pp::Rect& court, - float x_fraction, - float y_fraction) { - SetFractionalPosition(court, &rect, x_fraction, y_fraction); -} - -void BallModel::Move(float dt) { - rect.Offset(static_cast<int>(dt * dx), static_cast<int>(dt * dy)); -} - -float BallModel::GetPaddleCollisionTime(const PaddleModel& paddle) const { - assert(!rect.Intersects(paddle.rect)); - - // Calculate the range of time when the ball will be colliding with the x - // range of the paddle. - float float_dx = static_cast<float>(dx); - float x_collision_t_min = (paddle.rect.right() - rect.x()) / float_dx; - float x_collision_t_max = (paddle.rect.x() - rect.right()) / float_dx; - if (x_collision_t_min > x_collision_t_max) - std::swap(x_collision_t_min, x_collision_t_max); - - // If the last point in time that the ball is colliding, along the x axis, is - // negative, then the ball would have to move backward to collide with the - // paddle. - if (x_collision_t_max <= 0) - return std::numeric_limits<float>::max(); - - // Calculate the range of time when the ball will be colliding with the y - // range of the paddle. - float float_dy = static_cast<float>(dy); - float y_collision_t_min = (paddle.rect.bottom() - rect.y()) / float_dy; - float y_collision_t_max = (paddle.rect.y() - rect.bottom()) / float_dy; - if (y_collision_t_min > y_collision_t_max) - std::swap(y_collision_t_min, y_collision_t_max); - - // See above for the early out logic. - if (y_collision_t_max <= 0) - return std::numeric_limits<float>::max(); - - // The ball will be colliding with the paddle only when the x range and the y - // ranges intersect. The first time this happens is the whichever happens - // later: entering the x range or entering the y range. - // However, if either range's maximum is less than this value, then the - // ranges are disjoint, and the ball does not collide with the paddle (it - // will pass by it instead). - float max_of_mins = std::max(x_collision_t_min, y_collision_t_min); - if (x_collision_t_max > max_of_mins && y_collision_t_max > max_of_mins) - return max_of_mins; - - return std::numeric_limits<float>::max(); -} - -float BallModel::GetCourtCollisionTime(const pp::Rect& court) const { - assert(rect.y() >= court.y()); - assert(rect.bottom() <= court.bottom()); - - // When the ball is moving up, only check for collision with the top of the - // court. Likewise, if the ball is moving down only check for collision with - // the bottom of the court. - float y_collision_t = - dy < 0 ? (court.y() - rect.y()) / static_cast<float>(dy) - : (court.bottom() - rect.bottom()) / static_cast<float>(dy); - - return y_collision_t; -} - -void BallModel::ApplyPaddleCollision(PaddleCollision collision) { - switch (collision) { - case PADDLE_COLLISION_SPIN_UP: - dy -= kBallUpdateDistance; - if (dy == 0) - dy -= kBallUpdateDistance; - break; - case PADDLE_COLLISION_SPIN_DOWN: - dy += kBallUpdateDistance; - if (dy == 0) - dy += kBallUpdateDistance; - break; - case PADDLE_COLLISION_NORMAL: - default: - break; - } -} - -PongModel::PongModel(PongModelDelegate* delegate) - : delegate_(delegate), left_score_(0), right_score_(0) {} - -void PongModel::SetCourtSize(const pp::Size& size) { court_.set_size(size); } - -void PongModel::SetScore(int left_score, int right_score) { - left_score_ = left_score; - right_score_ = right_score; - delegate_->OnScoreChanged(); -} - -void PongModel::ResetPositions() { - ball_.SetPosition(court_, kBallStartX, kBallStartY); - left_paddle_.SetPosition(court_, kLeftPaddleStartX, kLeftPaddleStartY); - right_paddle_.SetPosition(court_, kRightPaddleStartX, kRightPaddleStartY); - ball_.dx = kBallUpdateDistance; - ball_.dy = kBallUpdateDistance; -} - -void PongModel::Update(MoveDirection left_movement, - MoveDirection right_movement) { - left_paddle_.Move(court_, ball_, left_movement); - right_paddle_.Move(court_, ball_, right_movement); - UpdateBall(); - - if (ball_.rect.x() < court_.x()) { - right_score_++; - delegate_->OnScoreChanged(); - delegate_->OnPlayerScored(); - } else if (ball_.rect.right() > court_.right()) { - left_score_++; - delegate_->OnScoreChanged(); - delegate_->OnPlayerScored(); - } -} - -void PongModel::UpdateBall() { - // If the ball's update distance is large enough, it could collide with - // multiple objects in one update. - // To detect this, we calculate when the ball will collide with all objects. - // If any collisions occur in this update, move the ball to this collision - // point, and repeat with the rest of the time that's left. - float dt = 1; - while (dt > 0) { - float left_paddle_t = ball_.GetPaddleCollisionTime(left_paddle_); - float right_paddle_t = ball_.GetPaddleCollisionTime(right_paddle_); - float min_paddle_t = std::min(left_paddle_t, right_paddle_t); - float court_t = ball_.GetCourtCollisionTime(court_); - float min_t = std::min(court_t, min_paddle_t); - - if (min_t > dt) { - // The ball doesn't hit anything this time. - ball_.Move(dt); - return; - } - - // Move the ball up to the point of collision. - ball_.Move(min_t); - dt -= min_t; - - if (court_t < min_paddle_t) { - // Just bounce off the court, flip ball's dy. - ball_.dy = -ball_.dy; - } else { - // Bouncing off the paddle flips the ball's dx, but also can potentially - // add "spin" when the ball bounces off the top or bottom of the paddle. - ball_.dx = -ball_.dx; - - float collision_y = ball_.rect.y() + ball_.rect.height() / 2; - PaddleCollision paddle_collision; - if (left_paddle_t < right_paddle_t) - paddle_collision = left_paddle_.GetPaddleCollision(collision_y); - else - paddle_collision = right_paddle_.GetPaddleCollision(collision_y); - - ball_.ApplyPaddleCollision(paddle_collision); - } - } -} diff --git a/native_client_sdk/src/examples/pong/pong_model.h b/native_client_sdk/src/examples/pong/pong_model.h deleted file mode 100644 index 789f69b..0000000 --- a/native_client_sdk/src/examples/pong/pong_model.h +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_PONG_PONG_MODEL_H_ -#define EXAMPLES_PONG_PONG_MODEL_H_ - -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/size.h" - -struct BallModel; - -enum MoveDirection { - MOVE_NONE, - MOVE_UP, - MOVE_DOWN -}; - -enum PaddleCollision { - PADDLE_COLLISION_NORMAL, - PADDLE_COLLISION_SPIN_UP, - PADDLE_COLLISION_SPIN_DOWN -}; - -struct PaddleModel { - PaddleModel(); - - /** - * Set the position of the paddle, given a court. - * @param[in] court The bounds to place the paddle in. - * @param[in] x_fraction A value in the range [0, 1]. 0 is on the left, 1 is - * on the right of the court. - * @param[in] y_fraction A value in the range [0, 1]. 0 is on the top, 1 is on - * the bottom of the court. - */ - void SetPosition(const pp::Rect& court, float x_fraction, float y_fraction); - - /** - * Move the paddle, given |dir|. The paddle will not move in if it will - * collide with |ball| or exit |court| after moving. - * @param[in] court The bounds to move the ball in. - * @param[in] ball The ball to avoid colliding with. - * @param[in] dir The direction to move the paddle. - */ - void Move(const pp::Rect& court, const BallModel& ball, MoveDirection dir); - - /** - * Given that a ball has collided with this paddle, determine if "spin" - * should be applied to the ball. - * @param[in] collision_y The y-coordinate of the ball that collided with the - * paddle. - * @return The paddle collision type. - */ - PaddleCollision GetPaddleCollision(float collision_y) const; - - pp::Rect rect; -}; - -struct BallModel { - BallModel(); - - /** - * Set the position of the ball, given a court. - * @param[in] court The bounds to place the ball in. - * @param[in] x_fraction A value in the range [0, 1]. 0 is on the left, 1 is - * on the right of the court. - * @param[in] y_fraction A value in the range [0, 1]. 0 is on the top, 1 is on - * the bottom of the court. - */ - void SetPosition(const pp::Rect& court, float x_fraction, float y_fraction); - - /** Move the ball in its current direction. - * @param[in] dt A time delta value in the range [0, 1]. The ball will move - * its update distance, multiplied by dt for each axis. - * For example, if dt==1, the ball will move its full update distance. If - * dt==0.5, it will move half its update distance, etc. - */ - void Move(float dt); - - /** Given that the ball collided with the paddle, determine how it should - * bounce off it, applying "spin". If the ball hits the top of the paddle it - * will spin up, if the ball hits the bottom of the paddle it will spin down. - * @param[in] collision The type of collision with the paddle. - */ - void ApplyPaddleCollision(PaddleCollision collision); - - /** Calculate the time (as a fraction of the number of updates), until the - * ball collides with |paddle|. - * @param[in] paddle The paddle to test for collision with. - * @return The time (maybe negative) when the ball will collide with the - * paddle. - * If the time is in the range [0, 1], the ball will collide with the - * paddle during this update. - * If the time is > 1, then the ball will collide with the paddle after - * ceil(time) updates, assuming the paddle doesn't move. - * Because we want to find the most recent collision (i.e. smallest time - * value), we use the value FLT_MAX to represent a collision that will - * never happen (the paddle is behind the ball). - */ - float GetPaddleCollisionTime(const PaddleModel& paddle) const; - - /** Calculate the time (as a fraction of the number of updates), until the - * ball collides with |court|. - * @param[in] court The bounds of the court to test for collision with. - * @return The time (maybe negative) when the ball will collide with bottom - * or top of the court. - * @see GetPaddleCollisionTime to understand the meaning of the return time. - */ - float GetCourtCollisionTime(const pp::Rect& court) const; - - pp::Rect rect; - int dx; - int dy; -}; - -class PongModelDelegate { - public: - /** Called when the score changes, whether due to PongModel::SetScore, or - * when a player scores. */ - virtual void OnScoreChanged() = 0; - /** Called only when a player scores, not when the score is changed - * programmatically. */ - virtual void OnPlayerScored() = 0; -}; - -class PongModel { - public: - explicit PongModel(PongModelDelegate* delegate); - - void SetCourtSize(const pp::Size& size); - void SetScore(int left_score, int right_score); - void ResetPositions(); - void Update(MoveDirection left_movement, MoveDirection right_movement); - - const PaddleModel& left_paddle() const { return left_paddle_; } - const PaddleModel& right_paddle() const { return right_paddle_; } - const BallModel& ball() const { return ball_; } - int left_score() const { return left_score_; } - int right_score() const { return right_score_; } - - private: - void UpdateBall(); - - PongModelDelegate* delegate_; // Weak pointer. - PaddleModel left_paddle_; - PaddleModel right_paddle_; - BallModel ball_; - pp::Rect court_; - int left_score_; - int right_score_; -}; - -#endif // EXAMPLES_PONG_PONG_MODEL_H_ diff --git a/native_client_sdk/src/examples/pong/pong_module.cc b/native_client_sdk/src/examples/pong/pong_module.cc deleted file mode 100644 index 9d99526..0000000 --- a/native_client_sdk/src/examples/pong/pong_module.cc +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2012 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. - -#include <ppapi/cpp/module.h> - -#include "pong_instance.h" - -// The Module class. The browser calls the CreateInstance() method to create -// an instance of your NaCl module on the web page. The browser creates a new -// instance for each <embed> tag with type="application/x-nacl". -class PongModule : public pp::Module { - public: - PongModule() : pp::Module() {} - virtual ~PongModule() {} - - // Create and return a PongInstance object. - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new PongInstance(instance); - } -}; - -// Factory function called by the browser when the module is first loaded. -// The browser keeps a singleton of this module. It calls the -// CreateInstance() method on the object you return to make instances. There -// is one instance per <embed> tag on the page. This is the main binding -// point for your NaCl module with the browser. -namespace pp { -Module* CreateModule() { return new PongModule(); } -} // namespace pp diff --git a/native_client_sdk/src/examples/pong/pong_view.cc b/native_client_sdk/src/examples/pong/pong_view.cc deleted file mode 100644 index 1c76d73..0000000 --- a/native_client_sdk/src/examples/pong/pong_view.cc +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2012 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. - -#include "pong_view.h" - -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/point.h" - -namespace { - -const uint32_t kBlack = 0xff000000; -const uint32_t kWhite = 0xffffffff; - -pp::Rect ClipRect(const pp::Rect& rect, const pp::Rect& clip) { - return clip.Intersect(rect); -} - -} // namespace - -PongView::PongView(PongModel* model) - : factory_(this), - model_(model), - graphics_2d_(NULL), - pixel_buffer_(NULL), - needs_erase_(false) {} - -PongView::~PongView() { - delete graphics_2d_; - delete pixel_buffer_; -} - -bool PongView::DidChangeView(pp::Instance* instance, - const pp::View& view, - bool first_view_change) { - pp::Size old_size = GetSize(); - pp::Size new_size = view.GetRect().size(); - if (old_size == new_size) - return true; - - delete graphics_2d_; - graphics_2d_ = - new pp::Graphics2D(instance, new_size, true); // is_always_opaque - if (!instance->BindGraphics(*graphics_2d_)) { - delete graphics_2d_; - graphics_2d_ = NULL; - return false; - } - - // Create a new pixel buffer, the same size as the graphics context. We'll - // write to this buffer directly, and copy regions of it to the graphics - // context's backing store to draw to the screen. - delete pixel_buffer_; - pixel_buffer_ = new pp::ImageData(instance, - PP_IMAGEDATAFORMAT_BGRA_PREMUL, - new_size, - true); // init_to_zero - - needs_erase_ = false; - - if (first_view_change) - DrawCallback(0); // Start the draw loop. - - return true; -} - -pp::Size PongView::GetSize() const { - return graphics_2d_ ? graphics_2d_->size() : pp::Size(); -} - -void PongView::DrawCallback(int32_t result) { - assert(graphics_2d_); - assert(pixel_buffer_); - - if (needs_erase_) { - EraseBall(old_ball_); - ErasePaddle(old_left_paddle_); - ErasePaddle(old_right_paddle_); - } - - // Draw the image to pixel_buffer_. - DrawBall(model_->ball()); - DrawPaddle(model_->left_paddle()); - DrawPaddle(model_->right_paddle()); - - // Paint to the graphics context's backing store. - if (needs_erase_) { - // Update the regions for the old positions of the ball and both paddles, - // as well as the new positions. - PaintRectToGraphics2D(old_ball_.rect, model_->ball().rect); - PaintRectToGraphics2D(old_left_paddle_.rect, model_->left_paddle().rect); - PaintRectToGraphics2D(old_right_paddle_.rect, model_->right_paddle().rect); - } else { - // Only update the regions for the new positions. The old positions are - // invalid. - PaintRectToGraphics2D(model_->ball().rect); - PaintRectToGraphics2D(model_->left_paddle().rect); - PaintRectToGraphics2D(model_->right_paddle().rect); - } - - // Save the locations of the ball and paddles to erase next time. - old_ball_ = model_->ball(); - old_left_paddle_ = model_->left_paddle(); - old_right_paddle_ = model_->right_paddle(); - needs_erase_ = true; - - // Graphics2D::Flush writes all paints to the graphics context's backing - // store. When it is finished, it calls the callback. By hooking our draw - // function to the Flush callback, we will be able to draw as quickly as - // possible. - graphics_2d_->Flush(factory_.NewCallback(&PongView::DrawCallback)); -} - -void PongView::DrawRect(const pp::Rect& rect, uint32_t color) { - assert(pixel_buffer_); - uint32_t* pixel_data = static_cast<uint32_t*>(pixel_buffer_->data()); - assert(pixel_data); - - int width = pixel_buffer_->size().width(); - int height = pixel_buffer_->size().height(); - - // We shouldn't be drawing rectangles outside of the pixel buffer bounds, - // but just in case, clip the rectangle first. - pp::Rect clipped_rect = ClipRect(rect, pp::Rect(pixel_buffer_->size())); - int offset = clipped_rect.y() * width + clipped_rect.x(); - - for (int y = 0; y < clipped_rect.height(); ++y) { - for (int x = 0; x < clipped_rect.width(); ++x) { - // As a sanity check, make sure that we aren't about to stomp memory. - assert(offset >= 0 && offset < width * height); - pixel_data[offset++] = color; - } - offset += width - clipped_rect.width(); - } -} - -void PongView::DrawBall(const BallModel& ball) { - assert(pixel_buffer_); - uint32_t* pixel_data = static_cast<uint32_t*>(pixel_buffer_->data()); - assert(pixel_data); - - int width = pixel_buffer_->size().width(); - int height = pixel_buffer_->size().height(); - - // We shouldn't be drawing outside of the pixel buffer bounds, but just in - // case, clip the rectangle first. - pp::Rect clipped_rect = ClipRect(ball.rect, pp::Rect(pixel_buffer_->size())); - - int radius2 = (ball.rect.width() / 2) * (ball.rect.width() / 2); - pp::Point ball_center = ball.rect.CenterPoint() - clipped_rect.point(); - - int offset = clipped_rect.y() * width + clipped_rect.x(); - - for (int y = 0; y < clipped_rect.height(); ++y) { - for (int x = 0; x < clipped_rect.width(); ++x) { - int distance_x = x - ball_center.x(); - int distance_y = y - ball_center.y(); - int distance2 = distance_x * distance_x + distance_y * distance_y; - - // As a sanity check, make sure that we aren't about to stomp memory. - assert(offset >= 0 && offset < width * height); - // Common optimization here: compare the distance from the center of the - // ball to the current pixel squared versus the radius squared. This way - // we avoid the sqrt. - pixel_data[offset++] = distance2 <= radius2 ? kWhite : kBlack; - } - - offset += width - clipped_rect.width(); - } -} - -void PongView::DrawPaddle(const PaddleModel& paddle) { - DrawRect(paddle.rect, kWhite); -} - -void PongView::EraseBall(const BallModel& ball) { DrawRect(ball.rect, kBlack); } - -void PongView::ErasePaddle(const PaddleModel& paddle) { - DrawRect(paddle.rect, kBlack); -} - -void PongView::PaintRectToGraphics2D(const pp::Rect& rect) { - const pp::Point top_left(0, 0); - graphics_2d_->PaintImageData(*pixel_buffer_, top_left, rect); -} - -void PongView::PaintRectToGraphics2D(const pp::Rect& old_rect, - const pp::Rect& rect) { - // Try a little optimization here: since the paddles and balls don't move - // very much per frame, they often will overlap their old bounding boxes. When - // they do, update the union of the two boxes to save some time. - if (old_rect.Intersects(rect)) { - PaintRectToGraphics2D(old_rect.Union(rect)); - } else { - PaintRectToGraphics2D(old_rect); - PaintRectToGraphics2D(rect); - } -} diff --git a/native_client_sdk/src/examples/pong/pong_view.h b/native_client_sdk/src/examples/pong/pong_view.h deleted file mode 100644 index 7197d3a..0000000 --- a/native_client_sdk/src/examples/pong/pong_view.h +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012 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 EXAMPLES_PONG_VIEW_H_ -#define EXAMPLES_PONG_VIEW_H_ - -#include "ppapi/cpp/rect.h" -#include "ppapi/utility/completion_callback_factory.h" -#include "pong_model.h" - -namespace pp { -class Graphics2D; -class ImageData; -class Instance; -class Size; -class View; -} // namespace pp - -class PongView { - public: - explicit PongView(PongModel* model); - ~PongView(); - - bool DidChangeView(pp::Instance* instance, - const pp::View& view, - bool first_view_change); - pp::Size GetSize() const; - void StartDrawLoop(); - - private: - void DrawCallback(int32_t result); - void DrawRect(const pp::Rect& rect, uint32_t color); - void DrawBall(const BallModel& ball); - void DrawPaddle(const PaddleModel& paddle); - void EraseBall(const BallModel& ball); - void ErasePaddle(const PaddleModel& paddle); - void PaintRectToGraphics2D(const pp::Rect& rect); - void PaintRectToGraphics2D(const pp::Rect& old_rect, const pp::Rect& rect); - - pp::CompletionCallbackFactory<PongView> factory_; - PongModel* model_; // Weak pointer. - pp::Graphics2D* graphics_2d_; - pp::ImageData* pixel_buffer_; - - bool needs_erase_; - PaddleModel old_left_paddle_; - PaddleModel old_right_paddle_; - BallModel old_ball_; -}; - -#endif // EXAMPLES_PONG_VIEW_H_ |