Suggestions for improving the contact callback system

chriswa wrote:
hippocoder wrote:
if (shape1.collided(shape2,optional index)... directly check a collision between two
if (shape1.collidedCategory(0x0002,optional index)... return true if collided with this category.

It would be trivial to write a ContactListener to store this information, but a waste of performance and memory if we forced everyone to store it. If this is such a common API request, I could write one up for the Wiki. I don't think it's a good idea to force everyone to store all that data, as you can achieve greater efficiency by reacting to collisions as they are detected.

I agree that it's not a big deal to write up a contact listener to do this, and it can be more efficient; however, the lack of a single built in call to do this type of check is probably the most common complaint I've heard about the engine, so I'm not sure that I think it's enough to just have example code somewhere online to do it.

I'd be fine with leaving it at shape.isColliding instead of shape.collided, the difference being that the former doesn't store mid-step temporary contacts - for impact listening, you should almost always use a listener. But listeners are really overkill for checking persistent contacts, even if it's just cut-and-paste code.

BorisTheBrave wrote:
2)
Even in that case, such functions are really just convenience wrappers for the contact list, which must be linearly iterated over. Currently Box2D doesn't store any data structures to quickly access this, and it could be difficult to do so efficiently. I'm not sure what sort of index you had in mind, but I think that sort of thing is ugly, people should not have to do manual caching. On the other hand, it is rare to have many contacts on a single shape, so perhaps linear iteration is fine as is.

I think a linear search is good enough for most people, as long as there is a note in the function documentation that the check runs in O(N) time in the number of contacts on that shape (and if it's not good enough, people can write listeners and store stuff away themselves, because they're doing something hard core with the engine and better know what they're doing anyways).

Internally we could check pairwise shape contacts a little "smarter" by iterating over the contact list on the shape with fewer contacts (the intuition being that usually if a shape has a lot of contacts, it's a large ground shape with lots of small stuff sitting on it, so it's quicker to check the small bodies lists instead of the big one).

Quote:
3)
Exposing the contact list. Having a binary test function is one thing, but I think it is equally important to be able to loop over all currently touching shapes. I can see a few ways of doing this:
a) Expose the underlying Box2D contact list. This is how it used to be, with GetContactList / m_contactList. This is dandy, but it kept tripping people up that it had speculative contacts in, and had this manifold/contact point structure that most people didn't want or understand. Perhaps better documentation would help, but is always going to have some usability issues.

Agreed, I remember having a rough time dealing with that stuff myself.
Quote:
b)Expose an iterator to the list. This can eliminate speculative contacts, and provide some help in browsing the list. The down side is that Box2D makes do without explicit iterator objects at the moment, preferring linked lists, so it'd be a bit of a depature.

c) Do a), but provide a GetNext() method that skips speculative contacts.

I think I'd go for c) as opposed to b), mainly for the reason you gave, that Box2d doesn't use iterators at all. It would be a bit weird, IMO, to shift for this one purpose when people are used to walking linked lists for everything else.
Quote:
d)A function, or family of functions, to fill an array with info. I don't like this, but I don't like providing just a few options in any list of things 😉.

In Java or AS3, creating and returning an array would probably be the cleanest and most user-friendly solution, but in C++ not so much.

In other words, I think I'm liking option c) best at the moment.
The problem with this query in my mind is that most of the time you're not looking for shape-shape collisions, but rather body-body collisions, or shape-body collisions (for sensors). Only having the first can lead to really inefficient code.

edit: Noticed ewjordan just suggested the below.

The contact list is stored by body, right? If you compare the number of contacts in each body, you can write each of these in terms of O(n), where n is the number of contacts in the body with fewer contacts. For a convenience method this test is probably better automated, since it will be common to test with ground.

Code:
if ( parameters are part of the same body )
   return ?
iterationBody = body of first parameter
otherBody = body of second parameter
if ( iterationBody.numberOfContacts > otherBody.numberOfContacts )
   swap(iterationBody, otherBody)
for each contact in iterationBody:
   if (test(contact.shape1) || test(contact.shape2))
      return true
return false


Where test(shape) is either shape == otherShape, or shape.body == otherShape.body.

