How to get the terrain height at mouse position when in 2D map? - cesiumjs

I'm using Cesium in 2D mode.
This is the code I'm using to take the terrain height at mouse position:
cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic( position );
var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(10);
var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(10);
mapPointerLatitude = latitudeString.slice(-15);
mapPointerLongitude = longitudeString.slice(-15);
var tempHeight = cartographic.height;
if( tempHeight < 0 ) tempHeight = 0;
mapPointerHeight = tempHeight.toFixed(2);
Where position came from a Cesium.ScreenSpaceEventType.MOUSE_MOVE event:
if ( mapStyle === '2D' ) {
var position = viewer.camera.pickEllipsoid(movement.endPosition, scene.globe.ellipsoid);
if (position) {
return position;
}
}
if ( mapStyle === '3D' ) {
var ray = viewer.camera.getPickRay(movement.endPosition);
var position = viewer.scene.globe.pick(ray, viewer.scene);
if (Cesium.defined(position)) {
return position;
}
}
When the map is in 3D mode (Cesium.SceneMode.SCENE3D) I have the height value in tempHeight but when the map is in Cesium.SceneMode.SCENE2D this value is always zero. What I'm doing wrong?
EDIT
Don't know if this is the best way but I get it to work putting my code inside this:
cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic( position );
var positions = [ cartographic ];
var promise = Cesium.sampleTerrain(terrainProvider, 11, positions);
Cesium.when(promise, function( updatedPositions ) {
// PUT ALL HERE
});

You can actually try Cesium.sampleTerrainMostDetailed to get more precise altitude.
// Query the terrain height of two Cartographic positions
const terrainProvider = Cesium.createWorldTerrain();
const positions = [
Cesium.Cartographic.fromDegrees(86.925145, 27.988257),
Cesium.Cartographic.fromDegrees(87.0, 28.0)
];
Cesium.sampleTerrainMostDetailed(terrainProvider, positions).then((updatedPositions) => {
// positions[0].height and positions[1].height have been updated.
// updatedPositions is just a reference to positions.
})
https://cesium.com/learn/cesiumjs/ref-doc/global.html?classFilter=sample#sampleTerrainMostDetailed

Related

How can i add an svg image and a label to a custom shape dynamically mxgraph

`function Domain() {
mxCylinder.call(this);
}
/*
The next lines use an mxCylinder instance to augment the
prototype of the shape ("inheritance") and reset the
constructor to the topmost function of the c'tor chain.
*/
mxUtils.extend(Domain, mxCylinder);
Domain.prototype.redrawPath = function (
path: any,
x: any,
y: any,
w: any,
h: any
) {
var dy = this.extrude * this.scale;
var dx = this.extrude * this.scale;
path.moveTo(0, dy);
path.lineTo(dx, 0);
path.lineTo(w, 0);
path.lineTo(w, h - dy);
path.lineTo(w, h);
path.lineTo(0, h);
path.lineTo(0, dy);
path.lineTo(dx, 0);
path.close();
};
mxCellRenderer.registerShape("Domain", Domain);
export function main(container: any) {
if (!mxClient.isBrowserSupported()) {
mxUtils.error("Browser is not supported!", 200, false);
} else {
mxEvent.disableContextMenu(container);
var graph = new mxGraph(container);
graph.setCellsCloneable(true);
graph.setHtmlLabels(true);
graph.setPanning(true);
graph.setEnabled(false);
graph.centerZoom = false;
new mxRubberband(graph);
configureStylesheet(graph);
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try {
var v1 = graph.insertVertex(
parent,
null,
"RAN",
20,
20,
240,
120,
// 'image;image=icons/secure-gdpr-user-svgrepo-com.svg;selectable=0;connectable=0;editable=0;movable=0;fillColor=hsl(36deg 98% 51%)'
//here i'm regestering my shape how can i add an image and a label inside the shape "shape=Domain;startSize=30;fillColor=hsl(36deg 98% 51%);spacingLeft=10;align=left;fontColor=#FFFFFF;fontSize=18;shadow=0;strokeColor=none;whiteSpace=wrap;img;"
);
} finally {
// Updates the display
graph.getModel().endUpdate();
}
}
}
i Used configure style sheet to add the image to the shape but when i do this
// style[mxConstants.STYLE_SHAPE] = "Domain";
the image disappears and i get only the sape
export function configureStylesheet(graph: any) {
var style: any = new Object();
style = mxUtils.clone(style);
// style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
// style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_LABEL;
// style[mxConstants.STYLE_SHAPE] = "Domain";
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_LABEL;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER;
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP;
style[mxConstants.STYLE_IMAGE_ALIGN] = mxConstants.ALIGN_CENTER;
style[mxConstants.STYLE_IMAGE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP;
style[mxConstants.STYLE_IMAGE] = "icons/secure-gdpr-user-svgrepo-com.svg";
style[mxConstants.STYLE_IMAGE_WIDTH] = "48";
style[mxConstants.STYLE_IMAGE_HEIGHT] = "48";
style[mxConstants.STYLE_SPACING_TOP] = "80";
style[mxConstants.STYLE_SPACING] = "8";
graph.getStylesheet().putCellStyle("img", style);
Here's the approach i'm trying to do but the thing is that the image is overwriting the shape and not able to display the image in my customised shape. i need to have that custom shape taking the label and the image and dynamically for it to be implemented more than once`

