NAV Navigation
JavaScript

Viewer 3D API v1.0

Getting started

The Viewer 3D API allows developers to embed the bimsync viewer in their applications.

Dependencies

The viewer requires jQuery 1.x to run.

Initialize

The viewer can either be automatically initialized by using the DOM data API or manually initialized in JavaScript.

DOM Data API

Add viewer framework

<script type="text/javascript" src="https://api.bimsync.com/1.0/js/viewer.js"></script>

Create a viewer instance

<div data-viewer="webgl" data-url="https://api.bimsync.com/1.0/viewer/access?token=897..."></div>
  1. Create a viewer access token by using the POST /viewer/access resources in the bimsync API.

  2. Add the viewer framework to you application:

  3. Create a viewer instance. The data attribute data-viewer must have the value webgl. The data attribute data-url must be the url field from a viewer access token.

To enable the viewer UI plugin, add the data attribute, data-ui, to the viewer element. See the viewer UI plugin documentation for more info.

JavaScript

Create DIV element

<div id="viewer-container"></div>

Follow the pattern from below to initialize

<script type="text/javascript" src="https://api.bimsync.com/1.0/js/viewer.js"></script>
<script type="text/javascript">
    // Load the Viewer API.
    bimsync.load();
    
    // Set a callback to run when the Viewer API is loaded
    bimsync.setOnLoadCallback(createViewer);
    
    // Callback that loads a viewer access token URL
    function createViewer() {
        $('#viewer-container').viewer('loadUrl', 'https://api.bimsync.com/1.0/viewer/access?token=897...');
    }
</script>
  1. Create a viewer access token by using the POST /viewer/access resources in the bimsync API.

  2. Create a DIV element which will contain the viewer.

To enable the viewer UI plugin, a parameter could be passed to the bimsync.load() method. See the viewer UI plugin documentation for more info.

Options

    var options = {
        defaultColor: String or Number,     // Any valid CSS color, default: '#101010'
        selectedColor: String or Number,    // Any valid CSS color, default: '#a7f555'
        translucentOpacity: Number,         // Default: 0.05
        fieldOfView: Number,                // Number in degrees, default: 60
        enableTouch: Boolean,               // Default: false
        enableClippingPlaneWidget: Boolean  // Default: false
    }

Setting options when using JavaScript initialization:

    $('#viewer-container').viewer({
        defaultColor: 'red',
        selectedColor: 'blue',
        translucentOpacity: 0.05,
        enableTouch: true,
        enableClippingPlaneWidget: true
    });
    $('#viewer-container').viewer('loadUrl', 'https://api.bimsync.com/1.0/viewer/access?token=897...');

Setting options when using data attribute initialization:

    <div data-viewer="webgl" data-url="https://api.bimsync.com/1.0/viewer/access?token=897..."
        data-default-color="#22ff22" data-enable-touch="true" data-translucent-opacity="0.1"></div>

All options can be set using data attributes on the viewer element, or passed as an object when initializing with JavaScript.

defaultColor

The default color for objects that has no color specified.

selectedColor

The color of selected objects.

translucentOpacity

The opacity of translucent objects.

fieldOfView

The camera field of view.

enableTouch

Enables touch support.

enableClippingPlaneWidget

Enables a clipping plane widget that makes viewing and selecting clipping planes easier. The widget will only appear when there exists at least one clipping plane.

Methods

All methods are invoked by calling the method viewer on the result of a jQuery/$ function call. The first argument to the viewer method must be the method name.

Chaining and callbacks

In bimsync Viewer API v1.0 all methods are chainable. This design decision causes the API to be rather callback heavy. A pattern being used is that the same method can be used to both set and get a value from the viewer. The value will then be returned using a callback function. When calling callbacks, the this value will be set to the viewer's DOM element.

Example

Given a viewer initialized using the DOM API:

    <div class="viewer" data-viewer="webgl" data-url="..."></div>

The following chained method calls will isolate object id '1':

    $('.viewer').viewer('hideAll').viewer('show', '1')

The following takes a screenshot of an isolated object and resets the view:

    $('.viewer').viewer('hideAll')
                .viewer('show', '1')
                .viewer('screenshot', function(screenshot) {
        $('img').attr('src', screenshot);
        $(this).viewer('showAll');
    });

show

Makes a hidden or translucent object visible.

Parameters:

showAll

Makes all objects visible.

Parameters: None

hide

Makes object hidden.

Parameters:

hideAll

Hides all objects.

Parameters: None

translucent

Makes object translucent.

Parameters:

translucentAll

Make all objects translucent.

Parameters: None

opaque

Makes object opaque.

Parameters:

opaqueAll

Make all objects opaque.

