### Install Vite Project
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRDemos
Use npm to create a new Vite project with a vanilla TypeScript setup.
```bash
npm create vite@latest
##> Project name: babylon-webxr-test
##> Select a framework: vanilla
##> Select a variant: vanilla-ts
```
--------------------------------
### Full In-Browser Example with UMD Havok
Source: https://doc.babylonjs.com/features/featuresDeepDive/physics/havokPlugin
A complete HTML example demonstrating Babylon.js with the Havok physics plugin using the UMD version. It includes scene setup, physics initialization, and object creation.
```html
Babylon.js using Havok
```
--------------------------------
### Basic Particle System Setup
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro
Assigns a texture to the particle system and sets the emitter. The emitter can be a mesh, an abstract mesh, or a Vector3 position. Starts the particle emission.
```javascript
myParticleSystem.particleTexture = new BABYLON.Texture("path to texture");
myParticleSystem.emitter = mesh; // a mesh or abstract mesh in the scene
// or
myParticleSystem.emitter = point; //a Vector3
myParticleSystem.start(); //Starts the emission of particles
```
--------------------------------
### Install Babylon.GUI via NPM
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Install the Babylon.GUI package using npm. This is the recommended method for integrating GUI into your project.
```bash
npm install @babylonjs/gui
```
--------------------------------
### Dat.GUI Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui
Shows a simple example of integrating the Dat.GUI system into your Babylon.js scene. This is useful for quick debugging and parameter control.
```javascript
const gui = new dat.GUI();
const cubeFolder = gui.addFolder('Cube');
cubeFolder.add(mesh.rotation, 'x', 0, Math.PI.toFixed(2)).name('Rotate X');
cubeFolder.add(mesh.rotation, 'y', 0, Math.PI.toFixed(2)).name('Rotate Y');
cubeFolder.open();
```
--------------------------------
### Fastest Build Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/fastBuildWorld
Use `createDefaultCameraOrLight` and `createDefaultEnvironment` to quickly set up a viewable world.
```javascript
scene.createDefaultCameraOrLight(true, true, true);
scene.createDefaultEnvironment();
```
--------------------------------
### Install Babylon.js Controls
Source: https://doc.babylonjs.com/features/featuresDeepDive/controls/resizer
Install the controls npm package to use the Resizer control. This also requires installing the core package if not already present.
```bash
npm install @babylonjs/controls
```
```bash
npm install @babylonjs/core
```
--------------------------------
### Simple GUI Slider Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui
Demonstrates how to add a basic GUI slider to your Babylon.js scene. This is a good starting point for interactive elements.
```javascript
const advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
const slider = new BABYLON.GUI.Slider();
slider.minimum = 0;
slider.maximum = 1;
slider.value = 0.5;
slider.height = "30px";
slider.width = "200px";
slider.onvalueChangedObservable.add(function(value) {
console.log(value);
});
advancedTexture.addControl(slider);
```
--------------------------------
### Clipboard Observable Mesh Creation Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Example demonstrating the use of clipboard observables to create new meshes.
```javascript
advancedTexture.onClipboardObservable.add((clipText) => {
// Creates a new mesh
});
```
--------------------------------
### Observables Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Demonstrates the usage of various pointer and clipboard observables available on GUI controls.
```javascript
control.onPointerMoveObservable.add((coordinates) => {
// Called when the pointer moves over the control
});
control.onPointerEnterObservable.add((coordinates) => {
// Called when the pointer enters the control
});
control.onPointerOutObservable.add((coordinates) => {
// Called when the pointer leaves the control
});
control.onPointerDownObservable.add((coordinates) => {
// Called when the pointer is pressed down on the control
});
control.onPointerUpObservable.add((coordinates) => {
// Called when the pointer is released on the control
});
control.onPointerClickObservable.add((coordinates) => {
// Called when the control is clicked
});
control.onClipboardObservable.add((clipText) => {
// Called when a clipboard event is triggered
});
```
--------------------------------
### Standalone HTML Example with Custom Loading Screen
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
A complete HTML file demonstrating a custom loading screen with a Babylon.js scene. It includes basic CSS for the loading screen and JavaScript for engine and scene setup.
```html
Babylon.js custom loading screen example
default div text
```
--------------------------------
### Start Timeline Render Loop
Source: https://doc.babylonjs.com/features/featuresDeepDive/controls/timeline
Initiates the rendering of thumbnails for the timeline. This is the basic call to start the timeline.
```javascript
timeline.runRenderLoop();
```
--------------------------------
### Simple Motion Controller Input Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRInputControllerSupport
A basic example demonstrating how to react to controller input, such as pressing a trigger, by modifying the scaling of a 3D object.
```javascript
const xr_ids = motionController.getComponentIds();
let triggerComponent = motionController.getComponent(xr_ids[0]); //xr-standard-trigger
triggerComponent.onButtonStateChangedObservable.add(() => {
if (triggerComponent.pressed) {
Box_Right_Trigger.scaling = new BABYLON.Vector3(1.2, 1.2, 1.2);
} else {
Box_Right_Trigger.scaling = new BABYLON.Vector3(1, 1, 1);
}
});
```
--------------------------------
### Geospatial Camera Demo Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/geospatial/geospatialCamera
This example demonstrates basic geospatial camera orbiting with drag, zoom, and tilt interactions on a globe.
```typescript
Geospatial Camera Demo
[PG] Basic geospatial camera orbiting a globe with drag, zoom, and tilt interactions.
```
--------------------------------
### Create Cone
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/cylinder
This example shows how to create a cone by setting the diameterTop option to zero.
```APIDOC
## Create Cone
### Description
Creates a cone mesh by setting the `diameterTop` option to zero.
### Method
```javascript
BABYLON.MeshBuilder.CreateCylinder(name, options, scene)
```
### Parameters
#### `options.diameterTop` (number)
Set this value to 0 to create a cone.
### Request Example
```javascript
const cone = BABYLON.MeshBuilder.CreateCylinder("cone", {height: 5, diameterBottom: 2, diameterTop: 0, tessellation: 16}, scene);
```
### Response
Returns the created cone mesh.
```
--------------------------------
### Start Particle System
Source: https://doc.babylonjs.com/features/introductionToFeatures/chap6/particlespray
Initiates the particle emission process.
```javascript
particleSystem.start();
```
--------------------------------
### Install Preview Versions of Babylon.js Controls
Source: https://doc.babylonjs.com/features/featuresDeepDive/controls/resizer
If you need the latest updates while the controls are in preview, use this command to install the preview versions of both controls and core packages.
```bash
npm install @babylonjs/controls@preview
npm install @babylonjs/core@preview
```
--------------------------------
### Example Using Babylon.js Viewer
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/meshExploder
This example integrates MeshExploder with the Babylon.js Viewer. It retrieves the viewer, listens for the model loaded observable, and then applies an explosion effect to the loaded meshes, using the first loaded mesh as the center.
```javascript
BabylonViewer.viewerManager.getViewerPromiseById("babylon-viewer").then(function (viewer) {
viewerObservables(viewer);
});
let newExplosion;
function viewerObservables(viewer) {
viewer.onModelLoadedObservable.add(function (model) {
model.rootMesh.getScene().executeWhenReady(function () {
newExplosion = new BABYLON.MeshExploder(model.meshes, model.meshes[0]);
newExplosion.explode(2);
});
});
}
```
--------------------------------
### Create Cylinder
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/cylinder
This example demonstrates the basic usage of creating a cylinder mesh with default parameters.
```APIDOC
## Create Cylinder
### Description
Creates a cylinder or a cone mesh.
### Method
```javascript
BABYLON.MeshBuilder.CreateCylinder(name, options, scene)
```
### Parameters
#### `name` (string)
The name of the mesh.
#### `options` (object)
An object containing the following properties:
- **height** (number): The height of the cylinder. Defaults to 2.
- **diameterTop** (number): The diameter of the top cap. Can be zero to create a cone. Defaults to 1.
- **diameterBottom** (number): The diameter of the bottom cap. Cannot be zero. Defaults to 1.
- **diameter** (number): The diameter of both caps. Overwritten by `diameterTop` and `diameterBottom`. Defaults to 1.
- **tessellation** (number): The number of radial sides. Defaults to 24.
- **subdivisions** (number): The number of rings. Defaults to 1.
- **faceColors** (Color4[]): An array of 3 Color4 objects for bottom cap, cylinder tube, and top cap. Defaults to white for each face.
- **faceUV** (Vector4[]): An array of 3 Vector4 objects for bottom cap, cylinder tube, and top cap. Defaults to UVs(0, 0, 1, 1) for each face.
- **arc** (number): The ratio of the circumference between 0 and 1. Defaults to 1.
- **hasRings** (boolean): Makes subdivisions independent, creating separate faces. Defaults to false.
- **enclose** (boolean): Adds two extra faces per subdivision to close a sliced cylinder around its height axis. Defaults to false.
- **updatable** (boolean): Set to true if the mesh is updatable. Defaults to false.
- **sideOrientation** (number): The side orientation. Defaults to DEFAULTSIDE.
- **frontUVs** (Vector4): Only when sideOrientation: BABYLON.Mesh.DOUBLESIDE is set. Defaults to Vector4(0,0, 1,1).
- **backUVs** (Vector4): Only when sideOrientation: BABYLON.Mesh.DOUBLESIDE is set. Defaults to Vector4(0,0, 1,1).
#### `scene` (Scene, optional)
The scene to add the mesh to. Defaults to the current scene.
### Request Example
```javascript
const cylinder = BABYLON.MeshBuilder.CreateCylinder("cylinder", {height: 5, diameterBottom: 2, diameterTop: 1, tessellation: 16}, scene);
```
### Response
Returns the created cylinder mesh.
```
--------------------------------
### Control Alignments Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Demonstrates how to set the horizontal and vertical alignments for a GUI control.
```javascript
control.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER;
control.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
```
--------------------------------
### Basic SceneOptimizer Setup
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer
Instantiate SceneOptimizer with a scene and custom options. Add specific optimizations like hardware scaling.
```javascript
var options = new BABYLON.SceneOptimizerOptions();
options.addOptimization(new BABYLON.HardwareScalingOptimization(0, 1));
// Optimizer
var optimizer = new BABYLON.SceneOptimizer(scene, options);
```
--------------------------------
### Torus Creation with Options
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/torus
This example demonstrates creating a torus with specified options for diameter, thickness, tessellation, and side orientation. Ensure 'scene' is defined.
```javascript
const torus = BABYLON.MeshBuilder.CreateTorus("torus", {diameter, thickness, tessellation, updatable, sideOrientation}, scene);
```
--------------------------------
### Complete Morph Target Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets
A comprehensive example demonstrating the creation of multiple morph targets from different mesh configurations and their addition to a MorphTargetManager. This setup allows for complex deformations by blending multiple target shapes.
```javascript
const scramble = function (data) {
for (index = 0; index < data.length; index++) {
data[index] += 0.1 * Math.random();
}
};
// Main sphere
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere1", { segments: 16, diameter: 2 }, scene);
// Let's create some targets
const sphere2 = BABYLON.MeshBuilder.CreateSphere("sphere2", { segments: 16, diameter: 2 }, scene);
sphere2.setEnabled(false);
sphere2.updateMeshPositions(scramble);
const sphere3 = BABYLON.MeshBuilder.CreateSphere("sphere3", { segments: 16, diameter: 2 }, scene);
sphere3.setEnabled(false);
sphere3.scaling = new BABYLON.Vector3(2.1, 3.5, 1.0);
sphere3.bakeCurrentTransformIntoVertices();
const sphere4 = BABYLON.MeshBuilder.CreateSphere("sphere4", { segments: 16, diameter: 2 }, scene);
sphere4.setEnabled(false);
sphere4.updateMeshPositions(scramble);
const sphere5 = BABYLON.MeshBuilder.CreateSphere("sphere5", { segments: 16, diameter: 2 }, scene);
sphere5.setEnabled(false);
sphere5.scaling = new BABYLON.Vector3(1.0, 0.1, 1.0);
sphere5.bakeCurrentTransformIntoVertices();
// Create a manager and affect it to the sphere
const manager = new BABYLON.MorphTargetManager();
sphere.morphTargetManager = manager;
// Add the targets
const target0 = BABYLON.MorphTarget.FromMesh(sphere2, "sphere2", 0.25);
manager.addTarget(target0);
const target1 = BABYLON.MorphTarget.FromMesh(sphere3, "sphere3", 0.25);
manager.addTarget(target1);
const target2 = BABYLON.MorphTarget.FromMesh(sphere4, "sphere4", 0.25);
manager.addTarget(target2);
const target3 = BABYLON.MorphTarget.FromMesh(sphere5, "sphere5", 0.25);
manager.addTarget(target3);
```
--------------------------------
### Positions and Sizes Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Illustrates setting and updating the position (left, top) and size (width, height) of a GUI control, including padding.
```javascript
// Setting position and size with pixel units
control.left = "50px";
control.top = "100px";
control.width = "200px";
control.height = "150px";
// Setting position and size with percentage units
control.left = "50%";
control.top = "50%";
control.width = "50%";
control.height = "50%";
// Setting position and size with default unit (percentage)
control.width = 0.5;
control.height = 0.5;
// Setting padding
control.paddingTop = "10px";
control.paddingBottom = "10px";
control.paddingLeft = "5px";
control.paddingRight = "5px";
```
--------------------------------
### Initialize a Point Cloud System
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/point_cloud_system/pcs_creation
Create an empty PCS by providing its name, particle size, and the scene. This is the first step before adding any particles.
```javascript
var pcs = new BABYLON.PointsCloudSystem("pcs", 5, scene);
```
--------------------------------
### Custom Start Direction Function
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/customizingParticles
Defines a custom function to set the initial direction of particles. This example randomizes the direction within specified bounds.
```typescript
particleSystem.startDirectionFunction = (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle, isLocal: boolean) {
var randX = randomNumber(this.direction1.x, this.direction2.x);
var randY = randomNumber(this.direction1.y, this.direction2.y);
var randZ = randomNumber(this.direction1.z, this.direction2.z);
Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
}
```
--------------------------------
### Load and Animate a Skinned Mesh
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
Loads a mesh with a skeleton from a .babylon file and starts its animation. Ensure the scene has default camera and environment setup.
```javascript
BABYLON.ImportMeshAsync("scenes/Dude/Dude.babylon", scene, { meshNames: "him" }).then(function (result) {
scene.createDefaultCameraOrLight(true, true, true);
scene.createDefaultEnvironment();
scene.beginAnimation(result.skeletons[0], 0, 100, true, 1.0);
});
```
--------------------------------
### Run Development Server
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRDemos
Start the Vite development server with the `--host 0.0.0.0` flag to make it accessible from other devices on the network.
```bash
npm run dev -- --host 0.0.0.0
```
--------------------------------
### Custom Start Position Function
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/customizingParticles
Defines a custom function to set the initial position of particles. This example randomizes the position within a defined emission box.
```typescript
particleSystem.startPositionFunction = (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle, isLocal: boolean): void => {
var randX = randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
var randY = randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
var randZ = randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
};
```
--------------------------------
### Full Example: Record, Modify, and Apply Delta
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/deltaFiles
Demonstrates the complete workflow: setting up a scene, recording changes, making modifications (position, color, intensity, dispose), and then applying the recorded delta.
```javascript
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
camera.setTarget(BABYLON.Vector3.Zero());
camera.attachControl(canvas, true);
var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
var sphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 2, segments: 32 }, scene);
sphere.position.y = 1;
var ground = BABYLON.MeshBuilder.CreateGround("ground", { width: 6, height: 6 }, scene);
// Instantiate the recorder
var recorder = new BABYLON.SceneRecorder();
recorder.track(scene);
// Let's make some changes
sphere.position.y = 0;
scene.clearColor.r = 1;
light.intensity = 0;
var light2 = new BABYLON.HemisphericLight("light2", new BABYLON.Vector3(0, 1, 0), scene);
ground.dispose();
// Now we can get the delta file
let delta = recorder.getDelta();
// Just to see the changes, we are updating the value so we can see what the delta is doing
ground = BABYLON.MeshBuilder.CreateGround("ground", { width: 6, height: 6 }, scene);
light2.dispose();
sphere.position.y = 2;
scene.clearColor.r = 0;
light.intensity = 1.0;
// Apply the delta
BABYLON.SceneRecorder.ApplyDelta(delta, scene);
```
--------------------------------
### Basic Raycast Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/physics/raycast
Performs a raycast from a start point to an end point and logs the hit point if a collision occurs. The `raycastResult` object should be reused for performance.
```javascript
var raycastResult = new BABYLON.PhysicsRaycastResult();
var start = new BABYLON.Vector3(1, 20, 2);
var end = new BABYLON.Vector3(1, -20, 2);
physicsEngine.raycastToRef(start, end, raycastResult);
if (raycastResult.hasHit) {
console.log("Collision at ", raycastResult.hitPointWorld);
}
```
--------------------------------
### Update particles from a specific index
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/point_cloud_system/pcs_manage
This example demonstrates updating only a subset of particles, starting from a specific index, which can be useful for managing different particle behaviors or pools.
```javascript
setParticles(5000, 9999, true);
```
--------------------------------
### Import Models and Build World Quickly
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/fastBuildWorld
Combine `BABYLON.AppendSceneAsync` with `createDefaultCameraOrLight` and `createDefaultEnvironment` to quickly import models and set up a basic scene. Ensure these helpers are called within the scene loading callback.
```javascript
BABYLON.AppendSceneAsync("https://www.babylonjs.com/assets/DamagedHelmet/glTF/", "DamagedHelmet.gltf", scene).then(function ({ meshes }) {
scene.createDefaultCameraOrLight(true, true, true);
scene.createDefaultEnvironment();
});
```
--------------------------------
### AdvancedTimer for Flexible Timer Control
Source: https://doc.babylonjs.com/features/featuresDeepDive/events/observables
The AdvancedTimer class offers more flexibility than setAndStartTimer. This example shows how to instantiate and use it with observables for starting and stopping, and handling timer events.
```typescript
const guiButton = // created a GUI button
const guiButtonMaterial = ... // get the material
const advancedTimer : BABYLON.AdvancedTimer = new BABYLON.AdvancedTimer({
timeout: 3000,
contextObservable: scene.onBeforeRenderObservable
});
advancedTimer.onEachCountObservable.add(() => {
// turn it slowly green on each call to the registered observer
guiButtonMaterial.diffuseColor.set(0,data.completeRate,0);
});
advancedTimer.onTimerAbortedObservable.add(() => {
// Aborted, back to a black button
guiButtonMaterial.diffuseColor.set(0,0,0);
});
advancedTimer.onTimerEndedObservable.add(() => {
// back to a black button
guiButtonMaterial.diffuseColor.set(0,0,0);
console.log('Button pressed!');
});
scene.onPointerDown = () => {
advancedTimer.start();
}
scene.onPointerUp = () => {
advancedTimer.stop();
}
```
--------------------------------
### Create a Scene with WebXR and Floor Meshes
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/introToWebXR
This example demonstrates creating a basic Babylon.js scene with a sphere and enabling WebXR support. It uses the async/await pattern and configures floor meshes for the XR experience.
```javascript
var createScene = async function () {
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
camera.setTarget(BABYLON.Vector3.Zero());
camera.attachControl(canvas, true);
var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
var sphere = BABYLON.MeshBuilder.CreateSphere("sphere1", { segments: 16, diameter: 2 }, scene);
sphere.position.y = 1;
const env = scene.createDefaultEnvironment();
// here we add XR support
const xr = await scene.createDefaultXRExperienceAsync({
floorMeshes: [env.ground],
});
return scene;
};
```
--------------------------------
### Simple Command Buffer Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/smartFilters/howSmartFiltersWork
Illustrates the command buffer content for a basic Smart Filter, showing a single render command.
```text
----- Command buffer commands -----
Owner: OutputBlock (output) - Command: OutputBlock.render
-----------------------------------
```
--------------------------------
### Example Color Array for Goldberg Faces
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/goldberg_poly
Defines an array of color definitions for Goldberg polyhedron faces. Each element specifies a start face, end face, and a Color4 object.
```javascript
const colorArray = [
[18, 18, new BABYLON.Color4(1, 0, 0, 1)], // color face 18 red
[26, 37, new BABYLON.Color4(0, 1, 0, 1)], //color faces 26 to 37 inclusive green
];
```
--------------------------------
### Custom Loading Screen in Plain JavaScript
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
Implement the ILoadingScreen interface using JavaScript prototype for a custom loading screen. This example shows basic alert messages for loading start and end.
```javascript
function CustomLoadingScreen(/* variables needed, for example:*/ text) {
//init the loader
this.loadingUIText = text;
}
CustomLoadingScreen.prototype.displayLoadingUI = function () {
alert(this.loadingUIText);
};
CustomLoadingScreen.prototype.hideLoadingUI = function () {
alert("Loaded!");
};
```
--------------------------------
### Create and Configure a Reflection Probe
Source: https://doc.babylonjs.com/features/featuresDeepDive/environment/reflectionProbes
Instantiate a reflection probe and specify which meshes to include in its rendering. Assign the probe's cube texture to a material for reflections.
```javascript
const probe = new BABYLON.ReflectionProbe("main", 512, scene);
probe.renderList.push(yellowSphere);
probe.renderList.push(greenSphere);
probe.renderList.push(blueSphere);
probe.renderList.push(mirror);
mainMaterial.reflectionTexture = probe.cubeTexture;
```
--------------------------------
### Example UV Array for Goldberg Faces
Source: https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/goldberg_poly
Defines an array of UV definitions for Goldberg polyhedron faces. Each element specifies a start face, end face, a Vector2 center, radius, and angle.
```javascript
const uvArray = [
[18, 18, new BABYLON.Vector2(0.25, 0.75), 0.25, 0], // updates the uvs for face 18 to match the vertices of the green hexagon in Fig 3
[26, 37, new BABYLON.Vector2(0.625, 0.37), 0.37, Math.PI / 2], //updates the uvs for faces 26 to 37 to match the vertices of the red hexagon in Fig 3
];
```
--------------------------------
### Manually Play Video Texture
Source: https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture
Handle user interaction to play video textures, as modern browsers often restrict autoplay with audio. This example starts playback on the first pointer down event.
```javascript
scene.onPointerDown = function () {
videoTexture.video.play();
scene.onPointerDown = null;
};
```
--------------------------------
### Create a Babylon.js Scene with WebXR Support
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/introToWebXR
This snippet demonstrates setting up a basic Babylon.js scene, including lighting, camera, environment, shadows, and enabling WebXR support via the VR helper. It also includes a GUI color picker that functions in XR.
```javascript
var createScene = function () {
// Create scene
var scene = new BABYLON.Scene(engine);
// Create simple sphere
var sphere = BABYLON.MeshBuilder.CreateIcoSphere(
"sphere",
{
radius: 0.2,
flat: true,
subdivisions: 1,
},
scene,
);
sphere.position.y = 3;
sphere.material = new BABYLON.StandardMaterial("sphere material", scene);
// Lights and camera
var light = new BABYLON.DirectionalLight("light", new BABYLON.Vector3(0, -0.5, 1.0), scene);
light.position = new BABYLON.Vector3(0, 5, -2);
var camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 4, 3, new BABYLON.Vector3(0, 3, 0), scene);
camera.attachControl(canvas, true);
scene.activeCamera.beta += 0.8;
// Default Environment
var environment = scene.createDefaultEnvironment({
enableGroundShadow: true,
groundYBias: 2.8,
});
environment.setMainColor(BABYLON.Color3.FromHexString("#74b9ff"));
// Shadows
var shadowGenerator = new BABYLON.ShadowGenerator(1024, light);
shadowGenerator.useBlurExponentialShadowMap = true;
shadowGenerator.blurKernel = 32;
shadowGenerator.addShadowCaster(sphere, true);
// Enable VR, use XR when possible
var vrHelper = scene.createDefaultVRExperience({
createDeviceOrientationCamera: false,
useXR: true, // This will enable XR if supported
floorMeshes: [environment.ground],
});
// Runs every frame to rotate the sphere
scene.onBeforeRenderObservable.add(() => {
sphere.rotation.y += 0.0001 * scene.getEngine().getDeltaTime();
sphere.rotation.x += 0.0001 * scene.getEngine().getDeltaTime();
});
// GUI
var plane = BABYLON.MeshBuilder.CreatePlane("plane", { size: 1 });
plane.position = new BABYLON.Vector3(0.4, 4, 0.4);
var advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(plane);
var panel = new BABYLON.GUI.StackPanel();
advancedTexture.addControl(panel);
var header = new BABYLON.GUI.TextBlock();
header.text = "Color GUI";
header.height = "100px";
header.color = "white";
header.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER;
header.fontSize = "120";
panel.addControl(header);
var picker = new BABYLON.GUI.ColorPicker();
picker.value = sphere.material.diffuseColor;
picker.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER;
picker.height = "350px";
picker.width = "350px";
// This will work in XR, since we are using native pointer events!
picker.onValueChangedObservable.add(function (value) {
sphere.material.diffuseColor.copyFrom(value);
});
panel.addControl(picker);
vrHelper.onAfterEnteringVRObservable.add(() => {
// This callback will still work! Would be better to use the XR native observables.
});
return scene;
};
```
--------------------------------
### Manually Start a Flow Graph
Source: https://doc.babylonjs.com/features/featuresDeepDive/flowGraph/flowGraphBasicConcepts
Begin the execution of a specific FlowGraph. While graphs are typically started by their coordinator, manual starting is also possible.
```javascript
graph.start();
```
--------------------------------
### HTML GUI Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui
Illustrates a basic implementation of using HTML GUI elements overlaid on your Babylon.js scene. This leverages familiar web technologies for UI design.
```javascript
const htmlGUITexture = BABYLON.GUI.HtmlButton.Create("button", "Click Me", "100px", "50px");
htmlGUITexture.position.x = -0.2;
advancedTexture.addControl(htmlGUITexture);
htmlGUITexture.onPointerUpObservable.add(function() {
alert("button clicked");
});
```
--------------------------------
### Set up Scene with Camera and Emitter
Source: https://doc.babylonjs.com/features/featuresDeepDive/materials/node_material/particles_and_nme
Initializes a Babylon.js scene, camera, and a sphere to serve as a particle emitter.
```javascript
const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 10, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// Create a random emitter
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 0.01, segments: 4 }, scene);
```
--------------------------------
### Enable Random Start Cell for Particles
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/animation
Starting from Babylon.js v3.3, you can enable random selection of the start sprite cell ID for each particle within the defined range.
```javascript
particleSystem.spriteRandomStartCell = true;
```
--------------------------------
### Create and Start Animation Helper Function Signature
Source: https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations
Defines the signature for a helper function to create and start animations. This function generates two keyframes (start and end) and works on AbstractMesh objects.
```javascript
Animation.CreateAndStartAnimation = function(name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode);
```
--------------------------------
### Install Recast Navigation Dependencies
Source: https://doc.babylonjs.com/features/featuresDeepDive/crowdNavigation/v2Intro
Install the necessary packages for using the recast-navigation-js library with Babylon.js.
```bash
npm i @babylonjs/addons @recast-navigation/core @recast-navigation/generators
```
--------------------------------
### Create Standard Rendering Pipeline
Source: https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/standardRenderingPipeline
Instantiate the Standard Rendering Pipeline by providing a name, the scene, a rendering ratio, an optional base post-process, and a list of cameras.
```javascript
var pipeline = new BABYLON.StandardRenderingPipeline(
"standard", // The name of the pipeline
scene, // The scene instance
1.0, // The rendering pipeline ratio
null, // The original post-process that the pipeline will be based on
[camera] // The list of cameras to be attached to
);
```
--------------------------------
### onPointerClickObservable Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Specific example showing how to use the onPointerClickObservable to handle click events on a control.
```javascript
control.onPointerClickObservable.add(() => {
console.log("Control clicked!");
});
```
--------------------------------
### Create and Configure a Selection Panel
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/selector
Create a fullscreen advanced dynamic texture, then instantiate and configure a SelectionPanel with specific dimensions and alignment. Finally, add the panel to the texture and append selector groups to it.
```javascript
const advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
const selectBox = new BABYLON.GUI.SelectionPanel("selectBox");
selectBox.width = 0.25;
selectBox.height = 0.52;
selectBox.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
selectBox.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM;
advancedTexture.addControl(selectBox);
selectBox.addGroup(rotateGroup);
selectBox.addGroup(transformGroup);
selectBox.addGroup(colorGroup);
```
--------------------------------
### Install Babylon.js ES6 Packages
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRDemos
Install the core Babylon.js engine and loaders packages using npm.
```bash
npm install @babylonjs/core
npm install @babylonjs/loaders
```
--------------------------------
### Create Basic WebXR Experience Helper
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRExperienceHelpers
Use the static factory method to create an instance of the WebXR Experience Helper. This method is asynchronous and returns a Promise. Catch exceptions if the browser does not support XR.
```javascript
const xrHelper = await WebXRExperienceHelper.CreateAsync(scene);
```
```javascript
try {
const xrHelper = await WebXRExperienceHelper.CreateAsync(scene);
} catch (e) {
// no XR support
}
```
```javascript
WebXRExperienceHelper.CreateAsync(scene).then((xrHelper) => {
// great success
}, (error) => {
// no xr...
})
```
--------------------------------
### Simple SPS Material Setup with `useModelMaterial`
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_material
Use this method to automatically assign materials from models to particles. The SPS optimizes draw calls by reusing identical materials. Set `useModelMaterial` to true during SPS creation.
```javascript
var sps = new BABYLON.SolidParticleSystem("sps", scene, {
useModelMaterial: true
});
sps.addShape(model1, 300);
sps.addShape(model2, 300);
sps.addShape(model3, 300);
sps.buildMesh();
```
--------------------------------
### Pointer Input Condition Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/cameras/cameraMovementSystem
Example of a condition object for pointer input, matching a left-click with specific modifiers.
```json
{
source: "pointer", button: 0, interaction: "pan"
}
```
```json
{
source: "pointer", button: 0, modifiers: { ctrl: true }, interaction: "pan"
}
```
```json
{
source: "pointer", button: 0, modifiers: { ctrl: true, alt: false }, interaction: "pan"
}
```
--------------------------------
### Remove Start Size Gradient
Source: https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/tuning_gradients
Removes a start size gradient at a specific fraction of the particle system's duration.
```javascript
particleSystem.removeStartSizeGradient(0.4);
```
--------------------------------
### Set Up Basic WebXR Scene
Source: https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRDemos
Configure a basic Babylon.js scene in main.ts, including engine, scene, light, environment, camera, a sphere, and WebXR default experience with floor detection for teleportation. Essential imports for NodeMaterial blocks and GLTF loaders are included.
```typescript
import "./style.css";
import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera.js";
import { Color3 } from "@babylonjs/core/Maths/math.color.js";
import { Engine } from "@babylonjs/core/Engines/engine.js";
import { EnvironmentHelper } from "@babylonjs/core/Helpers/environmentHelper.js";
import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js";
import { Mesh } from "@babylonjs/core/Meshes/mesh";
import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder.js";
import { Scene } from "@babylonjs/core/scene.js";
import { StandardMaterial } from "@babylonjs/core/Materials/standardmaterial.js";
import { Vector3 } from "@babylonjs/core/Maths/math.vector.js";
import { WebXRDefaultExperience } from "@babylonjs/core/XR/webXRDefaultExperience.js";
// Required for EnvironmentHelper
import "@babylonjs/core/Materials/Textures/Loaders";
// Enable GLTF/GLB loader for loading controller models from WebXR Input registry
import "@babylonjs/loaders/glTF";
// Without this next import, an error message like this occurs loading controller models:
// Build of NodeMaterial failed" error when loading controller model
// Uncaught (in promise) Build of NodeMaterial failed: input rgba from block
// FragmentOutput[FragmentOutputBlock] is not connected and is not optional.
import "@babylonjs/core/Materials/Node/Blocks";
// Create a canvas element for rendering
const app = document.querySelector("#app");
const canvas = document.createElement("canvas");
app?.appendChild(canvas);
// Create engine and a scene
const babylonEngine = new Engine(canvas, true);
const scene = new Scene(babylonEngine);
// Add a basic light
new HemisphericLight("light1", new Vector3(0, 2, 0), scene);
// Create a default environment (skybox, ground mesh, etc)
const envHelper = new EnvironmentHelper(
{
skyboxSize: 30,
groundColor: new Color3(0.5, 0.5, 0.5),
},
scene,
);
// Add a camera for the non-VR view in browser
const camera = new ArcRotateCamera("Camera", -(Math.PI / 4) * 3, Math.PI / 4, 10, new Vector3(0, 0, 0), scene);
camera.attachControl(true);
// Add a sphere to have something to look at
const sphereD = 1.0;
const sphere = MeshBuilder.CreateSphere("xSphere", { segments: 16, diameter: sphereD }, scene);
sphere.position.x = 0;
sphere.position.y = sphereD * 2;
sphere.position.z = 0;
const rMat = new StandardMaterial("matR", scene);
rMat.diffuseColor = new Color3(1.0, 0, 0);
sphere.material = rMat;
// Setup default WebXR experience
// Use the enviroment floor to enable teleportation
WebXRDefaultExperience.CreateAsync(scene, {
floorMeshes: [envHelper?.ground as Mesh],
optionalFeatures: true,
});
// Run render loop
babylonEngine.runRenderLoop(() => {
scene.render();
});
```
--------------------------------
### Install HtmlInCanvasPolyfill
Source: https://doc.babylonjs.com/features/featuresDeepDive/materials/using/htmlTexture
Install the HtmlInCanvasPolyfill helper from @babylonjs/core when the native API is not present. This polyfill lazily imports three-html-render only when needed.
```javascript
import { InstallHtmlInCanvasPolyfill } from "@babylonjs/core/Materials/Textures/HTML/htmlInCanvasPolyfill";
// No-op when the API is supported natively; installs the polyfill otherwise.
await InstallHtmlInCanvasPolyfill();
```
--------------------------------
### Initialize Havok Physics with npm (async/await)
Source: https://doc.babylonjs.com/features/featuresDeepDive/physics/havokPlugin
Import and initialize the Havok physics engine using npm with async/await syntax. This method ensures the WebAssembly module is ready before proceeding.
```javascript
import HavokPhysics from "@babylonjs/havok";
async function getInitializedHavok() {
return await HavokPhysics();
}
```
--------------------------------
### Clipboard Observable Textblock Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui
Example demonstrating the use of clipboard observables to create new textblocks from clipboard data.
```javascript
advancedTexture.onClipboardObservable.add((clipText) => {
// Creates a new textblock
});
```
--------------------------------
### Create Browser Instance and Load Webpage with Puppeteer
Source: https://doc.babylonjs.com/features/featuresDeepDive/scene/renderRemoteScreenshot
Launches a headless browser instance and navigates to a specified webpage. Ensure Puppeteer is installed.
```javascript
const browser = await puppeteer.launch({});
const page = await browser.newPage();
await page.goto("https://playground.babylonjs.com/frame.html#PN1NNI#1");
```
--------------------------------
### Keyboard Input Condition Example
Source: https://doc.babylonjs.com/features/featuresDeepDive/cameras/cameraMovementSystem
Example of a condition object for keyboard input, binding multiple keys to a single interaction.
```json
{ source: "keyboard", key: [187, 107, 189, 109], interaction: "zoom" }
```
--------------------------------
### Start All Graphs in a Coordinator
Source: https://doc.babylonjs.com/features/featuresDeepDive/flowGraph/flowGraphBasicConcepts
Initiate the execution of all graphs associated with a FlowGraphCoordinator. This method should be called after graphs have been created and potentially started individually.
```javascript
coordinator.start();
```
--------------------------------
### Create and Configure a Holographic Slate
Source: https://doc.babylonjs.com/features/featuresDeepDive/gui/gui3D
Set up a HolographicSlate with a title, minimum dimensions, and initial dimensions. The content and GUI manager must be added after initialization.
```javascript
// Create the 3D UI manager
const manager = new BABYLON.GUI.GUI3DManager(scene);
// Let's add a slate
const slate = new BABYLON.GUI.HolographicSlate("down");
slate.title = "Checkers";
slate.minDimensions = new BABYLON.Vector(5, 5);
slate.dimensions = new BABYLON.Vector2(10, 10);
slate.titleBarHeight = 1.5;
manager.addControl(slate);
// Must be done AFTER addControl in order to overwrite the default content
slate.content = new BABYLON.GUI.Image("checkers", "./textures/Checker_Albedo.png");
```
--------------------------------
### Install Babylon.js Controls
Source: https://doc.babylonjs.com/features/featuresDeepDive/controls/timeline
Install the necessary npm package for the Babylon.js controls library. This is the first step to using the Timeline Control.
```bash
npm install @babylonjs/controls
```