Autodesk forge Markup extension markers position not matching x y z values - autodesk-forge

I am using the markup extension that can be found at https://github.com/wallabyway/markupExt and have not changed the code within the extension except setting this.size to a bigger value to make the marker easier to find
the actual rendering of the points works fine I just can't seem to place them in a specific position on the model, they just appear floating off in the middle of empty space.
Code to generate the point
var dummyData = [];
dummyData.push({
icon: Math.round(Math.random() * 3),
x: 129597.054373,
y: -27184.841094,
z: 44514.362733
});
window.dispatchEvent(new CustomEvent('newData', { 'detail': dummyData }));
I have tried feeding it values taken straight from a selected items properties and have also tried feeding it values taken from the following code (I have tried with and without the nominalise step)
function onMouseClick(event) {
var screenPoint = {
x: event.clientX,
y: event.clientY
};
var n = normalizeCoords(screenPoint)
var hitTest = viewer.impl.hitTest(n.x, n.y, true);
if (hitTest) {
alert(hitTest.intersectPoint.x + ' ' + ' ' + hitTest.intersectPoint.y + ' ' + hitTest.intersectPoint.z)
}
}
function normalizeCoords(screenPoint) {
var viewport = viewer.navigation.getScreenViewport();
var n = {
x: (screenPoint.x - viewport.left) / viewport.width,
y: (screenPoint.y - viewport.top) / viewport.height
};
return n;
}
The point moves when i change the x y z values but never to where I want them and am not sure where I am going wrong

Rather than the code found in the other extensions that uses the viewport to offset the point I seem to have fixed it by adding viewer.model.getData().globalOffset to the hit test intersection values

Related

How can i get correct coordinates on model in forge viewer

I want to realize pushpin extension for autodesk forge with point cloud, but with custom coordinates. I want to get custom coordinates on model click event. I cant normalize the points so that they appear where I clicked.
I try to normalize points with this code, but its not working.
viewer.canvas.addEventListener( 'click', (event) => {
var screenPoint = {
x: event.clientX,
y: event.clientY
};
var n = normalize(screenPoint);
var dbId = /*_viewer.utilities.getHitPoint*/ getHitDbId(n.x, n.y);
if (dbId == null) return;
})
function getHitDbId(x, y) {
x = x * 2.0 - 1.0;
y = y * 2.0 - 1.0;
var vpVec = new THREE.Vector3(x, y, 0.5);
var result = viewer.impl.hitTestViewport(vpVec, false);
result.distance = 1;
if(result){
dummyData.push({
icon: Math.round(Math.random()*3),
x: result.point.x,
y: result.point.y,
z: result.point.z,
});
window.dispatchEvent(new CustomEvent('newData', {
'detail': dummyData
}))
} else {
return
}
};
function normalize(screenPoint) {
var viewport = viewer.navigation.getScreenViewport();
var n = {
x: (screenPoint.x - viewport.left) / viewport.width,
y: (screenPoint.y - viewport.top) / viewport.height
};
console.log(n);
return n;
}
Edited answer.
Now i have another problem after when i normalize offset. Some pushpins are appearing incorrect. You can see problem in picture.
How can i fix it?
You can find the sample code for finding the corresponding world coordinates in the Forge Digital Twin code: https://github.com/petrbroz/forge-digital-twin/blob/master/public/scripts/extensions/issues.js.
Live demo: http://forge-digital-twin.autodesk.io/ (try the flag icon in the toolbar).

Alignment issue between BPMN.IO and Heatmap.js

