Create a point in a direction In Cesiumjs - math

I am using CesiumJs. I would like to create point D at distance C from point A using the direction B
Point A => start Position (CartographicPosition {latitude, longitude; altitude})
Direction B => direction from A (HeadingPitchRoll {heading, pitch, roll})
Distance C => in meters
I am trying to get the rotation an object is facing, and create a point in front of him.
My current implementation is
public createROIfromRotation(position: Cartographic, rotation: HeadingPitchRoll): Cartographic {
const pos = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
const quat = Cesium.Transforms.headingPitchRollQuaternion(pos, rotation);
const rot = CesiumMath.QuaternionToEuler(quat);
const dir = Cesium.Cartesian3.multiplyByScalar(rot, 10, new Cesium.Cartesian3());
const roiPos = Cesium.Cartesian3.add(pos, dir, new Cesium.Cartesian3());
return Cesium.Ellipsoid.WGS84.cartesianToCartographic(roiPos);
}
But it is not rotating around the object, it is doing some kind of curve in different planes.
I would like the red point to be always in front of the truck at 10 meters distance
Exemple

I fixed using
public createROIfromRotation(position: Cartographic, rotation: HeadingPitchRoll) {
const cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
rotation.heading = rotation.heading - CesiumMath.deg2Rad(90);
const referenceFrame1 = Cesium.Transforms.headingPitchRollQuaternion(cartesianPosition, rotation);
const rotationMatrix = Cesium.Matrix3.fromQuaternion(referenceFrame1, new Cesium.Matrix3());
// Replace 1000 for changing the distance
const rotationScaled = Cesium.Matrix3.multiplyByVector(rotationMatrix, new Cesium.Cartesian3(10000, 0, 0), new Cesium.Cartesian3());
const roiPos = Cesium.Cartesian3.add(cartesianPosition, rotationScaled, new Cesium.Cartesian3());
this.store$.dispatch(new ROIsStoreActions.CreateROIPoint({position: Cesium.Ellipsoid.WGS84.cartesianToCartographic(roiPos), id: uuid()}));
}
So basically, converting everything to Matrix3 before applying my calculations

Related

Is there a way to get two parallel lines that won't change the distance in Paper js?

I need to draw two parallel lines that won't change the distance between them regardless of the inclination of the lines.
I think one possibility is by changing the start point of the line B to form a perpendicular line with the line A but I can't find a way to get the coordinates of the start or end point of a line using Path.Line
Here is a sketch that should help you reach your goal.
const createParallelLines = (start, end, distance) => {
const line = end - start;
const leftStart = start + line.rotate(90).normalize(distance / 2);
const leftEnd = end + line.rotate(90).normalize(distance / 2);
const rightStart = start + line.rotate(-90).normalize(distance / 2);
const rightEnd = end + line.rotate(-90).normalize(distance / 2);
const leftLine = new Path.Line(leftStart, leftEnd);
const rightLine = new Path.Line(rightStart, rightEnd);
return [leftLine, rightLine];
};
const [leftLine, rightLine] = createParallelLines(view.center - 100, view.center + 100, 20);
leftLine.selected = true;
rightLine.selected = true;

How to translate a vector from an offset vector

