Archive

Archive for the ‘Internet’ Category

WebGL – Part 2: In the beginning there was…

February 27th, 2011 No comments

…a Triangle! In the previous part I presented WebGL, a new competitor in the graphics programming market. You got to know some history and parallel branches in the history of 3D graphics in the browser environment. Now, in this part you will see how to get a WebGL application into your browser.

The beginning

Last time was historical, this time we will get practical. In this part we will write one HTML page with embedded JavaScript code to draw a simple triangle through WebGL into an HTML5 Canvas. For that we will see how to set up a canvas, create a WebGL context, embed shaders and create a draw loop to present our triangle. Especially the shaders are an important topic regarding WebGL as WebGL is based on OpenGL ES 2.0 and OpenGL ES 2.0 does not support the fixed function transformation and fragment pipeline of OpenGL ES 1.x. Therefore, everything has to be done through shaders.

Note: What I present is an overview and user guide of WebGL, not OpenGL (nor OpenGL ES Shading Language)! WebGL could be seen as a wrapper for OpenGL ES 2.0 in your browser (and in the current state programmable by JavaScript). Therefore, I will not explain every OpenGL command or speciality. What is pointed out is just how to get your OpenGL knowledge into your browser. General programming knowledge and some HTML/JavaScript expertise may help. If you need help with OpenGL please refer to the masses of great tutorials in the net, especially NeHe and the OpenGL ES 2.0 Programming Guide (the main inspiration for this).

The Page

First of all we will set up our frame, our basic HTML file which we will use throughout this post. To write and develop HTML, JavaScript and therefore WebGL yourself you are pretty open to what to use. You can use a normal text editor or rely on a WebDevelopment environment but there are no distinct WebGL IDEs.
For WebDevelopment you can use Aptana or the direct Eclipse JavaScript Development Branch IDE. Both are fully fledged IDEs with great support, refactoring, auto-completion etc. Always a good simple helper is also Notepad++.
Everything shown here has been developed in Eclipse, Notepad++ and tested in Chrome 9. Chrome 9 is currently the only release browser download with enabled WebGL and has very good Developer Tools. Both is recommended for JavaScript development as debugging is kind of a pain in the a** (we will come to this in later parts).

If you have everything ready, have a look at the initial HTML scaffold:

  1. <!DOCTYPE html>
  2. <html>
  3.  <head>
  4.   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5.   <meta name="keywords" content="altdev,webgl,insanitydesign" />
  6.   <meta name="author" content="INsanityDesign" />
  7.  
  8.   <title>WebGL – Part 2: In the beginning there was…</title>
  9.  
  10.   <style type="text/css">
  11.    #canvas {
  12.     width: 640px;
  13.     height: 480px;
  14.    }
  15.   </style>
  16.  
  17.   <script type="text/javascript" src="webgl-utils.js" />
  18.  
  19.   <script type="text/javascript">
  20.    …
  21.   </script>
  22.  </head>
  23.  
  24.  <body>
  25.   <canvas id="canvas">
  26.   </canvas>
  27.  </body>
  28. </html>

This is the scaffold we will use throughout this part to show how to embed WebGL in a HTML file. You can copy it and save it as e.g. an webgl-part2.html file to open it with your WebGL enabled browser. At the moment, there is nothing to see or do. We will consequently fill it up and start using WebGL to draw our triangle.

One thing you might notice immediately if you have seen or written HTML pages before is the first line: <!DOCTYPE html>! This is the reduced Doctype used to init a HTML 5 page. You no longer have to write these long Doctype XHTML 1.0 transitional etc. Just that! Afterwards comes pretty general HTML stuff and nothing very special for our test.
Between lines 11 and 14 we define the width and height of our canvas we want to draw in through CSS. For now and the following we will stick with a classic 640×480. There are several ways to define the width and height of the canvas. As it is an HTML entity you can use everything that HTML allows. Regarding the WebGL drawing viewport we can refer to this size later on, increase or decrease the glViewport.
At line 17 you can see how to embed external JavaScript files into the page. We already embed one .js file in this case: webgl-utils.js! These utils provide some common methods for creating a WebGL context on a canvas. These are cross-browser compatible and actively maintained at Khronos, therefore it is unnecessary to rewrite these by yourself. You can download the original file from the Khronos CVS. Download and save the file at the same location where you put your HTML file. I will rely on these in this and the following parts.
The lines 25 and 26 define the initial canvas which we will use to draw in. It is just a simple HTML entity. We identify it by the id attribute as “canvas” but the naming is up to you (but you would have change other occurrences).

Now, the interesting things will happen in between line 19 and 21. This is where the magic will occur. In this showcase we will fill it part by part to get our triangle in the browser. Every code shown in the following should be copied in between here (or download the full file at the end).

Global Definition

At first, we will add some global variables that we will use in the following WebGL application. In addition, we define our triangle vertices and the mandatory fragment and vertex shader (add this where the dots are).

  1. <script type="text/javascript">
  2.   //Some global variables
  3.   var gl;
  4.   var width;
  5.   var height;
  6.   var canvas;
  7.  
  8.   //Our triangle
  9.   var vertsTriangle = new Float32Array([
  10.                     0.0, 0.7, 0.0, //Top
  11.                     -0.7, -0.7, 0.0,//Bottom Left
  12.                     0.7, -0.7, 0.0  //Bottom Right
  13.   ]);
  14.   var vertsTriangleBuffer;
  15.  
  16.   //Fragment Shader
  17.   var shaderFS = "precision highp float;\n\
  18.          void main() {\n\
  19.            gl_FragColor = vec4(1.0, 1.0, 0.2, 1.0);\n\
  20.          }\n";
  21.  
  22.   //Vertex Shader    
  23.   var shaderVS = "attribute vec4 position;\n\
  24.          void main() {\n\
  25.            gl_Position = position;\n\
  26.          }\n";
  27.          
  28.   //The shader program
  29.   var shaderProgram;

