How to load two forge viewers in single web page - autodesk-forge

I am trying to add two forge viewers in a single web page. I am using "react-forge-viewer" npm package to do that, but for some reason, only one viewer gets loaded and another one stays at "starting viewer..." state. It would be really great if anyone could help me resolve this problem.
I think this might be because of the dependency on class names or ID's.
Also, I want to synch their events in such a way that if I change camera view by dragging on on viewer same thing should reflect on another viewer as well.

You can easily fit multiple Viewers together, just be sure to initialize them separately with distinct container divs:
var viewer1 = new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('MyViewerDiv1'));
var viewer2 = new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('MyViewerDiv2'));
Autodesk.Viewing.Initializer(options1, function() {
viewer1.start();
viewer1.load(...);
});
Autodesk.Viewing.Initializer(options2, function() {
viewer2.start();
viewer2.load(...);
});
And you can sync the states of two viewers by subscribing to the CAMERA_CHANGE_EVENT, but beware pitfalls like endless loops - you can overcome this by implementing critical blocks to ensure only one viewer is exclusively requesting the other viewer to sync at any given time:
viewer1.addEventListener(Autodesk.Viewing.CAMERA_CHANGE_EVENT, function()
{
//critical block to prevent endless chained loop of events
viewer2.restoreState(viewer1.getState())
});
viewer2.addEventListener(Autodesk.Viewing.CAMERA_CHANGE_EVENT, function()
{
//critical block to prevent endless chained loop of events
viewer1.restoreState(viewer2.getState())
});
See a working sample here.
P.S:react-forge-viewer is a third party package not authored by Autodesk as is noted in its own README so you might need to contact its author if you have issues with it.

Related

load 2D & 3D forge viewers in single web page

I would like to link between elements from the 2D sheet and 3D model, so when I select the element from 2D it should reflect and select (isolate) in the 3D also if I change the color it does the same on both e.g. and the other way around.
so I can use the document browser extensions to open the 2d sheet on 1st viewer and the 3d model on the 2nd viewer:
const firstModel = new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('MyViewerDiv1'));
const secondModel = new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('MyViewerDiv2'));
Autodesk.Viewing.Initializer(options1, function() {
viewer1.start();
viewer1.load(...);
});
Autodesk.Viewing.Initializer(options2, function() {
viewer2.start();
viewer2.load(...);
});
if the example above is correct I am still missing how to links both viewers.
I hope someone could help me with this issue
Note that we have a viewer extension that might already give you what you're looking for: https://github.com/Autodesk-Forge/forge-extensions/blob/master/public/extensions/NestedViewerExtension/README.md.
If you want to implement the cross-selection between two viewer instances yourself, you can. Just subscribe to the SELECTION_CHANGED event in one of the viewers, get the selected IDs, and select the same IDs in the other viewer using the usual viewer.select([...]); method.
Btw. regarding your code snippet:
the Autodesk.Viewing.Initializer only needs to be called once per the entire webpage
the Autodesk.Viewing.Private.GuiViewer3D instances should be created after the initializer has done its work

ViewingApplication with multiple viewers

This is more of a "best practices" question. It seems to me that a ViewingApplication as outline in the docs here is directly tied to a div on the page. If that is true and I want to show both a 3d viewer and a 2d viewer, does that mean I need a seperate instance of the ViewingApplication for each div?
Yes you will need as many separate containers for your Viewer instances, just so you can initialise them separately and Viewer won’t mind if these containers share the same parent - that’s so long as a Viewer can operate exclusively in a distinct, direct parent.
See here for sample code accommodating multiple Viewers.
Alternatively if you are only after a quick fix to render several models in one div/canvas then the SplitScreen Extension probably fits the bill already:
var options = {
viewports: [
function(id) { return id === 1; },
function(id) { return id !== 1; }
]
};
viewer.loadExtension('Autodesk.SplitScreen', options);

Google Maps with Meteor and a reactive InfoWindow

