├── Makefile.Linux ├── Makefile.Darwin ├── examples ├── gles │ ├── assets │ │ ├── basemap.png │ │ └── lightmap.png │ ├── shaders │ │ ├── ch8-simple-vertexshader.fs │ │ ├── m3d-vshader.sl │ │ ├── ch8-simple-vertexshader.vs │ │ ├── ch9-vshader.sl │ │ ├── ch9-fshader.sl │ │ ├── ch10-vshader.sl │ │ ├── ch9-texture2d-fshader.sl │ │ ├── ch9-texture2d-vshader.sl │ │ ├── ch10-fshader.sl │ │ └── m3d-fshader.sl │ ├── metatunnel-3d.js │ ├── shaderutil.js │ ├── lib │ │ ├── v3d.js │ │ ├── core.js │ │ └── matrix.js │ ├── ch8-simple-vertexshader.js │ ├── ch2-hello-triangle.js │ ├── ch9-simple-texture-cubemap.js │ ├── ch9-simple-texture2d.js │ ├── ch10-multitexture.js │ ├── metaballs │ │ └── metaballs.js │ └── common.js ├── example1.js └── example2.js ├── glutbindings ├── glutInit.template ├── glutbind.h ├── glutTimerFunc.template ├── glutbind.py └── glut.h ├── utils.h ├── glbindings ├── glbind.h ├── make_json.py └── glbind.py ├── glesbindings ├── glesbind.h ├── glew_desktop_shim.h ├── make_json.py ├── gles_desktop_shim.h └── glesbind.py ├── glubindings ├── glubind.h ├── glubind.py └── glu.h ├── v8-typed-array ├── wscript ├── package.json ├── README.md └── typed-array.cc ├── v8-gl.h ├── main.cpp ├── Makefile ├── imageloader.h ├── utils.cpp ├── README.mkd ├── imageloader.cpp └── v8-gl.cpp /Makefile.Linux: -------------------------------------------------------------------------------- 1 | LIBS = v8/libv8.a -lpthread -lglut -lGLU -lGL 2 | -------------------------------------------------------------------------------- /Makefile.Darwin: -------------------------------------------------------------------------------- 1 | LIBS = v8/libv8.a -lpthread -framework OpenGL -framework GLUT 2 | -------------------------------------------------------------------------------- /examples/gles/assets/basemap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philogb/v8-gl/HEAD/examples/gles/assets/basemap.png -------------------------------------------------------------------------------- /examples/gles/assets/lightmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philogb/v8-gl/HEAD/examples/gles/assets/lightmap.png -------------------------------------------------------------------------------- /examples/gles/shaders/ch8-simple-vertexshader.fs: -------------------------------------------------------------------------------- 1 | void main() { 2 | gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); 3 | } -------------------------------------------------------------------------------- /examples/gles/shaders/m3d-vshader.sl: -------------------------------------------------------------------------------- 1 | attribute vec4 pos; 2 | 3 | void main() { 4 | gl_Position = vec4(pos.x * float(370), pos.y * float(240), 0.0, 1.0); 5 | } -------------------------------------------------------------------------------- /glutbindings/glutInit.template: -------------------------------------------------------------------------------- 1 | 2 | Handle GLUTInitCallback(const Arguments& args) { 3 | glutInit(( int* ) pargc_, ( char** ) argv_); 4 | return v8::Undefined(); 5 | } 6 | -------------------------------------------------------------------------------- /examples/gles/shaders/ch8-simple-vertexshader.vs: -------------------------------------------------------------------------------- 1 | uniform mat4 u_mvpMatrix; 2 | attribute vec4 a_position; 3 | void main() { 4 | gl_Position = u_mvpMatrix * a_position; 5 | //gl_PointSize = 1 6 | } -------------------------------------------------------------------------------- /examples/gles/shaders/ch9-vshader.sl: -------------------------------------------------------------------------------- 1 | attribute vec4 a_position; 2 | attribute vec3 a_normal; 3 | varying vec3 v_normal; 4 | void main() 5 | { 6 | gl_Position = a_position; 7 | v_normal = a_normal; 8 | } 9 | -------------------------------------------------------------------------------- /examples/gles/shaders/ch9-fshader.sl: -------------------------------------------------------------------------------- 1 | /*precision mediump float;*/ 2 | varying vec3 v_normal; 3 | uniform samplerCube s_texture; 4 | void main() 5 | { 6 | gl_FragColor = textureCube(s_texture, v_normal); 7 | } 8 | -------------------------------------------------------------------------------- /examples/gles/shaders/ch10-vshader.sl: -------------------------------------------------------------------------------- 1 | attribute vec4 a_position; 2 | attribute vec2 a_texCoord; 3 | varying vec2 v_texCoord; 4 | void main() 5 | { 6 | gl_Position = a_position; 7 | v_texCoord = a_texCoord; 8 | } 9 | -------------------------------------------------------------------------------- /examples/gles/shaders/ch9-texture2d-fshader.sl: -------------------------------------------------------------------------------- 1 | /*precision mediump float;*/ 2 | varying vec2 v_texCoord; 3 | uniform sampler2D s_texture; 4 | void main() 5 | { 6 | gl_FragColor = texture2D(s_texture, v_texCoord); 7 | } -------------------------------------------------------------------------------- /examples/gles/shaders/ch9-texture2d-vshader.sl: -------------------------------------------------------------------------------- 1 | attribute vec4 a_position; 2 | attribute vec2 a_texCoord; 3 | varying vec2 v_texCoord; 4 | void main() 5 | { 6 | gl_Position = a_position; 7 | v_texCoord = a_texCoord; 8 | } 9 | -------------------------------------------------------------------------------- /utils.h: -------------------------------------------------------------------------------- 1 | #ifndef V8GLUTILS_H_ 2 | #define V8GLUTILS_H_ 3 | 4 | namespace V8GLUtils { 5 | void setRootPath(char* program_path, char* jsfile_path); 6 | 7 | char* getRootPath(void); 8 | char* getRealPath(char* file_path); 9 | 10 | char *pushRootPath(char *new_path); 11 | void popRootPath(char *old_path); 12 | }; 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /glbindings/glbind.h: -------------------------------------------------------------------------------- 1 | /* 2 | * glbind.h 3 | * 4 | * Created on: Jun 15, 2009 5 | * Author: nicolas 6 | */ 7 | 8 | #ifndef GLBIND_H_ 9 | #define GLBIND_H_ 10 | 11 | #include 12 | 13 | class GlFactory { 14 | public: 15 | static v8::Handle createGl(void); 16 | 17 | static v8::Persistent self_; 18 | }; 19 | 20 | #endif /* GLBIND_H_ */ 21 | -------------------------------------------------------------------------------- /examples/gles/shaders/ch10-fshader.sl: -------------------------------------------------------------------------------- 1 | /*precision mediump float;*/ 2 | varying vec2 v_texCoord; 3 | uniform sampler2D s_baseMap; 4 | uniform sampler2D s_lightMap; 5 | void main() 6 | { 7 | vec4 baseColor; 8 | vec4 lightColor; 9 | 10 | baseColor = texture2D(s_baseMap, v_texCoord); 11 | lightColor = texture2D(s_lightMap, v_texCoord); 12 | gl_FragColor = baseColor * (lightColor + 0.25); 13 | } 14 | -------------------------------------------------------------------------------- /glesbindings/glesbind.h: -------------------------------------------------------------------------------- 1 | /* 2 | * glesbind.h 3 | * 4 | */ 5 | 6 | #ifndef GLESBIND_H_ 7 | #define GLESBIND_H_ 8 | 9 | #include 10 | #include "../utils.h" 11 | #include "../imageloader.h" 12 | 13 | class GlesFactory { 14 | public: 15 | static v8::Handle createGles(void); 16 | static v8::Persistent gles_persistent_context; 17 | static v8::Persistent self_; 18 | }; 19 | 20 | #endif /* GLESBIND_H_ */ 21 | -------------------------------------------------------------------------------- /glubindings/glubind.h: -------------------------------------------------------------------------------- 1 | /* 2 | * glubind.h 3 | * 4 | * Created on: Jun 15, 2009 5 | * Author: nicolas 6 | */ 7 | 8 | #ifndef GLUBIND_H_ 9 | #define GLUBIND_H_ 10 | 11 | 12 | #include 13 | 14 | #ifdef __APPLE__ 15 | #include 16 | #include 17 | #else 18 | #include 19 | #endif 20 | 21 | #include 22 | 23 | using namespace std; 24 | using namespace v8; 25 | 26 | Handle createGlu(void); 27 | 28 | #endif /* GLUBIND_H_ */ 29 | -------------------------------------------------------------------------------- /v8-typed-array/wscript: -------------------------------------------------------------------------------- 1 | from os import mkdir 2 | from os import symlink 3 | from os import remove 4 | from os.path import lexists 5 | 6 | srcdir = '.' 7 | blddir = 'build' 8 | VERSION = '0.0.2' 9 | 10 | def set_options(opt): 11 | opt.tool_options('compiler_cxx') 12 | 13 | def configure(conf): 14 | conf.check_tool('compiler_cxx') 15 | conf.check_tool('node_addon') 16 | 17 | def build(bld): 18 | obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') 19 | obj.target = 'typed-array' 20 | obj.source = 'typed-array.cc' 21 | -------------------------------------------------------------------------------- /v8-typed-array/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typed-array", 3 | "description": "Typed Array implementation for V8 and Node.js", 4 | "version": "0.0.2", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/tlrobinson/v8-typed-array.git" 8 | }, 9 | "keywords": ["buffer", "typed array", "webgl"], 10 | "author": "Tom Robinson (http://tlrobinson.net/)", 11 | "main": "build/default/typed-array.node", 12 | "scripts": { "install": "node-waf configure build" }, 13 | "engines": { 14 | "node": "*" 15 | } 16 | } -------------------------------------------------------------------------------- /v8-gl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * v8-gl.h 3 | */ 4 | 5 | #ifndef V8GL_H_ 6 | #define V8GL_H_ 7 | 8 | #include 9 | #include 10 | 11 | #include "utils.h" 12 | #ifdef BUILD_GL_BINDINGS 13 | #include "glbindings/glbind.h" 14 | #endif 15 | #ifdef BUILD_GLES_BINDINGS 16 | #include "glesbindings/glesbind.h" 17 | #endif 18 | #ifdef BUILD_GLU_BINDINGS 19 | #include "glubindings/glubind.h" 20 | #endif 21 | #ifdef BUILD_GLUT_BINDINGS 22 | #include "glutbindings/glutbind.h" 23 | #endif 24 | 25 | using namespace std; 26 | using namespace v8; 27 | 28 | class V8GL { 29 | 30 | public: 31 | bool initialize(int* pargc, char** argv, string scriptname); 32 | bool executeScript(string scriptname); 33 | static const char* ToCString(const v8::String::Utf8Value& value); 34 | static void ReportException(TryCatch* try_catch); 35 | 36 | //keep a reference to the global context. 37 | static Persistent context; 38 | }; 39 | 40 | #endif /* V8GL_H_ */ 41 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "v8-gl.h" 4 | #include 5 | 6 | using namespace v8; 7 | 8 | void ParseOptions(int argc, 9 | char* argv[], 10 | string* file) { 11 | for (int i = 1; i < argc; i++) { 12 | std::string arg = argv[i]; 13 | size_t index = arg.find('=', 0); 14 | if (index == std::string::npos) { 15 | *file = arg; 16 | } else { 17 | std::string key = arg.substr(0, index); 18 | std::string value = arg.substr(index+1); 19 | } 20 | } 21 | } 22 | 23 | int main(int argc, char* argv[]) { 24 | string file; 25 | ParseOptions(argc, argv, &file); 26 | if (file.empty()) { 27 | fprintf(stderr, "No script was specified.\n"); 28 | return 1; 29 | } 30 | 31 | V8GL v8gl; 32 | if(!v8gl.initialize(&argc, argv, file)) { 33 | fprintf(stderr, "Error initializing script.\n"); 34 | return 1; 35 | } 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /glutbindings/glutbind.h: -------------------------------------------------------------------------------- 1 | /* 2 | * glutbind.h 3 | * 4 | * Created on: Jun 15, 2009 5 | * Author: nicolas 6 | */ 7 | 8 | #ifndef GLUTBIND_H_ 9 | #define GLUTBIND_H_ 10 | 11 | #include 12 | 13 | #ifdef __APPLE__ 14 | #include 15 | #include 16 | #else 17 | #include 18 | #endif 19 | 20 | #ifndef GLUT_APIENTRY_DEFINED 21 | #define GLUT_APIENTRY_DEFINED 1 22 | #endif 23 | 24 | #ifndef GLUT_WINGDIAPI_DEFINED 25 | #define GLUT_WINGDIAPI_DEFINED 1 26 | #endif 27 | 28 | #ifndef GLUT_MACOSX_IMPLEMENTATION 29 | #define GLUT_MACOSX_IMPLEMENTATION 0 30 | #endif 31 | #ifndef GLUT_NO_RECOVERY 32 | #define GLUT_NO_RECOVERY 0 33 | #endif 34 | 35 | #include 36 | #include 37 | using namespace std; 38 | using namespace v8; 39 | 40 | class GlutFactory { 41 | public: 42 | static Handle createGlut(int* pargc, char** argv); 43 | static Persistent glut_persistent_context; 44 | }; 45 | 46 | #endif /* GLUTBIND_H_ */ 47 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Pull in platform specific settings. 2 | include Makefile.$(firstword $(subst _, ,$(shell uname -s))) 3 | 4 | CC = g++ 5 | CFLAGS := $(CFLAGS) -m32 -Wall -Iv8/include 6 | PROG = v8-gl 7 | 8 | BUILD_GL_BINDINGS=1 9 | BUILD_GLES_BINDINGS=1 10 | BUILD_GLU_BINDINGS=1 11 | BUILD_GLUT_BINDINGS=1 12 | 13 | SRCS = main.cpp imageloader.cpp utils.cpp v8-gl.cpp \ 14 | v8-typed-array/typed-array.cc 15 | 16 | ifdef BUILD_GL_BINDINGS 17 | SRCS += glbindings/glbind.cpp 18 | CFLAGS += -DBUILD_GL_BINDINGS 19 | endif 20 | 21 | ifdef BUILD_GLES_BINDINGS 22 | SRCS += glesbindings/glesbind.cpp 23 | CFLAGS += -DBUILD_GLES_BINDINGS 24 | endif 25 | 26 | ifdef BUILD_GLU_BINDINGS 27 | SRCS += glubindings/glubind.cpp 28 | CFLAGS += -DBUILD_GLU_BINDINGS 29 | endif 30 | 31 | ifdef BUILD_GLUT_BINDINGS 32 | SRCS += glutbindings/glutbind.cpp 33 | CFLAGS += -DBUILD_GLUT_BINDINGS 34 | endif 35 | 36 | all: $(PROG) 37 | 38 | $(PROG): $(SRCS) 39 | $(CC) $(CFLAGS) $(SRCS) -o $(PROG) $(LIBS) 40 | 41 | clean: 42 | rm -f $(PROG) 43 | -------------------------------------------------------------------------------- /examples/gles/shaders/m3d-fshader.sl: -------------------------------------------------------------------------------- 1 | uniform vec4 in_color; 2 | vec2 v=(gl_FragCoord.xy-vec2(400,300))/vec2(400,300); 3 | float w=dot(in_color.xyz,vec3(1.0,256.0,65536.0))*.25; 4 | const float s=0.4; 5 | 6 | float obj(vec3 pos){ 7 | float final=1.0; 8 | final *= distance(pos,vec3(cos(w)+sin(w*0.2),0.3,2.0+cos(w*0.5)*0.5)); 9 | final *= distance(pos,vec3(-cos(w*0.7),0.3,2.0+sin(w*0.5))); 10 | final *= distance(pos,vec3(-sin(w*0.2)*0.5,sin(w),2.0)); 11 | final *= cos(pos.y)*cos(pos.x)-0.1-cos(pos.z*7.+w*7.)*cos(pos.x*3.)*cos(pos.y*4.)*0.1; 12 | return final; 13 | } 14 | 15 | void main(){ 16 | vec3 o=vec3(v.x,v.y*1.25,0.0); 17 | vec3 d=vec3(v.x+cos(w)*.3,v.y,1.0)/64.0; 18 | vec4 color=vec4(0.0); 19 | float t=0.0; 20 | 21 | for(int i=0;i<75;i++) { 22 | if(obj(o+d*t)>8) & 0xff; 37 | var b = (n>>16) & 0xff; 38 | Gles.uniform4fv(0, 1, [r/255.0, g/255.0, b/255.0, 1.0]); 39 | Gles.drawArrays(Gles.TRIANGLE_STRIP, 0, 4); 40 | 41 | Glut.swapBuffers(); 42 | } 43 | 44 | Glut.displayFunc(draw); 45 | 46 | //Set timeout callback 47 | Glut.timerFunc(25, function() { 48 | Glut.postRedisplay(); 49 | Glut.timerFunc(25, arguments.callee, 0); 50 | }, 0); 51 | 52 | Glut.mainLoop(); 53 | -------------------------------------------------------------------------------- /examples/example1.js: -------------------------------------------------------------------------------- 1 | //Initializes 3D rendering 2 | function initRendering() { 3 | Gl.enable(Gl.DEPTH_TEST) 4 | .enable(Gl.COLOR_MATERIAL); 5 | } 6 | 7 | //Called when the window is resized 8 | function handleResize(w, h) { 9 | Gl.viewport(0, 0, w, h) 10 | .matrixMode(Gl.PROJECTION) 11 | .loadIdentity(); 12 | 13 | Glu.perspective(45.0, w / h, 1.0, 200.0); 14 | } 15 | 16 | //Draws the 3D scene 17 | function drawScene() { 18 | Gl.clear(Gl.COLOR_BUFFER_BIT | Gl.DEPTH_BUFFER_BIT) 19 | .matrixMode(Gl.MODELVIEW) 20 | .loadIdentity() 21 | 22 | .begin(Gl.QUADS) 23 | 24 | //Trapezoid 25 | .vertex3f(-0.7, -1.5, -5.0) 26 | .vertex3f(0.7, -1.5, -5.0) 27 | .vertex3f(0.4, -0.5, -5.0) 28 | .vertex3f(-0.4, -0.5, -5.0) 29 | 30 | .end() 31 | 32 | .begin(Gl.TRIANGLES) 33 | 34 | //Pentagon 35 | .vertex3f(0.5, 0.5, -5.0) 36 | .vertex3f(1.5, 0.5, -5.0) 37 | .vertex3f(0.5, 1.0, -5.0) 38 | 39 | .vertex3f(0.5, 1.0, -5.0) 40 | .vertex3f(1.5, 0.5, -5.0) 41 | .vertex3f(1.5, 1.0, -5.0) 42 | 43 | .vertex3f(0.5, 1.0, -5.0) 44 | .vertex3f(1.5, 1.0, -5.0) 45 | .vertex3f(1.0, 1.5, -5.0) 46 | 47 | //Triangle 48 | .vertex3f(-0.5, 0.5, -5.0) 49 | .vertex3f(-1.0, 1.5, -5.0) 50 | .vertex3f(-1.5, 0.5, -5.0) 51 | 52 | .end(); 53 | 54 | Glut.swapBuffers(); 55 | } 56 | 57 | function main() { 58 | //Initialize Glut 59 | Glut.init(); 60 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 61 | Glut.initWindowSize(400, 400); 62 | 63 | //Create the window 64 | Glut.createWindow("OpenGL on V8 baby!"); 65 | initRendering(); //Initialize rendering 66 | 67 | //Set handler functions for drawing, keypresses, and window resizes 68 | Glut.displayFunc(drawScene); 69 | Glut.reshapeFunc(handleResize); 70 | 71 | Glut.mainLoop(); //Start the main loop. 72 | } 73 | 74 | main(); 75 | -------------------------------------------------------------------------------- /imageloader.h: -------------------------------------------------------------------------------- 1 | /* Permission is hereby granted, free of charge, to any person obtaining a copy 2 | * of this software and associated documentation files (the "Software"), to deal 3 | * in the Software without restriction, including without limitation the rights 4 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | * copies of the Software, and to permit persons to whom the Software is 6 | * furnished to do so, subject to the following conditions: 7 | * 8 | * The above notice and this permission notice shall be included in all copies 9 | * or substantial portions of the Software. 10 | * 11 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | * SOFTWARE. 18 | */ 19 | 20 | 21 | #ifndef IMAGE_LOADER_H_ 22 | #define IMAGE_LOADER_H_ 23 | 24 | //Represents an image 25 | class Image { 26 | public: 27 | Image(char* ps, int w, int h); 28 | ~Image(); 29 | 30 | /* An array of the form (R1, G1, B1, R2, G2, B2, ...) indicating the 31 | * color of each pixel in image. Color components range from 0 to 255. 32 | * The array starts the bottom-left pixel, then moves right to the end 33 | * of the row, then moves up to the next column, and so on. This is the 34 | * format in which OpenGL likes images. 35 | */ 36 | char* pixels; 37 | int width; 38 | int height; 39 | }; 40 | 41 | //Reads a bitmap image from file. 42 | Image* loadBMP(const char* filename); 43 | Image* loadPNG(const char* filename); 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /examples/example2.js: -------------------------------------------------------------------------------- 1 | //Add array iteration method 2 | Array.prototype.each = function(f) { 3 | var len = this.length; 4 | for ( var i = 0; i < len; i++) f(this[i]); 5 | }; 6 | 7 | //Initializes 3D rendering 8 | function initRendering() { 9 | "DEPTH_TEST COLOR_MATERIAL LIGHTING LIGHT0 NORMALIZE COLOR_MATERIAL" 10 | .split(" ").each(function(elem) { 11 | Gl.enable(Gl[elem]); 12 | }); 13 | } 14 | 15 | //angle variable 16 | var angle = 0; 17 | 18 | //Draws the 3D scene 19 | function drawScene() { 20 | //Set global color and drawing properties 21 | Gl.clear(Gl.COLOR_BUFFER_BIT | Gl.DEPTH_BUFFER_BIT); 22 | Gl.matrixMode(Gl.MODELVIEW); 23 | Gl.loadIdentity(); 24 | Gl.translatef(0.0, 0.0, -5.0); 25 | //Set diffuse and positioned lights 26 | Gl.lightModelfv(Gl.LIGHT_MODEL_AMBIENT, [0.3, 0.3, 0.3, 1.0]); 27 | Gl.lightfv(Gl.LIGHT0, Gl.DIFFUSE, [0.4, 0.4, 0.4, 1.0]); 28 | Gl.lightfv(Gl.LIGHT0, Gl.POSITION, [5.0, 5.0, 5.0, 1.0]); 29 | //Rotate and plot Icosahedron 30 | Gl.rotatef(angle, 1.0, 1.0, 1.0); 31 | Gl.color3f(0.5, 0.0, 0.8); 32 | Glut.solidIcosahedron(2.5); 33 | //Render 34 | Glut.swapBuffers(); 35 | } 36 | 37 | (function() { 38 | //Initialize Glut 39 | Glut.init(); 40 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 41 | Glut.initWindowSize(400, 400); //Set the window size 42 | //Create the window 43 | Glut.createWindow("OpenGL on V8 baby!"); 44 | initRendering(); 45 | //Set drawing callback 46 | Glut.displayFunc(drawScene); 47 | //Set resize window callback 48 | Glut.reshapeFunc(function(w, h) { 49 | Gl.viewport(0, 0, w, h); 50 | Gl.matrixMode(Gl.PROJECTION); 51 | Gl.loadIdentity(); 52 | Glu.perspective(45.0, w / h, 1.0, 200.0); 53 | }); 54 | //Set timeout callback 55 | Glut.timerFunc(25, function() { 56 | angle += 2.0; 57 | if (angle > 360) angle -= 360; 58 | Glut.postRedisplay(); 59 | Glut.timerFunc(25, arguments.callee, 0); 60 | }, 0); 61 | //Start the main loop. 62 | Glut.mainLoop(); 63 | })(); 64 | -------------------------------------------------------------------------------- /v8-typed-array/README.md: -------------------------------------------------------------------------------- 1 | v8-typed-array 2 | ============== 3 | 4 | Typed Array implementation for V8 and Node.js. Works well enough to run jslinux but otherwise has not been tested. Many missing APIs. 5 | 6 | * ArrayBuffer 7 | * Int8Array 8 | * Uint8Array 9 | * Int16Array 10 | * Uint16Array 11 | * Int32Array 12 | * Uint32Array 13 | * Float32Array 14 | 15 | Based Editor's Draft 28 April 2011: http://www.khronos.org/registry/typedarray/specs/latest/ 16 | 17 | Build 18 | ----- 19 | 20 | node-waf configure build 21 | 22 | Or install using NPM (npm install typed-array) 23 | 24 | Credits 25 | ------- 26 | 27 | Inspired by: 28 | 29 | * https://github.com/pufuwozu/node-webgl 30 | * http://v8.googlecode.com/svn/trunk/samples/shell.cc 31 | 32 | TODO 33 | ---- 34 | 35 | * Implement the rest of the API 36 | * Bridge to Node's Buffers? 37 | 38 | License 39 | ------- 40 | 41 | Copyright (C) 2011 by Thomas Robinson (http://tlrobinson.net/) 42 | 43 | Permission is hereby granted, free of charge, to any person obtaining a copy 44 | of this software and associated documentation files (the "Software"), to deal 45 | in the Software without restriction, including without limitation the rights 46 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 47 | copies of the Software, and to permit persons to whom the Software is 48 | furnished to do so, subject to the following conditions: 49 | 50 | The above copyright notice and this permission notice shall be included in 51 | all copies or substantial portions of the Software. 52 | 53 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 54 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 55 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 56 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 57 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 58 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 59 | THE SOFTWARE. 60 | -------------------------------------------------------------------------------- /glutbindings/glutTimerFunc.template: -------------------------------------------------------------------------------- 1 | 2 | typedef struct { 3 | int value; 4 | Persistent timerFunc; 5 | } timerData; 6 | 7 | timerData * persistentTimers[50] = { NULL }; 8 | 9 | void callbackTimerFunc(int value) { 10 | timerData * elem = persistentTimers[value]; 11 | if(elem != NULL) { 12 | //define handle scope 13 | HandleScope scope; 14 | Handle args[1]; 15 | args[0] = Integer::New(elem->value); 16 | Persistent timer = elem->timerFunc; 17 | timer->Call(GlutFactory::glut_persistent_context->Global(), 1, args); 18 | 19 | timer.Dispose(); 20 | delete elem; 21 | persistentTimers[value] = NULL; 22 | } 23 | } 24 | 25 | Handle GLUTTimerFuncCallback(const Arguments& args) { 26 | //if less that nbr of formal parameters then do nothing 27 | if (args.Length() < 3) return v8::Undefined(); 28 | //get arguments 29 | unsigned int millisec = args[0]->Uint32Value(); 30 | int timerId = args[2]->IntegerValue(); 31 | 32 | //find an empty timer spot and place the function there. 33 | int i = 0; 34 | bool found = false; 35 | for(; i < 50; i++) { 36 | if(persistentTimers[i] == NULL) { 37 | //get the function 38 | Handle value = Handle::Cast(args[1]); 39 | Persistent persistentValue = Persistent::New(value); 40 | //assign callback and value values. 41 | timerData * structElem = new timerData; 42 | structElem->value = timerId; 43 | structElem->timerFunc = persistentValue; 44 | persistentTimers[i] = structElem; 45 | found = true; 46 | break; 47 | } 48 | } 49 | 50 | //TODO add dynamic resize for persistent Timers 51 | if(!found) return v8::Undefined(); 52 | 53 | //make call 54 | //Don't pass the actual *value*, but an id to our persistent Function 55 | glutTimerFunc(( unsigned int ) millisec, ( void (* )( int )) callbackTimerFunc, ( int ) i); 56 | return v8::Undefined(); 57 | } 58 | -------------------------------------------------------------------------------- /utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | #include 3 | #include 4 | 5 | namespace V8GLUtils { 6 | char separator = '/'; 7 | char* root_path; 8 | 9 | void setRootPath(char* program_path, char* jsfile_path) { 10 | //Set the root_path for opening shader files with 11 | //relative paths 12 | //take path from executable 13 | char* pch = strrchr(program_path, V8GLUtils::separator); 14 | int last_index = pch ? (pch - program_path +1) : 2; 15 | char* tmp_exec_path = new char[last_index +1]; 16 | strncpy(tmp_exec_path, pch ? program_path : "./", last_index); 17 | tmp_exec_path[last_index] = '\0'; 18 | 19 | //take relative path from javascript file 20 | char* p1ch = strrchr(jsfile_path, V8GLUtils::separator); 21 | int last_index1 = p1ch ? (p1ch - jsfile_path +1) : 2; 22 | char* tmp_js_path = new char[last_index1 +1]; 23 | strncpy(tmp_js_path, p1ch ? jsfile_path : "./", last_index1); 24 | tmp_js_path[last_index1] = '\0'; 25 | 26 | V8GLUtils::root_path = new char[last_index + last_index1 +1]; 27 | 28 | strcpy(V8GLUtils::root_path, tmp_exec_path); 29 | strcat(V8GLUtils::root_path, tmp_js_path); 30 | 31 | delete[] tmp_exec_path; 32 | delete[] tmp_js_path; 33 | } 34 | 35 | char *pushRootPath(char *new_path) { 36 | char *old_path = root_path; 37 | char *pch = strrchr(new_path, V8GLUtils::separator); 38 | int last_index = pch ? (pch - new_path + 1) : 2; 39 | root_path = new char[last_index + 1]; 40 | strncpy(root_path, pch ? new_path : "./", last_index); 41 | root_path[last_index] = '\0'; 42 | return old_path; 43 | } 44 | void popRootPath(char *old_path) { 45 | delete[] root_path; 46 | root_path = old_path; 47 | } 48 | 49 | char* getRootPath(void) { 50 | return V8GLUtils::root_path; 51 | } 52 | 53 | char* getRealPath(char* filepath_str) { 54 | //read the file source 55 | char* filename = NULL; 56 | if(filepath_str[0] != V8GLUtils::separator) { 57 | filename = new char[strlen(V8GLUtils::root_path) + strlen(filepath_str) +1]; 58 | strcpy(filename, V8GLUtils::root_path); 59 | strcat(filename, filepath_str); 60 | } else { 61 | filename = new char[strlen(filepath_str) +1]; 62 | strcpy(filename, filepath_str); 63 | } 64 | return filename; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /examples/gles/shaderutil.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009, Nicolas Garcia Belmonte 3 | * 4 | * Some Utility functions. 5 | */ 6 | 7 | (function() { 8 | //convenience function to create a shader from a filepath 9 | function getShader(filepath, type) 10 | { 11 | var shaderScriptType = type; 12 | var shaderPath = filepath; 13 | 14 | if (!shaderPath || shaderPath.length == 0) 15 | return 0; 16 | 17 | var shader = Gles.createShader(type); 18 | 19 | if (shader == 0) return 0; 20 | 21 | //added method 22 | Gles.shaderSourceFile(shader, filepath); 23 | Gles.compileShader(shader); 24 | 25 | if (Gles.getShaderiv(shader, Gles.COMPILE_STATUS) != 1) { 26 | var error = Gles.getShaderInfoLog(shader); 27 | log("Error while compiling " + id + ":"); 28 | log(shader); 29 | 30 | Gles.deleteShader(shader); 31 | return 0; 32 | } 33 | 34 | return shader; 35 | } 36 | 37 | // Convenience function to create a program from all the passed-in 38 | // shader filepaths and types. 39 | function getProgram() { 40 | var shaders = []; 41 | 42 | // first load and compile all the passed-in shaders. 43 | for (var i = 0; i < arguments.length; i+=2) { 44 | var shader = getShader(arguments[i], arguments[i+1]); 45 | if (shader == 0) 46 | return 0; 47 | shaders.push(shader); 48 | } 49 | 50 | // then do the program object creation 51 | var program = Gles.createProgram(); 52 | if (program == 0) 53 | return 0; 54 | 55 | // attach all the shaders 56 | for (var i = 0; i < shaders.length; i++) { 57 | Gles.attachShader(program, shaders[i]); 58 | } 59 | 60 | // link, and check for errors 61 | Gles.linkProgram(program); 62 | 63 | var linked = Gles.getProgramiv(program, Gles.LINK_STATUS); 64 | if (!linked) { 65 | var error = Gles.getProgramInfoLog(program); 66 | log("Error while linking: " + error); 67 | return 0; 68 | } 69 | 70 | return program; 71 | } 72 | 73 | this.getProgram = function(vertexShader, fragmentShader) { 74 | return getProgram(vertexShader, Gles.VERTEX_SHADER, 75 | fragmentShader, Gles.FRAGMENT_SHADER); 76 | }; 77 | 78 | })(); 79 | -------------------------------------------------------------------------------- /glesbindings/glew_desktop_shim.h: -------------------------------------------------------------------------------- 1 | #define GL_ES_VERSION_2_0 1 2 | #define GL_FIXED 0x140C 3 | #define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB 4 | #define GL_MAX_VARYING_VECTORS 0x8DFC 5 | #define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD 6 | #define GL_SHADER_COMPILER 0x8DFA 7 | #define GL_SHADER_BINARY_FORMATS 0x8DF8 8 | #define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 9 | #define GL_LOW_FLOAT 0x8DF0 10 | #define GL_MEDIUM_FLOAT 0x8DF1 11 | #define GL_HIGH_FLOAT 0x8DF2 12 | #define GL_LOW_INT 0x8DF3 13 | #define GL_MEDIUM_INT 0x8DF4 14 | #define GL_HIGH_INT 0x8DF5 15 | #define GL_FRAMEBUFFER 0x8D40 16 | #define GL_RENDERBUFFER 0x8D41 17 | #define GL_RGB565 0x8D62 18 | #define GL_STENCIL_INDEX8 0x8D48 19 | #define GL_RENDERBUFFER_WIDTH 0x8D42 20 | #define GL_RENDERBUFFER_HEIGHT 0x8D43 21 | #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 22 | #define GL_RENDERBUFFER_RED_SIZE 0x8D50 23 | #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 24 | #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 25 | #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 26 | #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 27 | #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 28 | #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 29 | #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 30 | #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 31 | #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 32 | #define GL_COLOR_ATTACHMENT0 0x8CE0 33 | #define GL_DEPTH_ATTACHMENT 0x8D00 34 | #define GL_STENCIL_ATTACHMENT 0x8D20 35 | #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 36 | #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 37 | #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 38 | #define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 39 | #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD 40 | #define GL_FRAMEBUFFER_BINDING 0x8CA6 41 | #define GL_RENDERBUFFER_BINDING 0x8CA7 42 | #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 43 | 44 | // Some of the OpenGL 2.0 spec is defined as doubles, so ES 2.0 adds float 45 | // versions. Implement some simple shims here. 46 | #define glClearDepthf(depth) glClearDepth(depth) 47 | #define glDepthRangef(zNear, zFar) glDepthRange((zNear), (zFar)) 48 | 49 | // These don't exist in desktop OpenGL, just stub them out. 50 | #define glReleaseShaderCompiler ((void) 0) 51 | #define glGetShaderPrecisionFormat(a, b, c, d) ((void) 0) 52 | 53 | -------------------------------------------------------------------------------- /examples/gles/lib/v3d.js: -------------------------------------------------------------------------------- 1 | /* 2 | File: v3d.js 3 | 4 | Description: 5 | 6 | 3D Vector Class. 7 | 8 | Dependencies: 9 | 10 | core.js 11 | 12 | Author: 13 | 14 | Nicolas Garcia Belmonte 15 | 16 | Copyright: 17 | 18 | Copyright 2009 by Nicolas Garcia Belmonte. 19 | 20 | Homepage: 21 | 22 | 23 | 24 | License: 25 | 26 | MIT License 27 | */ 28 | var V3D = new Class({ 29 | x: null, y: null, z: null, 30 | 31 | initialize: function(x, y, z){ 32 | this.x = x || 0; 33 | this.y = y || 0; 34 | this.z = z || 0; 35 | }, 36 | 37 | copy: function(v){ 38 | this.x = v.x; 39 | this.y = v.y; 40 | this.z = v.z; 41 | return this; 42 | }, 43 | 44 | add: function(v){ 45 | this.x += v.x; 46 | this.y += v.y; 47 | this.z += v.z; 48 | return this; 49 | }, 50 | 51 | sub: function(v){ 52 | this.x -= v.x; 53 | this.y -= v.y; 54 | this.z -= v.z; 55 | return this; 56 | }, 57 | 58 | cross: function(v){ 59 | var tx = this.x, 60 | ty = this.y, 61 | tz = this.z; 62 | 63 | this.x = ty * v.z - tz * v.y; 64 | this.y = tz * v.x - tx * v.z; 65 | this.z = tx * v.y - ty * v.x; 66 | return this; 67 | }, 68 | 69 | scale: function(s){ 70 | this.x *= s; 71 | this.y *= s; 72 | this.z *= s; 73 | return this; 74 | }, 75 | 76 | distanceTo: function(v){ 77 | return Math.sqrt(this.distanceToSq(v)); 78 | }, 79 | 80 | distanceToSq: function(v){ 81 | var dx = this.x - v.x, 82 | dy = this.y - v.y, 83 | dz = this.z - v.z; 84 | 85 | return dx * dx + dy * dy + dz * dz; 86 | }, 87 | 88 | length: function(){ 89 | return Math.sqrt(this.lengthSq()); 90 | }, 91 | 92 | lengthSq: function(){ 93 | return this.distanceToSq(V3D.KER); 94 | }, 95 | 96 | negate: function(){ 97 | this.x = -this.x; 98 | this.y = -this.y; 99 | this.z = -this.z; 100 | return this; 101 | }, 102 | 103 | normalize: function(){ 104 | var len = this.length(), ratio; 105 | if (len > 0) 106 | ratio = 1.0 / len; 107 | else 108 | ratio = 0; 109 | 110 | this.x *= ratio; 111 | this.y *= ratio; 112 | this.z *= ratio; 113 | return this; 114 | }, 115 | 116 | dot: function(v){ 117 | return this.x * v.x + this.y * v.y + this.z * v.z; 118 | }, 119 | 120 | clone: function(){ 121 | return new V3D(this.x, this.y, this.z); 122 | }, 123 | 124 | toString: function(){ 125 | return '(' + this.x + ', ' + this.y + ', ' + this.z + ')'; 126 | } 127 | }); 128 | 129 | V3D.KER = new V3D; 130 | 131 | V3D.add = function(a, b) { 132 | return new V3D( a.x + b.x, a.y + b.y, a.z + b.z ); 133 | }; 134 | 135 | V3D.sub = function(a, b) { 136 | return new V3D( a.x - b.x, a.y - b.y, a.z - b.z ); 137 | }; 138 | 139 | V3D.scale = function(a, s) { 140 | return new V3D( a.x * s, a.y * s, a.z * s ); 141 | }; 142 | 143 | V3D.cross = function(a, b) { 144 | return new V3D( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x ); 145 | }; 146 | 147 | V3D.dot = function(a, b) { 148 | return a.x * b.x + a.y * b.y + a.z * b.z; 149 | }; 150 | -------------------------------------------------------------------------------- /glbindings/make_json.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | 4 | PATH_GL = 'gl.h' 5 | FILE_JSON = 'glbind.json' 6 | 7 | #constant and function patterns 8 | constant_pattern = """ 9 | .+define[\s]+ #define C/C++ keyword 10 | 11 | (?PGL_[^\s]+) #Constant name 12 | 13 | [\s]+ 14 | 15 | (?P[^\s]+) #Constant value 16 | 17 | [\s]* 18 | """ 19 | 20 | function_pattern = """ 21 | [\s]*extern[\s]+ #extern declaration 22 | 23 | (?P[^\s]+) #Function return type 24 | 25 | [\s]+ 26 | 27 | (?Pgl[A-Za-z0-9]+) #Function name 28 | 29 | [\s]* 30 | 31 | \((?P.*)\); #Function parameters 32 | """ 33 | #precompile regexps 34 | constant = re.compile(constant_pattern, re.VERBOSE) 35 | function = re.compile(function_pattern, re.VERBOSE) 36 | 37 | def main(): 38 | json_out = [] 39 | constants = [] 40 | #open input file 41 | with open(PATH_GL, 'r') as fin: 42 | #line accumulator. Function definitions 43 | #can be spread into multiple lines 44 | l = '' 45 | #get function/constant prototype 46 | for cont in fin: 47 | l += cont.replace('\n', '') 48 | if not balanced(l): 49 | continue 50 | #is constant declaration 51 | mat = re.match(constant, l) 52 | if mat and not mat.group('name') in constants: 53 | constants.append(mat.group('name')) 54 | json_out.append(make_constant(mat)) 55 | else: 56 | #is function declaration 57 | mat = re.match(function, l) 58 | if mat: 59 | json_out.append(make_function(mat)) 60 | 61 | l = '' #empty line accumulator 62 | 63 | #dump as JSON 64 | with open(FILE_JSON, 'w') as fout: 65 | fout.write(json.dumps(json_out, indent=4)) 66 | 67 | def make_constant(match): 68 | """Returns a Constant JSON Object""" 69 | 70 | return { 71 | 'type': 'c', #c for constant, f for function 72 | 'name': match.group('name'), 73 | 'value': match.group('value') #is this necessary? 74 | } 75 | 76 | def make_function(match): 77 | """Returns a Function JSON Object""" 78 | 79 | return { 80 | 'type': 'f', #f for function 81 | 'name': match.group('name'), 82 | 'return_type': match.group('return_type'), 83 | 'parameters': get_parameters(match.group('parameters')) 84 | } 85 | 86 | def get_parameters(params): 87 | """Returns an ordered list of parameter types""" 88 | 89 | params_list = [] 90 | params_aux = params.split(',') 91 | passed = False 92 | for par in params_aux: 93 | if passed and not balanced(params_list[-1]): 94 | params_list[-1] += ',' + par 95 | else: 96 | #magic 97 | param = ' '.join(par.strip().split(' ')[:-1]) + ('*' * (par.count('*') + par.count('['))) 98 | if param.strip() != '': params_list.append(param) 99 | passed = True 100 | 101 | return params_list 102 | 103 | 104 | def balanced(l): 105 | return l.count('(') == l.count(')') 106 | 107 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /glesbindings/make_json.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | 4 | PATH_GL = 'gl2.h' 5 | FILE_JSON = 'glesbind.json' 6 | 7 | #constant and function patterns 8 | constant_pattern = """ 9 | .+define[\s]+ #define C/C++ keyword 10 | 11 | (?PGL_[^\s]+) #Constant name 12 | 13 | [\s]+ 14 | 15 | (?P[^\s]+) #Constant value 16 | 17 | [\s]* 18 | """ 19 | 20 | function_pattern = """ 21 | [\s]*GL_APICALL[\s]+ #GLAPICALL typedef 22 | 23 | (?P[^\s]+) #Function return type 24 | 25 | [\s]+GL_APIENTRY[\s]+ #GLAPIENTRY typedef 26 | 27 | (?Pgl[A-Za-z0-9]+) #Function name 28 | 29 | [\s]* 30 | 31 | \((?P.*)\); #Function parameters 32 | """ 33 | #precompile regexps 34 | constant = re.compile(constant_pattern, re.VERBOSE) 35 | function = re.compile(function_pattern, re.VERBOSE) 36 | 37 | def main(): 38 | json_out = [] 39 | constants = [] 40 | #open input file 41 | with open(PATH_GL, 'r') as fin: 42 | #line accumulator. Function definitions 43 | #can be spread into multiple lines 44 | l = '' 45 | #get function/constant prototype 46 | for cont in fin: 47 | l += cont.replace('\n', '') 48 | if not balanced(l): 49 | continue 50 | #is constant declaration 51 | mat = re.match(constant, l) 52 | if mat and not mat.group('name') in constants: 53 | constants.append(mat.group('name')) 54 | json_out.append(make_constant(mat)) 55 | else: 56 | #is function declaration 57 | mat = re.match(function, l) 58 | if mat: 59 | json_out.append(make_function(mat)) 60 | 61 | l = '' #empty line accumulator 62 | 63 | #dump as JSON 64 | with open(FILE_JSON, 'w') as fout: 65 | fout.write(json.dumps(json_out, indent=4)) 66 | 67 | def make_constant(match): 68 | """Returns a Constant JSON Object""" 69 | 70 | return { 71 | 'type': 'c', #c for constant, f for function 72 | 'name': match.group('name'), 73 | 'value': match.group('value') #is this necessary? 74 | } 75 | 76 | def make_function(match): 77 | """Returns a Function JSON Object""" 78 | 79 | return { 80 | 'type': 'f', #f for function 81 | 'name': match.group('name'), 82 | 'return_type': match.group('return_type'), 83 | 'parameters': get_parameters(match.group('parameters')) 84 | } 85 | 86 | def get_parameters(params): 87 | """Returns an ordered list of parameter types""" 88 | 89 | params_list = [] 90 | params_aux = params.split(',') 91 | passed = False 92 | for par in params_aux: 93 | if passed and not balanced(params_list[-1]): 94 | params_list[-1] += ',' + par 95 | else: 96 | #magic 97 | param = ' '.join(par.strip().replace('*', '').split(' ')[:-1]) + ('*' * (par.count('*') + par.count('['))) 98 | if param.strip() != '': params_list.append(param) 99 | passed = True 100 | 101 | return params_list 102 | 103 | 104 | def balanced(l): 105 | return l.count('(') == l.count(')') 106 | 107 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /examples/gles/ch8-simple-vertexshader.js: -------------------------------------------------------------------------------- 1 | //load common code. 2 | load("common.js", "shaderutil.js"); 3 | 4 | //start custom code. 5 | var angle = 0; 6 | 7 | // an object we'll use to store shaders, textures, etc. on as we create them 8 | var userData = {}; 9 | 10 | function init() { 11 | userData.programObject = getProgram("shaders/ch8-simple-vertexshader.vs", 12 | "shaders/ch8-simple-vertexshader.fs"); 13 | 14 | if(userData.programObject == 0) return false; 15 | 16 | userData.positionLoc = Gles.getAttribLocation(userData.programObject, "a_position"); 17 | userData.mvpLoc = Gles.getUniformLocation(userData.programObject, "u_mvpMatrix"); 18 | userData.obj = esGenCube(1.0); 19 | Gles.clearColor(0, 0, 0, 0); 20 | return true; 21 | } 22 | 23 | function updateObjects() { 24 | // compute the window aspect ratio 25 | var aspect = 800 / 600; 26 | 27 | // Generate a perspective matrix with a 60 degree FOV 28 | var persp = new Matrix4x4(); 29 | persp.perspective(60, aspect, 1.0, 20.0); 30 | 31 | // Create our modelview matrix 32 | var modelview = new Matrix4x4(); 33 | 34 | // translate away from the viewer 35 | modelview.translate(0, 0, -2); 36 | 37 | // then rotating the cube 38 | modelview.rotate(angle, 1, 1, 1); 39 | 40 | userData.mvpMatrix = modelview.multiply(persp); 41 | } 42 | 43 | 44 | // Update MVP matrix based on time; deltaTime is in seconds 45 | function update() { 46 | angle += 2.0; 47 | if (angle > 360) angle -= 360; 48 | updateObjects(); 49 | Glut.postRedisplay(); 50 | Glut.timerFunc(25, update, 0); 51 | } 52 | 53 | // Actually draw the triangle, using the program created in init() 54 | function draw() { 55 | // Set up the viewport 56 | Gles.viewport(0, 0, 800, 600); 57 | 58 | // Clear the color buffer 59 | Gles.clear(Gles.COLOR_BUFFER_BIT); 60 | 61 | // Use the program object we created in init() 62 | Gles.useProgram(userData.programObject); 63 | 64 | // Load the vertex data 65 | Gles.vertexAttribPointer(userData.positionLoc, 3, Gles.FLOAT, false, 0, userData.obj.vertices); 66 | Gles.enableVertexAttribArray(userData.positionLoc); 67 | 68 | // Load the MVP matrix 69 | Gles.uniformMatrix4fv(userData.mvpLoc, userData.mvpMatrix.elements.length, Gles.FALSE, userData.mvpMatrix.elements); 70 | 71 | // Draw the cube 72 | //Gles.drawArrays(Gles.TRIANGLE_FAN, 0, userData.obj.vertices.length); 73 | Gles.drawElements(Gles.TRIANGLES, userData.obj.indices.length, Gles.UNSIGNED_SHORT, userData.obj.indices); 74 | 75 | // Finally do the swap to display what we just drew 76 | Glut.swapBuffers(); 77 | } 78 | 79 | function main() { 80 | //Initialize Glut 81 | Glut.init(); 82 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 83 | Glut.initWindowSize(800, 600); 84 | //Create the window 85 | Glut.createWindow("OpenGL ES on V8! (^_^)/"); 86 | 87 | if (!init()) 88 | return; 89 | 90 | updateObjects(); 91 | //Set drawing callback 92 | Glut.displayFunc(draw); 93 | //Set resize window callback 94 | Glut.reshapeFunc(function(w, h) { 95 | Gles.viewport(0, 0, w, h); 96 | Gl.matrixMode(Gl.PROJECTION); 97 | Gl.loadIdentity(); 98 | Glu.perspective(45.0, w / h, 1.0, 200.0); 99 | }); 100 | 101 | Glut.timerFunc(25, update, 0); 102 | //Start the main loop. 103 | Glut.mainLoop(); 104 | } 105 | 106 | main(); -------------------------------------------------------------------------------- /glesbindings/gles_desktop_shim.h: -------------------------------------------------------------------------------- 1 | #define GL_ES_VERSION_2_0 1 2 | #define GL_FIXED 0x140C 3 | #define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB 4 | #define GL_MAX_VARYING_VECTORS 0x8DFC 5 | #define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD 6 | #define GL_SHADER_COMPILER 0x8DFA 7 | #define GL_SHADER_BINARY_FORMATS 0x8DF8 8 | #define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 9 | #define GL_LOW_FLOAT 0x8DF0 10 | #define GL_MEDIUM_FLOAT 0x8DF1 11 | #define GL_HIGH_FLOAT 0x8DF2 12 | #define GL_LOW_INT 0x8DF3 13 | #define GL_MEDIUM_INT 0x8DF4 14 | #define GL_HIGH_INT 0x8DF5 15 | #define GL_FRAMEBUFFER 0x8D40 16 | #define GL_RENDERBUFFER 0x8D41 17 | #define GL_RGB565 0x8D62 18 | #define GL_STENCIL_INDEX8 0x8D48 19 | #define GL_RENDERBUFFER_WIDTH 0x8D42 20 | #define GL_RENDERBUFFER_HEIGHT 0x8D43 21 | #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 22 | #define GL_RENDERBUFFER_RED_SIZE 0x8D50 23 | #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 24 | #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 25 | #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 26 | #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 27 | #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 28 | #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 29 | #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 30 | #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 31 | #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 32 | #define GL_COLOR_ATTACHMENT0 0x8CE0 33 | #define GL_DEPTH_ATTACHMENT 0x8D00 34 | #define GL_STENCIL_ATTACHMENT 0x8D20 35 | #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 36 | #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 37 | #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 38 | #define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 39 | #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD 40 | #define GL_FRAMEBUFFER_BINDING 0x8CA6 41 | #define GL_RENDERBUFFER_BINDING 0x8CA7 42 | #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 43 | #define glBindFramebuffer glBindFramebufferEXT 44 | #define glBindRenderbuffer glBindRenderbufferEXT 45 | #define glCheckFramebufferStatus glCheckFramebufferStatusEXT 46 | #define glDeleteFramebuffers glDeleteFramebuffersEXT 47 | #define glDeleteRenderbuffers glDeleteRenderbuffersEXT 48 | #define glFramebufferRenderbuffer glFramebufferRenderbufferEXT 49 | #define glFramebufferTexture2D glFramebufferTexture2DEXT 50 | #define glGenerateMipmap glGenerateMipmapEXT 51 | #define glGenFramebuffers glGenFramebuffersEXT 52 | #define glGenRenderbuffers glGenRenderbuffersEXT 53 | #define glGetFramebufferAttachmentParameteriv glGetFramebufferAttachmentParameterivEXT 54 | #define glGetRenderbufferParameteriv glGetRenderbufferParameterivEXT 55 | #define glIsFramebuffer glIsFramebufferEXT 56 | #define glIsRenderbuffer glIsRenderbufferEXT 57 | #define glRenderbufferStorage glRenderbufferStorageEXT 58 | 59 | // Some of the OpenGL 2.0 spec is defined as doubles, so ES 2.0 adds float 60 | // versions. Implement some simple shims here. 61 | #define glClearDepthf(depth) glClearDepth(depth) 62 | #define glDepthRangef(zNear, zFar) glDepthRange((zNear), (zFar)) 63 | 64 | // These don't exist in desktop OpenGL, just stub them out. 65 | #define glReleaseShaderCompiler ((void) 0) 66 | #define glGetShaderPrecisionFormat(a, b, c, d) ((void) 0) 67 | 68 | -------------------------------------------------------------------------------- /examples/gles/ch2-hello-triangle.js: -------------------------------------------------------------------------------- 1 | // an object we'll use to store shaders, textures, etc. on as we create them 2 | var userData = { }; 3 | 4 | function loadShader(shaderType, shaderSource) { 5 | // Create the shader object 6 | var shader = Gles.createShader(shaderType); 7 | if (shader == 0) return 0; 8 | 9 | // Load the shader source 10 | Gles.shaderSource(shader, shaderSource); 11 | 12 | // Compile the shader 13 | Gles.compileShader(shader); 14 | 15 | // Check the compile status 16 | var compiled = Gles.getShaderiv(shader, Gles.COMPILE_STATUS); 17 | if (!compiled) { 18 | // Something went wrong during compilation; get the error 19 | var error = Gles.getShaderInfoLog(shader); 20 | Gles.deleteShader(shader); 21 | return 0; 22 | } 23 | 24 | return shader; 25 | } 26 | 27 | function init() { 28 | // put our shader source in variables 29 | var vertexShaderSource = 30 | "attribute vec4 vPosition; \n" + 31 | "void main() \n" + 32 | "{ \n" + 33 | " gl_Position = vPosition; \n" + 34 | "} "; 35 | var fragmentShaderSource = 36 | "/*precision mediump float;*/ \n" + 37 | "void main() \n" + 38 | "{ \n" + 39 | " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n" + 40 | "} "; 41 | 42 | // create our shaders 43 | var vertexShader = loadShader(Gles.VERTEX_SHADER, vertexShaderSource); 44 | var fragmentShader = loadShader(Gles.FRAGMENT_SHADER, fragmentShaderSource); 45 | 46 | if (!vertexShader || !fragmentShader) 47 | return false; 48 | 49 | // Create the program object 50 | var programObject = Gles.createProgram(); 51 | if (programObject == 0) 52 | return false; 53 | 54 | // Attach our two shaders to the program 55 | Gles.attachShader (programObject, vertexShader); 56 | Gles.attachShader (programObject, fragmentShader); 57 | 58 | // Bind "vPosition" to attribute 0 59 | Gles.bindAttribLocation (programObject, 0, "vPosition"); 60 | 61 | // Link the program 62 | Gles.linkProgram (programObject); 63 | 64 | // Check the link status 65 | var linked = Gles.getProgramiv (programObject, Gles.LINK_STATUS); 66 | if (!linked) { 67 | // something went wrong with the link 68 | var error = Gles.getProgramInfoLog (programObject); 69 | 70 | Gles.deleteProgram(programObject); 71 | Gles.deleteProgram(fragmentShader); 72 | Gles.deleteProgram(vertexShader); 73 | 74 | return false; 75 | } 76 | 77 | userData.programObject = programObject; 78 | 79 | // set up the clear color to clear to transparent black 80 | Gles.clearColor (0, 0, 0, 0); 81 | 82 | //Set drawing callback 83 | Glut.displayFunc(draw); 84 | 85 | return true; 86 | } 87 | 88 | // Actually draw the triangle, using the program created in init() 89 | function draw() { 90 | var vertices = [ 0.0, 0.5, 0.0, 91 | -0.5, -0.5, 0.0, 92 | 0.5, -0.5, 0.0 ]; 93 | 94 | // Set up the viewport 95 | Gles.viewport(0, 0, 800, 600); 96 | 97 | // Clear the color buffer 98 | Gles.clear(Gles.COLOR_BUFFER_BIT); 99 | 100 | // Use the program object we created in init() 101 | Gles.useProgram(userData.programObject); 102 | 103 | // Load the vertex data 104 | Gles.vertexAttribPointer(0, 3, Gles.FLOAT, false, 0, vertices); 105 | Gles.enableVertexAttribArray(0); 106 | 107 | // Do the draw, as triangles 108 | Gles.drawArrays(Gles.TRIANGLES, 0, 3); 109 | 110 | // Finally do the swap to display what we just drew 111 | Glut.swapBuffers(); 112 | } 113 | 114 | function main() { 115 | //Initialize Glut 116 | Glut.init(); 117 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 118 | Glut.initWindowSize(800, 600); 119 | //Create the window 120 | Glut.createWindow("OpenGL ES on V8! \\(^_^)/"); 121 | 122 | if (!init()) 123 | return; 124 | 125 | Glut.mainLoop(); 126 | } 127 | 128 | main(); -------------------------------------------------------------------------------- /examples/gles/ch9-simple-texture-cubemap.js: -------------------------------------------------------------------------------- 1 | //load libraries 2 | load("common.js", "shaderutil.js"); 3 | 4 | // an object we'll use to store shaders, textures, etc. on as we create them 5 | var userData = { }; 6 | 7 | // 8 | // Create a simple cubemap texture 9 | // 10 | function createSimpleTextureCube() 11 | { 12 | // Generate a texture object. genTextures always returns 13 | // an array, and we're only interested in the first element 14 | var textureId = Gles.genTextures(1)[0]; 15 | 16 | // Bind the texture object 17 | Gles.bindTexture(Gles.TEXTURE_CUBE_MAP, textureId); 18 | 19 | // Load each cube face 20 | Gles.texImage2D(Gles.TEXTURE_CUBE_MAP_POSITIVE_X, 0, Gles.RGB, 1, 1, 0, Gles.RGB, Gles.UNSIGNED_BYTE, [ 255, 0, 0 ]); 21 | Gles.texImage2D(Gles.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, Gles.RGB, 1, 1, 0, Gles.RGB, Gles.UNSIGNED_BYTE, [ 0, 255, 0 ]); 22 | Gles.texImage2D(Gles.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, Gles.RGB, 1, 1, 0, Gles.RGB, Gles.UNSIGNED_BYTE, [ 0, 0, 255 ]); 23 | Gles.texImage2D(Gles.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, Gles.RGB, 1, 1, 0, Gles.RGB, Gles.UNSIGNED_BYTE, [ 255, 255, 0 ]); 24 | Gles.texImage2D(Gles.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, Gles.RGB, 1, 1, 0, Gles.RGB, Gles.UNSIGNED_BYTE, [ 255, 0, 255 ]); 25 | Gles.texImage2D(Gles.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, Gles.RGB, 1, 1, 0, Gles.RGB, Gles.UNSIGNED_BYTE, [ 255, 255, 255 ]); 26 | 27 | // set up filtering modes 28 | Gles.texParameteri(Gles.TEXTURE_CUBE_MAP, Gles.TEXTURE_MIN_FILTER, Gles.NEAREST); 29 | Gles.texParameteri(Gles.TEXTURE_CUBE_MAP, Gles.TEXTURE_MAG_FILTER, Gles.NEAREST); 30 | 31 | return textureId; 32 | } 33 | 34 | function init() 35 | { 36 | // Create the linked program object 37 | userData.programObject = getProgram("shaders/ch9-vshader.sl", 38 | "shaders/ch9-fshader.sl"); 39 | if (userData.programObject == 0) 40 | return false; 41 | 42 | // Get the attribute locations 43 | userData.positionLoc = Gles.getAttribLocation(userData.programObject, "a_position"); 44 | userData.normalLoc = Gles.getAttribLocation(userData.programObject, "a_normal"); 45 | 46 | // Get the sampler location 47 | userData.samplerLoc = Gles.getUniformLocation(userData.programObject, "s_texture"); 48 | 49 | // Load the texture 50 | userData.textureId = createSimpleTextureCube(); 51 | 52 | // Create a sphere object 53 | userData.obj = esGenSphere(20, 0.75); 54 | 55 | // set up the clear color to clear to transparent black 56 | Gles.clearColor (0, 0, 0, 0); 57 | 58 | Glut.displayFunc(draw); 59 | return true; 60 | } 61 | 62 | // 63 | // Draw the sphere we created in init() 64 | // 65 | function draw() 66 | { 67 | // set up the viewport 68 | Gles.viewport (0, 0, 800, 600); 69 | 70 | // clear 71 | Gles.clear (Gles.COLOR_BUFFER_BIT); 72 | 73 | Gles.cullFace(Gles.BACK); 74 | 75 | Gles.enable(Gles.CULL_FACE); 76 | // use the program 77 | Gles.useProgram (userData.programObject); 78 | 79 | // load the vertex positions 80 | Gles.vertexAttribPointer (userData.positionLoc, 3, Gles.FLOAT, false, 0, userData.obj.vertices); 81 | 82 | // load the texture coordinates 83 | Gles.vertexAttribPointer (userData.normalLoc, 3, Gles.FLOAT, false, 0, userData.obj.normals); 84 | 85 | Gles.enableVertexAttribArray (userData.positionLoc); 86 | Gles.enableVertexAttribArray (userData.normalLoc); 87 | 88 | // bind the texture 89 | Gles.activeTexture(Gles.TEXTURE0); 90 | Gles.bindTexture(Gles.TEXTURE_CUBE_MAP, userData.textureId); 91 | 92 | // and set the sampler to texture unit 0 93 | Gles.uniform1i(userData.samplerLoc, 0); 94 | 95 | // and finally do the draw 96 | Gles.drawElements(Gles.TRIANGLES, userData.obj.indices.length, Gles.UNSIGNED_SHORT, userData.obj.indices); 97 | 98 | // swap buffers to display 99 | Glut.swapBuffers(); 100 | } 101 | 102 | function main() 103 | { 104 | //Initialize Glut 105 | Glut.init(); 106 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 107 | Glut.initWindowSize(800, 600); 108 | //Create the window 109 | Glut.createWindow("v8-gl Textures"); 110 | 111 | if (!init()) 112 | return; 113 | 114 | Glut.mainLoop(); 115 | 116 | } 117 | 118 | main(); 119 | -------------------------------------------------------------------------------- /examples/gles/ch9-simple-texture2d.js: -------------------------------------------------------------------------------- 1 | //load common code. 2 | load("common.js", "shaderutil.js"); 3 | 4 | // an object we'll use to store shaders, textures, etc. on as we create them 5 | var userData = { }; 6 | 7 | // 8 | //Create a simple 2x2 texture image with four different colors 9 | // 10 | function createSimpleTexture2D() 11 | { 12 | var textureId; 13 | 14 | // 2x2 Image, 3 bytes per pixel (RGB) 15 | var pixels = [ 16 | 255, 0, 0, // Red 17 | 0, 255, 0, // Green 18 | 0, 0, 255, // Blue 19 | 255, 255, 0 // Yellow 20 | ]; 21 | 22 | // Use tightly packed data 23 | Gles.pixelStorei(Gles.UNPACK_ALIGNMENT, 1); 24 | 25 | // Generate a texture object. genTextures always returns 26 | // an array, and we're only interested in the first element 27 | textureId = Gles.genTextures(1)[0]; 28 | 29 | // Bind the texture object 30 | Gles.bindTexture(Gles.TEXTURE_2D, textureId); 31 | 32 | // Load the pixels into the texture object 33 | Gles.texImage2D(Gles.TEXTURE_2D, // target 34 | 0, // level 35 | Gles.RGB, // interal format 36 | 2, 2, // width, height 37 | 0, // border 38 | Gles.RGB, // format 39 | Gles.UNSIGNED_BYTE, // type 40 | pixels); // pixels array 41 | 42 | // set up filtering modes 43 | Gles.texParameteri(Gles.TEXTURE_2D, Gles.TEXTURE_MIN_FILTER, Gles.NEAREST); 44 | Gles.texParameteri(Gles.TEXTURE_2D, Gles.TEXTURE_MAG_FILTER, Gles.NEAREST); 45 | 46 | return textureId; 47 | } 48 | 49 | 50 | function init() 51 | { 52 | // Create the linked program object 53 | userData.programObject = getProgram("shaders/ch9-texture2d-vshader.sl", 54 | "shaders/ch9-texture2d-fshader.sl"); 55 | if (userData.programObject == 0) 56 | return false; 57 | 58 | // Get the attribute locations 59 | userData.positionLoc = Gles.getAttribLocation(userData.programObject, "a_position"); 60 | userData.texCoordLoc = Gles.getAttribLocation(userData.programObject, "a_texCoord"); 61 | 62 | // Get the sampler location 63 | userData.samplerLoc = Gles.getUniformLocation(userData.programObject, "s_texture"); 64 | 65 | // Load the texture 66 | userData.textureId = createSimpleTexture2D(); 67 | 68 | // set up the clear color to clear to transparent black 69 | Gles.clearColor (0, 0, 0, 0); 70 | 71 | Glut.displayFunc(draw); 72 | 73 | return true; 74 | } 75 | 76 | function draw() 77 | { 78 | var vVertices = [ 79 | -0.5, 0.5, 0.0, // Position 0 80 | -0.5, -0.5, 0.0, // Position 1 81 | 0.5, -0.5, 0.0, // Position 2 82 | 0.5, 0.5, 0.0 // Position 3 83 | ]; 84 | 85 | var vTexCoords = [ 86 | 0.0, 0.0, // TexCoord 0 87 | 0.0, 1.0, // TexCoord 1 88 | 1.0, 1.0, // TexCoord 2 89 | 1.0, 0.0 // TexCoord 3 90 | ]; 91 | 92 | var indices = [ 0, 1, 2, 0, 2, 3 ]; 93 | 94 | // set up the viewport 95 | Gles.viewport (0, 0, 800, 600); 96 | 97 | // clear 98 | Gles.clear (Gles.COLOR_BUFFER_BIT); 99 | 100 | // use the program 101 | Gles.useProgram (userData.programObject); 102 | 103 | // load the vertex positions 104 | Gles.vertexAttribPointer (userData.positionLoc, 3, Gles.FLOAT, false, 0, vVertices); 105 | 106 | // load the texture coordinates 107 | Gles.vertexAttribPointer (userData.texCoordLoc, 2, Gles.FLOAT, false, 0, vTexCoords); 108 | 109 | Gles.enableVertexAttribArray (userData.positionLoc); 110 | Gles.enableVertexAttribArray (userData.texCoordLoc); 111 | 112 | // bind the texture 113 | Gles.activeTexture(Gles.TEXTURE0); 114 | Gles.bindTexture(Gles.TEXTURE_2D, userData.textureId); 115 | 116 | // and set the sampler to texture unit 0 117 | Gles.uniform1i(userData.samplerLoc, 0); 118 | 119 | // and finally do the draw 120 | Gles.drawElements(Gles.TRIANGLES, indices.length, Gles.UNSIGNED_SHORT, indices); 121 | 122 | // swap buffers to display 123 | Glut.swapBuffers(); 124 | } 125 | 126 | function main() { 127 | //Initialize Glut 128 | Glut.init(); 129 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 130 | Glut.initWindowSize(800, 600); 131 | //Create the window 132 | Glut.createWindow("v8-gl Texture2D"); 133 | 134 | if (!init()) 135 | return; 136 | 137 | Glut.mainLoop(); 138 | } 139 | 140 | main(); 141 | -------------------------------------------------------------------------------- /examples/gles/ch10-multitexture.js: -------------------------------------------------------------------------------- 1 | //load common code 2 | load("common.js", "shaderutil.js"); 3 | 4 | // an object we'll use to store shaders, textures, etc. on as we create them 5 | var userData = { }; 6 | 7 | // 8 | // Create a 2D texture from the given HTML image 9 | // 10 | function textureFromImage(img) 11 | { 12 | var textureId = Gles.genTextures(1)[0]; 13 | 14 | Gles.bindTexture(Gles.TEXTURE_2D, textureId); 15 | 16 | // Load it. The dimensions, format, etc. are all read from the image. 17 | Gles.texImage2DFile(img); 18 | 19 | // Set up filtering and wrap modes 20 | Gles.texParameteri(Gles.TEXTURE_2D, Gles.TEXTURE_MIN_FILTER, Gles.NEAREST); 21 | Gles.texParameteri(Gles.TEXTURE_2D, Gles.TEXTURE_MAG_FILTER, Gles.NEAREST); 22 | 23 | Gles.texParameteri(Gles.TEXTURE_2D, Gles.TEXTURE_WRAP_S, Gles.CLAMP_TO_EDGE); 24 | Gles.texParameteri(Gles.TEXTURE_2D, Gles.TEXTURE_WRAP_T, Gles.CLAMP_TO_EDGE); 25 | 26 | return textureId; 27 | } 28 | 29 | 30 | function init() 31 | { 32 | 33 | // Create the linked program object 34 | userData.programObject = getProgram("shaders/ch10-vshader.sl", 35 | "shaders/ch10-fshader.sl"); 36 | if (userData.programObject == 0) 37 | return false; 38 | 39 | // Get the attribute locations 40 | userData.positionLoc = Gles.getAttribLocation(userData.programObject, "a_position"); 41 | userData.texCoordLoc = Gles.getAttribLocation(userData.programObject, "a_texCoord"); 42 | 43 | // Get the sampler locations 44 | userData.baseMapLoc = Gles.getUniformLocation(userData.programObject, "s_baseMap"); 45 | userData.lightMapLoc = Gles.getUniformLocation(userData.programObject, "s_lightMap"); 46 | 47 | // Load the textures; the textures were loaded earlier in main() 48 | userData.baseMapTexId = textureFromImage("assets/basemap.png"); 49 | userData.lightMapTexId = textureFromImage("assets/lightmap.png"); 50 | 51 | // set up the clear color to clear to transparent black 52 | Gles.clearColor (0, 0, 0, 0); 53 | 54 | Glut.displayFunc(draw); 55 | 56 | return true; 57 | } 58 | 59 | // 60 | // Draw a rectangle using a pair of triangles and the program 61 | // created in init() 62 | // 63 | function draw() 64 | { 65 | var vVertices = [ 66 | -0.5, 0.5, 0.0, // Position 0 67 | -0.5, -0.5, 0.0, // Position 1 68 | 0.5, -0.5, 0.0, // Position 2 69 | 0.5, 0.5, 0.0 // Position 3 70 | ]; 71 | 72 | var vTexCoords = [ 73 | 0.0, 0.0, // TexCoord 0 74 | 0.0, 1.0, // TexCoord 1 75 | 1.0, 1.0, // TexCoord 2 76 | 1.0, 0.0 // TexCoord 3 77 | ]; 78 | 79 | var indices = [ 0, 1, 2, 0, 2, 3 ]; 80 | 81 | // set up the viewport 82 | Gles.viewport (0, 0, 800, 600); 83 | 84 | // clear 85 | Gles.clear (Gles.COLOR_BUFFER_BIT); 86 | 87 | // use the program 88 | Gles.useProgram (userData.programObject); 89 | 90 | // load the vertex positions 91 | Gles.vertexAttribPointer (userData.positionLoc, 3, Gles.FLOAT, false, 0, vVertices); 92 | 93 | // load the texture coordinates 94 | Gles.vertexAttribPointer (userData.texCoordLoc, 2, Gles.FLOAT, false, 0, vTexCoords); 95 | 96 | Gles.enableVertexAttribArray (userData.positionLoc); 97 | Gles.enableVertexAttribArray (userData.texCoordLoc); 98 | 99 | // bind the base map 100 | Gles.activeTexture(Gles.TEXTURE0); 101 | Gles.bindTexture(Gles.TEXTURE_2D, userData.baseMapTexId); 102 | 103 | // and set the base map sampler to texture unit 0 104 | Gles.uniform1i(userData.baseMapLoc, 0); 105 | 106 | // bind the light map 107 | Gles.activeTexture(Gles.TEXTURE1); 108 | Gles.bindTexture(Gles.TEXTURE_2D, userData.lightMapTexId); 109 | 110 | // and set the light map sampler to texture unit 1 111 | Gles.uniform1i(userData.lightMapLoc, 1); 112 | 113 | // and finally do the draw 114 | Gles.drawElements(Gles.TRIANGLES, indices.length, Gles.UNSIGNED_SHORT, indices); 115 | 116 | // swap buffers to display 117 | Glut.swapBuffers(); 118 | } 119 | 120 | function main() 121 | { 122 | //Initialize Glut 123 | Glut.init(); 124 | Glut.initDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 125 | Glut.initWindowSize(800, 600); 126 | //Create the window 127 | Glut.createWindow("v8-gl Textures"); 128 | 129 | if (!init()) 130 | return; 131 | 132 | Glut.mainLoop(); 133 | } 134 | 135 | main(); 136 | -------------------------------------------------------------------------------- /examples/gles/metaballs/metaballs.js: -------------------------------------------------------------------------------- 1 | /* 2 | File: metaballs.js 3 | 4 | Description: 5 | 6 | Creates a Metaballs class similar to what's defined in the sprite-o-mat example. 7 | 8 | 9 | 10 | Dependencies: 11 | 12 | core.js 13 | 14 | Author: 15 | 16 | Nicolas Garcia Belmonte 17 | 18 | Copyright: 19 | 20 | Copyright 2009 by Nicolas Garcia Belmonte. 21 | 22 | Homepage: 23 | 24 | 25 | 26 | License: 27 | 28 | MIT License 29 | */ 30 | 31 | var Config = { 32 | gridDim: 64, 33 | shift1: 6, 34 | shift2: 12, 35 | ballCount: 128, 36 | 37 | GP_TYPE_META: 0x1, 38 | GP_TYPE_BORDER: 0x2, 39 | GP_TYPE_TEXT: 0x4 40 | }; 41 | 42 | var MetaBalls = new Class({ 43 | balls: null, 44 | grid: null, 45 | 46 | initialize: function(grid) { 47 | this.grid = grid; 48 | var count = Config.ballCount; 49 | var b = this.balls = new Array(count); 50 | for(var i=0; i < count; i++) { 51 | //add metaobject 52 | b.push({ 53 | 'pos': { 'x':0, 'y':0, 'z':0 }, 54 | 'a': 0, 55 | 'b': 0 56 | }); 57 | } 58 | }, 59 | 60 | update: function(from, to) { 61 | var balls = this.balls; 62 | var dim = Config.gridDim; 63 | var points = this.grid.points; 64 | var shift1 = Config.shift1, shift2 = Config.shift2; 65 | var meta = Config.GP_TYPE_META; 66 | 67 | while (from < num) { 68 | var ballsFrom = balls[from]; 69 | var influenceRange = 1 + (ballsFrom.b >> 0); 70 | var pos = ballsFrom.pos; 71 | var posx = (pos.x >> 0); 72 | var posy = (pos.y >> 0); 73 | var posz = (pos.z >> 0); 74 | for (var z = posz-influenceRange; z < posz+influenceRange; ++z) { 75 | if (z < 0 || z >= dim) 76 | continue; 77 | 78 | for (var y = posy-influenceRange; y < posy+influenceRange; ++y) { 79 | if (y < 0 || y >= dim) 80 | continue; 81 | 82 | for (var x = posx-influenceRange; x < posx+influenceRange; ++x) { 83 | if (x < 0 || x >= dim) 84 | continue; 85 | 86 | var dist = { 87 | 'x': pos.x - x, 88 | 'y': pos.y - y, 89 | 'z': pos.z - z 90 | }; 91 | var dist2 = dist.x * dist.x + dist.y * dist.y + dist.z * dist.z; 92 | var range2 = ballsFrom.b * ballsFrom.b; 93 | 94 | if (range2 > dist2) { 95 | var gp = points[(z<> 12) & 0x3f) > 0) { 142 | var p = points[movecount]; 143 | var pdiff = points[movecount - dimSq]; 144 | 145 | p.value = fac * pdiff.value; 146 | p.flags = pdiff.flags; 147 | } else { 148 | points[movecount].value = 0; 149 | } 150 | } 151 | } 152 | 153 | }); 154 | 155 | function rgba(redval, greenval, blueval, alphaval) { 156 | return ((alphaval << 24) | (redval << 16) | (greenval << 8) | blueval); 157 | } 158 | 159 | function gridColor(gp) { 160 | var maxval = 2.0 * gp.value - 1.0; 161 | 162 | if (maxval > 1.0) 163 | maxval = 1.0; 164 | 165 | var metacolor = rgba(196, 64 + ((192.0 * (1.0 - maxval)) >> 0), 0, 0); 166 | 167 | if (gp.flags & Config.GP_TYPE_META) { 168 | if (gp.flags & Config.GP_TYPE_BORDER) 169 | return { 170 | 'color': ((metacolor & 0xfefefefe) >> 1) + rgba(0, 64, 92, 0), 171 | 'maxval': maxval 172 | }; 173 | else 174 | return { 175 | 'color': metacolor, 176 | 'maxval': maxval 177 | }; 178 | } else { 179 | if (gp.flags & Config.GP_TYPE_BORDER) 180 | return { 181 | 'color': rgba(0, 128, 196, 0), 182 | 'maxval': maxval 183 | }; 184 | else 185 | return { 186 | 'color': rgba(128, 228, 128, 0), 187 | 'maxval': maxval 188 | }; 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /README.mkd: -------------------------------------------------------------------------------- 1 | V8-GL 2 | ========= 3 | 4 | A JavaScript Toolkit for creating Desktop Hardware Accelerated Graphics with JS. 5 | 6 | ![A V8-GL example code](http://blog.thejit.org/assets/v8gl2.png) 7 | 8 | Note 9 | ------ 10 | 11 | If you're interested in this project you might also want to check out [Plask](http://www.plask.org/), a JavaScript multimedia programming environment by [Dean McNamee](https://github.com/deanm). 12 | 13 | 14 | Description 15 | --------- 16 | 17 | V8-GL intends to provide bindings for creating 2D-3D hardware accelerated graphics on the Desktop with JavaScript. 18 | 19 | Although OpenGL bindings are included in this library, this project main goal is to provide a more rich and easy-to-use toolkit 20 | for making 2D-3D graphics. 21 | 22 | I set a few goals for this project, the first of those is to provide complete OpenGL bindings for V8. 23 | Other goals will be explained at [my blog](http://blog.thejit.org) in due time. 24 | 25 | 26 | Status 27 | --------- 28 | 29 | No releases yet. OpenGL 2.1 bindings are 75% complete. The repo already has some functional examples. See the *example* readme section for a complete working example. 30 | 31 | Requirements 32 | --------- 33 | 34 | - I use Mac OS X, but you can try to build your examples with Linux or Windows if you want. I guess that the only differences between Mac and Linux might be a couple of lines in the Makefile. 35 | - OpenGL 2.1+ 36 | - [V8](http://code.google.com/p/v8/) and its requirements 37 | 38 | Download 39 | --------- 40 | 41 | Since there are no releases yet, you can clone the repo from github 42 | 43 | $ git clone git://github.com/philogb/v8-gl.git 44 | 45 | Then [checkout](http://code.google.com/p/v8/source/checkout) V8 source 46 | 47 | $ cd v8-gl 48 | $ svn co http://v8.googlecode.com/svn/trunk/ v8 49 | 50 | Build V8 51 | 52 | $ cd v8 53 | $ scons mode=release 54 | 55 | Make the project 56 | 57 | $ cd .. 58 | $ make 59 | 60 | You'll probably get some warnings (but no errors), so everything should be ok. 61 | Finally, run some example JS code 62 | 63 | $ ./v8-gl examples/example2.js 64 | 65 | 66 | 67 | Example 68 | --------- 69 | 70 | Here's an example of a rotating Icosahedron with some lighting and colors. 71 | 72 | //Add array iteration method 73 | Array.prototype.each = function(f) { 74 | var len = this.length; 75 | for ( var i = 0; i < len; i++) f(this[i]); 76 | }; 77 | 78 | //Initializes 3D rendering 79 | function initRendering() { 80 | "DEPTH_TEST COLOR_MATERIAL LIGHTING LIGHT0 NORMALIZE COLOR_MATERIAL" 81 | .split(" ").each(function(elem) { 82 | Gl.Enable(Gl[elem]); 83 | }); 84 | } 85 | 86 | //global angle variable 87 | var angle = 0; 88 | 89 | //Draws the 3D scene 90 | function drawScene() { 91 | //Set global color and drawing properties 92 | Gl.Clear(Gl.COLOR_BUFFER_BIT | Gl.DEPTH_BUFFER_BIT); 93 | Gl.MatrixMode(Gl.MODELVIEW); 94 | Gl.LoadIdentity(); 95 | Gl.Translatef(0.0, 0.0, -5.0); 96 | //Set diffuse and positioned lights 97 | Gl.LightModelfv(Gl.LIGHT_MODEL_AMBIENT, [0.3, 0.3, 0.3, 1.0]); 98 | Gl.Lightfv(Gl.LIGHT0, Gl.DIFFUSE, [0.4, 0.4, 0.4, 1.0]); 99 | Gl.Lightfv(Gl.LIGHT0, Gl.POSITION, [5.0, 5.0, 5.0, 1.0]); 100 | //Rotate and plot Icosahedron 101 | Gl.Rotatef(angle, 1.0, 1.0, 1.0); 102 | Gl.Color3f(0.5, 0.0, 0.8); 103 | Glut.SolidIcosahedron(2.5); 104 | //Render 105 | Glut.SwapBuffers(); 106 | } 107 | 108 | (function() { 109 | //Initialize Glut 110 | Glut.Init(); 111 | Glut.InitDisplayMode(Glut.DOUBLE | Glut.RGB | Glut.DEPTH); 112 | Glut.InitWindowSize(400, 400); //Set the window size 113 | //Create the window 114 | Glut.CreateWindow("OpenGL on V8 baby!"); 115 | initRendering(); 116 | //Set drawing callback 117 | Glut.DisplayFunc(drawScene); 118 | //Set resize window callback 119 | Glut.ReshapeFunc(function(w, h) { 120 | var gl = { 'Viewport': [0, 0, w, h], 'MatrixMode': [Gl.PROJECTION], 'LoadIdentity': [] }; 121 | for (var i in gl) Gl[i].apply(this, gl[i]); 122 | Glu.Perspective(45.0, w / h, 1.0, 200.0); 123 | }); 124 | //Set timeout callback 125 | Glut.TimerFunc(25, function() { 126 | angle += 2.0; 127 | if (angle > 360) angle -= 360; 128 | Glut.PostRedisplay(); 129 | Glut.TimerFunc(25, arguments.callee, 0); 130 | }, 0); 131 | //Start the main loop. 132 | Glut.MainLoop(); 133 | })(); 134 | 135 | 136 | 137 | License 138 | --------- 139 | 140 | BSD License. 141 | 142 | Redistribution and use in source and binary forms, with or without 143 | modification, are permitted provided that the following conditions are met: 144 | * Redistributions of source code must retain the above copyright 145 | notice, this list of conditions and the following disclaimer. 146 | * Redistributions in binary form must reproduce the above copyright 147 | notice, this list of conditions and the following disclaimer in the 148 | documentation and/or other materials provided with the distribution. 149 | * Neither the name of the organization nor the 150 | names of its contributors may be used to endorse or promote products 151 | derived from this software without specific prior written permission. 152 | 153 | THIS SOFTWARE IS PROVIDED BY Nicolas Garcia Belmonte ``AS IS'' AND ANY 154 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 155 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 156 | DISCLAIMED. IN NO EVENT SHALL Nicolas Garcia Belmonte BE LIABLE FOR ANY 157 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 158 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 159 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 160 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 161 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 162 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 163 | -------------------------------------------------------------------------------- /examples/gles/lib/core.js: -------------------------------------------------------------------------------- 1 | /* 2 | File: core.js 3 | 4 | Description: 5 | 6 | Provides common utility functions and the Class object. 7 | 8 | Dependencies: 9 | 10 | [None] 11 | 12 | Author: 13 | 14 | Nicolas Garcia Belmonte 15 | 16 | Copyright: 17 | 18 | Copyright 2009 by Nicolas Garcia Belmonte. 19 | 20 | Homepage: 21 | 22 | 23 | 24 | License: 25 | 26 | MIT License 27 | */ 28 | 29 | var $ = {}; 30 | 31 | $.empty = function() {}; 32 | 33 | $.extend = function(original, extended){ 34 | for (var key in (extended || {})) original[key] = extended[key]; 35 | return original; 36 | }; 37 | 38 | $.lambda = function(value){ 39 | return (typeof value == 'function') ? value : function(){ 40 | return value; 41 | }; 42 | }; 43 | 44 | $.time = Date.now || function(){ 45 | return +new Date; 46 | }; 47 | 48 | $.splat = function(obj){ 49 | var type = $.type(obj); 50 | return (type) ? ((type != 'array') ? [obj] : obj) : []; 51 | }; 52 | 53 | $.type = function(elem) { 54 | return $type.s.call(elem).match(/^\[object\s(.*)\]$/)[1].toLowerCase(); 55 | }; 56 | $.type.s = Object.prototype.toString; 57 | 58 | $.each = function(iterable, fn){ 59 | var type = $.type(iterable); 60 | if(type == 'object') { 61 | for (var key in iterable) fn(iterable[key], key); 62 | } else { 63 | for(var i=0; i < iterable.length; i++) fn(iterable[i], i); 64 | } 65 | }; 66 | 67 | $.merge = function(){ 68 | var mix = {}; 69 | for (var i = 0, l = arguments.length; i < l; i++){ 70 | var object = arguments[i]; 71 | if ($.type(object) != 'object') continue; 72 | for (var key in object){ 73 | var op = object[key], mp = mix[key]; 74 | mix[key] = (mp && $.type(op) == 'object' && $.type(mp) == 'object') ? $.merge(mp, op) : $.unlink(op); 75 | } 76 | } 77 | return mix; 78 | }; 79 | 80 | $.unlink = function(object){ 81 | var unlinked; 82 | switch ($.type(object)){ 83 | case 'object': 84 | unlinked = {}; 85 | for (var p in object) unlinked[p] = $.unlink(object[p]); 86 | break; 87 | case 'array': 88 | unlinked = []; 89 | for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $.unlink(object[i]); 90 | break; 91 | default: return object; 92 | } 93 | return unlinked; 94 | }; 95 | 96 | $.rgbToHex = function(srcArray, array){ 97 | if (srcArray.length < 3) return null; 98 | if (srcArray.length == 4 && srcArray[3] == 0 && !array) return 'transparent'; 99 | var hex = []; 100 | for (var i = 0; i < 3; i++){ 101 | var bit = (srcArray[i] - 0).toString(16); 102 | hex.push((bit.length == 1) ? '0' + bit : bit); 103 | } 104 | return (array) ? hex : '#' + hex.join(''); 105 | }; 106 | 107 | $.hexToRgb = function(hex) { 108 | var hex = hex.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); 109 | var array = hex.slice(1); 110 | if (array.length != 3) return null; 111 | var rgb = []; 112 | $.each(array, function(value){ 113 | if (value.length == 1) value += value; 114 | rgb.push(parseInt(value, 16)); 115 | }); 116 | return rgb; 117 | }; 118 | 119 | var Class = function(properties){ 120 | properties = properties || {}; 121 | var klass = function(){ 122 | for (var key in this){ 123 | if (typeof this[key] != 'function') this[key] = $.unlink(this[key]); 124 | } 125 | this.constructor = klass; 126 | if (Class.prototyping) return this; 127 | var instance = (this.initialize) ? this.initialize.apply(this, arguments) : this; 128 | return instance; 129 | }; 130 | 131 | for (var mutator in Class.Mutators){ 132 | if (!properties[mutator]) continue; 133 | properties = Class.Mutators[mutator](properties, properties[mutator]); 134 | delete properties[mutator]; 135 | } 136 | 137 | $.extend(klass, this); 138 | klass.constructor = Class; 139 | klass.prototype = properties; 140 | return klass; 141 | }; 142 | 143 | Class.Mutators = { 144 | 145 | Extends: function(self, klass){ 146 | Class.prototyping = klass.prototype; 147 | var subclass = new klass; 148 | delete subclass.parent; 149 | subclass = Class.inherit(subclass, self); 150 | delete Class.prototyping; 151 | return subclass; 152 | }, 153 | 154 | Implements: function(self, klasses){ 155 | $.each($.splat(klasses), function(klass){ 156 | Class.prototying = klass; 157 | $.extend(self, ($.type(klass) == 'function') ? new klass : klass); 158 | delete Class.prototyping; 159 | }); 160 | return self; 161 | } 162 | 163 | }; 164 | 165 | $extend(Class, { 166 | 167 | inherit: function(object, properties){ 168 | var caller = arguments.callee.caller; 169 | for (var key in properties){ 170 | var override = properties[key]; 171 | var previous = object[key]; 172 | var type = $.type(override); 173 | if (previous && type == 'function'){ 174 | if (override != previous){ 175 | if (caller){ 176 | override.__parent = previous; 177 | object[key] = override; 178 | } else { 179 | Class.override(object, key, override); 180 | } 181 | } 182 | } else if(type == 'object'){ 183 | object[key] = $.merge(previous, override); 184 | } else { 185 | object[key] = override; 186 | } 187 | } 188 | 189 | if (caller) object.parent = function(){ 190 | return arguments.callee.caller.__parent.apply(this, arguments); 191 | }; 192 | 193 | return object; 194 | }, 195 | 196 | override: function(object, name, method){ 197 | var parent = Class.prototyping; 198 | if (parent && object[name] != parent[name]) parent = null; 199 | var override = function(){ 200 | var previous = this.parent; 201 | this.parent = parent ? parent[name] : object[name]; 202 | var value = method.apply(this, arguments); 203 | this.parent = previous; 204 | return value; 205 | }; 206 | object[name] = override; 207 | } 208 | 209 | }); 210 | 211 | 212 | Class.prototype.implement = function(){ 213 | var proto = this.prototype; 214 | $.each(Array.prototype.slice.call(arguments || []), function(properties){ 215 | Class.inherit(proto, properties); 216 | }); 217 | return this; 218 | }; 219 | -------------------------------------------------------------------------------- /examples/gles/common.js: -------------------------------------------------------------------------------- 1 | load("lib/matrix.js"); 2 | 3 | /* 4 | * Copyright (c) 2009, Mozilla Corp 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * * Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of the nor the 15 | * names of its contributors may be used to endorse or promote products 16 | * derived from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY 19 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 22 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | /* 31 | * Based on sample code from the OpenGL(R) ES 2.0 Programming Guide, which carriers 32 | * the following header: 33 | * 34 | * Book: OpenGL(R) ES 2.0 Programming Guide 35 | * Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner 36 | * ISBN-10: 0321502795 37 | * ISBN-13: 9780321502797 38 | * Publisher: Addison-Wesley Professional 39 | * URLs: http://safari.informit.com/9780321563835 40 | * http://www.opengles-book.com 41 | */ 42 | 43 | // 44 | // port of esShapes.c 45 | // 46 | 47 | function shallowCloneArray(ar) { 48 | var o = Array(ar.length); 49 | for (var i = 0; i < ar.length; i++) { 50 | o[i] = ar[i]; 51 | } 52 | return o; 53 | } 54 | 55 | function shallowCloneArrayScaled(ar, scale) { 56 | var o = Array(ar.length); 57 | for (var i = 0; i < ar.length; i++) { 58 | o[i] = ar[i] * scale; 59 | } 60 | return o; 61 | } 62 | 63 | // make these accessible directly in the glboal scope, 64 | // in case someone wants to use them without copying 65 | var esCubeVertices = [ 66 | -0.5, -0.5, -0.5, 67 | -0.5, -0.5, 0.5, 68 | 0.5, -0.5, 0.5, 69 | 0.5, -0.5, -0.5, 70 | -0.5, 0.5, -0.5, 71 | -0.5, 0.5, 0.5, 72 | 0.5, 0.5, 0.5, 73 | 0.5, 0.5, -0.5, 74 | -0.5, -0.5, -0.5, 75 | -0.5, 0.5, -0.5, 76 | 0.5, 0.5, -0.5, 77 | 0.5, -0.5, -0.5, 78 | -0.5, -0.5, 0.5, 79 | -0.5, 0.5, 0.5, 80 | 0.5, 0.5, 0.5, 81 | 0.5, -0.5, 0.5, 82 | -0.5, -0.5, -0.5, 83 | -0.5, -0.5, 0.5, 84 | -0.5, 0.5, 0.5, 85 | -0.5, 0.5, -0.5, 86 | 0.5, -0.5, -0.5, 87 | 0.5, -0.5, 0.5, 88 | 0.5, 0.5, 0.5, 89 | 0.5, 0.5, -0.5 90 | ]; 91 | 92 | var esCubeNormals = [ 93 | 0.0, -1.0, 0.0, 94 | 0.0, -1.0, 0.0, 95 | 0.0, -1.0, 0.0, 96 | 0.0, -1.0, 0.0, 97 | 0.0, 1.0, 0.0, 98 | 0.0, 1.0, 0.0, 99 | 0.0, 1.0, 0.0, 100 | 0.0, 1.0, 0.0, 101 | 0.0, 0.0, -1.0, 102 | 0.0, 0.0, -1.0, 103 | 0.0, 0.0, -1.0, 104 | 0.0, 0.0, -1.0, 105 | 0.0, 0.0, 1.0, 106 | 0.0, 0.0, 1.0, 107 | 0.0, 0.0, 1.0, 108 | 0.0, 0.0, 1.0, 109 | -1.0, 0.0, 0.0, 110 | -1.0, 0.0, 0.0, 111 | -1.0, 0.0, 0.0, 112 | -1.0, 0.0, 0.0, 113 | 1.0, 0.0, 0.0, 114 | 1.0, 0.0, 0.0, 115 | 1.0, 0.0, 0.0, 116 | 1.0, 0.0, 0.0 117 | ]; 118 | 119 | var esCubeTexCoords = [ 120 | 0.0, 0.0, 121 | 0.0, 1.0, 122 | 1.0, 1.0, 123 | 1.0, 0.0, 124 | 1.0, 0.0, 125 | 1.0, 1.0, 126 | 0.0, 1.0, 127 | 0.0, 0.0, 128 | 0.0, 0.0, 129 | 0.0, 1.0, 130 | 1.0, 1.0, 131 | 1.0, 0.0, 132 | 0.0, 0.0, 133 | 0.0, 1.0, 134 | 1.0, 1.0, 135 | 1.0, 0.0, 136 | 0.0, 0.0, 137 | 0.0, 1.0, 138 | 1.0, 1.0, 139 | 1.0, 0.0, 140 | 0.0, 0.0, 141 | 0.0, 1.0, 142 | 1.0, 1.0, 143 | 1.0, 0.0 144 | ]; 145 | 146 | var esCubeIndices = [ 147 | 0, 2, 1, 148 | 0, 3, 2, 149 | 4, 5, 6, 150 | 4, 6, 7, 151 | 8, 9, 10, 152 | 8, 10, 11, 153 | 12, 15, 14, 154 | 12, 14, 13, 155 | 16, 17, 18, 156 | 16, 18, 19, 157 | 20, 23, 22, 158 | 20, 22, 21 159 | ]; 160 | 161 | // will return an object that has vertices, normals, texCoords, and indices members 162 | function esGenCube (scale) { 163 | return { 164 | vertices: shallowCloneArrayScaled(esCubeVertices, scale), 165 | texCoords: shallowCloneArray(esCubeTexCoords), 166 | indices: shallowCloneArray(esCubeIndices), 167 | normals: shallowCloneArray(esCubeNormals) 168 | }; 169 | } 170 | 171 | // 172 | // generates coordinate information for a sphere 173 | // 174 | 175 | function esGenSphere (numSlices, radius) { 176 | var i, j; 177 | var numParallels = numSlices; 178 | var numVertices = (numParallels + 1) * (numSlices + 1); 179 | var numIndices = numParallels * numSlices * 6; 180 | var angleStep = (2 * Math.PI) / numSlices; 181 | 182 | var vertices = Array(3*numVertices); 183 | var normals = Array(3*numVertices); 184 | var texCoords = Array(2*numVertices); 185 | var indices = Array(numIndices); 186 | 187 | for (i = 0; i < numParallels+1; i++) { 188 | for (j = 0; j < numSlices+1; j++) { 189 | var vertex = (i * (numSlices+1) + j) * 3; 190 | 191 | vertices[vertex+0] = radius * Math.sin(angleStep * i) * Math.sin(angleStep * j); 192 | vertices[vertex+1] = radius * Math.cos(angleStep * i); 193 | vertices[vertex+2] = radius * Math.sin(angleStep * i) * Math.cos(angleStep * j); 194 | 195 | normals[vertex+0] = vertices[vertex+0] / radius; 196 | normals[vertex+1] = vertices[vertex+1] / radius; 197 | normals[vertex+2] = vertices[vertex+2] / radius; 198 | 199 | var texIndex = (i * (numSlices+1) + j) * 2; 200 | 201 | texCoords[texIndex+0] = j / numSlices; 202 | texCoords[texIndex+1] = (1 - i) / (numParallels - 1); 203 | } 204 | } 205 | 206 | var k = 0; 207 | for (i = 0; i < numParallels; i++) { 208 | for (j = 0; j < numSlices; j++) { 209 | indices[k++] = i * (numSlices + 1) + j; 210 | indices[k++] = (i + 1) * (numSlices + 1) + j; 211 | indices[k++] = (i + 1) * (numSlices + 1) + (j + 1); 212 | 213 | indices[k++] = i * (numSlices + 1) + j; 214 | indices[k++] = (i + 1) * (numSlices + 1) + (j + 1); 215 | indices[k++] = i * (numSlices + 1) + (j + 1); 216 | } 217 | } 218 | 219 | return { 220 | vertices: vertices, 221 | normals: normals, 222 | texCoords: texCoords, 223 | indices: indices 224 | }; 225 | } 226 | -------------------------------------------------------------------------------- /glbindings/glbind.py: -------------------------------------------------------------------------------- 1 | from __future__ import with_statement 2 | 3 | import json 4 | import re 5 | 6 | #input output files 7 | IN_FILE = 'glbind.json' 8 | OUT_FILE = 'glbind.cpp' 9 | 10 | #exclude functions by name 11 | EXCLUDE = re.compile('ATI|MESA') 12 | 13 | def main(): 14 | """Generates Gl bindings""" 15 | 16 | with open(IN_FILE, 'r') as f: 17 | text_out = [] 18 | data = f.read() 19 | try: 20 | # Try the python 2.6 json module first. 21 | json_in = json.loads(data) 22 | except AttributeError: 23 | # Fall back to json-py. 24 | reader = json.JsonReader() 25 | json_in = reader.read(data) 26 | constants, functions = [], [] 27 | 28 | for obj in json_in: 29 | if not re.search(EXCLUDE, obj['name']): 30 | try: 31 | if obj['type'] == 'c': 32 | constants.append(obj['name']) 33 | else: 34 | text_out.append(generate_function(obj)) 35 | functions.append(obj['name']) 36 | except Exception, e: #probably an unhandled type 37 | print e 38 | pass 39 | 40 | with open(OUT_FILE, 'w') as fout: 41 | fout.write(""" 42 | #include "glbind.h" 43 | 44 | #if defined(V8_GL_USE_GLEW) 45 | #include "GL/glew.h" 46 | #elif defined(__APPLE__) 47 | #include 48 | #else 49 | #define GL_GLEXT_PROTOTYPES 50 | #include 51 | #endif 52 | 53 | using namespace v8; 54 | 55 | Persistent GlFactory::self_; 56 | """ + '\n'.join(text_out) + '\n' + generate_main_function(constants, functions)) 57 | 58 | 59 | def generate_main_function(constants, functions): 60 | """Generates the main createGl function definition""" 61 | 62 | text_out_begin = """ 63 | 64 | Handle GlFactory::createGl(void) { 65 | HandleScope handle_scope; 66 | 67 | Handle Gl = ObjectTemplate::New(); 68 | 69 | Gl->SetInternalFieldCount(1); 70 | 71 | """ 72 | 73 | text_out_end = """ 74 | 75 | // Again, return the result through the current handle scope. 76 | return handle_scope.Close(Gl); 77 | } 78 | """ 79 | bind_accessor = lambda n: " Gl->Set(String::NewSymbol(\"" + '_'.join(n.split('_')[1:]) \ 80 | + "\"), Uint32::New(" + n + "), ReadOnly);\n" 81 | bind_function = lambda n: " Gl->Set(String::NewSymbol(\"" + n[2].lower() + n[3:] + \ 82 | "\"), FunctionTemplate::New(GL" + n + "Callback));\n" 83 | 84 | cts = [bind_accessor(name) for name in constants] 85 | fts = [bind_function(name) for name in functions] 86 | 87 | return text_out_begin + '\n'.join(cts) + '\n' + '\n'.join(fts) + text_out_end 88 | 89 | def generate_function(obj): 90 | """Generates code for declaring a Function""" 91 | 92 | text_out = """ 93 | 94 | Handle<> GLCallback(const Arguments& args) { 95 | //if less that nbr of formal parameters then do nothing 96 | if (args.Length() < ) return v8::Undefined(); 97 | //get arguments 98 | 99 | //make call 100 | 101 | } 102 | 103 | """ 104 | return multiple_replace({ 105 | '': obj['name'], 106 | '': str(len(obj['parameters'])), 107 | '': generate_arguments(obj['parameters']), 108 | '': generate_call(obj), 109 | '': 'Value' 110 | }, text_out) 111 | 112 | 113 | #map some OpenGL types to V8 types 114 | unsigned = re.compile('unsigned|ubyte|ushort|uint|bitfield|boolean') 115 | integer = re.compile('int|enum|sizei|short|byte') 116 | double = re.compile('double|float|clampf|clampd') 117 | 118 | def generate_arguments(params): 119 | """generates the formal parameter definition""" 120 | 121 | text_out = [] 122 | #assignment template 123 | assign = lambda type, method, i: ' ' + type + ' arg' + i + \ 124 | ' = args[' + i + ']->' + method + '();\n' 125 | 126 | for i, type in enumerate(params): 127 | si = str(i) 128 | #TODO Find a way to map void* to a V8 type 129 | if type.find('void*') != -1: 130 | raise Exception("unhandled type " + type) 131 | #is array 132 | elif type.find('*') != -1 or type.find('[') != -1: 133 | text_out.append(generate_array_expression(type, i)) 134 | #is unsigned integer 135 | elif re.search(unsigned, type): 136 | text_out.append(assign('unsigned int', 'Uint32Value', si)) 137 | #is integer 138 | elif re.search(integer, type): 139 | text_out.append(assign('int', 'IntegerValue', si)) 140 | #is double, float 141 | elif re.search(double, type): 142 | text_out.append(assign('double', 'NumberValue', si)) 143 | else: 144 | raise Exception("unhandled type " + type) 145 | 146 | return ''.join(text_out) 147 | 148 | def generate_array_expression(type, i): 149 | """generates an Array assignment expression""" 150 | type = multiple_replace({ '(':'', ')':'', 'const':'' }, type) 151 | acc = get_accessor(type) 152 | clean_type = type.replace('*', '') 153 | 154 | text_out = """ 155 | 156 | Handle arrHandle##1 = Handle::Cast(args[##1]); 157 | ##2 arg##1 = new ##3[arrHandle##1->Length()]; 158 | for (unsigned j = 0; j < arrHandle##1->Length(); j++) { 159 | Handle arg(arrHandle##1->Get(Integer::New(j))); 160 | ##3 aux = (##3)arg->##4; 161 | arg##1[j] = aux; 162 | } 163 | 164 | """ 165 | return multiple_replace({ 166 | '##1': str(i), 167 | '##2': type, 168 | '##3': clean_type, 169 | '##4': acc + 'Value()' 170 | }, text_out) 171 | 172 | def get_accessor(type): 173 | """Returns the V8 type accesor method to be called""" 174 | 175 | if re.search(unsigned, type): return 'Uint32' 176 | if re.search(integer, type): return 'Integer' 177 | if re.search(double, type): return 'Number' 178 | 179 | return None 180 | 181 | def generate_call(obj): 182 | """generates the native function call syntax""" 183 | 184 | acc = get_accessor(obj['return_type']) 185 | function_call = obj['name'] + "(" + ", ".join(['(' + param + ') ' + "arg" + str(i) \ 186 | for i, param in enumerate(obj['parameters'])]) + ")" 187 | 188 | #dot-this-dot-that feature 189 | if acc is None: 190 | return function_call + ';\n Handle res(GlFactory::self_);\n return res;' 191 | else: 192 | return 'return ' + acc + '::New(' + function_call + ');' 193 | 194 | 195 | def multiple_replace(dict, text): 196 | """ Replace in 'text' all occurences of any key in the given 197 | dictionary by its corresponding value. Returns the new string.""" 198 | 199 | # Create a regular expression from the dictionary keys 200 | regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) 201 | 202 | # For each match, look-up corresponding value in dictionary 203 | return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 204 | 205 | if __name__ == '__main__': main() 206 | -------------------------------------------------------------------------------- /imageloader.cpp: -------------------------------------------------------------------------------- 1 | /* Permission is hereby granted, free of charge, to any person obtaining a copy 2 | * of this software and associated documentation files (the "Software"), to deal 3 | * in the Software without restriction, including without limitation the rights 4 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | * copies of the Software, and to permit persons to whom the Software is 6 | * furnished to do so, subject to the following conditions: 7 | * 8 | * The above notice and this permission notice shall be included in all copies 9 | * or substantial portions of the Software. 10 | * 11 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | * SOFTWARE. 18 | */ 19 | /* File for "Putting It All Together" lesson of the OpenGL tutorial on 20 | * www.videotutorialsrock.com 21 | */ 22 | 23 | 24 | 25 | #include 26 | #include 27 | 28 | #include "imageloader.h" 29 | 30 | using namespace std; 31 | 32 | Image::Image(char* ps, int w, int h) : pixels(ps), width(w), height(h) { 33 | 34 | } 35 | 36 | Image::~Image() { 37 | delete[] pixels; 38 | } 39 | 40 | namespace { 41 | //Converts a four-character array to an integer, using big-endian form 42 | int toInt(const char* bytes) { 43 | return (int)(((unsigned char)bytes[0] << 24) | 44 | ((unsigned char)bytes[1] << 16) | 45 | ((unsigned char)bytes[2] << 8) | 46 | (unsigned char)bytes[3]); 47 | } 48 | 49 | //Converts a two-character array to a short, using little-endian form 50 | short toShort(const char* bytes) { 51 | return (short)(((unsigned char)bytes[1] << 8) | 52 | (unsigned char)bytes[0]); 53 | } 54 | 55 | //Reads the next four bytes as an integer, using big-endian form 56 | int readInt(ifstream &input) { 57 | char buffer[4]; 58 | input.read(buffer, 4); 59 | return toInt(buffer); 60 | } 61 | 62 | //Reads the next two bytes as a short, using little-endian form 63 | short readShort(ifstream &input) { 64 | char buffer[2]; 65 | input.read(buffer, 2); 66 | return toShort(buffer); 67 | } 68 | 69 | //Just like auto_ptr, but for arrays 70 | template 71 | class auto_array { 72 | private: 73 | T* array; 74 | mutable bool isReleased; 75 | public: 76 | explicit auto_array(T* array_ = NULL) : 77 | array(array_), isReleased(false) { 78 | } 79 | 80 | auto_array(const auto_array &aarray) { 81 | array = aarray.array; 82 | isReleased = aarray.isReleased; 83 | aarray.isReleased = true; 84 | } 85 | 86 | ~auto_array() { 87 | if (!isReleased && array != NULL) { 88 | delete[] array; 89 | } 90 | } 91 | 92 | T* get() const { 93 | return array; 94 | } 95 | 96 | T &operator*() const { 97 | return *array; 98 | } 99 | 100 | void operator=(const auto_array &aarray) { 101 | if (!isReleased && array != NULL) { 102 | delete[] array; 103 | } 104 | array = aarray.array; 105 | isReleased = aarray.isReleased; 106 | aarray.isReleased = true; 107 | } 108 | 109 | T* operator->() const { 110 | return array; 111 | } 112 | 113 | T* release() { 114 | isReleased = true; 115 | return array; 116 | } 117 | 118 | void reset(T* array_ = NULL) { 119 | if (!isReleased && array != NULL) { 120 | delete[] array; 121 | } 122 | array = array_; 123 | } 124 | 125 | T* operator+(int i) { 126 | return array + i; 127 | } 128 | 129 | T &operator[](int i) { 130 | return array[i]; 131 | } 132 | }; 133 | 134 | 135 | } 136 | 137 | Image* loadBMP(const char* filename) { 138 | ifstream input; 139 | input.open(filename, ifstream::binary); 140 | assert(!input.fail() || !"Could not find file"); 141 | char buffer[2]; 142 | input.read(buffer, 2); 143 | assert((buffer[0] == 'B' && buffer[1] == 'M') || !"Not a bitmap file"); 144 | input.ignore(8); 145 | int dataOffset = readInt(input); 146 | 147 | //Read the header 148 | int headerSize = readInt(input); 149 | int width; 150 | int height; 151 | switch(headerSize) { 152 | case 40: 153 | //V3 154 | width = readInt(input); 155 | height = readInt(input); 156 | input.ignore(2); 157 | assert(readShort(input) == 24 || !"Image is not 24 bits per pixel"); 158 | assert(readShort(input) == 0 || !"Image is compressed"); 159 | break; 160 | case 12: 161 | //OS/2 V1 162 | width = readShort(input); 163 | height = readShort(input); 164 | input.ignore(2); 165 | assert(readShort(input) == 24 || !"Image is not 24 bits per pixel"); 166 | break; 167 | case 64: 168 | //OS/2 V2 169 | assert(!"Can't load OS/2 V2 bitmaps"); 170 | break; 171 | case 108: 172 | //Windows V4 173 | assert(!"Can't load Windows V4 bitmaps"); 174 | break; 175 | case 124: 176 | //Windows V5 177 | assert(!"Can't load Windows V5 bitmaps"); 178 | break; 179 | default: 180 | assert(!"Unknown bitmap format"); 181 | } 182 | 183 | //Read the data 184 | int bytesPerRow = ((width * 3 + 3) / 4) * 4 - (width * 3 % 4); 185 | int size = bytesPerRow * height; 186 | auto_array pixels(new char[size]); 187 | input.seekg(dataOffset, ios_base::beg); 188 | input.read(pixels.get(), size); 189 | 190 | //Get the data into the right format 191 | auto_array pixels2(new char[width * height * 3]); 192 | for(int y = 0; y < height; y++) { 193 | for(int x = 0; x < width; x++) { 194 | for(int c = 0; c < 3; c++) { 195 | pixels2[3 * (width * y + x) + c] = 196 | pixels[bytesPerRow * y + 3 * x + (2 - c)]; 197 | } 198 | } 199 | } 200 | 201 | input.close(); 202 | return new Image(pixels2.release(), width, height); 203 | } 204 | 205 | Image* loadPNG(const char* filename) { 206 | ifstream input; 207 | input.open(filename, ifstream::binary); 208 | assert(!input.fail() || !"Could not find file"); 209 | //check if png file 210 | char buffer[8]; 211 | input.read(buffer, 8); 212 | assert((buffer[1] == 'P' && buffer[2] == 'N' && buffer[3] == 'G') 213 | || !"Not a png file"); 214 | 215 | char* data; 216 | int width, height; 217 | 218 | //read header 219 | char type_buffer[4]; 220 | //read header length 221 | int len = readInt(input); 222 | printf("%d - len\n", len); 223 | input.read(type_buffer, 4); 224 | if(type_buffer[0] == 'I' && type_buffer[1] == 'H' 225 | && type_buffer[2] == 'D' && type_buffer[3] == 'R') { 226 | //grab width and height 227 | width = readInt(input); 228 | height = readInt(input); 229 | 230 | printf("\n\nheader - width: %d, height: %d\n\n", width, height); 231 | //read other header options like color type, bit depths 232 | char buff[5]; 233 | input.read(buff, 5); 234 | //check for RGB pixel data 235 | if((buff[0] == 8 || buff[0] == 16) 236 | && buff[1] == 2) { 237 | input.ignore(4); //CRC 238 | //store data. 239 | data = new char[width * height * 3]; 240 | int len_accum = 0; 241 | int len = 0; 242 | //read all data chunks 243 | len = readInt(input); 244 | input.read(type_buffer, 4); 245 | while(!(type_buffer[0] == 'I' && type_buffer[1] == 'E' 246 | && type_buffer[2] == 'N' && type_buffer[3] == 'D')) { 247 | printf("%c-%c-%c-%c ", type_buffer[0], type_buffer[1], type_buffer[2], type_buffer[3]); 248 | if(type_buffer[0] == 'I' && type_buffer[1] == 'D' 249 | && type_buffer[2] == 'A' && type_buffer[3] == 'T') { 250 | printf("data\n\n"); 251 | // char* d = new char[len]; 252 | // input.read(d, len); 253 | // for(int i=0; i < len; i++) { 254 | // data[len_accum + (len - i - 1)] = d[i]; 255 | // } 256 | // delete[] d; 257 | input.read(data + len_accum, len); 258 | len_accum += len; 259 | } else { 260 | printf("not data\n\n"); 261 | input.ignore(len); 262 | } 263 | 264 | input.ignore(4); //CRC 265 | len = readInt(input); 266 | input.read(type_buffer, 4); 267 | } 268 | } else { 269 | //TODO(nico) take care of other png formats also 270 | return NULL; 271 | } 272 | } else { 273 | return NULL; 274 | } 275 | 276 | input.close(); 277 | return new Image(data, width, height); 278 | } 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | -------------------------------------------------------------------------------- /v8-gl.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * v8-gl.cpp 3 | * 4 | */ 5 | 6 | #include "v8-gl.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | extern "C" void 13 | v8_typed_array_init (Handle target); 14 | 15 | Persistent V8GL::context; 16 | 17 | //UTILITY FUNCTIONS 18 | // Reads a file into a v8 string. 19 | Handle ReadFile(const string& name) { 20 | FILE* file = fopen(name.c_str(), "rb"); 21 | if (file == NULL) return Handle(); 22 | 23 | fseek(file, 0, SEEK_END); 24 | int size = ftell(file); 25 | rewind(file); 26 | 27 | char* chars = new char[size + 1]; 28 | chars[size] = '\0'; 29 | for (int i = 0; i < size;) { 30 | int read = fread(&chars[i], 1, size - i, file); 31 | i += read; 32 | } 33 | fclose(file); 34 | Handle result = String::New(chars, size); 35 | delete[] chars; 36 | return result; 37 | } 38 | 39 | bool exec(string file) { 40 | HandleScope handle_scope; 41 | Handle source = ReadFile(file); 42 | 43 | if (source.IsEmpty()) { 44 | fprintf(stderr, "Error reading '%s'.\n", file.c_str()); 45 | return false; 46 | } 47 | 48 | // We're just about to compile the script; set up an error handler to 49 | // catch any exceptions the script might throw. 50 | TryCatch try_catch; 51 | 52 | // Compile the script and check for errors. 53 | Handle