BabylonJS – Discussion

Discuss BabylonJS ”; Previous Next BabylonJS is a javascript framework for building 3D games with HTML5 and WEBGL.It is anopen source framework and is hosted on github. The official website of BabylonJS is www.babylonjs.com. Print Page Previous Next Advertisements ”;

BabylonJS – Reflection Probes

BabylonJS – Reflection Probes ”; Previous Next Reflection probes are used to create a mirror like scene. This helps in seeing the reflection of the meshes in it. To create a mirror like scene, you need to call the class and the required meshes wherein you want to see reflection. Later, you need to add the meshes to the renderlist as shown below. Consider you have skybox with water surface and you need to show the clouds or tree reflection or the bird flying in the water, you can do so using reflection probe and the meshes created can be added to the renderlist as shown below. Syntax var probe = new BABYLON.ReflectionProbe(“main”, 512, scene); probe.renderList.push(yellowSphere); probe.renderList.push(greenSphere); probe.renderList.push(blueSphere); probe.renderList.push(mirror); Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Element-Creating Scene</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); var camera = new BABYLON.ArcRotateCamera(“camera1”, 0, 0, 10, BABYLON.Vector3.Zero(), scene); camera.setPosition(new BABYLON.Vector3(0, 5, -10)); camera.attachControl(canvas, true); camera.upperBetaLimit = Math.PI / 2; camera.lowerRadiusLimit = 4; var light = new BABYLON.HemisphericLight(“light1”, new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; var knot = BABYLON.Mesh.CreateTorusKnot(“knot”, 1, 0.4, 128, 64, 2, 3, scene); var yellowSphere = BABYLON.Mesh.CreateSphere(“yellowSphere”, 16, 1.5, scene); yellowSphere.setPivotMatrix(BABYLON.Matrix.Translation(3, 0, 0)); var blueSphere = BABYLON.Mesh.CreateSphere(“blueSphere”, 16, 1.5, scene); blueSphere.setPivotMatrix(BABYLON.Matrix.Translation(-1, 3, 0)); var greenSphere = BABYLON.Mesh.CreateSphere(“greenSphere”, 16, 1.5, scene); greenSphere.setPivotMatrix(BABYLON.Matrix.Translation(0, 0, 3)); // Mirror var mirror = BABYLON.Mesh.CreateBox(“Mirror”, 1.0, scene); mirror.scaling = new BABYLON.Vector3(100.0, 0.01, 100.0); mirror.material = new BABYLON.StandardMaterial(“mirror”, scene); mirror.material.diffuseTexture = new BABYLON.Texture(“images/square.jpg”, scene); mirror.material.diffuseTexture.uScale = 10; mirror.material.diffuseTexture.vScale = 10; mirror.material.reflectionTexture = new BABYLON.MirrorTexture(“mirror”, 1024, scene, true); mirror.material.reflectionTexture.mirrorPlane = new BABYLON.Plane(0, -1.0, 0, -2.0); mirror.material.reflectionTexture.renderList = [greenSphere, yellowSphere, blueSphere, knot]; mirror.material.reflectionTexture.level = 0.5; mirror.position = new BABYLON.Vector3(0, -2, 0); // Main material var mainMaterial = new BABYLON.StandardMaterial(“main”, scene); knot.material = mainMaterial; var probe = new BABYLON.ReflectionProbe(“main”, 512, scene); probe.renderList.push(yellowSphere); probe.renderList.push(greenSphere); probe.renderList.push(blueSphere); probe.renderList.push(mirror); mainMaterial.diffuseColor = new BABYLON.Color3(1, 0.5, 0.5); mainMaterial.reflectionTexture = probe.cubeTexture; mainMaterial.reflectionFresnel<h3>Parameters</h3> = new BABYLON.Fresnel<h3>Parameters</h3>(); mainMaterial.reflectionFresnel<h3>Parameters</h3>.bias = 0.02; // Fog scene.fogMode = BABYLON.Scene.FOGMODE_LINEAR; scene.fogColor = scene.clearColor; scene.fogStart = 20.0; scene.fogEnd = 50.0; // Animations scene.registerBeforeRender(function () { yellowSphere.rotation.y += 0.01; greenSphere.rotation.y += 0.01; blueSphere.rotation.y += 0.01; }); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Output In this demo, we have used image square.jpg. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link. images/square.jpg Print Page Previous Next Advertisements ”;

BabylonJS – Useful Resources

BabylonJS – Useful Resources ”; Previous Next The following resources contain additional information on BabylonJS. Please use them to get more in-depth knowledge on this. Useful Video Courses Full Stack Development With Vue JS 2 And Spring Boot 54 Lectures 3.5 hours Senol Atac More Detail Node js for Course for beginners + Game project 27 Lectures 2.5 hours Laurence Svekis More Detail Advanced Theoretical JavaScript: Learn Advanced JS Concepts 25 Lectures 2 hours Mehul Mohan More Detail ReactJS Course : Learn React JS From Scratch Best Seller 61 Lectures 4.5 hours Skillbakery More Detail JavaScript Deep Dive: Explore JS (For Beginners-to-Advanced) 129 Lectures 5.5 hours TELCOMA Global More Detail React JS and .NET Core Web API Full Stack Master Course 21 Lectures 3.5 hours Vinay Kumar More Detail Print Page Previous Next Advertisements ”;

BabylonJS – Bones and Skeletons

BabylonJS – Bones and Skeletons ”; Previous Next Babylonjs offers APIs to create skeletons and bones. Syntax Let us now see the syntax for different functions. For Skeleton BABYLON.Skeleton = function (name, id, scene) For Bone BABYLON.Bone = function (name, skeleton, parentBone, matrix) Skeletons and Bones can be created using blender and the same can be exported in .babylonjs. Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Element-Creating Scene</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); //Adding a light var light = new BABYLON.PointLight(“Omni”, new BABYLON.Vector3(20, 20, 100), scene); //Adding an Arc Rotate Camera var camera = new BABYLON.ArcRotateCamera(“Camera”, 0, 0.8, 100, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, false); BABYLON.SceneLoader.ImportMesh( “him”, “scenes/Dude/”, “Dude.babylon”, scene, function (newMeshes, particleSystems, skeletons) { var dude = newMeshes[0]; console.log(dude); dude.rotation.y = Math.PI; dude.position = new BABYLON.Vector3(0, 0, -80); scene.beginAnimation(skeletons[0], 0, 100, true, 1.0); }) return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> In the above demo link, we have used Dude.babylon mesh. You can download the json file for Dude.babylon from here − Dude.babylon Save the file in scenes to get the output as shown below. Output The above line of code generates the following output − Explanation For the import mesh, we have used babylonjs dude mesh. The mesh gives us skeletons. For example, skeleton = skeletons[0]; To get bones from the skeletons, execute the following command − skeleton.bones; //it gives a array. In the above demo, we created 2 spheres and passed on to the mesh. For this, we executed the following commands − sphere.attachToBone(skeleton.bones[30], dude); And, sphere1.attachToBone(skeleton.bones[40], dude); attachToBone is a function wherein, you can give any mesh to the bone. Skeleton.bones[30] and skeleton.bones[40] refers to the hands of the skeleton. Print Page Previous Next Advertisements ”;

