Create a ring on the surface of a sphere in threejs - three.js

I have a sphere in threejs, and I'd like a ring to animate over the top of it.
I have the following progress:
https://codepen.io/EightArmsHQ/pen/zYRdQOw/2919f1a1bdcd2643390efc33bd4b73c9?editors=0010
In the animate function, I call:
const scale = Math.cos((circlePos / this.globeRadius) * Math.PI * 0.5);
console.log(scale);
this.ring.scale.set(scale, scale, 1);
My understanding is that the sin and cos functions are exactly what I need to work out how far around the circle the ring has gotten to. However, the animation actually shows the ring fall inside the sphere, before eventually hitting the 0 scale at the outside of the sphere.
Ideally, I'd also like to just be changing the radius of the sphere but I cannot work out how to do that either, so I think it may be an issue of using the scale function.
How can I keep the ring on the surface of the sphere?

Not quite. Consider this:
You have a right triangle whose bases are your x and y, with a hypotenuse of r = globeRadius. So by Pythagoras' theorem, we have:
x2 + y2 = r2.
So if we solve for the height, y, we get:
y = √(r2 - x2).
Thus, in your code, you could write it e.g. like this:
const scale = Math.sqrt(this.globeRadius * this.globeRadius - circlePos * circlePos);
However, this is the scale in terms of world units, not relative to the objects. So for this to work, you need to either divide by your radius again, or just initialise your ring with radius 1:
this.ringGeometry = new THREE.RingGeometry(1, 1.03, 32);
Here I gave it an arbitrary ring width of 0.03 - you may of course adjust it to your own needs.

Related

d3 geo projection transitions from orthographic to X

