Tutorial·Build a model viewerJavaScript

Embed the viewer

Create the client, the ModelManager, the ObjectStateManager and a Viewer3d, initialise it, put it on the page and choose its settings.

The first lesson ends with an empty viewer on the page. Empty, because loading a model is the next lesson; but everything the later lessons need is already there. The rounds of this lesson start from nothing: your code creates every object itself, in the order of the four objects.

From a token to a viewer#

Five steps, each one line:

  • new BimWorksClientFactory(BIM_WORKS_ADDRESS) is made once per instance you talk to; createClientWithApiToken logs in and returns a client. Both are asynchronous where the network is involved, so the code awaits them. Keep the client for the life of the page; call client.close() when you leave.
  • new ModelManager(client) and new ObjectStateManager(modelManager) are plain constructors. The ObjectStateManager takes a settings object as second argument; {multiSelect: true}, Shift-click to extend the selection, is the default.
  • new Viewer3d(objectStateManager, loadProgressHandler, settings): the second argument reports load progress (lesson two), the third is the viewer settings. Both may be left out or null.
  • await viewer.initializeViewer() creates the WebGL context and starts the render loop. Do not call anything else on the viewer before it resolves, and call it once.
  • viewer.container is the element the viewer draws in. Append it wherever you want; the viewer follows the size of that element.
GoalStarts with · an empty page
Put an initialised 3D viewer on the page.
Ready to use: the SDK classes and the BIM_WORKS_* placeholders; document.body is the page the viewer goes on.
// A factory per BIM.works instance, a client per login
const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);

// Now the ModelManager, the ObjectStateManager and the Viewer3d
Running the code needs JavaScript in this page; the hints and the solution are below.
Hints
  1. new ModelManager(client) and new ObjectStateManager(modelManager) come first: the viewer needs the ObjectStateManager.
  2. new Viewer3d(objectStateManager) creates the viewer, and nothing is drawn until await viewer.initializeViewer() has resolved.
  3. The viewer draws in viewer.container: append it to document.body.
Show solution
const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);
const viewer = new Viewer3d(objectStateManager, null, {});
await viewer.initializeViewer();
document.body.appendChild(viewer.container);
Also accepted
const client = await new BimWorksClientFactory(BIM_WORKS_ADDRESS).createClientWithApiToken(BIM_WORKS_API_TOKEN);
const viewer = new Viewer3d(new ObjectStateManager(new ModelManager(client)));
await viewer.initializeViewer();
document.body.append(viewer.container);

Once the round has run, the viewer above is empty: there is nothing to draw yet. It is alive all the same. The default navigation mode is orbit: drag with the left button to orbit, with the middle button or Shift and the left button to pan, scroll to zoom. Ctrl and the left button places a section plane, Alt and the left button looks around, and the keyboard moves the camera (W/S/A/D, Q/Z up and down, the arrow keys). F fits the view to the selection, H hides the selected objects, C and D colour them, Space toggles the turntable animation. All bindings are listed in Default key bindings and can be replaced through the navigationModes setting.

Settings worth knowing#

The third constructor argument accepts a Viewer3dSettings object. Three settings matter from the start:

JavaScript#
const viewer = new Viewer3d(objectStateManager, null, {
	// Off by default; on, decoding and culling leave the main thread. Some bundlers
	// need configuration before workers load, which is why the default is off.
	technologyAllowed: {webGl2: true, webWorker: true},
	// Keep geometry in the browser's IndexedDB so a second load of the same version is fast
	cacheGeometry: true,
	// Show the built-in loading indicator (styled through the .viewer3d.loader class)
	showLoader: true
});

Web worker rendering is controlled by technologyAllowed.webWorker and nothing else. Workers run on any page; only sharing memory with them (technologyAllowed.sharedArrayBuffer) needs a page that is cross-origin isolated, and without it the viewer transfers buffers to the workers instead, when technologyAllowed.transferable allows that. The lessons on this page are the exception: their runtime switches workers off whenever the page is not cross-origin isolated, whatever you pass. The full settings type is on the Viewer3d reference.

Some things are switched after the viewer is initialised rather than in the settings. The reference grid is one: viewer.setGridEnabled(true) lays an infinite metric grid on the ground plane, which gives an empty scene something to orbit around and a model something to stand on.

