Re-positioning a Rigid Body in Bullet Physics - position

I am writing a character animation rendering engine that uses Bullet Physics as a physics simulation engine.
A sequence will start out with no model on the screen, then an animation will be assigned to that model, the model will be moved to frame 0 of the animation, and the engine will begin rendering the model with the animation.
What is the correct way to re-position the rigid bodies on the character model when it is initialized at frame 0?
Currently I am using this code, which is called immediately after the animation is assigned to the model and the bones are moved to the frame 0 position:
_world->removeRigidBody(_body);
bool k = (_type == Kinematics);
_body->setCollisionFlags(_body->getCollisionFlags() & ~btCollisionObject::CF_NO_CONTACT_RESPONSE);
btTransform tr = BulletPhysics::ConvertD3DXMatrix(&(_bone->getCombinedTrans()));
tr *= _trans;
_body->setCenterOfMassTransform(tr);
_body->clearForces();
_body->setLinearVelocity(btVector3(0,0,0));
_body->setAngularVelocity(btVector3(0,0,0));
_world->addRigidBody(_body, _groupID, _groupMask);
The issue is that sometimes this works, and other times not. For an example, take a skirt of a model. Sometimes it will show up in the natural position, other times slightly misaligned and it will fall into place, and other times it shows up completely clipped through the body, as if collision was turned off and some force pushed it in that direction. This does make sense most of the time, because in the test animation I am using the model's initial position is in the center of the screen, but the animation starts off the left side of the screen. Does anyone know how to solve this?
I know the bones on the skirt are not the problem, because I turned off physics and forced it to manually update the bone positions each frame, and everything was in the correct positions throughout the entire animation.
EDIT: I also have constraints, might that be what's causing this?

Here is my reposition method that does exactly this.
void LimbBt::reposition(btVector3 position,btVector3 orientation) {
btTransform initialTransform;
initialTransform.setOrigin(position);
initialTransform.setRotation(orientation);
mBody->setWorldTransform(initialTransform);
mMotionState->setWorldTransform(initialTransform);
}
The motion state mMotionState is the motion state you created for the btRigidBody in the beginning. Just add your clearForces() and velocities to it to stop the body from moving on from the new position as if it went through a portal. That should do it. It works nicely with me here.
Edit: The constraints will adapt if you reposition all rigidbodies correctly. For that purpose, it is easy to calculate the relative position and reposition the whole constrained rigidbody construct according to that. If you do it incorrectly, you will get severe twitching, as the constraints will try to adjust you construct numerically, causing high forces if the constraint gaps are large.
Edit2: Another issue is that if you need deterministic behavior (every time you reset your bodies, they should fall exactly the same), then you will have to kill your old dynamicsWorld, recreate it and add all the bodies again. The world stores some information about the bodies that just can not be cleared for now. This might change in the future as bullet4 is going to support deterministic resets. But for now, if you do experiments with deterministic resets, you need to drop the world and recreate it.
source: discussion with Erwin Coumans, the developer of Bullet Physics.

I can't tell you what causes the unusual outcome when moving rigid bodies but I can definitely sympathize!
There are three things you'll need to do in order to solve this:
Convert your rigid bodies to kinematic ones
Adjust the World Transform of the bodies motion state and NOT the rigid body
Convert the kinematic body back to a rigid body

A short tested code snippet effectively teleporting a rigid body by updating its motion state to its new position and orientation, plus nullifying all velocities and forces acting upon it.
void teleport(btVector3 position, btQuaternion& orientation) const {
btTransform transform;
transform.setIdentity();
transform.setOrigin(position);
transform.setRotation(orientation);
m_rigidBodyVehicle->setWorldTransform(transform);
m_rigidBodyVehicle->getMotionState()->setWorldTransform(transform);
m_rigidBodyVehicle->setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f));
m_rigidBodyVehicle->setAngularVelocity(btVector3(0.0f, 0.0f, 0.0f));
m_rigidBodyVehicle->clearForces();
}

Related

Fastest way to deal with many sprites in bevy-engine

