Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@cognite/3d-viewer

Package Overview
Dependencies
Maintainers
34
Versions
104
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cognite/3d-viewer

JavaScript viewer to visualize 3D models on Cognite's Data Platform

  • 3.9.0-beta.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
46
increased by12.2%
Maintainers
34
Weekly downloads
 
Created
Source

Cognite 3D Web Viewer

Visualize Cognite's 3D models in a web browser with WebGL.

Table of Contents

Install

$ npm install @cognite/3d-viewer

Cognite's Data Platform

To be able to use this 3D viewer you need to have access to Cognite's Data Platform (CDP). You can upload 3D models to our platform by looking at Cognite's API documentation. You can then use this viewer to visualize the 3D model in any web-based application.

Usage

import { Cognite3DViewer } from '@cognite/3d-viewer';
const viewer = new Cognite3DViewer();

Requirements

To be able to use this package you need the following polyfills:

Sample code

const viewer = new Cognite3DViewer();

// The viewer will render to a canvas.
// Add this canvas to your DOM
document.body.appendChild(viewer.canvas);

// At this point you will only see a black canvas.

// So let's add a 3D model:
const options = {
  projectName, // Project name (tenant) in Cognite's Data Platform
  modelId,     // 3D model id (has to be under the same project)
  revisionId,  // The model's revision id
};
viewer.addModel(options).then(function(model) {
  // Move camera to look at the model
  viewer.fitCameraToModel(model, 0);
});

Note: you may need additional styling to the canvas to make it fit your use-case. By default the canvas will have this style:

{
  width: 100%;
  height: 100%;
}
Add progress listeners
function onProgress(progress) {
  console.log(progress);
}

function onComplete() {
  console.log('Model loaded');
}

const options = {
  projectName,
  modelId,
  revisionId,
  onProgress, // optional
  onComplete, // optional
};
viewer.addModel(options)...
Make the viewer clickable
viewer.on('click', function(event) {
  const { offsetX, offsetY } = event;
  const intersection = viewer.getIntersectionFromPixel(offsetX, offsetY);
  if (intersection !== null) {
    const { nodeId, point, model } = intersection;
    console.log('User clicked at world coordinate', point);
    // highlight the object
    model.selectNode(nodeId);
    // make the camera zoom to the object
    const boundingBox = model.getBoundingBox(nodeId, null, model.matrix);
    viewer.fitCameraToBoundingBox(boundingBox, 2000); // 2 sec
  } else {
    // Clicked outside the 3D model
  }
});
Load saved camera position from the API

Assume you have the revision object from Cognite's Data Platform which you can get from this endpoint.

Here is a code snippet to use the saved camera position:

  const { target, position } = revision.camera;
  if (Array.isArray(target) && Array.isArray(position)) {
    // Create three.js objects
    const positionVector = new THREE.Vector3(...position);
    const targetVector = new THREE.Vector3(...target);
    // Apply transformation matrix
    positionVector.applyMatrix4(model.matrix);
    targetVector.applyMatrix4(model.matrix);
    // Set on viewer
    viewer.setCameraPosition(positionVector);
    viewer.setCameraTarget(targetVector);
  } else {
    viewer.fitCameraToModel(model, 0);
  }

API Reference

Table of Contents

Cognite3DViewer

Cognite3DViewer is the root class of a Cognite 3D viewer. It controls all aspects of the 3D viewer.

Parameters
  • options Object (optional, default {})
    • options.noBackground boolean -- Transparent background or not (optional, default false)
    • options.highlightColor boolean -- Highlight color of the selected objects (optional, default THREE.Color(0,0,1))
    • options.viewCube string? -- If defined then show a view cube and snap location of the view cube to this value. One of: 'topleft', 'topright', 'bottomleft', 'bottomright'.
Examples
const viewer = new Cognite3DViewer({
  noBackground: true,
});
isSupported

Check if the viewer supports the current browser

Examples
if (!viewer.isSupported()) {
  // create an error message to the user?
}
on

Add event listener to the viewer call off to remove an event listener

Parameters
  • type string -- Event type ('click' or 'cameraChange')
  • func function (event:PointerEvent) -- The callback function
Examples
const onClick = event => { ... };
viewer.on('click', onClick);
viewer.on('cameraChange', (position, target) => {
  console.log('Camera changed: ', position, target);
});
off

