Suggestion for sleep management using statistical variance
Recently in physicsjs i implemented body sleeping. I played around with techniques until i got something that seemed to give sensible behavior. Instead of having a velocity threshold I have a position variance threshold.
On every integration I push the current body position to a vector average (and variance) calculation. If the variance is below the threshold then I increase the idle timer.
This solves the problem of slowly moving bodies falling asleep. If the body is moving, even slowly, the variance will increase as the body moves, so the idle time will never reach its max. But if the body jitters then the variance will remain small and activate the sleep state.
For collisions, i use a velocity threshold. If the body collides, a sleep check is performed. If the sleeping body is given a velocity (impulse) above the threshold then it forces a wake up.
Here are the algorithms I use for mean and variance calculation: https://github.com/wellcaffeinated/PhysicsJS/blob/master/src/math/statistics.js
Here's the sleep check (it gets called by the integrator, collision response, and my primitive constraints): https://github.com/wellcaffeinated/PhysicsJS/blob/master/src/core/body.js#L303