Suggestions for improving the contact callback system

Quote:
BorisTheBrave: "How about a second set of events, corresponding to contact, rather than contact points? ..."

Quote:
Erin Catto: "BorisTheBrave: good idea. Would you care to sketch up the entire contact callback/query interface in pseudo code?"

Okay. I've been thinking about this a lot. Here is my suggestion:

Code:
class ContactCallback
{
   void ContactStart(b2Contact* contact);
   void ContactStop(b2Contact* contact);
   
   void ContactPointAdd(b2Contact* contact, b2ContactPoint* point);
   void ContactPointPersist(b2Contact* contact, b2ContactPoint* point);
   void ContactPointRemove(b2Contact* contact, b2ContactPoint* point);
   
   void ContactPointResponse(b2Contact* contact, b2ContactPointResult* result);
};


Immediately before the first contact point is created, ContactStart would be called. Immediately after the last contact point is removed, ContactStop would be called. Any contact involving at least one sensor would only get these two callbacks and none of the others. The other callbacks are our current callbacks, renamed and with one major change:

The b2Contact object would be exposed to every callback to help users in tracking a contact over its lifetime as well as allowing users to dynamically disable collisions for Mario-style platforms and breakable objects. This would primarily be done in ContactPointAdd callbacks and could be accomplished by changing the b2Contact's nonSolid flag, but having a method to call on b2Contact would be preferred (e.g. b2Contact->DisableCollisionResponses()). Optimally, the collision responses would be automatically re-enabled after the ContactStop callback so that the user wouldn't have to worry about whether a contact is "reused" (i.e. if the AABBs remain overlapping and a contact point appears again, triggering another ContactStart.)

I also suggest adding a UserData field to b2Contact so that users can track information specific to a contact shape-pair over its lifetime; although, this would be easy for users to do themselves with a map<b2Contact*, MyContactInfo*>.

I'm in favour of re-exposing the contact list to shapes. I think a caveat in the docs that "you shouldn't do anything that might affect a list you're iterating through or very bad things will happen" is more than enough. It's just so useful to provide this information, it's already available, and the alternative is to let users track these things themselves and run into the exact same problem while iterating over their own lists.

P.S. Another use case for collision filtering is "down jumping" through a platform you've been standing on. A simple solution would be to iterate through your shape(s)'s contacts and call ->DisableCollisionResponses() on any player-platform contacts.

P.P.S. You two are both brilliant.
This looks good. I will sticky this until the feature is implemented. I welcome more feedback on this.
I'm in a bit of a rush, but I've just had a go at implementing all this. I've included everything except the DisableCollisionResponses() method and re-exposing the contact list, which I may have a look at later. I've compiled it, but haven't actually tested it yet. Can someone check it out and let me know if it's close to hitting the mark?
Looks solid. Here's my analysis. * are points I've changed in the patch below.

1) b2ContactManager::Destroy calls ContactPointRemove, but not ContactStop. Why?

2) b2Contact has a m_userData field. You don't use it for anything, and it has no public interface. Also, what sort of thing can you actually see people doing with that?

3) I see a lot of
Code:
reportContactPoints = !(m_shape1->IsSensor() || m_shape2->IsSensor());
when of course this used to be what the m_nonSolid flag was for. Have you not used this because you intend to repurpose the flag? In which case, I think you'd be better off creating a new flag to represent disabled collisions.

4*) I did get some compilation errors on my setup, "Warnings treated as errors". You need to intialize bool reportContactPoints in two places.

5) The worry with disabling collisions was breaking TOI steps. I cannot test this yet, without DisableCollisionResponses, but I wanted to know if you have planned to solve this, or accurately determined nothing needs be done?

6*) ContactStart and ContactStop are not virtual. This must be a bug.

7*) TestBed is not updated. I've corrected some of it, but I haven't taken advantage of the new call backs so SensorTest can work yet.
Thanks for the analysis BorisTheBrave.