BabylonJS – Quick Guide

BabylonJS – Quick Guide ”; Previous Next BabylonJS – Introduction Babylon.js is a javascript open-source framework which is used to develop 3D applications/ video games for the web. The official website of BabylonJS is www.babylonjs.com. Using Babylon.js framework is easy for the users. It contains all the required tools to create and manage 3D objects, special effects, and sounds, etc. Babylon.js is one of the most popular 3D game engines and is widely used by developers. Being a 3D library, it provides built-in functions. These functions help you implement common 3D functionality with efficient and accurate ways. It is developed using TypeScript language based on WebGL and javascript. What is WebGL? WebGL (Web Graphics Library) is the new standard for 3D graphics on the Web. It is designed for the purpose of rendering 2D graphics and interactive 3D graphics. It is derived from OpenGL”s ES 2.0 library which is a low-level 3D API for phones and other mobile devices. WebGL provides similar functionality of ES 2.0 (Embedded Systems) and performs well on modern 3D graphics hardware. The TypeScript By definition, “TypeScript is JavaScript for application-scale development.” TypeScript is a strongly typed, object oriented, compiled language. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features. The goal of TypeScript language is to improve and secure the production of JavaScript code.Since BabylonJS is developed using TypScript, it is robust and secure. BabylonJS – Environment Setup In this chapter, we will learn how to set up the environment for BabylonJS. To start with the setup, visit the official website of Babylon.js − www.babylonjs.com. Go to the download section and choose the latest version of Babylon.js and store in your folder. The screenshot for the same is as follows − You can also go to GITHUB and clone the babylonjs project − Babylon.js In your command line type − git clone https://github.com/BabylonJS/Babylon.js.git go to cd BabylonJS/ npm install The required files will be available in the BabylonJS folder. You can use the VSCode (Microsoft Visual Studio Code) for editing.The code comes with builtin functionalities like highlighting if any error, hightlighting the syntax, etc. You can use the editor of your choice and it is not mandatory to use only VSCode. BabylonJS – Overview BabylonJS is an open sourceJavascript framework for building 3D games with HTML5 and WEBGL.It is hosted on github.The official web site of BabylonJS is www.babylonjs.com. In the world of 3D Animation,the shapes are drawn with triangles.With WebGL, the complexity increases with the deluge of coding that is involved in the process. BabylonJS is the easy solution that pitches in to mitigate the increased complexity. Here, the API for lights, cameras, engine are easy to handle and to create 3D objects. The source code of babylonJS is coded in typescript.It is compiled to Javascript and made available tothe end user. To start working with Babylonjs, download the babylonjs file, host it at your end and you are ready to get started to write your 3D code. BabylonJS is developed by Microsoft employees in the year 2016.David Catuhe, a Principal Program Manager for the Window & Devices Group at Microsoft is the main person behind developing BabylonJs and making it a big success. To run BabylonJS, we need modern browsers with WEBGL support. Latest browsers i.e Internet Explorer 11+, Firefox 4+, Google Chrome 9+, Opera 15+, etc. does have WEBGL support and the demos can be executed on same to see the output. BabylonJs offers following features which help to create different types of 3D-scenes − Shapes like box, sphere, scylinder, cone, height ground Cameras, Lights Meshes, textures, Materials Sprites Morphing Mesh Intersection and collision detection Physics engine plug-in Action Manager SolidParticles Instances and Particles Support for Bones and Skeletons Adding music and sound to the scene In addition to its own meshes, BabylonJS also allows the use of meshes created from third party 3D softwares like Blender, FBX and 3DS Max. Blender Blender is an open-source 3D computer graphics software product used to create animated scenes, 3D printed models, video games, etc. Blender gives. bablyon files which are to be used with Babylon to render meshes. How to convert files from blender to babylon is explained in subsequent chapters of this tutorial. FBX Also called the filmbox, it helps with 3D animation and texture painting software. The FBX files are saved with the.fbx extension. MAX The MAX software helps you in creating massive world in games, stunning scenes for designs and engaging virtual reality experiences. BabylonJS – Basic Elements Babylon.js is a popular framework to help build 3D games for developers. It has built-in functions to implement 3D functionalities. Let us build a simple demo using Babylon.js and understand the basic functionalities required to get started. We will first create a demo which contains the basic elements of Babylon.js. In addition, we will also learn the various functionalities of Babylon.js. Sample Demo 1 In this section, we will learn how to create a demo containing the basic elements of BabylonJS. <!doctype html> <html> <head> <meta charset = “utf-8”> <title> Babylon.JS : Demo2</title> <script src = “babylon.js”></script> <style> canvas { width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(1, 0.8, 0.8); var camera = new BABYLON.ArcRotateCamera(“Camera”, 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); scene.activeCamera.attachControl(canvas); var light0 = new BABYLON.PointLight(“Omni”, new BABYLON.Vector3(0, 0, 10), scene); var origin = BABYLON.Mesh.CreateSphere(“origin”, 10, 1.0, scene); var torus = BABYLON.Mesh.CreateTorus(“torus”, 5, 1, 10, scene, false); var box = BABYLON.Mesh.CreateBox(“box”, 3.0, scene); box.position = new BABYLON.Vector3(-5, 0, 0); var cylinder = BABYLON.Mesh.CreateCylinder(“cylinder”, 3, 3, 3, 6, 1, scene, false); cylinder.position = new BABYLON.Vector3(5, 0, 0); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> To run BabylonJS, we need