Remove event listener from the viewer call on to add an event listener

Parameters
  • type string -- Event type ('click' or 'cameraChange')
  • func function -- The callback function used in on
Examples
viewer.off('click', onClick);
addModel

Add a new 3D model to the viewer. call fitCameraToModel to see the model after the model has loaded

Parameters
  • options Object
    • options.projectName string -- The Cognite project the 3D model belongs to
    • options.modelId number -- The model's id
    • options.revisionId number -- The model's revision id
    • options.boundingBox THREE.Box3? -- Only load geometries inside this bounding box
    • options.onProgress function (progress: Object)? -- Callback for progress events
    • options.onComplete function? -- Callback when the model is fully loaded
Examples
const options = {
  projectName: 'COGNITE_TENANT_NAME',
  modelId:     'COGNITE_3D_MODEL_ID',
  revisionId:  'COGNITE_3D_REVISION_ID',
};
viewer.addModel(options).then(model => {
  viewer.fitCameraToModel(model, 0);
});

Returns Promise<Cognite3DModel>

addObject3D

Add a THREE.Object3D to the viewer

Parameters
  • object THREE.Object3D -- A three.js object
Examples
const sphere = new THREE.Mesh(new THREE.SphereBufferGeometry(), new MeshBasicMaterial());
viewer.addObject3D(sphere);
removeObject3D

Remove a THREE.Object3D from the viewer

Parameters
  • object THREE.Object3D -- A three.js object
Examples
const sphere = new THREE.Mesh(new THREE.SphereBufferGeometry(), new MeshBasicMaterial());
viewer.addObject3D(sphere);
viewer.removeObject3D(sphere);
setSlicePoint

Set slice point. Geometries will be hidden relative to this point based on slice planes specified by setSlicePlanes.

Parameters
  • slicePoint THREE.Vector3 -- Slice point
Examples
const slicePoint = new THREE.Vector3(1, 0, 0);
viewer.setSlicePoint(slicePoint);
setSlicePlanes

Set slice planes. Each component controls slicing for its direction. A value of +1 hides geometries in the positive direction relative to slicePoint. A value of -1 hides geometries in the negative direction relative to slicePoint. A value of 0 disables slicing for that plane.

Parameters
  • slicePlanes THREE.Vector3 -- Slice plane information
Examples
// Hide geometries with larger z-component than slicePoint. No slicing in x and y.
const slicePlanes = new THREE.Vector3(0, 0, 1);
viewer.setSlicePlanes(slicePlanes);
// Hide geometries with smaller x-component than slicePoint.
const slicePlanes = new THREE.Vector3(-1, 0, 0);
viewer.setSlicePlanes(slicePlanes);
// Hide geometries with larger x,y and z-component than slicePoint.
const slicePlanes = new THREE.Vector3(1, 1, 1);
viewer.setSlicePlanes(slicePlanes);
// Disable slicing.
const slicePlanes = new THREE.Vector3(0, 0, 0);
viewer.setSlicePlanes(slicePlanes);
getCameraPosition

Returns camera's position

Examples
const position = viewer.getCameraPosition();

Returns THREE.Vector3 Position in world space

getCameraTarget

Returns camera's target

Examples
const target = viewer.getCameraTarget();

Returns THREE.Vector3 Target in world space

setCameraPosition

Set camera's position

Parameters
  • position THREE.Vector3 -- Position in world space
Examples
// store position, target
const position = viewer.getCameraPosition();
const target = viewer.getCameraTarget();
// restore position, target
viewer.setCameraPosition(position);
viewer.setCameraTarget(target);
setCameraTarget

Set camera's target

Parameters
  • target THREE.Vector3 -- Target in world space
Examples
// store position, target
const position = viewer.getCameraPosition();
const target = viewer.getCameraTarget();
// restore position, target
viewer.setCameraPosition(position);
viewer.setCameraTarget(target);
fitCameraToBoundingBox

Move camera to a place where the content of a bounding box is visible to the camera.

Parameters
  • box THREE.Box3 -- The bounding box in world space
  • duration number? -- The duration of the animation moving the camera. Set this to 0 (zero) to disable animation.
  • radiusFactor number? -- The the ratio of the distance from camera to center of box and radius of the box (optional, default 4)
enableKeyboardNavigation

Enables camera navigation with the keyboard.