1) Yep, you're right, b2ContactManager::Destroy should indeed call ContactStop, just as in other parts I added. And ContactPointRemove should only be called if the contact is solid.

2) I added the userData field based on chriswa's suggestions, and it does have a public interface (unless I buggered something).

3) My knowledge of the engine is still very limited, and I didn't know about the m_nonSolid flag. I simply interpreted chriswa's description literally, and hence the check for either body being a sensor. If it makes more sense to use the flag instead, then that's what we should do.

4) I didn't think about "uninitialised" warnings. I left reportContactPoints uninitialised in a rather extreme and probably entirely unwarranted attempt at optimisation (which I noted in a comment above it). It's probably a very good idea to initialise it properly, and possibly even to initialise it straight to "!(m_shape1->IsSensor() || m_shape2->IsSensor())", (or the equivalent using the m_nonSolid flag), removing the "if (listener != NULL)" statement.

5) To be completely honest, I have no idea at this stage what TOI steps are, or how disabling collisions might break them. Again, I was following chriswa's description pretty blindly, based on a naive assumption that the implementation wouldn't really be that hard, just a bit time consuming. I think this will need to be thought out by those who know more about it that I.

6) Yep, woops 🙂

7) And yep, testing is obviously required.

I don't know how much time I'll have tomorrow (== later today) to have a go at fixing the last few bugs and testing it. Hopefully I've at least got the ball rolling 😉
Not sure if this is how the other port/version are, but with JBox2D 2.0.1 there is just the single collision handler on the world object. At least in my code that means I have to go through a list of shapes I care about to see if they are involved in any of the contacts.

Code:
      public void add(ContactPoint point) {
         if (point.shape1 == player || point.shape2 == player) {
            // do something.
         } else if (point.shape1 == someImportantShape1 || point.shape2 == someImportantShape1) {
            // do something
         } else if (point.shape1 == someImportantShape2 || point.shape2 == someImportantShape2) {
            // do something
         }
         // etc.
      }


Seems like it'd be more efficient if each Shape instance could have its own listener or callback (null by default). The engine could then just check whether either of the shapes in the collision had listeners and invoke them. It'd also be nice if the Shape's listener got the info as it relates to it rather then it having to figure out if it is shape1 or 2 in the contact and then adjusting normals, etc appropriately.

I maybe wrong about the performance cost of this, but seems more intuitive for an OO person to have their behavior in the individual Shape class not a global handler.
There's little point imho putting a dispatch system like that into the Box2D engine. It's quite easy to add one for yourself, so providing one has little benefit, just forcing into my design choices, of which there are a few. It wouldn't allow us to abandon the current call backs as there are times when you genuinely want it in that form.
For a start, you will find your callback idea quite painful for some things in practise as it logically must raise two events for every collision. What if you wanted to play a single sound?

Then there's the problem of adding a callback to b2Shape. You are not intended to inherit from b2Shape, so the call back would have to be a member variable, costing precious space in what is intended to be a slim class. Not to mention that it starts bluring the line between the Box2D physics engine and your own code. Storing the event call backs in an Actor class is a much more logical place for them, but as userData is necessarily opaque to Box2D this requires the current simple callback scheme.

I'm not saying Box2D shouldn't do more for the user (it should), but just that this proposal is not one of them.
Quote:
There's little point imho putting a dispatch system like that into the Box2D engine. It's quite easy to add one for yourself, so providing one has little benefit, just forcing into my design choices, of which there are a few.
It wouldn't allow us to abandon the current call backs as there are times when you genuinely want it in that form.

Agreed. This is adding another "officially" supported approach, although it seems like one that would be commonly be used (at least by the Java folks as it is a very common convention). We could still keep the global one. Would probably want to for backwards compatibility. There would likely be a performance hit though if the app uses both at the same time since they are traversing the contact list at least twice.

Quote:
For a start, you will find your callback idea quite painful for some things in practise as it logically must raise two events for every collision. What if you wanted to play a single sound?