How to translate a vector from an offset vector.
I have a line with 2 points attached one on the line start and one on the end vector of the line.
I want to translate the line and the points base on the DragConstrols position and not base on the line position I am just updating the line geometry vertices and the points position base on the line start and end vectors.
Keap in mind the points are not childs of the line, all objects are childs of the Scene
The line stores the points inside the userData of the line.
My goal is to translate all this 3 objects from the drag offset Vector3
Here is the screenshots of the line with the points.
start_vector = (-140, 60, 0)
end_vector = (-70, 100, 0)
I know the line start vector before the user drags the line v1 = (-140, 60, 0) and I
know the line end vector before the drag v2 = (-70, 100, 0)
Now when the user drags the line with the DragConstrols I dont let the dragControls to change the line position I get the dragConstrol vector3 and I want to translate the line vetrices base on that vector.
The DragControls allways start from (0, 0, 0) so I try to add the line vectors (v1, v2) with the position but I get this result.
Can someone show me how to set the line start and end vector from the dragControls position.
Or how to translate vectors from offset vectors.
Thank you.
My code so far.
Keep in mind the line is a Line2 (fat line) three/examples/jsm/lines/Line2
class NewLine extends Line2 {
private _start = new Vector3();
private _end = new Vector3();
/** The viewport width */
public viewportWidth: number;
/** The viewport height */
public viewportHeight: number;
/** The line3 */
public line3 = new Line3();
public get start() { return this._start; }
public set start(v: Vector3) {
this._start = v;
this.line3.set(v, this._end);
this.geometry['setPositions']([
v.x,
v.y,
v.z,
this._end.x,
this._end.y,
this._end.z
]);
this.geometry['verticesNeedUpdate'] = true; // maybe i don't need that
this.geometry.computeBoundingSphere();
this.computeLineDistances();
}
public get end() { return this._end; }
public set end(v: Vector3) {
this._end = v;
this.line3.set(this._start, v);
this.geometry['setPositions']([
this._start.x,
this._start.y,
this._start.z,
v.x,
v.y,
v.z,
]);
this.geometry['verticesNeedUpdate'] = true; // maybe i don't need that
this.geometry.computeBoundingSphere();
this.computeLineDistances();
}
constructor( start: Vector3, end: Vector3 ) {
super();
// create geometry
const geometry = new LineGeometry();
geometry.setPositions([
start.x, start.y, start.z,
end.x, end.y, end.z
]);
this.geometry = geometry;
// create material
const material = new LineMaterial({
color: 0x000000,
linewidth:5,
depthTest: false, // new
vertexColors: false,
});
this.material = material;
this.computeLineDistances();
this.scale.set( 1, 1, 1 );
this.line3.set(start, end);
}
}
/**
* Translates a line base on DragControls position.
* line: The NewLine
* position: The new Vector3 position from dragControls
*/
translateLineFromVector(line: NewLine, position: Vector3) {
const v1 = line.start;
const v2 = line.end;
const offset_start = line.start.clone().add( position ).sub(line.position);
const offset_end = line.end.clone().add( position ).sub(line.position);
line.start.copy( offset_start );
line.end.copy( offset_end );
}
Standard approach for dragging:
On mouse down(X,Y):
If Clicked at object and not Dragging:
Dragging = True
X0 = X
Y0 = Y
//important - remember object coordinates at this moment!
V1_0 = V1
V2_0 = V2
On mouse moving (X,Y) :
If Dragging:
//Draw object at coordinates shifted by (X - X0), (Y - Y0)
//from initial position, not from the current one
V1.X = V1_0.X + X - X0
V1.Y = V1_0.Y + Y - Y0
same for V2
DrawObject(V1,V2)
On Mouse Up(X,Y):
If Dragging:
Fragging = False
Fix positions V1,V2 if needed

Draw an ellipse arc between two points in Three.js

