Suggestions for improving the contact callback system

Been playing with bullet a little after a post by Erin got me thinking. Callbacks are the wrong way to deal with contacts. Instead, you should just ask for all the contacts on a shape or body and have access to the contact and result for each.

Right now a step works (almost) like this:
  1. User calls Step()
  2. Solve non-TOI (calling Add/Persist)
  3. Report
  4. Update broadphase (adding/deleting contacts, calling Remove)
  5. Solve TOI (calling Add/Persist)
  6. Report
  7. Update broadphase (adding/deleting contacts, calling Remove)
  8. If TOI events still exist goto (5)
  9. End of Step()
  10. User unbuffers events to make changes

What I'd like is this:
  1. User calls Step()
  2. Reset contact results
  3. Clear contacts marked for deletion
  4. Solve non-TOI
  5. Store b2ContactResult info with contact
  6. Update broadphase (adding contacts, marking others for removal next step)
  7. Solve TOI
  8. Store b2ContactResult info with contact
  9. Update broadphase (adding contacts, marking others for removal next step)
  10. If TOI events still exist goto (7)
  11. User checks a shape's or body's contact list for contacts, keeping track of adds/removes manually

No-longer-valid contacts are cached, and exist until cleared at the start of the next Step() call. Outside of a step, it might be best if adds/moves created new contacts, moves cached old ones and deletes got rid of contacts.

ContactResult data is saved along with the contact itself. If a body has multiple results due to multiple manifolds or TOI, perhaps multiple results will be stored per contact.

There's no Add/Persist/Remove required because the contacts are cached and the user can figure this out by checking whether a contact didn't exist the previous step or if it's marked for removal or doesn't exist now.

The special return value on Add could remain as a separate call, perhaps in b2ContactFilter.

As for speed and memory, I'd expect speed to increase because there are no callbacks interrupting contacts, though more memory usage by default because the engine would buffer b2ContactResults. But I'm willing to bet most users right now buffer b2ContactResults at least, and perhaps Adds/Persists/Removes as well.


Edit: Took a shot at making these changes. It's imperfect, but enough to play around with.
You cannot remove add/persist/remove. These are needed for several reasons (aside from the proposed filter)
* So the user can grab extra data about the collision (such as collision speed) when it happens. This information is gone after the solver.
* So the user can determine the order of contacts, and if a contact has been added and removed in the same tick. Again, you cannot determine this from the leftover contacts, even if you persist deleted ones by a frame.
* Because it is absurd to ask the user to query the contacts of 1000 shapes, when the engine already knows only one collision has occured.

If it wasn't for the first two, we'd buffer all contact events on behalf of the user.

And if you suggest immediately updating contacts when the user calls SetXForm etc, do you mean evaluating it as well. As this would be quite costly, and without it, the contacts would be fairly meaningless. And there's a certain cost to merely updating the broadphase for every call of SetXForm - i'm not sure how much, but the existance of buffering for the broadphase suggests it's non-negligable, though I may have missed the point of this.
1) Extra data: I considered this extra data. One idea would be to leave the event system in for advanced usage, possibly simplifying it. Another option would be to grab a little more data at the time of the collision and buffer that as well. Not sure on this one, but I tried to keep this test patch simple.

2) Order of contacts and adds/removes in the same tick: My feeling is that the user should treat a step as a single atomic event. The only meaningful ordering occurs between substeps, and the user can't change anything between them. Do you know a good use for it?

However, there are a couple ways to detect ordering and adds/removes in the same tick, to a limited extent. The list of contacts is already sorted with the newest contact first, both in the body and in the world list. ContactResults are currently being stored that way as well. You can detect adds and removes in the same step because buffered dying contacts aren't revived when a new collision occurs; rather, a new contact is created.

3) Query 1000 shapes: The only bodies it makes sense to query are those that will actually do something on contact, and it's likely that at least half the dynamic bodies are in contact with something if there's any gravity. The world already iterates over all the contacts to generate events.