Not the way I was thinking about it (I could be wrong). You could have up to 2 if both shapes in the contact had registered a listener. Depends on how many shapes you want to listener to and how often they collide. For the sound example, that could be handled as both shapes know what the other shape in the collision is, so you'd just need to decide (in your listeners) who gets priority. Could get messy depending upon the scenario I guess.

My concern with the current design is you essentially iterating over all of the shapes you care about responding to for every contact. If this is a large number than that seems worse that doing 2 null checks and 0-2 method invocations per contact event. Again, it all depends on how many folks actually listen to collisions and how many shapes they specifically check for. I'm still the newbie here so I can only talk to how I use it.

Quote:
Then there's the problem of adding a callback to b2Shape. You are not intended to inherit from b2Shape, so the call back would have to be a member variable, costing precious space in what is intended to be a slim class. Not to mention that it starts bluring the line between the Box2D physics engine and your own code. Storing the event call backs in an Actor class is a much more logical place for them, but as userData is necessarily opaque to Box2D this requires the current simple callback scheme.

Agreed. I didn't expect anyone to extend b2Shape. Rather, the listener is a property of a given interface as it is on the world class currently. The listener would be custom code and could include its own internal properties (set by constructor) and access to the userdata of the shape. Could even have the listener be the actor implementing the listener interface. I agree we shouldn't have folks adding their own properties to or extending b2Shape for non-physics purposes.
@Edge:

This is trivially easy to do with your own dispatching ContactListener. Here's mine, which is in AS3:

Code:
      override public function ContactPointAdd( contact:b2Contact, point:b2ContactPoint ):void {
         var shapeOwner1:* = contact.GetShape1().GetUserData();
         var shapeOwner2:* = contact.GetShape2().GetUserData();
         if ( shapeOwner1 is ContactRecipient ) {
            (shapeOwner1 as ContactRecipient).onContactPointAdd( contact.GetShape2(), point, contact, 1 );
         }
         if ( shapeOwner2 is ContactRecipient ) {
            (shapeOwner2 as ContactRecipient).onContactPointAdd( contact.GetShape1(), point, contact, -1 );
         }
      }
      // etc for each method...


player, someImportantShape1, and someImportantShape2 would all be classes which implement the ContactRecipient interface (or would be base classes of it, depending on what your language allows), so the call to onContactPointAdd() is dispatched to the correct class. No need to iterate over anything!

A commonly used ContactListener probably belongs in a FAQ or Wiki article, not hard-coded into Box2D.
Edge wrote:
My concern with the current design is you essentially iterating over all of the shapes you care about responding to for every contact.

You probably shouldn't be doing it this way, even under the current system - you're right that you shouldn't be iterating over every important shape for each contact, and there's a way around it.

chriswa showed one way, which works well; I do it a bit differently, running shape id pairs through a 2->1 hash to create a pair key and fill a hash map to mark the pairs that I care about, then when I get the "add" event, I only store (in a hash map with the same key) or respond to the pair if its hash matches an entry already in the "I care about these" hash table. This has better complexity behavior: you have to run the hash and check the hash map for every contact, and then run once through all the pairs that you care about to handle them, so it's O(M+N) instead of O(M*N) (where M is the number of contacts and N is the number of pairs you're interested in), assuming the hash map lookups happen in average O(1) time, which should be the case if you have a good 2->1 hash function and you use a decent hash map implementation.

The only advantage this has over chriswa's method is that you can register and unregister pairs in the hash map dynamically rather than having to mark the classes at compile time; if you don't need that ability, definitely go with his method.

I set up a whole dispatcher to do a bunch of this stuff, including registering/unregistering pair listeners (as well as some other stuff that gets a bit more messy) - it's dependent on PulpFizz, which is currently not really in a usable state, but it should be pretty clear anyhow, you can look at the code for sendEventMessages(HashMap<Integer,ArrayList<ContactEventListener>> hashMap, int id1, int id2, ContactData c) at http://code.google.com/p/pulpfizz/sourc ... r.java#306 if you think it might help.

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