---
name: babylonjs-edbc3c9dae62
description: >-
  Babylon.js is an open-source 3D engine for the browser that renders with
  WebGL or WebGPU and includes a scene graph, PBR materials, glTF loading,
  Havok physics, a GUI layer and WebXR. Use when a user asks to build a 3D
  scene, game, product configurator or VR/AR experience with Babylon.js, load a
  glTF/GLB model, add physics or in-scene UI, switch to WebGPU, or shrink a
  Babylon.js bundle.
license: Apache-2.0
compatibility: "Babylon.js 9 (@babylonjs/* ES module packages) with a bundler such as Vite; WebGL2 or WebGPU browser; Havok needs WebAssembly SIMD"
metadata:
  author: terminal-skills
  version: 1.1.0
  category: design
  repository: https://github.com/BabylonJS/Babylon.js
  tags: "3d, game-engine, webgl, webgpu, physics"
---

# Babylon.js — Professional 3D Engine for the Web

## Overview

Babylon.js is a complete 3D engine written in TypeScript: scene graph, cameras, lights, PBR materials, animation, particles, glTF and other loaders, Havok physics, a 2D/3D GUI and WebXR, running on WebGL or WebGPU. In a bundled app use the `@babylonjs/*` ES module packages (core, loaders, gui and materials share one version number, currently 9.x; `@babylonjs/havok` is versioned separately); the `babylonjs` UMD package is for pages without a bundler, and the CDN scripts are for playgrounds and quick experiments.

## Instructions

### Installation

```bash
npm install @babylonjs/core @babylonjs/loaders @babylonjs/gui
npm install @babylonjs/havok                # Physics (optional)
npm install @babylonjs/materials            # Advanced materials (optional)
npm install --save-dev @babylonjs/inspector # Debug inspector (optional)
```

The page needs a canvas: `<canvas id="renderCanvas" style="width:100%;height:100%"></canvas>`.

### Scene Setup

```typescript
// src/main.ts — Babylon.js scene
import {
  Engine, Scene, ArcRotateCamera, HemisphericLight,
  Vector3, MeshBuilder, PBRMaterial, Color3, Color4,
} from "@babylonjs/core";

const canvas = document.getElementById("renderCanvas") as HTMLCanvasElement;
const engine = new Engine(canvas, true, { adaptToDeviceRatio: true });   // 2nd argument: antialiasing

const scene = new Scene(engine);
scene.clearColor = new Color4(0.1, 0.1, 0.15, 1);

// Camera (orbit around target)
const camera = new ArcRotateCamera("camera", Math.PI / 4, Math.PI / 3, 10, Vector3.Zero(), scene);
camera.attachControl(canvas, true);
camera.lowerRadiusLimit = 3;              // Min zoom
camera.upperRadiusLimit = 20;             // Max zoom

// Lighting
const light = new HemisphericLight("light", new Vector3(0, 1, 0), scene);
light.intensity = 0.7;

// PBR Material
const material = new PBRMaterial("pbr", scene);
material.albedoColor = new Color3(0.8, 0.2, 0.3);
material.metallic = 0.3;
material.roughness = 0.4;

// Mesh
const sphere = MeshBuilder.CreateSphere("sphere", { diameter: 2, segments: 32 }, scene);
sphere.material = material;

// Render loop
engine.runRenderLoop(() => scene.render());
window.addEventListener("resize", () => engine.resize());
```

### Loading 3D Models

```typescript
import { ImportMeshAsync, LoadAssetContainerAsync } from "@babylonjs/core";
import { registerBuiltInLoaders } from "@babylonjs/loaders/dynamic";

registerBuiltInLoaders();                 // once at startup; each loader is downloaded on first use

// Load a glTF/GLB model: the URL comes first, the scene second
const result = await ImportMeshAsync("/models/product.glb", scene);
const model = result.meshes[0];           // "__root__" node that parents the glTF content
model.scaling = new Vector3(0.5, 0.5, 0.5);

// Access specific meshes by name
const body = scene.getMeshByName("Body");
if (body?.material instanceof PBRMaterial) {
  body.material.albedoColor = new Color3(1, 0, 0);   // Red
}

// Load without showing, then add (and later remove) everything in one call
const container = await LoadAssetContainerAsync("/models/showroom.glb", scene);
container.addAllToScene();
```

`SceneLoader.ImportMeshAsync("", "/models/", "product.glb", scene)` from older tutorials still works but is deprecated in favour of these module-level functions.