We define handles for the created GL context we want to re-use throughout this page as well as the width and height of the canvas into which we want to draw. Do not forget the canvas itself, of course. Afterwards we set up the three vertices of our triangle in vertsTriangle.
You may have noticed that we do not type the width/height or gl handle. All variables are just noted as (mutable) var‘s. As JavaScript is a dynamically typed language this is fine. The definition happens as soon as it assigned. But it is never strongly typed for dynamic variables and therefore can rely on different sets of types. Nevertheless, you can also type your variables.
As JavaScript is required to be more and more with high performance inside your browser an initiative started to define some specific arrays to speed up the applications. These Typed Arrays such as the used Float32Array are still in a draft state as well as WebGL but will be released and supported probably in parallel to it.

After the vertices array you can see the fragment and the vertex shader code. Here, it is assigned as String to a JavaScript variable. If you would copy these and remove the special symbols you will get a normal shader as you might know. Here, we explicitly define the end of each line through \n\. This looks odd but is required to compile it later on as the shader source is required to be an array. Therefore, you could also write:

  1. var shaderFS = [
  2.     "precision highp float;",
  3.     "void main() {",
  4.     "gl_FragColor = vec4(1.0, 1.0, 0.2, 1.0);",
  5.     "}"
  6. ];

Both things would work. It may seem pretty odd to write everything directly into these arrays/variables but for now it’s enough as we only need one shader each. In a ladder part we will see how to load/reload specific shaders into your application.
The last thing we already pre-define is a variable for our later assigned shader program.

Entry point

JavaScript itself and in its browser environment have no specific entry point such as a classic main method. Therefore, we have to create an entry point ourself based on the principles of the DOM loading of the WebPage. As we want to start our WebGL application as soon as the actual body of the page (with our canvas) has been loaded, we add a trigger to the body itself. The trigger is docked onto the onLoad delegate of the body:

  1. <body onload="main();">

By that we listen for the body to be loaded (the canvas has to be created in the DOM up to that) and fire our main() method where we start with our part of the application:

  1. /**
  2.  * The main entry point
  3.  */
  4. function main() {
  5.   //
  6.   canvas = document.getElementById("canvas");
  7.   gl = WebGLUtils.setupWebGL(canvas);
  8.   //Couldn't setup GL
  9.   if(!gl) {
  10.     alert("No WebGL!");
  11.     return;
  12.   }
  13.  
  14.   //
  15.   width = canvas.width;
  16.   height = canvas.height;
  17.  
  18.   //
  19.   if(!init()) {
  20.     alert("Could not init!");
  21.     return;
  22.   }
  23.  
  24.   //
  25.   draw();
  26. }

In the first 8 lines we init our canvas and the WebGL context for it. First, we retrieve the canvas element from the DOM through its id “canvas”. Then we call a method from the downloaded WebGL Utils to create and enable the WebGL context of that canvas. Please have a look at part 1 to see what is done in that method. Basically, we utilize the generalized setupWebGL(canvas) method to be cross-browser compatible as there is still no distinct method to init a WebGL context.
Afterwards we retrieve the width and height from the canvas (as defined in the CSS) to reuse these in our glViewport later on. Then we fire a general init() method to setup everything WebGL we need:

  1. /**
  2.  * Init our shaders, buffers and any additional setup
  3.  */
  4. function init() {
  5.   //
  6.   if(!initShaders()) {
  7.     alert("Could not init shaders!");
  8.     return false;
  9.   }
  10.  
  11.   //
  12.   if(!initBuffers()) {
  13.     alert("Could not init buffers!");
  14.     return false;
  15.   }
  16.  
  17.   //
  18.   gl.clearColor(0.0, 0.0, 0.0, 1.0);
  19.   gl.viewport(0, 0, width, height);
  20.   gl.clearDepth(1.0);
  21.  
  22.   //
  23.   return true;
  24. }

In general, the init method follows three steps:

  • Init our shaders
  • Init our buffers (our triangle buffer)
  • Set up the clear color, depth and our viewport

Step 3 should be self-explanatory, therefore we will continue with loading and setting up our shaders.

Load the Shaders

You already saw our two shader variables. Now, we want to compile, attach and link these. For that we require two methods: initShaders() and createShader().

  1. /**
  2.  * Init our shaders, load them, create the program and attach them
  3.  */
  4. function initShaders() {
  5.   //
  6.   var fragmentShader = createShader(gl.FRAGMENT_SHADER, shaderFS);
  7.   var vertexShader = createShader(gl.VERTEX_SHADER, shaderVS);
  8.          
  9.   //
  10.   shaderProgram = gl.createProgram();
  11.   if(shaderProgram == null) {
  12.     alert("No Shader Program!");
  13.     return;
  14.   }
  15.  
  16.   //
  17.   gl.attachShader(shaderProgram, vertexShader);
  18.   gl.attachShader(shaderProgram, fragmentShader);
  19.   gl.linkProgram(shaderProgram);    
  20.  
  21.   //
  22.   if(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
  23.     alert("Could not link shader!");
  24.     gl.deleteProgram(shaderProgram);
  25.     return false;
  26.   }
  27.  
  28.   //
  29.   gl.useProgram(shaderProgram);
  30.  
  31.   //
  32.   shaderProgram.position = gl.getAttribLocation(shaderProgram, "position");    
  33.   gl.enableVertexAttribArray(shaderProgram.position);
  34.  
  35.   return true;
  36. }
  37.  
  38. /**
  39.  *
  40.  */
  41. function createShader(shaderType, shaderSource) {
  42.   //Create a shader
  43.   var shader = gl.createShader(shaderType);
  44.   //
  45.   if(shader == null) {
  46.     return null;
  47.   }
  48.  
  49.   //
  50.   gl.shaderSource(shader, shaderSource);
  51.   gl.compileShader(shader);
  52.  
  53.   //
  54.   if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  55.     alert("Could not compile shader!");
  56.     gl.deleteShader(shader);
  57.     return null;
  58.   }
  59.  
  60.   //
  61.   return shader;
  62. }