Parameters: None

select

Marks object as selected.

Parameters:

deselect

Removes object from selected set.

Parameters:

deselectAll

Clears selected set.

Parameters: None

showModel

Makes a hidden model visible.

Parameters:

hideModel

Hides a model.

Parameters:

loadUrl

Example:

    $('.viewer').viewer('loadUrl', 'https://api.bimsync.com/1.0/viewer/access?token=8975b4a3149a49ba8bcc40f4ababc0d1');

Load the contents of a viewer access token.

Parameters:

unloadModel

Unloads a model.

Parameters:

transformModel

Example:


    // Move the model along the x-axis, scale it in y-direction, rotate it around the z-axis
    $('.viewer').viewer('transformModel', 'dabc6dfce6e849bfada976d9fa9e294a', {
        position: {x: 1, y: 0, z: 0},
        scale: {x: 1, y: 1.5, z: 1},
        rotation: {x: 0, y: 0, z: 1, angle: 1.57}
    });

Moves, scales and rotates a model.

Parameters:

transitionSettings

Example:

    $('.viewer').viewer('transitionSettings', {
      duration: 500,
      easing: 'QuadraticInOut'
    })

Set camera transition settings. Controls camera transition animations triggered by calls to lookAt, lookAtBoundingBox or viewpoint.

The viewer is initialized with the following transition settings:

{ duration: 0, easing: 'LinearNone' }

Parameters:

Settings fields:

Easing functions:

The following easing functions are available:

viewpoint

Example:

    // Get current viewpoint
    $('.viewer').viewer('viewpoint', null, function(viewpoint) {
        console.log(viewpoint);
    });

    // Set predefined viewpoint - available 'home', 'top', 'left', 'right', 'front', 'back'
    $('.viewer').viewer('viewpoint', 'top');

    // Set perspective viewpoint
    $('.viewer').viewer('viewpoint', {
        direction: {
            x: 0,
            y: -1,
            z: 0
        },
        location: {
            x: 0,
            y: 100,
            z: 0,
        },
        up: {
            x: 0,
            y: 0,
            z: 1
        },
        fov: 50,
        type: 'perspective'
    });
    
    // Set orthogonal viewpoint
    $('.viewer').viewer('viewpoint', {
        direction: {
            x: 0,
            y: 0,
            z: -1
        },
        location: {
            x: 7
            y: 2.5
            z: 17
        },
        up: {
            x: 0,
            y: 0,
            z: 1
        },
        viewToWorldScale: 14,
        type: 'orthogonal'
    });

Get and set current viewpoint.

Parameters:

clippingPlanes

Example:

    var clippingPlanes = [
      {
        location: {
          x: 6.9000000953674245,
          y: 2.4132123330870963,
          z: 4.384152126303485
        },
        direction: {
          x: 0,
          y: 0,
          z: 1
        }
      },
      {
        location: {
          x: 6.9000000953674245,
          y: 2.4132123333570963,
          z: 1.6841521263034842
        },
        direction: {
          x: 0,
          y: 0,
          z: -1
        }
      }
    ];
    
    // Set
    $('.viewer').viewer('clippingPlanes', clippingPlanes);
    or
    $('.viewer').bind('viewer.contextmenu', function(event, selected, intersects) {
        $('.viewer').viewer('clippingPlanes', [ { location: intersects.point, direction: intersects.normal } ]);
    });
    
    NOTE: To select a clipping plane you have to hold down the SHIFT key while clicking on the plane. When the plane is selected you should be able to move it using the mouse.
    
    // Get
    $('.viewer').viewer('clippingPlanes', null, function(clippingPlanes) {
        console.log(clippingPlanes);
    });

Set or get clipping planes. The viewer can display up to six clipping planes.

Parameters:

clippingPlaneWidgetViewport

Example:

    $('.viewer').viewer('clippingPlaneWidgetViewport', {x: 0, y: 300, width: 150, height: 150});

Set the position and size og the clipping plane widget. Note that the enableClippingPlaneWidget option have to be set to true to get this to work.

Parameters:

Viewport fields:

images

Example:

    // Set image
    $('.viewer').viewer('images', [{
      url: 'http://example.com/example.jpg'),
      size: {width: 200, height: 100},
      transform: {
        position: {x: 100, y: 50, z: 0},
        rotation: {x: 0, y: 0, z: 1, angle: Math.PI / 2}
      }
    }]);

Set or get images. Images are displayed on a plane defined by a size and transformation. If not transformed, the image will be placed with its center in the origin (0, 0, 0) facing up (position Z-axis). Supported formats are PNG, JPG, GIF and DDS. Size and transform position is defined in meters.

Parameters:

