> For the complete documentation index, see [llms.txt](https://docs.viverse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.viverse.com/polygon-streaming/polygon-streaming-javascript-sdk/babylon.js.md).

# Babylon.js

This document provides a guide for integrating Polygon Streaming web player for Babylon.js using the NPM package.

***

This is a guide to use Polygon Streaming web player for Babylon.js using the NPM package.

### **Getting Started - Sample Project** <a href="#getting-started-sample-project" id="getting-started-sample-project"></a>

You can download a sample project to get started [here](https://stream.viverse.com/assets/streamablemodel/2.4.6/babylonjs/PolygonStreaming-Babylonjs-Example.zip).

To run the sample project you first need to make sure you have [Node.js](https://nodejs.org/) installed. Then run the following in a terminal:

```bash
npm install
npm run dev
```

This will open a browser window and display the 3D model.

### **Code Explanation and Usage** <a href="#code-explanation-and-usage" id="code-explanation-and-usage"></a>

Import Babylon.js, glTF loader and the StreamController:

```javascript
import * as BABYLON from '@babylonjs/core/Legacy/legacy';
import '@babylonjs/loaders/glTF';
import { StreamController, loadWasmModule } from '@polygon-streaming/web-player-babylonjs';
```

Load Ammo.js. This is only required if you want to make use of the optional embedded collider in the model. Other physics plugins are not supported as Ammo.js is the only one that supports concave colliders. The Ammo.js physics plugin uses version 1 of the physics engine so you will need to add physics impostors to your meshes rather than physics aggregates or bodies.

```javascript
import ammoWasmJsUrl from './lib/ammo.wasm.js?url';
import ammoWasmWasmUrl from './lib/ammo.wasm.wasm?url';
import ammoJsUrl from './lib/ammo.js?url';

loadWasmModule('Ammo', ammoWasmJsUrl, ammoWasmWasmUrl, ammoJsUrl).then(ammoInstance => {
```

Instantiate the stream controller:

```javascript
const streamController = new StreamController(camera, engine, scene, cameraTarget, {
  cameraType: 'nonPlayer',
  triangleBudget: 5000000,
  mobileTriangleBudget: 3000000,
  minimumDistance: 0.01,
  distanceFactor: 1.1,
  maximumQuality: 15000,
  closeUpDistanceFactor: 5,
  closeUpDistance: 3,
  ammoInstance: ammoInstance
});
```

Add a streaming model, passing it a model URL and a TransformNode to act as a model parent:

```javascript
const modelParent = new BABYLON.TransformNode('Model parent', scene);
modelParent.position.set(0, 1, 0);
streamController.addModel('the URL of your model to be streamed (Asset ID)', modelParent, {
  qualityPriority: 1,
  initialTrianglePercent: 0.1,
  castShadows: true,
  receiveShadows: true,
  forceDoubleSided: false,
  useAlpha: true,
  environmentMap: null,
  hashCode: ''
});
```

Call the stream controller's update method in the render loop:

<pre class="language-javascript"><code class="lang-javascript"><strong> engine.runRenderLoop(function () {
</strong>  scene.render();
  streamController.update();
});
</code></pre>

Now you have everything setup to stream your 3D model inside your Babylon.js application.

### **Using Your Own 3D Model** <a href="#using-your-own-3d-model" id="using-your-own-3d-model"></a>

* Upload your 3D model to the online console: <https://stream.viverse.com/console>
* To get the model URL go to the models section of the console: <https://stream.viverse.com/console/models>\
  and click on the three dots next to your model and select "**Copy asset ID**".
* Paste this URL as the first parameter of streamController.addModel() method.

### **Stream Controller Parameters** <a href="#stream-controller-parameters" id="stream-controller-parameters"></a>

| Parameter               | Description                                                                       |
| ----------------------- | --------------------------------------------------------------------------------- |
| camera (required)       | The camera used in the scene.                                                     |
| engine (required)       | The engine used in the scene.                                                     |
| scene (required)        | The scene object.                                                                 |
| cameraTarget (required) | The camera target which is a Vector3.                                             |
| options (optional)      | You need to provide an object of options. The available options are listed below. |

#### Options

All options are optional.

| Option                | Description                                                                                                                                                                                             | Default Value |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| cameraType            | <p><strong>'nonPlayer':</strong> A camera that is not attached to a player e.g. a camera that orbits an object.</p><p><strong>'player':</strong> A camera that is attached to a player</p>              | 'nonPlayer'   |
| triangleBudget        | The maximum amount of triangles that you want to be in the scene at any single point.                                                                                                                   | 5000000       |
| mobileTriangleBudget  | The triangle budget used on a mobile device. If it is set to 0 it will use the non-mobile triangle budget.                                                                                              | 3000000       |
| minimumDistance       | The smallest possible distance to the camera.                                                                                                                                                           | 0.01          |
| distanceFactor        | Preference for nearby objects over objects further away. Values above one mean a preference for nearby objects. Values below one mean a preference for objects further away. One is neutral.            | 1.1           |
| maximumQuality        | Stops improving geometry that exceeds the maximum quality. This can be used to stop far away objects from showing more detail which can be wasteful. Setting it to 0 means there is no maximum quality. | 15000         |
| closeUpDistanceFactor | The distance factor used when close-up to an object. Should be higher than the standard distance factor.                                                                                                | 5             |
| closeUpDistance       | The distance where it starts using close-up distance factor. Set it to 0 to not use close-up distance factor.                                                                                           | 3             |
| iOSMemoryLimit        | The maximum amount of memory in MB that meshes and textures can consume on iOS devices to avoid the page crashing. Use 0 to let Polygon Streaming determine the limit or -1 for no limit.               | 0             |
| showLoadingModel      | Whether to show the animated loading model when loading streaming models.                                                                                                                               | True          |
| loadingModelUrl       | URL of a custom animated loading GLB file that overrides the default one.                                                                                                                               | Null          |
| ammoInstance          | The Ammo.js instance. Required if you want to make use of the embedded collider.                                                                                                                        | Null          |

### addModel Parameters

| Parameter              | Description                                                                            |
| ---------------------- | -------------------------------------------------------------------------------------- |
| URL (required)         | URL of the XRG model. If it doesn't end with .xrg it will append model.xrg to the URL. |
| modelParent (required) | The scene object that the streaming model will be attached to.                         |
| options (optional)     | You need to provide an object of options. The available options are listed below.      |

#### Options

All options are optional.

| Option                 | Description                                                                                                                                                                | Default Value |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| qualityPriority        | How much to prioritize the quality of this model relative to the quality of other models in the scene. This parameter does nothing if this is the only model in the scene. | 1             |
| initialTrianglePercent | Percentage of triangle budget to initialize the model with.                                                                                                                | 0.1           |
| castShadows            | Whether the model should cast shadows.                                                                                                                                     | true          |
| receiveShadows         | Whether the model should receive shadows.                                                                                                                                  | true          |
| forceDoubleSided       | Render the model double sided regardless of the setting in the model file.                                                                                                 | false         |
| useAlpha               | Whether to render semi-transparency in materials. You might turn this off to increase performance but all your materials will render opaque.                               | true          |
| environmentMap         | A cube map environment texture.                                                                                                                                            | null          |
| hashCode               | Hash code to validate streaming model                                                                                                                                      | ''            |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.viverse.com/polygon-streaming/polygon-streaming-javascript-sdk/babylon.js.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
