Object selection in forge viewer - autodesk-forge

I have created the sample application for forge viewer.
I am able to view the Revit and navisworks files in forge viewer.
I want to select an item from the viewer by passing inputs to viewer.bubble.search method.
I am using the same coding from the url:
https://forge.autodesk.com/en/docs/viewer/v7/reference/Viewing/BubbleNode/
I am using the below code. Please help.
var viewer;
var urn1;
var accestoken1;
var jsdata;
function uploadfile(file) {
document.getElementById('<%=UploadBtn.ClientID%>').click();
}
function showModel(urn) {
var options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken
};
Autodesk.Viewing.Initializer(options, () => {
viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('forgeViewer'), { extensions: ['Autodesk.DocumentBrowser'] });
viewer.start();
var documentId = 'urn:' + urn;
urn1 = urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
// viewer.fitToView([270005], viewer.model);
// viewer.select([270005]);
});
}
function myFunction1() {
setTimeout(function () {
myFunction2();
}, 500);
}
function onDocumentLoadSuccess(doc) {
var viewables = viewer.bubble.search({ type: 'geometry', role: '3d', name: 'DOMW PIPE' });
if (viewables.length === 0) {
console.error('Document contains no viewables.');
return;
}
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
function getForgeToken(callback) {
fetch('/api/forge/oauth/token').then(res => {
res.json().then(data => {
callback(data.access_token, data.expires_in);
accestoken1 = data.access_token;
});
});
}
with thanks and regards.
Castro Nelson

If you'd like to make it possible to choose which of the 2D or 3D views (that the Model Derivative service extracted from your original design) to load in the viewer, consider using the built-in viewer extension called Autodesk.DocumentBrowser. The extension will add a new UI to the viewer that can be used to switch between the different 2D/3D views quite easily.
You can experiment with the extension on https://forge-extensions.autodesk.io:

Related

Forge Vewer v7 - Search in Default UI

I'm trying to use Autodesk.InViewerSearch extension in Forge viewer v7, but I keep getting error that new Autodesk.Viewing.A360ViewingApplication('forgeViewer', options) is not a constructor. Does this extension work in viewer v7? If I set new Autodesk.Viewing.GuiViewer3D(htmlDiv, config3d) my app works, but Autodesk.InViewerSearch is not registered.
This is my Autodesk.Viewing.Initializer:
Autodesk.Viewing.Initializer(options, function onInitialized() {
// var randomId = makeid(36);
var documentId = 'urn:' + urn;
console.log(documentId);
var config3d = {
loaderExtensions: { svf: "Autodesk.MemoryLimited" },
extensions: [
'Autodesk.DocumentBrowser',
'Autodesk.Viewing.MarkupsCore',
'Autodesk.Viewing.MarkupsGui',
'Autodesk.VisualClusters',
'Autodesk.InViewerSearch',
'ToolbarExtension',
'BoundingBoxExtension',
],
inViewerSearchConfig: {
uiEnabled: false,
relatedItemsTab: {
enabled: true, //If false, the tab is hidden.
displayName: 'This Item',
pageSize: 20
},
loadedModelTab: {
enabled: true, //If false, the tab is hidden.
displayName: 'This View',
pageSize: 50
}
}
};
//viewerApp = new Autodesk.Viewing.A360ViewingApplication('forgeViewer', options);
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.GuiViewer3D, config3d);
// viewerApp.loadDocumentWithItemAndObject(documentId);
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D, config3d);
//viewerApp.loadDocument(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv, config3d);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
var documentId = 'urn:' + urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
My options file looks like this
var options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken,
api: 'derivativeV2' + (atob(urn.replace('_', '/')).indexOf('emea') > -1 ? '_EU' : ''),
/*memory: {
limit: 1024 // in MB
}*/
};
And in my index.html I've included:
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/three.min.js"></script>
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js"></script>
I haven't found the A360ViewingApplication class nor the Autodesk.InViewerSearch extension in the Forge Viewer codebase so I'm afraid these have been removed in version 7. Let us know what exactly you wanted to achieve with the extension, I'm sure there is a different way of implementing that goal with the viewer version 7.

Set Autodesk Forge Viewer to Infinity Pool environment