A more concrete example:
Code:
bool IsTouching(b2Shape* shape, b2Body* body) {
    // Special case where shape is part of body
    if (shape->GetBody() == body) {
        return true;
    }
    // Iterate to find the shorter list, and call a method with an appropriate test.
    b2ContactEdge* contactIter1 = shape->GetBody()->m_contactEdge;
    b2ContactEdge* contactIter2 = body->m_contactEdge;
    for (;;) {
        if (contactIter1 == 0) {
            return TestTouching(shape->GetBody(), body);
        }
        if (contactIter2 == 0) {
            return TestTouching(body, shape);
        }
        contactIter1 = contactIter1.next;
        contactIter2 = contactIter2.next;
    }
}

// Test whether any contact involves the test shape
bool TestTouching(b2Body* iterationBody, b2Shape* testShape) {
    b2ContactEdge* iter = iterationBody->m_contactList;
    for (; iter != 0; iter = iter->next) {
        if (iter->contact->GetShape1() == testShape || iter->contact->GetShape2() == testShape) {
            return true;
        }
    }
    return false;
}
// Test whether any contact involves the test body
bool TestTouching(b2Body* iterationBody, b2Body* testBody) {
    b2ContactEdge* iter = iterationBody->m_contactList;
    for (; iter != 0; iter = iter->next) {
        if (iter->other == testBody) {
            return true;
        }
    }
    return false;
}


This currently doesn't worry about potential contacts, etc. I'd also expose the contact list for more specific queries.
Ok, I've taken on board the advice, and have the following for you:
Attachment:
events.zip [6.89 KiB]
Downloaded 48 times

Bear in mind this is completely untested and undocumented. I don't see the point hammering out fine details when we are still working on the spec.

So, the changes are:
b2Body::GetContactList
does what you would expect it to do. b2ContactEdge has a GetNext method that skips speculative contacts.

b2Body::IsTouching and b2Shape::IsTouching
Ok, so I've got a function for each possible pairing of bodies and shapes, and implemented IsTouching as a linear search of the contact list. I don't do the "find which is shorter thing", partly as I cannot be bothered to code that, and partly I'm dubious it'll actually speed things up at all.

But even cooler, you can optionally specify a b2ContactResult for IsTouching to fill up with data. It picks the first contact point it can find, if there are several, and then translates it into a b2ContactResult, saving people the mental effort of understanding manifolds. By picking the first, it is ignoring out on data, but it's all available via the contact list anyway, and I expect this form to be more useful. Perhaps another overload returning the b2Contact would be of use?

The full method signatures, therefore, are:
Code:
bool IsTouching(b2Body* other);
bool IsTouching(b2Body* other, b2ContactResult* result);
bool IsTouching(b2Shape* otherShape);
bool IsTouching(b2Shape* otherShape, b2ContactResult* result);
Awesome work! I'll test this in detail at some point over the next few days and let you know how it goes.
BorisTheBrave wrote:
b2Body::IsTouching and b2Shape::IsTouching
Ok, so I've got a function for each possible pairing of bodies and shapes, and implemented IsTouching as a linear search of the contact list. I don't do the "find which is shorter thing", partly as I cannot be bothered to code that, and partly I'm dubious it'll actually speed things up at all.

Yup, seems reasonable - you're just trading one O(N) for another, and anyhow, if someone is using this enough to make it a bottleneck, they're probably calling it too much and should really be doing something else to do what they want. After all, the engine is already going to be iterating several times over every contact anyways, so unless someone is really abusing this call (by calling it on every possible body pairing, for instance), it's always going to take a lot less time than the contact solving itself.

As long as the behavior is documented, I think this will be perfect - we should probably add a special note when this is finally settled that it's generally better, for instance, to call myBody->IsTouching(ground) rather than ground->IsTouching(myBody), just because the ground often contains all the static geometry and will be touching almost everything.

Quote:
But even cooler, you can optionally specify a b2ContactResult for IsTouching to fill up with data. It picks the first contact point it can find, if there are several, and then translates it into a b2ContactResult, saving people the mental effort of understanding manifolds. By picking the first, it is ignoring out on data, but it's all available via the contact list anyway, and I expect this form to be more useful. Perhaps another overload returning the b2Contact would be of use?

The full method signatures, therefore, are:
Code:
bool IsTouching(b2Body* other);
bool IsTouching(b2Body* other, b2ContactResult* result);
bool IsTouching(b2Shape* otherShape);
bool IsTouching(b2Shape* otherShape, b2ContactResult* result);

Looks good to me. I suspect people will find this extremely useful, and I like the ability to get the b2ContactResult out.