I have a google maps API v3 application for meteor that I'm currently working on. When a person clicks on a marker, it shows an infoWindow with some at-window-creation time static content.
What I would like to do is use a reactive template to render the infoWindow's contents, either directly as HTML which can change or by referring to a dom element that updates reactively.
I've verified that if I use an infoWindow to refer to a DOM element, and that element's contents change, the Maps API updates the on-screen window properly. However, I am having problems with two issues:
(1) Closing the window destroys the DOM element, so it would have to be re-created. This is possibly easy enough to handle with a "if it exists update it, else create it, insert it, and update it" process.
(2) UI.render doesn't appear to be dynamic, so creating it, inserting it, and updating it is harder than it feels like it should be.
I am still an intermediate Meteor hacker, so forgive me if I'm making this too hard on myself.
For #1, make a clone: content: $('.stats').clone()[0]
For #2, you'll need to create a dependency. The docs do a pretty good job of explaining it & without knowing your reactive data source catalyst I can't help too much more (I assume it's a Session var in the example). Oh, and if it's based on new entries from a collection, check out the .observe() function.
Template.name.created = function() {
Session.set('stats',10);
statsDep = new Deps.Dependency();
};
statsDep.depend();
var dropWindow = new google.maps.InfoWindow({
content: $('.stats').clone()[0]
});
statsDep.changed();

All-in-one location/hashchange history management library

