Lab4 Forge API Web Intro JS

(This is a continuation from the previous post: Lab3 “Forge API Web Intro”)

Now that we have a model uploaded to our bucket and translated for viewing, the final piece of functionality that we want to add is an ability to view the uploaded model in a html page. To do this, Forge API provides a client side JavaScript API.

In this lab, we make a basic viewer, which is based on Basic Viewer Step-by-Step Tutorial and is slightly modified to put it in the context of our lab and make it easier to built on top of what we have built in the previous lab.

JavaScript API Layer

There are three JavaScript (.js) files that we are going to use:

  • three.min.js
  • viewer3D.min.js
  • viewerBasic.js

Let’s take a look at them one by one.

viewer3D.min.js and three.min.js 

The first two are the libraries that Autodesk provides. You can find the latest from the hosted location:

or

The first set of xxx.min.js is the version without any formatting, while the second, tree.js and viewer3D.js, are human-eyes friendly version.

To use them with our application, we include them in HTML page. e.g.,

here we included the style sheet css file for the viewer.

Typically, we use these files as is. Since it is open source, it is also possible to modify for your needs. You can download from the location mentioned above.

As of this writing, the latest version of the viewer is 3.3.5. For production usage, it is recommended to include the version number so that it won’t be affected by changes: e.g.,

… /viewer3D.min.js?v=3.3.*

If you omit the version number, it will pick up the latest.

viewerBasic.js

This is the code based from the Basic Viewer Tutorial, which  I have re-structured as an “utility” function for our minimum project. It assumes for a display of a single 3D model, such as Revit file, with the basic UI in the viewer. The code looks like below:

viewerBasic.js
  1. function viewByTokenAndUrn(token, urn, divId) {
  2.     var viewer;
  3.     var viewerDivId;
  4.     //==================================================
  5.     // Various callback functions
  6.     //==================================================
  7.     /**
  8.     * Autodesk.Viewing.Document.load() success callback.
  9.     * Proceeds with model initialization.
  10.     */
  11.     function onDocumentLoadSuccess(doc) {
  12.         // A document contains references to 3D and 2D viewables.
  13.         var viewables = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), { ‘type’: ‘geometry’ }, true);
  14.         if (viewables.length === 0) {
  15.             console.error(‘Document contains no viewables.’);
  16.             return;
  17.         }
  18.         // Choose any of the avialble viewables
  19.         var initialViewable = viewables[0];
  20.         var svfUrl = doc.getViewablePath(initialViewable);
  21.         var modelOptions = {
  22.             sharedPropertyDbPath: doc.getPropertyDbPath()
  23.         };
  24.         //var viewerDiv = document.getElementById(‘MyViewerDiv’);
  25.         var viewerDiv = document.getElementById(viewerDivId);
  26.         viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);
  27.         viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
  28.     }
  29.     /**
  30.     * Autodesk.Viewing.Document.load() failuire callback.
  31.     */
  32.     function onDocumentLoadFailure(viewerErrorCode) {
  33.         console.error(‘onDocumentLoadFailure() – errorCode:’ + viewerErrorCode);
  34.     }
  35.     /**
  36.     * viewer.loadModel() success callback.
  37.     * Invoked after the model’s SVF has been initially loaded.
  38.     * It may trigger before any geometry has been downloaded and displayed on-screen.
  39.     */
  40.     function onLoadModelSuccess(model) {
  41.         console.log(‘onLoadModelSuccess()!’);
  42.         console.log(‘Validate model loaded: ‘ + (viewer.model === model));
  43.         console.log(model);
  44.     }
  45.     /**
  46.     * viewer.loadModel() failure callback.
  47.     * Invoked when there’s an error fetching the SVF file.
  48.     */
  49.     function onLoadModelError(viewerErrorCode) {
  50.         console.error(‘onLoadModelError() – errorCode:’ + viewerErrorCode);
  51.     }
  52.     //======================================================================
  53.     // Main
  54.     //======================================================================
  55.     var options = {
  56.         env: ‘AutodeskProduction’,
  57.         accessToken: token //”
  58.     };
  59.     var documentId = ‘urn:’ + urn; // ‘urn:’;
  60.     viewerDivId = divId; // This is where your viewer goes. e.g.,

  61.     // This is from basic viewer.
  62.     Autodesk.Viewing.Initializer(options, function onInitialized() {
  63.         Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
  64.     });
  65. }

The above code defines a function called viewByTokenAndUrn(). It takes three arguments: 1) token, 2) urn of an uploaded model, and 3) div id of html element where the viewer to be embedded.