### Physics (Havok)

```typescript
import { HavokPlugin, PhysicsAggregate, PhysicsShapeType } from "@babylonjs/core";
import HavokPhysics from "@babylonjs/havok";

// Initialize Havok (downloads and compiles HavokPhysics.wasm)
const havok = await HavokPhysics();
scene.enablePhysics(new Vector3(0, -9.81, 0), new HavokPlugin(true, havok));

// Add physics to meshes
const ground = MeshBuilder.CreateGround("ground", { width: 20, height: 20 }, scene);
new PhysicsAggregate(ground, PhysicsShapeType.BOX, { mass: 0 }, scene);  // mass 0 = static

const ball = MeshBuilder.CreateSphere("ball", { diameter: 1 }, scene);
ball.position.y = 10;
new PhysicsAggregate(ball, PhysicsShapeType.SPHERE, {
  mass: 1,
  restitution: 0.7,                      // Bounciness
}, scene);
```

### GUI (2D UI in 3D)

```typescript
import { AdvancedDynamicTexture, Button, Control, Rectangle, StackPanel, TextBlock } from "@babylonjs/gui";

// Full-screen UI overlay
const ui = AdvancedDynamicTexture.CreateFullscreenUI("UI");

const panel = new StackPanel();
panel.width = "220px";
panel.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT;
panel.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP;
panel.paddingTop = "20px";
panel.paddingLeft = "20px";
ui.addControl(panel);

const button = Button.CreateSimpleButton("btn", "Change Color");
button.width = "200px";
button.height = "40px";
button.color = "white";
button.background = "#6366f1";
button.onPointerClickObservable.add(() => {
  material.albedoColor = Color3.Random();
});
panel.addControl(button);

// Label that follows a mesh on screen
const label = new Rectangle("label");
label.width = "140px";
label.height = "32px";
label.thickness = 0;
label.background = "#000000aa";
ui.addControl(label);                    // must be added to the texture before linking
label.linkWithMesh(sphere);
label.linkOffsetY = -80;

const text = new TextBlock("labelText", "Trail Runner 2");
text.color = "white";
text.fontSize = 16;
label.addControl(text);
```

### WebXR (VR/AR)

```typescript
// VR: adds an "enter VR" button, teleportation on the floor meshes and controller pointers
const xr = await scene.createDefaultXRExperienceAsync({
  floorMeshes: [ground],
});

// AR instead of VR
const xrAR = await scene.createDefaultXRExperienceAsync({
  uiOptions: { sessionMode: "immersive-ar", referenceSpaceType: "local-floor" },
  optionalFeatures: true,
});
```

### WebGPU and the Inspector

```typescript
import { Engine, WebGPUEngine } from "@babylonjs/core";

// WebGPU must be initialized asynchronously; fall back to WebGL where it is missing
const engine = (await WebGPUEngine.IsSupportedAsync)
  ? await WebGPUEngine.CreateAsync(canvas, { adaptToDeviceRatio: true })
  : new Engine(canvas, true);

if (import.meta.env.DEV) {                 // Vite dev server only: scene explorer, properties, stats
  const { ShowInspector } = await import("@babylonjs/inspector");   // a static import would ship it to production
  ShowInspector(scene);
}
```

## Examples

### Example 1: A product viewer with Vite

**User request:** "Show our shoe model in the browser so people can orbit around it and change its color."

```bash
npm install @babylonjs/core @babylonjs/loaders @babylonjs/gui
npm install --save-dev vite typescript
```

Put the canvas in `index.html` with `<script type="module" src="/src/main.ts"></script>`, copy the model to `public/models/product.glb`, and assemble `src/main.ts` from the Scene Setup, Loading 3D Models and GUI blocks above — without the demo sphere and the `showroom.glb` lines (a failed load rejects the top-level `await`, so the GUI code never runs), with the button setting `body.material.albedoColor` and the label linked to `model`. Then `npx vite` serves it and `npx vite build` produces the deployable files (two of about 1,100 output lines, because the dynamic imports split the engine into many chunks):

```
dist/assets/glTFLoader.pure-CG7fbjTQ.js      69.17 kB │ gzip:  18.79 kB
dist/assets/index-8MhFnHTx.js             4,063.46 kB │ gzip: 874.64 kB
✓ built in 684ms
```

The glTF loader is a separate chunk that is fetched only when the first model loads; the scene shows the model on a dark background, dragging orbits the camera, and the button assigns a random albedo color to the `Body` mesh.