section

Example

    // Create clipping planes above and below objects
    $('.viewer').viewer('section', [ '1', '2' ], ['top', 'bottom']);

Create clipping planes relative to the axis aligned bounding box of the provide objects.

Parameters:

screenshot

Example:

    $('.viewer').viewer('screenshot', function(screenshot) {
        $('img').attr('src', screenshot);
    });

Create a screenshot as base64 encoded PNG.

Parameters:

color

Example

    // RGB
    $('.viewer').viewer('color', '#FF0000', [ '1', '2' ]);

    // RGBA
    $('.viewer').viewer('color', '#FF0000A0', [ '1', '2' ]);

    // Get colors
    $('.viewer').viewer('color', null, [ '1', '2' ], function(colors) {
        // 'colors' will contain
        // {
        //   1: {
        //     color: {r: 1.0, g: 0.0, b: 0.0},
        //     opacity: 1.0
        //     style: '#FF0000FF
        //   },
        //   2: { ...
        //   }
        // }
    });

Set or get object color.

Parameters:

resetColors

Resets colors to the defaults.

Parameters: None

lookAt

Example:


    // Use current camera direction
    $('.viewer').viewer('lookAt', [ '18439659', '18439683', '18439751', '18439776' ]);

    // Use predefined direction - available 'home', 'top', 'left', 'right', 'front', 'back'
    $('.viewer').viewer('lookAt', [ '18439659', '18439683', '18439751', '18439776' ], 'top');

Move given objects into view. An optional predefined camera direction can be provided.

Parameters:

boundingBox

Example:

    $('.viewer').viewer('boundingBox', [ '18439659', '18439683', '18439751', '18439776' ], function(boundingbox) {
      console.log(boundingbox);
    });

Calculate the axis aligned bounding box of one or more objects. If the id is null the bounding box of all objects is returned. The bounding box will have the shape

{
  min: {
    x: ...
    y: ...
    z: ...
  },
  max: {
    x: ...
    y: ...
    z: ...
  }
}

Parameters:

lookAtBoundingBox

Example:

    // Get boundingbox of given objects
    $('.viewer').viewer('boundingBox', [ '18439659', '18439683', '18439751', '18439776' ], function(boundingBox) {
        // Use current camera direction
        $('.viewer').viewer('lookAtBoundingBox', boundingBox);

        // Use predefined direction - available 'home', 'top', 'left', 'right', 'front', 'back'
        $('.viewer').viewer('lookAtBoundingBox', boundingBox, 'top');
    });
    
    // Get model bounding box
    $('.viewer').viewer('modelInfo', 'ce168045...', function(modelInfos) {
        $('.viewer').viewer('lookAtBoundingBox', modelInfos[0].boundingBox);
    });

Move bounding box into view. An optional predefined camera direction can be provided.

Parameters:

each

Calls a function for each object.

Parameters:

For all objects in viewer:

All objects of a specific model:

eachSelected

Example:

    $('.viewer').viewer('eachSelected', function(id) {
        $(this).viewer('hide', id);
    });

Calls a function for each selected object.

Parameters:

objectInfo

Example:

    $('.viewer').viewer('objectInfo', ['18439659', 'UNKNOWN_ID'], function(info) {
        console.log(info[0]);
        // info[1] will be null
    });

Returns information for one or more objects. Each info object contains the following properties:

Querying information for unknown ids will result in the info object being null. If id is not provided, the method will return info for all objects.

Parameters:

modelInfo

Example:

    $('.viewer').viewer('modelInfo', function(modelInfos) {
        console.log(modelInfos);
        // This will print model info for all loaded models
    });

    $('.viewer').viewer('modelInfo', 'ce168045...', function(modelInfos) {
        console.log(modelInfos[0]);
        // This will print model info for the given model id

        $('.viewer').viewer('lookAtBoundingBox', modelInfos[0].boundingBox);
    });

Returns an array of model info objects. For now the modelId and the model boundingBox are returned.

Note that this method only returns information about loaded models.

Parameters:

keyDown

Example:

    // When the user press the 'w' key, move forward
    $('.viewer').viewer('keyDown', {moveForward: true});

    // The camera will now move straight ahead until
    $('.viewer').viewer('keyDown', {moveForward: false});

Move camera using one or more of the the following keywords:

Parameters:

resetKeyDown

Example:

If the current browser window loose focus, keyup events may not trigger.
To avoid moving after loosing focus on the window, trigger:

    $(window).bind('blur', function() {
        $(viewer).viewer('resetKeyDown');
    });

Mark all keys as being released.

Parameters: None