At the beginning of initShaders we call our createShader method with the type of the shader and the according shader source variable. The called method createShader does exactly what the name suggests: It creates a shader based on the given type, compiles the given source and returns the created glShader.
Actually nothing special here as it is just a helper method. If we would hand over the shaderSource in a different format we will probably extend this method to convert the given shader source to a common format. But for now this is fine.
One speciality you can find is the error handling: Throughout the page you can find alerts and empty returns. As we have no specific exit() call in JavaScript or HTML (there is a possibility, but we will not use it later on) we alert the user, firing a MessageBox and empty return. As catched in higher instances this will result in a jump out of the application which leads to a manually “stopped” application. As we entered by ourself through the main() method, we can jump out any time we want. An alert() may not be the nicest way to show errors and exit the application but it at least gives feedback. Later we will see how to combine HTML entities, CSS and WebGL and will use the normal HTML functionality to fire error messages and according to the error lead the user to a solution or mail these errors to the developer.

After we loaded and created our shader we start creating our program at line 10. Again we check for an error that may have occurred. If no error happened we attach both shader objects, link the program and if nothing happened, use it.
If you know OpenGL you might say: Still nothing that special here!… and this is intended. WebGL was intended as a low-level programming opportunity without too many specialities away from the original uses of OpenGL. This was done with VRML and many other special plug-ins but never lead to what was expected as commonly used 3D in the browser.

Nevertheless, one speciality about JavaScript is being used now: The dynamic prototyping. You can see at the end that we return “the index of the generic vertex attribute that is bound to that attribute variable” and we assign it to the shaderProgram as position.

  1. shaderProgram.position = gl.getAttribLocation(shaderProgram, "position");    
  2. gl.enableVertexAttribArray(shaderProgram.position);

This is possible even if we haven’t predefined that variable in the shaderProgram object. We dynamically extend and create a new prototype by assigning the position without prior definition.
This should never be used as best practice as there is no contract we can rely on, e.g. through a specifically defined class, structure or interface. In this simple case as we do not need reusable and generic objects we just assign the handle for later reuse in our own “knowledge space”. Regarding classes and interfaces for contracts, these are all possible in JavaScript and we will come to that in a later part.

But now our shaders are (hopefully) all loaded and assigned so that we can continue setting up our triangle vertices buffer.

Setup the Buffer

To set up the buffer based on our vertices we go straight forward:

  1. /**
  2.  * Init our required buffers (in our case for our triangle)
  3.  */
  4. function initBuffers() {
  5.   //
  6.   vertsTriangleBuffer = gl.createBuffer();
  7.   gl.bindBuffer(gl.ARRAY_BUFFER, vertsTriangleBuffer);
  8.   gl.bufferData(gl.ARRAY_BUFFER, vertsTriangle, gl.STATIC_DRAW);
  9.  
  10.   //
  11.   return true;
  12. }

Absolutely nothing special here! We create the buffer and assign it to our global variable, bind and set the according data. This will become more complicated in later parts, when we define structures, load models etc. But as we just want to draw one triangle this is enough.

Let’s draw

What we really want to do after all this work now is to draw. Therefore, we define our draw() method:

  1. /**
  2.  * Our draw/render main loop method
  3.  */
  4. function draw() {
  5.   // request render to be called for the next frame.
  6.   window.requestAnimFrame(draw, canvas);
  7.  
  8.   //
  9.   gl.clear(gl.COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
  10.  
  11.   //
  12.   gl.bindBuffer(gl.ARRAY_BUFFER, vertsTriangleBuffer);
  13.   gl.vertexAttribPointer(shaderProgram.position, 3, gl.FLOAT, false, 0, 0);
  14.  
  15.   //
  16.   gl.drawArrays(gl.TRIANGLES, 0, 3);
  17. }

As you can see no immediate drawing here for this very simple example. This again relates to WebGL and its origin OpenGL ES 2.0: Besides no fixed-function pipeline there is no immediate drawing. We just clear, bind our buffer and draw!
But wait, how do we draw? I said we have no specific entry point and created one ourself. If we have no specific entry point we probably also have no specific draw() loop we can rely on. Again, we have to create on our own. Here again we will rely on a method from the WebGL Utils and the according best practice from Khronos.

In the end of our main method, after all initiations we call our draw() method once:

  1.   //
  2.   draw();
  3. }

After the initial call, in the first line of the draw method we call up a utils method: requestAnimFrame(draw, canvas)! This cross-browser compatible method takes the canvas in which to draw and the according method as callback. Inside is a timeout that will recall and keep the loop running. Currently this is the recommended way to do a loop. But it has to be noted that this not final. You can see the drawbacks immediately in the timeout and in the call directly in the draw method. For now until we see a final call and the draft has been approved we will stick to that as it is nevertheless cross-browser compatible and works fine.

Now, if you copied and setup everything correctly you should see the following:

You can download the full source here. If you downloaded the webgl-utils.js put it at the same location as the HTML file.