Google map API image overlay in vector map with tilt and heading

I place the image on the map using custom overlay example in
https://developers.google.com/maps/documentation/javascript/customoverlays
but when i rotate the map, overlay deforms. Is it possible to fix it?
enter image description here
I understand that this is happening because in the draw method
processing is carried out at two points - SouthWest and NorthEast.
draw() {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this, we need to retrieve the projection from the overlay.
const overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
const sw = overlayProjection.fromLatLngToDivPixel(
this.bounds.getSouthWest()
);
const ne = overlayProjection.fromLatLngToDivPixel(
this.bounds.getNorthEast()
);
// Resize the image's div to fit the indicated dimensions.
if (this.div) {
this.div.style.left = sw.x + "px";
this.div.style.top = ne.y + "px";
this.div.style.width = ne.x - sw.x + "px";
this.div.style.height = sw.y - ne.y + "px";
this.div.style.transform = 'rotate(' + this.angle + 'deg)';
}
Because of this, the image is deformed.
But I don't know how to set four vertices for an image.
i solved it using WebGLOverlayView
https://developers.google.com/maps/documentation/javascript/webgl/webgl-overlay-view
const webGLOverlayView = new google.maps.WebGLOverlayView();
webGLOverlayView.onAdd = () => {
scene = new THREE.Scene();
const fov = 180;
const aspect = 2; // the canvas default
const near = 1;
const far = 1;
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
const width = 800;
const height = 400;
const widthSegments = 800;
const heightSegments = 400;
const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments)
const loader = new THREE.TextureLoader();
const texture = loader.load('img920C.jpg');
texture.magFilter = THREE.NearestFilter
texture.minFilter = THREE.NearestMipMapNearestFilter
texture.anisotropy = 16
var material = new THREE.MeshBasicMaterial( { map: texture, } );
var cube = new THREE.Mesh( geometry, material );
cube.name = 'cube';
scene.add( cube );
}
webGLOverlayView.onContextRestored = ({gl}) => {
renderer = new THREE.WebGLRenderer({
canvas: gl.canvas,
context: gl,
antialias: false,
...gl.getContextAttributes(),
});
renderer.autoClear = false;
renderer.antialias = false;
const controls = new THREE.OrbitControls(camera, renderer.domElement);
};
webGLOverlayView.onDraw = ({gl, transformer}) => {
const latLngAltitudeLiteral = {
lat: marker.getPosition().lat,
lng: marker.getPosition().lng,
altitude: 0
}
const matrix = transformer.fromLatLngAltitude(latLngAltitudeLiteral);
camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);
webGLOverlayView.requestRedraw();
renderer.render(scene, camera);
renderer.resetState();
}
webGLOverlayView.setMap(map)
}
It looks like this is the correct approach. But what about mouse events, I don't know. I would like to receive a mousedown click event? for webGLOverlayView.
Something similar to:
webGLOverlayView.addListener('click', function(){console.log("ok")});