Example:

    $('.viewer').viewer('navigate', { moveForward: 1.5, rotateRight: 0.5});
    
    // Another example:
    var randomMovement = function() {
        var sin = Math.sin(Math.random() * Math.PI);
        var cos = Math.cos(Math.random() * Math.PI);
        $('.viewer').viewer('navigate', {moveForward: sin, rotateRight: cos});
        setTimeout(randomMovement, 200);
    }
    randomMovement();

Navigate in one of the directions listed in the keydown method.

Parameters:

stopNavigation

Example:

    // Start movement
    $('.viewer').viewer('navigate', { moveForward: 1.5, rotateRight: 0.5});
    
    // Stop movement
    $('.viewer').viewer('stopNavigation');

Stops the movement started by the navigate method.

Parameters: None

Sets the current navigation mode.

Parameters:

Predefined modes

The following predefined modes are available.

Custom modes

The navigation mode can be customized by specifying an object containing a list of event/action pairs per device. The available devices are 'mouse', 'touch' and 'keyboard'. Passing an empty object ({}) will disable all navigation.

Download example

The source code for the definition of the predefined modes is available for download here.

Download example

Event matching

Example

Given the following definition:
    'mouse': [
      {
        'event': 'click',
        'action': 'click',
      },
      {
        'event': 'click',
        'action': 'select',
        'filter': {
          'button': 0
        }
      }
    ]
If a user clicks in the viewer with the left button (button 0) both event/action pairs will be executed. Clicking with the right button (button 2) will only execute the first.

When an event is triggered by a device, all event/action pairs are evaluated to find the actions to be executed. The event name must match the triggered event and if filter is specified, all filters must match the event state.

Filters

The following filters are available:

Event execution

    'mouse': [
      {
        'event': 'click',
        'action': 'click',
        'filter': {
          'button': 0
        }
      },
      {
        'event': 'click',
        'action': 'select',
        'filter': {
          'button': 0
        }
      }
    ]

All actions that match an event are executed in the order specified in the device list. If an action is cancelled (e.g. a viewer.click event handler returns false) when executed, the rest of the matching actions will not be executed.

In the example below, the click action will be run before the select action. Cancelling the viewer.click event will stop the select action from executing.

Action parameters

Each event/action pair can optionally contain the following action parameters passed as properties on the event/action pair object.

Mouse events

Touch events

Keyboard events

Actions

walkSpeed

Example:

    $('.viewer').viewer('walkSpeed', 3.0);

Sets the walk speed used when navigating with the keyboard controls.

Parameters:

elevationSpeed

Example:

    $('.viewer').viewer('elevationSpeed', 1.0);

Sets the vertical movement speed used when navigating with the keyboard controls.

Parameters:

rotationSpeed

Example:

    $('.viewer').viewer('rotationSpeed', 50.0);

Sets the rotation speed (in degrees/sec) used when navigating with the keyboard controls.

Parameters:

fieldOfView

Example:

    $('.viewer').viewer('fieldOfView', 50.0);

Sets the camera field of view angle in degrees.

Parameters:

Events

    $('.viewer').bind('viewer.select', function(event, selected) {
        console.log(selected);
    });

The events created by the viewer are custom jQuery events. Attach a handler to an event with jQuery.bind.

viewer.load

Triggered when viewer and content is completely loaded.

Callback parameters

None

viewer.error

Triggered when something goes wrong.

type String

Error types:

Callback parameters

viewer.select

Triggered when the set of selected objects is changed by user events (e.g. mouse clicks).

Callback Parameters

selected Array Set of selected object IDs. If no objects are selected the array is empty.

viewer.viewpoint

Triggered when the current viewpoint is changed by user events (e.g. mouse drags).

Callback Parameters

viewpoint Object A viewpoint

viewer.click

Triggered when the user clicks inside the viewer. Returning false from the event handler will cancel the default viewer behavior.

Callback Parameters

id String Id of the object below the cursor. Undefined if no objects are below the cursors.
intersects Object Position of the object below the cursor, and a direction vector perpendicular to the surface of the object. Undefined if no objects are below the cursors.

viewer.doubleclick

Triggered when the user doubleclick clicks inside the viewer. Returning false from the event handler will cancel the default viewer behavior.

Callback Parameters

id String Id of the object below the cursor. Undefined if no objects are below the cursors.
intersects Object Position of the object below the cursor, and a direction vector perpendicular to the surface of the object. Undefined if no objects are below the cursors.

viewer.contextmenu

Triggered when the user summons the context menu (e.g. by right-clicking).

Callback Parameters

id String Id of the object below the cursor. Undefined if no objects are below the cursors.
intersects Object Position of the object below the cursor, and a direction vector perpendicular to the surface of the object. Undefined if no objects are below the cursors.