I've been trying to draw an ellipse arc between two arbitrary points but my implementation is not working in some situations.
Because a part of this is involves mathematics, I started by asking this question.
Basically, given two points and the center, you can always get an ellipse if you allow rotation, except for cases where the points are collinear.
The solution proposed to that question is to:
Translate the center to the origin, translating both points by the same vector.
Rotate both points by the angle -alpha which is the simetric of the angle of the largest vector with the positive x-semiaxis.
Solve the ellipse equation to find its radiuses (system of two equations with two unknowns).
Define the ellipse
Rotate back the ellipse with the angle alpha and translate back to its center.
However, I'm having trouble implementing this in Three.js.
The documentation for the EllipseCurve lists the expected parameters. I assume the starting angle to always be zero and then set the end angle to either the angle between the two vectors or its simetric. I also want the arc to always be the smallest (i.e., if the angle is bigger than 180ยบ, I'd use the complementary arc). I assume the center of the ellipse to be the middle point between the centers of the shape's bounding boxes.
This is my example code:
https://jsfiddle.net/at5dc7yk/1/
This example tries to create an arc from a vertex in the original shape and the same vertex in the modified shape.
Code regarding the ellipse arc is under the class EllipseArc and you can mess with the transformation applied to the object in line 190.
It works for some cases:
But not all:
Just an idea from scratch, not the ultimate solution.
When you clone and translate object, to build an arc between two respective points you'll need their coordinates in world coordinate system, and a coordinate of the middle point between centroids of objects.
Find the mid point between points in world space (between start and end vectors).
Find its projection on the vector of translation (this is the center of an arc).
Find the angle between vectors that you get by subtraction the result center vector from each of them.
Divide an angle by amount of divisions - you'll get the step value.
Get the end vector as the base and rotate it around an axis (which is the normal of a triangle, built with start, center, end vectors) in a loop, multiplying that step angle value with the number of the current iteration.
Code example:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 10000);
camera.position.set(0, 0, 150);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var shapeGeom = new THREE.ShapeBufferGeometry(new THREE.Shape(californiaPts));
shapeGeom.center();
shapeGeom.scale(0.1, 0.1, 0.1);
var shapeMat = new THREE.MeshBasicMaterial({
color: "orange"
});
var shape = new THREE.Mesh(shapeGeom, shapeMat);
shape.updateMatrixWorld();
scene.add(shape);
var shapeClone = shape.clone();
shapeClone.position.set(25, 25, 0);
shapeClone.updateMatrixWorld();
scene.add(shapeClone);
var center = new THREE.Vector3().lerpVectors(shapeClone.position, shape.position, 0.5);
var vecStart = new THREE.Vector3();
var vecEnd = new THREE.Vector3();
var pos = shapeGeom.getAttribute("position");
for (let i = 0; i < pos.count; i++) {
vecStart.fromBufferAttribute(pos, i);
shape.localToWorld(vecStart);
vecEnd.fromBufferAttribute(pos, i);
shapeClone.localToWorld(vecEnd);
makeArc(center, vecStart, vecEnd);
}
function makeArc(center, start, end) {
console.log(center, start, end);
let vM = new THREE.Vector3().addVectors(start, end).multiplyScalar(0.5);
let dir = new THREE.Vector3().subVectors(end, start).normalize();
let c = new THREE.Vector3().subVectors(vM, center);
let d = c.dot(dir);
c.copy(dir).multiplyScalar(d).add(center); // get a center of an arc
let vS = new THREE.Vector3().subVectors(start, c);
let vE = new THREE.Vector3().subVectors(end, c);
let a = vS.angleTo(vE); // andgle between start and end, relatively to the new center
let divisions = 100;
let aStep = a / divisions;
let pts = [];
let vecTemp = new THREE.Vector3();
let tri = new THREE.Triangle(start, c, end);
let axis = new THREE.Vector3();
tri.getNormal(axis); // get the axis to rotate around
for (let i = 0; i <= divisions; i++) {
vecTemp.copy(vE);
vecTemp.applyAxisAngle(axis, aStep * i);
pts.push(vecTemp.clone());
}
let g = new THREE.BufferGeometry().setFromPoints(pts);
let m = new THREE.LineDashedMaterial({
color: 0xff0000,
dashSize: 1,
gapSize: 1
});
let l = new THREE.Line(g, m);
l.computeLineDistances();
l.position.copy(c);
scene.add(l);
}
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script>
var californiaPts = [
new THREE.Vector2(610, 320),
new THREE.Vector2(450, 300),
new THREE.Vector2(392, 392),
new THREE.Vector2(266, 438),
new THREE.Vector2(190, 570),
new THREE.Vector2(190, 600),
new THREE.Vector2(160, 620),
new THREE.Vector2(160, 650),
new THREE.Vector2(180, 640),
new THREE.Vector2(165, 680),
new THREE.Vector2(150, 670),
new THREE.Vector2(90, 737),
new THREE.Vector2(80, 795),
new THREE.Vector2(50, 835),
new THREE.Vector2(64, 870),
new THREE.Vector2(60, 945),
new THREE.Vector2(300, 945),
new THREE.Vector2(300, 743),
new THREE.Vector2(600, 473),
new THREE.Vector2(626, 425),
new THREE.Vector2(600, 370),
new THREE.Vector2(610, 320)
];
</script>
If you don't translate, and just rotate an object, in this case you don't need to compute a new center for each arc, just omit that step, as all the centers are equal to the centroid of the object.
I hope I explained it in more or less understandable way ^^

Create 3rd person camera position calculation with quaternions