This is it… at least for now. There are still some “not so ideal” things here as this is neither best practice nor the only way to program JavaScript and therefore WebGL. Everything is embedded directly into the HTML page, everything is handled as one. The shaders are odd string variables and the process is very focussed around “just work”. But this was intended for now. Now, you have a page you can use as an initial foundation for further experiments. For example, try fooling around with the shaders and see what happens.

Next time we will get into User Input and show how to make the triangle move to the rhythm of our key strokes (and build up our own matrix). In the following parts afterwards I will present how to load textures, load models and operate with several shader files, dynamic loading and obfuscated JavaScript.

Written for #AltDevBlogADay

Bookmark and Share

WebGL – Part 1: A new challenger appears…

February 13th, 2011 No comments

As I did not want to be as somewhat polemic as last time I checked several different pragmatic ideas I could post about. I weighted each against the other but with the news that the final draft of WebGL was released I decided to go this route and present some information, basics and a furthermore small tutorial in the following parts about WebGL!

A new challenger appears

Twelve years after HTML4 and eleven years after XHTML1.0 the WorldWideWeb Consortium “finally” dropped all efforts to standardize another, a different and more XML-based standard for the Web and continued where they left off to extend HTML4 to built it up to the requirements of our current time. As we are easily able to define that our current web-browsing habits are influenced by multimedia-based content with YouTube, Facebook, Farmville, Podcasts, … the new standard would have to be more multimedia flexible. And W3C listened!

The consequent successor HTML5 was finally started in 2008. Now, only three years later the standard is seeing the finishing line and most released drafts have already been implemented in common browsers such as Firefox, Chrome or Safari through WebKit. It provides special video, audio and canvas elements, support for codecs such as OGG Theora/Vorbis and MP4 (still a little dependent on decisions and implementation as it is still not final, possibly WebM), semantic support based on RDFa, sectioning etc. and a native 3D API named WebGL!

WebGL is a specification, independent from HTML5 but depending on the Canvas element of the standard. It is implemented as a context of the canvas and can be programmed (for now, actually more will be possible) through JavaScript and shaders. Speed and some specifics are dependent on the actual implementation i.e. the Browser but in general interchangeable in-between different Webengines.

Therefore, WebGL offers native in-browser support for 3D development. But actually the idea of 3D in your Browser is not a new challenge for our beloved internet…

3D on the Web

Already in the early days of the WorldWideWeb several different developers, companies and initiatives tried to establish 3D in the browser to provide a more persuasive environment for the user, correlating what was currently being established in games, that became more and more 3D focused during these years.
Already released in 1995 the Virtual Reality Modeling Language (VRML) tried to bring 3D to the Web. VRML 1.0 allowed to define the geometry, textures, materials etc. and especially scripts to visualize a 3D scene in a common textfile format. This scene was additionally able to retrieve additional data from different URLs as well as to react to events and triggers through special Java/JavaScript programs in its script nodes. Later it was extended to allow animations, sounds and other multimedia assets in 1997 with the VRML 2.0 standard.
The problem with VRML was mainly that it required a plugin to be installed in your browser as well as much processing power. Most plugins weren’t optimized and the scenes described in a very high-level style required too much load. There were some initiatives but besides some world viewers and websites of authorities no one really jumped onto VRML.

In 2001 the Web3D Consortium built a new high-level abstraction for 3D in the Browser: X3D. X3D extended VRML with more standards and especially profiles, shaders, gis and networking. It still requires a plugin or player and was therefore not as perceived as wished for.

As WebGL is more established and well-supported already by nearly every big browser on the market the Web3D initiative now jumps onto that train without giving up VRML and X3D. With X3DOM the initial specification and implementation is now being made available on your browser without the need of plugin a but with the power of WebGL and Canvas.

Nevertheless, in this multi-part series I will only focus on WebGL directly. If you want to know more about these “historic” approaches just follow the given links.

OpenGL in the Browser

In contrast to VRML or X3DOM WebGL follows a more direct (“low-level” in comparison) approach to 3D in the Browser. As the name suggests WebGL is based on OpenGL and specified by The Khronos Group. It is based on OpenGL ES 2.0 (nowadays good known from iOS and Android) and supports GLSL in version ES1.0. It docks onto the HTML5 canvas as a drawing context and with that it is fully integrated in the Document Object Model (DOM) and therefore allows full interaction with the general HTML Layout and Objects (e.g. overlaying, CSS styles, …).

As mentioned, as well as OpenGL WebGL is low-level and fully based around shaders. Therefore, things like defining simple geometry and scenes in an easy XML format as it is possible with X3D is not part of the WebGL standard itself. Possible implementations and APIs on top are nevertheless feasible (and already developed to some degree).

You can nearly cope everything you know about OpenGL ES 2.0 into WebGL. But there are some limitations (besides what is currently still different in-between the different Browser implementations). One important difference is that WebGL has no support for non-power-of-two textures (you could disable mipmapping). You have to resize dynamically. But in general you can feel with WebGL as you do with ES2.0 in other programming languages. It even looks similar. Let’s have a look at an exemplary draw() method (taken from the OpenGL ES 2.0 Programming Guide):

  1. function Draw(esContext) {
  2.    var userData = esContext.userData;
  3.  
  4.    // Set the viewport
  5.    gl.viewport( 0, 0, esContext.width, esContext.height );
  6.  
  7.    // Clear the color buffer
  8.    gl.clear( gl.COLOR_BUFFER_BIT );
  9.  
  10.    // Use the program object
  11.    gl.useProgram( userData.programObject );
  12.  
  13.    // Load the vertex position
  14.    gl.bindBuffer( gl.ARRAY_BUFFER, userData.vertPosObject );
  15.    gl.vertexAttribPointer( userData.positionLoc, 3, gl.FLOAT, false, 0, 0 );
  16.    gl.enableVertexAttribArray( userData.positionLoc );
  17.  
  18.    // Load the index buffer
  19.    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, userData.indicesObject );
  20.  
  21.    // Load the MVP matrix
  22.    gl.uniformMatrix4fv( userData.mvpLoc, false, getAsFloat32Array(userData.mvpMatrix) );
  23.  
  24.    // Draw the cube
  25.    gl.drawElements( gl.TRIANGLES, userData.numIndices, gl.UNSIGNED_SHORT, 0 );
  26. }

Looks pretty familiar, doesn’t it? A description of what this all means and how to really program it in JavaScript and embed it into a WebSite will follow in the coming parts.

Browser support

For the User
First of all you have to be able to see and test WebGL developments. Currently the easiest way to use WebGL is to install the current Chrome Browser. Since version 9 it has enabled WebGL support in its stable release. If you want to use other Browsers such as Mozilla or Safari you would have to get the according nightly builds. In each case you might need to configure the according download. For a small “manual” have a look here or be lazy and use Chrome.

For the Developer
If you want to develop WebGL in a supporting Browser, you check for and enable WebGL through JavaScript by actually just trying and checking for success. There are two things you have to do:

  • Check if the browser supports WebGL in general
  • Find/Get a canvas and enable the WebGL context for it

To check if your browser or more specifically the current window you are in allows WebGL you check for a specific window flag:

  1. if(window.WebGLRenderingContext) //This Window supports WebGL in general!

If this context returns true at least the Browser does support WebGL. Now, you need to check a canvas and enable the WebGL context in that canvas. Normally, you would specify a <canvas> element and hand this to a check and enabling function:

  1. function(canvas) {
  2.   //Several names to check because of still diverse implementations
  3.   var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
  4.  
  5.   //The context we want to fill
  6.   var context = null;
  7.  
  8.   //Iterate over all names and test for success
  9.   for(var i = 0; i < names.length; ++i) {
  10.     try {
  11.       context = canvas.getContext(names[i]); //Optional parameters can be handed to the implementation
  12.     } catch(e) {}
  13.    
  14.     //As soon as we got one -> SUCCESS!
  15.     if(context) {
  16.       break;
  17.     }
  18.   }
  19.  
  20.   return context;
  21. }

If no context can be received but the WebGLRenderingContext says it may do WebGL, some other problems occurred. If the browser supports, you have enabled and retrieved the WebGL context and can start developing applications in your browser with fancy JavaScript.

The “new” power of JavaScript

Actually, nothing is “new” about JavaScript. The JavaScript used to first make a clock tick down on a Website, later to “do AJAX” or now to develop WebGL is pretty much all the same and based around the ECMAScript standard. Even if it contains Java in its name it has nothing to do with it. The former LiveScript is supposedly just named JavaScript to establish it with the already established Java… and probably because of a somehow Netscape/Sun partnership. But do not hesitate: The interpretation of JavaScript during runtime has been incredibly speeded up especially over the last years as more and more client programming is now part of normal websites and administrative interfaces reload and rebuild many things on-the-fly.

For JavaScript itself, it is first and foremost a prototyping programming language. This means that instead of developing a class-based architecture structure that is instanciated and dependent to the initial implementation and used throughout your development, in JavaScript you “re-use” the same classes for all instances with all given methods (called behaviours) that are added at first or also during runtime. These can be extended by the developer. Further the instances made from the structure are the states. In general you could say that prototyping is based on copying: It copies the “prototype” over and over again! Now, the most important thing about the prototype implementation of JavaScript is that it also holds a link to its “prototype” and therefore derives recursively through the prototyping hierarchy to find what we request.

A very simple example: We define a Blog!

  1. var personalBlog = { title="Personal Blog", author="Savas Ziplies" };

Now we define a second blog:

  1. var altDevBlog = { title="AltDev Blog" };

and assign our personalBlog as prototype:

  1. //This does not work in all JavaScript implementation (as not all have the direct prototype to be settable), but for the example we rely on it!
  2. altDevBlog.__proto__ = personalBlog;

Now we query

  1. alert(altDevBlog.author + "@" + altDevBlog.title);

and will get the following result: Savas Ziplies@AltDev Blog! As you can see, even if I have not defined “author” in altDevBlog I may still access it as I specifically set the prototype of altDevBlog to personalBlog, therefore the “author” not available is resolved at the prototype personalBlog and printed. This hierarchy can go on and on forever and can be a performance issue if not consciously developed against. But in general prototyping and JavaScript itself offers many patterns that go well with WebGL and designs in general.

Therefore, JavaScript depends on a little different “thinking” approach. But besides that JavaScript also provides “somehow” object-oriented principles, delegation, dynamic typing, closures, run-time evaluation (very helpful indeed) and much more. Actually, JavaScript is a very powerful and somewhat interesting programming language but just seems awkward to most people because of its syntax, the name and because it is an interpreted language. Nevertheless, you can do practically everything with it, also relying on nearly every design pattern described.

To be concluded…

As I do not want to write a book as I did last time (yeah, hard to believe ^^’), this is it for today. You now know some history, the basic standard and how to “use” WebGL applications. The next parts will feature of course further explanations of WebGL, an additional introduction to JavaScript (and some of the creepy stuff you can do with it), presenting already existing WebGL libraries and an exemplary tutorial game developed fully in WebGL (as well as some twists and tweaks around networking and dynamic loading). In addition we will try to clarify how WebGL stands against other 3D in the Browser such as Flash3D, Unity3D and Shiva3D.

To already give you a taste of what to come and what is possible with WebGL, have a look at these publicly available WebGL Samples over at Googlecode, the astonishing Google Body example or the nice presentation of GLGE in the video.

Written for #AltDevBlogADay

Bookmark and Share