BabylonJS – Basic Elements

BabylonJS – Basic Elements ”; Previous Next Babylon.js is a popular framework to help build 3D games for developers. It has built-in functions to implement 3D functionalities. Let us build a simple demo using Babylon.js and understand the basic functionalities required to get started. We will first create a demo which contains the basic elements of Babylon.js. In addition, we will also learn the various functionalities of Babylon.js. Sample Demo 1 In this section, we will learn how to create a demo containing the basic elements of BabylonJS. <!doctype html> <html> <head> <meta charset = “utf-8”> <title> Babylon.JS : Demo2</title> <script src = “babylon.js”></script> <style> canvas { width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(1, 0.8, 0.8); var camera = new BABYLON.ArcRotateCamera(“Camera”, 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); scene.activeCamera.attachControl(canvas); var light0 = new BABYLON.PointLight(“Omni”, new BABYLON.Vector3(0, 0, 10), scene); var origin = BABYLON.Mesh.CreateSphere(“origin”, 10, 1.0, scene); var torus = BABYLON.Mesh.CreateTorus(“torus”, 5, 1, 10, scene, false); var box = BABYLON.Mesh.CreateBox(“box”, 3.0, scene); box.position = new BABYLON.Vector3(-5, 0, 0); var cylinder = BABYLON.Mesh.CreateCylinder(“cylinder”, 3, 3, 3, 6, 1, scene, false); cylinder.position = new BABYLON.Vector3(5, 0, 0); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> To run BabylonJS, we need modern browsers with WEBGL support. The latest browsers -Internet Explorer 11+, Firefox 4+, Google Chrome 9+, Opera 15+, etc. does have WEBGL support and the demos can be executed on the same platforms to see the output. Create a directory to store the files for babylonjs. Fetch the latest BabylonJSscripts file from BabylonJS site. All the demo links in this tutorial are tested with babylonjs version 3.3. Step 1 Create a simple html page and include the Babylon.js file. Create a canvas tag which is used to render contents by BabylonJSinside the body tag as shown below. Add css to the canvas to occupy the full width and height of the screen. <!doctype html> <html> <head> <meta charset = “utf-8”> <title>MDN Games: Babylon.js demo – shapes</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> </body> </html> Step 2 Let us now start with the BabylonJScode for rendering contents on the canvas. <!doctype html> <html> <head> <meta charset = “utf-8”> <title>MDN Games: Babylon.js demo – shapes</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); </script> </body> </html> Now, add the script tag to the html structure and store the canvas reference in variable canvas. To get started with Babylon.js, create an engine instance and pass the canvas reference to render on it. <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); </script> The BABYLON global object contains all the Babylon.js functions available in the engine. Step 3 In this step, we will first create a scene. A scene is where all the contents will be displayed. We will create the different types of objects and add the same to the scene to make it visible on the screen. To create scene, add the following code to the already created html structure. At present, we will append to the already created code as a continuation to the above html structure. var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(1, 0.8, 0.8); }; var scene = createScene(); The final html file will look as follows − <!doctype html> <html> <head> <meta charset = “utf-8”> <title>MDN Games: Babylon.js demo – shapes</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0, 1, 0); return scene; }; var scene = createScene(); </script> </body> </html> In the above example, the CreateScene function is defined and the var scene = createScene () is calling the function. The CreateScene function has the scene created inside it and the next line adds color to the scene, which is done using BABYLON.Color3(1, 0.8, 0.8) and the color over here is pink. var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(1, 0.8, 0.8); Executing the above demo link in the browser will not display anything right now on the browser screen. There is one more step to be added to the code which is called the engine.runRenderLoop as in step 4. Step 4 To make the scene actually visible on the screen, we need to render it using engine.runRenderLoop call. Let us now see how this is done. Rendering Loop engine.runRenderLoop(function() { scene.render(); }); The Engine.runRenderLoop function calls scene.render, which will render the scene and make it visible to the user. The final .html will look as follows − <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Element-Creating Scene</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(1, 0.8, 0.8); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Save the above file as basicscene.html and check the output in the browser. The screen that is shown is in pink color as shown below − Step 5 Now that we have the scene, we have to add camera to it. Adding Camera and Light The code given below adds camera to the scene. There are many types of camera that can be used on Babylon. ArcRotateCamera is a camera that rotates around the target. It can be controlled with mouse,