disableKeyboardNavigation

Disables camera navigation with the keyboard.

fitCameraToModel

Move camera to a place where the 3D model is visible. It uses the bounding box of the 3D model and calls fitCameraToBoundingBox

Parameters
worldToScreen

Convert a point in world space to its coordinates in the canvas. This can be used to place HTML objects near 3D objects on top of the 3D viewer.

Parameters
  • point THREE.Vector3 -- World space coordinate.
  • normalize bool? -- Optional. If true, coordinates are normalized into [0,1]. If false, the values are in the range [0, <canvas_size>). (optional, default false)
Examples
const boundingBoxCenter = new THREE.Vector3();
// Find center of bounding box in world space
model.getBoundingBox(nodeId, null, model.matrix).getCenter(boundingBoxCenter);
// Screen coordinates of that point
const screenCoordinates = viewer.worldToScreen(boundingBoxCenter);
const boundingBoxCenter = new THREE.Vector3();
// Find center of bounding box in world space
model.getBoundingBox(nodeId, null, model.matrix).getCenter(boundingBoxCenter);
// Screen coordinates of that point normalized in the range [0,1]
const screenCoordinates = viewer.worldToScreen(boundingBoxCenter, true);
const boundingBoxCenter = new THREE.Vector3();
// Find center of bounding box in world space
model.getBoundingBox(nodeId, null, model.matrix).getCenter(boundingBoxCenter);
// Screen coordinates of that point
const screenCoordinates = viewer.worldToScreen(boundingBoxCenter);
if (screenCoordinates == null) {
  // Object not visible on screen
} else {
  // Object is visible on screen
}

Returns (THREE.Vector2 | null) -- Returns 2D coordinates if the point is visible on screen, or null if object is outside screen.

getIntersectionFromPixel

Raycasting model(s) for finding where the ray intersects with the model.

Parameters
  • x number -- X coordinate in pixels (relative to the canvas)
  • y number -- Y coordinate in pixels (relative to the canvas)
  • cognite3DModel Cognite3DModel? -- If specified then only give results for this model
Examples
const intersection = viewer.getIntersectionFromPixel(50, 100); // x = 50 pixels from the left, y = 100 pixels from the top
if (intersection) // it was a hit
  console.log('You hit model ', intersection.model, ' at the node with id ', intersection.nodeId, ' at this exact point ', intersection.point);

Returns (Intersection | null) -- If there was an intersection then return the intersection object - otherwise it returns null if there was no intersections.

getScreenshot

Take screenshot from the current camera position.

Parameters
  • width number? -- Width of the final image. Default is current canvas size.
  • height number? -- Height of the final image. Default is current canvas size.

Returns Promise<string> A Blob URL to the image ('image/png')

Intersection

Type: object

Properties
  • model Cognite3DModel -- The node id
  • nodeId number -- The nodeId of the first intersected node
  • point THREE.Vector3 -- The 3D position of the intersection point in the world coordinate system

Cognite3DModel

Extends THREE.Object3D

Cognite3DModel is the class represeting a Cognite 3D model and its state

getSubtreeNodeIds

Get all node ids in a subtree where the root node has id 'nodeId'

Parameters
  • nodeId number -- The ID of the root node
  • subtreeSize number? -- If you already know the subtreeSize then this can help avoid an API call

Returns [number] List of nodeIds in the subtree

getBoundingBox

Get bounding box of a node

Parameters
  • nodeId number -- The node's id
  • box THREE.Box3? -- Optional target. Specify this to increase performance if the box can be reused.
  • matrix THREE.Matrix4? -- Optional transformation matrix. If not specified, identity matrix is used and bounding box will be in local space of the model.
Examples
const box = model.getBoundingBox(nodeId);
const reusableBox = new THREE.Box3();
const box = model.getBoundingBox(nodeId, reusableBox, model.matrix); // world space
// box === reusableBox
model.updateMatrixWorld();
const reusableBox = new THREE.Box3();
const matrix = model.matrixWorld;
const box = model.getBoundingBox(nodeId, reusableBox, matrix);
// box === reusableBox

Returns THREE.Box3

getNodeColor

Return the color on a node

Parameters
  • nodeId number -- The node's id

Returns {r: number, g: number, b: number}

setNodeColor

Set the color on a node