There are no Casual Games…

January 27th, 2011 1 comment

…but Casual Gaming (and Casual Gamers)! Wait, wait… Before you stop reading and ask yourself why I would make such an offensive proposition, please hear me out.

My Origin
I have a very tense relation to the terms Casual and Core Games that found on three things: 1) I am getting older and my best “Gamer” times are over ^^’, 2) I develop Browser Games and 3) I develop in Java! A very bad combination to go into a Game Developer discussion… trust me!
I am a Gamer for over two decades now, started with Pong and played a high percentage of every mentionable game ever made. Studying Computer Science and developing Games was a reasonable step and I like what I am doing now, I am good in what I do (yes, I am ^^), developing Games and I am proud of what I achieved until today. But nowadays if I mention that I develop Games, I get asked:

  • “Oh, very cool. What Games?”
  • “Browser MMOs”
  • “Ahhh…*pause*… Casual Games!”

Even with swallowing the bitter taste of that sentence I somehow feel unvalued for being part of one of the largest Browser Games around, over four years old, still growing and established way before Facebook. A massive simultaneous multiplayer game, relying heavy on PvP, time intensive and based on a very technical Story. All features that are normally related to so called “Core Games”. But if a Browser Game features such elements why is it that the term “Browser Game” is instantly related to “Casual Game”? And why in general is “Casual Game” leading to the idea of “not a real game”?
In my specific case Browser and Casual is not the only evil term. The dialog above often continues as follows:

  • “Why do you think I develop a Casual Game?”
  • “It’s in the Browser… probably Flash.”
  • “I am Java Developer.”
  • “I think you said you develop Games. How can you develop Games in Java?”

But that is another story I will cover in another post ^^’.

My Problem
Another thing that leads me to my “new” thinking was the evolution of my own gaming habits. As mentioned, I am a Gamer, a Core Gamer you would say, played Games from Wolfenstein 3D to Call of Duty: Black Ops, from Half-Life over CS to TS2, from Zork to The Whispered World. I owned and own Handhelds, Consoles and PCs. I spent ages playing through games each day after school, alone or with friends. But over time my gaming habits changed through studies and now a whole lot of work. I am still a Gamer, just tested the newest Crysis 2 and Bulletstorm Demos… but the actual gaming sessions changed!

I am part of the working community now. Most of the day I am sitting at my work desk and if I get home I have some commitments to do or just want to get some peace. Nevertheless, my Civilization is teasing me to conquer the world, while Snake is asking me to finally complete the Mission, besides Kane & Lynch still arguing. Everything becomes a Quest that Puzzles me and I get Angry like the Birds outside my Windows (couldn’t find a transition to my iPad here ^^).
So, every evening I really have to decide what I do and IF I play. And even if I play, the time a playing session takes reduced a lot nowadays. For example, I played Plants vs. Zombies as well as Dead Space. I played Mirror’s Edge as well as Angry Birds. All four games would be categorized into Casual and Core Games, but the way I played them somehow did not fit the definition. I played Plants vs. Zombies for hours straight but Dead Space actually in 15-20 minutes chunks until the end (not only because it was scary). Mirror’s Edge I played through in one session but Angry Birds just 15 minutes some evenings.
Now, with the advent of all this classification that somehow does not fit my overall love for games of every type that “entertains” me, I questioned myself: Am I doing something wrong? Or is the classification not practicable?

The Definition
With that many inconsistencies in my general understanding of Browser and further more Casual Games I tried to find a conclusive definition. During the search of a definition I had to notice that I never read so many different ways of defining something, especially as most definitions come down to attitudes of the writer. Because of that, let’s start with a “not so ideal” example from the Urban Dictionary:

Casual games are any kind of game that is over hyped and over rated or just the exactly same thing as a previous version that was over hyped and over rated, these games are known by gamers as “crap” because even with all the perfect scores the games still have mediocre graphics and shitty plots that casual gamers think are good. Usually the only thing that makes a casual game not-total shit is the multiplayer; otherwise these games would get ratings lower than dirt.
With shitty graphics and a generally horrible campaign mode, the halo series is the indisputable king of casual games.

But all jokes aside, for a more serious definition from the IGDA Casual Games SIG from 2005/2006:

The term “casual games” is used to describe games that are easy to learn, utilize simple controls and aspire to forgiving gameplay. Without a doubt, the term “casual games” is sometimes an awkward and ill-fitting term ““ perhaps best described as games for everyone. Additionally, the term “casual” doesn’t accurately depict that these games can be quite addictive, often delivering hours of entertainment similar to that provided by more traditional console games. To be sure, there is nothing “casual” about the level of loyalty, commitment and enjoyment displayed by many avid casual game players ““ just as there is nothing “casual” about the market opportunity and market demand for these games.

That is an interesting definition. Let’s have a look at some more. Wikipedia describes:

Most casual games have similar basic features:

  • Extremely simple gameplay, like a puzzle game that can be played entirely using a one-button mouse or cellphone keypad
  • Allowing gameplay in short bursts, during work breaks or, in the case of portable and cell phone games, on public transportation
  • The ability to quickly reach a final stage, or continuous play with no need to save the game
  • Some variant on a “try before you buy” business model or an advertising-based model

The CasualGameWiki as well as About.com extend the definition with specifics about the price point and the platforms:

  • Style Of Play: Casual Games are now considered “games for everyone” – with a special emphasis on whether your mom can play it.
  • Distribution: Casual Games are frequently distributed with a “Try Before You Buy” model. Where a person can play for an hour for free and then decide whether to purchase or not. This model of play grew out of the Shareware distribution model.
  • Casual Games are usually sold for $19.95.
  • Platforms: Casual Games can now be found on Cell Phones and Consoles such as XBox 360 via the Xbox Live system.

