threebox

repository·master·Indexed 20 days ago

https://github.com/jscastro76/threebox

A Three.js plugin for Mapbox GL JS (version 2.2.7) that uses the CustomLayerInterface to render 3D models, geometries, and animations. It provides tools for managing objects in lnglat coordinates, synchronizing cameras, and implementing interactions such as selecting, dragging, and rotating 3D objects. Features include support for OBJ/MTL, GLTF/GLB, FBX, and DAE formats, realistic sunlight and shadows, atmospheric sky, and performance optimizations via multi-layer support.

Tokens
25.1K
Snippets
68
Records
105
Agent score
72%

What's inside threebox

  1. Optimize performance with multi-layer support

    master

    Creating many individual 3D layers in Mapbox is resource-intensive because each layer is rendered separately. To optimize performance, use the multiLayer parameter.

    When multiLayer is enabled, Threebox creates an embedded internal layer that manages rendering with a single call to tb.update. This ensures the Mapbox render loop only calls the Three.js render once, significantly saving resources.

    You can also manage visibility for these layers using tb.setLayoutZoomRange to hide/show layers based on the current zoom level.

  2. Understand Static vs Dynamic objects in Threebox

    master

    Threebox objects are categorized into two types based on how they interact with the map and coordinates:

    • Static objects: Used for background or geographical features that do not move or change once placed. They use complex internal geometry expressed primarily in lnglat coordinates.
    • Dynamic objects: Objects that can move around the map, positioned by a single lnglat point. Their internal geometries are produced in local scene units (e.g., via external .obj files or convenience methods like tb.extrusion).
  3. Enable interaction and selection for 3D objects

    master

    You can enable built-in interaction modes for 3D objects using specific methods on the Threebox instance. These allow users to select, drag, rotate, and view tooltips for objects.

    Key interaction methods:

    • enableSelectingObjects: Enables raycasting and selection. Objects can be selected and unselected.
    • enableDraggingObjects: Enables dragging. Once an object is selected, use the [Shift] key for translation and [Ctrl] for altitude.
    • enableRotatingObjects: Enables rotation on the vertical axis. Once an object is selected, use the [Alt] key.
    • enableTooltips: Enables default labels/tooltips at the object's altitude.
  4. Load and interact with 3D models

    master

    Threebox supports loading 3D models in formats such as OBJ/MTL, GLTF/GLB, FBX, and DAE.

    Loading a Model

    Use tb.loadObj(options, callback) to load a model. The options object should include:

    • obj: Path to the file.
    • type: Format (e.g., 'gltf').
    • scale: Scale factor.
    • units: Coordinate units (e.g., 'meters').
    • rotation: Initial rotation object { x, y, z }.

    Interactions

    If enableSelectingObjects, enableDraggingObjects, and enableRotatingObjects are set to true in the Threebox instance, you can interact with models:

    • Drag (Position): Select the object, hold SHIFT, and move the mouse to change Lnglat. Hold CTRL to change altitude.
    • Rotate: Select the object, hold ALT, and move the mouse. Rotation occurs around the object's defined center.
    • Tooltips: If enableTooltips is true, tooltips will appear on hover.
    var options = {
    	obj: '/3D/soldier/soldier.glb',
    	type: 'gltf',
    	scale: 1,
    	units: 'meters',
    	rotation: { x: 90, y: 0, z: 0 } //default rotation
    }
    
    tb.loadObj(options, function (model) {
    		soldier = model.setCoords(origin);
    		b.add(soldier);
    })
  5. Run Threebox examples locally

    master

    To run the provided Threebox examples, you must create a config.js file in the same directory as the example HTML file. This file must contain your Mapbox GL JS access token following the format of the config_template.js provided in the repository.

    Example structure for config.js:

    window.mapgl = { access_token: 'YOUR_MAPBOX_ACCESS_TOKEN' };
  6. Configure sunlight, shadows, and sky

    master

    Threebox provides built-in support for realistic lighting and atmospheric effects:

    • Atmospheric Sky: Add a sky layer by passing sky: true in the configuration parameters.
    • Real Sunlight: Enable sunlight that follows real-world positions using realSunlight.
    • Shadows:
      • For 3D objects: Enable via the castShadow property.
      • For Mapbox fill-extrusions: Use tb.setBuildingShadows.
    • Sunlight Management:
      • setSunlight: Set the map lights based on a specific time/date.
      • tb.getSunTimes: Retrieve sun times to automatically change styles (e.g., from sunset to sunrise).
  7. Optimize performance when adding many identical objects

    master

    To maintain performance when rendering many identical objects, use obj.duplicate().

    Important Note: If your object contains sub-objects that are not part of the obj.children collection, those sub-objects must also be cloned manually to ensure they are properly duplicated.

    By default, tb.loadObj handles duplication for you.

  8. Enable interaction and selection for Mapbox features

    master

    To enable interaction with Mapbox features (like fill-extrusion layers) rather than just Threebox Object3D entities, use:

    • enableSelectingFeatures: Enables built-in raycasting and selection for Mapbox features.
    • enableTooltips: Enables default labels on altitude for features (e.g., for fill-extrusions).

    You can manage selection events for features using the Mapbox event handler: map.on('SelectedFeatureChange', ...).

  9. Initialize Threebox in a Mapbox GL Custom Layer

    master

    To use Threebox, you must add a custom layer to your Mapbox GL map. The onAdd function initializes the Threebox instance, and the render function calls tb.update() to ensure the 3D scene renders correctly.

    map.addLayer({
    	id: 'custom_layer',
    	type: 'custom',
    	renderingMode: '3d',
    	onAdd: function (map, gl) {
    
    		window.tb = new Threebox(
    			map,
    			gl,
    			{
    				defaultLights: true,
    				enableSelectingFeatures: true,
    				enableSelectingObjects: true,
    				enableDraggingObjects: true,
    				enableRotatingObjects: true,
    				enableTooltips: true
    			}
    		);
    
    		// Load objects here...
    	},
    	render: function (gl, matrix) {
    		tb.update();
    	}
    });
  10. Maintain fixed object scale during zoom

    master
    To prevent a 3D object from changing its visual size as the user zooms, you can implement a fixed scale at a specific zoom level. This ensures the object preserves its visual size even when the zoom level is lower than the target fixed zoom value.
  11. Use Threebox via local bundle or CDN

    master

    You can include Threebox in your project using several methods:

    Local Bundle

    Download dist/threebox.js or dist/threebox.min.js and include it in a <script> tag. If you want to use predefined styles, include the CSS file:

    <script src="../dist/threebox.js" type="text/javascript"></script>
    <link href="./css/threebox.css" rel="stylesheet" />

    Public CDNs

    jsdelivr

    Requires a specific version in the URL:

    <script src="https://cdn.jsdelivr.net/gh/jscastro76/threebox@v.2.2.1/dist/threebox.min.js" type="text/javascript"></script>
    <link href="https://cdn.jsdelivr.net/gh/jscastro76/threebox@v.2.1.1/dist/threebox.css" rel="stylesheet" />

    unpkg

    Omitting the version downloads the latest published version:

    <script src="https://unpkg.com/threebox-plugin/dist/threebox.min.js" type="text/javascript"></script>
    <link href="https://unpkg.com/threebox-plugin/dist/threebox.css" rel="stylesheet" />

    To use a specific version (e.g., v2.2.1):

    <script src="https://unpkg.com/threebox-plugin@2.2.1/dist/threebox.min.js" type="text/javascript"></script>
    <link href="https://unpkg.com/threebox-plugin@2.2.1/dist/threebox.css" rel="stylesheet" />