I'm trying to overlay a bpmn flow using bpmn.io with a heatmap using heatmap.js. If the canvas is set to the first and only element in the dom it actually works, but once you add anything else like in my sample a header, the coordinate system between both gets off.
I've prepared a fiddle that shows exactly what I mean.
https://jsfiddle.net/rafaturtle/qt8Ly4ez/16/
const rect = canvas.getGraphics(element).getBoundingClientRect();
const x = (rect.x + rect.width / 2);
const y = (rect.y + rect.height / 2);
data.push({
x: x.toFixed(0),
y: y.toFixed(0),
value: stats[element.id]
});
I believe its on the calculation of x,y of each element, off setting it by a factor but after trying every combination I could think of I didn't manage.
thanks
I am not sure if I misunderstood what you aim for, but laying the heatmap over the elements can be easily achieved by using the dimensions of the current element, element.x, element.y, element.width, element.height.
The following code places the heatmap at the exact position of the elements:
var registry = bpmnJS.get('elementRegistry');
for (var i in registry.getAll()) {
var element = registry.getAll()[i];
if (stats[element.id] != null) {
const centerx = element.x + (element.width / 2 )
const centery = element.y + (element.height / 2 )
data.push({
x: centerx,
y: centery,
value: stats[element.id]
});
}
}
Working example: https://jsfiddle.net/cr8Lg53a/
const x = (rect.x + rect.width / 2) - canvas.getContainer().getBoundingClientRect().x;
const y = (rect.y + rect.height / 2) - canvas.getContainer().getBoundingClientRect().y;
try this

Static Maps: Drawing polygons with many points. (2048 char limitation)