Im trying to set the Infinity pool environment on the viewer but it doesn't change, it still has the initial grey background, any ideas? I'm trying to set the light preset in the ondocumentLoadSuccess Callback
var viewer;
function launchViewer(urn, accessToken, expires) {
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function (onTokenReady) {
var token = accessToken;
var timeInSeconds = expires; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function () {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Viewer3D(htmlDiv);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:' + urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
}
function onDocumentLoadSuccess(viewerDocument) {
viewer.setLightPreset(7);
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
In some cases the model you are loading into the viewer may be trying to set its own environment. Try calling the viewer.setLightPreset method after the model is loaded.

Error in viewing files in Autodesk forge viewer - error calling doc.getRootItem()

When viewing files in Autodesk forge viewer, getting the following errors,
Cannot read property ‘setEndpoint’ of undefined. Screenshot
doc.getRootItem is not a function. Screenshot
And will be able to view after empty cache and hard reload (Ctrl + Shift +R) the page. Sometimes the same errors will persist even after hard reload and clearing browser cache.
Code for the second error.
var options = {
env: 'AutodeskProduction',
accessToken: getAccessToken() //Method to get access token- no errors here
};
var documentId = 'urn:' + urn;
Autodesk.Viewing.Initializer(options, function onInitialized() {
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
//Autodesk.Viewing.Document.load - success function.
function onDocumentLoadSuccess(doc) {
setTimeout(function() {
debugger;
}, 5000);
//Error is thrown in the line below.
var viewables = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
'type': 'geometry'
}, true); //throws error on calling doc.getRootItem()
if (viewables.length === 0) {
console.error('Document contains no viewables.');
return;
}
// Choose any of the avialble viewables
var initialViewable = viewables[0];
var svfUrl = doc.getViewablePath(initialViewable);
var modelOptions = {
sharedPropertyDbPath: doc.getPropertyDbPath()
};
var viewerDiv = document.getElementById('divViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);
viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
}
You must have unwitting upgraded to Viewer V7 with which getRootItem and several other functions have been deprecated - see here for its release notes and migration guide.
Stick with V6 with <script src="https://developer-stg.api.autodesk.com/modelderivative/v2/viewers/viewer3D.js?v=6.6"></script> - if you don't specify a version by default the latest stable version would be served which is now V7.0.

How to set light theme on viewer?

I have this sample code, to initialize viewer:
<div id="viewer"></div>
<script>
var app;
var options = {
env: 'AutodeskProduction',
accessToken: 'mytoken'
};
var urn = 'myUrn';
Autodesk.Viewing.Initializer(options, function() {
app = new Autodesk.Viewing.ViewingApplication('viewer');
app.registerViewer(app.k3D, Autodesk.Viewing.Private.GuiViewer3D);
function onDocumentLoadSuccess() {
const viewables = app.bubble.search({ 'type': 'geometry' });
app.selectItem(viewables[0].data);
}
function onDocumentLoadFailure() {}
app.loadDocument('urn:' + urn, onDocumentLoadSuccess, onDocumentLoadFailure);
});
</script>
I want to use light theme but I'm not sure how to do that.
How to set light theme to viewer, please?
Thank you
You can add during inside the Initializer
Autodesk.Viewing.Initializer(options, function onInitialized() {
viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('MyViewerDiv'));
viewer.setTheme("light-theme");
viewer.start();
loadDocument(....)
});
Are you looking for the following API? Just call this method after your viewer is initialized.
/**
* Sets the current UI theme of the viewer.
* Supported values are "light-theme" and "dark-theme", which is the default.
*
* #param {string} name - Name of the theme, it will be added to the viewer's container class list.
*
* #alias Autodesk.Viewing.Viewer3D#setTheme
*/
Viewer3D.prototype.setTheme = function (name) {
};
Modified your code as follow and added one line of code in onItemLoadSuccess() as follow.
viewerApp.myCurrentViewer.setTheme("light-theme");
<script>
var viewerApp;
var options = {
env: 'AutodeskProduction',
getAccessToken: function(onGetAccessToken) {
//
// TODO: Replace static access token string below with call to fetch new token from your backend
// Both values are provided by Forge's Authentication (OAuth) API.
//
// Example Forge's Authentication (OAuth) API return value:
// {
// "access_token": "<YOUR_APPLICATION_TOKEN>",
// "token_type": "Bearer",
// "expires_in": 86400
// }
//
var accessToken = 'mytoken';
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
}
};
let config3d = {
};
var documentId = 'urn:myurn';
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.Viewing.ViewingApplication('MyViewerDiv');
viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D, config3d);
viewerApp.loadDocument(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
function onDocumentLoadSuccess(doc) {
// We could still make use of Document.getSubItemsWithProperties()
// However, when using a ViewingApplication, we have access to the **bubble** attribute,
// which references the root node of a graph that wraps each object from the Manifest JSON.
var viewables = viewerApp.bubble.search({'type':'geometry'});
if (viewables.length === 0) {
console.error('Document contains no viewables.');
return;
}
// Choose any of the avialble viewables
viewerApp.selectItem(viewables[0].data, onItemLoadSuccess, onItemLoadFail);
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
function onItemLoadSuccess(viewer, item) {
console.log('onItemLoadSuccess()!');
viewerApp.myCurrentViewer.setTheme("light-theme");
}
function onItemLoadFail(errorCode) {
console.error('onItemLoadFail() - errorCode:' + errorCode);
}
</script>

Button for markupCore extension not showing in dockingpanel

I have followed Philippe Leefsma's tutorial on how to implement the markup tool, but without any luck. Link here: http://adndevblog.typepad.com/cloud_and_mobile/2016/02/playing-with-the-new-view-data-markup-api.html
and here: https://developer.api.autodesk.com/viewingservice/v1/viewers/docs/tutorial-feature_markup.html
I get errors that I need to include requireJS, but I don't want to use it. So instead I used this script in my html file:
<script src="https://autodeskviewer.com/viewers/2.2/extensions/MarkupsCore.js">
I don't know if this is the right way to go? I get no errors in the console, but the markup button doesn't show up in the dockingpanel.
This is my code for loading the extension in the viewer:
viewerApp = null;
function initializeViewer(containerId, urn, params) {
function getToken(url) {
return new Promise(function (resolve, reject) {
$.get(url, function (response) {
resolve(response.access_token);
});
});
}
var initOptions = {
documentId: 'urn:' + urn,
env: 'AutodeskProduction',
getAccessToken: function (onGetAccessToken) {
getToken(params.gettokenurl).then(function (val) {
var accessToken = val;
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
});
}
}
function onDocumentLoaded(doc) {
var rootItem = doc.getRootItem();
// Grab all 3D items
var geometryItems3d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '3d' }, true);
// Grab all 2D items
var geometryItems2d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '2d' }, true);
// Pick the first 3D item otherwise first 2D item
var selectedItem = (geometryItems3d.length ?
geometryItems3d[0] :
geometryItems2d[0]);
var domContainer = document.getElementById('viewerContainer');
var config = { extensions: ["Autodesk.Viewing.MarkupsCore"] };
// GUI Version: viewer with controls
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(domContainer, config);
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.initialize();
viewer.loadModel(doc.getViewablePath(selectedItem));
var extension = viewer.getExtension("Autodesk.Viewing.MarkupsCore");
viewerApp = viewer;
}
function onEnvInitialized() {
Autodesk.Viewing.Document.load(
initOptions.documentId,
function (doc) {
onDocumentLoaded(doc);
},
function (errCode) {
onLoadError(errCode);
})
}
function onLoadError(errCode) {
console.log('Error loading document: ' + errCode);
}
Autodesk.Viewing.Initializer(
initOptions,
function () {
onEnvInitialized()
})
}
Any help is highly appreciated!
Unfortunately there has been a few changes to the API since I wrote that blog post. The MarkupCore.js is now included in the viewer3D.js source, so you don't need to reference any extra file or use requireJS if you use the latest version of the viewer API.
Keep in mind that this is an API-only feature, so even after loading the markup extension, you won't get any UI out of the box. You have to implemented it yourself, for example create a dialog with buttons that may eventually create markups by calling the API.
Some of the code from my blog post may still be valid and give you an idea about what you need to do.
Hope that helps.