and

Casual games are most often played via a Flash or Java based platform on a PC, but are now appearing in larger quantities on video game consoles and mobile phones.

The definitions often come with a timeframe of around the millennium or 2001.

An Interlude
Let’s move away a little from the term “Casual Games” and the definitions given and have a look at the last sentence: The Year! If we take a look on what happened and was released around that time that is somehow “defined” as the origin of the term we will find things like the Playstation 2 (2000) and the Xbox (2001). While the Playstation 1 was still a child of the “old” console generation especially the Playstation 2 as well as the Xbox introduced the “new” generation of consoles, away from old Entertainment Systems we adored. More important is that with the new generation the games from the “old world”, the Personal Computer, and the consoles were starting to congregate. Complexity from the PC moved to consoles and simplicity of the Consoles moved to the PC.
On the PC Flash was released in version 4.0 in 99 and one year later in version 5.0. These introduced and extended Flash’s own programming language ActionScript. From here on Flash was not only a way of playing frames off a timeline but introducing conditional actions onto these. More and more Flash Games started popping up. Around the same time Java 1.3 was released introducing the HotSpot VM and building the foundation for JavaME (J2ME at that time) that brought gaming very heavily to normal phones.
This interlude is important to understand how Games opened up to a larger community (yes, long before the Wii) away from the nerdy PC hardware geeks that “pimped” their autoexec.bat to play games as of today these build a large majority of the people defining and mostly complaining about “Casual Games” (no offense).

The Ambiguity
If we sum up the definitions the following list could be seen as a general understanding of Casual Games:

  • Easy to learn/simple gameplay
  • Simple controls
  • Forgiving Gameplay/quickly reach a final stage
  • Gameplay in Short Bursts
  • Games for Everyone
  • Up to 20$
  • Try before you Buy
  • Flash and Java Games on the PC side/DLGames on XBoxLive, PSN, etc.
  • Since 2000/2001

This list looks pretty decent doesn’t it? As you can guess from the headline the list is not as decent as I hoped it to be. I often refer to these hand full of games that somehow should fit these rules, are named casual but do not really allow a distinct identification of what a casual game should be.

Let’s start off with Plants vs. Zombies (one of my favourites over the last years). This modified Tower Defense game is a success on every platform. First released in 2009 it sold and sold and people rated it effusively. It’s a great game that just brings a ton of fun. If we look at our list we can see that it looks pretty good: It costs under 20$, the controls are simple and it is downloadable on PC, iOS and XBoxLive. Regarding the gameplay, it is simple and easy to learn… because of the many tutorials, and can be hard to master. This makes this game attractive to be played for just some minutes or for hours fiddling on the new strategies and therefore attracting Casual Gamers and Core Games as well as hybrids like me. It provides Casual Gaming and more, for Casual and Core Gamers. So, is this a Casual Game?
My second example would be Super Meat Boy (and N/N+ in parallel). This 2010 hit platform game has gone through different stages of the list. It was a Flash Game first, ported, tuned and extended for the PC and Consoles. Over 300 mostly short levels (short bursts) with a very gory portion of simple gameplay. It is also cheaper then 20$ and has some very simple controls. But it is extremely hard to master forbidding the slightest error ending in a pure gore fest. And actually (as PETA already noticed ^^’) this is no “game for everyone” anymore because of its scenario and its quickly increasing difficulty level. Hardly a Casual Game, isn’t it?
My third example is Prince of Persia (the one before the crappy Movie Game). Not a typical Casual Game and was more expensive then 20$. But if we look at some definitions it fits as much as the previous two examples: It has forgiving gameplay (yes, I mean you Elika), had a Demo, was easy to learn but had not the easiest controls. The save points were pretty frequent and it had a scenario that even my casual sister was able to relate to. Still Core or did it become Casual?
My fourth example is Lara Croft and the Guardian of Light. A franchise that may have brought many women to gaming, featuring intense 3D platform gaming and 3rd Person Shooting Gameplay. With GoL it became a DLG with a strict isometric perspective. It’s on PC and Consoles, downloadable, costs under 20$ and has (in my opinion) simple controls to master the fine placed action and puzzles. Now, are Tomb Raider and Lara Croft becoming casual? Is it just that game? Or does Lara Croft not count?
My fifth example (to use the full hand) would be every Wii Game. Nearly every gaming site and every “Core Gamer” defines a Wii Game as a Casual Game. Why? Because your Family got into “your hemisphere”?

In general if we just take some of the bullet points, some of the definitions describe things that nearly every game, no matter if Casual or Core, wants to achieve nowadays or is a general gaming tradition:

  • Try before you Buy

Demos, Shareware, … Nothing new to the experienced Gamer and Games in general.

  • Gameplay in Short Bursts

Actually, this is something popping up more and more since the advent of consoles. PC users are used to saving games, being able to use up space on their hard disc. For console gamers this was no natural thing to use so developers very often used stages with manual and automatic save points that were not separated too far away from each other to not enrage the player if he dies. I mentioned Dead Space and my very tight gaming sessions playing through it. This was only possible because of the very “controlled” stages and their save points that I could reach in the given time frame.

  • Forgiving Gameplay/quickly reach a final stage

This as well is something that especially First-Person-Shooters nowadays provide to the user. “Old” Gamers remember a time when it was a necessity to know where the next HealthPack is. Today, we rely on a regenerative system, often presented with the argument to be more accessible to more gamers (“games for everyone”). Becoming casual? And regarding the second part, I could get heretical now but games such as Modern Warfare do not really provide that much gaming time to the user anymore. 5-6 hours are some times normal.
The problem is that gaming following the definitions given is way older. This is why gameplay elements can hardly be used to define the games themselves. What is left are technical definitions, prices as well as hardware to describe the so called “Casual Games” and these obliterate more and more.
So, with all this ambiguity coming from the point of defining the Game, wouldn’t it be better to define the interaction?