Because there is a limitation to 2048 characters in the get request, you are not able to generate an image with Google Static Maps which contains a polygon with a great number of polygon points.
Especially if you try to draw many complex polygons on one map.
If you use Google Maps API, you will have no problem - it works very well!
But I want to have an image (jpg or png)...
So, is there any opportunity to create an image from the Google Maps API? Or any way to 'trick' the 2048 char limitation?
Thanks!
There's no way to 'trick' the character limit, but it is possible to simplify your polyline to bring the encoded polyline string below the character limit. This may or may not result in a polygon of suitable fidelity for your needs.
One additional caveat is that (to the best of my knowledge) the Static Maps API only allows a single encoded polyline to be drawn on the map (this can look like a polygon, if you either close it yourself or fill it, but it's still a polyline, not a polygon).
One option for simplifying your polyline is the Douglas Peucker algorithm. Below is an implementation which extends the google.maps.Polyline object with a simplify method.
This relies on having the Google Maps JS API loaded, which you may not want if you're using Static Maps, but the code below could easily be re-written.
google.maps.Polyline.prototype.simplify = function(tolerance) {
var points = this.getPath().getArray(); // An array of google.maps.LatLng objects
var keep = []; // The simplified array of points
// Check there is something to simplify.
if (points.length <= 2) {
return points;
}
function distanceToSegment(p, v, w) {
function distanceSquared(v, w) {
return Math.pow((v.x - w.x),2) + Math.pow((v.y - w.y),2)
}
function distanceToSegmentSquared(p, v, w) {
var l2 = distanceSquared(v, w);
if (l2 === 0) return distanceSquared(p, v);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if (t < 0) return distanceSquared(p, v);
if (t > 1) return distanceSquared(p, w);
return distanceSquared(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) });
}
// Lat/Lng to x/y
function ll2xy(p){
return {x:p.lat(),y:p.lng()};
}
return Math.sqrt(distanceToSegmentSquared(ll2xy(p), ll2xy(v), ll2xy(w)));
}
function dp( points, tolerance ) {
// If the segment is too small, just keep the first point.
// We push the final point on at the very end.
if ( points.length <= 2 ) {
return [points[0]];
}
var keep = [], // An array of points to keep
v = points[0], // Starting point that defines a segment
w = points[points.length-1], // Ending point that defines a segment
maxDistance = 0, // Distance of farthest point
maxIndex = 0; // Index of said point
// Loop over every intermediate point to find point greatest distance from segment
for ( var i = 1, ii = points.length - 2; i <= ii; i++ ) {
var distance = distanceToSegment(points[i], points[0], points[points.length-1]);
if( distance > maxDistance ) {
maxDistance = distance;
maxIndex = i;
}
}
// check if the max distance is greater than our tollerance allows
if ( maxDistance >= tolerance ) {
// Recursivly call dp() on first half of points
keep = keep.concat( dp( points.slice( 0, maxIndex + 1 ), tolerance ) );
// Then on second half
keep = keep.concat( dp( points.slice( maxIndex, points.length ), tolerance ) );
} else {
// Discarding intermediate point, keep the first
keep = [points[0]];
}
return keep;
};
// Push the final point on
keep = dp(points, tolerance);
keep.push(points[points.length-1]);
return keep;
};
This has been cobbled together with the help of a couple of examples (here and here).
You can now take your original polyline and feed it through this function with increasing tolerance until the resulting encoded polyline falls below the URL length limit (which will depend on the other parameters you're passing to Static Maps).
Something like this should work:
var line = new google.maps.Polyline({path: path});
var encoded = google.maps.geometry.encoding.encodePath(line.getPath());
var tol = 0.0001;
while (encoded.length > 1800) {
path = line.simplify(tol);
line = new google.maps.Polyline({path: path});
encoded = google.maps.geometry.encoding.encodePath(path);
tol += .005;
}
Another way is to use a javascript library that can convert your content of a canvas to an image. Something like
http://html2canvas.hertzen.com/
http://www.nihilogic.dk/labs/canvas2image/
Though I am not sure about it's performance for googlemaps with overlay's.
EDIT: If you're using html2canvas, be sure to checkout this question:
https://stackoverflow.com/a/17816195/2279924
As of September 2016 the URL limit has been changed to 8192 characters in size.
https://developers.google.com/maps/documentation/static-maps/intro#url-size-restriction
There was also a feature request in public issue tracker that was marked as Fixed.

Smooth drag scrolling of an Isometric map - Html5

I have implemented a basic Isometric tile engine that can be explored by dragging the map with the mouse. Please see the fiddle below and drag away:
http://jsfiddle.net/kHydg/14/
The code broken down is (CoffeeScript):
The draw function
draw = ->
requestAnimFrame draw
canvas.width = canvas.width
for row in [0..width]
for col in [0..height]
xpos = (row - col) * tileHeight + width
xpos += (canvas.width / 2) - (tileWidth / 2) + scrollPosition.x
ypos = (row + col) * (tileHeight / 2) + height + scrollPosition.y
context.drawImage(defaultTile, Math.round(xpos), Math.round(ypos), tileWidth, tileHeight)
Mouse drag-scrolling control
scrollPosition =
x: 0
y: 0
dragHelper =
active: false
x: 0
y: 0
window.addEventListener 'mousedown', (e) =>
handleMouseDown(e)
, false
window.addEventListener 'mousemove', (e) =>
handleDrag(e)
, false
window.addEventListener 'mouseup', (e) =>
handleMouseUp(e)
, false
handleDrag = (e) =>
e.preventDefault()
if dragHelper.active
x = e.clientX
y = e.clientY
scrollPosition.x -= Math.round((dragHelper.x - x) / 28)
scrollPosition.y -= Math.round((dragHelper.y - y) / 28)
handleMouseUp = (e) =>
e.preventDefault()
dragHelper.active = false
handleMouseDown = (e) =>
e.preventDefault()
x = e.clientX
y = e.clientY
dragHelper.active = true
dragHelper.x = x
dragHelper.y = y
The Problem
As you can see from the fiddle the dragging action is ok but not perfect. How would I change the code to make the dragging action more smooth? What I would like is the point of the map you click on to stay under the mouse point whilst you drag; the same as they have done here: http://craftyjs.com/demos/isometric/
Lots of libraries help with things like this. I would recommend using the data manipulation abilities of d3 to help, for several reasons.
First, in d3, there is a drag behavior where the origin of the object is stored and a mouse position relative to the origin is computed when the drag starts. Then, you can use the absolute position of the mouse to determine where the object should be and avoid the incremental errors that occur when you use relative changes - which get far worse when you start rounding them, as above.
dragMap = (d) ->
d.x = d3.event.x # d3.event.x, y are computed relative to the origin for you!
d.y = d3.event.y
dragBehavior = d3.behavior.drag()
.origin(Object) # equivalent to (d) -> d
.on("drag", dragMap)
d3.select(canvas)
.datum(x: 0, y: 0) # Load your canvas with an arbitary origin
.call(dragBehavior) # And now you can drag it!
Second, by using d3's linear or other numerical scales you can avoid doing typical drawing math yourself which is error-prone especially when you have to do it all over the place. Before you were scaling the drag by 28. In my current approach it's unnecessary, but if you change your drawing algorithm to use tiles instead of pixels, you can change this scale which will automatically convert mouse pixels into tile sizes.
pixelToTile = d3.scale.linear()
.domain([0, 1])
.range([0, 1])
Here's your fiddle re-done with d3 help. No dragHelper and all that extraneous code necessary. All the Math.round calls are also unnecessary except the one for canvas draw, which prevents antialiasing.
http://jsfiddle.net/kHydg/23/
Isn't that much shorter and sweeter?
P.S. Isometric real-time browser games are an awesome idea. I will definitely try making one when I have time.

Expand fill of convex polygon

I have a convex polygon P1 of N points. This polygon could be any shape or proportion (as long as it is still convex).
I need to compute another polygon P2 using the original polygons geometry, but "expanded" by a given number of units. What might the algorithm be for expanding a convex polygon?
To expand a convex polygon, draw a line parallel to each edge and the given number of units away. Then use the intersection points of the new lines as the vertices of the expanded polygon. The javascript/canvas at the end follows this functional breakdown:
Step 1: Figure out which side is "out"
The order of the vertices (points) matters. In a convex polygon, they can be listed in a clockwise (CW), or a counter-clockwise (CCW) order. In a CW polygon, turn one of the edges 90 degrees CCW to obtain an outward-facing normal. On a CCW polygon, turn it CW instead.
If the turn direction of the vertices is not known in advance, examine how the second edge turns from the first. In a convex polygon, the remaining edges will keep turning in the same direction:
Find the CW normal of the first edge. We don't know yet whether it's facing inward or outward.
Compute the dot product of the second edge with the normal we computed. If the second edge turns CW, the dot product will be positive. It will be negative otherwise.
Math:
// in vector terms:
v01 = p1 - p0 // first edge, as a vector
v12 = p2 - p1 // second edge, as a vector
n01 = (v01.y, -v01.x) // CW normal of first edge
d = v12 * n01 // dot product
// and in x,y terms:
v01 = (p1.x-p0.x, p1.y-p0.y) // first edge, as a vector
v12 = (p2.x-p1.x, p2.y-p1.y) // second edge, as a vector
n01 = (v01.y, -v01.x) // CW normal of first edge
d = v12.x * n01.x + v12.y * n01.y; // dot product: v12 * n01
if (d > 0) {
// the polygon is CW
} else {
// the polygon is CCW
}
// and what if d==0 ?
// -- that means the second edge continues in the same
// direction as a first. keep looking for an edge that
// actually turns either CW or CCW.
Code:
function vecDot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
}
function vecRot90CW(v) {
return { x: v.y, y: -v.x };
}
function vecRot90CCW(v) {
return { x: -v.y, y: v.x };
}
function polyIsCw(p) {
return vecDot(
vecRot90CW({ x: p[1].x - p[0].x, y: p[1].y - p[0].y }),
{ x: p[2].x - p[1].x, y: p[2].y - p[1].y }) >= 0;
}
var rot = polyIsCw(p) ? vecRot90CCW : vecRot90CW;
Step 2: Find lines parallel to the polygon edges
Now that we know which side is out, we can compute lines parallel to each polygon edge, at exactly the required distance. Here's our strategy:
For each edge, compute its outward-facing normal
Normalize the normal, such that its length becomes one unit
Multiply the normal by the distance we want the expanded polygon to be from the original
Add the multiplied normal to both ends of the edge. That will give us two points on the parallel line. Those two points are enough to define the parallel line.
Code:
// given two vertices pt0 and pt1, a desired distance, and a function rot()
// that turns a vector 90 degrees outward:
function vecUnit(v) {
var len = Math.sqrt(v.x * v.x + v.y * v.y);
return { x: v.x / len, y: v.y / len };
}
function vecMul(v, s) {
return { x: v.x * s, y: v.y * s };
}
var v01 = { x: pt1.x - pt0.x, y: pt1.y - pt0.y }; // edge vector
var d01 = vecMul(vecUnit(rot(v01)), distance); // multiplied unit normal
var ptx0 = { x: pt0.x + d01.x, y: pt0.y + d01.y }; // two points on the
var ptx1 = { x: pt1.x + d01.x, y: pt1.y + d01.y }; // parallel line
Step 3: Compute the intersections of the parallel lines
--these will be the vertices of the expanded polygon.
Math:
A line going through two points P1, P2 can be described as:
P = P1 + t * (P2 - P1)
Two lines can be described as
P = P1 + t * (P2 - P1)
P = P3 + u * (P4 - P3)
And their intersection has to be on both lines:
P = P1 + t * (P2 - P1) = P3 + u * (P4 - P3)
This can be massaged to look like:
(P2 - P1) * t + (P3 - P4) * u = P3 - P1
Which in x,y terms is:
(P2.x - P1.x) * t + (P3.x - P4.x) * u = P3.x - P1.x
(P2.y - P1.y) * t + (P3.y - P4.y) * u = P3.y - P1.y
As the points P1, P2, P3 and P4 are known, so are the following values:
a1 = P2.x - P1.x a2 = P2.y - P1.y
b1 = P3.x - P4.x b2 = P3.y - P4.y
c1 = P3.x - P1.x c2 = P3.y - P1.y
This shortens our equations to:
a1*t + b1*u = c1
a2*t + b2*u = c2
Solving for t gets us:
t = (b1*c2 - b2*c1)/(a2*b1 - a1*b2)
Which lets us find the intersection at P = P1 + t * (P2 - P1).
Code:
function intersect(line1, line2) {
var a1 = line1[1].x - line1[0].x;
var b1 = line2[0].x - line2[1].x;
var c1 = line2[0].x - line1[0].x;
var a2 = line1[1].y - line1[0].y;
var b2 = line2[0].y - line2[1].y;
var c2 = line2[0].y - line1[0].y;
var t = (b1*c2 - b2*c1) / (a2*b1 - a1*b2);
return {
x: line1[0].x + t * (line1[1].x - line1[0].x),
y: line1[0].y + t * (line1[1].y - line1[0].y)
};
}
Step 4: Deal with special cases
There is a number of special cases that merit attention. Left as an exercise to the reader...
When there's a very sharp angle between two edges, the expanded vertex can be very far from the original one. You might want to consider clipping the expanded edge if it goes beyond some threshold. At the extreme case, the angle is zero, which suggests that the expanded vertex is at infinity, causing division by zero in the arithmetic. Watch out.
When the first two edges are on the same line, you can't tell if it's a CW or a CCW polygon by looking just at them. Look at more edges.
Non convex polygons are much more interesting... and are not tackled here.
Full sample code
Drop this in a canvas-capable browser. I used Chrome 6 on Windows. The triangle and its expanded version should animate.
canvas { border: 1px solid #ccc; }
$(function() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var context = canvas.getContext('2d');
// math for expanding a polygon
function vecUnit(v) {
var len = Math.sqrt(v.x * v.x + v.y * v.y);
return { x: v.x / len, y: v.y / len };
}
function vecMul(v, s) {
return { x: v.x * s, y: v.y * s };
}
function vecDot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
}
function vecRot90CW(v) {
return { x: v.y, y: -v.x };
}
function vecRot90CCW(v) {
return { x: -v.y, y: v.x };
}
function intersect(line1, line2) {
var a1 = line1[1].x - line1[0].x;
var b1 = line2[0].x - line2[1].x;
var c1 = line2[0].x - line1[0].x;
var a2 = line1[1].y - line1[0].y;
var b2 = line2[0].y - line2[1].y;
var c2 = line2[0].y - line1[0].y;
var t = (b1*c2 - b2*c1) / (a2*b1 - a1*b2);
return {
x: line1[0].x + t * (line1[1].x - line1[0].x),
y: line1[0].y + t * (line1[1].y - line1[0].y)
};
}
function polyIsCw(p) {
return vecDot(
vecRot90CW({ x: p[1].x - p[0].x, y: p[1].y - p[0].y }),
{ x: p[2].x - p[1].x, y: p[2].y - p[1].y }) >= 0;
}
function expandPoly(p, distance) {
var expanded = [];
var rot = polyIsCw(p) ? vecRot90CCW : vecRot90CW;
for (var i = 0; i < p.length; ++i) {
// get this point (pt1), the point before it
// (pt0) and the point that follows it (pt2)
var pt0 = p[(i > 0) ? i - 1 : p.length - 1];
var pt1 = p[i];
var pt2 = p[(i < p.length - 1) ? i + 1 : 0];
// find the line vectors of the lines going
// into the current point
var v01 = { x: pt1.x - pt0.x, y: pt1.y - pt0.y };
var v12 = { x: pt2.x - pt1.x, y: pt2.y - pt1.y };
// find the normals of the two lines, multiplied
// to the distance that polygon should inflate
var d01 = vecMul(vecUnit(rot(v01)), distance);
var d12 = vecMul(vecUnit(rot(v12)), distance);
// use the normals to find two points on the
// lines parallel to the polygon lines
var ptx0 = { x: pt0.x + d01.x, y: pt0.y + d01.y };
var ptx10 = { x: pt1.x + d01.x, y: pt1.y + d01.y };
var ptx12 = { x: pt1.x + d12.x, y: pt1.y + d12.y };
var ptx2 = { x: pt2.x + d12.x, y: pt2.y + d12.y };
// find the intersection of the two lines, and
// add it to the expanded polygon
expanded.push(intersect([ptx0, ptx10], [ptx12, ptx2]));
}
return expanded;
}
// drawing and animating a sample polygon on a canvas
function drawPoly(p) {
context.beginPath();
context.moveTo(p[0].x, p[0].y);
for (var i = 0; i < p.length; ++i) {
context.lineTo(p[i].x, p[i].y);
}
context.closePath();
context.fill();
context.stroke();
}
function drawPolyWithMargin(p, margin) {
context.fillStyle = "rgb(255,255,255)";
context.strokeStyle = "rgb(200,150,150)";
drawPoly(expandPoly(p, margin));
context.fillStyle = "rgb(150,100,100)";
context.strokeStyle = "rgb(200,150,150)";
drawPoly(p);
}
var p = [{ x: 100, y: 100 }, { x: 200, y: 120 }, { x: 80, y: 200 }];
setInterval(function() {
for (var i in p) {
var pt = p[i];
if (pt.vx === undefined) {
pt.vx = 5 * (Math.random() - 0.5);
pt.vy = 5 * (Math.random() - 0.5);
}
pt.x += pt.vx;
pt.y += pt.vy;
if (pt.x < 0 || pt.x > 400) { pt.vx = -pt.vx; }
if (pt.y < 0 || pt.y > 400) { pt.vy = -pt.vy; }
}
context.clearRect(0, 0, 800, 400);
drawPolyWithMargin(p, 10);
}, 50);
}
});
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
sample code disclaimers:
the sample sacrifices some efficiency for the sake of clarity. In your code, you may want to compute each edge's expanded parallel just once, and not twice as in here
the canvas's y coordinate grows downward, which inverts the CW/CCW logic. Things keep on working though as we just need to turn the outward normals in a direction opposite to the polygon's -- and both get flipped.
For each line segment of the original, find the midpoint m and (unit length) outward normal u of the segment. The corresponding segment of the expanded polygon will then lie on the line through m+n*u (where you want to expand the original by n) with normal u. To find the vertices of the expanded polygon you then need to find the intersection of pairs of successive lines.
If the polygon is centered on the origin simply multiply each of the points by a common scaling factor.
If the polygon is not centered on the origin then first translate so the center is on the origin, scale, and then translate it back to where it was.
After your comment
It seems you want all points to be moved the same distance away from the origin.
You can do this for each point by getting the normalised vector to this point. multiplying this by your 'expand constant' and adding the resulting vector back onto the original point.
n.b. You will still have to translate-modify-translate if the center is not also the origin for this solution.
Let the points of the polygon be A1, B1, C1... Now you have lines from A1 to B1, then from B1 to C1... We want to compute points A2, B2, C2 of the polygon P2.
If you bisect angle, for example A1 B1 C1, you will have a line which goes in the direction you want. Now you can find a point B2 on it which is the appropriate distance from B1 on bisector line.
Repeat this for all points of the polygon P1.
Look at straight skeletons. As has been implied here there are a number of tricky issues with non convex polygons that you have been mecifully spared!