Merge or Use instance and Native render make no difference with Chrome plus Integrated Graphics Card [duplicate]

I am testing the FPS with my laptop using the Intel(R) Iris(R) Plus Graphics 655 card.
To test the threeJS example with Instance rendering and merge-drawcall rendering.
So I used both the QRCode_buffergeometry.json model and the suzanne_buffergeometry.json model.
for the QRCode_buffergeometry.json: vertex:12852, face: 4284
and for the suzanne_buffergeometry.json: vertex:1515 face: 967
Then the FPS for the suzanne_buffergeometry with 8000 count:
INSTANCE: 36
MERGED: 43
NATIVE: from 23 to 35 by rotation
for the QRCode_buffergeometry model with 8000 count:
INSTANCE: 9
MERGED: 15-17
NATIVE: 17-19
I am very confused with this performance.
1. As far as my understanding, with no matter if i use instance or merge-drawcall, the drawcall is fixed to be 1 and the total face number to draw is same, why merged-drawcall is better than instance? Since the face and vertex number are both same, I suppose what happened in the vertex shader for transform the vertex should be same too, so why merged is faster?
For the QRCode_buffergeometry model, native is almost same as merged, and better than instance, so I guess the CPU is not the bottle neck but the GPU is, however the final drawing data should be same, i mean eventually the face number to be draw should be same, why native is faster?, isn't that the instance is supposed to be the best way? I am pretty sure the camera's far and near is big enough, so there should not be any culling issue.
When I am trying to optimize some big scene, when should I pick merge? when to pick instance? and when maybe no doing anything is better?
Any help?
Thanks a lot~~~
Attached the code for the sample is here
body { margin: 0; }
<div id="container"></div>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three#0.112.1/build/three.module.js';
import Stats from 'https://cdn.jsdelivr.net/npm/three#0.112.1/examples/jsm/libs/stats.module.js';
import {
GUI
} from 'https://cdn.jsdelivr.net/npm/three#0.112.1/examples/jsm/libs/dat.gui.module.js';
import {
OrbitControls
} from 'https://cdn.jsdelivr.net/npm/three#0.112.1/examples/jsm/controls/OrbitControls.js';
import {
BufferGeometryUtils
} from 'https://cdn.jsdelivr.net/npm/three#0.112.1/examples/jsm/utils/BufferGeometryUtils.js';
var container, stats, gui, guiStatsEl;
var camera, controls, scene, renderer, material;
// gui
var Method = {
INSTANCED: 'INSTANCED',
MERGED: 'MERGED',
NAIVE: 'NAIVE'
};
var api = {
method: Method.INSTANCED,
mesh_number: 1,
count_per_mesh: 1000
};
var modelName = 'suzanne_buffergeometry.json';
var modelScale = (modelName === 'suzanne_buffergeometry.json' ? 1 : 0.01);
var modelVertex = (modelName === 'suzanne_buffergeometry.json' ? 1515 : 12852);
var modelFace = (modelName === 'suzanne_buffergeometry.json' ? 967 : 4284);
//
init();
initMesh();
animate();
//
function clean() {
var meshes = [];
scene.traverse(function(object) {
if (object.isMesh) meshes.push(object);
});
for (var i = 0; i < meshes.length; i++) {
var mesh = meshes[i];
mesh.material.dispose();
mesh.geometry.dispose();
scene.remove(mesh);
}
}
var randomizeMatrix = function() {
var position = new THREE.Vector3();
var rotation = new THREE.Euler();
var quaternion = new THREE.Quaternion();
var scale = new THREE.Vector3();
return function(matrix) {
position.x = Math.random() * 40 - 20;
position.y = Math.random() * 40 - 20;
position.z = Math.random() * 40 - 20;
rotation.x = Math.random() * 2 * Math.PI;
rotation.y = Math.random() * 2 * Math.PI;
rotation.z = Math.random() * 2 * Math.PI;
quaternion.setFromEuler(rotation);
scale.x = scale.y = scale.z = Math.random() * modelScale;
matrix.compose(position, quaternion, scale);
};
}();
function initMesh() {
clean();
console.time(api.method + ' (build)');
for (var i = 0; i < api.mesh_number; i++) {
// make instances
new THREE.BufferGeometryLoader()
.setPath('https://threejs.org/examples/models/json/')
.load(modelName, function(geometry) {
material = new THREE.MeshNormalMaterial();
geometry.computeVertexNormals();
switch (api.method) {
case Method.INSTANCED:
makeInstanced(geometry);
break;
case Method.MERGED:
makeMerged(geometry);
break;
case Method.NAIVE:
makeNaive(geometry);
break;
}
});
}
console.timeEnd(api.method + ' (build)');
var drawCalls = 0;
switch (api.method) {
case Method.INSTANCED:
case Method.MERGED:
drawCalls = api.mesh_number;
break;
case Method.NAIVE:
drawCalls = api.mesh_number * api.count_per_mesh;
break;
}
guiStatsEl.innerHTML = [
'<i>GPU draw calls</i>: ' + drawCalls,
'<i>Face Number</i>: ' + (modelFace * api.mesh_number * api.count_per_mesh),
'<i>Vertex Number</i>: ' + (modelVertex * api.mesh_number * api.count_per_mesh)
].join('<br/>');
}
function makeInstanced(geometry, idx) {
var matrix = new THREE.Matrix4();
var mesh = new THREE.InstancedMesh(geometry, material, api.count_per_mesh);
for (var i = 0; i < api.count_per_mesh; i++) {
randomizeMatrix(matrix);
mesh.setMatrixAt(i, matrix);
}
scene.add(mesh);
}
function makeMerged(geometry, idx) {
var instanceGeometry;
var geometries = [];
var matrix = new THREE.Matrix4();
for (var i = 0; i < api.count_per_mesh; i++) {
randomizeMatrix(matrix);
var instanceGeometry = geometry.clone();
instanceGeometry.applyMatrix(matrix);
geometries.push(instanceGeometry);
}
var mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(geometries);
scene.add(new THREE.Mesh(mergedGeometry, material));
}
function makeNaive(geometry, idx) {
var matrix = new THREE.Matrix4();
for (var i = 0; i < api.count_per_mesh; i++) {
randomizeMatrix(matrix);
var mesh = new THREE.Mesh(geometry, material);
mesh.applyMatrix(matrix);
scene.add(mesh);
}
}
function init() {
var width = window.innerWidth;
var height = window.innerHeight;
// camera
camera = new THREE.PerspectiveCamera(70, width / height, 1, 100);
camera.position.z = 30;
// renderer
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
renderer.outputEncoding = THREE.sRGBEncoding;
container = document.getElementById('container');
container.appendChild(renderer.domElement);
// scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
// controls
controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
// stats
stats = new Stats();
container.appendChild(stats.dom);
// gui
gui = new GUI();
gui.add(api, 'method', Method).onChange(initMesh);
gui.add(api, 'count_per_mesh', 1, 20000).step(1).onChange(initMesh);
gui.add(api, 'mesh_number', 1, 200).step(1).onChange(initMesh);
var perfFolder = gui.addFolder('Performance');
guiStatsEl = document.createElement('li');
guiStatsEl.classList.add('gui-stats');
perfFolder.__ul.appendChild(guiStatsEl);
perfFolder.open();
// listeners
window.addEventListener('resize', onWindowResize, false);
Object.assign(window, {
scene
});
}
//
function onWindowResize() {
var width = window.innerWidth;
var height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
stats.update();
render();
}
function render() {
renderer.render(scene, camera);
}
//
function getGeometryByteLength(geometry) {
var total = 0;
if (geometry.index) total += geometry.index.array.byteLength;
for (var name in geometry.attributes) {
total += geometry.attributes[name].array.byteLength;
}
return total;
}
// Source: https://stackoverflow.com/a/18650828/1314762
function formatBytes(bytes, decimals) {
if (bytes === 0) return '0 bytes';
var k = 1024;
var dm = decimals < 0 ? 0 : decimals;
var sizes = ['bytes', 'KB', 'MB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
</script>
This is only guesses
Three.js by default culls if things are outside the frustum.
We can turn this off with mesh.frustumCulled = false. I didn't notice a difference and this should show up in the draw count.
Three.js by default sorts opaque objects back to front.
This means everything else being equal, sorted will run faster
than unsorted because of the depth test. If I set the depth test
to always
material.depthFunc = THREE.AlwaysDepth
Then I seem to get slightly faster rendering with instanced vs native. Of course
everything else is not equal.
An issue in Chrome.
If I run in Firefox or Safari I get the expected results. Merged > Instanced > Native
It could be a bug or it could be they're working around a driver or
security issue that the other browsers are not. You'd have to ask.

Picking under elements of an element in Autodesk Forge viewer

I would like to accomplish a feature that I can do in Three.js but cannot in Autodesk Forge viewer. Here is the link to test: http://app.netonapp.com/JavaScript/Three.js/select_inner_objects.html
The requirement is to select objects inside an object. This job can be done with THREE.Raycaster in the above demo, to use a raycaster to detect all elements which are on the line the ray going through. Then I can get objects behind or inner another object.
I tried this concept in Autodesk Forge viewer but having no success. Here is the code:
// Change this to:
// true to use original Three.js
// false to use Autodesk Forge Viewer API
var useThreeJS = true;
var container = $('div.canvas-wrap')[0];
container.addEventListener('mousedown', function (event) {
if (useThreeJS) {
var canvas = _viewer.impl.canvas;
var containerWidth = canvas.clientWidth;
var containerHeight = canvas.clientHeight;
var camera = _viewer.getCamera();
var mouse = mouse || new THREE.Vector3();
var raycaster = raycaster || new THREE.Raycaster();
mouse.x = 2 * (event.clientX / containerWidth) - 1;
mouse.y = 1 - 2 * (event.clientY / containerHeight);
mouse.unproject(camera);
raycaster.set(camera.position, mouse.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(objects);
if (intersects.length == 1) {
var obj = intersects[0].object;
obj.material.color.setRGB(1.0 - i / intersects.length, 0, 0);
} else if (intersects.length > 1) {
// Exclude the first which is the outer object (i == 0)
for (var i = 1; i < intersects.length; i++) {
var obj = intersects[i].object;
obj.material.color.setRGB(1.0 - i / intersects.length, 0, 0);
}
}
} else {
var vp = _viewer.impl.clientToViewport(event.canvasX, event.canvasY);
var renderer = _viewer.impl.renderer();
var dbId = renderer.idAtPixel(vp.x, vp.y);
if (dbId) {
console.debug("Selected Id: " + dbId);
_viewer.select(dbId);
_viewer.impl.invalidate(true);
}
}
}, false);
I found the Forge viewer has viewer.impl.renderer().idAtPixel method which is great to get an element at the picking pixel. However, I want it to do more, to select all elements (which are under or nested) at the picking pixel. How I can do it with the Forge Viewer API?
Based on the suggestion of Zhong Wu in another post, here is the final solution to select element which is under or inside another element. I created an Autodesk Forge viewer extension to use it easily.
///////////////////////////////////////////////////////////////////////////////
// InnerSelection viewer extension
// by Khoa Ho, December 2016
//
///////////////////////////////////////////////////////////////////////////////
AutodeskNamespace("Autodesk.ADN.Viewing.Extension");
Autodesk.ADN.Viewing.Extension.InnerSelection = function (viewer, options) {
Autodesk.Viewing.Extension.call(this, viewer, options);
var _self = this;
var _container = viewer.canvas.parentElement;
var _renderer = viewer.impl.renderer();
var _instanceTree = viewer.model.getData().instanceTree;
var _fragmentList = viewer.model.getFragmentList();
var _eventSelectionChanged = false;
var _viewport;
var _outerDbId;
_self.load = function () {
_container.addEventListener('mousedown',
onMouseDown);
viewer.addEventListener(
Autodesk.Viewing.SELECTION_CHANGED_EVENT,
onItemSelected);
console.log('Autodesk.ADN.Viewing.Extension.InnerSelection loaded');
return true;
};
_self.unload = function () {
_container.removeEventListener('mousedown',
onMouseDown);
viewer.removeEventListener(
Autodesk.Viewing.SELECTION_CHANGED_EVENT,
onItemSelected);
console.log('Autodesk.ADN.Viewing.Extension.InnerSelection unloaded');
return true;
};
function onMouseDown(e) {
var viewport = viewer.impl.clientToViewport(e.canvasX, e.canvasY);
_viewport = viewport; // Keep this viewport to use in onItemSelected()
var dbId = _renderer.idAtPixel(viewport.x, viewport.y);
if (_outerDbId == dbId) {
_outerDbId = -1;
// Deselect everything
viewer.select();
} else {
_outerDbId = dbId;
// Hide outer element temporarily to allow picking its behind element
viewer.hideById(dbId);
_eventSelectionChanged = true;
}
viewer.impl.sceneUpdated(true);
}
function onItemSelected(e) {
if (_eventSelectionChanged) {
// Prevent self looping on selection
_eventSelectionChanged = false;
// Show outer element back
viewer.show(_outerDbId);
// Get inner element Id after the outer element
// was just hidden on mouse down event
var innerDbId = _renderer.idAtPixel(_viewport.x, _viewport.y);
if (innerDbId > -1) {
// Select the inner element when it is found
viewer.select(innerDbId);
console.debug("Selected inner Id: " + innerDbId);
} else if (_outerDbId > -1) {
// Select the outer element if the inner element is not found
viewer.select(_outerDbId);
console.debug("Selected outer Id: " + _outerDbId);
}
}
}
};
Autodesk.ADN.Viewing.Extension.InnerSelection.prototype =
Object.create(Autodesk.Viewing.Extension.prototype);
Autodesk.ADN.Viewing.Extension.InnerSelection.prototype.constructor =
Autodesk.ADN.Viewing.Extension.InnerSelection;
Autodesk.Viewing.theExtensionManager.registerExtension(
'Autodesk.ADN.Viewing.Extension.InnerSelection',
Autodesk.ADN.Viewing.Extension.InnerSelection);
As of now (Dec/16), when you select using mouse click, the Viewer will not ignore transparent elements, so it will select an element even if it is transparent. Below is a code I used to track what's under the cursor, maybe can be useful.
// use jQuery to bind a mouve move event
$(_viewer.container).bind("mousemove", onMouseMove);
function onMouseMove(e) {
var screenPoint = {
x: event.clientX,
y: event.clientY
};
var n = normalize(screenPoint);
var dbId = /*_viewer.utilities.getHitPoint*/ getHitDbId(n.x, n.y);
//
// use the dbId somehow...
//
}
// This is a built-in method getHitPoint, but the original returns
// the hit point, so this modified version returns the dbId
function getHitDbId(){
y = 1.0 - y;
x = x * 2.0 - 1.0;
y = y * 2.0 - 1.0;
var vpVec = new THREE.Vector3(x, y, 1);
var result = _viewer.impl.hitTestViewport(vpVec, false);
//return result ? result.intersectPoint : null; // original implementation
return result ? result.dbId : null;
}
function normalize(screenPoint) {
var viewport = _viewer.navigation.getScreenViewport();
var n = {
x: (screenPoint.x - viewport.left) / viewport.width,
y: (screenPoint.y - viewport.top) / viewport.height
};
return n;
}
I see method viewer.impl.renderer().idAtPixel works better than viewer.impl.hitTestViewport to select element on mouse pick. The first one can click through the hidden/ghost element to get the objectId of element behind. While the second cannot. Here is the code to test:
var container = $('div.canvas-wrap')[0];
container.addEventListener('mousedown', function (event) {
var clickThroughHiddenElement = true;
if (clickThroughHiddenElement) {
var vp = _viewer.impl.clientToViewport(event.canvasX, event.canvasY);
var renderer = _viewer.impl.renderer();
var dbId = renderer.idAtPixel(vp.x, vp.y);
if (!!dbId) {
_viewer.select(dbId);
}
console.debug("Selected Id: " + dbId);
} else {
var screenPoint = {
x: event.clientX,
y: event.clientY
};
var viewport = _viewer.navigation.getScreenViewport();
var x = (screenPoint.x - viewport.left) / viewport.width;
var y = (screenPoint.y - viewport.top) / viewport.height;
// Normalize point
x = x * 2.0 - 1.0;
y = (1.0 - y) * 2.0 - 1.0;
var vpVec = new THREE.Vector3(x, y, 1);
var result = _viewer.impl.hitTestViewport(vpVec, false);
if (!!result) {
var dbId = result.dbId;
_viewer.select(dbId);
console.debug("Selected Id: " + dbId);
}
}
}
However, they are not what I want, to click through transparent element to get elements behind. If user selects transparent element, it will be selected. If user selects inner elements, it will ignore outer transparent element to select the pick inner element.
I check Forge viewer uses THREE.Raycaster with element bounding box to detect intersection on mouse click. It seems my problem is doable with the Forge viewer like it does in my Three.js demo.

GMap Polyline position of center

When I create Gmap she needed to establish the center and zoom
Once we've created a map via the GMap2
constructor, we need to initialize it.
This initialization is accomplished
with use of the map's setCenter ()
method. The setCenter () method
requires a GLatLng coordinate and a
zoom level and this method must be
sent before any other operations are
performed on the map, including
setting any other attributes of the
map itself.
Because of this route is not positioned at the center - this is an example http://grab.by/4OD6
I should on the basis of the coordinates to get the center?
And get a zoom which displays all objects map?
My code:
var TrainingGMap = Class.create ((
initialize: function (div_id, points, options) (
this.options = Object.extend ((), options)
this.points = points;
this.map = new GMap2 (document.getElementById (div_id));
this.map.setCenter (new GLatLng (this.points [0]. lan, this.points [0]. lon), 12);
this.map.setUIToDefault ();
this.set_route ();
)
set_route: function () (
var line = new Array ();
for (var i = 0; i <this.points.length; i + +) (
line [i] = new GLatLng (this.points [i]. lat, this.points [i]. lon);
)
var polyline = new GPolyline (line, "# aa0000", 5);
this.map.addOverlay (polyline);
)
));
I resolve my problem
this.map.setCenter(polyline.getBounds().getCenter());
this.map.setZoom(this.map.getBoundsZoomLevel(polyline.getBounds()));
New code
var TrainingGMap = Class.create({
initialize: function(div_id, points, options) {
this.options = Object.extend({}, options)
this.points = points;
this.map = new GMap2(document.getElementById(div_id));
this.map.setCenter(new GLatLng(this.points[0].lan, this.points[0].lon), 12);
this.map.setUIToDefault();
var line = new Array();
for (var i = 0; i < this.points.length; i++) {
line[i] = new GLatLng(this.points[i].lan,this.points[i].lon);
}
var polyline = new GPolyline(line, "#aa0000", 5);
this.map.setCenter(polyline.getBounds().getCenter());
this.map.setZoom(this.map.getBoundsZoomLevel(polyline.getBounds()));
this.map.addOverlay(polyline);
}
});
var TrainingGMap = Class.create({
initialize: function(div_id, points, options) {
this.options = Object.extend({}, options)
this.points = points;
this.map = new GMap2(document.getElementById(div_id));
this.map.setCenter(new GLatLng(this.points[0].lan, this.points[0].lon), 12);
this.map.setUIToDefault();
var line = new Array();
for (var i = 0; i < this.points.length; i++) {
line[i] = new GLatLng(this.points[i].lan,this.points[i].lon);
}
var polyline = new GPolyline(line, "#aa0000", 5);
var tengah=Math.round(polyline.getVertexCount()/2)-1;
this.map.setCenter(polyline.getVertex(tengah));
this.map.setZoom(this.map.getBoundsZoomLevel(polyline.getBounds()));
this.map.addOverlay(polyline);
}
});