### Example 2: Shrink the bundle

**User request:** "Our Babylon.js bundle is several megabytes. Can you cut it down?"

Importing from the package root pulls in the whole engine because many modules have side effects. Import each class from its own module instead (folders start with an upper-case letter, files with a lower-case one):

```typescript
import { Engine } from "@babylonjs/core/Engines/engine.js";
import { Scene } from "@babylonjs/core/scene.js";
import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera.js";
import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js";
import { Vector3 } from "@babylonjs/core/Maths/math.vector.js";
import { Color3, Color4 } from "@babylonjs/core/Maths/math.color.js";
import { CreateSphere } from "@babylonjs/core/Meshes/Builders/sphereBuilder.js";
import { PBRMaterial } from "@babylonjs/core/Materials/PBR/pbrMaterial.js";

const sphere = CreateSphere("sphere", { diameter: 2, segments: 32 }, scene);   // instead of MeshBuilder.CreateSphere
```

For the Scene Setup block above, the entry chunk of the Vite build goes from 6,676 kB (1,475 kB gzip) to 967 kB (236 kB gzip). Features added through module augmentation need their own side-effect import, for example `import "@babylonjs/core/Physics/physicsEngineComponent.js"` for `scene.enablePhysics` and `import "@babylonjs/core/Helpers/sceneHelpers.js"` for `scene.createDefaultXRExperienceAsync`.

## Guidelines

1. **PBR materials** — use `PBRMaterial` for realistic rendering; set metallic/roughness and give the scene an environment texture (`scene.environmentTexture`), because PBR reflections come from it.
2. **Asset loading** — call `registerBuiltInLoaders()` once, then `ImportMeshAsync(url, scene)`; without a registered loader a `.glb` cannot be read. Compress large models with Draco or Meshopt.
3. **Havok physics** — Havok is the recommended engine (Physics V2); the Ammo, Cannon and Oimo plugins are deprecated. It needs WebAssembly SIMD (not available on iOS before 16.4), and in Node the wasm must be passed in: `HavokPhysics({ wasmBinary })`.
4. **Inspector** — keep `@babylonjs/inspector` out of production bundles (it brings React and Fluent UI): load it with a dynamic `import()` behind a dev check, because a guarded static import is not tree-shaken; the older `scene.debugLayer.show()` call still works once `@babylonjs/core/Debug/debugLayer.js` and `@babylonjs/inspector` are imported.
5. **Node Material Editor** — build custom shaders visually at nme.babylonjs.com instead of writing GLSL/WGSL; `npx -y @babylonjs/mcp-servers nme` starts an MCP server for that editor (`gui`, `nge` and `npe` do the same for the GUI, geometry and particle editors).
6. **GUI for UI** — Babylon GUI draws buttons, panels and sliders inside the canvas, as a fullscreen overlay or on a mesh (`AdvancedDynamicTexture.CreateForMesh`); labels that track an object use `linkWithMesh`. For forms and long text use regular HTML over the canvas.
7. **WebGPU** — `new WebGPUEngine(canvas)` is unusable until `await engine.initAsync()` (or use `WebGPUEngine.CreateAsync`); always keep the WebGL fallback.
8. **XR** — WebXR only runs on HTTPS (or localhost) and must start from a user gesture, which the default enter-XR button provides. XR on a WebGPU engine is experimental and needs `{ xrCompatible: true }` at engine creation; use the WebGL engine for XR otherwise.
9. **Clean up** — in single-page apps call `scene.dispose()` and `engine.dispose()` when the view unmounts, or WebGL contexts and listeners leak.
10. **CDN scripts are not for production** — the Babylon team asks that `cdn.babylonjs.com` be used for learning and experiments only; bundle or self-host for a live site.
11. **When not to use** — to only display a model with orbit controls, the `@babylonjs/viewer` package is enough; for a 2D game or chart a 3D engine is overhead.


---
Source attribution: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/babylonjs/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2025 Terminal Skills

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/babylonjs/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Design
Roles: Game Developer, Frontend Developer, UX Designer
Specialties: Frontend, Backend, Mobile, Cross Platform
Tools: Babylonjs
Country applicability: Country not specified
Classification basis: Source category, role and specialization labels
Instruction SHA-256: 6ef02772d04f6fb6fa38fca34ab0f0ac0c9fb2efca8759d2d1742e8765a9cad8