I want to create a 3rd person camera similiar to example. The camera should stick behind the object and rotate if the rotation difference between camera and object is too high (maybe above ten percent).
This is my actual camera code:
var targetPosition = this.getTargetPosition();
var targetRotation = this.getTargetRotation();
var tmpQuaternion = new THREE.Quaternion();
tmpQuaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), 180 * (Math['PI'] / 180));
this.camera.quaternion = targetRotation;
this.camera.position = targetPosition;
this.camera.quaternion.multiplySelf(tmpQuaternion);
this.camera.quaternion.normalize();
this.camera.updateMatrix();
this.camera.translateZ(200);
this.camera.translateY(50);
But there are several problems right now. The camera quaternion should not set directly to the target rotation. But I dont know how to calculate the difference between camera quaternion and target quaternion and use maybe this if the distance is too high:
var qm = new THREE.Quaternion();
THREE.Quaternion.slerp(targetRotation, this.camera.quaternion, qm, time);
this.camera.quaternion = qm;
The second problem is the position itself. Currently I set camera position to the object position and translate it back to view behind, but the translation should be already in target position and the camera position should be translated to the target position.
Update 1: I made an example html: http://ssachtleben.github.com/CameraProblem/
Update 2: I made some progress now. Seems like I get quaternion difference with this function:
getAxisAngle = function(quaternion1, quaternion2) {
var tmpQuaternion = new THREE.Quaternion();
tmpQuaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), 180 * (Math['PI'] / 180));
var tmpRotation1 = quaternion1.clone();
tmpRotation1.multiplySelf(tmpQuaternion);
tmpRotation1.normalize();
var tmpRotation2 = quaternion2.clone();
if (tmpRotation2.w > 1) {
tmpRotation2.normalize();
}
var angle1 = 2 * Math['acos'](tmpRotation1.w);
var angle2 = 2 * Math['acos'](tmpRotation2.w);
var diff = angle1 > angle2 ? angle1 - angle2 : angle2 - angle1;
return diff;
};
But know I need to freeze the axis if the angle difference is too high. How can I do this?
Any help would be appreciated.
Ok finally the camera is fixed and works as excepted:
var targetPosition = this.getTargetPosition();
var targetRotation = this.getTargetRotation();
var tmpQuaternion = new THREE.Quaternion();
tmpQuaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), 180 * (Math['PI'] / 180));
targetRotation.multiplySelf(tmpQuaternion);
targetRotation.quaternion.normalize();
var qm = new THREE.Quaternion();
THREE.Quaternion.slerp(this.camera.quaternion, targetRotation, qm, 0.07);
this.camera.quaternion = qm;
this.camera.quaternion.normalize();

Bounding Spheres move farther than sphere object