I am building a Cellular Automata visualization "game" with Rust and the BevyEngine. Currently, when initializing the world, I spawn a sprite for every cell. Within each update the sprites color is changed according to wether it is alive or dead.
for (grid_pos, mut color_mat) in query.iter_mut() {
let cell_state = world.0[grid_pos.1][grid_pos.0];
match cell_state {
0 => *color_mat = materials.dead_cell.clone(),
1 => *color_mat = materials.alive_cell.clone(),
_ => (),
}
}
The thing is, when dealing with a larger and larger map, the number of sprites gets very high. So I wondered if it might be faster when I only spawn a sprite in the position of a living cell and remove it when the cell dies.
So my question is: Is it faster if I spawn all a sprite for every grid position OR is the better way to only spawn a sprite when a cell is alive and remove it when the cell dies.
I'm not familiar with Bevy's performance characteristics, but it is generally the case that to get good performance for drawing a cellular automaton, you don't want to be storing "sprite" objects for every cell, but an array of just the cell states, and drawing them in some kind of efficient batch form.
The state of of a cellular automaton is basically an image (possibly one with rather chunky pixels). So, treat it that way: copy the cell states into a texture and then draw the texture. If you want the cells to appear fancier than little squares, program the fragment shader to do that. (For example, you can read the CA-state texture and use it to decide which of several other textures to draw within the bounds of one square.)
This may or may not be necessary to get acceptable performance for your use case, but it will certainly be faster than managing individual sprites.

Get velocity or deviation of hand, during manipulation on Hololens2 with MRTK2.5

What I'm trying to do:
I am using MRTK2.5.1 / Hololens2 and the OnlineMaps asset in Unity. I want to use my hand (by either touching map, or pointer from distance) to scroll the map. i.e. tap/grip the map, then drag hand around x/z plane.
What I've done previously:
With holotoolkit/hololens1, this was easily done with a listener for manipulation events.
The OnManipulationChanged event provided me with a CumulativeDelta value of how the hand position had changed since the start of the manipulation.
What I've tried in MRTK2.5:
I started off with ManipulationHandler, which gives me the pointer in eventdata. The pointer->controller has a velocity value, but that's always 0,0,0. I couldn't see anything else obvious relating to velocity or delta position of the thing (hand) triggering the manipulation.
The PointerHandler script has an OnPointerDragged event, but again has no property that looks like a velocity or delta position of hand.
Do i need to be using Gestures?
Not looking for code, just a brief explanation of the correct approach to get the hand velocity or deviation of hand, once the hand has tapped/clicked on the map.
Actually, ManipulationHandler component is deprecated and ObjectManipulator component is a replacement for manipulation behavior. So it is recommended you start with the Object Manipulator component to makes your map movable.
For your question about how to scroll the map around x/z plane, Constraint is aimed at limiting manipulation in some way. Once constraint enabled on your ObjectManipulator component, transform changes will be processed by constraints registered to the selected constraint manager. In your case, MoveAxisConstraint can meet your need, you can add MoveAxisConstraint to game object from Constraint Manager component and set the Constraint On Movement property of Move Axis Constraint component to Y Axis. For more information about MoveAxisConstraint please refer to: https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/README_ConstraintManager.html#moveaxisconstraint

How do I rotate an object so that it's always facing the mouse position?