First of all, I know there's libraries that provide polyfills for location.pushState/popState (History.js, Hash.js, jQuery hashchange), so please don't just link to those.
I need a more powerful library to achieve the following in a RIA:
User clicks a link
library is notified and loads context via Ajax (no complete reload!)
All <a> elements are leveraged with a click handler that
prevents page reloads in 2. (preventDefault) and
calls location.pushState instead / sets location.hash for older browsers
loaded content is inserted in page and replaces current content
Continue with 1.
Also, previously loaded content should be restored as the user navigates back.
As an example, klick through Google+ in Internet Explorer <10 and any other browser.
Is there anything that comes even close? I need support for IE8, FF10, Safari 5 and Chrome 18. Also, it should have a permissive license like MIT or Apache.
I believe Sammy.js ( http://sammyjs.org) (MIT-licenced) has the best focus on what you want to do, with its 2 main pillars being:
Routes
Events
I could quote from the docs but it's pretty straightforward:
setup clientside routes that relate to stuff to be done, e.g: update the view through ajax
link events to call routes, e.g: call the route above when I click an link. (You would have to make sure e.preventDefault is called in the defined event I believe, since this is an app decision really, so that can't be abstracted away by any library that you're going to use imho)
Some relevant docs
http://sammyjs.org/docs
http://sammyjs.org/docs/routes
http://sammyjs.org/docs/events
Example for a route: (from http://sammyjs.org/docs/tutorials/json_store_1)
this.get('#/', function(context) {
$.ajax({
url: 'data/items.json',
dataType: 'json',
success: function(items) {
$.each(items, function(i, item) {
context.log(item.title, '-', item.artist);
});
}
});
});
Or something like
this.get('#/', function(context) {
context.app.swap(''); ///the 'swap' here indicates a cleaning of the view
//before partials are loaded, effectively rerendering the entire screen. NOt doing the swap enables you to do infinite-scrolling / appending style, etc.
// ...
});
Of course other clientside MVC-frameworks could be an option too, which take away even more plumbing, but might be overkill in this situation.
a pretty good (and still fairly recent) comparison:
http://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/
( I use Spine.js myself ) .
Lastly, I thought it might be useful to include an answer I've written a while ago that goes into detail to the whole best-practice (as I see it) in client-side refreshes, etc. Perhaps you find it useful:
Accessibility and all these JavaScript frameworks
I currently use PathJS in one of my applications.
It has been the best decision that i have made.
For your particular usecase take a look at HTML5 Example.
The piece of code that that makes the example work (from the source):
<script type="text/javascript">
// This example makes use of the jQuery library.
// You can use any methods as actions in PathJS. You can define them as I do below,
// assign them to variables, or use anonymous functions. The choice is yours.
function notFound(){
$("#output .content").html("404 Not Found");
$("#output .content").addClass("error");
}
function setPageBackground(){
$("#output .content").removeClass("error");
}
// Here we define our routes. You'll notice that I only define three routes, even
// though there are four links. Each route has an action assigned to it (via the
// `to` method, as well as an `enter` method. The `enter` method is called before
// the route is performed, which allows you to do any setup you need (changes classes,
// performing AJAX calls, adding animations, etc.
Path.map("/users").to(function(){
$("#output .content").html("Users");
}).enter(setPageBackground);
Path.map("/about").to(function(){
$("#output .content").html("About");
}).enter(setPageBackground);
Path.map("/contact").to(function(){
$("#output .content").html("Contact");
}).enter(setPageBackground);
// The `Path.rescue()` method takes a function as an argument, and will be called when
// a route is activated that you have not yet defined an action for. On this example
// page, you'll notice there is no defined route for the "Unicorns!?" link. Since no
// route is defined, it calls this method instead.
Path.rescue(notFound);
$(document).ready(function(){
// This line is used to start the HTML5 PathJS listener. This will modify the
// `window.onpopstate` method accordingly, check that HTML5 is supported, and
// fall back to hashtags if you tell it to. Calling it with no arguments will
// cause it to do nothing if HTML5 is not supported
Path.history.listen();
// If you would like it to gracefully fallback to Hashtags in the event that HTML5
// isn't supported, just pass `true` into the method.
// Path.history.listen(true);
$("a").click(function(event){
event.preventDefault();
// To make use of the HTML5 History API, you need to tell your click events to
// add to the history stack by calling the `Path.history.pushState` method. This
// method is analogous to the regular `window.history.pushState` method, but
// wraps calls to it around the PathJS dispatched. Conveniently, you'll still have
// access to any state data you assign to it as if you had manually set it via
// the standard methods.
Path.history.pushState({}, "", $(this).attr("href"));
});
});
</script>
PathJS has some of the most wanted features of a routing library:
Lightweight
Supports the HTML5 History API, the 'onhashchange' method, and graceful degredation
Supports root routes, rescue methods, paramaterized routes, optional route components (dynamic routes), and Aspect Oriented Programming
Well Tested (tests available in the ./tests directory)
Compatible with all major browsers (Tested on Firefox 3.6, Firefox 4.0, Firefox 5.0, Chrome 9, Opera 11, IE7, IE8, IE9)
Independant of all third party libraries, but plays nice with all of them
I found the last too points most attractive.
You can find them here
I hope you find this useful.
i'd like to suggest a combination of
crossroads.js as a router
http://millermedeiros.github.com/crossroads.js/
and hasher for handling browser history and hash urls (w/ plenty of fallback solutions):
https://github.com/millermedeiros/hasher/
(based on http://millermedeiros.github.com/js-signals/)
This will still require a few lines of code (to load ajax content etc.), but give you loads and loads of other possibilities when handling a route.
Here's an example using jQuery (none of the above libraries require jQuery, i'm just lazy...)
http://fiddle.jshell.net/Fe5Kz/2/show/light
HTML
<ul id="menu">
<li>
foo
</li>
<li>
bar/baz
</li>
</ul>
<div id="content"></div>
JS
//register routes
crossroads.addRoute('foo', function() {
$('#content').html('this could be ajax loaded content or whatever');
});
crossroads.addRoute('bar/{baz}', function(baz) {
//maybe do something with the parameter ...
//$('#content').load('ajax_url?baz='+baz, function(){
// $('#content').html('bar route called with parameter ' + baz);
//});
$('#content').html('bar route called with parameter ' + baz);
});
//setup hash handling
function parseHash(newHash, oldHash) {
crossroads.parse(newHash);
}
hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
//add click listener to menu items
$('#menu li a').on('click', function(e) {
e.preventDefault();
$('#menu a').removeClass('active');
$(this).addClass('active');
hasher.setHash($(this).attr('href'));
});​
Have you looked at the BigShelf sample SPA (Single Page Application) from Microsoft? It sounds like it covers how to achieve most of what you're asking.
It makes use of History.js, a custom wrapper object to easily control navigation called NavHistory and Knockout.js for click handling.
Here's an extremely abbreviated workflow of how this works: first you'll need to initialize a NavHistory object which wraps history.js and registers a callback which executes when there is a push state or hash change:
var nav = new NavHistory({
params: { page: 1, filter: "all", ... etc ... },
onNavigate: function (navEntry) {
// Respond to the incoming sort/page/filter parameters
// by updating booksDataSource and re-querying the server
}
});
Next, you'll define one or more Knockout.js view models with commands that can be bound to links buttons, etc:
var ViewModel = function (nav) {
this.search = function () {
nav.navigate({ page: 2, filter: '', ... }); // JSON object matching the NavHistory params
};
}
Finally, in your markup, you'll use Knockout.js to bind your commands to various elements:
<a data-bind="click: search">...</a>
The linked resources are much more detailed in explaining how all of this works. Unfortunately, it's not a single framework like you're seeking, but you'd be surprised how easy it is to get this working.
One more thing, following the BigShelf example, the site I'm building is fully cross-browser compatible, IE6+, Firefox, Safari (mobile and desktop) and Chrome (mobile and desktop).
The AjaxTCR Library seems to cover all bases and contains robust methods that I haven't seen before. It's released under a BSD License (Open Source Initiative).
For example, here are five AjaxTCR.history(); methods:
init(onStateChangeCallback, initState);
addToHistory(id, data, title, url, options);
getAll();
getPosition();
enableBackGuard(message, immediate);
The above addToHistory(); has enough parameters to allow for deep hash-linking in websites.
More eye-candy of .com.cookie(), .storage(), and .template() provides more than enough methods to handle any session data requirements.
The well documented AjaxTCR API webpage has a plethora of information with downloadable doc's to boot!
Status Update:
That website also has an Examples Webpage Section including downloadable .zip files with ready to use Front End(Client) and Back End(Server) project files.
Notably are the following ready-to-use examples:
One-way Cookie
HttpOnly Cookies
History Stealing
History Explorer
There are quite a bit other examples that rounds out the process to use many of their API methods, making any small learning curve faster to complete.
Several suggestions
ExtJs, see their History Example, and here are the docs.
YUI Browser History Manager.
jQuery BBQ seem to provide a more advanced feature-set over jQuery.hashcode.
ReallySimpleHistory may also be of help, though it's quite old and possibly outdated.
Note: ExtJs History has been extended to optimize duplicate (redundant) calls to add().
PJAX is the process you're describing.
The more advanced pjax techniques will even start to preload the content, when the user hovers over the link.
This is a good pjax library.
https://github.com/MoOx/pjax
You mark the containers which need will be updated on the subsequent requests:
new Pjax({ selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"] })
So in the above, only the title, the .my-header, .my-content, and .my-sidebar will be replaced with the content from the ajax call.
Somethings to look out for
Pay attention to how your JS loads and detects when the page is ready. The javascript will not reload on new pages. Also pay attention to when any analytics calls get called, for the same reason.

Preload dynamically created views in Actionscript for Flex Mobile App

I've got the following problem, my boss wants me to make our app far more responsive without any waiting time between switching views. It used to a "standard" application based on a ViewNavigator but with just one View that was destroyed and re-created with different content based on the user's selection of tabs he created himself. Views were switched with the default SlideViewTransition. I'm down to half a second now with a slightly more lightweight approach as described below, however that half second is still too much.
The app is a tabbed application where the user can create and edit new views himself, so create/edit/delete tabs and their corresponding tabs.
My current implementation is based on a ButtonBar and a Group that is used to display the "views". The group's content is created based on the selected tab. The content is based on XML data that stores all the required information to build the "view". Naturally, removing and creating the component's takes a little while (the half second I talked about), so I'm after another solution.
What I thought about is using the ViewNavigator and create all stored views upon application start.
Very much like this:
for each (var _view:XML in _allViewsConfig.children()) {
var compView:View = new View();
compView.percentHeight = 100;
compView.percentWidth = 100;
compView.name = _view.label;
for each (var _groupElement:XML in _view.vgroup) {
var group:VGroup = new VGroup;
group.percentWidth = 100;
group.percentHeight = 100;
for each (var _windowElement:XML in _groupElement.window) {
var window:WindowContainer = new WindowContainer;
for each (var _componentElement:XML in _windowElement.component) {
var component:UIComponent = _componentManager.create(_componentElement.#type, _componentElement);
window.addElement(component);
}
group.addElement(window);
}
compView.addElement(group);
}
views.addItem(compView);
}
views is an ArrayList that is used to store the created views.
The only problem I've got right now is that I can't use the Views stored in this ArrayList in the corresponding ViewNavigator.
I tried it the usual way, i.e. navigation.pushView(_viewCreator.views.getItemAt(0) as Class);
This, however doesn't work, no error or anything, the ViewNavigatorjust doesn't do anything, so I guess that a View class can't be created like this.
So how can I make this work?
Also, do you guys think that this is a proper solution to the problem, especially considering the whole dynamic nature of the application (being based on tabs)?
Naturally, slide transitions will be completely disabled as they are quite slow with our complex components.
Any help, comments or thoughts would be greatly appreciated!
EDIT:
On second thought, simply using Groups instead of ViewNavigator and View should make this a little more lightweight and solve the issue of views not being pushed.
In fact ViewNavigator pushView() is a mechanism which create an instance of a given Class (method parameter).
For all navigation history purpose, ViewNavigator uses NavigationStack objects to store relevant values (that you can customize too).
I don't have a straightforward answer for you, but I think you'll have to implement your own custom ViewNavigator mechanism (extending ViewNavigator to leverage existing useful methods and override others).