Also, what do you think about category/group collision tests, as hippocoder had requested earlier?
Code:
if (shape1.collided(shape2,optional index)... directly check a collision between two
if (shape1.collidedCategory(0x0002,optional index)... return true if collided with this category.
ewjordan wrote:
Awesome work! I'll test this in detail at some point over the next few days and let you know how it goes.
Also, what do you think about category/group collision tests, as hippocoder had requested earlier?
Code:
if (shape1.collided(shape2,optional index)... directly check a collision between two
if (shape1.collidedCategory(0x0002,optional index)... return true if collided with this category.


In principle, this looks pretty useful to me, but I have some reservations.
Firstly, I don't like officially acknowledging categories/groups. Box2D 2.0 allows you to completely ignore them by overriding b2ContactFilter, and I would like to keep it that way. But the complaints I got for doing so with Raycast filtering suggest most people do use the built in b2FilterData, and would appreciate the convenience of using it directly. So I'm of two minds.

Secondly, collidedCategory looks like the sort of thing that you would expect a list of collisions from, instead of just a boolean. Would people really find it that useful as suggested? Would it be even more misleading to provide one contact result (of many) using the second form? In any case, I refuse to use an index parameter to provide access to a list, though admittedly all options for returning a list in C++ are pretty ugly.
So cool to get updates so quickly.

Thoughts: It might be a bad idea to fill out a single b2ContactResult, because it gives the impression that there can be only one contact point. (Was my impression at first.) If you want to provide it, you could use the same pattern in b2World::Query, which takes a buffer and a maximum size. That would let the user specify the address of a local b2ContactResult and 1, to limit it to the first result. The flip side is that pattern is horrendous to use for the end-user; people use C++ to avoid the need for fixed-size arrays. Maybe box2d should provide a lightweight std::vector for this sort of thing. (Just an array structure with dynamic memory management.)
BorisTheBrave wrote:
ewjordan wrote:
Awesome work! I'll test this in detail at some point over the next few days and let you know how it goes.
Also, what do you think about category/group collision tests, as hippocoder had requested earlier?
Code:
if (shape1.collided(shape2,optional index)... directly check a collision between two
if (shape1.collidedCategory(0x0002,optional index)... return true if collided with this category.


In principle, this looks pretty useful to me, but I have some reservations.
Firstly, I don't like officially acknowledging categories/groups. Box2D 2.0 allows you to completely ignore them by overriding b2ContactFilter, and I would like to keep it that way. But the complaints I got for doing so with Raycast filtering suggest most people do use the built in b2FilterData, and would appreciate the convenience of using it directly. So I'm of two minds.

Secondly, collidedCategory looks like the sort of thing that you would expect a list of collisions from, instead of just a boolean. Would people really find it that useful as suggested? Would it be even more misleading to provide one contact result (of many) using the second form? In any case, I refuse to use an index parameter to provide access to a list, though admittedly all options for returning a list in C++ are pretty ugly.


I have to agree, we shouldn't assume that the user will be using the internal filter data structures, and we serverly limit Box2D by removing the ability to customize this.
dinedal wrote:
I have to agree, we shouldn't assume that the user will be using the internal filter data structures, and we serverly limit Box2D by removing the ability to customize this.

Yup, now that I think on it a bit more I'd leave it out for now. We can always come back later if it's sorely needed (IMO, the workaround for checking shape vs. group is simple enough so this won't be the case, you just loop over the shape's contacts and check them yourself, which is maybe four lines of code, and works just as easily with custom contact filters), but once it's in there people will rely heavily on it and we lose the option to painlessly remove it.

Things look good as they stand, and it's a lot more user friendly than it was before. I think we may want to let it sit like it is for a little while, see if people think the new changes address their major complaints; so far they seem to do the trick for me, and I'm probably going to bring them over to Java soon assuming no major problems show up in the meantime.
Mayobutter's post here points out that contacts are very frequently delayed by one frame. This affects the calls provided in this thread too.

Is this going to be a problem/negate the use of them?

The only solution I can see is to evaluate contacts at the beginning and end of every step (instead of just beginning as current), taking care to only re-evaluate contacts that have actually changed through user action.
I don't think box2d will ever be able to handle that sort of state well. Imagine all the degenerate cases: the player could be trying to jump with a ceiling overhead, gravity could be so high that the jump impulse has no impact, gravity could be sideways, the player could be buried slightly within the ground, or the player could be jumping off a block that is moving upwards.

The key is to just define jumping and landing appropriately. In these cases, jumping could mean moving after hitting the jump key until landing, and landing could mean coming into contact with a body with a greater or equal y-value for velocity that causes a normal force pointed within 60 degrees of straight up.

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