I'm using ggez to make a game with some friends, and I'm trying to have our character rotate to face the pointer at all times. I know so far that I need to get an angle value (f32) in radians, and I think I can use atan2 to get this (?) However, I just don't get the behavior that I want.
This is the code I have: (btw, move_data is a struct holding our player character's values, such as position, velocity, angle and rotation speed).
let m = mouse::position(ctx);
move_data.angle = ((m.y - move_data.position.y).atan2(move_data.position.x - m.x)) * (consts::PI / 2.0) as f32;
I think that I'm close, as I'm already able with this to rotate the character, but only in a sort of 'incomplete' way. The player character (pc) can mostly only face to the upper left corner, when I move the mouse there. Otherwise, if the pointer is to the right and/or below the pc, it rotates in a very slow and minor way, and stops facing the pointer. I don't know if this description makes sense.
I think the problem is that I'm not entirely sure what atan2 is doing in the first place (I only remember some basic trigonometry), and I am also not sure if I'm using it correctly, so I don't exactly know what my code is doing. (Here is the documentation I used for atan2: https://doc.rust-lang.org/std/primitive.f64.html#method.atan2)
I've gotten only so far after much trial and error, Googling as much as I can (mostly Unity tutorial results showed up when looking for algorithms to base my code off of) and I've also asked in the unofficial Rust community Discord server, but nothing so far has worked.
I also had this code earlier, but couldn't find how to make it work either.
let m = mouse::position(ctx); // Type Point2
let mouse_pos = Vector2::new(m.x, m.y); // Transformed to Vector2 to be read by Matrix
move_data.angle = Matrix::angle(&mouse_pos, &move_data.position);

Revit: Why is my wall BoundaryBox not Coinciding with its LocationCurve?

Using Revit API, I split a wall in 3 parts. To do that, I create 3 Lines:
Line.CreateBound(p1, p2)
Line.CreateBound(p2, p3)
Line.CreateBound(p3, p4)
Then I create a wall with each of these lines, which are consecutive and aligned. The result isn't as expected, as the third wall is overlapping the second one, see the illustration below.
Now, this could be a programming error, but I print the Lines' end points just before creating the 3 walls, and these points are perfectly consecutive, in the right order. The print looks like this (I remove the Y and Z coordinates, they're constant):
Now creating a new wall, from (11.811023622, ...) to (17.388451444, ...)
Now creating a new wall, from (17.388451444, ...) to (18.044619423, ...)
Now creating a new wall, from (18.044619423, ...) to (28.871391076, ...)
If I then use the RevitLookup Addin to check that problematic wall, I see that its LocationCurve's origin is indeed located at (18.044619423, ...).
But if I look at it's BoundingBox Min and Max properties, I can see that it starts at 17.388.. and goes up to 28.871391076. That is what the illustration shows..
Furthermore I use this split method on some other walls in my geometry, for which I have no problems, and I do obtain 3 nicely consecutive walls!
My question therefore is: Am I missing a property somewhere that would somehow 'shift' the wall BoundingBox from its Location Curve?? That would explain somehow this behavior?
How else could I explain and correct this?
Thanks a lot!
Arnaud.
Maybe Revit is automatically connecting the walls somehow, and modifying their geometry in order to connect them well. Imagine, for example, two perpendicular walls along the X and Y axis, from (0,0) to (1,0) and (0,1), respectively, with a wall thickness of 0.2. Revit will connect them. To do so, it will extend them in the corner where they meet at the origin. Due to that, their bounding boxes both do not end at (0,0) (or at (0,-0.1) and (-0.1,0)), as you might expect. Instead, they will both have a common corner at (-0.1,-0.1). Thus, both bounding boxes will have a maximal extension of 1.1 instead of 1.0. I hope this explanation is clear. A picture would say more than a thousand words... sorry about the stupid attempt using words instead.
You may be able to prevent wall 3 from joining up with wall 1 by setting the location line JoinType property on both of them to JoinType.None.
EDIT: Using WallUtils.DisallowWallJoinAtEnd function did the trick!
So this is the status after some investigation: The third wall is indeed auto-expanding its BoundaryBox so that it connects to the first wall. And doing that, it overlaps the small wall (see "wall 2 in the picture below - this wall is of different type than walls 1 and 3 (which are of same type), hence being ignored when wall 3 is looking for somewhere to connect) in between them (that was only 20cm long).
Making "Wall 2" a bit longer (40 cm) helps and prevents the 3rd wall from auto-expanding to the first wall, that is what I did here:
Then it's ok. But this doesn't solve the problem. I didn't see any way of preventing the "auto-expansion" of the BoundingBox, or any way to control the max distance at which it looks for another wall.
I also tried first imposing 3 different types, and then changing wall type of wall 3 to the same wall type as wall 1: when their wall types are different: no expansion. When I change the wall type, it expands, even though the wall was already created.
Finally, the really strange behavior is that for some walls, I don't have this problem at all. This is: 3 walls of the same types as when I do have the problem, with same length of 20cm for wall 2. This last thing is really unexplained.

Haskell IdleCallback too slow

I just started designing some graphics in haskell. I want to create an animated picture with a rotating sphere, so I created an IdleCallback function to constantly update the angle value:
idle :: IORef GLfloat -> IdleCallback
idle angle = do
a <- get angle
angle $= a+1
postRedisplay Nothing
I'm adding 1 each time to the angle because I want to make my sphere smoothly rotate, rather than just jump from here to there. The problem is that now it rotates TOO slow. Is there a way to keep the rotation smooth and make it faster??
Thanks a lot!
There's not a lot to go on here. I don't see an explicit delay anywhere, so I'm guessing it's slow just because of how long it takes to update?
It also doesn't look explicitly recursive, so it seems like the problem is outside the scope of this snippet.
Also I don't know which libraries you may be using.
In general, though, that IORef makes me feel unhappy.
While it may be common in other languages to have global variables, IORefs in Haskell have their place, but are often a bad sign.
Even in another language, I don't think I'd do this with a global variable.
If you want to do time-updating things in Haskell, one "common" approach is to use a Functional Reactive Programming library.
They are built to have chains of functions that trigger off of a signal coming from outside, modifying the state of something, which eventually renders an output.
I've used them in the past for (simple) games, and in your case you could construct a system that is fed a clock signal 24 times per second, or whatever, and uses that to update the counter and yield a new image to blit.
My answer is kind of vague, but the question is a little vague too, so hopefully I've at least given you something to look into.

Resources