Classic Classification
We tend to define things based on their surroundings and the “object” using the “subject” (“People Playing a Game” in our case) because that is what we visually perceive. And as it is easy for us to define unknown things from what we know, we derive the Browser into our experience of Casual Games as the Browser was never a dedicated environment for games but so many things that so many people do, not only gamer. Therefore, it is very easy for “Core Gamers” to define games such as Plants vs. Zombies as Casual Games as their Moms or Dads are playing them.
The problem with the classification and the according definitions of Casual Games is that they try to really define constraints where these games may fit in. In a time where it becomes harder and harder to “just” define the Genre of a game (e.g. Puzzle-Survival-Horror Adventure-Games) it is even harder to define an umbrella term of games in general. But my personal strongest point regarding the definition of “Casual Games” is that most of the people that play “Casual Games” do not even know that these are “Casual Games” (or did your Mother or Sister ever talked about Casual Games when playing Wii or DS?).
The classification normally is given by “Core Gamers”, Developers or Game Editors that want to separate themselves from these “unappreciated” games (in many cases). But what we were able to see from the definitions normally used to describe Casual Games is that these do not fit the real world anymore. Especially as they evolved over the last years, away from most simplistic Flash Games to the best gaming experiences of the last decade (e.g. Darwinia, Braid, Limbo and more)

What is required is to divide not only Games but the interaction, the gaming. For gameplay we have genres. Now, we need a new graduation for Facebook, Flash, Indie and everything else that evolved our gaming experience (and will in the future). To what this New Classification could be, I can give you no answer. This needs a long discussion and a broad overview of everything gaming has to offer nowadays.
But what all Gamers need to do is to be open minded to new possibilities and not argue with the term “Casual Game” anymore, especially those that call themselves Core Gamer. I think we all do not want to hear another: “Epic Mickey is a Casual Game. It’s on the Wii!“

My Conclusion
My intention was to make a polemic assertion, presented with my experience, many questions and concluded with my own ways of thinking. If you were looking for THE definition of Casual Gaming, this post does not deliver. It just brings up some things that do not work out in our current scheme of games classification and with the ever growing amount of releases that qualify to our current definition of Casual Games we should quickly start thinking about a new way of filtering, fitting all modern characteristics such as Facebook, iOS and Android, Unity/Shiva/…, Steam and all the other new ways of developing, presenting and distributing games, challenging the “old way” of games development.
I started off with arguing that there are no “Casual Games” but “Casual Gaming” and I tend to support this even if I give away no new definition because such a broad definition of games cannot be made, if the gamers that count are so broad and different themselves. I agree that I only presented arguments for my theory but as long as it is possible to oppugn the current definition that easily it is in our hands to discuss and define better definitions for our most beloved games… that are changing pretty quickly right now!

Written for #AltDevBlogADay

Bookmark and Share

The Chronicles of Spellborn – Free to play begins now!

August 20th, 2009 2 comments

TCOS is coming F2PTwo days ago, the USA version of The Chronicles of Spellborn, published by Acclaim went F2P. Today they made this step official. You can go to their website, register a free account and download the about 3GB, install and start playing. I recommend it, as TCOS features a new, active and live fighting system (which I like very much). It also has a very believable world, which does not follow any large license but cooks its own soup. Something I like, as it also encourages you to explore. Now, you can make up your mind yourself as it is free! For those that already played TCOS at the beginning, please note: It has changed nearly completely in my opinion! It is far more user friendly, the interface got better, the guidance, the environment more lively…
It was announced some weeks ago that the European Servers shutdown and The Chronicles of Spellborn will nevertheless continue as a F2P, beginning from next year. This is fantastic, as so many good but not great MMOs (like Tabula Rasa) just get lost in the Windows Trashcan because of shutdowns. The European servers have been shutdown already, but now Acclaim announced that the US Version is F2P from today on but will not feature any updates or patches until the official relaunch. In my opinion it is worth it. And as it is free now it has enough content to keep you playing for a while. And let’s see… maybe you like it!

The Chronicles of Spellborn
TCOS

TCOSThe Chronicles of Spellborn was a bold try to do something completely out of line from UO, Everquest or World of Warcraft. The studio from Netherlands licensed the Unreal 2.5 engine and created their own story, their own environment, their own world! Main focus was put on the fighting system, which features a complex looking but very special and good kind of active and live fighting, with skill-based tiers. Moving, jumping, attacking from behind gets more interactive and it encourages to test your skill-tiers, similar to Guild Wars, because of the alignment and limitations in the slots.
Unfortunately TCOS could not fully keep up to the (and my) expectations. It was polished but too little content was available. Some people also argued that the quest descriptions were missing concrete directions. I liked that, as it was no following arrows and points but really reading the quests, the logs, the text. As the quest and discussion system also features some kind of answer selection, sometimes you can change your stand and the mood of NPCs to you. Something I also like.

So, just head over to the official website and download the game. It is worth at least a quick look and maybe the community will bring Spellborn back to live, somehow like Ryzom.

The Chronicles of Spellborn – Trailer

Pictures taken from the official Website: http://spellborn.acclaim.com/

Bookmark and Share

An Inglourious Piece of fan made Trailer

August 17th, 2009 No comments

Just a quick post about a short parody trailer of Quentin Tarantino’s “Inglourious Basterds” made by Gamervision. Just watch and laugh your guts out like I did… the Mushroom Kingdom awaits you!

Inglorious Plummers (2009)
Bookmark and Share