GoalStarts with · an empty page
Keep the geometry of loaded models in the browser's cache, and show the reference grid in the empty viewer.
Ready to use: the SDK classes and the BIM_WORKS_* placeholders; document.body is the page the viewer goes on.
const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);
const viewer = new Viewer3d(objectStateManager, null, {});
await viewer.initializeViewer();
document.body.appendChild(viewer.container);
Running the code needs JavaScript in this page; the hints and the solution are below.
Hints
  1. The cache is a setting: it goes in the object that is the third argument of new Viewer3d.
  2. The setting is cacheGeometry.
  3. The grid is switched on after initializeViewer(): viewer.setGridEnabled(true).
Show solution
const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);
const viewer = new Viewer3d(objectStateManager, null, {cacheGeometry: true});
await viewer.initializeViewer();
document.body.appendChild(viewer.container);
viewer.setGridEnabled(true);
Also accepted
const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);
const viewer = new Viewer3d(objectStateManager, null, {
	technologyAllowed: {webGl2: true, webWorker: true},
	cacheGeometry: true,
	showLoader: true
});
await viewer.initializeViewer();
viewer.setGridEnabled(true);
document.body.appendChild(viewer.container);

Orbit and zoom over the grid: its spacing follows the zoom in steps of ten, from 10 cm to 10 m and beyond.

Your own page#

In the rounds the page around the code was given. On a page of your own the packages are imports, the client comes from a token your backend issues rather than from the API token (Show your users' models in your web app), and the page gives the viewer its size: the container is a block element with the class viewer3d and no intrinsic size. In the CSS tab below the body is a column flexbox that fills the window and .viewer3d takes the remaining space with flex: 1. Without a rule like that the viewer is zero pixels high and you see nothing. The viewer resizes itself when its container changes size, so a responsive layout needs no code.

// A factory per BIM.works instance, a client per login
const factory = new BimWorksClientFactory("https://bim.works");
const client = await factory.createClientWithApiToken("<your API token>");

// The ModelManager keeps track of which models are loaded
const modelManager = new ModelManager(client);

// The ObjectStateManager keeps the state of every object: visibility, colour, selection
const objectStateManager = new ObjectStateManager(modelManager);

// The viewer renders what the ObjectStateManager says. The second argument is an
// optional load progress handler, the third the optional settings object
const viewer = new Viewer3d(objectStateManager, null, {});

// Wait for the WebGL context before calling anything else on the viewer
await viewer.initializeViewer();

// The container is an element with the class "viewer3d"; the page gives it a size
document.body.appendChild(viewer.container);

// Nothing is loaded yet: show the reference grid so there is something to orbit around
viewer.setGridEnabled(true);
html, body {
	height: 100%;
	margin: 0;
}

body {
	display: flex;
	flex-direction: column;
}

/* The viewer's container has no size of its own: give it the remaining height */
.viewer3d {
	flex: 1;
	min-height: 0;
}

.viewer3d canvas {
	outline: none;
}
<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>BIM.works viewer</title>
	<link rel="stylesheet" href="viewer-embed.css">
</head>
<body>
	<script type="module">
		// With a bundler the bare specifiers resolve to the npm packages; without one an
		// import map points them at the single-file builds, see the JavaScript install guide
		import {BimWorksClientFactory} from "@bimworks/jssdk";
		import {ModelManager, ObjectStateManager} from "@bimworks/viewercommon";
		import {Viewer3d} from "@bimworks/viewer3d";

		const factory = new BimWorksClientFactory("https://bim.works");
		const client = await factory.createClientWithApiToken("<your API token>");

		const modelManager = new ModelManager(client);
		const objectStateManager = new ObjectStateManager(modelManager);

		const viewer = new Viewer3d(objectStateManager, null, {});
		await viewer.initializeViewer();
		document.body.appendChild(viewer.container);
		viewer.setGridEnabled(true);
	</script>
</body>
</html>

The Code tab is the program of the first two rounds. The HTML tab is the same program as a page of your own: the packages are imported, and the CSS sizes the viewer. With a bundler the imports resolve to the npm packages; without one an import map points them at the single-file builds (JavaScript and TypeScript).

Cleaning up#

A viewer holds GPU memory and a render loop. When your page removes it, call viewer.destroy(); when it is merely hidden, viewer.stop() and later viewer.start() save the work of rendering an invisible canvas. The rounds do the same between two runs: the viewer your code created is destroyed and its client closed before the next run starts.

You can now#

  • Create a client from an API token and the two managers a viewer needs.
  • Construct and initialise a Viewer3d and place it in your layout.
  • Pass the viewer its settings, and switch on the reference grid.
  • Navigate a scene with mouse and keyboard.

Next: Load a model.