onDocumentLoadSuccess() defines the most of the processes once it successfully gets the document pointed by the given urn. This is where a view-able is selected and finally starts rendering a targeted model in the viewer.

Actual loading of a document happens in the callback defined for Autodesk.Viewing.Initializer(), which you see at the bottom of the code. Autodesk.Viewing.Initializer() takes the above onDocumentLoadSuccess() callback as the second argument.

We can include this file to your HTML page, e.g.,

  <script src=”Scripts/viewerBasic.js”></script>

(Note: in our exercise, we place the JavaScript files under Scripts folder.)

Later on, when you are ready to explore more features, such as displaying 2D drawing, you can come back to this file and modify for your needs. For now, let’s move on and call this function from your  web form.

Embedding the Viewer in a Web Form

In your web page, include style sheet for the viewer. I’m also using ajax library to make it easy to get a handle on an html element I’m interested in. For example:

in ForgeUI.aspx
  1.     <!– Added for Lab 4 –> 
  2.     <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
  3.     <!– Autodesk Viewer CSS –> 
  4.     <link rel=”stylesheet” href=”https://developer.api.autodesk.com/modelderivative/v2/viewers/style.min.css&#8221; type=”text/css”/>
  5.     

Add the following scrip to include the necessary libraries and functions for the viewer:

in ForgeUI.aspx
  1.     <!– Viewer Lab 4 –>
  2.     <!– Autodesk Viewer JS –> 
  3.     <script src=”https://developer.api.autodesk.com/modelderivative/v2/viewers/three.min.js”></script>
  4.     <script src=”https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js”></script>
  5.     <!– Forge API Intro Code –> 
  6.     <script src=”Scripts/viewerBasic.js”></script>
  7.     <script>
  8.         // Call our basic viewer with a valid access token, urn
  9.         // and id of div where the actual viewer goes.
  10.         // For our Intro lab project, we simply pass the value from
  11.         // the token text box. In real world application, you will
  12.         // get it from your server.
  13.         function buttonViewClicked() {
  14.             var token = $(‘#TextBoxToken’).val();
  15.             var urn = $(‘#TextBoxUrn64’).val();
  16.             viewByTokenAndUrn(token, urn, “MyViewerDiv”);
  17.         }
  18.     </script>

here buttonViewClick() calls viewByTokenAndUrn() which we defined in viewerBasic.js. The first and second arguments of viewByTokenAndUrn() are token and urn. In our Intro project, we simply get necessary values from the text boxes of the web page that we have defined in the previous lab. “MyViewerDiv” is the id of div where we embed the viewer.

Finally, add a div section to embed the viewer, and name it “MyViewerDiv”. And add a button that triggers the viewing function, buttonViewClicked(). e.g.,

in ForgeUI.aspx
  1.         <!– Viewer Lab 4 –> 
  2.         <input id=”ButtonView” type=”button” value=”View” onclick=”buttonViewClicked() /><br />
  3.         
  4.         <!– The viewer will be instanciated here –>
  5.         <div id=”MyViewerDiv” style=”position:absolute; width:97%; height:40%;“></div>

An example of final web page might look like this:

ForgeIntroOverview

Tips:  The REST call to translate a model for viewing will return the status OK. But the actual process may be still in progress. You can check the status by calling GET :urn/manifest. In the sample labs code, “Status” button is added to check the status of the translation. To give you an idea how long it takes, with my environment, rst_basic_sample_project.rvt (which comes with Revit install, 6.44 MB of size) takes about 3 min. rac_advanced_sample_project.rvt (13.4 MB) takes about 10 min. 

Troubleshoot: When the model is not ready, errorCode:9 will be returned in the browser’s console. If this happens, wait a little bit, and try again. If you see errorCode:4, a problem might be with getting valid access token. Make sure you have the scope defined correctly. (Error code is defined in viewer3D.js. If you are getting a different error code, try searching a keyword “ErrorInfoData”.) 

Note: viewerBasic.js is based on Basic Viewer which does not support displaying .pdf file as it is. If you want to display .pdf, you can use Basic Application instead.

You can get the source code of Lab4 from here: Lab4

This concludes the first tour of Forge API Intro Labs. I hope you will find it helpful to get started with the Forge API.

Mikako

Update 2/8/2018: I’ve migrated one more lab’s exercise showing how to access and search objects properties using the viewer API. Please take a look at this post if you are interested in continuing with the tutorial: Lab5 Forge API Intro – Get Properties & Search

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s