Babylon.js: a complete JavaScript framework for building 3D games with HTML5 and WebGL
Join the DZone community and get the full member experience.
Join For FreeI am a real fan of 3D development. Since I was 16, I spent all my spare time creating 3d engines with various technologies (DirectX, OpenGL, Silverlight 5,pure software, etc.).
My happiness was complete when I discovered that Internet Explorer 11 has native support for WebGL. So I decided to write once again a new 3D engine but this time using WebGL and my beloved JavaScript.
If you are a 3D beginner, I suggest you to read this excellent series of blogs written by my friendDavid Rousset:http://blogs.msdn.com/b/davrous/archive/2013/06/13/tutorial-series-learning-how-to-write-a-3d-soft-engine-from-scratch-in-c-typescript-or-javascript.aspx
Thus babylon.js was born and you can find some samples right here:http://www.babylonjs.com.
The engine is currently at early stage but I plan to add a lot of cool new features quickly.
The current version supports the following features (I always loved this kind of very long and very technical list):
- Complete scene graph with lights, cameras, materials, sprites, layers and meshes
- Complete collisions/responses system
- Highly configurable material with support with
- Diffuse
- Specular
- Emissive
- Opacity / Alpha
- Reflection
- Ambient
- Up to 4 simultaneous lights
- Two kind of lights:
- Point
- Directional
- Three kind of cameras:
- Free camera (FPS like)
- Touch compatible camera
- Arc rotate camera
- Textures:
- 2D
- Render target
- Mirrors
- Dynamic
- Alpha blending
- Alpha testing
- Billboarding / sprites
- Scene picking
- Frustum clipping
- Sub-meshes clipping
- Antialiasing
- Particles system
- Animations engine
- Babylon file format is a JSON file that can be produced from:
- .OBJ
- .FBX
- .MXB
- Blender
Obviously I will not cover ALL the features during this article. Indeed this one is just the first one of a long series that will focused on every feature of babylon.js.
About IE11 preview: IE11 is still in preview stage right now and so you should consider it as a…preview. Some shaders would not work as expected or would not even display something…. so, please be patient…
Furthermore, our blog platform forces IE10 compatibility mode which implies the deactivaction of WebGL (I do a complex job…^^). So for every sample, you will find a picture where you can click to open a new window using brand new IE11 rendering engine.
Getting started with babylon.js
The only thing you really need to unleash the power of babylon.js is a small js file (less than 200 KB uncompressed): http://www.babylonjs.com/babylon.zip
You will also need to add hand.js to your page if you want to seamlessly supporttouch events:http://handjs.codeplex.com
Once you grabbed this file, you just have to import it in your HTML file and create a canvas (this is where babylon.js will render the scenes)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Using babylon.js - Test page</title> <script src="babylon.js"></script> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0; overflow: hidden; } #renderCanvas { width: 100%; height: 100%; } </style> </head> <body> <canvas id="renderCanvas"></canvas> </body> </html>
Babylon.js is built around a main object: the engine. This object will let you create a scene where you will be able to add meshes (the 3D objects), lights, cameras and materials:
<script> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); </script>
You may want to test if WebGL is supported on the current browser by using the following code:
<script> if (BABYLON.Engine.isSupported()) { var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); } </script>
The engine is the hub between babylon.js and WebGL. It is in charge of sending orders to WebGL and creating internal WebGL related objects.
Once the engine is created, you are able to create the scene:
var scene = new BABYLON.Scene(engine);
The scene can be seen as a container for all entities that works together to create a 3D image. With the scene you can create a light, a camera and a mesh (in this case a sphere):
var camera = new BABYLON.FreeCamera("Camera", new BABYLON.Vector3(0, 0, -10), scene); var light0 = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(0, 100, 100), scene); var sphere = BABYLON.Mesh.createSphere("Sphere", 16, 3, scene);
Babylon.js supports different kind of cameras, lights and meshes. I will get back to them in this article.
You may have noticed the usage of BABYLON.Vector3 to define a 3D position. Indeed,babylon.jscomes with a complete math Library that can handle vectors, matrix, colors, rays and quaternions.
Please note that babylon.js use a left handed coordinate system:
The last thing you need to do is to register a render loop:
// Render loop var renderLoop = function () { // Start new frame engine.beginFrame(); scene.render(); // Present engine.endFrame(); // Register new frame BABYLON.Tools.QueueNewFrame(renderLoop); }; BABYLON.Tools.QueueNewFrame(renderLoop);
Using QueueNewFrame (which is just a call to requestAnimationFrame when supported or setTimeout else), you will ask thebrowser to call your renderLoop as soon as possible. The renderLoop itself is based upon 4 parts:
- engine.beginFrame: This is a required call to determine the start of a new frame
- scene.render: Asks the scene to render all entities it owns
- engine.endFrame: Closes the current frame and present it to the canvas
- QueueNewFrame: Registers a new frame for rendering
If you want to add a bit more of real-time, you can add function for scene.beforeRender and use it to animate the sphere:
var alpha = 0; sphere.scaling.x = 0.5; sphere.scaling.z = 1.5; scene.beforeRender = function() { sphere.rotation.x = alpha; sphere.rotation.y = alpha; alpha += 0.01; };
The result is the following (if your browser does not support WebGL, you will see a wonderful white on white rectangle):
For IE11 Preview, you could click here:
Materials
Our sphere is a bit sad with its simple gray color. This is time for us to talk about materials. A material for babylon.js is an object that defines how a mesh looks like.
Babylon.js has an object called StandardMaterial which supports the following properties:
-
diffuseColor and diffuseTexture: Define the base color of the mesh
-
ambientColor and ambientTexture: Define the ambient color of the mesh (can be used for light maps for instance)
-
specularColor and specularTexture: Define the specular color of the mesh
-
emissiveColor and emissiveTexture: Define the color emitted by the mesh (the color the object has without light)
-
opacityTexture: Define the transparency of the mesh
-
reflectionTexture: Define the reflection color received by the mesh (can be a texture or a dynamic mirror)
-
alpha: Define the global transparency of the mesh
color properties define an unique color where texture properties use a bitmap to define colors
So let’s add some color to our sphere:
// Material var material = new BABYLON.StandardMaterial("default", scene); material.diffuseTexture = new BABYLON.Texture("kosh.jpg", scene); material.emissiveColor = new BABYLON.Color3(0.3, 0.3, 0.3); sphere.material = material;
And the result (once again, with WebGL, it should be white…):
For IE11 Preview, you could click here:
The StandardMaterial is very versatile and there are tons of available combinations. For instance let’s change the texture used by the diffuseTexture with a texture that contains alpha values:
var material = new BABYLON.StandardMaterial("default", scene); material.diffuseTexture = new BABYLON.Texture("tree.png", scene); material.diffuseTexture.hasAlpha = true; material.emissiveColor = new BABYLON.Color3(0.3, 0.3, 0.3); material.backFaceCulling = false; sphere.material = material;
And the result:
For IE11 Preview, you could click here:
Please note that in this case, we have to indicate that the texture contains useful alpha values (has Alpha = true). We also need to deactivate the back face culling system (which remove the faces that are not toward us) to see back faces.
Lights, cameras and meshes
Lights
Babylon.js lets you create two kind of lights:
- pointLight (like the sun for instance) which emits lights in every direction from a specific position
- directionalLight which emits lights from the infinite towards a specific direction
Creating them is easy:
var omni = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(10, 0, 0), scene); var dir = new BABYLON.DirectionalLight("Dir0", new BABYLON.Vector3(1, -1, 0), scene);
You can create as much lights as you want but beware: the StandardMaterial can only take in account up to 4 lights simultaneously.
Lights have three main properties:
- diffuse: Diffuse color
- specular: Specular color
- position/direction
Cameras
Babylon.js supports 3 kind of cameras:
- freeCamera is a FPS like camera where you control the camera with the cursors keys and the mouse
- touchCamera is a camera controlled with touch events (it requireshand.jsto work)
- arcRotateCamera is a camera that rotates around a given pivot. It can be controlled with the mouse or touch events (and it also requires hand.js to work)
You can create as much cameras as you want but only one camera can be active at a time
var camera = new BABYLON.ArcRotateCamera("Camera1", 0, 0.8, 10, BABYLON.Vector3.Zero(), scene); var camera2 = new BABYLON.FreeCamera("Camera2", new BABYLON.Vector3(0, 0, -10), scene); var camera3 = new BABYLON.TouchCamera("Camera3", new BABYLON.Vector3(0, 0, -10), scene); scene.activeCamera = camera;
All the cameras can automatically handle inputs for you by calling attachControl function on the canvas. And you can revoke the control by using detachControl function:
camera.attachControl(canvas);
Meshes
Creation
Meshes are the only entities that you can effectively see. They have tons of properties and can be created from basic shapes or from a list of vertices and faces.
Basic shapes are:
- Cube
- Sphere
- Plane
var box = BABYLON.Mesh.createBox("Box", 0.8, scene); var sphere = BABYLON.Mesh.createSphere("Sphere", 16, 3, scene); var plane = BABYLON.Mesh.createPlane("plane", 3, scene);
You can also create a mesh from a list of vertices and faces:
var plane = new BABYLON.Mesh("plane", [3, 3, 2], scene); var indices = []; var vertices = []; // Vertices var halfSize = 0.5; vertices.push(-halfSize, -halfSize, 0, 0, 1.0, 0, 0.0, 0.0); vertices.push(halfSize, -halfSize, 0, 0, 1.0, 0, 1.0, 0.0); vertices.push(halfSize, halfSize, 0, 0, 1.0, 0, 1.0, 1.0); vertices.push(-halfSize, halfSize, 0, 0, 1.0, 0, 0.0, 1.0); // Indices indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); plane.setVertices(vertices, 1); plane.setIndices(indices); return plane;
You have to create a blank new mesh and call setVertices and setIndices.
When you create a blank mesh, you have to give a description of every vertex. In this case, the value is [3, 3, 2] which means that a vertex is composed of 3 parts: the first one is based on 3 floats, the second one is based on 3 floats and the last one on 2 floats (position[3], normal[3] and texture coordinates[2])
To define where the mesh is, you can use the position/rotation/scaling properties:
plane.position = new BABYLON.Vector3(0, 7, 0); plane.rotation.z = 0.1; plane.scaling.x = 2;
Meshes hierarchy
You can create meshes hierarchies by setting the parent property of a mesh. By doing this you create a link between two meshes. This link implies that all parent transformations (position/rotation/scaling) will be combined with the child’s transformations.
For instance, with the following code:
var box = BABYLON.Mesh.createBox("Box", 1.0, scene); box.position = new BABYLON.Vector3(0, 2, 2); box.parent = sphere;
You will get the following result (based obviously on the previous scene we created, where I removed the scaling of the sphere for clarity):
For IE11 Preview, you could click here:
Activation and visibility
You can control the visibility and the activation of meshes according to following rules:
- StandardMaterial can control the opacity of an object with
- alpha property to control alpha blending (transparency) per mesh
- alpha channel of the diffuseTexture: this will cause babylon.js to activate alpha testing which means it will discard all pixel with alpha value < 0.5
- opacityTexture to define alpha blending per pixel (and not for the whole mesh like alpha property)
- visibility property to control the transparency per mesh directly (without using a material)
- isVisible property to activate the rendering of the mesh. The mesh is kept into the scene for others operations (collisions, picking, etc.). This property is not transmitted to children
- setEnabled function to deactivate completely a mesh and all its descendants.
Collisions
One of the great feature of babylon.js is certainly its complete and really simple to use collisions system. By settings a small set of options, you will be able to reproduce a first person shooter
There are three levels of options to set. First of all you have to activate the collisions globally on the scene and define the gravity:
scene.collisionsEnabled = true; scene.gravity = new BABYLON.Vector3(0, -9, 0);
Then you have to configure the camera you want to use for collisions:
camera.checkCollisions = true; camera.applyGravity = true; camera.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
The collisions engine considers the camera like an ellipsoid (a kind of capsule). In this case the camera is like a big ellipsoid measuring 1mx2mx1m (the ellipsoid property defines the radius of the ellipsoid).
You can also create a flying camera by not applying gravity.
Finally you have to define which meshes can collide:
plane.checkCollisions = true; sphere.checkCollisions = true;
The result is the following (use the cursors keys to move and the mouse to change your point of view by clicking and moving it. Beware not to fall off of the ground):http://www.babylonjs.com/tutorials/simple5.html
Babylon.js can even handle stairs as you can see in the “Espilit demo” on the main site.
Particle systems
Particle systems are a cool toy when you play with 3D. They can easily add stunning effects on your scene (explosions, impacts, magic effects, etc.).
Creating a particle system is simple as follow:
var particleSystem = new BABYLON.ParticleSystem("particles", 4000, scene);
You have to define the maximum capacity of a particle system to allowbabylon.jsto create associatedWebGLobjects. So in this case, there will be no more than 4000 active particles simultaneously.
Particle systems are highly configurable with the help of the following set of properties:
- particleTexture: Defines the texture associated with every particle
- minAngularSpeed/maxAngularSpeed: The range of the angular rotation speeds of every particle
- minSize/maxSize: The range of sizes of every particle
- minLifeTime/maxLifeTime: The range of lifetimes for every particle
- minEmitPower/maxEmitPower:: The range of emission powers (emission speed) of every particle
- minEmitBox/maxEmitBox:: The box from where every particle starts (can be a point if min == max)
- direction1/direction2: The range of directions for every particle
- color1/color2: The range of colors for every particle
- colorDead: The color of a dead particle (Babylon.jswill interpolate particle’s color to this color)
- deadAlpha: The alpha of a dead particle (in a same way,babylon.jswill interpolate particle’s alpha to finish with this specific alpha)
- textureMask: A mask used to filter which part of the texture is used for every particle
- blendMode: Alpha blending mode (BLENDMODE_ONEONEto add current color and particle color orBLENDMODE_STANDARDto blend current color and particle color using particle’s alpha)
- emitter:A Vector3 to define the position of the particle system. You can also used a mesh here and in this case the particle system will use the mesh position
- emitRate: How many particles are launched on every frame.
- manualEmitCount: Specifying a value greater or equal to zero here will disable emitRate. You are then responsible for feeding this value to control the particles count emitted.
- updateSpeed: The global speed of the system
- gravity:Graviy applied to particles
- targetStopDuration:Stops the particle system after a specific duration
- disposeOnStop: Disposes the particle system on stop (Very useful if you want to create a one shot particle system with a specifictargetStopDuration)
Every range values are used to generate a controlled random value for every particle.
You can control a particle system by calling start/stop functions.
That’s a lot of properties, isn’t it ?The best way to understand them is to try all of them on a test scene and play with properties. For instance, the following code:
var particleSystem = new BABYLON.ParticleSystem("particles", 4000, scene); particleSystem.particleTexture = new BABYLON.Texture("Flare.png", scene); particleSystem.minAngularSpeed = -0.5; particleSystem.maxAngularSpeed = 0.5; particleSystem.minSize = 0.1; particleSystem.maxSize = 0.5; particleSystem.minLifeTime = 0.5; particleSystem.maxLifeTime = 2.0; particleSystem.minEmitPower = 0.5; particleSystem.maxEmitPower = 1.0; particleSystem.emitter = new BABYLON.Vector3(0, 0, 0); particleSystem.emitRate = 500; particleSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE; particleSystem.minEmitBox = new BABYLON.Vector3(0, 0, 0); particleSystem.maxEmitBox = new BABYLON.Vector3(0, 0, 0); particleSystem.direction1 = new BABYLON.Vector3(-1, -1, -1); particleSystem.direction2 = new BABYLON.Vector3(1, 1, 1); particleSystem.color1 = new BABYLON.Color4(1, 0, 0, 1); particleSystem.color2 = new BABYLON.Color4(0, 1, 1, 1); particleSystem.gravity = new BABYLON.Vector3(0, -5, 0); particleSystem.disposeOnStop = true; particleSystem.targetStopDuration = 0; particleSystem.start();
Produces the following rendering (click and move the mouse on the canvas to use the arcRotateCamera):
Sprites and layers
Babylon.js is designed to extract the full power of WebGL for your apps and games. And even if you want to create a 2D game, babylon.js can help you by providing a support for sprites and 2D layers.
Please note than you can also define the billboardMode property of a mesh to align it with the camera to simulate a 2D object: plane.billboardMode = BABYLON.Mesh.BILLBOARDMODE_ALL
A sprite is defined by a texture containing all its animation states:
The current state (the current cell displayed) is defined using the cellIndex property. You can then manipulate it by code or use the playAnimation function to let babylon.js control the cellIndex property.
Sprites working on the same texture are gathered around a SpriteManager to optimize resources usage:
var spriteManager = new BABYLON.SpriteManager("MonsterA", "MonsterARun.png", 100, 64, scene); for (var index = 0; index < 100; index++) { var sprite = new BABYLON.Sprite("toto", spriteManager); sprite.position.y = 0; sprite.position.z = Math.random() * 10 - 5; sprite.position.x = Math.random() * 10 - 5; sprite.invertU = (Math.random() < 0.5); sprite.playAnimation(0, 9, true, 100); }
Please note the usage of invertU for inverting horizontally the texture.
The previous code produced the following rendering:
In addition to sprites, babylon.js also supports 2D layers in order to let you add backgrounds or foregrounds:
var background0 = new BABYLON.Layer("back0", "Layer0_0.png", scene); var background1 = new BABYLON.Layer("back1", "Layer1_0.png", scene); var foreground = new BABYLON.Layer("fore0", "Layer2_0.png", scene, false);
The last boolean defines if the layer is background (or not).
The resulting render is the following:
Animations
There are two ways of animating properties in babylon.js: You can do it by yourself using JavaScript (see previous samples) or you can use the animations engine.
The animations engine is based on objects called Animation(!!). An Animation is defined by various properties and a collection of keys. Every key represents the value of the Animation at a given time. Once an Animationis created you can add it to the animations property of a given object:
// Animations var animation = new BABYLON.Animation("anim0", "scaling.x", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); var keys = []; keys.push({ frame: 0, value: 1 }); keys.push({ frame: 50, value: 0.2 }); keys.push({ frame: 100, value: 1 }); animation.setKeys(keys); box.animations.push(animation);
Animations can work on types:
- float (BABYLON.Animation.ANIMATIONTYPE_FLOAT)
- Vector3 (BABYLON.Animation.ANIMATIONTYPE_VECTOR3)
- Quaternion (BABYLON.Animation.ANIMATIONTYPE_QUATERNION)
They can have various behaviors when they hit their upper limit:
- Use previous values and increment it (BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE)
- Restart from initial value (BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE)
- Keep their final value (BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT)
So using the previous code and this small line will launch the animation:
scene.beginAnimation(box, 0, 100, true);
And give us the following scene:
For IE11 Preview, you could click here:
Advanced textures
Textures can obviously be based on pictures but you have the opportunity with babylon.js to use Advanced features to generate textures at runtime.
Dynamic textures
A dynamic texture uses a canvas to generate its content.
Creating and affecting a dynamic texture is simple:
var dynamicTexture = new BABYLON.DynamicTexture("dynamic texture", 512, scene, true); dynamicTexture.hasAlpha = true; material.diffuseTexture = dynamicTexture;
Once the texture is created, you can updated it when you want (for instance here every time the scene is rendered) using the getContext and update functions:
var count = 0; scene.beforeRender = function() { // Dynamic var textureContext = dynamicTexture.getContext(); var size = dynamicTexture.getSize(); var text = count.toString(); textureContext.save(); textureContext.fillStyle = "red"; textureContext.fillRect(0, 0, size.width, size.height); textureContext.font = "bold 120px Calibri"; var textSize = textureContext.measureText(text); textureContext.fillStyle = "white"; textureContext.fillText(text, (size.width - textSize.width) / 2, (size.height - 120) / 2); textureContext.restore(); dynamicTexture.update(); count++; };
The result is the following (yes I know, I’m not a designer)
For IE11 Preview, you could click here:
The getContext returns a true canvas’ context so everything you can do with a canvas is available with a dynamic texture.
Mirrors
Mirrors textures are another kind of dynamic textures. You can use them to simulate “mirrors” which mean that babylon.js will compute for you the reflection and fill the texture with the results. A Mirror texture must be set in the reflectionTexture channel of a standardMaterial:
// Mirror var mirror = BABYLON.Mesh.createBox("Mirror", 1.0, scene); mirror.material = new BABYLON.StandardMaterial("mirror", scene); mirror.material.diffuseColor = new BABYLON.Color3(0.4, 0, 0); mirror.material.reflectionTexture = new BABYLON.MirrorTexture("mirror", 512, scene, true); mirror.material.reflectionTexture.mirrorPlane = new BABYLON.Plane(0, -1.0, 0, -2.0); mirror.material.reflectionTexture.renderList = [box, sphere];
A mirrorTexture is created with a parameter that specify the size of the rendering buffer (512x512here). Then you have to define the reflection plane and a render list (the list of meshes to render Inside the mirror).
The result is pretty convincing:
For IE11 Preview, you could click here:
Importing scene from 3D assets
Babylon.js can load scenes from a file format called.babylon. This file format is based on JSON and contains all required data to create a complete scene.
BabylonExport
A .babylon can be created with a custom tool I developed: BabylonExport. This command line tool can generate .babylon file from various file formats:
- .FBX
- .OBJ
- .MXB
BabylonExport takes 2 parameters:
BabylonExport /i:"Test scenes\Viper\Viper.obj" /o:"c:\Export\Viper"
The tool can be found here: http://www.babylonjs.com/babylonexport.zip
Warning: The tool requires XNA 4.0 runtime:http://www.microsoft.com/en-us/download/details.aspx?id=20914
Blender
You can also produce .babylonfiles with Blender. To do so, please download the exporter script right here: http://www.babylonjs.com/Blender2Babylon.zip.
To install it, please follow this small guide:
- Unzip the file to your Blender’s plugins folder (Should beC:\Program Files\Blender Foundation\Blender\2.67\scripts\addonsfor Blender 2.67 x64).
- Launch Blender and go to File/User Préférences/Addon and select Import-Export category. You will be able to activate Babylon.js exporter.
- Create your scene
- Go to File/Export and select Babylon.js format. Choose a filename and you are done !
You are now able to produce .babylonscene! The exporter will be able to support more and more options in the future but right now the following features are already supported:
- Cameras
- Lights
- Meshes
- Material and Multimaterials
- Diffuse
- Ambient
- Opacity
- Reflection
- Emissive
- Collisions (with custom UI Inside Blender)
And much more to come…
The backlog is full of cool things among which we can note:
- Bump mapping
- Spot lights
- Hemispheric lights
- Video textures
- Bones
- Morphing
- Refraction
- Fog
- Water shader
The main goal of babylon.js is to provide you with a strong framework for simplifying 3D. Use it freely as a foundation for your games and applications.
And now go to http://www.babylonjs.com and start exploring the wonderful world of 3D rendering!
Opinions expressed by DZone contributors are their own.
Comments