4) SetXForm already updates the broadphase, so I just meant to create the contacts it already does and move them as normal. When shapes stop overlapping, they get buffered, so they still exist until the start of the next step. However, to avoid dangling pointer errors, if a shape (or body) is deleted, its contacts are removed immediately.

New pairs could be buffered until the start of the step as well, but that gets a little complicated.
1) Yeah, possibly. I've not seen anyone want anything other than collision velocity, tbh.

2) The user can change tons of stuff, game state! He just cannot change any physics. He can change that too, really, he just has to buffer the actual changes.
Ordering has several uses, but I think the most clear argument is that it simplifies logic. If I have a goal, and some lava in my game, I can just win the game on hitting the goal, and lose on hitting the lava. With events, I don't need to worry about checking which occurred first, or if they were in the same frame or not, i can just set a win/lose/playing enum.

3) This is a fairly specific use case. Box2D is broader than that, and we need to support it all. In fact, such considerations preclude removing features (such as events) alone - I will not support cutting features unless they are virtually made redundant.

You say that the world already iterates over all contacts to generate events. This is true, but I had got the impression you were proposing users iterate over the contacts for a given body, not the world's contact list. Hence complaining it's bad in the case of many bodies few contacts. But if you are iterating over the world contact list, I don't see any advantage over buffered events - or even that much difference.


I am objecting here to removing features. The original intention of this thread was to be additive - provide an easier alternative to events for those who do no need the power, or have needs which events are not helpful for (such as jumping).
I see your point now. The point of this was to treat a physics step like a single, atomic event, which now I realize is probably impossible. I was trying to do so because it seems necessary to split rigid body and character movement:

Quote:
In games I've worked on, most of the time the character is not a rigid body. The character is a represented by a geometric proxy that is manipulated between physics time-steps (not during). I use a specialized character solver that has it's own set of rules. I think Box2D should be extended to support character proxies by providing phantoms that can be shape-cast and allow the computation of contact manifolds. With this functionality, it would be much easier to plug in a user FSM to control the collision behavior, without mucking with the code that handles rigid body movement.


I'm having difficulty understanding character-rigid body interaction would work in box2d. How, for instance, would you get a rock to bounce off the player?
Hangar wrote:
I'm having difficulty understanding character-rigid body interaction would work in box2d. How, for instance, would you get a rock to bounce off the player?


Things like this make character controllers a difficult problem. If you want a Mario type game where every movement is under the designer's control, then you have to use a character proxy.

If you want a physically driven character you eventually have to hack some things and live with the consequences.

For the rock problem we can have many solutions:
1 - The rock and player don't collide
2 - The rock and player collide using the rigid body solver and both move.
3 - The character proxy detects the rock and applies an impulse.
4 - The character proxy detects the rock and moves out of the way. We have to prioritize static collision over dynamic collision so that the rock won't push the character out of the world.
Could this work? 5) The player detects the rock after the step and moves it manually. I know movement is expensive. Do you think it would help to be lazy about broadphase commits? Only doing them when you need new information?


I'm curious about a couple other ways to control characters:

Would it make sense to detect characters within islands and solve islands differently if any are detected? This feels complicated though. Maybe the character could receive an event, iterate over contacts and adjust its own position, then allow the other bodies to treat it either as a ghost or static object. Or maybe it would help a bit to detect contacts and be able to apply velocities to other bodies before solving them.

Would it help to have the ghost body update between each substep in time of impact?


But for now, since no shapecasts or ghost bodies are implemented, how's this for faking it? Make characters rigid bodies. You manually move the characters after the normal step. Maybe mimic shapecasts by moving the character body in small deltas, solve any contacts, and adjust the final hit fraction by interpolating by max(penetration * normal dot shapecast direction). To walk, you shapecast up, shapecast forward, then shapecast down, so you can climb steps and walk over rubble.

I'm not sure about handling built-in velocity and gravity. You have to be able to detect whether the character is on the ground by the contacts the character has with the ground. I'm leaning toward right now leaving normal velocity and gravity alone, but, during a character update, reset velocity to 0 and move the rest of the way manually. The alternative might be to fake a ghost body with sensors using the unpatched contact generation, then, after the step, do the adjustment normally.


Finally, a general question: should platformer-style enemies generally be characters or normal rigid bodies? Characters seem pretty expensive in terms of shapecasts, but AI could benefit from acting like a character.
That sounds good. You can do all the character work using a sensor. The missing piece is the character solver, but conceptually it is just a matter of iterating over the contacts and projecting out.

I would also use a character proxy for AIs. This allows for designer control and re-use of character code.
Thank you for your help. Wanted to wait to reply until I got something written.

I took a slightly different approach that seems to work well enough. Instead of doing the sensoring manually, because I don't think I could do better than the rigid body solver, I isolated the axis that the player wants to control. The player picks a direction to call down, and each update, between steps, calls a Move() method, passing a velocity. Move() sets the player's velocity perpendicular to the down vector to 0 and preserves the parallel velocity. Then, Move() applies some shapecasts that move the player in the right direction. While on the ground, Move() attempts to step over small objects or stairs and not go up steep slopes. The normal update can move the player around, but any user input is dealt with in terms of slowing the velocity and using shapecasts.
Returning to the callback system, I read the views given in this thread, and have the following proposal that I think will satisfy most people involved. It is a bit complicated, so bear with me as I explain, but it does cover a lot of the aspects under discussion.

1) As Hangar suggests, a dirty-contact scheme can be used to free Box2D from evaluating contacts at a specific time in the step cycle. Though I'm not sure it's technically required, keeping the broadphase updated at all times will simplify this implementation.

2) A couple of people wanted contacts evaluated after the Step, so they'd be up to date. I propose to update contacts lazily. I.e. users do not have direct access to contacts, but instead rely on function calls such as IsTouching and b2ContactEdge.GetNext, which always update dirty contacts before returning. If none of these are called, then contacts will be updated immediately before Step, as currently.

3) Updating contacts out of phase leads to new problems - events can quickly become re-entrant, or very confusing to say the least. My proposal to fix it is to buffer all events, in addition to firing them immediately. Every event, say an Add, raises two callbacks, one immediately, and one when the buffer is flushed (either manually, or at a fixed point in the step cycle). The former event is always meant to be treated as "world locked", and the latter unlocked.

4) A lot of uses cases can ignore the unbuffered events, but for people who do wish to use them, a userdata unique to the contact can be set, to facilitate passing information between related events, and most specifically from an unbuffered callback to it's corresponding buffered one. ContactStart and ContactStop are now vitally important events, as I'll need to use them to allocate and deallocate that userdata.

5) The settings will be expanded with an option to control the events system. The options are: unbuffered, to restore old, faster, behavior; lazy, the default as described above; and eager, where contacts are always kept in a nondirty state.

Notes:
The events buffer is flushed every frame, which should allow a fast allocation scheme like b2StackAllocator to be used.

The difference between lazy and eager is subtle - because events are generated when contacts are updated, and contacts are updated behind the scenes, you could potentially get quantum effects where the state of your game changes according to whether you inspect contacts or not.

As contacts are locked behind function calls from the user, there's no obligation for the user to ever see what b2Contact looks like internally. Which is good, as I consider it to be confusingly laid out. Like IsTouching, I'd be keen to see functions returning b2ContactResults and the like instead of b2Contact and b2Manifold*.

I really expect most users to not care about the complicated details of this, which is why they can just dive right in to buffered events and evaluated contacts, even though these things will lead to less efficient code than that encouraged by contacts.

Original thread: https://box2d.org/forum/viewtopic.php?t=1784