BabylonJS – Lens Flares

BabylonJS – Lens Flares ”; Previous Next When light is scattered and falls on the image, you get to see a different image in terms of looks and the color changes too. When you develop a game to show a realistic occurrence of the light effect, lens flare is used. Consider sun rays falling on the mirror and the effect seen of it is mostly called Lens Flare. Syntax Following is the syntax to create lens flare − var lensFlareSystem = new BABYLON.LensFlareSystem(“lensFlareSystem”, light0, scene); Parameters Consider the following parameters to create lens flare − Name − Name given to the lensflaresystem. Light − This can be light source or camera. Scene − Scene to which the lens flare will be added. To add flares to the scene, execute the following command − var flare1 = new BABYLON.LensFlare(0.5, 0.15, new BABYLON.Color3(1, 1, 1), “images/sun1.png”, lensFlareSystem); Size − Floating value between 0 and 1. Position − The source (the emitter) of the lens flares (it can be a camera, a light or a mesh). Lensflaresystem − Object created using lensflaresystem class. Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Element-Creating Scene</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = BABYLON.Color3.Gray(); var camera = new BABYLON.ArcRotateCamera( “Camera”, -Math.PI / 2, 1.5, 15, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, false); var light1 = new BABYLON.HemisphericLight(“light1”, new BABYLON.Vector3(0, -1, 0), scene); light1.groundColor = new BABYLON.Color3(0.2, 0.2, 0.2); light1.intensity = 0.5; var bigdiamond = BABYLON.Mesh.CreateSphere(“sphere”, 32,6, scene); bigdiamond.visibility = 0.6; var dmat = new BABYLON.StandardMaterial(“dmat”, scene); dmat.diffuseColor = BABYLON.Color3.Blue(); var texture = new BABYLON.Texture(“images/earth.jpg”, scene); dmat.diffuseTexture = texture; dmat.specularColor = BABYLON.Color3.White(); bigdiamond.material = dmat; var lensflare1 = new BABYLON.LensFlareSystem(“lensFlareSystem”, camera, scene); var flare1 = new BABYLON.LensFlare( Math.random(), 0.15, new BABYLON.Color3(1, 1, 1), “images/sun1.png”, lensflare1); var lensflare2 = new BABYLON.LensFlareSystem(“lensFlareSystem”, camera, scene); var flare2 = new BABYLON.LensFlare( Math.random()/2, 0.1, new BABYLON.Color3(1, 0, 0), “images/sun1.png”, lensflare2); var lensflare3 = new BABYLON.LensFlareSystem(“lensFlareSystem”, camera, scene); var flare3 = new BABYLON.LensFlare( Math.random()/8, 0.1, new BABYLON.Color3(1, 0, 1), “images/sun1.png”, lensflare3); var lensflare4 = new BABYLON.LensFlareSystem(“lensFlareSystem”, camera, scene); var flare4 = new BABYLON.LensFlare( Math.random()/12, 0.1, new BABYLON.Color3(0, 1, 0), “images/sun1.png”, lensflare4); scene.registerBeforeRender(function() { scene.getCameraByID(“Camera”).alpha += 0.01; }); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Output The above line of code generates the following output − earth.jpg images/sun1.png Print Page Previous Next Advertisements ”;