I'm working on an educational map project in which different map projections are displayed. I'd like to implement a morph transition between choosing different projections.
I've found a great example how to implement it, and I've had not much troubles to recreate it. Unfortunately, I also need the capability to clip the projections. This works flawlessly with the target states, but not when morphing the projections.
You can see it in this example when choosing "orthographic" as first projection and for example "equirectangular" as second one:
https://bl.ocks.org/alexmacy/082cb12c8f4d5c0d5c4445c16a3db383
The clipping path follows the darker line instead of the current map extent. Is there a way to implement it correctly?
This is a lot trickier to implement than appears, I remember looking at this a few years back. The cleanest solution is to create a new preclipping function that determines which portions of the projected earth should be behind/covered by portions closer to the origin. But it turns out this is relatively hard to define - at least my me - and also hard to use in a new preclipping function.
Instead we could cheat. There are a couple ways, I'll propose one that nearly does the trick - you can still see some overlap though. We'll use d3's antimeridian preclipping to make sure no features stretch over the antimeridian, then we'll use a clip angle to remove portions of the earth that need to be removed.
Setting Clip Angle
When the hybrid projection is purely orthographic, clipping angle is great: the clip angle is the same in all directions. Here it should be 90 degrees.
When the equirectangular is dominant in the hybrid projection, the clipping angle is not needed (I use an angle of 180 degrees, which doesn't clip anything below). This is because the entire earth should still be visible.
But otherwise, the hybrid clip angle is not the same in all directions - this is why this is not a perfect solution. However, it does remove nearly all the overlap. So as we go from the projection being mostly equirectangular to wholly orthogrpahic, we slowly reduce the clip angle.
Example
Starting with an equirectangular projection and transitioning to an orthographic, we'll start transitioning the clipAngle from 180 degrees to 90 degrees only once we get 40 percent of the way trough the transition:
function getProjection(d) {
var clip = Math.PI; // Starting with 180 degrees: don't clip anything.
var projection = d3.geoProjection(project)
.rotate([posX, posY])
.fitExtent([[10, 10], [width - 10, height - 10]], {
type: "Sphere"
})
// Apply the two pre clipping functions:
.preclip( function(stream){
stream = d3.geoClipAntimeridian(stream) // cut antimeridian
return d3.geoClipCircle(clip)(stream) // apply clip angle
})
var path = d3.geoPath(projection);
function project(λ, φ) {
λ *= 180 / Math.PI,
φ *= 180 / Math.PI;
var p0 = projections[0]([λ, φ]),
p1 = projections[1]([λ, φ]);
// Don't actually clip anything until t == 0.4
if(t > 0.4) {
clip = Math.PI/2 + (0.60-(t-0.4)) * Math.PI/2
}
return [
(1 - t) * p0[0] + t * p1[0],
(1 - t) * -p0[1] + t * -p1[1]
];
}
return path(d)
}
Here's an example.
Great answer Andrew Reid! I just made one small change. I removed the t > 0.4 if statement and used this clip for transitioning into an orthogrpahic projection:
clip = Math.PI/2 + (1 - t) * Math.PI/2
.. and this clip for transitioning out of an orthogrpahic projection:
clip = Math.PI/2 + t * Math.PI/2
I like this because it's slightly cleaner, is a 'catch-all' for any t value and having the reverse is also useful.

How do I calculate the position on a circle based on a progress value?

Currently I'm working on a orbit system for a game. I've got it so an object will move along a circle based on a progress value that'll be between 0.0 and 1.0 (0.5 being half way around the circle). I calculate this like this:
float angle = Mathf.Deg2Rad * 360 * t;
float xPos = Mathf.Sin(angle) * xAxis;
float yPos = Mathf.Cos(angle) * yAxis;
return new Vector3(xPos, yPos, 0.0f);
With t simply being deltatime and the xAxis/yAxis variables being the radius of the circle.
What I'm a little stuck on currently though is how I could possibly get the progress around the circle based on a poisition. So if I have an object that hits the bottom of the circle, how do I calculate that to be a progress of 0.5?
First step: Find out the angle of your given position with the y-axis.
Second step: Calculate the fraction of a full circle (360 degs) that your angle has.
First step involves a bit of trigonometry, and there you have to make sure to get the right type of angle based on what quadrant you're in. Second step should be trivial then.
You can check out the atan2 function that's available in many programming languages: https://en.wikipedia.org/wiki/Atan2
It gives the angle between a point (x, y) and the positive x-axis. So then in your case, depending on where your circle starts, you'd then shift that by 90 degrees to get the angle with the positive y-axis. Other than that it should work fine though.

distributing 2d vector points around a sphere

I'm using d3.js to create a bubble chart, which I'm then trying to wrap partially around a sphere in three.js. I'd like the end result to look like a dandelion, as pictured here:
The bubble chart on a 2d plane looks like this. I'm trying to wrap it half-way around a sphere to create that dandelion effect.
I have three semi-working solutions, yet none exactly follow the curve of a sphere when viewed from the side
Example A - zCoord = new THREE.Vector2(xCoord, yCoord).length();
This gives a linear looking cone effect, not a curved effect. I think I somehow need to calculate a quadratic curves instead of a linear line but I'm stuck trying to figure it out.
Example B - zCoord = (diameter / 2 ) * Math.cos(phi);
This uses code from the periodic table of elements and spirals the data along the z axis.
Example C - Close to what I want, but it doesn't wrap around sphere enough, and everything seems to bunch up together. I'd like to preserve the padding or space around the mini-spheres
zCoord = (diameter / 2 );
var vector = new THREE.Vector3(xCoord, yCoord, zCoord).normalize().multiplyScalar(diameter / 2);
jsfiddle link to try out the methods
May not be the most efficient solution, but I did get pretty close using Mercator Projection. It's almost like I'm UV wrapping, but with Vector2 points.
My solution involved mapping X,Y coords to latitude and longitude, then projecting them onto a sphere using mercator projection.
var latitude = data[i].position.x / R;
var longitude = (2 * Math.atan(Math.exp(data[i].position.y / R))) - (Math.PI / 2);
xCoord = R * Math.cos(latitude) * Math.cos(longitude);
yCoord = R * Math.cos(latitude) * Math.sin(longitude);
zCoord = R * Math.sin(latitude);
link to jsfiddle showing tweening from 2d > 3d

WebGL - What are some performant ways to select 3d objects? [duplicate]

I'm building a boardgame in WebGL. The board can be rotated/zoomed. I need a way to translate a click on the canvas element (x,y) into the relevant point in 3D space (x, y, z). The ultimate result is that I want to know the (x, y, z) coordinate that contains the point that touches the object closest to the user. For instance, the user clicks a piece, and you imagine a ray traveling through 3D space that goes through both the piece and the game board, but I want the (x, y, z) coord of the piece at the point where it was touched.
I feel like this must be a very common problem, but I can't seem to find a solution in my googles. There must be some way to project the current view of the 3D space into 2D so you can map each point in 2D space to the relevant point in 3D space. I want to the user to be able to mouse over a space on the board, and have the spot change color.
You're looking for an unproject function, which converts screen coordinates into a ray cast from the camera position into the 3D world. You must then perform ray/triangle intersection tests to find the closest triangle to the camera which also intersects the ray.
I have an example of unprojecting available at jax/camera.js#L568 -- but you'll still need to implement ray/triangle intersection. I have an implementation of that at jax/triangle.js#L113.
There is a simpler and (usually) faster alternative, however, called 'picking'. Use this if you want to select an entire object (for instance, a chess piece), and if you don't care about where the mouse actually clicked. The WebGL way to do this is to render the entire scene in various shades of blue (the blue is a key, while red and green are used for unique IDs of the objects in the scene) to a texture, then read back a pixel from that texture. Decoding the RGB into the object's ID will give you the object that was clicked. Again, I've implemented this and it's available at jax/world.js#L82. (See also lines 146, 162, 175.)
Both approaches have pros and cons (discussed here and in some of the comments after) and you'll need to figure out which approach best serves your needs. Picking is slower with huge scenes, but unprojecting in pure JS is extremely slow (since JS itself isn't all that fast) so my best recommendation would be to experiment with both.
FYI, you could also look at the GLU project and unproject code, which I based my code loosely upon: http://www.opengl.org/wiki/GluProject_and_gluUnProject_code
I'm working on this problem at the moment - the approach I'm taking is
Render objects to pick buffer each with unique colour
Read buffer pixel, map back to picked object
Render picked object to buffer with each pixel colour a function of Z-depth
Read buffer pixel, map back to Z-depth
We have picked object and approximate Z for the pick coords
This is the working demo
function onMouseUp(event) {
event.preventDefault();
x_pos = (event.clientX / window.innerWidth) * 2 - 1;
y_pos = -(event.clientY / window.innerHeight) * 2 + 1;
z_pos = 0.5;
var vector = new THREE.Vector3( x_pos , y_pos , z_pos );
var projector = new THREE.Projector();
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(intersectObjects);
if (intersects.length > 0) {
xp = intersects[0].point.x.toFixed(2);
yp = intersects[0].point.y.toFixed(2);
zp = intersects[0].point.z.toFixed(2);
destination = new THREE.Vector3( xp , yp , zp );
radians = Math.atan2( ( driller.position.x - xp) , (driller.position.z - zp));
radians += 90 * (Math.PI / 180);
console.log(radians);
var tween = new TWEEN.Tween(driller.rotation).to({ y : radians },200).easing(TWEEN.Easing.Linear.None).start();
}
weissner-doors.de/drone/
culted from one of the threads.
not sure about (x,y,z) but you can get the canvas(x,y) using
getBoundingClientRect()
function getCanvasCoord(){
var mx = event.clientX;
var my = event.clientY;
var canvas = document.getElementById('canvasId');
var rect = canvas.getBoundingClientRect();// check if your browser supports this
mx = mx - rect.left;
my = my - rect.top;
return {x: mx , y: my};
}

How to place svg shapes in a circle?

I'm playing a bit with D3.js and I got most things working. But I want to place my svg shapes in a circle. So I will show the difference in data with color and text. I know how to draw circles and pie charts, but I want to basically have a circle of same size circles. And not have them overlap, the order is irrelevant. I don't know where to start, to find out the x & y for each circle.
If I understand you correctly, this is a fairly standard math question:
Simply loop over some angle variable in the appropriate step size and use sin() and cos() to calculate your x and y values.
For example:
Let's say you are trying to place 3 objects. There are 360 degrees in a circle. So each object is 120 degrees away from the next. If your objects are 20x20 pixels in size, place them at the following locations:
x1 = sin( 0 * pi()/180) * r + xc - 10; y1 = cos( 0 * pi()/180) * r + yc - 10
x2 = sin(120 * pi()/180) * r + xc - 10; y2 = cos(120 * pi()/180) * r + yc - 10
x3 = sin(240 * pi()/180) * r + xc - 10; y3 = cos(240 * pi()/180) * r + yc - 10
Here, r is the radius of the circle and (xc, yc) are the coordinates of the circle's center point. The -10's make sure that the objects have their center (rather than their top left corner) on the circle. The * pi()/180 converts the degrees to radians, which is the unit most implementations of sin() and cos() require.
Note: This places the shapes equally distributed around the circle. To make sure they don't overlap, you have to pick your r big enough. If the objects have simple and identical boundaries, just lay out 10 of them and figure out the radius you need and then, if you need to place 20, make the radius twice as big, for 30 three times as big and so forth. If the objects are irregularly shaped and you want to place them in the optimal order around the circle to find the smallest circle possible, this problem will get extremely messy. Maybe there's a library for this, but I don't have one in the top of my head and since I haven't used D3.js, I'm not sure whether it will provide you with this functionality either.
Here's another approach to this, for shapes of arbitrary size, using D3's tree layout: http://jsfiddle.net/nrabinowitz/5CfGG/
The tree layout (docs, example) will figure out the x,y placement of each item for you, based on a given radius and a function returning the separation between the centers of any two items. In this example, I used circles of varying sizes, so the separation between them is a function of their radii:
var tree = d3.layout.tree()
.size([360, radius])
.separation(function(a, b) {
return radiusScale(a.size) + radiusScale(b.size);
});
Using the D3 tree layout solves the first problem, laying out the items in a circle. The second problem, as #Markus notes, is how to calculate the right radius for the circle. I've taken a slightly rough approach here, for the sake of expediency: I estimate the circumference of the circle as the sum of the diameters of the various items, with a given padding in between, then calculate radius from the circumference:
var roughCircumference = d3.sum(data.map(radiusScale)) * 2 +
padding * (data.length - 1),
radius = roughCircumference / (Math.PI * 2);
The circumference here isn't exact, and this will be less and less accurate the fewer items you have in the circle, but it's close enough for this purpose.

Resources