I have a program that I'm making with others and I ran into a problem. I'm working on adding in polygon models into our scene in an XNA window. I have that part complete. I also have bounding spheres(I know I tagged as bounding-box but there is no bounding sphere tag) drawing around each polygon. My problem is when I move the polygons around the 3D space the bounding spheres move twice as much as the polygons. I imagine its something within my polygon matrices that I use to create the bounding sphere that makes it move twice as much but that is only speculation.
So just to clarify I'll give you an example of my problem. If I hold down D to move a polygon along the X axis. (model.position.X--;) The polygon moves as expected to but the bounding sphere around the polygon moves twice as much. Thanks for the help guys!
Here is how I draw the models and the bounding spheres:
public void Draw(Matrix view, Matrix projection, bool drawBoundingSphere)
{
Matrix translateMatrix = Matrix.CreateTranslation(position);
Matrix worldMatrix = translateMatrix * Matrix.CreateScale(scaleRatio);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix * modelAbsoluteBoneTransforms[mesh.ParentBone.Index];
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
if (drawBoundingSphere)
{
// the mesh's BoundingSphere is stored relative to the mesh itself.
// (Mesh space). We want to get this BoundingSphere in terms of world
// coordinates. To do this, we calculate a matrix that will transform
// from coordinates from mesh space into world space....
Matrix world = modelAbsoluteBoneTransforms[mesh.ParentBone.Index] * worldMatrix;
// ... and then transform the BoundingSphere using that matrix.
BoundingSphere sphere = BoundingSphereRenderer.TransformBoundingSphere(mesh.BoundingSphere, world);
// now draw the sphere with our renderer
BoundingSphereRenderer.Draw(sphere, view, projection);
}
}
And here is the BoundingSphereRenderer Code:
private static VertexBuffer vertexBuffer;
private static BasicEffect effect;
private static int lineCount;
public static void Initialize(GraphicsDevice graphicsDevice, int sphereResolution)
{
// create our effect
effect = new BasicEffect(graphicsDevice);
effect.LightingEnabled = false;
effect.VertexColorEnabled = true;
// calculate the number of lines to draw for all circles
lineCount = (sphereResolution + 1) * 3;
// we need two vertices per line, so we can allocate our vertices
VertexPositionColor[] vertices = new VertexPositionColor[lineCount * 2];
// compute our step around each circle
float step = MathHelper.TwoPi / sphereResolution;
// used to track the index into our vertex array
int index = 0;
//create the loop on the XY plane first
for (float angle = 0f; angle < MathHelper.TwoPi; angle += step)
{
vertices[index++] = new VertexPositionColor(new Vector3((float)Math.Cos(angle), (float)Math.Sin(angle), 0f), Color.Blue);
vertices[index++] = new VertexPositionColor(new Vector3((float)Math.Cos(angle + step), (float)Math.Sin(angle + step), 0f), Color.Blue);
}
//next on the XZ plane
for (float angle = 0f; angle < MathHelper.TwoPi; angle += step)
{
vertices[index++] = new VertexPositionColor(new Vector3((float)Math.Cos(angle), 0f, (float)Math.Sin(angle)), Color.Red);
vertices[index++] = new VertexPositionColor(new Vector3((float)Math.Cos(angle + step), 0f, (float)Math.Sin(angle + step)), Color.Red);
}
//finally on the YZ plane
for (float angle = 0f; angle < MathHelper.TwoPi; angle += step)
{
vertices[index++] = new VertexPositionColor(new Vector3(0f, (float)Math.Cos(angle), (float)Math.Sin(angle)), Color.Green);
vertices[index++] = new VertexPositionColor(new Vector3(0f, (float)Math.Cos(angle + step), (float)Math.Sin(angle + step)), Color.Green);
}
// now we create the vertex buffer and put the vertices in it
vertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.WriteOnly);
vertexBuffer.SetData(vertices);
}
public static void Draw(this BoundingSphere sphere, Matrix view, Matrix projection)
{
if (effect == null)
throw new InvalidOperationException("You must call Initialize before you can render any spheres.");
// set the vertex buffer
effect.GraphicsDevice.SetVertexBuffer(vertexBuffer);
// update our effect matrices
effect.World = Matrix.CreateScale(sphere.Radius) * Matrix.CreateTranslation(sphere.Center);
effect.View = view;
effect.Projection = projection;
// draw the primitives with our effect
effect.CurrentTechnique.Passes[0].Apply();
effect.GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, lineCount);
}
public static BoundingSphere TransformBoundingSphere(BoundingSphere sphere, Matrix transform)
{
BoundingSphere transformedSphere;
// the transform can contain different scales on the x, y, and z components.
// this has the effect of stretching and squishing our bounding sphere along
// different axes. Obviously, this is no good: a bounding sphere has to be a
// SPHERE. so, the transformed sphere's radius must be the maximum of the
// scaled x, y, and z radii.
// to calculate how the transform matrix will affect the x, y, and z
// components of the sphere, we'll create a vector3 with x y and z equal
// to the sphere's radius...
Vector3 scale3 = new Vector3(sphere.Radius, sphere.Radius, sphere.Radius);
// then transform that vector using the transform matrix. we use
// TransformNormal because we don't want to take translation into account.
scale3 = Vector3.TransformNormal(scale3, transform);
// scale3 contains the x, y, and z radii of a squished and stretched sphere.
// we'll set the finished sphere's radius to the maximum of the x y and z
// radii, creating a sphere that is large enough to contain the original
// squished sphere.
transformedSphere.Radius = Math.Max(scale3.X, Math.Max(scale3.Y, scale3.Z));
// transforming the center of the sphere is much easier. we can just use
// Vector3.Transform to transform the center vector. notice that we're using
// Transform instead of TransformNormal because in this case we DO want to
// take translation into account.
transformedSphere.Center = Vector3.Transform(sphere.Center, transform);
return transformedSphere;
}

Resources