BabylonJS – Create ScreenShot

BabylonJS – Create ScreenShot ”; Previous Next To capture the screen on which you are presently working, it is not possible to take screenshot with high resolution using the print screen keypress. BabylonJS provides createscreenshot APIwhich helps to do so. It saves the file as png format and the quality of the image is not sacrified. Syntax To take screenshot of the screen we need to provide engine, camera and the size as shown below. BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 }, function (data) { var img = document.createElement(“img”); img.src = data; document.body.appendChild(img); }); A button that calls the screenshot API, when a user clicks it, is put. Changes are made to the engine which is passed to the screenshot api. var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); It requires options like preserveDrawingBuffer and stencil set to true. Button is added as follows − ssButton = document.createElement(“input”); document.body.appendChild (ssButton); Click event is added to the button above and the createscreenshot is called. It will update the screenshot at the end of the screen. The data used for image src has the screenshot url created. Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Element-Creating Scene</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); var createScene = function() { var scene = new BABYLON.Scene(engine); // Setup environment var light = new BABYLON.HemisphericLight(“light1”, new BABYLON.Vector3(1, 0.5, 0), scene); var camera = new BABYLON.ArcRotateCamera(“ArcRotateCamera”, 1, 0.8, 20, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); var gmat = new BABYLON.StandardMaterial(“mat1”, scene); gmat.alpha = 1.0; //gmat.diffuseColor = new BABYLON.Color3(1, 0, 0); var texture = new BABYLON.Texture(“images/mat.jpg”, scene); gmat.diffuseTexture = texture; var ground = BABYLON.MeshBuilder.CreateGround(“ground”, {width: 150, height:15}, scene); ground.material = gmat; var mat = new BABYLON.StandardMaterial(“mat1”, scene); mat.alpha = 1.0; mat.diffuseColor = new BABYLON.Color3(1, 0, 0); var texture = new BABYLON.Texture(“images/rugby.jpg”, scene); mat.diffuseTexture = texture; var sphere = BABYLON.MeshBuilder.CreateSphere(“sphere”, {diameter: 2, diameterX: 3}, scene); sphere.position= new BABYLON.Vector3(15,1,0); sphere.material = mat; var faceColors = new Array(); faceColors[1] = new BABYLON.Color4(0,1,0,1); // green front var matcone = new BABYLON.StandardMaterial(“mat1”, scene); matcone.alpha = 1.0; matcone.diffuseColor = new BABYLON.Color3(0.9, 0, 2); var texture = new BABYLON.Texture(“images/cone.jpg”, scene); matcone.diffuseTexture = texture; var cone = BABYLON.MeshBuilder.CreateCylinder(“cone”, {diameterTop: 0, tessellation: 4}, scene); cone.position= new BABYLON.Vector3(12,1,0); cone.material = matcone; var matplane = new BABYLON.StandardMaterial(“matplane”, scene); matplane.alpha = 1.0; matplane.diffuseColor = new BABYLON.Color3(0.9, 0, 2); var texture = new BABYLON.Texture(“images/board.jpg”, scene); matplane.diffuseTexture = texture; var plane = BABYLON.MeshBuilder.CreatePlane(“plane”, {width: 5, height : 5}, scene); plane.position= new BABYLON.Vector3(9,2.5,0); plane.material = matplane; var disc = BABYLON.MeshBuilder.CreateDisc(“disc”, {tessellation: 3}, scene); disc.position= new BABYLON.Vector3(5,1,0); var mattorus = new BABYLON.StandardMaterial(“matoct”, scene); mattorus.alpha = 1.0; var texture = new BABYLON.Texture(“images/ring.jpg”, scene); mattorus.diffuseTexture = texture; var torus = BABYLON.MeshBuilder.CreateTorus(“torus”, {thickness: 0.5}, scene); torus.position= new BABYLON.Vector3(3,1,0); torus.material = mattorus; var matoct = new BABYLON.StandardMaterial(“matoct”, scene); matoct.alpha = 1.0; var texture = new BABYLON.Texture(“images/d1.png”, scene); matoct.diffuseTexture = texture; var octahedron = BABYLON.MeshBuilder.CreatePolyhedron(“oct”, {type: 1, size: 3}, scene); octahedron.position= new BABYLON.Vector3(-2,5,0); octahedron.material = matoct; var matico = new BABYLON.StandardMaterial(“matico”, scene); matico.alpha = 1.0; var texture = new BABYLON.Texture(“images/diamond.jpg”, scene); matico.diffuseTexture = texture; var icosphere = BABYLON.MeshBuilder.CreateIcoSphere(“ico”, {radius: 5, radiusY: 3, subdivisions: 2}, scene); icosphere.position= new BABYLON.Vector3(-13,3,0); icosphere.material = matico; //add screenshot button var ssButton = document.getElementById(“takescreenshot”); if (ssButton == null) { ssButton = document.createElement(“input”); document.body.appendChild(ssButton); } ssButton.id = “takescreenshot”; ssButton.type = “button”; ssButton.style.position = “fixed”; ssButton.style.right = “0px”; ssButton.style.top = “100px”; ssButton.value = “create screenshot”; ssButton.onclick = function () { BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 }, function (data) { var img = document.createElement(“img”); img.src = data; document.body.appendChild(img); }); }; return scene; } var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Output The above line of code generates the following output − In this demo, we have used images mat.jpg, rugby.jpg, cone.jpg, board.jpg, ring.jpg, d1.png, diamond.jpg. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link. Images/mat.jpg Images/rugby.jpg Images/cone.jpg Images/board.jpg Images/ring.jpg Images/d1.png Images/diamond.jpg Print Page Previous Next Advertisements ”;

BabylonJS – Playing Sounds & Music

BabylonJS – Playing Sounds and Music ”; Previous Next Without sound and music, a game is incomplete. BabylonJS sound engine comes with an API that helps to add sound effects to the game. When there is a fight seen in the game, you need to get the gunshot firing, the same can be achieved over here with babylonjs sound engine. You can get the sound effect based on the keyboard/mouse controls effect to the games. The sound engine offers ambient sound, specialized sound and directional sound. The engine supports .mp3 and .wav sound formats. Syntax var music = new BABYLON.Sound( “Music”, “sound.wav”, scene, null, { loop: true, autoplay: true } ); Parameters Consider the following parameters related to the sound engine − Name − Name of the sound. URL − url of the sound to be played. Scene − Scene to which the sound has to be played. Callbackfunction − The callbackfunction which is called when the sound is ready to be played.At present, it is null. We will go through a few examples and learn how to use it. Json object − This object has basic details of what needs to be done. sound.autoplay − With this, the sound plays automatically once the file is downloaded. loop:true − This means the sound will continuously play in a loop. Create sound folder in your project directory and download any sample audio file to test the output. Let us now add sound to the scene that we have already created. Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Scene- Playing sounds and music</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0, 1, 0); var camera = new BABYLON.ArcRotateCamera(“Camera”, 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); var music = new BABYLON.Sound(“sound”, “sounds/scooby.wav”, scene, null, { loop: true, autoplay: true }); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Output The above line of code generates the following output − Let us now check how the callback function works. If you do not want the sound to autoplay or you want to play the sound only when you want, you can do so with the callback function. For example, Var music = new BABYLON.Sound (“Music”, “music.wav”, scene, function callback() {music.play();}); Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Scene- Playing sounds and music</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0, 1, 0); var camera = new BABYLON.ArcRotateCamera(“Camera”, 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true) var music = new BABYLON.Sound( “sound”, “sounds/scooby.wav”, scene, function callback() { setTimeout(function() {music.play();}, 5000)}); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> In the callback,we will use setTimeout. This means, we want the sound to be played only after a specific time. We have added 5s as a timer to it, so the sound will play when the files Scooby.wav is downloaded and 5s complete. Play sounds with clicks and keys on the keyboard Upon clicking anywhere on the scene, you will hear explosive sound effect and if you press any of the arrow keys -left, right, up or down, it will play the explosive sound effect. For click, we are attaching the event onmousedown to the window and for keys, we will use the keydown event. Based on keycode, the sound is played. Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Scene- Playing sounds and music</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0, 1, 0); var camera = new BABYLON.ArcRotateCamera(“Camera”, 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true) var sound = new BABYLON.Sound(“gunshot”, “sounds/explosion.wav”, scene); window.addEventListener(“mousedown”, function (evt) { if (evt.button === 0) { // onclick sound.play(); } }); window.addEventListener(“keydown”, function (evt) { // arrow key left right up down if (evt.keyCode === 37 || evt.keyCode === 38 || evt.keyCode === 39 || evt.keyCode === 40) { sound.play(); } }); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Output The above line of code will generate the following output − You can control the volume of the sound in the json object, which we encountered in the beginning. For example, Var music = new BABYLON.Sound(“sound”, “sounds/scooby.wav”, scene, null, { loop: true, autoplay: true, volume:0.5 }); To know when a sound file has finished, there is an event which can be used as follows − music.onended = function () { console.log(“sound ended”); //you can do the required stuff here like play it again or play some other sound etc. }; The SetVolume property is also available in case you want to control the sound besides the constructor. For example, music.setVolume(volume); If you are playing more than one sound in your scene, you can set a global sound for all the sounds created. For example, BABYLON.Engine.audioEngine.setGlobalVolume(0.5); Creating a Spatial 3D Sound If you want to convert the sound to spatial sound (sound similar to space sound), you need to add options to your sound constructor. For example, var music = new BABYLON.Sound(“music”, “sounds/explosion.wav”, scene, null, { loop: false, autoplay: true, spatialSound: true }); Following are the different options for spatial sound − DistanceModel − It is using a “linear” equation by default. Other options are “inverse” or “exponential”. MaxDistance − It is set to 100.

BabylonJS – ShaderMaterial

BabylonJS – ShaderMaterial ”; Previous Next Shader material gives you a material as an output. You can apply this material to any mesh. It basically passes the data from your scene to the vertex and fragment shaders. To get the shader material, the following class is called − var myShaderMaterial = new BABYLON.ShaderMaterial(name, scene, route, options); Parameters Consider the following parameters related to the shader material − Name − A string, naming the shader. Scene − The scene in which the shader is to be used. Route − The route to the shader code in one of the three ways − object – { vertex: “custom”, fragment: “custom” }, used with BABYLON.Effect.ShadersStore[“customVertexShader”] and BABYLON.Effect.ShadersStore[“customFragmentShader”] object – { vertexElement: “vertexShaderCode”, fragmentElement: “fragmentShaderCode” }, used with shader code in <script> tags string – “./COMMON_NAME”, The syntax mentioned in the end is used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in the index.html folder. Options − object containing attributes and uniforms arrays containing their names as strings. The shader syntax with values look as shown below − var shaderMaterial = new BABYLON.ShaderMaterial(“shader”, scene, { vertex: “custom”, fragment: “custom”, }, { attributes: [“position”, “normal”, “uv”], uniforms: [“world”, “worldView”, “worldViewProjection”, “view”, “projection”] }); Attributes have to be in array form. These contain position, normal and uv which are vector3 3D floating point vectors. vec2 − A two-dimensional vector of floating-point numbers. vec3 − A three-dimensional vector of floating-point numbers. mat4 − A matrix with 4 columns and 4 rows floating-point numbers. gl_Position − It provides positional data for screen coordinates. gl_FragColor − It provides colour data for the representation of a facet on screen. The above are built in variables in GLSL language. Since vertex positions need to be as accurate as possible, all floating-point numbers should be set as having high precision. This is done at the start of the code for each shader using – precision highp float. The precision highp float determines how much precision is used for a float. The following demo is based on the first object method. Demo <!doctype html> <html> <head> <meta charset = “utf-8”> <title>BabylonJs – Basic Element-Creating Scene</title> <script src = “babylon.js”></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = “renderCanvas”></canvas> <script type = “text/javascript”> //downloaded HDR files from :http://www.hdrlabs.com/sibl/archive.html var canvas = document.getElementById(“renderCanvas”); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); var camera = new BABYLON.ArcRotateCamera( “Camera”, Math.PI / 4, Math.PI / 4, 4, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, true); var light = new BABYLON.HemisphericLight(“light1”, new BABYLON.Vector3(0, 1, 0), scene); BABYLON.Effect.ShadersStore[“customVertexShader”] = “rn” + “precision highp float;rn” + “// Attributesrn” + “attribute vec3 position;rn” + “attribute vec2 uv;rn” + “// Uniformsrn” + “uniform mat4 worldViewProjection;rn” + “// Varyingrn” + “varying vec2 vUV;rn” + “void main(void) { rn” + “gl_Position = worldViewProjection * vec4(position, 1.0);rn” + “vUV = uv;rn”+” } rn”; BABYLON.Effect.ShadersStore[“customFragmentShader”] = “rn”+ “precision highp float;rn” + “varying vec2 vUV;rn” + “uniform sampler2D textureSampler;rn” + “void main(void) { rn”+ “gl_FragColor = texture2D(textureSampler, vUV);rn”+” } rn”; var shaderMaterial = new BABYLON.ShaderMaterial(“shader”, scene, { vertex: “custom”, fragment: “custom”, }, { attributes: [“position”, “normal”, “uv”], uniforms: [“world”, “worldView”, “worldViewProjection”, “view”, “projection”] }); var mainTexture = new BABYLON.Texture(“images/mat.jpg”, scene); shaderMaterial.setTexture(“textureSampler”, mainTexture); shaderMaterial.backFaceCulling = false; var box = BABYLON.MeshBuilder.CreateBox(“box”, {}, scene); box.material = shaderMaterial; return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Output The above line of code will generate the following output − In this demo, we have used image mat.jpg. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link. Images/mat.jpg Print Page Previous Next Advertisements ”;