Parameters
  • nodeId number -- The node's id
  • r number -- The red color value (0-255)
  • g number -- The green color value (0-255)
  • b number -- The blue color value (0-255)
resetNodeColor

Reset a node's color to its original color

Parameters
  • nodeId number -- The node's id
selectNode

Mark a node as selected. Only visible nodes can be selected.

Parameters
  • nodeId number -- The node's id
deselectNode

Mark a node as deselected.

Parameters
  • nodeId number -- The node's id
deselectAllNodes

Mark all selected nodes as deselected

showNode

Show a node

Parameters
  • nodeId number -- The node's id
showAllNodes

Show all nodes

hideAllNodes

Hide all nodes

Parameters
  • ghost bool -- Hide with ghost effect (optional, default false)
hideNode

Hide a node

Parameters
  • nodeId number -- The node's id
  • ghost bool -- Hide with ghost effect (optional, default false)

getNode

Get a single node.

Parameters
  • projectName string -- The Cognite project that the 3D model belongs to
  • modelId number -- The ID of the 3D model
  • revisionId number -- The ID of the 3D model revision
  • nodeId number -- The ID of the node to retrieve.

Returns Promise<Node>

Node

Type: object

Properties
  • id number -- The node id
  • treeIndex number -- The tree index
  • parentId number -- The node id of the parent
  • name number -- The name of the node
  • subtreeSize number -- Size of the subtree where this node is the root. This number included the node it self.
  • depth number -- The depth level from the overall root node (0-indexed).
  • boundingBox THREE.Box3 -- The bounding box for the subtree where this node is the root.

AssetMapping

Type: object

Properties
  • nodeId number -- The node id for the mapping
  • assetId number -- The mapped asset id
  • subtreeSize number -- Size of the subtree with the node with id = nodeId as root

getAssetMappingsFromNodeId

Get the assets associated with a given node.

Parameters
  • projectName string -- The Cognite project that the 3D model belongs to
  • modelId number -- The ID of the 3D model
  • revisionId number -- The ID of the 3D model revision
  • nodeId number -- The ID of the node to get the associated assets of

Returns Promise<[AssetMapping]>

getAssetMappingsFromAssetId

Get the node ids associated with a given asset.

Parameters
  • projectName string -- The Cognite project that the 3D model belongs to
  • modelId number -- The ID of the 3D model
  • revisionId number -- The ID of the 3D model revision
  • assetId number -- The ID of the asset to get the associated nodes of

Returns Promise<[AssetMapping]>

getSectorsFromBoundingBox

Get sectors intesecting a bounding box.

Parameters
  • projectName string -- The Cognite project that the 3D model belongs to
  • modelId number -- The ID of the 3D model
  • revisionId number -- The ID of the 3D model revision
  • boundingBox THREE.Box3 -- The bounding box

Returns Promise<[Sector]> A list of sectors intersecting the bounding box

Sector

Type: object

Properties
  • id number -- The sector id
  • parentId number? -- The id of the parent sector. Undefined if it is the root sector.
  • path number -- A string representing the path from the root sector to this sector. Describes how to traverse the sector tree to get to this sector.
  • depth number -- The depth level from the root sector (0-indexed).
  • threedFileId number -- File id for the file describing geometries attached to the sector. Use /3d/files to retrieve it.
  • boundingBox THREE.Box3 -- The bounding box of which the sector covers.

Cognite3DModelLoader

Cognite3DModelLoader is the class used to load a Cognite 3D model to Three.js.

load
Parameters
  • options Object? (optional, default {})
    • options.projectName string -- The Cognite project the 3D model belongs to
    • options.modelId number -- The model's id
    • options.revisionId number -- The model's revision id
    • options.boundingBox THREE.Box3? -- Only load geometries inside this bounding box
    • options.onProgress function (progress: Object)? -- Callback for progress events
    • options.onComplete function? -- Callback when the model is fully loaded
Examples
const options = {
  projectName: 'COGNITE_TENANT_NAME',
  modelId:     'COGNITE_3D_MODEL_ID',
  revisionId:  'COGNITE_3D_REVISION_ID',
};
Cognite3DModelLoader.load(options).then(model => {
  // if we have a THREE.Scene then:
  scene.add(model);
});

Returns Promise<Cognite3DModel>

Support

For support contact mailto:support-3d@cognite.com

Keywords

FAQs

Package last updated on 04 Feb 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc