Feature request: iterators

In Box2D there are several functions to obtain a list of objects.
In particular I spotted two kind of these functions:
  • Functions like b2World::GetBodyList()
  • Functions like b2World::QueryAABB
The former returns an pointer to an object with a function GetNext which can be used to iterate thru the list.
The latter needs a callback that gets called for any matching element until they're over or until the user is satisfied.

I find this second kind to be pretty awkward. The advantage of it is that the engine does only the needed computation, and doesn't waste CPU loops, but I think it's possible to do another way (which I think would be better):
Why not using iterators? That's it, iterators compatible with STL/boost, with an operator++ to iterate thru elements, functions begin() and end() and so on.
This way all of Box2D lists will have a homogeneous interface, and they'll be compatible with other standard tools (many std algorithms and boost functions, like std::for_each, std::find, std::count_if, BOOST_FOREACH ... ).
Box2D doesn't use the STL for a number of reasons. The number one issue is compatibility. I suggest searching these forums for the term STL.
I agree that STL can be a problematic dependence, but to implement "standard" iterators we don't need STL at all.

To implement a custom Iterator (for Box2D bodies, for example) we don't need to inherit any iterator class, nor to use in any way anything provided by STL or Boost: functions operating on iterators are template functions, they need only that iterators supply some functions/operators.

Once we decide what kind of operator is the most adapt to our classes (eg: ForwardIterator for b2World::QueryAABB) we just need to write a custom class (which will be our operator) that provides:
  • Default constructor
  • Copy constructor and assignment operator (operator=)
  • Equality/inequality comparisons (operator==, operator!=)
  • Dereferenced operators (operator*, operator->)
  • Incrementing operators (operator++ postfix and prefix)

Applications will then be able to use that class as an iterator for standard functions (STL and Boost's).

This shouldn't add any kind of overhead to Box2D, and doesn't require to use any "incompatible" tool (external libs, templates, RTTI). The only thing it requires is rewriting a few lines of code; although I'm not very happy about the zlib license, I can turn a blind eye to it and submit some patches, if you're interested in providing standard iterators instead of current way to iterate.

Here is an overview about STL compatible iterators.
But iterators would add more complexity to Box2D and it would slow down the debug build and compile times. Also, many people have been using the API without major problems. This feels like fixing something that isn't broken.

Are iterators standard? Yes, in some circles. But I've worked on several professional game projects with little or no iterators in sight. Would iterators add clarity to the interface? In my opinion it doesn't really because iterators often seem a bit magical with lots of operator overloads.
I don't agree with your points...

  • Why would iterators add complexity to Box2D and slow down build times?

    Instead of having a b2QueryCallback class we'd have a BodyIterator class (that does'n need templates, polymorphism, RTTI or anything else -- while b2QueryCallback do needs polymorphism), that shouldn't result in a heavier compile phase.

    Besides I think that iterators will perform better at runtime, since they don't need the invokation of a virtual function ( b2QueryCallback::ReportFixture ), but only to use iterators' functions and operators which can be inlined (to the countrary of the virtual function).

  • Iterator pattern is a well known pattern used by plenty languages and libraries. It's been chosen as one of the bearing patterns of the C++ Standard Template Library.

    How an iterator works should be understood by any good C++ (or Java, or Python, or ...) developer. Anyone should be already familiar with iterators, while I felt like b2QueryCallback is someway an exotic pattern.

  • This is not a bug-fix request, but a feature request -- or even better, a feature suggestion.

    Both b2QueryCallback and the iterator pattern are able to easily do that job; just I felt like iterators would do it in a better (ie: more standard) way.

  • At last, about the usage of iterators in professional game projects, well, an application is different from a library.
    If you write a game and decide not to use other standard-compliant libraries (STL, Boost), then iterators are useless to you.
    A library on the other hand (especially a public one) could be used in a variety of projects; since some of them could use STL and Boost, providing some kind of support for standard iterators will help them.

These points mostly hold about an iterator replacement for b2QueryCallback.
I think it would be a good idea to also provide iterators instead of the GetNext functions, in order to have a consistent interface, but this is a lot less justified.

The only disadvantage I can see about introducing iterator classes, is that it would break API compatibility, abruptly changing the API. (And this is a big deal!)
Leaving old classes/function in for a few versions, marking them as deprecated, should alleviate this problem.



Anyway we've entered the subjective field here.
I'm glad of hearing your opinion about this subject.
It's OK if support for iterator is a feature Box2D is not interested in; I'll build iterators above Box2D functions and that will be enough to me.
I don't have a strong opinion about iterators in general, but I usually try to play devil's advocate when feature requests are proposed. That seems to make more of the issues bubble up.

Good point on the iterator's lack of a virtual function. This is a big plus. I added this to the issue tracker.

http://code.google.com/p/box2d/issues/detail?id=164
I thought about iterators a bit more. It seems there are some thorny details.

b2QueryCallback and b2RayCastCallback have a similar function. For consistency, both should be converted to iterators. However, the interface for b2RayCastCallback::ReportFixture has a return value that communicates back to the ray cast algorithm some information on how to proceed. It is not as simple as just advancing to the next element. AFAIK, typical iterator frameworks do not provide this without extension.

Another thing that has me worried is cleanup and data structure integrity. For example, when the user starts a query they create an iterator that must contain the state of the algorithm. Since these algorithms use a stack, we must store the stack in the iterator. This stack remains as long as the iterator is in scope. This stack may have some invalid entries if the client modifies the world before the iterator goes out of scope. Also, incorrect iterator usage may lead to unintended copies of the stack.

In the callback scheme I can lock b2World until the end of the algorithm. This seems intuitive because the scope is the query. In the case of iterators, the scope is user defined.

I would like to see how you could make iterators work for AABB queries and ray casts with these issues in mind.
About returning multiple values you've got two ways:

  • Your iterator should give you a single object that can be used to access all informations; by using the dereferencing operator on your custom iterator, you should get an object of a struct "RayCast" which has four fields "fixture", "point", "normal" and "fraction".

    This us what STL do: look at std::map, the iterator of a map points to elements of this value_type (which is an std::pair<const Key, T>).

  • Another way (that doesn't require another class "RayCast") is to put other fields or getter functions in your iterators to access those values (in this case dereferencing operators could return the most important value). This is how Qt do.


About the second thing, you again have a few solutions:

  • You could lock b2World using something similar to RAII: when you instantiate an iterator, it locks the world. When it gets destroyed (gets out of scope), when it becomes unusable (eg: reaches the end, if it's a Forward Iterator only), or even when the user explicitly deactivates it (by calling an iterator's function), it unlocks the world.

  • Another idea is to do the opposite: if the user does something to b2World, iterators get invalidated and can no longer be used.

    I think this one would cost a little more at runtime, or would be a little more difficult/annoying to implement, but this is cleaner: it doesn't require that the user explicitly takes care of deactivating the iterator.

Anyway - this is a personal opinion! - I wouldn't care if the user does something he's not supposed to do: if he does, your library should be free to have unpredictable behavior and crash (just like if the user does something bad with a pointer). This is how STL mostly works: if you modify a sequence, iterators working on it gets invalidated (it means they become "dangling iterators": you don't get any kind of warning).

If you only care about this to help users debugging their code, my best suggestion would be to implement the second idea I proposed, but only enabling it when compiling without NDEBUG.[/list]

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